Class imbalance: training set is balanced but test set is imbalanced, how to train?

Question: I have a huge dataset, say around 100M data points, with a class imbalance of 1 positive for every 100 negatives. It is very difficult to train on the entire dataset, so I tend to undersample the negatives such that the training data becomes balanced (1:1). But the test set remains imbalanced to reflect the real life nature of the data. FYI, I use a simple feedforward neural network
How do I go about training in such a combination? I'd use class weights during training but I'm thinking it might overpredict on the test set? Moreover how do I evaluate this model with AUC and AUPRC, do I need to use some form of weighting?
Comment: Unbalanced classes are almost certainly not a problem, and oversampling, undersampling or weighting will not solve this non-problem:
[Are unbalanced datasets problematic, and (how) does oversampling (purport to) help?](https://stats.stackexchange.com/q/357466/1352)
Comment: Don't use accuracy, precision, recall, sensitivity, specificity, or the F1 score. Every criticism at the following threads applies equally to all of these, and indeed to all evaluation metrics that rely on hard classifications:
[Why is accuracy not the best measure for assessing classification models?](https://stats.stackexchange.com/q/312780/1352)
[Is accuracy an improper scoring rule in a binary classification setting?](https://stats.stackexchange.com/q/359909/1352)
[Classification probability threshold](https://stats.stackexchange.com/q/312119/1352)
Comment: Instead, use probabilistic classifications, and evaluate these using [proper scoring rules](https://stats.stackexchange.com/tags/scoring-rules/info).
Comment: The choice of model performance statistic depends on the aim of the analysis or the needs of the application.  Proper scoring rules are a good idea for model selection, but model selection and performance evaluation are not the same thing.  If you are using AUC, that implies you are primarily interested in the ranking of the patterns, in which case the imbalance is likely to be irrelevant and you don't need to do anything.
Comment: Whatever you do, don't undersample unless you need to to make the problem computationally tractable.  First you need to work out what performance metric is important for your application, and why, and then work out what to do.  The answer is not necessarily a proper scoring rule https://stats.stackexchange.com/a/538524/887
Comment: Sadly the answer to @StephanKolassa's quesiton https://stats.stackexchange.com/questions/357466/are-unbalanced-datasets-problematic-and-how-does-oversampling-purport-to-he is not correct (or at least is not a good answer to the question).  Class imbalance problems can arise if you don't have enough data to characterize the distribution of the minority class.  You will not observe a class imbalance problem if you provide a large amount of data.  Most estimation problems go away if you throw enough data at them.
Comment: I have discussed this in some of my answers on related questions, but I can't find it immediately.  Essentially the problem isn't the imbalance per-se, but that if you have an imbalanced dataset, then it needs to be very large in order to provide sufficient data to characterise the distribution of the negative class properly, so it is effectively a small-sample estimation problem.
Comment: Yes, if we have $1000$ observations divided up $990$ and $10$, we probably can't characterize the distribution of the minority class like we could with $500$ and $500$, but if we have $1000000$ observations divided up $990000$ and $10000$, we still have the same class imbalance but lack the issue of having too few observations to characterize distribution of the the minority class.
Comment: @StephanKolassa, I interpreted "It is very difficult to train on the entire dataset" to mean because of the very large size, rather than a statement of trying to "fix" the imbalance.
Comment: @BenReiniger: guilty as charged, of using boilerplate comments, which I have in a txt file because imbalance/oversampling questions crop up here *regularly*. I unfortunately don't have the time to tailor answers to every one of these questions and believe that these comments may still be helpful, even if they don't address the exact question. In the present case, I would recommend sampling the training data "as is", without over-/undersampling a class.
Comment: @DikranMarsupial: I confess I am a bit surprised. "You will not observe a class imbalance problem if you provide a large amount of data." Can you explain what you mean by that, perhaps add a few references?
Comment: I'm working on a tutorial on this.  One way of looking at it is that the minimum likelihood estimators have a bias, the paper by Gary King mentions this https://gking.harvard.edu/files/0s.pdf .  The class imbalance problem does exist, but as far as I can see, there isn't actually anything you can do about it (as there isn't enough data to work out how much correction to apply).  It is not clear that it can even be diagnosed https://stats.stackexchange.com/questions/539638/how-do-you-know-that-your-classifier-is-suffering-from-class-imbalance
Comment: just to add MLE has good asymptotic properties, so as you add more data, the bias rapidly becomes too small to matter.
Comment: I disagree that Stephan Kolassa gives a poor answer there. I think it just addresses a different issue. Dikran, your point a couple of times has been that class imbalance is a problem when it means that you lack data on the minority class, but that doesn't make class imbalance the issue. It means that lack of data is the issue.
Comment: @Dave, that *is* the class imbalance problem.  There is no other problem with imbalanced classes.   AFAIK, if you can suggest another problem with them, I'd be keen to hear about it.  BTW my experience with SVMs suggest they don't have a problem with imbalance in large datasets either.  Also I didn't say it was a poor answer, I said it wasn't a good one.  My choice of words was deliberate and careful.
Comment: I don't see class imbalance as a problem, but think about how many approaches there are to dealing with class imbalance. People will use sensitivity, specificity, $F_1$ score since accuracy can be an impressive-looking $99\%$ even though the prior probability of being in one of the classes is $0.995$. People downsample their data to get the classes to be balanced. People run [SMOTE](https://twitter.com/f2harrell/status/1062424969366462473?lang=en) to balance the data. *Someone* thinks it's an issue not to have a 50/50 split, even if we disagree with that.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/132159/discussion-between-dikran-marsupial-and-dave).
Answer: The primary effect on a model of downsampling like this is a shift in the predicted log-odds.  This is rigorously shown for logistic regression, see https://stats.stackexchange.com/a/68726/232706; for other models, I've observed the same effect (though I don't do a lot of neural nets).  Assuming that's really true in your case, you can "fix" the probability estimates by adding the adjustment term listed in the above link.  Note too that such a monotonic adjustment should not affect AUROC or AUPRC at all.
Using class weights in training instead should produce a very similar effect; see https://datascience.stackexchange.com/a/58899/55122
You have "plenty" (difficult to say without more context, but 1M is a lot) of positive examples, so the suggestion to sample without affecting class balance given by @StephanKolassa in a comment may also be fine.  In other contexts where the positive class is so small that you wouldn't want to throw away any information from them, I think downsampling the giant negative class is fine (and note that Scortchi in the first link mentions exactly this case).
Answer: Before, you should use stratify method for data sampling
after that You have to give weight to your model
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: Welcome to Cross Validated! I second what @utobi wrote. This is the beginning of what could be a quality answer but really needs details added, especially considering the presence of another answer and multiple comments that discuss class imbalance issues extensively.


Set custom header to hash key in Varnish

Question: I want to see which request gets which hash key (req.hash in older versions, or setting the hash key using hash_data()),
but I can't find any documentation about how to read it in Version 4.0.
How do I set my custom header to the request key?
Like:
set res.header.X-HASH = get_hash_key();

Only Version 4.0! Like req.hash is not available in version 4.
Answer: You can view the data making up the hash key using the varnishlog command.
On your Varnish server, run the command
varnishlog

Then when you make a request, you should see something like this in varnishlog's output:
11 VCL_call     c hash
11 Hash         c /index.html
11 Hash         c www.example.com
11 VCL_return   c hash

In this example, the middle two lines show the data that is being used to make up the hash key.


Derivatives of function when the function is defined differently for different values of x

Question: If $$ f(x) := \begin{cases} 0 & x = 0 \\ x + x^2\sin(1/x) & x \neq 0 \end{cases} $$ then by the definition of derivative I get $f'(0) = 1$, and if I differentiate $x + x^2\sin(1/x)$ and then plug in $0$ I also get $f'(0) = 1$, but I don't know why I can plug in $0$ here since isn't $f(x)=x + x^2\sin(1/x)$ only when $x\neq0$?
And I'm also wondering since $f(x)=0$ when $x=0$ why can't we just differentiate this function and say $f'(0) = 0$.
Another question I have is that if $$ f'(x) := \begin{cases} x^3 & x\geq 0 \\ -x^3 & x < 0 \end{cases} $$ why do we have to consider $x=0$ to be a separate case when trying to find the derivatives (for $x=0$ we have to use the definition of derivative to show $f'(0) = 0$ but for $x\neq0$ we can just differentiate it directly)?
Comment: The derivative $f'(x)=1+2x\sin(1/x)-\cos(1/x)$. How did you plug in $0$ to get $f'(0)=1$?
Comment: For the differentiability at $x=0$ you may use in both cases that if $g$ is a bounded function, defined on a neighbourhood of $0$, then $f(x)=x^2g(x)$ is differentiable in $x=0$: in the first case take $g(x)=\sin(1/x)$, in the second one $g(x)=|x|$.
Answer: First of all, since $f'(x)=1+2x\sin\left(\frac1x\right)-\cos\left(\frac1x\right)$, you simply cannot plug in $0$.
Concerning the second question, suppose that you define$$\begin{array}{rccc}g\colon&\mathbb R&\longrightarrow&\mathbb R\\&x&\mapsto&\begin{cases}x&\text{ if }x\neq0\\0&\text{ if }x=0.\end{cases}\end{array}$$If the method that you suggested worked, we would have $g'(0)$. But $g$ is the identity function (that is, $g(x)=x$ for each $x$) and therefore $g'(0)=1$).
FInally, my answer to the second question also answers the third one.


How to combine predictions from ensemble learning

Question: Suppose I have three models, model-1, model-2, model-3 for binary classification. Suppose model-1 has $a_1$ accuracy, model-2 has $a_2$ accuracy, model-3 has $a_3$ accuracy.
For some test data, model-1 classifies it as $1$, whereas model-2 and model-3 classify it as $0$.
What are the best heuristic ways to combine the result and decide the final classification ?
One of the naive way to do this would be :
We can create map $M$ where $M[1]=1$ and $M[0]=-1$. Let we denote result of model-1 as $r_1$, model-2 as $r_2$, model-3 as $r_3$. Let us define $S = a_1*M[r_1]+a_2*M[r_2]+a_3*M[r_3]$. If $S>0$ we can declare final result as $1$ else $0$.
Problem with this is it won't give accurate result with large number of models. Suppose I have $100$ models,also suppose first model has accuracy of $0.9$ and other $99$ models have accuracy of $0.1$ then final result might get wrong.
One way to resolve this is we can only allow those models whose accuracy is not less than $H-0.1$ where $H$ is highest accuracy of any model.
What are some best way to combine the results from different models ?  Are there some libraries in python to do this ? I found some of way to do ensemble learning but I want to keep some weightage proportional to accuracy of models (based on previous performance on test data) and not do just some kind of averaging.
Answer: First off, don't use accuracy, which is a seriously misleading evaluation measure. Instead, use probabilistic classifications, and evaluate these using proper scoring rules.
You can easily combine probabilistic classifications. If your three models yield predicted probabilities $\hat{p}_1, \hat{p}_2$ and $\hat{p}_3$ for a new instance to belong to the target class, simply take the average of the $\hat{p}_i$ as the combined probabilistic prediction.
If your models differ on some proper scoring rule, then you can use a weighting based on these scores. Or you could even run a logistic regression of your target on the in-sample probabilistic classifications of your three models.
Note, however, that any attempt to estimate weights for combinations will introduce additional variance, and the end result may well be worse than if you had used a simple unweighted average (e.g., Claeskens et al., 2016).
Comment: We can't always use average of probability. For example if one of our model is SVM. Also averaging won't give accurate result always. Suppose model-1 has 0.9 accuracy and model-2 has 0.1 accuracy then it's safer to not take average of probability output from both models. We need some equation where accuracy can act as coefficient in such way that lower accuracy model doesn't have much impact.
Comment: I have added one more line at the end of my question.
Comment: Yes, the fact that SVM does not output probabilities is one glaring weakness of the model. Also, a model's accuracy is not a good guide to its quality, see the initial link.
Comment: One way we can solve the problem is by just voting. Suppose I have 10 models whose pairwise accuracy don't differ by some 0.1 or 0.05 (we can chose the number by experimentation) then I can let them vote
Answer: I upgraded your question due to its more general importance in practice.
As background, I am in the process of filing an algorithmic patent that asserts the falsity of the following statement for many distributions:

Note, however, that any attempt to estimate weights for combinations will introduce additional variance, and the end result may well be worse than if you had used a simple unweighted average.

The apparent secret to combining relates quite intuitively, and applies particularly, to small samples where robust methods can suggest new information content that can apparently increase accuracy.
As a simple example, consider the mode of a distribution (which equals, or is mathematically related to, the mean) for which one wants an improved mean estimate over the sample mean. As such, a clustering of points in the middle range of the sorted sample (where one would expect the mode) can be quite informative in shifting a combined estimator towards the true mean and away from the sample mean which is easily distorted by outliers and in small unrepresented samples. The process is, however, as expected heavily dependent on the parent distribution and sample size.
My comment relates to my analysis that was confirmed over repeated simulations for over a dozen distributions commonly found in applications. Quite simply, it is a question of new robust information content introduced. Adding it improves, and surprisingly, it is not a major issue on how to precisely weigh it, as in the effort of discovering/inventing the new information metric.
As to your question, my suggested answer for large data sets that appear relevant to your decision making, just either average (as was suggested) or be selective as to which data set model appears to be more in line with your goals/data going forward. An understanding of the differences in the predictive classifications with respect to information content may also be a path to selecting a single model.
Comment: We can't always use average of probability. For example if one of our model is SVM. Also averaging won't give accurate result always. Suppose model-1 has 0.9 accuracy and model-2 has 0.1 accuracy then it's safer to not take average of probability output from both models. We need some equation where accuracy can act as coefficient in such way that lower accuracy model doesn't have much impact. I have added one more line at the end of my question.
Comment: I am puzzled by your simple example. The mode is typically quite different from the mean, except for symmetric distributions. Also, there is no error measure that elicits the mode in general (in contrast to the mean, which is elicited by the mean squared error).
Comment: SK, I actually use a modal-based statistic. One such statistic, based on frequency, however, spread over all data points you certainly are more acquainted with (less puzzling), it is the MLE.


Differentiation to tangent and normals

Question: The equation of the curve is given by
$ y = \frac{6}{2x^2+1} $
Find the equation of the tangent and the normal at the point when
$ x = -1$
My workings
When $x= -1, y= 2 $
$\frac{d}{dx} (Y) = \frac{-24}{(2x^2+1)^2} $
Sub $x=-1$ to the above expression to find the gradient ...
$\frac{d}{dx} (Y) = \frac{-8}{3} $
Now , to find the equation of the tangent , what can I do ?
Is it $y=mx+c$ ?
Sub in $x=-1 , y=2$ to find the y intercept and then continue to find the equation of the tangent ?
Which is
$y=  \frac{-8}{3} x - \frac{2}{3} $
But that don't feel right to me .. so im here to ask .
Answer: The derivative should be
$\frac{d}{dx} (Y) = \frac{-24*x}{(2x^2+1)^2} $
when $x=-1 $, it gives $24/9 $
So the tangent equation is $ y-2=8/3 *(x+1) $ and the normal is $ y-2 =-3/8 *(x+1)$
Does it sound good ?
Comment: How did the $y-2$ and $(x+1)$ come about
Comment: @user307640  If you want the tangent at point (x=a,y=b), you must write $ y-b = y'(a)*(x-a) $. If $x=a$, you find well $y=b$. See https://en.wikipedia.org/wiki/Tangent#Equations
Answer: HINT: write your function in the form $$y=6(2x^2+1)^{-1}$$ then the derivative is given by
$$y'=6(-1)(2x^2+1)^{-2}\cdot 4x=\frac{-24x}{(2x^2+1)^2}$$
Comment: ya missed a negative bro

Differentiation to tangent and normals


Core data search and update

Question: I'm struggling to find a tutorial whereby I can update a core data entity. For example, if I have a field and an add button, I know how to add it to an entity. This field can add names: john, jack, jill but if I add john again I want to ensure that the duplicate is not entered.
Here is my add code.
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

let entity = NSEntityDescription.entity(forEntityName: "UserAccountTbl", in: context)!
let person = NSManagedObject(entity: entity, insertInto: context)

person.setValue(NameSurname, forKeyPath: "nameSurname")

try context.save()

Comment: Try this: https://stackoverflow.com/a/49199015/8374890
Comment: Core Data objects have methods you can override such as `validateForUpdate()`, `validateForInsert()`, and others.
Answer: Swift 4
func isEntityAttributeExist(id: Int, entityName: String) -> Bool {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let managedContext = appDelegate.persistentContainer.viewContext
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
        fetchRequest.predicate = NSPredicate(format: "id == %@", id)

        let res = try! managedContext.fetch(fetchRequest)
        return res.count > 0 ? true : false
      }

Objective C
NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:@"UserAccountTbl"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"nameSurname == %@", ameSurname];
[fetch setPredicate:predicate];
YourObject *obj = [ctx executeRequest:fetch];

if(!obj) {
    //not there so create it and save
    obj = [ctx insertNewManagedObjectForEntity:@"UserAccountTbl"]; //typed inline, dont know actual method
    obj. nameSurname = NameSurname;
    [ctx save];
}

Comment: check the record first if it present then dont insert ... insert if its not already there

Core data search and update


Problema em insert não apresenta erro

Question: Pessoal tudo beleza? Eu já fuçei o fórum inteiro e até outros fóruns e não achei respostas sobre isso.
 Se alguém puder dar uma olhada e apontar o meu erro agradeço.
Segue o  formulário:
   <form action="add.php" method="post" name="form1">
   div>

        Data de Cadastro:

        Nome Fantasia:
        <input type="text" name="nomefantasia"  required autofocus class='form-control'/>

        Razão Social
        <input type="text" name="razaosocial"  required class='form-control'/>

        CNPJ:
        <input type="text" name="cnpj"  required class='form-control'/>

        Inscrição Estadual:
        <input type="text" name="inscricaoestadual"  required class='form-control'/>

        Categoria:
        <select name="categoria" size="1">
                     <option>Selecione...</option>
                     <?PHP mysql_connect('localhost','root','') or die(mysql_error());

                        mysql_select_db('suinos') or die(mysql_error());
                        mysqli_set_charset($mysqli,"utf8");
                        ?>
                     <?php $query = mysql_query("SELECT categoria_id, categoria_titulo FROM comp_categoria");
                     while($categoria = mysql_fetch_array($query)) { ?>
                     <option class='form-control' value="<?php echo $categoria['categoria_id'] ?>"><?php echo $categoria['categoria_titulo'] ?></option>
                     <?php } ?>
            </select>

        Endereço:
        <input type="text" name="endereco"  required class='form-control'/>

        Número:
        <input type="text" name="numero"  required class='form-control'/>

        Bairro:
        <input type="text" name="bairro"  required class='form-control'/>

    CEP:
        <input type="text" name="cep"  required class='form-control'/>

        Cidade:

            <select name= "cidade"><option>Escolha a cidade</option>

                     <?php $queryy = mysql_query("SELECT Id, Nome FROM comp_cidade ORDER BY Nome ASC");
                     while($cidade = mysql_fetch_array($queryy)) { ?>
                     <option class='form-control' value="<?php echo $cidade['Id'] ?>"><?php echo $cidade['Nome'] ?></option>
                     <?php } ?>
            </select>

         Estado:
        <select name="estado" size="1">
                     <option>Selecione...</option>

                     <?php $bquery = mysql_query("SELECT Id, Nome FROM comp_estado ORDER BY Nome ASC");
                     while($estado = mysql_fetch_array($bquery)) { ?>
                     <option class='form-control' value="<?php echo $estado['Id'] ?>"><?php echo $estado['Nome'] ?></option>
                     <?php } ?>

            </select>

        E-mail:
        <input type="email" name="email"  required class='form-control'/>

        Contato:
        <input type="text" name="contato"  required class='form-control'/>

        Telefone:
        <input type="text" name="fone"  required class='form-control'/>

         Nome do Banco:
        <select name="banco">
                     <option>Selecione...</option>

                     <?php $bquery = mysql_query("SELECT id_banco, nomebanco FROM fat_bancos");
                     while($nbanco = mysql_fetch_array($bquery)) { ?>
                     <option class='form-control' value="<?php echo $nbanco['id_banco'] ?>"><?php echo $nbanco['nomebanco'] ?></option>
                     <?php } ?>

            </select>

        Número da conta
        <input type="text" name="nconta"  required class='form-control'/>

        Número da Agencia:
        <input type="text" name="nagencia"  required class='form-control'/>

            <input type="Submit" name="Submit" value="Salvar" class="btn btn-primary">

   </form>

E aqui o PHP com o insert:
<?php

include($_SERVER['DOCUMENT_ROOT']."/NovoModelo/config.php");

if(isset($_POST['Submit'])) {

$nomefantasia = mysqli_real_escape_string($mysqli, trim($_POST['nomefantasia']));
$razaosocial = mysqli_real_escape_string($mysqli, trim($_POST['razaosocial']));
$endereco = mysqli_real_escape_string($mysqli, trim($_POST['endereco']));
$numero = mysqli_real_escape_string($mysqli, trim($_POST['numero']));
$bairro = mysqli_real_escape_string($mysqli, trim($_POST['bairro']));
$idcidade =  $_POST['cidade'];
$idestado = $_POST['estado'];
$email = mysqli_real_escape_string($mysqli, trim($_POST['email']));
$contato = mysqli_real_escape_string($mysqli, trim($_POST['contato']));
$fone = mysqli_real_escape_string($mysqli, trim($_POST['fone']));
$cnpj = mysqli_real_escape_string($mysqli, trim($_POST['cnpj']));
$cep = mysqli_real_escape_string($mysqli, trim($_POST['cep']));
$inscricaoestadual = mysqli_real_escape_string($mysqli, trim($_POST['inscricaoestadual']));
$nbanco = mysqli_real_escape_string($mysqli, trim($_POST['banco']));
$nconta = mysqli_real_escape_string($mysqli, trim($_POST['nconta']));
$nagencia = mysqli_real_escape_string($mysqli, trim($_POST['nagencia']));
$categoria = $_POST['categoria'];

 $result = mysqli_query($mysqli, "INSERT INTO comp_fornecedor(FORN_ID, FORN_NOMEFANTASIA, FORN_RAZAOSOCIAL, FORN_ENDERECO, FORN_NUMERO, FORN_BAIRRO, FORN_IDCIDADE, FORN_IDESTADO, FORN_EMAIL, FORN_CONTATO, FORN_FONE, FORN_CNPJ, FORN_CEP,FORN_INSCRICAOESTADUAL, FORN_CATEGORIAID, FORN_IDBANCO,FORN_NCONTA,FORN_NAGENCIA)
VALUES('','$nomefantasia', '$razaosocial', '$endereco','$numero', '$bairro', '$idcidade', '$idestado', '$email', '$contato', '$fone','$cnpj','$cep','$inscricaoestadual','$categoria','$nbanco','$nconta', '$nagencia')") or die(mysqli_error($mysqli));

}
?>

Agradeço desde já!
Comment: ele está em uma  pagina externa. Na qual estou chamando no include.
Comment: "or die(mysqli_error))" eu coloquei pra apresentar erro  e mesmo assim nada.
Comment: No insert não seria `...or die (mysql_error())`? Está somente `(mysql_error)`
Comment: corrigido o or die (mysql_error()). Mesmo assim, nada ainda.
Comment: veja que a variavel  $razaosocial tem que estar envolvida em aspas simples como as demais.
Comment: Rapaz, eu criei um banco só pra testar isso e está funcionando perfeitamente. Dá para você editar a sua pergunta e colocar todo o codigo corrigido?
Answer: Para exibir o erro, se é que há algum erro na query você deve usar mysqli_error e não mysql_error, isto esta errado:
 or die(mysql_error));

Fora que o mysqli_query não tem o parenteses no final ), em:
$result = mysqli_query($mysqli, "INSERT INTO comp_fornecedor(FORN_ID, FORN_NOMEFANTASIA, FORN_RAZAOSOCIAL, FORN_ENDERECO, FORN_NUMERO, FORN_BAIRRO, FORN_IDCIDADE, FORN_IDESTADO, FORN_EMAIL, FORN_CONTATO, FORN_FONE, FORN_CNPJ, FORN_CEP,FORN_INSCRICAOESTADUAL, FORN_CATEGORIAID, FORN_IDBANCO,FORN_NCONTA,FORN_NAGENCIA)
VALUES('','$nomefantasia', $razaosocial, '$endereco','$numero', '$bairro', '$idcidade', '$idestado', '$email', '$contato', '$fone','$cnpj','$cep','$inscricaoestadual','$categoria','$nbanco','$nconta', '$nagencia')" or die(mysql_error));

O correto deveria ser isto:
$result = mysqli_query($mysqli, "INSERT INTO comp_fornecedor(FORN_ID, FORN_NOMEFANTASIA, FORN_RAZAOSOCIAL, FORN_ENDERECO, FORN_NUMERO, FORN_BAIRRO, FORN_IDCIDADE, FORN_IDESTADO, FORN_EMAIL, FORN_CONTATO, FORN_FONE, FORN_CNPJ, FORN_CEP,FORN_INSCRICAOESTADUAL, FORN_CATEGORIAID, FORN_IDBANCO,FORN_NCONTA,FORN_NAGENCIA)
VALUES('','$nomefantasia', $razaosocial, '$endereco','$numero', '$bairro', '$idcidade', '$idestado', '$email', '$contato', '$fone','$cnpj','$cep','$inscricaoestadual','$categoria','$nbanco','$nconta', '$nagencia')") or die(mysqli_error($mysqli));

Provavelmente você não esta vendo nenhum erro porque os erros devem estar desligados no php.ini:
display_errors=Off

Recomendo que se for no seu computador habilite, basta editar o php.ini:
display_errors=On

Após ajustar é necessário reiniciar o Apache ou Nginx ou LightTTPD ou IIS
Também verifique se error_reporting esta igual a E_ALL, pode ser alguma configuração no teu NovoModelo/config.php, veja se não ajustou o a função error_reporting(...);.
Eu recomendo mesmo que leia isto para entender sobre os erros em PHP:

Por que usar error_reporting com display_errors e display_startup_errors?

Note também que talvez seus ajustes nos scripts não tenham efeito porque esta usando opcode, como por exemplo Xcache, Apcache ou Opcache, recomendo que leia isto:

PHP trabalha com cache?

Não misture mysql_ com mysqli_
Notei que você esta misturando mysql_ que são funções da API antiga com mysqli_, isto deve estar causando o problema todo, recomendo que mude tudo para mysqli que é a API mais nova, aqui eu explico motivo do porque não usar as APIs antigas https://pt.stackoverflow.com/a/66489/3635
Veja aqui por exemplo você misturou mysqli_ e mysql_:
 <option>Selecione...</option>
 <?PHP mysql_connect('localhost','root','') or die(mysql_error());

    mysql_select_db('suinos') or die(mysql_error());  <--- Aqui
    mysqli_set_charset($mysqli,"utf8"); <--- Aqui
    ?>
 <?php $query = mysql_query("SELECT categoria_id, categoria_titulo FROM comp_categoria");
 while($categoria = mysql_fetch_array($query)) { ?>
 <option class='form-control' value="<?php echo $categoria['categoria_id'] ?>"><?php echo $categoria['categoria_titulo'] ?></option>
 <?php } ?>

Outra coisa não é necessário ficar abrindo conexão com o servidor mysql várias vezes para cada <select> que você criou, basta uma vez e pegar o handle, outra coisa que faltou foi escapar algumas variáveis, faça assim:
$nomefantasia = mysqli_real_escape_string($mysqli, $_POST['nomefantasia']);
$razaosocial = mysqli_real_escape_string($mysqli, $_POST['razaosocial']);
$endereco = mysqli_real_escape_string($mysqli, $_POST['endereco']);
$numero = mysqli_real_escape_string($mysqli, $_POST['numero']);
$bairro = mysqli_real_escape_string($mysqli, $_POST['bairro']);
$idcidade =  mysqli_real_escape_string($mysqli, $_POST['cidade']);
$idestado = mysqli_real_escape_string($mysqli, $_POST['estado']);
$email = mysqli_real_escape_string($mysqli, $_POST['email']);
$contato = mysqli_real_escape_string($mysqli, $_POST['contato']);
$fone = mysqli_real_escape_string($mysqli, $_POST['fone']);
$cnpj = mysqli_real_escape_string($mysqli, $_POST['cnpj']);
$cep = mysqli_real_escape_string($mysqli, $_POST['cep']);
$inscricaoestadual = mysqli_real_escape_string($mysqli, $_POST['inscricaoestadual']);
$nbanco = mysqli_real_escape_string($mysqli, $_POST['banco']);
$nconta = mysqli_real_escape_string($mysqli, $_POST['nconta']);
$nagencia = mysqli_real_escape_string($mysqli, $_POST['nagencia']);
$categoria = mysqli_real_escape_string($mysqli, $_POST['categoria']);

Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](http://chat.stackexchange.com/rooms/59525/discussion-on-answer-by-guilherme-nascimento-problema-em-insert-nao-apresenta-er)
Answer:
Sua query tem erros:

mysqli_error e não mysql_error conforme meu comentário que por sinal tb tem erros :) o correto é  or die(mysqli_error($mysqli))
a variavel  $razaosocial  tem que estar envolvida em aspas simples como as demais.
$result = mysqli_query($mysqli, "INSERT INTO comp_fornecedor(FORN_ID, FORN_NOMEFANTASIA, FORN_RAZAOSOCIAL, FORN_ENDERECO, FORN_NUMERO, FORN_BAIRRO, FORN_IDCIDADE, FORN_IDESTADO, FORN_EMAIL, FORN_CONTATO, FORN_FONE, FORN_CNPJ, FORN_CEP,FORN_INSCRICAOESTADUAL, FORN_CATEGORIAID, FORN_IDBANCO,FORN_NCONTA,FORN_NAGENCIA)
VALUES('','$nomefantasia', '$razaosocial', '$endereco','$numero', '$bairro', '$idcidade', '$idestado', '$email', '$contato', '$fone','$cnpj','$cep','$inscricaoestadual','$categoria','$nbanco','$nconta', '$nagencia')") or die(mysqli_error($mysqli));

Comment: Corrigi mas, continua com o mesmo problema.
Comment: Rapaz, eu criei um banco só pra testar isso e está funcionando perfeitamente. Dá para você editar a sua pergunta e colocar todo o codigo corrigido?
Comment: Editei,  me desculpe sou novo e estou me adaptando ao fórum.
Comment: Deve ter algo a ver com o meu banco de dados então. Estou usando o phpmyadmin. Estou dizendo isso, porque criei uma outra página com um formulário simples. Criei a tabela  para o teste. E não está salvando e nem retornando erros.

Problema em insert não apresenta erro


Why does `await asyncio.create_task()` behave different then when assigning it to a variable?

Question: Why is there a different how tasks are run between tasks 1-3 and 4-6 in the code below?
Code:
import asyncio

async def do_something(i, sleep):  # No I/O here
    print("Doing... ", end="")
    print(await no_io_1(i, sleep))

async def no_io_1(i, sleep):  # No I/O here
    return await no_io_2(i, sleep)

async def no_io_2(i, sleep):  # No I/O here
    return await io(i, sleep)

async def io(i, sleep):
    await asyncio.sleep(sleep)  # Finally some I/O
    # t = asyncio.create_task(asyncio.sleep(sleep))
    # await t
    return i

async def main():
    await asyncio.create_task(do_something(1, sleep=4))
    await asyncio.create_task(do_something(2, sleep=3))
    await asyncio.create_task(do_something(3, sleep=2))

    t4 = asyncio.create_task(do_something(4, sleep=4))
    t5 = asyncio.create_task(do_something(5, sleep=3))
    t6 = asyncio.create_task(do_something(6, sleep=2))
    await t4
    await t5
    await t6

asyncio.run(main())
print("\r\nBye!")

Output:
Doing... 1
Doing... 2
Doing... 3
Doing... Doing... Doing... 6
5
4

Answer: In the first snippet you immediately await each task you've created. As a result, the tasks are prevented from running in parallel.
In the second snippet you create three tasks and only then start awaiting. This allows all three to run in parallel, despite your await specifying you're interested in the result of the first one. Being able to run other tasks while waiting for the results of a specific one is essential to libraries like asyncio.
In other words, await t1 doesn't mean "run t1", it means "suspend me and spin the event loop until t1 is done". The difference has nothing to do with tasks being stored in variables, but with creating tasks in advance. For example, you could modify the second example like this:
    t4 = asyncio.create_task(do_something(4, sleep=4))
    await t4
    t5 = asyncio.create_task(do_something(5, sleep=3))
    await t5
    t6 = asyncio.create_task(do_something(6, sleep=2))
    await t6

...and you would get behavior like that of the first example.


Motifs in Bartók's 5th Quartet

Question: I'm doing a motific analysis of the first movement of Bartók's 5th Quartet and I've traced almost everything.
The only bit which bothers me occurs at bar 82, then again at bar 177 where it forms the basis of the coda.
According to the plan by Bartok and the analysis by Ligeti this is part of the first theme but I absolutely can't find where it's first stated.
Any help is extremely welcome.
Answer: Look at the viola part in m.70, the 2nd violin part in m.72, the viola again in ms.74-75, and the 'cello in m.76ff (vastly expanded), and then ms.82-85 falls neatly into place. Also note that the rhythm and conjunct motion show up long before this, but are bent into this particular contour by m.70. The notion of developing variation applies to Bartók quite as much as it does to Schoenberg, even if Bartók didn't use the term. Note also that ms.82-85 are also the simplest and shortest presentations of the motif to this point - in Schoenbergian terms, a liquidation of the motif. In m.177ff, the motif is stated, then further liquidated (rather quickly) and transformed into contrary scale segments.
Now it strikes me on a very cursory read-through of the score that m.44ff, m.103ff and m.132ff are all at least somewhat related to the passages in question; I've probably missed others. Bartók's motivic work tends to be very plastic: extension, gradual change of contour, and expansion/contraction of intervals while maintaining contour are all very much part of his arsenal.

Motifs in Bartók's 5th Quartet


Disable the swipe action in table view cell in swift

Question: I have implemented the swipe action for the table view cell and they are two actions: Accept and Reject.
When I swipe for the first time it must appear and for the second time if I swipe the cell it should not open.
The swipe action for the cell must be in the disabled mode.
Comment: please read this first : [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
Answer: First, you should keep track of the indexPath of cells you have interacted with.
private var disabledCellsIndexPath = [IndexPath]()

Then in the method to configure your swipe actions (this is the new iOS 11 API):
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

    let action = UIContextualAction(style: .normal, title: "Action Title", handler: { _, _, completionHandler in

        // DO WHAT YOU WANT HERE
        // …

        // This is where you specify that this specific cell should be 'disabled'
        self?.disabledCellsIndexPath.append(indexPath)

        completionHandler(true)
    })

    return UISwipeActionsConfiguration(actions: [action])
}

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return !disabledCellsIndexPath.contains(indexPath)
}

Answer: Use  allowEdit flag when you want swipe Enable. else make it false.
var allowEdit: Bool = true
    func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return allowEdit
    }

     func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]?
        {
           if allowEdit{
               /*to perform Accept and Reject action on row*/
           }
    }

