Uso do WaitAll em C#

Question: Tenho o seguinte problema:
Um programa gera dois tipos de threads A e B através de cliques em seus respectivos botões. Os dois tipos não podem executar ao mesmo tempo. Se eu tiver 10 threads A, a B só pode executar quando as 10 do tipo A terminarem.
Consigo restringir a entrada,  criando um mutex para cada tipo e uma variável booleana que me diz se existe ou não threads do outro tipo sendo executadas. Porém, quando termina a primeira thread, a do tipo contrário pode entrar na região crítica porque estou usando nomeMutex.WaitOne().
Como posso adaptar o uso do 'WaitAll' para esta situação? Não consegui compreender bem o conceito.
Answer: É possível resolver esse problema usando:

um Mutex (lock)
dois contadores, um para A e outro para B
e dois eventos de reset manual ManualResetEventSlim
O ManualResetEventSlim serve para travar a execução quando alcança o método Wait, mas somente se estiver em estado não-setado (existem dois estados, setado e não-setado). Threads podem chamar o método Set para colocar o objeto em estado setado, ou Reset para colocar em estado não-setado.
exemplo: uma implementação fácil, seria como abaixo. Este código entretanto não cuida de casos e starvation, que é quando As ou Bs podem ser impedidos de executar, caso a thread do tipo oposto entre com mais frequência do que o processador é capaz de executá-las... assim sendo o número de threads do tipo oposto só aumenta.
private static int a = 0;
private static int b = 0;
private static readonly object locker = new object();
private static readonly ManualResetEventSlim mreA = new ManualResetEventSlim(true);
private static readonly ManualResetEventSlim mreB = new ManualResetEventSlim(true);

static void A()
{
    while (true)
    {
        lock (locker)
        {
            // se não tem Bs executando, então o A pode executar
            if (b == 0)
            {
                // o A vai executar, então devemos:
                //  - impedir o acesso de Bs
                //  - incrementar o contador de As
                mreB.Reset();
                a++;
                break;
            }
        }

        // já tem Bs executando, vamos ficar esperando um sinal para continuar A
        mreA.Wait();
    }

    Console.WriteLine("A está executando");

    lock (locker)
    {
        // o A terminou, então:
        //  - decrementamos o contador de As
        //  - liberamos os Bs, se não houver mais As executando
        a--;
        if (a == 0)
            mreB.Set();
    }
}

static void B()
{
    while (true)
    {
        lock (locker)
        {
            // se não tem As executando, então o B pode executar
            if (a == 0)
            {
                // o B vai executar, então devemos:
                //  - impedir o acesso de As
                //  - incrementar o contador de Bs
                mreA.Reset();
                b++;
                break;
            }
        }

        // já tem As executando, vamos ficar esperando um sinal para continuar B
        mreB.Wait();
    }

    Console.WriteLine("B está executando");

    lock (locker)
    {
        // o B terminou, então:
        //  - decrementamos o contador de Bs
        //  - liberamos os As, se não houver mais Bs executando
        b--;
        if (b == 0)
            mreA.Set();
    }
}

Resposta anterior
ReaderWriterLockSlim
O que são A e B? Me parece o caso de um reader-writer lock, onde a leitura pode ser executada várias vezes ao mesmo tempo, e a escrita pode ser executada apenas se nada mais estiver executando, nem outras escritas nem leituras sendo feitas.
Se for este o caso, o melhor é usar um ReaderWriterLockSlim, que faz parte do framework .Net, que serve exatamente para isso.
Comment: Na verdade, meu problema se parece mais com o do "Banheiro Unissex". Poderia dizer que A e B são homens e mulheres tentando usar o mesmo "banheiro". Se tiver A, só A pode entrar e B espera esvaziar. Se tiver B, só B pode entrar e A espera esvaziar.
Comment: Entendo... nesse caso o `ReaderWriterLockSlim` não serve realmente. Fiz uma implementação usando um Mutex, dois `ManualResetEventSlim` e dois contadores. Não é perfeita (sofre de starvation), mas é um bom início. Vê ai se te serve, e me fala se tiver dúvida.

Uso do WaitAll em C#


Pitch and Hearing beginner question