Comment: I tried this code. But no change it is not disabled
Answer: If I understood your question correctly, Please follow following generalize idea,

You can manage the flag for that indexPath in app end database. Whenever required open or disable i.e manage it you can enable/disable the edit action for that indexPath.


PHP Get Value from Array with Value of Key

Question: following problem: I want to build a mysql based language system.
To decrease loading time and increase performance I thought it would be the best, to first fetch all Language phrases into an array (which happens with mysqli fetch array). Then, if a language term is required, calling a function with the array as global variable.
My function for the array:
$sql       = $db->query('SELECT * FROM lang_phrases WHERE phraseLanguageId = 1');
$phrases   = array();

while($row = $sql->fetch_array()) {
    $phrases[] = $row;
}

Now I've got this array:
array(2) {
    [0]=> array(8) {
        [0]=> string(1) "1"
        ["phraseId"]=> string(1) "1"
        [1]=> string(1) "1"
        ["phraseLanguageId"]=> string(1) "1"
        [2]=> string(4) "HOME"
        ["phraseKey"]=> string(4) "HOME"
        [3]=> string(10) "Homepage"
        ["phraseContent"]=> string(10) "Homepage"
    }
    [1]=> array(8) {
        [0]=> string(1) "2"
        ["phraseId"]=> string(1) "2"
        [1]=> string(1) "1"
        ["phraseLanguageId"]=> string(1) "1"
        [2]=> string(4) "BACK"
        ["phraseKey"]=> string(4) "BACK"
        [3]=> string(6) "Back"
        ["phraseContent"]=> string(6) "Back"
    }
}

And thats my function:
function l($key) {
    global $phrases;

    return PLACEHOLDER;
}

I wonder, how can I now search the array for "phraseKey" $key from the function and get the value?
Do you have any hints? Or shall I simply select each phrase with each one query (performance problems with 100 quers per load?!)?
Cheers and Thanks!
Comment: Just as an aside, this will probably have a much lower overhead to do the same thing, if you've got enough control over your server to use it (probably want a dedicated server as you'll need to soft restart if/when you change the PO files) : http://php.net/manual/en/book.gettext.php
Answer: That's a bad structure. Why not key your array with the phrase ID and the language? e.g.
$translations = array(
    'HOME' => array(
       'english' => 'Home',
       'french' => 'Maison',
       'german' => 'Haus"
    etc...

This eliminates the need for ANY searching. You just look up directly by language/phrase ID.
Comment: I don't like the idea that you area loading all of the languages into this array
Comment: 6 of this, half-a-dozen of the other. depends entirely on just how many phrases/languages OP has. at some point the overhead of buildnig this array will outweigh the overhead of only having parts of it and doing repeated queries.
Answer: May I suggest to retrive the phrases with
while($row = $sql->fetch_array()) {
    $phrases[$row['phraseKey']] = $row;
}

Then in your function l($key) you can search them with
$t = isset($phrases[$key]) ? $phrases[$key] : null


Double Abel summation

Question: I am trying to calculate the Abel summation formula for a function of the form
$$
\sum _{j=1}^x \sum _{i=1}^x \phi \left( x-i j \right)
$$
where the function $\phi$ meets the requirements for Abel's formulation. The summation formula states that
$$
\begin{align}
\sum _{i=1}^x \phi (i)
&= \lfloor x\rfloor \phi (x) -\int_1^x \lfloor u\rfloor  \phi' (u) \mathrm{d}u \\
&= \lfloor x\rfloor \phi (x) -\int_1^x \lfloor u\rfloor  \frac {\delta}{\delta u} \phi (u) \mathrm{d}u
\end{align}
$$
(I have included that last line to clarify the basis of differentiation.)
The first summation, indexed on $i$, seems fine. Set $\psi (i) = \phi (x-i j)$. Then
$$
\begin{align}
\sum _{i=1}^x \phi (x-i j)
&= \sum _{i=1}^x \psi (i) \\
&= \lfloor x\rfloor \psi (x) -\int_1^x \lfloor u\rfloor  \frac {\delta}{\delta u} \psi (u) \mathrm{d}u \\
&= \lfloor x\rfloor \phi \left( x (1-j) \right) -\int_1^x \lfloor u\rfloor  \frac {\delta}{\delta u} \phi \left( x-u j \right) \mathrm{d}u
\end{align}
$$
As a simple test, define $\phi (x) := x^3$. Tabulating the results in Mathematica suggests the formula is correct (the Mathematica code is there in case the later error is in my coding - in which case, I will re-ask my question on the appropriate forum.):

Obviously, the fact that this particular example works is not proof that the formula is correct, but at least it's reassuring. However, I run into trouble on the second summation, indexed over $j$.
Set $\mu (j) = \sum _{i=1}^x \phi (x-i j) = \sum _{i=1}^x \psi (i)$ which we have just formulated above. Then
$$
\begin{align}
\sum _{j=1}^x \sum _{i=1}^x \phi (x-i j)
&= \sum _{j=1}^x \mu (j) \\
&= \lfloor x\rfloor \mu (x) -\int_1^x \lfloor u\rfloor  \frac {\delta}{\delta u} \mu (u) \mathrm{d}u \\
&= \lfloor x\rfloor \left( \lfloor x\rfloor \phi \left( x (1-x) \right) -\int_1^x \lfloor u\rfloor  \frac {\delta}{\delta u} \phi \left( x (1-u) \right) \mathrm{d}u \right) -\int_1^x \lfloor u\rfloor  \frac {\delta}{\delta u} \left( \lfloor x\rfloor \phi \left( x (1-u) \right) -\int_1^x \lfloor u\rfloor  \frac {\delta}{\delta u} \phi \left( x-u^2 \right) \mathrm{d}u \right) \mathrm{d}u
\end{align}
$$
However, a simple test proves this wrong. Using $\phi (x) := x^3$ again, Mathematica produces the following:

So. Something is clearly wrong... But what?
Answer: I believe the error is in your last line. The last term should have the two $u$'s labeled differently, so it should read
$$
-\int_1^x \lfloor u\rfloor \frac\delta{\delta u}\big(\lfloor x\rfloor \phi(x(1-u)) - \int_1^x \lfloor w\rfloor \frac\delta{\delta w} \phi(x-uw)\,dw\big)\,du.
$$
Please let me know if this works.
Comment: Hi @Three Aggies, that's absolutely right - and a salutary lesson in the use of dummy variables... Many thanks.

Double Abel summation


Big O complexity comparison of n^0.000001 and log(n) and many other

Question: I have been trying to learn Big O complexity and I read multiple resources including the answer given by dheeran with a graph.
Polynomial time and exponential time
I have few doubts of my own and few new doubts are raised after reading the answer below because it was not descriptive and clear.
Note: n is large (in billions)
Q1. I have read that,  for any c > 0, log n is O(n^c).
My understanding of Big O is log n will always be less than n^c for any value of c.
So, check this example:
c = 0.000001
n = 1,000,000,000 i.e 1 billion
=> n^c = 1.00002072348
=> log(1 billion) = 9
So how come log n > n^c when log n is O(n^c)
Q.2 As mentioned in the answer, the order of increasing complexity is:
O(1),O(log n),O( (log n)^c ),O(n),O(n^2),O(n^c),O(c^n),O(n!)
If 0 < c < 1 eg. 0.001
Would the order change or still be:
-O( log n ),O( (log n)^c )
-O(n^c),O(c^n)
-O(n),O(c^n)
Answer: Here "in billions" means large enough. Hence, it depends on functions. To prove that you need an n0, and it can be 10^20 here, in your example.
Also, as c is a constant, you can choose n0 base on the value of c. For example, if c < 1, you can choose n0 = 10^{10/c}. So, for all n > n0, n^c is greater than log(n).
For the second question, definitely for 0 < c <= 1, c^n is less than all those, as it goes to zero for bigger n! and log(n)^c is in O(log(n)). Therefore the order is:
c^n, 1, (log(n))^c, log(n), n^c, n, n^2, n!


Adding more space to VirtualBox HD (Centos Host) does not add space in the folder

Question: I am running Centos 6.5 guest on Windows 7 Pro host (VirtualBox v4.3.6) - all 64 bit.
I am trying to increase the size of Centos virtual disk (which is currently about 15G) to 90G.
I did run the following Command
VBoxManage modifyhd "C:_Ten\Centos 6.5.vdi" --resize 92160
I observed expected output
0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
and so far everything looks good.
Then I booted my Centos VM into GParted utility and this is where things start get confusing.
What I see in GParted is two partitions /dev/sda1 500MiB, /dev/sda2 30GiB and unallocated space of 60 GiB. What /dev/dev1 and /dev/sda2 represent? Which one of them do I need to grow?
I actually tried growing both (separately and simultaneously) nothing helps. What I really need is to add space available under /data (where I have my MongoDB databases). Prior to HD resize exercise "df -h /data" command in Centos was showing that that directory is using 98% of 28G available.
After running VBoxManage and GParted nothing changed no matter which partition I grow.
Question 1: How come my physical disk size is only 15GB but df shows that I have used 28 is there some kind of compression going on in VBoxManage?
Question 2: how do I get more space available to "/" and thus respectively to "/data"?
Thank you
Comment: I found way to do it by adding another virtual hard drive to Centos (rather than extending existing one). I did not need GParted utility at all. I then followed steps from this blog and it all worked: [link](http://www.turnkeylinux.org/blog/extending-lvm)
Answer: Question 1: Could be a corrupt filesystem. Run fsck and see if it fixes the problem.
Question 2: You have to resize your partition and your filesystem. The partition can be resized using parted. The filesystem has to be resized using a tool specific for your filesystem, for example resize2fs for ext2/ext3/ext4, xfs_growfs for xfs and so on.
Here is a guide for the whole procedure: http://positon.org/resize-an-ext3-ext4-partition
And sda1 could be your boot or swap partition. Check your /etc/fstab.


Problems with trying to call a dictionary using an input between files

Question: I am creating a dictionary which is added into a separate file. I am trying to use an input (dictSearch) to try and return the dictionary and its contents like it is shown in the other file (file.py). The problem is that the program is searching through the second file for a string called "dictSearch", not for what dictSearch is assigned to.
I have tried to change the data type of dictSearch.
def searchFunction():
  with open('file.py') as myfile:
    dictSearch = input("Enter name of donor (MAKE NAME ONE WORD WITH FIRST LETTER CAPS! ex. \"SomeText\"): ")

    if dictSearch in myfile.read():
      print(dictSearch)

    else:
      print("False")

#Below is what file.py looks like.

Andy = {
'age':'18',
'bloodType':'O-',
'diseases':'NA',
'medications':'NA',
'name':'Andy',
}

MATT = {
'age':'21',
'bloodType':'A',
'diseases':'NA',
'medications':'NA',
'name':'MATT',
}

Ex2 = {
'age':'1354',
'bloodType':'B',
'diseases':'NA',
'medications':'NA',
'name':'Ex2',
}

#Below is how I am creating these unique dictionaries in a separate file (in file.py)

with open('file.py','a') as file:                               #Code from lines x-y gotten from https://stackoverflow.com/questions/36965507/writing-a-dictionary-to-a-text-file
    file.write(str(dictName) + " = { \n")
    for k in sorted (donorDictionary.keys()):
        file.write("'%s':'%s', \n" % (k, donorDictionary[k]))
    file.write("} ")
    file.write("\n")
    file.close()

I expect the output to return the input dictionary and its key/value pairs, but it is returning the string that dictSearch is assigned to.
Comment: Does said separate file contain anything but the dictionary? Have you considered using common data formats such as JSON instead?
Comment: @MisterMiyagi No. It contains nothing but the created dictionaries. And no, I have not tried any formats like JSON. I have no experience with JSON, but would be open to learning it. Thanks.
Answer: You can just import the dictionary you defined in file.py, so if the file.py looks like

file.py

dct = {....}

Then you code will change to
#Import dct from file
from file import dct

def searchFunction():

    dictSearch = input("Enter name of donor (MAKE NAME ONE WORD WITH FIRST LETTER CAPS! ex. \"SomeText\"): ")

    #Perform your search
    if dictSearch in dct:
        print(dictSearch)

    else:
        print("False")

Comment: What is "dct" representative of in your example? I see what is being done, but do not know what dct will correspond to in my code. Thanks.
Comment: dct is the dictionary in another file, as you said in the question return the dictionary and its contents like it is shown in the other file (file.py) @AndyMaratea :)
Comment: Thanks for the help. That worked for individual dictionaries. The problem I am stuck on now is that the problem calls for me to create multiple dictionaries with unique names, which are generated by a series of inputs and stored in a separate file (file.py). The variable dictSearch is supposed to return the dictionary with the unique name assigned to dictSearch. I cannot seem to get that part to work. @Devesh Kumar Singh
Comment: Could I please how file.py would look like with  these dictionary names and how do you like to search as an update on the question please @AndyMaratea
Comment: Thanks, I have updated the code in the question to show how I create the unique dictionaries, as well as how file.py would look. Hopefully that can help you out. @Devesh Kumar Singh


View database values in new window-C#

Question: The code here displays the values into my datagrid that is on the same page, but I want to display the database values onto a new page using the same buton. Any suggestions?
        string Query = "SELECT * FROM database;";
        SqlConnection conn = new SqlConnection(connection);
        SqlCommand cmd = new SqlCommand(Query, conn);

        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        sda.Fill(dt);
        dataGrid.ItemsSource = dt.DefaultView;

Answer: Have your datagrid on a separate .aspx page (assuming that you are talking about ASP.NET) and then on button click redirect to that page saying
  protected void button_click(object sender, EventArgs e)
  {
     Response.Redirect("gridpage.aspx");
  }

In gridpage.aspx page_load event process the data and bind to gridview like
protected void Page_Load(object sender, EventArgs e)
{
      if(!IsPostBack)
      {
        string Query = "SELECT * FROM database;";
        SqlConnection conn = new SqlConnection(connection);
        SqlCommand cmd = new SqlCommand(Query, conn);

        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        sda.Fill(dt);
        dataGrid.ItemsSource = dt.DefaultView;
       }
}

Comment: sorry I meant to put c# in there but forgot
Comment: is it ASP.NET or winform? You can do the same thing in both case.

View database values in new window-C#


Flutter TikTokStyleFullPageScroller() not working on empty (non content) screen

Question: I am new to Flutter and trying to add slide functions to videos. It seems to be working as expected but only if slide by tapping on content area. In other words if tapped on video to slide it doesn't work.
Package:
tiktoklikescroller: ^0.1.1

import 'package:tiktoklikescroller/tiktoklikescroller.dart';

Here is my code:
@override
Widget build(BuildContext context) {
  final List<Color> colors = <Color>[Colors.red, Colors.blue, Colors.yellow];
  return Expanded(
    child: TikTokStyleFullPageScroller(
      contentSize: colors.length,
      swipeThreshold: 0.2,
      swipeVelocityThreshold: 2000,
      animationDuration: const Duration(milliseconds: 300),
      builder: (BuildContext context, int index) {
        return Row(
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            VideoDescription(),
            ActionToolbar(),
          ],
        );
      },
    ),
  );
}

Video Description
class VideoDescription extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: Align(
        alignment: Alignment.bottomLeft,
        child: Container(
          height: 70.0,
          padding: EdgeInsets.only(left: 20.0),
          margin: EdgeInsets.only(bottom: 160.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text('Title', style: TextStyle(fontWeight: FontWeight.bold),),
            ],
          ),
        ),
      ),
    );
  }
}