Question: I'm a total newbie. And I'll pretend there are no black notes so it is easier for me to explain.
CDEFGABḈḊ (where Ḉ and Ḋ are one octave above C and D)
When a Musician says, "oh, C and Ḉ are the same note" (Sound or pitch? wise), is it because music theory says so or is there a scientific reason? (for example, like Li and Na have same-ish properties in the Periodic table.)
Comment: Your instinct to compare to the periodic table is apt!
Comment: Somewhat related: https://music.stackexchange.com/questions/127418/semitones-vs-perfect-fifth , especially my answer (and the comment on it): words like "sound," "note," and "pitch" can be used vaguely. C and Ç in this example belong to the same "pitch class" (meaning all Cs). And the simple answer of why they sound "different but related" is that their frequencies are in a ratio of 2:1; if "C" is 256 Hz, then "Ç" is 512.
Comment: [Here's a fascinating piece](https://www.quantamagazine.org/perceptions-of-musical-octaves-are-learned-not-wired-in-the-brain-20191030/) on how 'octave equivalence' might in fact be learned rather than innate. Time is running out to find sufficiently "uncontacted" peoples to gather more data from!
Comment: The brain may contribute to octave equivalence as well.  https://music.stackexchange.com/q/44783/20675
Comment: There are octave numbers you can use, like `C4 D4 E4 F4 G4 A4 B4 C5 D5`, that's a convention, use it an people will understand your meaning.
Comment: Don't you think pretending there are no black notes is part of the reason this seems difficult to understand?
Answer: We say that C and Ḉ are "the same note" because their frequencies (rates of vibration) are in a 1:2 ratio. In other words, the sound waves of Ḉ vibrate twice as fast as those of C, and the waves of the pitch an octave above Ḉ vibrate at twice the rate of those of Ḉ (four times the rate of those of C).
In music theory, we distinguish between pitch and pitch class. A pitch is any given musical sound; C and Ḉ are both separate pitches. A pitch class, however, is the collection of musical sounds that all have the same name. Thus C and Ḉ are both members of pitch-class C, even though they are separated by octave. Similarly, D♭ and Ḋ♭ are all members of pitch-class D♭.
Another similar term is that of octave equivalence. At least in tonal music, because of the how the vibrations align, we treat C and Ḉ as "equivalent" from this stand point; hence the use of the term pitch class, which assumes equivalence across all octaves.
Answer: Music theory says that notes with the same name are "the same note" even though they are obviously different pitches. When played together, it can sound like a single pitch even though there are two or more.
By designating C and Ḉ as "the same", it allows for scales, for example to be seven pitches that repeat rather than infinite series. It also allows for chords to be defined consistently no matter which octave the notes happen to be in.
To the degree that there is a scientific basis, it's that given a particular pitch, its first overtone is one octave higher (and further octaves are also within the overtone series). Thus, when we hear C, we're also hearing Ḉ (as well as other overtones), but we perceive it just as the single pitch C.
Answer:
is it because music theory says so or is there a scientific reason? (for example, like Li and Na have same-ish properties in the Periodic table.)

Well music theory does say so, but you can empirically determine this yourself by listening to octaves. They sound very similar to each other.
I agree with Theodore's comment, the periodic table comparison is pretty good. Elements have an electron shell with a certain shape, this determines how they react with other elements (and why Li and Na are in the same "group"/column.) All notes have an overtone series, and many people believe the way two notes sound together has everything to do with how their overtones overlap.
In the case of the octave: if our fundamental pitch is 100Hz, the sounds produced would be 100Hz, 200Hz, 300Hz, 400Hz, 500Hz, 600Hz, etc. You hear all of these but interpret them as a single pitch. If you played the octave, the sound would be 200Hz, 400Hz, 600Hz, etc. You can see that the lower octave's overtones contain every one of the higher octaves overtones. When played at the same time, all you get is a change in amplitude of frequencies that are already present.
Back to the periodic table, Halogens and Alkali metals react a certain way because of how their electron shells complement each other. The notes C and E react a certain way because of how their overtones complement each other. This reaction creates chemical compounds, intervals, chords, and the reaction is similar regardless of octave.
Don't completely disregard octave. We season our food with NaCl, not KBr despite both compounds being made of the same groups. Similarly, we don't usually write basslines in the range of C5.

Pitch and Hearing beginner question


Normalized 2D tensor values are not in range 0-1

Question: Below function takes in 2D tensor and normalizes it using broadcasting .The issue is except all values to be in range 0-1 but the result has values outside this range . How to get all values in 2D tensor in range 0-1
def torch_normalize(tensor_list):
    means = tensor_list.mean(dim=1, keepdim=True)
    stds = tensor_list.std(dim=1, keepdim=True)
    normalized_data = (tensor_list - means) / stds
    return normalized_data

INPUT
tensor_list=tensor([[-5.6839, -7.5829, -7.2277, -6.5066, -8.4702, -7.9844, -5.6841,  1.8570,
          1.6170, -3.7592, -4.4140, -0.4981,  0.2501,  5.8463,  1.8897, -1.3968,
         -5.5402, -2.4561, -5.6819]])

Normalized result

tensor([[-0.5981, -1.0615, -0.9748, -0.7988, -1.2780, -1.1594, -0.5981,  1.2420,
          1.1835, -0.1284, -0.2882,  0.6673,  0.8499,  2.2155,  1.2500,  0.4480,
         -0.5630,  0.1896, -0.5976]])

Answer: Short Answer: What you're thinking about is called min-max normalization. You want the minimum value at each component to be mapped to 0, and the max to 1. Would look like this
mins = tensor_list.min(dim=1, keepdim=True)
maxs = tensor_list.max(dim=1, keepdim=True)
normalized_data = (tensor_list - mins) / (maxs - mins)

Longer Answer: What you tried is usually called standardization, and what it achieves is to make the mean and std 0 and 1, respectively, in the standardized sample. I'll happily expand on that if needed. That condition I mentioned over the mean and std doesn't imply at all that the transformed sample would stay in the [0, 1] range, which is what you observed.
Comment: so standardization focus on values to have mean -0 and std -1 and not about the range  of values to be between [0-1]  where as normalization using min-maz is the opposite it focus on the range to be [0-1] and not about having mean 0 and std 1 .Am i  right ?
Comment: Yep, that's it!


Optimise SVM to avoid false-negative in binary classification

Question: I am training an SVM binary classifier using Scikit learn.
Due to the nature of my problem I need to avoid false negatives. As nothing is free I am okay getting a higher rate of false positives in order to reduce the number of false negatives. How can we do that (ideally with Scikit learn)?
In other words, how can we minimise false negatives using an SVM classifier ? Is there some way to tune hyper parameters in order to favor false positives over false negatives?
Comment: The output of an SVM is a real number, a (signed) distance from the hyperplane $x$. A *decision function* says that for $x>c$, it's a positive; else it's a negative, for some specific $c$. You can change $c$ to change the contents of a confusion matrix/the estimates of TPR, FPR, FNR, TNR.
Comment: You don't need to change how you optimize your SVM, you just need to change at what decision value you declare an observation to be a negative or a positive. Adjust that to taste.
Comment: I think this question would be more squarely on topic if you emphasized the more general statistical or mathematical principles rather than how to do this in sklearn. (I feel that my comments demonstrate that at its core, this question is statistical in nature.)
Comment: @Sycorax Could you elaborate?
Comment: Please edit as suggested by Sycorax; as the outlined-answer-in-comments indicate, it would then be answerable here.
Comment: @Sycorax Thanks for the answer that has been quite helpful. This is in spirit what I was already doing. It is great to see that I was in the right direction.
I'm still wondering whether there are some hyper parameters that could be tuned in order to minimise false negatives. Is it possible to add a penalty for false positive during training (maybe SVM is not the right algorithm)? Would it make sense to  favor one of the class during training? Does it make sense to do a grid/random search on the hyper parameters to see the one that are minimising false positives?
Answer: Scikit learn implementation of the SVM binary classifier does not let you set a cutoff threshold as the other comments/replies have suggested. Instead of giving class probabilities, it straighaway applies a default cutoff to give you the class membership e.g. 1 or 2.
To minimize false negatives, you could set higher weights for training samples labeled as the positive class, by default the weights are set to 1 for all classes. To change this, use the hyper-parameter class_weight .
Ideally, you should avoid choosing a cutoff and simply provide the class probabilities to the end users who can then decide on which cutoff to apply when making decisions based on the classifier.
A better metric to compare classifiers is a proper scoring function, see https://en.wikipedia.org/wiki/Scoring_rule and the score() method in the svm classifier module sklearn.svm.SVC.
Answer: Like many predictive model, SVM will output probability scores and the apply threshold to probability to convert it into positive or negative labels.
As,  @Sycorax mentioned in comment, you can adjust the cut-off threshold to adjust the trade-off between false positive and false negative.
Here is some example in R.
library(kernlab)
library(mlbench)
graphics.off()
set.seed(0)

d=mlbench.2dnormals(500)
plot(d)
# using 2nd order polynominal expansion
svp <- ksvm(d$x,d$classes,type="C-svc",kernel="polydot",
            kpar=list(degree=2),C=10,prob.model=T)
plot(svp)

p=predict(svp,d$x, type="prob")[,1]

cut_off=0.5
caret::confusionMatrix(d$classes,ifelse(p<cut_off,2,1))

cut_off=0.8
caret::confusionMatrix(d$classes,ifelse(p<cut_off,2,1))

Note when we change cut_off, the confusion matrix (false postive, false negative etc.) changes
> caret::confusionMatrix(d$classes,ifelse(p<cut_off,2,1))
Confusion Matrix and Statistics

          Reference
Prediction   1   2
         1 253  16
         2  38 193

               Accuracy : 0.892
                 95% CI : (0.8614, 0.9178)
    No Information Rate : 0.582
    P-Value [Acc > NIR] : < 2.2e-16

                  Kappa : 0.7813
 Mcnemar's Test P-Value : 0.004267

            Sensitivity : 0.8694
            Specificity : 0.9234
         Pos Pred Value : 0.9405
         Neg Pred Value : 0.8355
             Prevalence : 0.5820
         Detection Rate : 0.5060
   Detection Prevalence : 0.5380
      Balanced Accuracy : 0.8964

       'Positive' Class : 1

> cut_off=0.8

> caret::confusionMatrix(d$classes,ifelse(p<cut_off,2,1))
Confusion Matrix and Statistics

          Reference
Prediction   1   2
         1 223  46
         2  10 221

               Accuracy : 0.888
                 95% CI : (0.857, 0.9143)
    No Information Rate : 0.534
    P-Value [Acc > NIR] : < 2.2e-16

                  Kappa : 0.7772
 Mcnemar's Test P-Value : 2.91e-06

            Sensitivity : 0.9571
            Specificity : 0.8277
         Pos Pred Value : 0.8290
         Neg Pred Value : 0.9567
             Prevalence : 0.4660
         Detection Rate : 0.4460
   Detection Prevalence : 0.5380
      Balanced Accuracy : 0.8924

       'Positive' Class : 1


How can I add another argument to CompareTo method?

Question: How can I add another argument to the CompareTo method so I can implement a switch statement to allow my program to select what the CompareTo method will be comparing?
Current I'm doing:
public int CompareTo(Employee other)
        {
            return name.CompareTo(other.name);
        }

What I want to do:
public int CompareTo(Employee other, string choice)
        {
            switch(choice)
            {
                 case "name":
                     return name.CompareTo(other.name);
                 case "number"
                     return number.CompareTo(other.number);
            }
            return name.CompareTo(other.name);
        }

Comment: Have you not just provided the answer as part of your question?
Comment: Take a look at IComparable<>.  _"The role of IComparable is to provide a method of comparing two objects of a particular type."_
Comment: Is this question regarding _String_.CompareTo() ?
Answer: I assume you're asking how you can extend the functionality of existing classes that you can't modify (otherwise you could directly edit the class itself), and if that's the case, I'd recommend making an extension method as such:
public static class EmployeeExtensions {
    public static int CompareTo(this Employee baseEmployee, Employee other, string choice){
         ... code ....
         return 0;
    }
}

This will then allow you to extend the compare to functionality, and call this from wherever you require it. You need to put the extension method in its own static class.
You can call it by going:
Employee a = new Employee(...);
Employee b = new Employee(...);
a.CompareTo(b, "args");

Assuming the extension class has been imported where you are trying to use it. This is usually the way C# allows for extending functionality of classes you do not have access to. Although if you do have access to the class I'd recommend editing the class itself and making a new method (you may be able to override, but if they provide distinct functionality you'll need to write two methods, in this case code duplication is ok).
This doesn't apply if you're actually trying to change the default equality members, and if that's the case, you can't add your own argument and have it still work with existing infrastructure such as list sorting, so I'd recommend re-evaluating your problem if you 'want to add an argument to equals' for example.
If you're trying to change the way objects compare (objects implementing IComparable), then make your own IComparer, and use that to do the comparing, don't try and change the way CompareTo is done on the class, as the default behavior of Compare (with arguments as is) is useful. I'm also not saying don't implement IComparable (rather than making a IComparer) if it makes sense and you have access to the class then use an IComparable, but that won't allow you to change the arguments of the inherited compare method.
Comment: By nature of the his question referring to code that would achieve what he is asking if he had access to the initial class, I state the assumption that he doesn't have access. Then at the end I talk about comparators and comparables as you suggest. I've covered a few different bases due to the original ambiguous nature of the question, but happy to add more.
Comment: `I assume you're asking`, `This doesn't apply if you're actually trying to`, `If you're trying to change the way objects compare `. I feel I covered all three interpretations in order of how likely I think they are, but in any case, I don't feel like I've neglected any information?
Comment: What _may be_ is not as important as the facts.  Besides, your use of extension methods is an example of not how to do things.  As I said, it is no different to what OP is doing.
Comment: The net effect is no different to the OP's original
Comment: @MickyD I'd agree in the general case, but in the case OP doesn't have access to original class it is different, and in the case OP has access but is trying to make use of a 'comparer' I've also addressed that with a comparator, but I'm just trying to suggest a few ways for him to achieve things in different circumstances. Because it seems from his question directly modifying the original class isn't a solution. (*he/she for whole comment)
Comment: Where does OP state they don't have access to original class?   Anyway, the way this sort of thing is normally done is by wring a new comparison static object that implements IComparable<>. _"The role of IComparable is to provide a method of comparing two objects of a particular type."_
Comment: Incorrect.  His very **first** code snippet clearly says _"Current[ly] **I'm** doing:"_


Creating a wpf UIElement from a sample

Question: I'm looking to create a bunch of rectanges that are going to share some properties and some other properties will be different. This is all done in codebehind, and clearly it is very possible to do this without breaking a sweat by copy and paste skills, but in the spirit of making my code more elegant; is it possible to have a sample rectangle like so
Rectangle sampleRect = new Rectangle(){Stroke = strokebrush,Margin = new Thickness(5)};

and model everyother rectangle after that with diefferent height and width attributes?
UPDATE Thanks for the answers, I am actually looking for more of a CSS/style thing...
Answer: you could have Class that represents your Rectangle parameters and use DataTemplate to convert your class into Rectangle in your XAML
and your class will have default Strock and Margin and you can override height and width
Answer: You could wrap it inside a method, like this (assuming strokebrush is some sort of local field)
private static Rectangle RectangleBuilder(int height, int width)
{
   Rectangle sampleRect = new Rectangle()
   {
       Stroke = strokebrush,
       Margin = new Thickness(5),
       Height = height,
       Width = width
   };
   return sampleRect;
}

Creating a wpf UIElement from a sample


Reason for the diferentiability of function on open interval in Rolle's Theorem

Question: "Let $f(x)$ be a continuous function on $[a,b]$ and differentiable on $]a,b[$ ,further let $f(a)=f(b)$. Then there exist at least one number $c \in ]a,b[$ such that $f'(c)=0$". The above statement is the Rolle's Theorem. Why we take open interval for differentiability rather then close interval. What's the reason behind it??
Comment: It suffices. There's no reason to impose more stringent conditions.
Answer: See the proof of the theorem. If $f$ isn't constant, the point where $f$ reaches the max or the min $\in(a,b)$, so is a local extremum...
Answer: The requirement of differentiability over the whole closed interval would be excessive. Recall how the proof works: it shows that derivative vanishes somewhere in the interior part of the domain because there is at least a local maximum or minimum. Do you really need differentiability at extreme points for this?
Try to answer the last question while looking at the following graph:

$$f(x)=\begin{cases}
\sqrt{x}, & 0\le x < \frac{1}{2} \\
-\frac{\sqrt{2}}{2}(x-1)^2+\frac{1}{\sqrt{2}}+\frac{\sqrt{2}}{8}, & \frac{1}{2}\le x < \frac{3}{2} \\
\sqrt{2-x}, & \frac{3}{2}\le x \le 2.
\end{cases}
$$
Comment: Do you agree that the function shown has a maximum? However, is it differentiable at extreme points?
Answer: Simply put: there is no two-side derivative for the bounders of the closed interval. only one side derivative exists for $a$ and $b$. so we must exclude the two points.
Comment: I disagree with this answer. That's not the point: we could require that the one-side derivatives exist. The OP asks why we do not require this.


Horizontally Center a  that is not fixed

Question: I want to horizontally center a column in a responsive grid I'm trying to make.  I have the grid set up, and it works just fine.  But I want to make a .class that will take a column and center it horizontally in the parent (.row).  I would use this class to take a one-column-row and center the column in said row.  I can center the text using the text-align property, but I want the entire column to be centered that way if I add a border/background to the column it will be centered in the row, not just the column's content.
Here is the codepen.
Comment: Couldn't you simply set `margin: auto` to get the column centered?
Answer: Given that you are setting a width on the column, simply use margin:0 auto to center it. You would need to overwrite float:left with float:none though..
UPDATED EXAMPLE HERE
.center {
    text-align: center;
    margin:0 auto;
    float:none;
}

Alternatively, if the element doesn't have a fixed width set on it, you could simply make it an inline-block element and add text-align:center to the parent. Perfect for dynamically varying widths.
Comment: This works perfectly.  Thank you Josh!  I obviously was overlooking the fact that I had `float:left` set the the columns.

Horizontally Center a  that is not fixed


Intercept of logit vs intercept of multinomial logit

Question: If I simulate the success probability for a Bernoulli random variable $t_{binary}$ conditional on some regressor $x$:
N <- 100000
x <- rnorm(N, 0, 1)
b0 <- 0
p <- plogis(b0 + 0.3*x)

the average probability (mean(p)) will be 0.5 as long as the intercept b0 is zero. Changing the slope of $x$ to something other than $0.3$ has no impact on this average.
But if I simulate the probabilities of a 3-category $t_{multi}$:
p0 <- exp(0 + 0.1*x)
p1 <- exp(0 + 0.2*x)
p2 <- exp(0 + 0.3*x)
p <- cbind(p0,p1,p2)
p <- t(apply(p, MARGIN = 1, function(h) h / sum(h)))

the average probability is split evenly (.33,.33,.33) only when the slope of x is the same for the three categories or if I fiddle with the intercepts. Is this correct (is this a property of the multinomial logit) or am I just simulating it wrong? The formula I have in mind is:
$P(t_{multi}=c|x)=\frac{exp(\beta_{0c}+\beta_cx)}{\sum_{k=0}^2exp(\beta_{0k}+\beta_kx)}$
Thanks.
Answer: This is a consequence of Jensen's inequality. Because the exponential function is convex, the expectation $\mathbb{E} \{ \exp(\beta_0 + \beta_1 x) \}$ is not the same as $\exp\{ \mathbb{E} (\beta_0 +  \beta_1 x) \}$. Instead, $\mathbb{E} \{ \exp(\beta_0 + \beta_1 x) \} = \exp(\beta_0 + \frac{\beta_1^2}{2} )$
For logistic regression, this doesn't matter because zeroes and ones are symmetric due to how the logistic function is defined. But in your multinomial case, you're using the softmax function to set the probabilities, and so using your example of 0.1, 0.2, and 0.3 for the coefficients:
$ p(X=1) = \frac{ \exp(0.1^2/2 ) }{\exp(0.1^2/2 ) + \exp(0.2^2/2 ) + \exp(0.3^2/2 )} = 0.327$
Comment: I'm glad to hear you looked up the expectation of the exponential! I have a slightly different perspective than what you found, but it points to the same result: $\mathbb{E} \exp(\beta x)$ is the definition of the moment generating function of $X$. So you can find how to evaluate it by looking up the moment generating function of a normal random variable. And the $\exp(\beta_0)$ part is just a constant so you leave it as-is.
Comment: Thank you! I had to Google the rule you mention at the end of your first paragraph. In case anyone else is wondering: since $x$ is standard normal, $\beta_0+\beta_1x$ is a normal with mean $\beta_0$ and standard deviation $\beta_1$; this is all inside an exponential function, so we have to apply an $ln$ to get to the normal stuff, meaning that $exp(\beta_0+\beta_1x)$ has a log-normal distribution. Then $exp(\beta_0+\beta_1^2/2)$ is simply the expectation of that log-normal, or $exp(\mu+\sigma^2/2)$.


How to find all polynomials $P(x)$ with real coefficents satisfying $P^2(x)-1=4P(x^2-4x+1)$

Question:
Find all polynomials $P(x)$ with real coefficents satisfying
  $P^2(x)-1=4P(x^2-4x+1)$.

My solution:
Let the first term of $P(x)$ be $ax^n$. We see first term of left side is easily $a^2x^{2n}$ and right side's is
$4ax^{2n}$ . As we see there's absolutely no solution. If $n=0$ then easily, $a^2-4a-1=0$ and then we can find only 2 values for $P(x)=a$. So the solution is $2$.
Comment: Why do you think there is no solution if $n\neq 0$ ? $a^2=4a$ holds true for $a=4$ (also for $a=0$ but then this would not be a polynomial of degree $n$)
Answer: Let $Q(x+3)=P(x)$. Hence $$Q^2(x+3)-1=4Q(x^2-4x+4)=4Q((x-2)^2)$$
Let $x\rightarrow x+2$. $$Q^2(x+5)=4Q(x^2)+1$$
So $Q(5+x)=\pm Q(5-x)$
Let $R(x)=Q(5+x)$. $R$ is either odd or even and $$R^2(x)=4R(x^2-5)+1$$
If $R$ is odd then $R(0)=0$ and $R(5)=\frac{1}{4}$ and $R(-20)=\frac{15}{64}$ and more generally :
$S_0=0$, $S_{n+1}=5-S_n^2$, $T_0=0$ and $T_{n+1}=\frac{1-T_n^2}{4}$
It's easy to see that $P(S_n)=T_n$, but $\lim(T_n)$ is finite and $\lim(|S_n|)=\infty$. So $R$ is not a polynomial function.
If $R$ is even, $R(0)$ is an optimum (either maximum or minimum, $R'(0)=0$). Hence $R(\sqrt{5})$ is an optimum too, and $S_0=0$, $S_{n+1}=\sqrt{5+S_n}$ , then $S_n$ are all optimum... But all $S_n$ are different, so $R'$ has an infinite number of roots. This is not a polynomial function, except for a degree 0 polynomial.
So the only solutions are constant.
I hope there is no mistake :)
Answer: Suppose that P is not constant. Fixing $degP=n$ and comparing coefficients of both sides we deduce that the coefficients of polynomial $P$ must be rational. On the other hand, setting $x=a$ with $a=a^2−4a+1$, that is, $a=\frac{5±\sqrt{21}}{2}$, we obtain $P(a)=b$, where $b^2−4b−1=0$, i.e. $b=2±\sqrt{5}$. However, this is impossible because P(a) must be of the form $p+q\sqrt{21}$ for some rational p,q for the coefficients of P are rational. It follows that $P(x)$ is constant.
That is solution from http://www.imomath.com/index.php?options=346&lmm=0
But I don't know why the coefficients of polynomial $P$ must be rational


construct file tree from path components

Question: I have an array of file path components like this:
[ ['some', 'dir', 'file.txt'],
  ['other', 'folder', 'here.txt'],
  ['this', 'one', 'is', 'deeper', 'file.txt'],
  ['some', 'dir', 'second.txt'
]

So the array contains arrays each consisting of path components to a file. The last element in an inner array is always the file itself, with the preceding elements being directories leading to the file.
What I'm trying to figure out is how to transform the above data so that I can easily generate a file tree with it using
 and
 tags such that folders are nested within each other and files within the same folder show up together. All sorted alphabetically.
From the above I would like to generate the following. The file
 themselves have to be links to the path to that file:

some/

dir/

file.txt

second.txt

other/

folder/

here.txt

this/

one/

is/

deeper/

file.txt

Thanks, I'd appreciate any ideas.
Answer: Rough outline; as simple as possible (i.e., no tricks to keep things simple :)
require 'pp'

dir = {}

files = [
  ['some', 'dir', 'file.txt'],
  ['other', 'folder', 'here.txt'],
  ['this', 'one', 'is', 'deeper', 'file.txt'],
  ['some', 'dir', 'second.txt']
]

def merge_paths(h, paths)
  top = paths[0]

  if paths.size == 1
    h[top] = top
  else
    h[top] ||= {}
    merge_paths h[top], paths[1..-1]
  end
end

files.each do |paths|
  merge_paths dir, paths
end

pp dir

Outputs:
{"some"=>{"dir"=>{"file.txt"=>"file.txt", "second.txt"=>"second.txt"}},
 "other"=>{"folder"=>{"here.txt"=>"here.txt"}},
 "this"=>{"one"=>{"is"=>{"deeper"=>{"file.txt"=>"file.txt"}}}}}

Creating the lists is essentially the same process; recurse over hash keys. You're at the last level when a hash value isn't another hash. You might want to also sort by name and/or type, e.g., put directories (key values that are hashes) first, and so on.
There are a number of games you can play with this, including turning it into just a few lines of code, combined with gems like deep_merge to reduce the amount of busy-work you have to do manually.
This also doesn't do any "sanity checking" to make sure the data isn't pathological, e.g., you could construct an array that would turn a filename into a directory, wipe out a directory with a filename, and so on--an exercise left for the reader.
Comment: Thanks a ton. This is definitely a nice place to start. I appreciate it.


Understanding Gtk template objects

Question: While looking at the code for gnome-builder which is written in C using Gtk and other libraries, I found the following code for a shortcut window definition:
ide-shortcuts-window-private.h:
#pragma once
#include <gtk/gtk.h>

G_BEGIN_DECLS

#define IDE_TYPE_SHORTCUTS_WINDOW (ide_shortcuts_window_get_type())

G_DECLARE_FINAL_TYPE (IdeShortcutsWindow, ide_shortcuts_window, IDE, SHORTCUTS_WINDOW, GtkShortcutsWindow)

G_END_DECLS

ide-shortcuts-window.c:
#define G_LOG_DOMAIN "ide-shortcuts-window"
#include "config.h"

#include <glib/gi18n.h>

#include "ide-shortcuts-window-private.h"

struct _IdeShortcutsWindow
{
  GtkShortcutsWindow parent_instance;
};

G_DEFINE_TYPE (IdeShortcutsWindow, ide_shortcuts_window, GTK_TYPE_SHORTCUTS_WINDOW)

static void
ide_shortcuts_window_class_init (IdeShortcutsWindowClass *klass)
{
  GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass);

  gtk_widget_class_set_template_from_resource (widget_class, "/org/gnome/libide-gui/ui/ide-shortcuts-window.ui");
}

static void
ide_shortcuts_window_init (IdeShortcutsWindow *self)
{
  gtk_widget_init_template (GTK_WIDGET (self));
}

And this ui file which describes the window:
<?xml version="1.0" encoding="UTF-8"?>
<interface>

  <template class="IdeShortcutsWindow">
    <property name="modal">true</property>
    <child>
      <object class="GtkShortcutsSection">
        <property name="visible">true</property>
        <property name="section-name">editor</property>
        <property name="title" translatable="yes" context="shortcut window">Editor Shortcuts</property>
        <child>
          <object class="GtkShortcutsGroup">
            <property name="visible">true</property>
            <property name="title" translatable="yes" context="shortcut window">General</property>
            <child>
              <object class="GtkShortcutsShortcut">
                <property name="visible">true</property>
                <property name="title" translatable="yes" context="shortcut window">Show help</property>
                <property name="accelerator">F1</property>
              </object>
            </child>
              ...............

I have built some Gtk applications before but I have never seen or used such a way of describing objects and I am having a hard time understanding this code. I know that the .ui file describes a template from which the structure IdeShortcutsWindow will be initialized. But I don't quite understand how to use it. Should I create an instance of the structure like so:
IdeShortcutsWindow shortcuts;

But then how do I initialize it? Should I call the functions defined in ide-shortcuts-window.c for the instance? While looking at the rest of the code I didn't find a single other place where an instance of IdeShortcutsWindow is used.
Comment: No, you use `gtk_widget_class_bind_template_child`. `member_name` should be in `Private`-section. Go to `Building composite widgets from template XML` [here](https://developer.gnome.org/gtk3/stable/GtkWidget.html#GtkWidget.description)
Comment: By use I mean how can I create an instance of IdeShortcutsWindow and show it with gtk_window_present() for example.
Comment: You will need [GtkBuilder](https://developer.gnome.org/gtk3/stable/GtkBuilder.html)
Comment: Should I associate a GtkBuilder object with the ui file and call gtk_builder_get_object()? But what ID should I pass to gtk_builder_get_object()?
Answer:
Should I create an instance of the structure like so:
IdeShortcutsWindow shortcuts;

A new instance of the class is created with g_object_new (IDE_TYPE_SHORTCUTS_WINDOW, NULL). You can see the same in gnome-builder code.
Sometimes helper functions are provided to create new instances.  Say for example: gtk_button_new () and g_object_new (GTK_TYPE_BUTTON, NULL) are the same.  This is applicable to all GObjects and not specific to GtkBuilder templates.
See related documentations: 1 2
Please note that some_type_new() is a function that can be used only in C. Languages using GObject introspection bindings (eg: Python) shall only use g_object_new (...) to create new objects.
Personally I maintain a template project to help me easily develop GTK Applications, may be helpful for you: Link

Understanding Gtk template objects


Group structure from involutions, exercise devised by Richard Brauer.

Question: The following is an idea originally communicated by Richard Brauer. I'm having difficulty following some of the combinatorial elements.

Let $G$ be a finite group containing exactly two conjugacy classes of involutions. Let $u_1$ and $u_2$ be nonconjugate involutions in $G$. Let $c_i=|C(u_i)|$, the respective centralizers of the $u_i$. Let $S_i$ be the set of ordered pairs $(x,y)$ with $x$ conjugate to $u_1$, $y$ conjugate to $u_2$, and $(xy)^n=u_i$ for some $n$. Let $s_i=|S_i|$. Then $|G|=c_1s_2+c_2s_1$.

The idea is to count the ordered pairs $(x,y)$ with $x$ conjugate to $u_1$ and $y$ conjugate to $u_2$ in two different ways. Is it somehow clear that this number is $(|G|/c_1)(|G|/c_2)$ right off the bat? I believe this follows since the possible choices of the $x$ is the cardinality of the orbit of $u_1$ under the conjugation action, which equals the index of the stabilizer in $G$, but the stabilizer is just the centralizer in this case. Likewise for the choices of $y$.
On the other hand, I know that if the product $uv$ of two involutions $u$ and $v$ has odd order, then $u$ and $v$ are conjugate. So if $x$ and $y$ are not conjugate here, their product $xy$ has even order. Then $(xy)^n$ for $n=o(xy)/2$ is an involution, and thus conjugate to either $u_1$ or $u_2$. This exhausts all the pairs in question, but why does counting in this way give $(|G|/c_1)s_1+(|G|/c_2)s_2$? I only know that $(xy)^n$ is conjugate to some $u_i$ for some $n$, not that $(xy)^n=u_i$ as in the definition of the $s_i$.
After that, the result will follow from the equality
$$
(|G|/c_1)(|G|/c_2)=(|G|/c_1)s_1+(|G|/c_2)s_2.
$$
Thanks.
Answer: $G$ acts on the conjugacy class of $u_i$ by conjugation, so the number of elements conjugate to $u_i$ is the index of the stabilizer of $u_i$ in $G$.  The stabilizer is $C(u_i)$, so the number of involutions conjugate to $u_i$ is $|G|/c_i$.
For your second question:
Let $S$ be the set of pairs $(x,y)$ such that $x$ is conjugate to $u_1$ and $y$ is conjugate to $u_2$.
Let $T_i$ be the set of pairs $(x,y) \in S$ such that $(xy)^n$ (for $n=o(xy)/2$) is conjugate to $u_i$.
You want to prove that $|T_i| = |S_i| (|G|/c_i)$.
For each involution $u$, let $S_u$ be the set of pairs $(x,y) \in S$ such that $(xy)^n$ (for $n=o(xy)/2$) equals $u$.
We then have $|T_i| = \sum |S_u|$, where the sum takes place over the conjugacy class of $u_i$.  But the size of $S_u$ is independent of the choice of $u$ within the conjugacy class of $u_i$, because if $u^g = v$ then $(x,y) \mapsto (x^g, y^g)$ is a bijection between $S_u$ and $S_v$.  Hence $|S_u| = |S_i|$ for all $u$ in the conjugacy class of $u_i$.  There are $|G|/c_i$ conjugates of $u_i$, so $|T_i| = |S_i| (|G|/c_i)$.
Comment: Yes.  I have fixed it.


Premium DNS, Zones & VPS (nightmare...)

Question: I'm in need of networking expert help.
I have a server (CentOS) with private nameservers. The nameservers are pointing to my server. I have several domains that I set DNS to point to my private nameservers. I am using webmin for server configs and editing some configs with vim in /etc/.. Using bind8 (with webmin module) for domain names to resolve correctly and sites to be accessible by name and not ip.
This setup is working fine, however I want to get rid of BIND and having all the zones on my server. Instead I would like to manage all the zones by 3rd party management tool (GoDaddy Premium DNS). This way I can have all the zones in one place and have multiple servers in future with 1 central place for zones etc.
What do I need to do this? and how?
I have few ideas but do not want to mess with it unless I know for sure... Some domain are live and are getting good traffic. Have to do it as fast as possible.
Here are some of my ideas:

There are A records for private nameservers under my main domain. E.g. ns1.example.com & ns2.example.com. Will changing the IP Address for this A record to 3rd party DNS Server IP work? And then configure zones there... Basically instead of doing directly to my server it will go to 3rd party DNS server and then to my server.
Set up DNS resolver on the server to use 3rd party server... If this is the case, where do I start.
Comment: is there any reason you dont want to put all the zones on one webmin server and have that as the master record and then use other webmin servers as slaves this way you only have to make config changes from the master sercver and it will push to the slaves on its own. and if the master server goes down the slasves will still repond you just wont be able to edit from the slave.
Comment: I wanted to reduce # of things that are managed on my servers and worry less about running named... Less severs -> less expenses =), your solution looks good but it does the opposite. I got it figured out, changing ips of my Vanity Nameservers aka "private nameserver" to 3rd party DNS server and uploading my old zones there did the trick.
Comment: Good to hear that you got it working I have started my own cluster of virtual servers.
Answer:
There are not such things, as "private nameservers" and I don't want  translate it into technical term
On one (ordinary singlehomed) host you can't have nemeserverS, you have running DNS-daemon

You want to change NS-servers for all your existing domains, but save as much old zones content, as possible - this is your bisiness-task.

Order service from GoDaddy Premium DNS
Create empty zones for all your domains, which NSes you want to transfer
Edit original zones on  your named and decrease TTL to minimim (1h is OK)
While your new data for zones replacing old cached, copy-paste stable part of zones to GoDaddy (most IN A, CNAME, TXT RR): NS and SOA only will be new on new place
When you'll see working and propagaded and correct zones on GoDaddy and requests to your zones will return fresh-data (according to p.3) you have to go registrar, which registered domains for you and replace glue-records for domains (data, which tells everybody where authoritative-servers for domain located) with new names (GoDaddy's)
Wait for TTL-expiration (ask registar how long) and have fun
Comment: thank for you answer, I was referring to Private Nameserver as to  Vanity Nameservers, both terms are alias for A records for nameservers. Actually my business task was to "keep all NS-servers on my existing domains and change DNS hosting (server handling my zone files)". Thanks for the help anyway.
Comment: In common case, you **can't** "keep all NSes AND change DNS-hosting", because changing authoritative NS **must change** IN NS and SOA records of every moved zone
Comment: your are right, that stuff was updated in zones files when I uploaded them from BIND to Premium DNS. It was not upload and done experience, had to do some customization. It was not that bad because all domain had my Vanity Nameservers, I changed IP there to point to Premium DNS host and had my updated zones there...

Premium DNS, Zones & VPS (nightmare...)


Dirac delta and non-test functions

Question: Normalization of the delta function (distribution) is often informally written as an integral
$$\int_{-\infty}^{+\infty} \delta(x) \, dx = 1$$
An attempt to write this formally would be expression like $\delta[1] = 1$. However, the constant function $f(x) = 1$ has no compact support, therefore it is not a test function. Is there a precise way to translate such integral expression into the language of distributions?
Also, a related problem occurs with expressions like $\delta[\chi_{[a,b]}]$, where $\chi_{[a,b]}$ is a characteristic function over $[a,b] \subset \mathbb{R}$ (defined such that $\chi_{[a,b]}(x) = 1$ for $x \in [a,b]$ and $\chi_{[a,b]}(x) = 0$ for $x \notin [a,b]$). Informally, this would correspond to the integral
$$\int_a^b \delta(x) \, dx$$
and, intuitively, one would like to get result $1$ for $0 \in [a,b]$ and $0$ otherwise. However, $\chi_{[a,b]}$ is not a test function (since it has discontinuities at $a$ and $b$), so we again have a formal problem as the one mentioned above.
Comment: Well Dirac delta is not a function so you cannot use it in these ways. $\delta[\phi] = \phi(0)$, stop! Obviously if $\phi(0) = 1$ you get $1$. That "normalization property" isn't correct, and does not enter in distribution theory. Distributions eat test functions, not meat or vegetables, test functions. If you feed your delta with weird things you break up the theory. For the second question you could use mollifiers to smoothly approximate the function
Comment: @Emar  I absolutely agree with you, distributions are strictly test functions vegans! The potential issue raises because such integral expressions are widely used in physics, so I would just like to make more sense out of them.
Answer: Suppose $d$ is a distribution with compact support $S$ and $f$ is a smooth function, not necessarily with compact support. Define a smooth, compactly supported cutoff function $k$ such that $k=1$ on a neighborhood of $S$. Then $\langle d,kf \rangle$ makes proper sense. One can prove that the value of this expression does not depend on $k$, under the preceding assumptions. So this defines a meaningful extension of $d$ to all of $C^\infty$. Now that we know the key idea is that of a compactly supported distribution, a quick google search finds a proof: http://www.math.chalmers.se/~hasse/distributioner_eng.pdf page 31.
Now the Dirac delta has support $\{ 0 \}$, so this applies to it.
The principle is the same if you want to apply $d$ to a function like $\chi_{[a,b]}$ which is smooth on a neighborhood of the support of $d$ but not globally smooth: use a smooth cutoff which keeps the function the same on a neighborhood of the support of $d$ but such that the result is globally smooth. So this procedure works for $\delta[\chi_{[a,b]}]$ provided $a,b \neq 0$.
Comment: Since $\delta$ is of order $0$, you can even let it act on functions that are merely *continuous*, not necessarily smooth.
Comment: Thank you Ian, your comments are very useful!
Answer: You can see the Dirac not only as a distribution, but also as an element of the dual of continuous functions : a Radon measure.
This point of view gives sense to $\delta[1]$.
And if a measure $\mu$ is absolutely continuous in respect to the Lebesgue measure,
$$\mu( \phi ) = \int_{\mathbb{R}} \phi(x) d\mu(x) = \int_{\mathbb{R}} \phi(x) \mu(x) dx$$
(the first equality is Riesz representation theorem)
This gives, by abuse of notation (as $\delta$ is not absolutely continuous in respect to the Lebesgue measure)
$$\delta( 1 ) = \int_{\mathbb{R}} 1 d\delta(x) = \int_{\mathbb{R}} \delta(x) dx$$
For $\chi_{[a,b]}$, I'm not sure what could be the correct point of view.
Comment: I see what you were going for now. I honestly didn't understand where you were going with your previous version.
Comment: It was not clear, yes, but as $\int_{\mathbb{R}} \delta(x) dx$ is an abuse of notation, it was natural for me to consider the abuse of notation in the case where $\mu$ is not absolutely continuous in respect to the Lebesgue measure. But it's better when said explicitely ;)

Dirac delta and non-test functions


Parameters of a Statistical Distribution

Question: Any statistical distribution is described in terms of shape, scale and location parameters. But what do these parameters mean, geometrically, statistically and for a layman with minimum statistical knowledge?
I have explored wikipedia and still, this doubt continues to exist.
Answer: Some technicalities to complement @vinux's answer:
If you have a density $f_X(\cdot)$ for a random variable $X$ where
$$f_X\left(x;\theta,\phi;\vec\xi\right)=\tfrac{1}{\phi}f_X\left(\frac{x-\theta}{\phi};0,1;\vec\xi\right)$$
then $\theta$, $\phi$, & $\vec\xi$ are location, scale, & shape parameters respectively.
Location parameters only shift the density, changing its mean (if it has one) & other measures of central tendency, but no higher moments.
Scale parameters only stretch the density, changing its variance (if it has one) & other measures of dispersion, & the mean when $\newcommand{\ex}{\operatorname{E}}\ex X\neq\theta$, but no higher moments.
Shape parameters change the shape of the density, perhaps stretching or shifting too, so may change any moments. They tend to get called 'shape' parameters only in contrast to location & scale parameters; e.g. the Weibull distribution has scale & shape parameters but no-one talks about the shape parameter of the Poisson distribution (though they do about the two shape parameters of the beta distribution).
It's perhaps worth emphasizing @Nick's point that a parameter's being equal to the expectation of the random variable  doesn't imply that it's a location parameter: $$\psi=\ex{X} \quad \not\Rightarrow \quad f_X\left(x;\psi\right)=f_X\left(x-\psi;0\right)$$
Answer: The names of the parameters are suggestive. Location, and scale parameters are associated with central tendency, dispersion respectively. For eg: If you change location parameters, mostly it change only the central tendency measures.
Try this online tool. Distributions
See how the distribution changes for different values of parameters. You could try this with generalized extreme value distribution.
Not all standard distributions have all three parameters. Some distributions have only one or two of the parameters (eg: gamma distribution-shape and scale parameters)
Comment: I guess that mathematical statisticians have invariance and equivariance criteria for different kinds of parameter. I am reacting to @Vinux's line that location indicates central tendency and the idea that location and central tendency are the same ballpark. That's probably loose at best by mathematical standards, but it's a data analytic view.
Comment: Thanks for clearing the geometric way of explaining the doubts. I wish to have clarity on the statistical idea. A standard reference with a detailed explanation would be of great help. A confusion regarding the scale and the shape exists though !
Comment: Shape is associated not just with skew, but with anything that isn't to do with central tendency or dispersion; a shape parameter might well affect higher moments. It's any parameter that isn't a location or scale parameter. And cross out 'mostly' in the second sentence unless you can think of an exception.
Comment: @Scortchi Agreed on "shape". Vinux: A simple example is the Poisson. Change the mean and you change variance, skewness, kurtosis, ... It is not clear whether you regard such linked changes as usual or exceptional.
Comment: @Nick: But would you call the mean of the Poisson  a location parameter? I wouldn't. Same goes for the mean of the exponential distribution - it's a scale parameter.
Comment: Would it be right to say that for a location parameter $\theta$ the density $f(x;\theta)=f(x-\theta;0)$ and changing it only changes the mean; while for a scale parameter $\phi$ the density $f(x;\phi)=\frac{f(\frac{x}{\phi};1)}{\phi}$ and changing it only changes the variance & perhaps the mean?
Comment: I think the question is very broad. I am not sure about  any standard definition for shape in distribution context. I was trying to give a layman's picture.
Comment: Fair enough - but 'skewness' is even less a layman's term than 'shape'. Location parameters *shift*, scale parameters *stretch*, and shape parameters change the *shape*.
Comment: @Scortchi You are right. I should not associate shape with skewness. I will edit my answer.
Comment: @Scortchi The lay use of "skewed" is increasingly as meaning "biased", as in "the results are skewed by including too many people of type X". It may have been around for some time, but I've noticed it more recently. I haven't noticed "skewness" as a synonym for "bias".


PHP Associative Array To Table

Question: I am trying to sort an associative array in ascending in order and then  transfer it to a HTML table and I am currently stumped at an error. I looked for guidelines here on SO and followed instructions on some posts:
PHP display associative array in HTML table
But still no luck, here is my attempt:
<?php
         function format($g){

          array_multisort($g, SORT_ASC);
          echo "
";
          foreach($g as $key=>$row) {
              echo "
";
              foreach($row as $key2=>$row2){
                  echo "" . $row2 . "	";
              }
              echo "
";
          }
          echo "
";
         }
         $bib = array("Luke"=>"10",
                      "John"=>"30",
                      "Matt"=>"20",
                      "Mark"=>"40");
         format($bib);
       ?>

My debugger is telling me there is an error at my for each loop but I don't see how it is wrong unless there is some syntax error that I am not seeing? The error is saying Invalid argument supplied for foreach()
Comment: Your array is not multi dimensional, so there is no need for the second foreach-loop. What output structure are you expecting? (I.e. what columns and rows should it produce?)
Comment: You're trying to go too deep. The array only has 1 set of key/value pairs. Your second foreach fails because there's nothing to iterate through.
Comment: you have to check whether $row is an array
Comment: Use a recursive function or is_array check
Answer: Because your $bib is only single array but you use two foreach to loop this array
At 2nd loop, your $row variable is a string, you can't use foreach for this type
Can you try that for single array ?
<?php
function format($data) {
    array_multisort($data, SORT_ASC);
    echo "
";
    foreach($data as $k => $v) {
        echo "
";
        echo "$k	";
        echo "$v	";
        echo "
";
    }
    echo "
";
}

$bib = array("Luke"=>"10",
             "John"=>"30",
             "Matt"=>"20",
             "Mark"=>"40");
format($bib);

?>

$k is Luke John Matt and Mark,
$v is 10 30 20 and 40
You can see the foreach example here: http://php.net/manual/en/control-structures.foreach.php
Hope this helpful ^^
Comment: this works, but you have a syntax error or 2, thanks for your help
Comment: You are missing a " in your answer, other than that it's useful because it explains the problem. It should be the accepted answer.
Comment: Why use `_multisort()` on a solitary array???
Answer: You can try this
<?php

function format($data){
    array_multisort($data, SORT_ASC);
    echo "
";
    foreach($data as $key => $row) {
        echo "
";
            echo "" . $key . "	";
            echo "" . $row . "	";
        echo "
";
    }
    echo "
";
}

$bib = array(
    "Luke"=>"10",
    "John"=>"30",
    "Matt"=>"20",
    "Mark"=>"40"
);

format($bib);

?>

Comment: I display one item per loop, One td for key and one td value.

PHP Associative Array To Table


Como fazer um alerta no browser, usando node.js

Question: Sou iniciante em node.js, sei que a função principal do node não é essa, porém quero aprender um pouco mais sobre tal evento, outra duvida que também tenho é se posso usar funções javascript comuns no "meio" do meu código node.
Gostaria de uma maneira de adicionar o meu javascript sem a função fs.readFile()
Obrigado pela atenção!
Answer: Se você usar o ajax você pode fazer assim:
No lado servidor
<code> res.send(500,'Errooooou')
</code>
e no lado cliente
<code>error: function(error){
      if(error.responseText == 'Errooooou')
          alert("Sua resposta está errada.")
</code>


Apache SOLR indexing stop working

Question: solr indexing has suddenly stop working.
Here is all the detail which i got from system admin
while running cron we are getting message during run cron.php through command
PHP Notice:  Undefined index:  REMOTE_ADDR in /var/www/XXXXXXX/includes/bootstrap.inc on line 1670
PHP Fatal error:  Exception thrown without a stack frame in Unknown on line 0
where should i look first and what are the possibility for apache solr indexing to stop suddenly.
Answer: The not to good solution was, deleted all the index of apache solr and tried with the fresh indexing and all of sudden all thing work well.
Comment: I think this is actually a good solution, sure could be better especially if you have to reindex a lot of items. But this would be an easy to try and fix for getting the production site back online. I think most in most cases the indexing stopped working the index got corrupted. reindexing would then be the best option. +1

Apache SOLR indexing stop working


How to ser GEM_PATH for www-data user Ubuntu/Debian

Question: I have mod_rails and Ruby Enterprise edition. I have an error the the process spawner cannot find the fastthread gem. The problem is that the gem is installed by passenger is looking into the gem directory of the standard MRI version. I should set the GEM_PATH the same as my user. Since www-data is a special user, without any home directory and profile, how can I set that environment variable?
There should be a way to pass enviroment variable to the Apache user.
Answer: are you sure your mod_rails is using REE and not MRI ? Check your PassengerRuby setting in apache.
usually you shouldn't have to pass any GEM_PATH since each ruby binary knows where its gems are installed. so what you might need to do is to install your gems in the proper location. your REE should have installed its own version of gem (I think it should be called gemee, or gem-ee or smth like that) so use it to see which gems are intsalled in REE environment.
Comment: I thing you are right, probably Passenger is using MRI. How and where I should set up PassengerRuby? I tried inside the  directive but I get an error. Thanks
Comment: How to set up PassengerRuby; http://serverfault.com/questions/60222/apache-dispatch-fcgi-doesnt-get-interpreted-with-passenger
Comment: if you followed the passenger install you should already have
PassengerRuby in a conf file under /etc/apache, just grep for it:
`grep -nsri PassengerRuby /etc/apache*`

it can't be set for a directory, it should be set globally.
Comment: on my ubuntu setup passenger config is in 2 files: /etc/apache2/mods-available/passenger.load and /etc/apache2/mods-available/passenger.conf


Access host's wireguard from Docker containers

Question: I have a Debian server that has a Wireguard connection to a box sitting behind a NAT. The box has Wireguard IP 192.168.60.2 whereas the server has Wireguard IP 192.168.60.1. On the server, a few Docker containers are running. I would like to be able to assign some containers an IP on the 192.168.60.0/24 subnet so that I can tell the containers apart by IP on the box as requests from the contains come in.
When I launch containers without special network config, i.e. using the standard bridge driver, I can reach the box via its IP 192.168.60.2, however, the originating IP is the server's (192.168.60.1).
I tried using Docker's IPVLAN network driver, but that requires an actual Ethernet interface as opposed to a tunnel.
How can I achieve this?

edit: After creating a Docker network with docker network create --driver=bridge --subnet=192.168.60.0/24 my-net and starting a dummy container with docker run -it --rm --network=my-net --ip=192.168.60.10 alpine, I still cannot get this to work.
The Wireguard settings on the server are like so:
[Interface]
PrivateKey = *** REDACTED ***
ListenPort = 51821
Address = 192.168.60.1/24
[Peer]
PublicKey = *** REDACTED ***
AllowedIPs = 192.168.60.2/32 # I also tried setting this to /24

In the box's Wireguard settings the Address is set to 192.168.60.2/32 and AllowedIPs is set to 192.168.60.0/24.
I checked the firewall counters and I don't think this is what's stopping the packets. However, when looking at the routing table, this seems suspicious:
192.168.60.0/24 dev wg1 proto kernel scope link src 192.168.60.1
192.168.60.0/24 dev br-df2fc584e6b0 proto kernel scope link src 192.168.60.1

wg1 is the Wireguard interface and br-df2fc584e6b0 corresponds to the Docker bridge my-net. More details:
$ ip a show dev br-df2fc584e6b0
184: br-df2fc584e6b0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 02:42:98:27:08:23 brd ff:ff:ff:ff:ff:ff
    inet 192.168.60.1/24 brd 192.168.60.255 scope global br-df2fc584e6b0
       valid_lft forever preferred_lft forever
    inet6 fe80::42:98ff:fe27:823/64 scope link
       valid_lft forever preferred_lft forever

$ ip a show dev wg1
177: wg1: <POINTOPOINT,NOARP,UP,LOWER_UP> mtu 1420 qdisc noqueue state UNKNOWN group default qlen 1000
    link/none
    inet 192.168.60.1/24 scope global wg1
       valid_lft forever preferred_lft forever

edit2: I was able to resolve this by making the IP subnets non-overlapping, i.e. the Wireguard interface has the address 192.168.60.1/28 and the bridge network is assigned the subnet 192.168.60.16/28. Additionally, I created the bridge network with com.docker.network.bridge.enable_ip_masquerade=false to keep the original IP.
Answer: you can create a custom bridge network in Docker and then connect your containers to this network.
1.
docker network create --driver=bridge --subnet=192.168.60.0/24 mynetwork

docker run --network=mynetwork --ip=192.168.60.x -d your_container_image

Ensure that your WireGuard setup allows traffic from the Docker bridge network. Update your WireGuard configuration to allow traffic from the Docker bridge subnet (192.168.60.0/24). Update the
AllowedIPs both on WireGuard client and server side and make sure to restart WireGuard after that.
Comment: Thanks for the suggestion. I tried it, but I'm not having success yet, see my edit above.


Can I use Bray-Curtis distance when performing MRPP or MRBP?

Question: Can I use Bray-Curtis distance when performing MRPP (Multi-response Permutation Procedures) or MRBP (Blocked Multi-response Permutation Procedures)?
[See Ch 24 of McCune & Grace (2002) for explanation of MRPP & MRBP].
Typically, according to McCune & Grace and the literature they cite, Euclidean, Squared Euclidean and Sorensen distance are most often used for these procedures. My question is whether Bray-Curtis Distance would also be appropriate?
Answer: You can use non-euclidean distances such as Bray-Curtis if you use Pseudo-F as your test statistic (see Reiss et al 2010, Biometrics, Vol. 66 (2), pp. 636-643).
"the pseudo-F statistic is a generalization of the classical F statistic that can be calculated directly from the distance matrix D, whether or not D is Euclidean."
The authors of the vegan package in R recommend using the function "adonis", which uses a permutation test with pseudo-F ratios, rather than mrpp. You might want to look into using adonis instead.


dynamically create new columns using withColumn function from a list in PySpark

Question: I am trying to figure out how to dynamically create columns for each item in list(cp_codeset list in this case) by using withColumn() function and calling udf in the withColumn() function in the pySpark. Below is the code that I wrote but it is giving me an error.
from pyspark.sql.functions import udf, col, lit
from pyspark.sql import Row
from pyspark.sql.types import IntegerType

codeset = set(cp_codeset['CODE'])

for col_name in cp_codeset.col_names.unique():
    def flag(d):
        if (d in codeset):
            name = cp_codeset[cp_codeset['CODES']==d].col_names
            if(name==col_name):
                return 1
            else:
                return 0

    cpf_udf = udf(flag, IntegerType())

    p.withColumn(col_name, cpf_udf(p.codes)).show()

The other option is to manually do it but in that case I have to write same udf function and call it with withColumn() function 75 times (which is the size of cp_codeset["col_names"])
Below is my two dataframes and I am trying to get how result appears
    P (This is Pyspark dataframe and this dataframe is too large for pandas to handle)
id|codes
1|100
2|102
3|104

    cp_codeset (pandas dataframe)
codes| col_names
100|a
101|b
102|c
103|d
104|e
105|f

    result (pyspark dataframe)
id|codes|a|c|e
1|100   |1|0|0
2|102   |0|1|0
3|104   |0|0|1

Comment: Possible duplicate of [E-num / get Dummies in pyspark](http://stackoverflow.com/questions/42805663/e-num-get-dummies-in-pyspark)
Comment: Is [that](https://spark.apache.org/docs/latest/ml-features.html#onehotencoder) what you want? BTW why did you set `[pandas]` tag if you need a PySpark solution? It's confusing...
Comment: @MaxU Sorry for confusion.I only have cp_codeset as a Panda dataframe and have P as a pyspark dataframe. I want result in pyspark dataframe. Thank you.
Comment: @Viraj, in this case you have two answers from [piRSquared](http://stackoverflow.com/a/43053959/5741205) and from [Boud](http://stackoverflow.com/a/43053207/5741205) - it should be pretty straightforward to generate Spark DataFrame from Pandas DF...
Answer: With this data filtered:
cp_codeset.set_index('codes').loc[p.codes]
Out[44]:
      col_names
codes
100           a
102           c
104           e

Simply use get_dummies:
pd.get_dummies(cp_codeset.set_index('codes').loc[p.codes])
Out[45]:
       col_names_a  col_names_c  col_names_e
codes
100              1            0            0
102              0            1            0
104              0            0            1

Answer: I'd use get_dummies with join + map
m = cp_codeset.set_index('codes').col_names

P.join(pd.get_dummies(P.codes.map(m)))

   id  codes  a  c  e
0   1    100  1  0  0
1   2    102  0  1  0
2   3    104  0  0  1

Comment: This gives error of "TypeError: 'Column' object is not callable". If I write P.select("codes").map(m) then it gives "AttributeError: 'DataFrame' object has no attribute '_jdf'"
Comment: @Viraj why are you writing `P.select`?  That is no where in my code.


Several questions about Riesz–Markov–Kakutani representation theorem

Question: This is a list of questions about Riesz–Markov–Kakutani representation theorem
.
1)If $f\in L^1(\mu)$, is it true that $\phi(f)=\int_Xfd\mu$, where $\mu$ is given by the theorem?
I am quite sure it is correct, since $C_c(X)$ is dense in $L^1(\mu)$. And we can extract a subsequence that pointwise converges to $f$.
2)If $X$ is not locally compact, does the theorem still stands? If not, does there exist a non-regular measure such that $\phi(f)=\int_Xfd\mu$?
The property of locally compact is a must to use Urysohn lemma in the proof. The reason why Urysohn lemma (or partition unity) is widely used is because the way we construct the measure. So I am thinking if we can construct the same measure in another way that we can avoid Urysohn lemma.
3) If $X$ is not Hausdorff, what will happen as stated in 2)?
4)If $X$ is normal and not locally compact?
Comment: I don't understand what you mean with (1).  $\phi$ is defined as a linear functional on $C_c(X)$; a priori, $\phi(f)$ has no meaning for $f \in L^1(\mu) \setminus C_c(X)$.
Answer: Well, as a start, if you drop local compactness, you lose uniqueness.
Suppose $X$ is Hausdorff and not locally compact.  Then there exists a point $x \in X$ such that no open neighborhood of $U$ is contained in a compact set.  Now if $f \in C_c(X)$ and $f(y) \ne 0$, then the set $U = f^{-1}(\mathbb{R} \setminus \{0\})$ is an open neighborhood of $y$ which is contained in the support of $f$, which by assumption is compact.  As such, we must have $f(x)=0$ for every $f \in C_c(X)$.  Thus if we take $\phi=0$ to be the zero functional, $\mu=0$ the zero measure, and $\nu = \delta_x$ a point mass at $x$, we have for every $f \in C_c(X)$ that $\phi(f) = \int f\,d\mu = \int f\,d\nu$.
For instance, if you take $X = \mathbb{Q}$, then every compact set has empty interior, so no point has an open neighborhood which is contained in a compact set.  Hence $C_c(\mathbb{Q})$ consists only of 0.  There are lots of Borel measures on $\mathbb{Q}$, but there is only one linear functional on $C_c(\mathbb{Q})$ (the zero functional), and it's induced by every measure.
Note that $\mathbb{Q}$ is metrizable, hence normal, and every measure on $\mathbb{Q}$ is regular.  So that part is not the issue.
A similar example is to take $X$ to be an infinite-dimensional Banach space.  Again we get $C_c(X) = 0$ by Riesz's lemma.
You can also lose uniqueness if you drop Hausdorff.  Suppose $X$ is the line with two origins, call them $0$ and $0'$.  It's easy to show that for every continuous $f : X \to \mathbb{R}$ we have $f(0) = f(0')$, and moreover the sets $\{0\}$ and $\{0'\}$ are Borel.  So the point masses $\delta_0$ and $\delta_{0'}$ are two different measures which induce the same linear functional on $C_c(X)$.
I am not sure what happens to existence in either case.
Answer: For your first question, $C_c(X)$ is a subspace of $L^1(\mu)$, and $\phi$ is dominated by the $L^1(\mu)$ norm on $C_c(X)$. By the Hahn-Banach theorems, $\phi$ extends to some continuous linear functional $\Lambda$ on $L^1(\mu)$. For any $f\in L^1(\mu)$, we can find a sequence $\{f_n\}$ in $C_c(X)$ such that $\|f_n-f\|_1 \rightarrow 0$ as $n\rightarrow \infty$. By continuity of $\Lambda$,
$$
\Lambda f = \lim_{n\rightarrow \infty} \int_Xf_nd\mu.
$$
Also,
$$
\lim_{n\rightarrow \infty} \bigg|\int_X(f_n-f)d\mu\bigg| \leq \lim_{n\rightarrow \infty} \int_X|f_n-f|d\mu = 0
$$
implies
$$
\int_Xfd\mu = \lim_{n\rightarrow \infty} \int_{X}f_nd\mu,
$$
hence
$$
\Lambda f = \int_Xfd\mu.
$$
This in fact shows that $\Lambda$ is the unique continuous extension of $\phi$ to $L^1(\mu)$. In other words, $C_c(X)$ and $L^1(\mu)$ have the same dual space.
Note that we never used pointwise convergence, nor do we need it. A direct application of Fatou's lemma, however, does show that $f_n(x)\rightarrow f(x)$ as $n\rightarrow \infty$ for a.e. $x \in X$.
Comment: I don't think u can use Hann-Banach theorem, since the functional may not be continuous. That's why Riesz represent ion theorem is quite strong
Comment: @89085731 The extension theorems do not refer to any topology. The very reason we dominate the extensions by seminorms is to ensure that, given a topology, we can find bounded(hence continuous) extensions.


How can I backup an SQL Server database using Windows Server Backup?

Question: Apparently Windows Server Backup has some support for backup of SQL Server databases:

Ability to recover applications. Windows Server Backup uses VSS functionality that is built into applications like Microsoft® SQL Server® to protect application data. [Source: TechNet]

In addition, people report that Windows Server Backup seems to trigger some sort of backup operation in SQL Server.
However, I fail to find (official) documentation on how exactly to backup SQL Server databases using Windows Server Backup.

Do I just need to backup the .mdf? The .mdf and the .ldf?
Online or just offline?
What's the official procedure for restoring SQL Server databases backed up this way?
Is there anything special to consider when doing incremental/differential backups?
Where is all of this documented?

(I know how to do backups with SQL Server Maintenance Plans, sqlmaint.exe, T-SQL BACKUP and SQL Server Agent. I'm just interested in the alternative that Windows Server Backup (apparently?) offers.)
Comment: I have a Windows Server 2008 that is doing a full backup. As far as I can tell it is pulling the databases from SQL Server Express as part of its full backup, since each database says that it was last backed up at the time that that backup runs. This has confused me, since I'm trying to figure out how I've managed to backup these databases, since I can't find a script that's doing it anywhere. I think I will write a script to do it anyway, so that I know it's working and know exactly what I have.
Comment: What version of Windows Server, and what version of SQL server?
Comment: @pauska: Personally, I'd be interested in Windows Server 2012 R2 and SQL Server 2012. (I deliberately keep the question more general to make it more useful to others.)
Answer: Windows Server Backup is not intended as a backup tool for SQL Server.

...However, the design makes it especially well-suited for smaller organizations or individuals who are not IT professionals...

Quote from Windows Server Backup Step-by-Step Guide for Windows Server 2008 section: "Who should use Windows Server Backup?"
The section you quoted is basically saying, that when Windows Server Backup kicks in, it will trigger the VSS feature in Windows. SQL Server will be aware that a Volume Shadow Copy is occurring and with the aid of SQL Server Writer service, will ensure that a copy of the database files (*.mdf, *.ndf, *.ldf) can be performed.
The purpose of the SQL Server Writer service is defined as follows:

When running, Database Engine locks and has exclusive access to the data files. When the SQL Writer Service is not running, backup programs running in Windows do not have access to the data files, and backups must be performed using SQL Server backup.
Use the SQL Writer Service to permit Windows backup programs to copy SQL Server data files while SQL Server is running.

Quote from SQL Writer Service section: "Purpose"
So that is basically all that happens with the Windows Server Backup.
The backups created with Windows Server Backup while SQL Server is running should be consistent, but the transactions not yet written to disk are not in the Volume Shadow Copy. The database snapshot was taken while being ONLINE.
However the MSDN article Snapshot Backups states:

Only the following types of backups can be snapshot backups:

Full backups
Partial backups
File backups
Differential database backups. These are supported only when the vendor uses the VSS interface.

and additionally:

Except as noted earlier in this topic, snapshot backups are functionally equivalent to the corresponding conventional backups. You can use snapshot backups in restore sequences with non-snapshot full backups, differential backups, and log backups. Like other backups, snapshot backups are tracked in the msdb database, where snapshot backups are identified by backupset.is_snapshot = 1. For more information about msdb, see msdb Database.
SQL Server does not support online restore from a snapshot backup. Restoring a snapshot backup automatically takes the database offline. A piecemeal restore can incorporate snapshot backups, but all the restore sequences are offline restores. For more information about piecemeal restores, see Performing Piecemeal Restores.

To answer your questions:

Do I just need to backup the .mdf? The .mdf and the .ldf?
Online or just offline?
What's the official procedure for restoring SQL Server databases backed up this way?
Is there anything special to consider when doing incremental/differential backups?
Where is all of this documented?

Answers:

Yes, you can do a Windows Server Backup (VSS) copy of the .mdf and .ldf files. The backup should be consistent, but the database will be OFFLINE after a restore.
If SQL Server is stopped / database is detached / database is OFFLINE then a VSS copy of the .mdf and .ldf files is 100% consistent.
I'm unsure of how to restore a database (to a point-in-time) that is conducted with Windows Server Backup, because the database is restored in an OFFLINE state. A database in the OFFLINE state can not be restored/recovered any further and bringing the database ONLINE results in a database being considered fully recovered. I would recommend separate SQL Server FULL, DIFF and TLOG Backups to ensure you can perform a database restore to a point-in-time.
Transaction Logs are not part of the snapshots created with Window Server Backup and should be performed additionally. Differential snapshots are supported by 3rd party vendors as part of the backup sequence, but Windows Server Backup does not seem to be able to perform differential backups. In this case you would also have to perform additional differential backups. (see 3.)
Different References

Understanding SQL Server Log Sequence Numbers for Backups
Log Sequence Numbers and Restore Planning
How do I map a differential/transaction log backup to its full backup without using MSDB?
Introduction to Log Sequence Numbers
Snapshot Backups
SQL Writer
Introduction to Backup and Restore Strategies in SQL Server
Restore and Recovery Overview (SQL Server)

Explained in real-life implementation
In our environment we have a similar situation where VMware is conducting a snapshot and the DBA's are conducting SQL Server dumps with Commvault. The backup history looks like this:
DBNAME  TYPE BACKUPSET_NAME            IS_SNAPSHOT BACKUP_START_DATE
------- ---- ------------------------- ----------- -----------------------
DB_NAME  Full  NULL                    1           2016-12-10 18:23:59.000
DB_NAME  Full  CommVault Galaxy Backup 0           2016-12-10 20:07:41.000
DB_NAME  Log   CommVault Galaxy Backup 0           2016-12-11 06:00:40.000
DB_NAME  Full  NULL                    1           2016-12-11 18:24:00.000
DB_NAME  Diff  CommVault Galaxy Backup 0           2016-12-11 20:03:38.000
DB_NAME  Log   CommVault Galaxy Backup 0           2016-12-12 06:02:29.000
DB_NAME  Log   CommVault Galaxy Backup 0           2016-12-12 07:02:17.000

The VMware snapshot will create an entry in the MSDB database history tables with IS_SNAPSHOT = 1 and FULL for each VMware snapshot that is conducted (daily). The  native (well Commvault using native) SQL Server backups are conducted using FULL, DIFF and TLOG backups. These backups are not marked as IS_SNAPSHOT and exist as additional FULL (once a week), DIFF (every other day) and LOG (hourly) entries in the backup tables in the msdb database.
With this setup, we can perform either a restore to the snaphot date-time and then bring the database ONLINE, or we can perform an individual restore to any point-in-time using the "native" SQL Server backups.
Answer: You can't. Or at least you probably shouldn't. As far as SQL Server databases are concerned native backups are the supported method.
I think you may be misunderstanding what the TechNet article is saying. The comment you quoted doesn't indicate that you can use Windows Server backup for SQL Server databases. It is actually just highlighting that Windows Server backup utilizes the same Volume Shadow Copy Service that is used by SQL Server. More info: TechNet: SQL Writer Service
Comment: Apparently, Windows Server Backup *does* trigger some kind of SQL server backup, see [this quesiton](http://dba.stackexchange.com/q/39865/5273).
Comment: I know that I shouldn't -- I wouldn't entrust my data on such a poorly documented feature. Still, I'm curious if it is possible, theoretically: SQL Server *does* provide a VSS writer, and Windows Server Backup *is* a VSS requestor, so I'll leave the question open for now. Maybe it's just a question of matching those two up (there are, for example, instructions online on [how to do this for the Hyper-V VSS writer](http://www.petri.co.il/register-volume-shadow-copy-service.htm)).
Answer: Sql backup not just copy data, it truncate the log also.
You can find hundreds options in the man page thats will help you, such of compressing the backup file on the fly.
I remember that vss backup was used for copying a freezed Virtual Machine or to snapshotting a lun on a SAN in order to backup a static image, but the backup will be "crash consistent" just like power interruption and not really consistent.
Related

ServerFault.com, 2010-09-18, SQL Server Backups using Volume Shadow Copy
ServerFault.com, 2015-07-20, Is it safe to back up SQL Server data directly if using VSS?
Answer: I think it uses a special backup type called "Snapshot Backup".
From the SQL Server 2008 documentation:

SQL Server snapshot backup is also used by Microsoft Windows Server 2003 Volume Shadow Copy Service (VSS) and by all the backup software and storage software that uses this framework. For more information, see SQL Writer Service.

It is all very unclear to me. Especially if this truncates transaction logs or not.


Verficar se número digitado realmente é inteiro no Visualg

Question: Eu não estou conseguindo colocar a lógica do  num % 1 = 0 que vi pela internet haha
Sou novo nesse mundo rs
Algoritmo "semnome"
// Data atual  : 06/10/2021
Var
num, a : inteiro
Inicio
leia (num)
a <- num % 1
se (a = 0) entao
escreva("número inteiro")
senao
escreval("erro / número real")
fimse
Fimalgoritmo
Answer: De acordo com o manual do visualg 3.0 a função Caracpnum() recebe um caractere e retorna o valor em inteiro ou em real.
Para mais informações segue o link do manual do visualG 3.0


SwiftUI ViewBuilder can't pass in different views

Question: In Swift/SwiftUI, I'm trying to make a custom view, which takes other views as arguments. However, I'm getting the error Type of expression is ambiguous without more context.
I know that this error is usually due to mismatching types. Also, in the implementation below, having 2 Text views causes no error, but using a Text view as well as an Image view causes an error.
This makes me believe that the error is due to the fact that Image and Text are technically different types. However, since they both conform to View, and because my CustomView has both parameters of type View, I don't understand why this issue is happening.
struct CustomView<Content: View>: View {
    @ViewBuilder var label: Content
    @ViewBuilder var content: Content

    var body: some View {
        VStack {
            self.label

            self.content
        }
    }
}

struct ContentView: View {
    var body: some View {
        CustomView {             //<-- ERROR: Type of expression is ambiguous without more context
            Image(systemName: "person.3.fill")
        } content: {
            Text("")
        }
    }
}

What am I doing wrong, and how can I fix this error? Thanks in advance!
Answer: The problem with your code is that in CustomView you defined both label and content as views of a single type (generic Content), but you pass different kinds to the initializer.
One way to fix it is to define different types for label and content:
struct CustomView: View {
    @ViewBuilder let label: Label
    @ViewBuilder let content: Content

    // The rest is unchanged.


Probability of a medical symptom based on different causations

Question: I want to ask something about a common medical situation:

Suppose the probability of a medical symptom X (let's say blue tongue:-) ), to occur in a person at a specific time moment is 1/1000. Pretty rare.
Suppose also the probability of a disease A to occur in a person at a specific time moment is 1/200. Not that rare.
We know also that disease A causes the symptom X in 1/10 cases.
Suppose also the probability of another disease B to occur in a person at a specific time moment is 1/2000. Somewhat rare.
We know also that disease B causes the symptom X in 1/40 cases.

Obviously the probability of:
 - Someone getting the symptom X is 1/1000.
 - Someone getting the symptom X because of disease A is (1/200)(1/10) = 1/2000
 - Someone getting the symptom X because of disease B is (1/2000)(1/40) = 1/80000
Now suppose that someone is diagnosed with the disease B AND then develops the symptom X. We also don't know anything about whether he has or not the disease A or any other disease that can cause symptom X. We just know he has disease B and the symptom X.
My question is what is the probability the symptom X has occurred because of disease B?  Is it 1/40 or something much higher?
Because any doctor for example would say that this can't be a coincidence (that this person had this symptom X after he was diagnosed with disease B, that causes in some cases the symptom X) and that the symptom X was caused by disease B with very big probability, but I want to quantify this probability. How much is it?
For the general case, i.e with general numbers, with known $P(A)$, $P(B)$, $P(X)$, $P(X|A)$, $P(X|B)$, I want to find probability of X being caused by B and not A or anything else, knowing that X and B are true.
Are there any references books about these kind of problems?
Answer: The way I would look at this is as follows:
P(B caused X) = P(X given B) / sum of this and other ways to get X
P(B caused X) = P(X given B) / ( P(X given B) + P(X given A)P(A) )
P(B caused X) = 1/40 / ( 1/40 + 1/200 x 1/10 )
P(B caused X) = 50 / 51 or about 98% chance that B caused X not an undiagnosed A condition
Depending upon your assumptions, this could change a bit.  For example, if you believe that 1/1000 people get X (even with B) that is not caused by B.  That is, this small possibility is included in the 1/40.  If you go the other way the equation becomes:
P(B caused X) = P(X given B) / ( P(X given B) + P(X given A)P(A) + P(X not from A or B) )
P(B caused X) = 1/40 / ( 1/40 + 1/200 x 1/10 + 1/1000 )
P(B caused X) = 50 / 53 or about 94% chance that B caused X not an undiagnosed A condition or just among the whole population
Comment: << The way I would look at this is as follows:
P(B caused X) = P(X given B) / sum of this and other ways to get X >>

The problem with this is that:
a) I don't get the reason the following equality is true. How it is being derived logically?
b) Since we know someone is diagnosed with B and has the symptom X, then the probability of both is 1. I.e P(B)=P(X)=1
So for example P(X|B) is not 1/40 but 1.
Comment: Furthermore following another thinking procedure i come up with a different result:
Let's say that all the diseases that create the symptom X are B, A, A2, A3, ..., An. And the symptom X has probability 1/1000 to occur generally from any of these diseases.
P(B causes X) = 1 - P(B hasn't caused X) =
1 - P(X was not caused by B and was caused by A or A2 or A3 or... An) =
1 - P(X was not caused by B)·P(X was caused by A or A2 or A3 or... An) =
1 - (39/40)·(1/1000 - 1/80000)

Since P(X was caused by A or A2 or A3 or... An) is the probability of X to occur(1/1000) minus P(to occur from B).
Comment: Formatting in comments is terrible and i can't enter line breaks so sorry for this hideous formatting.
Comment: So one definition of probability is the number of simple events that support the event of interest divided by the total number of simple events.  Unless the simple events are not equally probable, in which case the numbers are simply scaled.

There are only so many ways to end up with X, so we take all these ways and sum their probabilities to get the denominator.  The numerator (simple events that satisfy or probability of them) is given in your assumptions - it's the odds of getting X from B *in general* not for the specific individual.


Deletar imagem do BD e da Pasta

Question: Estou tentando criar um script que exclua a imagem do banco de daos e da pasta, mas o problema é que só está excluindo do BD e não da pasta.
Tabela equipes
id, nome, foto

Aqui é o PHP que estou usando:
$id = $_GET["id"];
if($_SERVER["REQUEST_METHOD"] == "POST"){
    if(isset($_POST["deletar"])){
        $sqlDeletar = $pdo->prepare("DELETE FROM equipes WHERE id = :id");
        $sqlDeletar->bindValue(":id", $id);
        $sqlDeletar->execute();
        $dadosDeletar = $sqlDeletar->fetchObject();
        unlink("../upload/".$dadosDeletar->foto);
        echo "Aqui é o link de redirecionar.";
    }else{
        if(isset($_POST["nao"])){
            echo "Aqui é o link de redirecionar.";
        }
    }
}

E aqui o formulário:
<form action="" method="post" enctype="multipart/form-data">

        <input type="submit" name="deletar" value="Excluir">
        <input type="submit" name="nao" value="Não excluir">

</form>

Comment: Você precisa fazer um select antes de deletar um registro. Pois, depois que é excluído você não tem mais a opção "$dados->foto"
Answer: Faça uma verificação pra saber se o arquivo existe.
if (is_file("../upload/".$dadosDeletar->foto)) {/*excluir imagem*/}

Certifique-se de que $dadosDeletar->foto retorna o valor esperado e que você está passando o caminho correto para a pasta upload.
Comment: ta dando o msm error, será que não está habilitado alguma coisa no php.ini ?
Comment: Por favor, informe o erro na sua pergunta.
Comment: Ta dando esse error: General error in
Answer: Como o amigo disse ali nos comentários você precisa fazer um select na foto antes de remover do banco, mais ou menos assim.
$id = $_GET["id"];
if($_SERVER["REQUEST_METHOD"] == "POST"){
    if(isset($_POST["deletar"])){

        /* Primeiro você precisa saber o nome do arquivo */
        /* Selecione o mesmo no banco */
        $sqlSelect = $pdo->prepare("SELECT foto FROM equipes WHERE id = :id");
        $sqlSelect->bindValue(":id", $id);
        $sqlSelect->execute();
        $dadosSelect = $sqlSelect->fetchObject();

        /* É legal você verificar se o arquivo está lá na pasta */
        if (is_file("../upload/".$dadosSelect->foto)) {
            /* Remove o arquivo */
            unlink("../upload/".$dadosSelect->foto);
        }

        /* Aqui deleta o banco */
        $sqlDeletar = $pdo->prepare("DELETE FROM equipes WHERE id = :id");
        $sqlDeletar->bindValue(":id", $id);
        $sqlDeletar->execute();

        echo "Aqui é o link de redirecionar.";

    }else{

        if(isset($_POST["nao"])){
            echo "Aqui é o link de redirecionar.";
        }

    }
}

Meu forte não é PDO, mas acho que é essa a solução que precisa.
Answer: if(isset($_GET['delete'])){
$id_e = $_GET['delete'];
$sql = "select * from empresa where id_e = ".$id_e;
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
  $row = mysqli_fetch_assoc($result);
  $userPic = $row['logo'];
  unlink($upload_dir.$userPic);
  $sql = "delete from empresa where id_e=".$id_e;
  if(mysqli_query($conn, $sql)){
    header('location:produtos.php');
  }
}

}
( essa e a parte da imagem(logo) com o (id) na tabela empresa ... entendeu ,,vc precisa colocar a imagem e o id juntos ao deletar
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

Deletar imagem do BD e da Pasta


Mowing the lawn alone vs. together

Question: The question is: Nils mows the lawn in 3 hrs alone. Nils and Jonas mow the lawn together in 2 hrs. How quickly would Jonas mow the lawn alone?
My thinking: If Nils mows the lawn alone in 3 hrs, he mows 1/3 the lawn in 1 hr. If Nils and Jonas mow the lawn together in 2 hrs, they mow 1/2 the lawn in one hr., which means they each mow 1/4 of the lawn in one hr.
So, I would think that Jonas would take 4 hrs to mow the lawn alone, but the answer provided is 6 hrs.
What am I doing wrong?
Comment: As you said, Nils mows 1/3 of the lawn in 1 hour, and they together mow 1/2 the lawn in 1 hour. So Jonas mows $1/2-1/3=1/6$ of the lawn in 1 hour. Thus she takes 6 hours alone.
Comment: You know that Nils mows 1/3 of the lawn in one hour, not 1/4. So if Nils and Jonas mow 1/2 of the lawn between them in one hour, how much of the lawn has lazy Jonas mown?
Answer: This kind of problem is always confusing, and this is why the use of variables is really useful, even in everyday life.
Let's identify things that won't change with the number of people mowing the lawn simultaneously. The most obvious pick is what you identified : the fraction of the lawn that each one of them mow in 1 hour.
Let's call $x$ this value for Nils and $y$ for Jonas.
"Nils mows the lawn in 3 hrs alone" translates in $3x=1$. So $x = \frac13$ as you said.
"Nils and Jonas mow the lawn together in 2 hrs" translates in $2(x+y) = 1$. So $2x + 2y = 1$, and $y = \frac{1-2x}{2}$.
You know that $x = \frac13$ so $y = \frac{1-2x}{2} = \frac{1-2*\frac13}{2} = \frac16$.
We then know that Jonas mows $\frac16$ of the lawn in 1 hour, so he takes 6 hours to do the whole job alone.
Your mistake was in this sentence : "they mow 1/2 the lawn in one hr., which means they each mow 1/4 of the lawn in one hr", because you assume that Nils and Jonas take the same time to mow.
Addendum : You could also solve the problem with a less formal way. You know that in $2$ hours, Nils hae mowed $\frac23$ of the lawn, and that Nils and Jonas have finished the job at this time. This means that Jonas has mowed $\frac13$ of the lawn in this time. Thus, he is $2$ times slower than Nils. Hence the result.
Answer: You say:

...they mow 1/2 the lawn in one hr., which means they each mow 1/4 of the lawn in one hr.

but here, you're assuming that Nils and Jonas mow at the same speed. This is not necessarily true. Nils and Jonas do mow half the lawn in one hour, but remember that Nils has mowed a third of it and Jonas has done the rest. So Jonas has mowed $\frac{1}{2} - \frac{1}{3} = \frac{1}{6}$ of the lawn in one hour, implying that he will mow the entire lawn alone in $6$ hours.
Answer: If the lawn were 6 acres, apparently Nils mows 2 acres per hour, while Nils and Jonas together mow 3 acres per hour.  Hence Jonas mows one acre per hour.  So Jonas would require 6 hours to mow the lawn by himself.

Mowing the lawn alone vs. together