Action Toolbar
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 100.0,
      margin: EdgeInsets.only(bottom: 25.0),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          _getMusicPlayerAction(),
        ],
      ),
    );
  }

Please help.
Comment: Please mention full detail. Which package you are using?
Comment: Thanks @Yash, please have a look at updated question.
Comment: Could you share me `VideoDescription()` and `ActionToolbar()`. This way I could help more.
Comment: Okay it's there now.
Comment: As far, I have Discovered you have remove Expanded widget above `TikTokStyleFullPageScroller` and next you need pass correct and relevant `contentSize`. as you are not using `List colors` but still using its length.
Comment: This seems to be a package issue. I suggest you to open a issue on the package github repository.
Comment: Thanks for all your help @Yash and @ Vipin malik, I think I figured it out. I wrapped `VideoDescription()` and `ActionToolbar()` inside a container and gave it a transparent color. I will post the answer soon.
Answer: I wrapped VideoDescription() and ActionToolbar() inside a container and gave it a transparent color.
@override
Widget build(BuildContext context) {
  final List<Color> colors = <Color>[Colors.red,
Colors.blue, Colors.yellow];
  return Expanded(
child: TikTokStyleFullPageScroller(
  contentSize: colors.length,
  swipeThreshold: 0.2,
  swipeVelocityThreshold: 2000,
  animationDuration: const Duration(milliseconds: 300),
  builder: (BuildContext context, int index) {
    return Container(
                color: Colors.transparent,
                Row(
      mainAxisSize: MainAxisSize.max,
      children: <Widget>[
        VideoDescription(),
        ActionToolbar(),
      ],
     ),
    );
  },
    ),
  );
}


Applying styles to an element with a class based on both the parent div's class and its previous sibling's class

Question: Consider the following example:

      I am good

..

and

      I am bad

..

Now I want to apply  different rulesets for the two examples(say give the first example's 'child' class a margin of 10px and the second example's 'child' class a margin of 20px). Using CSS how would I define the rules which taken into account the previous sibling's class i.e 'goodchild' or 'badchild' and the parent class 'parent'.
Answer: You can achieve that using "Adjacent Sibling Selector" (+).
.goodchild + .child {
    margin: 10px;
}
.badchild + .child {
    margin: 20px;
}

Answer: Try this: Try adjacent siblings selector to target nearest sibling element
.parent .goodchild + .child {
    margin:10px;
}
.parent .badchild + .child {
    margin:20px;
}

Fiddle
Comment: I don't know why this answer is downvoted but it works. Thanks =)!
Answer: .parent .goodchild{
   margin:10px;
}

.parent .badchild{
   margin:20px;
}

This should work.
Comment: I believe you didn't understand what the OP wants. He wants to apply the margin to the `.child` div inside each of the `.parent` div's.
Comment: as Fahad pointed out, your answer does not target the .child class


Second-to-last measure (m. 33) of Chopin Op 9 No 2

Question: The second-to-last measure of Chopin's Op.9 No.2 has two voices(?). The very first double note (G-Eb2) on right hand, how do you tell which is that "other voice" and which one goes with the two other notes (Bb-G2) on the same beam? Also it seems to me from the score that the G and Eb2 are both 1/8 and so have the same duration, however I see multiple people playing it by holding down the G (with the thumb) while playing the Eb2 and the Bb (second note), why?
Answer: There are three reasonable interpretations for the "other voice":

There really isn't a second voice in the right hand, or, the second voice comes and goes. On piano there is some leeway in terms of interpreting voices; they can come and go within the music. In a multi-instrument piece this would sound weird, with instruments entering and exiting at odd moments, but on piano it's usually not disruptive.

After the G-Eb dyad, both voices "sing" the Bb and Eb. This is how I think of it. Double-stemming would just create clutter, so it's left off, but aurally it makes sense that these are two overlapping triplets.

The right-hand G4 and the left-hand Bb3 are the middle voice. The argument here would be that the G4 is one eighth note, and the Bb3 is a quarter note (i.e., two eighth notes), thus making a complete triplet beat. This is the weakest interpretation, I think, because they don't really sound like a single voice, and were that the intention, the beaming would almost surely reflect that.

As to why some pianists hold down the G, it's probably just convenience or comfort. Since the pedal is used throughout, it's not going to change the sound if the G4 is held an extra eighth note.
Comment: My Henle edition doesn't have the upper stem of the Bb notes on the bass clef. (the image is from a video)


Determine whether the given map ϕ is an isomorphism of these two binary structures

Question: $\langle M_2(\mathbb{R}), \cdot \rangle$ with $\langle \mathbb{R}, \cdot \rangle$ where $\phi(a)$ is the determinant of matrix $M_{2\times 2}$.
I don't think $\phi$ is an isomorphism because I think it is not onto. For a  real number $r \in \mathbb{R}$, $\phi(r) \neq M_{2\times 2}$. In other words, we cannot use the inverse of $\phi$, a determinant $a$, and get a $M_{2\times 2}$.
If the two binary spaces were $\langle M_1(\mathbb{R}), \cdot \rangle$ with $\langle \mathbb{R}, \cdot \rangle$, then I think $\phi$ would have passed the onto check because $a(\mathbb{R}) = M_{1\times 1}$.
Is my reasoning correct?

Edit with additional work/clarifications:
The map is not injective because the transpose of matrix $a$ will have the same determinant as $a^T$. Therefore $\phi$ is not an isomorphism.
Comment: Not a single part of your edit makes any sense.
Comment: Can't follow your argument, but I think you are over complicating matters.
 Whatever you mean by isomorphism here, you want the map to be injective. Is it?
Comment: let me work through it more and add some more work
Comment: Okay, is the argument better to follow now?
Comment: I want to show that the map is not injective because for a given matrix $M$ and it's transpose, $M^T$, the determinant is the same number. Is at least that the right move in the right direction?
Answer: The map is surjective. For $r\in\Bbb{R}$ the expression $\phi(r)$ makes no sense, because the domain of $\phi$ is $M_2(\Bbb{R})$, not $\Bbb{R}$.
In stead, show that the map is not injective; show that there are two matrices with the same determinant.
Comment: No, not a single part of your edit makes any sense to me.
Comment: Okay, I will try to do that and update the main post with my results
Comment: Okay, does my wording show that the map is not injective? I am hoping that I did not leave any ambiguity and everything is clearly defined


About 10-fold cross validation train/test split

Question: So, I want to do 10 fold CV. After I googled it, all of the websites I've found told me that to do the split, take 1 fold as test and the rest as train. But my professor told me another way. She told me to take 1 fold as train and 1 fold as test (and repeat until 10). So in 10 fold, the way she meant is:

Model1: Fold1 (Train) + Fold2 (Test)
Model2: Fold1 (Train) + Fold3 (Test)

And so on until

Model9: Fold1 (Train) + Fold10 (Test)

After that continue to Fold2 as train

Model10: Fold2 (Train) + Fold1 (Test)
.............. Fold2 (Train) + Fold10 (Test)

It continues until it reaches: Fold10 (Train) + Fold9 (Test). So there is 10x9 iteration until it finished.
I told her the former way (take 1 as test and the rest as train) but she said that the latter way (her way) is more valid/stronger and made the model robust.
So I'm wondering, is her way of doing the CV correct?
(Excuse my english, btw)
Comment: If your professor meant it in the way you are describing it, it is a bad way for x-validation because each model uses only 10% data. Usually you would run 10 models (plus the final model).
Comment: Is this longitudinal data, where rows are not independent of one another or is this IID data?
Comment: @akash87 I'm sorry I can't determine which it is. My dataset have 250 rows and 9 attributes which are RGB values. Each have 3 values (R1-R3, G1-G3, B1-B3). And 1 target column that contain 3 classes. So, I think it is IID data? Because they are independent of one another
Answer: I think what you describe as $k$-fold cross-validation is fine.
I would urge you to use freely available and established references in your work instead of websites; websites might be excellent at times but it can be hard to convince people of their quality and/or detect "mistakes" when starting in ML. For example, on the matter of cross-validation:

Hastie et al. (2009) Elements of Statistical Learning, Sect. 7.10 Cross-Validation,
Shalev-Shwartz & Ben-David (2014) Understanding Machine Learning: From Theory to Algorithms, Sect. 11.2.4 $k$-Fold Cross Validation and
Bishop (2006) Pattern Recognition and Machine Learning, Sect. 1.3. Model Selection

can all serve as authoritative, well-established and widely used references that will withstand academic scrutiny. For that matter, probably most of the areas covered in an  undergraduate ML course will be included in one of these books.
On a purely interpersonal level: Your lecturer might have a particular application in  mind. Politely ask him/her to point you to some relevant material.
Comment: Thank you so much for the references! But is it true that my professor way is more valid and made the model robust like she said?
Comment: I am glad I could help. Without sugarcoating it, what your professor described does not appear to be a very standard approach. But as I said maybe there is a particular application so you should definitely ask for some material.
Comment: okay, will do. thanks for the assistance!


Problemas ao persistir dados no Doctrine

Question: Estou a fazer isto:

  function Autenticar($objecto) {

        //require $this->db;
        require ROOT . "config/bootstrap.php";

        return $entityManager->getRepository('models\Usuarios')->findOneBy(array('login' => $objecto->login, 'senha' => $objecto->senha));
    }

Ele me retorna isto:

Class "models\Usuarios" is not a valid entity or mapped super class.

Alguém tem uma ideia do que esta a se passar?
Já lutei aqui e não consegui nada.
Comment: O repositório retorna um, ou uma coleção de entidades. Você está definindo que essa entidade é `models\Usuarios`, é isso mesmo?
Comment: esse é o caminho onde esta a minha classe mapeada. o caminho é models\usuarios (models e o nome do meu namespace)
Comment: Você tem que passar o caminho completo da classe. Se você tem uma classe `Usuario` dentro do namespace `Models\Usuarios`, então tem que usar `Models\Usuarios\Usuario`. E se atente às maiúsculas também.
Comment: ok, obrigado era mesmo isso! valeuu
Answer: Mudei a configuração da criação entity manager desse jeito
setando as configurações definidas anteriormente

$config = Setup::createAnnotationMetadataConfiguration($entidades, $isDevMode, NULL, NULL, FALSE); //adicionei Null no 3 e 4 parametro, e no 5 parametro coloquei true pra ele aceitar  uso de NAMESPACE..

criando o Entity Manager com base nas configurações de dev e banco de dados

$entityManager = EntityManager::create($dbParams, $config);

Ok Valeu pela ajuda


ruby sidekiq `require': cannot load such file -- pg (LoadError)

Question: I try to build a microservice on pure ruby with some additional features. I use sidekiq for jobs and pg for DB connection.
To start the Sidekiq server I use default settings and code:
# ./config/sidekiq.rb

require 'sidekiq'
require 'pg'  # This doesn't work with "`require': cannot load such file -- pg (LoadError)"
require_relative '../jobs/location_jobs/collect_job' # here is my job locates

# If your client is single-threaded, we just need a single connection in our Redis connection pool
Sidekiq.configure_client do |config|
  config.redis = { url: 'redis://localhost:6379/0', namespace: 'analytic_serv', size: 5 }
end

# Sidekiq server is multi-threaded so our Redis connection pool size defaults to concurrency (-c)
Sidekiq.configure_server do |config|
  config.redis = { url: 'redis://localhost:6379/0', namespace: 'analytic_serv' }
end

As you can see I try require PG gem in sidekiq.rb. Actually I use it in another file and use it here only for example.
So, when I try to run my sidekiq-server it raises an exception
bundle exec sidekiq -r ./config/sidekiq.rb -C ./config/sidekiq.yml

analytic_serv/config/sidekiq.rb:2:in require': cannot load such file -- pg (LoadError)`
it works for the simple ruby script that I use for creating job, but it doesn't work when I run sidekiq-server.
Please, help. What am I doing wrong?
How can I include a gem in this case?
Comment: Are you sure the `pg` gem is installed on the machine?
Comment: sure! I use it for set data, when I create job. And with my other Rails projects
Comment: it works in ruby script, but not in sidekiq-server file
Answer: Always use Bundler to make sure your gems are set up correctly: bundle exec ruby script.rb and bundle exec sidekiq
Comment: unfortunately, it didn't help.
Answer: Try adding gem 'pg' to your Gemfile, and install bundle via bundle install.
Answer: Cannot load such a file means, the specific file is not available.
Search for path bundle show pg.
Sometimes even if the gem is not there it is shown because of the gemspec. So, remove the gemspec as well and do bundle install.


How to correctly apply LDA following PCA?

Question: I have a high dimensional dataset ($n \times p$: $30 \times  100$) which I want to use as an testing dataset to build a two group classifier (LDA or QDA). I've read that you can do PCA to do an dimension reduction of your dataset to select to most important features. But I'm a bit confused what you use exactly as the input to build the classifier. I'm familiar with PCA using SVD and what it means.
Consider following situation:

I do a SVD of my dataset.
I look at the scores of the first couple of principal components.
When I assign my scores a label indicating from which group they come, I see that the 3th PC best separates my 2 groups (although it only explains 7% of the total variance).

What do I do next?

I take the 3th PC transform to the original parameter space (scores * loadings * scale + mean) and build my classifier
I look at the loadings in the 3th PC and try to decide which parameters in my original parameter space are important and build a classifier only using these.
...

Option 2 seems the most sensible in my opinion but I'm not entirely sure.
Also If I see that only the 3th PC is important to explain the variance in my two groups, can I forget about the first two PC in my further analysis?
Comment: It is unclear whether you want just dimensionality reduction (given that you have n<p) or you want feature selection (i.e. you insist to stay only with very few variables out of 100 _before_ you proceed to LDA).
Comment: If your wish is the first one I said about, i.e. only the fact that n<p bothers you and only this fact forces you to apply PCA, - then you should retain 28 (all but one last) components in PCA and do LDA on those 28 components, leaving there few strongest discrimimants. Each of those is the linear combination of 28 components, each of which is in turn the linear combination of 100 variables.
Comment: See also: [Best practice for dimensionality reduction with PCA and LDA: does it make sense to combine them?](http://stats.stackexchange.com/questions/106121)
Answer: If you're going to do LDA after PCA I would keep the first k components. Don't try and figure out which of the components are important and don't go back to the original parameter space. You can feed in the k dimensional data into your LDA classifier and let it figure out what is important there.
Comment: If you want to feed only scores into the LDA training that actually have discriminativ power, consider using e.g. PLS instead of PCA for the dimensionality reduction step.
Comment: You mean use the principal components to build your classifier? How is this possible? How can  your classifier know to look at the correct parameters without when you give it test data (which has all p parameters) without the information in your loadings. Or do you have to transform somehow your test data and your future data?
Comment: You always do the exact same transformations to your test data as you did to your training data.
Comment: Ok, I think I got it. So the following should be the right thing to do with the test data afterwards. (test_data-mean_training) * scale_training * q loadings_train
Comment: Looks cgood to me.


Users suddenly missing write permissions to the root drive c within an active directory domain

Question: I'm managing an active directory single domain environment on some Windows Server 2008, Windows Server 2008 R2 and Windows Server 2012 machines.
Since a few weeks I got a strange issue. Some users (not all!) report that they cannot any longer save, copy or write files to the root drive c, whether on their clients (vista, win 7) nor via remote desktop connection on a Windows Server 2008 machine. Even running programs that require direct write permissions to the root drive without administrator permissions fail to do so since then.
The affected users have local administrator permissions.
The question I'm facing now is:
What caused this change of system behavior? Why did this happen? I didn't find out yet.
What was the last thing I did before it happened?

The last action that was made before it happened was the rollout of a
GPO containing network drive mappings for the users depending on
their security group membership. All network drives are located on a
linux server with samba enabled.
We did not change any UAC settings, and they have always been activated.
However I can't imagine that rolling out this GPO caused the problem.
Has anybody faced an issue like that?

Just in case:

I know that it is for a specific reason that an user without
administrative privileges is prevented from writing to the root drive
since windows vista and the implementation of UAC. I don't think that
those users should be able to write to drive c, but I try to figure
out why this is happening and a few weeks ago this was still working.
I also know that a user who is a member of the local administrators
group does not execute anything with administrator permissions per
default unless he or she executes a program with this permissions.

What did I do yet?

I checked the permissions of the affected programs, the affected
clients/server. Didn't find something special.
I checked ALL of our GPOs if there exist any restrictions that could
prevent the affected users from writing to the root drive. Did not
find any settings.
I checked the UAC settings of the affected users and compared those
to other users that still can write to the root drive. Everything
similar.
I googled though the internet and tried to find someone who had a
similar problem. Did not find one.

Has anybody an idea? Thank you very much.
Edit:
The GPO that was rolled out does the following (Please excuse if the settings are not named exactly like that, I translated the settings into english):

**Windows Settings --> Network Drive Mappings --> Drive N: --> General:**
Action: Replace

**Properties:**
Letter: N
Location: \\path-to-drive\drivename
Re-Establish connection: deactivated
Label as: Name_of_the_Share
Use first available Option: deactivated

**Windows Settings --> Network Drive Mappings --> Drive N: --> Public:
Options:**
On error don't process any further elements for this extension: no
Run as the logged in user: no
remove element if it is not applied anymore: no
Only apply once: no

**Securitygroup:**
Attribute --> Value
bool --> AND
not --> 0
name --> domain\groupname
sid --> sid-of-the-group
userContext --> 1
primaryGroup --> 0
localGroup --> 0

**Securitygroup:**
Attribute --> Value
bool --> OR
not --> 0
name --> domain\another-groupname
sid --> sid-of-the-group
userContext --> 1
primaryGroup --> 0
localGroup --> 0

Edit:
The Error-Message of an affected users says the following:

Due to an unexpected error you can't copy the file.
Error-Code 0x80070522: The client is missing a required permission.

The command icacls C: shows the following:

NT-AUTORITY\SYSTEM:(OI)(CI)(F)
PRE-DEFINED\Administrators:(OI)(CI)(F)
computername\username:(OI)(CI)(F)

A college just told me that also the primary domain-controller (PDC) changed from Windows Server 2008 to Windows Server 2012. That also may be a reason. Any suggestions?
Comment: Can you tell us what your Anti-Virus solution is? Anything changed there?
Comment: Can you share exactly what the GPO does (settings, scripts, regkeys, etc.)?
Comment: I edited the post and described the content of the GPO. Thank you for your answer.
Comment: What's the actual error they get when trying to save a file to C:\? What do the NTFS permissions look like?
Comment: I also edited this information. Thanks for your input.
Answer: I'm not allowed to comment yet and this isn't a solution as such, but I have noted the same sort of behavior on Windows 7 and 8 in addition to Server 2012 and Server 2012 R2. On top of that, this happens from the Administrator account even after changing the ownership and full permissions of the drives root directory to the Administrator account. Also, this experience was observed on the local account with machines in a workgroup, so networking and the being in a domain is not part of the issue.
For example, Administrator is not allowed to copy a file from the D: drive to the E:\ root, but can copy to E:\temp and then move the file to E:\.  Copying is not allowed, but moving on the same drive is.
If you really have users that are allowed to do these functions:

Some users (not all!) report that they cannot any longer save, copy or
  write files to the root drive c

I would suggest studying closely what is unique about their accounts compared to the others. As far as why the behavior changed, I just assumed that it was something that got applied with Microsoft update. (Sort of an answer :-)


Como fazer uma subquery no Laravel com base nessas informações?

Question: Tenho as tabelas:
notifications:

users:

... E tenho o seguinte código que está no meu controller:
public function allRelations($internalClientId)
{

  $internalClient = InternalClient::find($internalClientId);

  if(empty($internalClient))
  {
     return response()->json(['error' => 'Internal Client not found!'], 404);
  }

  $notifications = InternalClient::join('notifications', 'notifications.internal_client_id','=','internal_client_id')
  ->select(
           'notifications.id AS notification_id',
           'notifications.from_user_id AS from_user_id',
           'notifications.to_user_id AS to_user_id',
           'notifications.title AS notification_title',
           'notifications.message AS notification_message',
           'notifications.checked AS notification_checked'
          )
          ->where('internal_client_id',$internalClientId)
          ->groupBy('notifications.id')
          ->get();

   return response()->json($notifications, 201);
}

No momento esse código me retorna isso:

Até ai tudo bem. Só que eu gostaria de retornar o 'name' (que está na tabela users) correspondentes aqueles ID's que estão nos campos from_user_id e to_user_id na tabela notifications (que são foreign key de usuários da tabela users). Acredito que para isso será necessário fazer uma subquery. Porém nunca fiz isso no Laravel.
Alguém poderia me ajudar ?
Answer: Consegui resolver utilizando o raw da classe DB.
Importei a classe no topo do arquivo assim:
use Illuminate\Support\Facades\DB; //Chamando a classe DB
E o código do método ficou assim:
public function allRelations($internalClientId)
{

   $internalClient = InternalClient::find($internalClientId);

   if(empty($internalClient))
   {
      return response()->json(['error' => 'Internal Client not found!'], 404);
   }

   $notifications = InternalClient::join('notifications', 'notifications.internal_client_id','=','internal_client_id')
   ->select(
             'notifications.id AS notification_id',
             'notifications.from_user_id AS from_user_id',
              DB::raw("(SELECT name FROM users WHERE id = from_user_id) AS from_user_name"),
              'notifications.to_user_id AS to_user_id',
              DB::raw("(SELECT name FROM users WHERE id = to_user_id) AS to_user_name"),
              'notifications.title AS notification_title',
              'notifications.message AS notification_message',
              'notifications.checked AS notification_checked'
            )
            ->where('internal_client_id',$internalClientId)
            ->groupBy('notifications.id')
            ->get();

   return response()->json($notifications, 201);
}

O retorno ficou assim:

Apesar de eu achar que tenha ficado meio feio (e saído [acho eu] um pouco da premissa do Laravel), foi exatamente o que eu estava precisando. Espero que possa ajudar a quem mais precisar!


$1$ man can eat $1$ apple in $1$ day.How many apples can six men eat in six days?

Question: $1$ man can eat $1$ apple in $1$ day.How many apples can six men eat in six days?
My approach:
$1$ men can eat $1$ apple in $1$ day.
Now, 6 men can eat in 6 days 6 apples only assuming each men eat $1$ apple a day.
Am I right in my approach?
Comment: @Jack Sure: 1 man can eat 1 apple in 1 day. In 6 days, that one man can eat 1 apple each day, so in total, 1 man can eat 6 apples in 6 days. Now multiply by the number of men...
Comment: Nope. Each man has all of the six days to eat apples : )
Comment: @A.Sh Can you explain in detail what you are trying to say?
Comment: It depends on if they get fed up with apples at any point or keep the same apple eating speed.
Comment: I can eat like twenty apples a day before I get sick. These puzzles are silently teaching you to view any relationship as (multi-)linear. Sure, work out the math that is intended for them, but also make sure to stay real, you know. If you can scramble five eggs in five minutes using one pan, how long does it take to scramble three eggs using four pans? Well, just use one of those pans to scramble them in five minutes as well! You know what I'm sayin'?
Comment: @k.stm Multi linear relationship ya i am getting used to these problems.In your question i think it takes 12 minutes ?
Comment: Not really "problems". More like a jesters juggling balls. 99% theatre 1% serious.
Answer: no. 1 man can eat 1 apple in 1 day therefor 1 man can eat 6 apples in 6 days. therefor 6 men can eat 36 apples in 6 days....
Comment: But we need to assume no one gets fed up with apples at any point.
Comment: right ;) :D :D :D and we have to assume that nobody becomes greedy and so on.... ;)
Comment: And that no one loses motivation.
Comment: haha :) :P Carry on
Comment: @mathreadler To overcome the obstacles you seem to foresee just keep in mind that 1 apple a day keeps 1 doctor away ;-)
Comment: Not a real obstacle... more like a little experiment. =)
Answer: The following piece by Lewis Carroll first appeared in ``The Monthly
Packet'' of February 1880 and is reprinted in _The_Magic_of_Lewis_Carroll_,
edited by John Fisher, Bramhall House, 1973.
                             Cats and Rats

If 6 cats kill 6 rats in 6 minutes, how many will be needed to kill 100
   rats in 50 minutes?
This is a good example of a phenomenon that often occurs in working
   problems in double proportion; the answer looks all right at first, but,
   when we come to test it, we find that, owing to peculiar circumstances in
   the case, the solution is either impossible or else indefinite, and needing
   further data.  The 'peculiar circumstance' here is that fractional cats or
   rats are excluded from consideration, and in consequence of this the
   solution is, as we shall see, indefinite.
The solution, by the ordinary rules of Double Proportion, is as follows:
   6 rats   :  100 rats  \
                          >   :: 6 cats : ans.
  50 min.   :    6 min.  /

Then:  ans = (100)(6)(6)/(50)(6) = 12

But when we come to trace the history of this sanguinary scene through all
   its horrid details, we find that at the end of 48 minutes 96 rats are dead,
   and that there remain 4 live rats and 2 minutes to kill them in: the
   question is, can this be done?
Now there are at least four different ways in which the original feat,
   of 6 cats killing 6 rats in 6 minutes, may be achieved.  For the sake of
   clearness let us tabulate them:
      A.  All 6 cats are needed to kill a rat; and this they do in one minute,
          the other rats standing meekly by, waiting for their turn.
      B.  3 cats are needed to kill a rat, and they do it in 2 minutes.
      C.  2 cats are needed, and do it in 3 minutes.
      D.  Each cat kills a rat all by itself, and take 6 minutes to do it.
In cases A and B it is clear that the 12 cats (who are assumed to come
   quite fresh from their 48 minutes of slaughter) can finish the affair in
   the required time; but, in case C, it can only be done by supposing that 2
   cats could kill two-thirds of a rat in 2 minutes; and in case D, by
   supposing that a cat could kill one-third of a rat in two minutes.  Neither
   supposition is warranted by the data; nor could the fractional rats (even
   if endowed with equal vitality) be fairly assigned to the different cats.
   For my part, if I were a cat in case D, and did not find my claws in good
   working order, I should certainly prefer to have my one-third-rat cut off
   from the tail end.
In cases C and D, then, it is clear that we must provide extra cat-power.
   In case C less than 2 extra cats would be of no use.  If 2 were supplied,
   and if they began killing their 4 rats at the beginning of the time, they
   would finish them in 12 minutes, and have 36 minutes to spare, during which
   they might weep, like Alexander, because there were not 12 more rats to
   kill.  In case D, one extra cat would suffice; it would kill its 4 rats in
   24 minutes, and have 24 minutes to spare, during which it could have killed
   another 4.  But in neither case could any use be made of the last 2
   minutes, except to half-kill rats---a barbarity we need not take into
   consideration.
To sum up our results.  If the 6 cats kill the 6 rats by method A or B,
   the answer is 12; if by method C, 14; if by method D, 13.
This, then, is an instance of a solution made indefinite by the
   circumstances of the case. If an instance of the impossible be desired,
   take the following: If a cat can kill a rat in a minute, how many would be
   needed to kill it in the thousandth part of a second?  The mathematical
   answer, of course, is 60,000, and no doubt less than this would not
   suffice; but would 60,000 suffice?  I doubt it very much.  I fancy that at
   least 50,000 of the cats would never even see the rat, or have any idea of
   what was going on.
Or take this: `If a cat can kill a rat in a minute, how long would it be
   killing 60,000 rats?'  Ah, how long, indeed!  My private opinion is that
   the rats would kill the cat.


owncloud with pre-existing user database

Question: I have a setup of dovecot with virtual users in a database. Now I would like to set up owncloud using the same users as already in the database. Is it somehow possible to configure owncloud as such one can log in only with the username and password from my existing database? Do you maybe know of a tutorial, that does that? (I couldn't find neither explanations on that nor a tutorial.)
The database has two columns, one with the user, one with the hashed password (sha512-crypt, with the normal format of mysql: $6$salt$hash )
Answer: As far as I can tell you can't use the external user database directly. However, it should be possible to use a hook that accesses the user database in a login attempt.
This post from the owncloud form shows how the hook pre_login is used. It checks for an LDAP group, but this should be easily adapted to your case.
Copy&paste of the essentials from the post:
Create a function that does the lookup in your database and returns true when the user is valid.
File <owncloud>/apps/<your_plugin>/appinfo/hooks.php
OC::$CLASSPATH['OC_Templates'] = 'lib/util.php';
class OC_user_ldap_Hooks{

public static function IsUserInGroup($parameters) {
            // replace this with your own database logic
            $filter = "(&(cn=owncloudusers)(memberUid=".$parameters['uid']."))";
           if(!OC_LDAP::searchGroups($filter, 'dn') && $parameters['uid']!="admin")
            {
                    $tmpl = new OC_Template( '', 'error', 'guest' );
                    $tmpl->assign('errors',array(1=>array('error'=>"User ".$parameters['uid']." is not a member of a group allowed to login.")));
                    $tmpl->printPage();
                    exit;
            }
            return true;
    }
}

And in the file <owncloud>/apps/<your_plugin>/appinfo/app.php
OC::$CLASSPATH['OC_user_ldap_Hooks'] = 'apps/<your_plugin>/lib/hooks.php';
OCP\Util::connectHook('OC_User', 'pre_login', 'OC_user_ldap_Hooks', 'isUserInGroup')

This is just the basic to get you started, you will have to handle a little more (for example creation of a new user in ownCloud if a user logs in the first time).
Comment: thanks (: I already solved the problem by using the imap backend as I have a mail server accesing the same database anyway. But if I find the time to write the hook then I'll post my results here. (PS: sorry, I can't vote you up, still new here ^^ )


Prove that integration and summation can be swapped

Question: $\def\d{\mathrm{d}}$Prove that integration and summation can be swapped in the following expression:
$$\int_{0}^{\infty} \sum_{n=0}^{\infty} \frac{(itx)^n}{n!}f(x)\,\d x,$$
where $|t|<\lambda$ and $f(x)$ is the density function of the $\mathrm{Gamma}(\lambda, \alpha)$ distribution for any real $\alpha >0$.
I know that I need to use Fubini's theorem and show:
$$\int_{0}^{\infty} \sum_{n=0}^{\infty} \left|\frac{(itx)^n}{n!}f(x)\right|\,\d x< \infty,$$
or
$$\sum_{n=0}^{\infty} \int_{0}^{\infty} \left|\frac{(itx)^n}{n!}f(x)\right|\,\d x< \infty.$$
I have tried the following:
\begin{align*}
&\mathrel{\phantom{=}} \sum_{n=0}^{\infty} \int_{0}^{\infty} \left|\frac{(itx)^n}{n!}f(x)\right|\,\d x\\
&< \sum_{n=0}^{\infty} \int_{0}^{\infty} \frac{\lambda^nx^n}{n!}|f(x)|\,\d x\ \text{(Used $|t|<\lambda$)}\\
&=\sum_{n=0}^{\infty} \int_{x=0}^{\infty} \frac{\lambda^nx^n}{n!}\left|\frac{x^{\alpha-1}\lambda^{\alpha}e^{-{\lambda}x}}{\Gamma(\alpha)}\right|\,\d x\ \text{(Substituted in $f(x)$)}\\
&=\sum_{n=0}^{\infty} \int_{x=0}^{\infty} \frac{1}{n!}\frac{x^{n+\alpha-1}\lambda^{n+\alpha}e^{-{\lambda}x}}{\Gamma(\alpha)}\,\d x\\
&\mathrel{\phantom{=}}\text{(Combined exponents and removed absolute value)}\\
&=\sum_{n=0}^{\infty} \frac{\Gamma(n+\alpha)}{n!\Gamma(\alpha)} \int_{x=0}^{\infty}\frac{x^{n+\alpha-1}\lambda^{n+\alpha}e^{-{\lambda}x}}{\Gamma(n+\alpha)}\,\d x\\
&=\sum_{n=0}^{\infty} \frac{\Gamma(n+\alpha)}{n!\Gamma(\alpha)}\\
&\mathrel{\phantom{=}}\text{(As the integral of the density of Gamma($\lambda$, $n+\alpha$) is $1$)}
\end{align*}
The problem now is I don't believe this sum converges.
Any help would be appreciated!
Comment: Is your sum over $i  $ or over $n $? Is the sum finite or infinite?
Comment: @PhoemueX The sum is over n and it is infinite. Thank you for spotting that typo
Answer: You have two problems that prevent you from proving the claim:

You effectively only use that $|t| \leq \lambda$, but you really do need to use $|t| < \lambda$.
You correctly realized that you have to options to prove the claim ("I know that I need to use Fubini's theorem and show abc OR xyz"), but you tried to use the more difficult one.

First of all, note
$$
\sum_{n=0}^\infty \left|\frac{(itx)^n}{n!}\right|
= \sum_{n=0}^\infty (|t| \cdot x)^n / n!
= e^{|t| \cdot x}.
$$
Therefore, what we need to show is
$$
\infty > \int_0^\infty e^{|t|\cdot x} \cdot f(x) dx.
$$
From your attempt, I conclude that $f(x) = \frac{\lambda^\alpha}{\Gamma(\alpha)} \cdot x^{\alpha - 1} \cdot e^{-\lambda x}$. Since the first factor is independent of $x$, it is not relevant for finiteness of the integral. Hence, we need to consider
$$
\int_0^\infty e^{|t| \cdot x} \cdot x^{\alpha - 1} \cdot e^{\lambda x} dx
= \int_0^1 x^{\alpha - 1} \cdot e^{(|t| - \lambda) x} \, dx + \int_1^\infty x^{\alpha - 1} \cdot e^{(|t| - \lambda) x} \, dx .
$$
For the first integral, simply note that since $|t| \leq \lambda$ and since $x \geq 0$, we have $e^{(|t| - \lambda)x} \leq 1$, so that the first integral satisfies
$$
\int_0^1 x^{\alpha - 1} \cdot e^{(|t| - \lambda) x} \, dx \leq \int_0^1 x^{\alpha - 1}\, dx = \frac{x^\alpha}{\alpha}\bigg|_0^1 = \frac{1}{\alpha},
$$
where we used that $\alpha > 0$.
Thus, it only remains to consider the second integral. To this end, let $\delta = \frac{\lambda - |t|}{2}$ and note $\delta > 0$. Now, for example from the Taylor expansion $e^x = \sum_n x^n / n!$, we have for $x \geq 1 > 0$ that $e^{\delta x} \geq (\delta x)^n / n! = C_{\delta, n} \cdot x^n \geq C_{\delta, n} \cdot x^{\alpha - 1}$ for arbitrary $n \in \Bbb{N}$ with $n \geq \alpha - 1$.
Therefore,
$$
\int_1^\infty x^{\alpha - 1} e^{(|t| - \lambda)x} \, dx
\leq \frac{1}{C_{\delta, n}} \cdot \int_1^\infty e^{\delta x} \cdot e^{-2\delta x} \, dx
= \frac{1}{C_{\delta, n}} \cdot \int_1^\infty e^{-\delta x} \, dx < \infty,
$$
since $\delta > 0$.