Qual a diferença e quando usar o Flexbox ou CSS Grid?

Question: Primeiramente tivemos o Flexbox como uma nova solução para a construçãod e layouts responsivos. Mais precisamente na parte de grids. Agora há pouco tempo surge o CSS Grid. Minha questão é: Qual a diferença dos 2 ? Quando devo usar 1 ao invés do outro ? Para a construção de grids para layouts responsivos, qual devo escolher ?
Obrigado
Answer: Se usa mais o GRID para toda a página (o  todo). Vai dividir a página completa em linhas e células (como se fosse uma grande planilha Excel). Esse GRID foi [inter-] invenção da Microsoft. Mas a maioria dos navegadores ainda não o aceitam, somente o EDGE da MS. :/
O FLEX (display:flex) é mais usado para centralizar ou posicionar
´s ou
´s que estão dentro de uma outra div mãe (contenedor). O FLEX é o mais usado hoje (que o GRID, que praticamente está em fase de teste). Mas, atenção: FLEXBOX é uma coisa, o FLEX do display:flex (CSS) é outra coisa. Espero que você me perguntou desse último, ainda que muitos chamam o FLEX de FLEXBOX, mas não é correto: FLEXBOX é um framework. FLEX são atributos do CSS puro.
Talvez o GRID só será algo para que voltemos ao passado dos tables... Não está sendo visto como boa alternativa pela maioria.
Aquí fiz um exemplo de FLEX para centralizar linhas e colunas, usando flex:.
https://codepen.io/colombe/pen/mPmNbb
Te recomendo que leia isso: https://css-tricks.com/snippets/css/a-guide-to-flexbox/.
Comment: Grid é [suportado](https://caniuse.com/css-grid) pela maioria dos navegadores hoje em dia.
Comment: pergunta: o flex do css não tem suporte pra todos os navegadores, mas o flexbox tem?
Comment: Sinceramente eu não sei pq esse frame nunca usei. Mas o FLEX parece que está mais aceito.. veja isso: http://i.stack.imgur.com/azmua.png
Comment: Obrigado pela resposta @Fiel. Sim, não estava falando do framework. Mas sobre a questão do nome, até mesmo a W3 o chamada assim 0 https://www.w3.org/TR/css-flexbox-1/.
Comment: O framework flexbox utiliza os atributos chamados flexbox pra fazer essa parte de responsividade.
Answer: Os propósitos de flexbox e Grid-layout são diferentes.
Flexbox:
O foco dele é organizar os itens em linhas ou colunas, mas seguindo o sistema de "blocos", ou seja o conteúdo será vários retângulos, um ao lado do outro, ou sobre o outro.
Grid-layout:
Como o nome diz, faz um grid (grade), e serve para organizar seus itens de forma mais sofisticada, onde cada um tem um comportamento independente, ocupa um número de linhas e colunas que você estipula.
Exemplo de layout que precisei fazer:

A versão mobile era totalmente diferente dessa, mas foi muito fácil de converter, pois, como eu disse, cada item se comporta independente, logo eu só mudei a posição de cada um deles e foi mais fácil do que usar qualquer "gambiarra".
Problema do Grid-layout é a compatibilidade com IE, funciona somente na versão 11 e não muito bem, então uso uma biblioteca mixin SASS que gera para mim.
grid-layout-IE11


Adding weights for highly skewed data sets in logistic regression

Question: I am using a standard version of logistic regression to fit my input variables to binary output variables.
However in my problem, the negative outputs (0s) far outnumber the positive outputs (1s). The ratio is 20:1. So when I train a classifier, it seems that even features that strongly suggest the possibility of a positive output still have very low (highly negative) values for their corresponding parameters. It seems to me that this happens because there are just too many negative examples pulling the parameters in their direction.
So I am wondering if I can add weights (say using 20 instead of 1) for the positive examples. Is this likely to benefit at all? And if so, how should I add the weights (in the equations below).
The cost function looks like the following:
$$J = (-1 / m) \cdot\sum_{i=1}^{m}  y\cdot\log(h(x\cdot\theta)) + (1-y)(1 - \log(h(x\cdot\theta)))$$
The gradient of this cost function (wrt $\theta$) is:
$$\mathrm{grad} = ((h(x\cdot\theta) - y)' \cdot X)'$$
Here $m$ = number of test cases, $x$ = feature matrix, $y$ = output vector, $h$=sigmoid function, $\theta$ = parameters we are trying to learn.
Finally I run the gradient descent to find the lowest $J$ possible. The implementation seems to run correctly.
Comment: Classification is not a good goal and is not the way logistic regression was developed.  It is the notion of classification that causes all the problems listed here.  Stick to predicted probabilities and proper accuracy scoring rules
Comment: What you are doing is confusing a loss function with maximum likelihood.  The unweighted mle is doing the "right thing" from an inferential perspective, and reflecting how rare the outcome is for each covariate specification.  You could also have separation - this would happen that a particular set of covariates that can perfectly predict the response in the training data - this would lead to large negative values.
Comment: @arahant That's only partially true. A binary logistic regression with a logit link is still valid in that the coefficients on your covariates are MLE and reflect the effect those variables have on the odds of class 1 compared to class 0. However, in a case-control design, the intercept is always fixed to reflect the proportion of class 1 to class 0, and it is perfectly valid to adjust the intercept term to assign classes in line with, e.g., some cost function of misclassification, or some other process, because this doesn't change coefficients on variables.
Comment: Where did anyone get the idea that a cutoff is needed/wanted/desireable?
Comment: Hi, I have exactly the same problem that you described. In my data a lot of examples are negative and very few positive, and for me it's more important to correctly classify the positive, even if that means to miss-classify some negatives.
It appears that I'm also applying the same methods as you were, since I'm using the same Cost Function and gradient equations. So far, I have run a few tests and I obtained the following results: - With *7 parameters*, *Training sample size: 225000*, *Test sample size: 75000* Results: **92% accuracy**, although in the **positives cases only 11%** w
Comment: @arahant, Hi, I have exactly the same problem that you described. In my data a lot of examples are negative and very few positive, and for me it's more important to correctly classify the positive, even if that means to miss-classify some negatives. It appears that I'm also applying the same methods as you were, since I'm using the same Cost Function and gradient equations. It seems that the only way I have to improve these results is to use weights, so I would like to know if you found an answer to your question, and if so how (and where) did you applied those weights. It would really help me
Comment: @Cartz, I am pretty much a beginner at this, but IIRC when I did try the weights, I did not get any notable improvement. As noted by Frank and probabilityislogic, the probability estimates are valid even when using unweighted features. What you should think is whether cutoff of p = 0.5 is a good indicator. Try lowering that. Also, from my experience, using better features is of prime importance, so work on that as well.
Comment: @arahant,
Where in your code did you change the cutoff value?
Comment: @arahant How was your sample constructed? Did you randomly sample the relevant population for the two classes, or did you assemble a case-control design?
Comment: @Cartz, well you do that in the end right? You output 1 if p >= cutoff and 0 if p < cutoff. Usually cutoff is 0.5, but you can change that.
Comment: @user777, yes I did take a random sample from the population. Taking anything other than a random sample seems to be a bad idea because then you are learning a function which is not the target function.
Comment: @FrankHarrell, It is just a quick tradeoff fix, if you want to improve the accuracy of your true positives at the expense of some false positives. Which is what Cartz is looking for it seems.
Answer: That would no longer be maximum likelihood.  Such an extreme distribution of $Y$ only presents problems if you are using a classifier, i.e., if you are computing the proportion classified correctly, an improper scoring rule.  The probability estimates from standard maximum likelihood are valid.  If the total number of "positives" is smaller than 15 times the number of candidate variables, penalized maximum likelihood estimation may be in order.
Comment: Just in case anyone else should misread the above as I did at first.  The 20:1 in the question is the ratio of negative to positive observations.  The 15:1 in Frank Harrell's answer is something else: the ratio of positive observations to candidate independent variables.
Comment: Frank, is there a reference or something to support your "15 times..." detail? I have similar unbalance in some data that I am using logistic regression for in place of a ROC method some other researchers developed. I have recently come across the small-sample bias and added an option for Firth's bias-reduction as a fitting option in my code/package. As I'm writing this up for a journal it would be useful to have something to cite along side rules of thumb like this. Apologies if the reference is your RMS book as that is sat on my shelves, but haven't looked there yet.
Comment: There are papers on small-sample bias and the value of the Firth penalization.  I don't have those handy.  Regarding 15:1 see http://biostat.mc.vanderbilt.edu/wiki/pub/Main/FrankHarrell/smi92pro.pdf
Comment: Thanks Frank - the 15:1 issues was what I was most after. I have some publications on the small-sample bias and Firth's method - but if you did have something to hand eventually I'd be most grateful if you let me know what it was.
Comment: An extreme distribution also presents a problem by increasing the chance of quasi-complete separation, especially if you have categorical predictors.  Penalisation helps here as well.
Answer: In cases like this, it is often better to use a flexible link, instead of the logistic link, that can capture this asymmetry. For example a skew-normal, GEV, sinh-arcsinh, and the references therein. There are many others but I cannot post more than 2 links.
Comment: Can you provide any explanation for other link functions are better?


Wpf data grid CurrentCell property fires only once MVVM

Question: I have a datagrid that looks like:
<DataGrid x:Name="Applications" CanUserResizeColumns="False" CanUserResizeRows="False"
 AutoGenerateColumns="false" CanUserAddRows="false" ItemsSource="{Binding Applications}"
 SelectionMode="Single"
 CurrentCell="{Binding CellInfo, Mode=TwoWay}">

And I have a question about CurrentCell, it is binded to poeprty in view model that looks like:
    private DataGridCellInfo cellInfo;
    public DataGridCellInfo CellInfo
    {
        get => cellInfo;
        set
        {
            cellInfo = value;
            OnPropertyChanged();

            if (cellInfo.Column.DisplayIndex == 1)
            {
                var selectedApplication = (ExtendedApplicationFile)cellInfo.Item;
                ExpandAppDetailsCommand.Execute(selectedApplication);
            }
        }
    }

And what it does, it sets correct item and sends it to command that will expend and hide row details window.
Problem is if I click once property is set and it will expand, but when I click second time on same cell, property is not setting and details row is not collapsing. It will work again when I click other cell and get back to it, but that is not I am aiming for.
Comment: That's not how it works. Nothing changes if currentCell is the same... Most like you have to use the Click event or MouseButtonDown event to achieve what you are requiring!
Comment: *"when I click second time on same cell, property is not setting"* - by design. The cell is not changed by such an action. *"that is not I am aiming for"* - you want to toggle some visibility, that's naively either checkbox or togglebutton behavior. If you want to mimic it you have to keep state and handle clicks.
Comment: You can template a control into pretty much anything you like. So you could put a togglebutton in every cell and whatever is currently showing in a cell within that. This seems an unlikely requirement though. Isn't the standard rowdetails behaviour sufficient for your requirement? By default you see the detail template for the selected row. Once you select one you'd need some way to un-select it if you really need that aspect. Like maybe a double click mousegesture.
Answer: Basing on information in comment I came up with simple solution, Ive added cell template with event trigger:
<DataGridTemplateColumn.CellTemplate>
       <DataTemplate>

           </DataTemplate>
</DataGridTemplateColumn.CellTemplate>

Using thin each time I click cell event fires and toggles details view.


Zeros à esquerda

Question: Vou receber vários números que podem ser de até 9 dígitos. Gostaria que quando não fosse de 9 (111 por exemplo) o sistema automaticamente substituísse por 000000111.
Os exemplos que eu achei na internet colocavam para preencher números fixos a esquerda, eu não posso utilizar os mesmos pois posso receber 11 e teria que aparecer 000000011.
Answer: Acredito que o PadLeft resolveria para o seu caso:
Dim pad As Char
str = "11"
pad = "0"c
Console.WriteLine(str.PadLeft(11, pad))

Outra possibilidade encontrada nesta resposta:
Console.WriteLine(string.Format("{0:00000000000}", 11));

Zeros à esquerda


What does +- mean in piano music?

Question: Attached is a picture of one of my piano students' Bach Inventions (BWV 785). What does the +- mean? I've never seen it used before.  A precursory search online revealed nothing. Sometimes a + indicates a raised tone, and a - indicates a lowered tone. This is all I can think of but it doesn't make sense in this setting if that's it.
Comment: I would bet there would be some explanation in whatever edition this came from.
Comment: @Marzipanherz since that marking is editorial it's highly unlikely that it exists in any other edition.
Comment: @Marzipanherz that's true, but my point is that the editorial markings express the editor's interpretational ideas, and the chance that another editor has had the same idea is probably rather small.
Comment: @Marzipanherz I just edited to add the BWV number.
Comment: Kevin H if I were you I would explain to the student that the markings have nothing to do with Bach and suggest getting an edition that doesn't have editorial expression markings.  If you want to teach your student how to interpret such markings, use repertoire from a later period where the composer actually used them.  Alternatively, you can help the student decide whether to agree with the editor's interpretation or to come up with his or her own.
Comment: There are explanations of symbols and passages at the bottom, but it seems like this was not one of the things addressed. I can check again however.
Comment: @phoog I was thinking the same and updated my answer with some highlights of Bach's autograph.
Answer: I have seen + used to indicate an ornament, but I think this is an older sign from before Bach's time.
Also, the - could be tenuto.
But I don't think this is what they mean in this score. Try @Richard's advice and look for an explanation in the edition.
This isn't a direct answer, but it may be helpful...
According to IMSLP this is the measure from your question in Bach autograph...

...no ornaments.
And this...

...is a well known guide to ornaments also in Bach's actual writing.
Whatever those marks are supposed to mean they aren't Bach's. Same goes for the expression markings. It seems worth noting those things are someone else's additions and are not Bach's instructions.
Answer: I don't know this symbol, but I think it would probably be an indicator of either volume, as it is near that crescendo, or fingering. Some guitar sheet music will use + and - for position shifts (if you need to go up 3 frets with your 1st finger, +3 is indicated at that note). It could also be indicating a slight variation in tempo, as in specifying the rubato.

What does +- mean in piano music?


Accessing function results from another Jquery

Question: hope someone can assist with the following.
I have a function that reads image data from database and returns the object url to be displayed based on the image/file type.
function newFile(data) {
//example image j -> jpg image type
 if ('j'.search(imgType) >= 0)
  {
     var d = imgData;
     data = new Uint8Array(d.length / 2);
     for (var i = 0; i < d.length; i += 2)
     data[i/2] = parseInt(d.substr(i, 2), 16);
     mime_type = 'image/jpeg';
  }
  //example image s -> svg image type
 if ('s'.search(imgType) >= 0)
  {
    var d = imgData;
    mime_type = 'image/svg+xml';
  }
    url = window.URL.createObjectURL(new Blob([data], { type: mime_type }));
}

How would i access this function from another file and function, using it to render other images. example if i have an jpg it does the conversion to the image. I am trying to create a preview page, and would like to use the above function instead of copying and pasting this in another on click function.
$('.preview').click(function(){
$.ajax({
  url: "/images.php",
  data: { id: "imageId"},
  type: 'post',
  dataType: 'json',
  success: function(ids){
    {
      for (var i = 0; i < ids.length; ++i)
      {
        var k = ids[i].result[0];
        if (k.imgType = 'j')) //jpg
        {
          //go to newFile function where k.imgType = j return image blob url
          $('previewer').html("");
        }
      }
    }
  }
});

});
Thanks in Advance
Comment: Please fix the indentation of your code. Also, the brackets aren't balanced.
Comment: `'j'.search(imgType)` doesn't make much sense. Did you mean `imgType.search(/j/)`?
Answer: Something like this
Your code was a mess by the way. Missing brackets all over the place.
Also if there is more than one image (you DO loop) then you need to append
I cannot guarantee the code below works, but it is closer than it were

const mimeTypes = {
  'j': 'image/jpeg',
  's': 'image/svg+xml'
}
// not tested but cleaned up
function newFile(imgData, imgType) {
  const data = new Uint8Array(imgData.length / 2);
  for (let i = 0; i < imgData.length; i += 2) {
    data[i / 2] = parseInt(imgData.substr(i, 2), 16);
  }
  return window.URL.createObjectURL(new Blob([data], {
    type: mimeTypes[imgType]
  }));
}

$('.preview').on("click", function() {
  $.ajax({
    url: "/images.php",
    data: {
      id: "imageId"
    },
    type: 'post',
    dataType: 'json',
    success: function(ids) {
      for (var i = 0; i < ids.length; ++i) {
        const k = ids[i].result[0];
        $('previewer').append('')
      }
    }
  });
});
Answer: The function should end with return url;.
Then you can call it from the AJAX success function.
$('previewer').html(`");

Comment: I think there is a bit more to it than that. Please see my answer for what I mean
Comment: I was ignoring all the messed up code, and assuming that would be fixed independently.
Comment: Also they need to append or they will only see the last image
Comment: hi @Barmar code was fixed, it was taken from a long file and i only wanted to show code i was trying to use.


Prove or disprove that $n^3-n$ is divisible by $6$, without using induction

Question:
Prove or disprove that $n^3-n$ is divisible by $6$, without using induction

I have no idea how to go about this.
I should add that n is an integer. I started by looking for some  integer that was a single case disproving it, but I couldn't find one.
Any help/suggestions are welcome!
Comment: $$n^3-n = 6\binom{n+1}{3}\in 6\mathbb{Z}$$
Comment: Possible duplicate of [Show that $n^3-n$ is divisible by $6$ using induction](https://math.stackexchange.com/questions/211121/show-that-n3-n-is-divisible-by-6-using-induction). Several other candidates for duplicate targets can be found with [Approach0](https://approach0.xyz/search/?q=%246%5Cmid%20n%5E3-n%24&p=1). That is the oldest (and has been used earlier as well).
Comment: This question is different than that possible duplicate: I'm trying to prove this without using induction
Comment: [Here's a variant](https://math.stackexchange.com/q/1202868/11619) where induction is not used. Sorry about not paying attention.
Answer: We have
$$n^3 - n = n(n^2-1) = n(n+1)(n-1)$$
One of these $(n, n+1, n-1)$ must be even (why?) and one must be divisible by 3 (why?).
Comment: I can prove one of those must be even, but I'm not sure how to prove that one of them must be divisible by 3...
Comment: $n-1, n, n+1$ are three consecutive numbers. Whenever you have three consecutive numbers and take it $\pmod 3$, then one has to be $0 \pmod 3$.
Answer: By the division theorem we have $n=6k+r$ for some $0 \le r < 6$. Then
$$(n^3-n) = (6k+r)^3 - (6k+r) = 6(x-k) + (r^3-r)$$
where $x = \sum_{i=1}^3 \binom{3}{i} 6^{i-1}k^ir^{3-i} \in \mathbb{Z}$ by the binomial theorem.
But $r \in \{0,1,2,3,4,5\}$, so $r^3-r \in \{0,0,6,24,60,120\}$, each of which is a multiple of $6$.

Disclaimer: I would argue that both this answer and twnly's answer 'use induction', because both depend on results that themselves require induction in some form to be proved.
Comment: That disclaimer is so, so true. You really can't do much with regards to the natural numbers without induction. In some definitions of natural numbers, induction is actually part of them.
Answer: Hint:
Fermat's theorem and Chinese remainder theorem.


Do three arithmetic sequences of real numbers that include $0$ always get arbitrarily close to each other at nonzero numbers?

Question: I know that two arithmetic sequences of real numbers that both contain the number $0$ have terms that are arbitrarily close together, that is, for any $\varepsilon>0$ there exists a real number such both sequences have a term within $\varepsilon$ of that number but $0$ isn't within $\varepsilon$ of that number. Is this necessarily true for three (or more) arithmetic sequences that all contain the number $0?$ If not, for what number of arithmetic sequences does this fail?
My motivation for this question was that I wanted to devise a scale in music that had very close approximations to nice intervals like the octave, perfect fifth, major third, harmonic seventh, and other nice intervals relative to the number of notes per octave, but I wanted to know whether we can get arbitrarily close before attempting an "optimal" such scale.
Answer: Yes, this is always true; in fact, there is not just a real number that every sequence gets within $\epsilon$ of but an integer.  Let me reformulate the question a bit first.  Suppose you have a lattice $A\subset\mathbb{R}^n$ (e.g., the lattice consisting of points whose coordinates are from each of $n$ chosen arithmetic sequences) and a nonzero vector $v\in\mathbb{R}^n$ (e.g., $v=(1,1,\dots,1)$).  Then I claim that there are nonzero integer multiples of $v$ that get arbitrarily close to points of $A$.
To prove this, note that by compactness of the quotient group $\mathbb{R}/A$, the sequence $(nv)_{n\in\mathbb{N}}$ has a subsequence that converges mod $A$.  So, for any $\epsilon>0$, there exist distinct $m,n\in\mathbb{N}$ such that $mv$ is within $\epsilon$ of $nv$ mod $A$.  Then $(m-n)v$ is a nonzero integer multiple of $v$ that is within $\epsilon$ of a point of $A$.


how do you add get and set for an array in c#

Question: I'm coding a func that inputs an array with different year of birth and prints out the oldest person.
I'm trying to add a validation with get and set but my syntax is wrong.
enter image description here
Comment: please add your code instead of a image file
Comment: Along with the precise error, instead of "my syntax is wrong". See https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/ for suggestions about writing good Stack Overflow questions.
Comment: Do you really need 2 arrays? Can't you make a class that contains a name & birth year members, then add those to a list of that class? Also, doing a bit of validation inside adding items from a console is always a good thing to think about
Comment: Where do you want to add that "validation"? Note that you already have a problem spot with that Convert.ToInt32(...) - try entering a non-number
Comment: Hey, @JonSkeet just wanted to thank you for the "C# in Depth" book. Great stuff there.
Answer: TL;DR
Properties declaration part:
public class Employee
{
    private string _fullName;
    private int _yearIn;

    public string FullName
    {
        get => _fullName;
        set
        {
            if (!string.IsNullOrEmpty(value))
            {
                _fullName = value;
            }
        }

    }

    public int YearIn
    {
        get => _yearIn;
        set
        {
            if (value > 0 && value <= 2020)
            {
                _yearIn = YearIn;
            }
        }
    }
}

And a usage:
var employees = new List<Employee>();
for (int i = 0; i < 3; i++)
{
    Console.WriteLine("Enter Name:");
    string name = Console.ReadLine();

    Console.WriteLine("Enter Year:");
    int yearIn = Convert.ToInt32(Console.ReadLine());

    employees.Add(new Employee
    {
        FullName = name,
        YearIn = yearIn
    });
}

Update
You can do the same in a bit different manner though:
public class Employee
{
    private string _fullName;
    private int _yearIn;

    public bool IsNameValid { get; set; }
    public bool IsYearValid { get; set; }

    public string FullName
    {
        get => _fullName;
        set
        {
            _fullName = value;
            IsNameValid = string.IsNullOrEmpty(value);
        }

    }

    public int YearIn
    {
        get => _yearIn;
        set
        {
            _yearIn = value;
            IsYearValid = (value < 0) || (value > 2020);
        }
    }
}

And later:
Console.WriteLine($"Employee name is: {employees[i].IsNameValid}");
Console.WriteLine($"Employee year is: {employees[i].IsYearValid}");

Update 2
And the last alternative version is that you can use Validation attributes:
public class Employee
{
    [Required]
    [Range(0, 2020)]
    public int YearIn { get; set; }

    [Required]
    [StringLength(50)]
    public string FullName { get; set; }
}

later:
var empl = new Employee{ YearIn =  yearIn, FullName = name};

var context = new ValidationContext(empl, serviceProvider: null, items: null);
var results = new List<ValidationResult>();

var isValid = Validator.TryValidateObject(empl, context, results, true);
Console.WriteLine($"Is model valid: {isValid}");

if (isValid)
{
    employees.Add(new Employee
    {
        FullName = name,
        YearIn   = yearIn
    });
}

Comment: it's a pitty you can set the validation fields from outside the class ;) You could have autoproperties on the FullName and YearIn and get only properties for the validation stuff
Comment: @Icepickle exactly, you were ahead of me, because right now I was going to submit the version with auto properties and validation attributes. But you know it also depends on the business needs, whether it needs to be implemented with the version I've already posted or with other ways, that all depends on use cases.
Answer: You can create wrapper classes over array and use indexer method for accessing the array item.
There in, you can put all your validation logic.
class IntData
    {

        public IntData(int size)
        {
            data = new int[size];
        }
        // Array of temperature values
        private int[] data;

        public int this[int index]
        {
            get
            {
                return data[index];
            }

            set
            {
                // Do your validation here
                if (value < 5000)
                {
                    data[index] = value;
                }
            }
        }
    }

      static void Main(string[] args)
        {
            IntData year = new IntData(3);
            year[0] = 2000;
            year[1] = 6000; // This value won't set because of validation
            year[2] = 4000;

            Console.Read();
        }

Comment: This is similar to validation when setting properties. We can throw exception when user try to set some invalid value and not allow the user to enter that value.


Estimate intercept and fixed effects with fixest's GLM function

Question: I'm trying to replicate Stata outputs that provide both constant and FEs.
Here's an example of what I'm trying to do
> fixest::feglm(mpg ~ 1 + wt | cyl, mtcars)

GLM estimation, family = gaussian, Dep. Var.: mpg
Observations: 32
Fixed-effects: cyl: 3
Standard-errors: Clustered (cyl)
   Estimate Std. Error  t value Pr(>|t|)
wt -3.20561    1.18823 -2.69781  0.11431
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Log-Likelihood: -74.3   Adj. Pseudo R2: 0.252149
           BIC: 162.5     Squared Cor.: 0.837433

The idea of the "1" in my formula is to estimate the model
$$mpg_i = \beta_0 + \beta_1 wt_i + \sum_j \beta_j cyl_{ij} + e_i$$
Instead of the model
$$mpg_i = \beta_1 wt_i + \sum_j \beta_j cyl_{ij} + e_i$$
Would that be possible with a "hack"?
The reason to use fixest is that it is much faster than
stats::glm(mpg ~ wt + as.factor(cyl), data = mtcars)

which estimates an intercept and the FEs but dropping one factor level that passes as the intercept.
Answer: Given one continuous predictor wt and one categorical predictor cyl, you propose two models, with and without intercept.
The model with an intercept is over-parameterized. The (global) intercept is redundant because each cyl level has its own intercept: fixed effect of cyl_i = intercept for all observations in the cyl_i group.
So in practice fixest discretely ignores the + 1 "hack" and fits the model without an intercept.
PS. A better way to write down the model is:
$$
E\{mpg_i\} = beta_{cyl_i} + beta_{wt} * wt
$$
This formula makes it explicit that the intercept is specific to each cyl level.
And we can check that this is indeed how fixest interprets the formula:
library("fixest")

# Not necessary to fit the model but handy to compute the predictions by hand
mtcars$cyl <- as.factor(mtcars$cyl)

fit <- feglm(mpg ~ wt | cyl, mtcars)

beta_cyl_i <- fixef(fit)$cyl[mtcars$cyl]
beta_wt_x_wt <- coef(fit)["wt"] * mtcars$wt

# We now know how to compute by hand the predictions that we get with `predict()`
beta_cyl_i + beta_wt_x_wt
#>        6        6        4        6        8        6        8        4
#> 21.33650 20.51907 26.55377 19.42916 16.89262 18.64379 16.47590 23.76489
#>        4        6        6        8        8        8        8        8
#> 23.89311 18.70790 18.70790 14.87309 15.96300 15.80272 11.09046 10.53269
#>        8        4        4        4        4        8        8        8
#> 10.78593 26.93844 28.81373 28.10849 26.08896 16.63618 16.90865 15.61038
#>        8        4        4        4        8        6        8        4
#> 15.59435 27.78793 27.13078 29.14070 17.75814 20.85566 16.47590 25.07919
predict(fit)
#>  [1] 21.33650 20.51907 26.55377 19.42916 16.89262 18.64379 16.47590 23.76489
#>  [9] 23.89311 18.70790 18.70790 14.87309 15.96300 15.80272 11.09046 10.53269
#> [17] 10.78593 26.93844 28.81373 28.10849 26.08896 16.63618 16.90865 15.61038
#> [25] 15.59435 27.78793 27.13078 29.14070 17.75814 20.85566 16.47590 25.07919

Created on 2022-03-20 by the reprex package (v2.0.1)


Polynomials that share at least one root

Question: Let $P(x) = x^2 + Bx + C$, for $B,C \in \mathbb{R}$, have real roots.
Represent the set of all other $p(x)= x^2 + bx + c$ that share a root with $P(x)$ by a plot in the $bc$-plane. It forms a nice picture:
for example, here it is for $B=3, C=-1$, when
the roots are $-\frac{1}{2}
   \left(3 \pm \sqrt{13}\right)$:

Lines intersect at $b=3,c=-1$.

All those $(b,c)$ on the two lines share a root with
$x^2 + 3x -1$. The lines are tangent to the paraboloid
$b^2 = 4c$, where the discriminant is zero.
Two questions:

Q1. Can you explain the characteristics of this picture
  geometrically, without relying heavily on explicit algebraic calculations?

By "the characteristics" I mean: Two straight lines meeting
at the $B,C$ point, tangent to the discriminant parabola.

Q2. What is the analogous picture for $P(x) = x^3 + B x^2 + C x + D$, the set of cubic polynomials that share at least one root
  with $P(x)$, plotted in $bcd$-space?

I would welcome further generalizations: To coefficients and
roots in $\mathbb{C}$, and/or to higher degree polynomials.
Comment: I am not sure about the parabolic description - for a given $a$ results a linear relation between $b$ and $c$. $(x-a)(x-y)=0$ leads (by eliminating $y$) to the relation between the $b$ and $c$
Comment: Generalized question posted to MO, https://mathoverflow.net/questions/335232/polynomials-that-share-at-least-one-root
Comment: Nice question, +1.
Comment: For the Qubed one take the same process - for a solution $a$ (real number?) you derive a relation between B, C, D by eliminating the other two roots.
Comment: With regard to the Qube - you get a plane
Comment: And [answered on MO](https://mathoverflow.net/a/335241/6094).
Answer: Fix a root $\alpha$ of $P(X)$.
Then every polynomial of that form with root $\alpha$ must be of the form $(x-\alpha)(x-\beta)$ and $b=-\alpha-\beta, c=\alpha\beta$.
From this formula we get that the dependance between $c$ and $b$ is linear.
More specifically $c=-\alpha b-\alpha^2$.
This way you obtain a line through $(B,C)$ and if you chose the other root you obtain the other line.
Now, about the parabola, it is clear that these lines must intersect it in the point $(-2\alpha_1,\alpha_1^2 )$ and $(-2\alpha_2,\alpha_2^2)$ and they certainly can't go in the $b^2<4c$ area because a point in this zone corresponds to a polynomial with no real root.
It follows that the lines must be tangent to the parabola.
Comment: You are right, I meant the point corresponding to the roots $(\alpha_1,\alpha_1)$ which is $(-2\alpha_1,\alpha_1^2)$
Comment: Nice, but I don't see the tangencies at $(\alpha_i,\alpha_i)$. In my example, the two roots are $-3.303$ and $0.303$, whereas one tangency is about $(10,6.3)$.
Comment: $(-2 \alpha_1, \alpha_1^2) \approx (6.6,10.9)$---checks out.


Block specific URI with Query String in Varnish

Question: Can someone help to block an URL which has querystrings as part of it in Varnish ?
For eg: /abcd.php?
Blocking /abcd.php works good yet with ? I'm able to access the page
Thanks,
Raj
Answer: You can make a rewrite rule and return an HTTP error code something like this:
if (req.url ~ "/abcd.php$") {
  error 404 "Not found"
}

If you have some parameters you have to remove the $ at the end of the string.


C# asp.net: Cookie Expiration date in Chrome

Question: I'm having an issue with the Expiration date of a cookie in C# when in chrome.
Here is the code I'm using:
<code>public static void createCookie(Users u, DateTime expirationDate)
{
    HttpCookie loginCookie = new HttpCookie("cookie");
    loginCookie.Value = "somevalue";
    loginCookie.Expires = DateTime.UtcNow.AddDays(1d);
    HttpContext.Current.Response.Cookies.Add(loginCookie);
}
</code>
I've run this code through Fiddler and it does return the correct Expiration Date. The cookie's expiration date is also correct in Firefox and IE9 However, when I run this in chrome the expiration date is always set to: Sun, 07 Dec 1969 03:28:36 GMT
Always at 3:28:36 GMT it never changes. Any idea on why this is happening would be greatly appreciated. Thanks!
I've also tried to set the expiration date using: DateTime.Now.AddDays(1d) with the same result.
Answer: It's a bug in the current version of chrome, it's the displaying of the expiration date that is wrong, not the actual expiration, the value you have set will be honored by chrome!
Here's a link to the bug which has been fixed in their nightly builds (Verified as Fixed with 20.0.1132.7 (Official Build 136817))
: http://code.google.com/p/chromium/issues/detail?id=125546
Comment: And this bug reappears in 2018?? I am still having it and it is getting worse, the session cookie persists even after the machine reboots.
Comment: Sorry about that, I'm new to Stack Overflow, let me know if I didn't do it right.


Decomposition of PDEs

Question: If decomposing the following PDE:
$\dfrac{\partial}{\partial\,x} \left[\dfrac{\lambda}{T}  \dfrac{\partial \rho}{\partial\,x}\right]$
to
$\dfrac{\partial}{\partial\,x} \left[\dfrac{\lambda}{T}  \dfrac{\partial \rho}{\partial\,x}\right]  \:\rightarrow\:  \left[\dfrac{1}{T}\dfrac{\partial \lambda}{\partial\,x} - \dfrac{\lambda}{T^2}\dfrac{\partial T}{\partial\,x}\right]\dfrac{\partial^{\,2} \rho}{\partial x^{\,2}}  $
is true, could you please give me a clue of decomposing $\dfrac{\partial^{\,2} \rho}{\partial x^{\,2}}$ such that every term has only one variable as a partial derivative.
Thank you.
Answer: The "decomposing" you mention is simply the application of the product & chain rule of differentiation. Since $\rho$ is not a composed function nor a product, there is nothing more to do.
Comment: Yes, that is what I meant. Thanks, no wonder I couldn't find anything else to do :).

Decomposition of PDEs


SSH always fails to start and status is activating

Question: I am running open-ssh 7.8p1 on Redhat 7.0. I downloaded the package and executed the commands in order to install the package:
./configure --prefix=/usr --sysconfdir=/etc/ssh --with-privsep-path=/var/lib/sshd  --with-pam --with-xauth=/usr/bin/xauth
make
sudo make install
sshd/config:
<code>#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key

# Ciphers and keying
#RekeyLimit default none

# Logging
#SyslogFacility AUTH
SyslogFacility AUTHPRIV
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m
#PermitRootLogin yes
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

#PubkeyAuthentication yes

# The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2
# but this is overridden so installations will only check .ssh/authorized_keys
AuthorizedKeysFile      .ssh/authorized_keys

#AuthorizedPrincipalsFile none

#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no
PasswordAuthentication yes

# Change to no to disable s/key passwords
#ChallengeResponseAuthentication yes
ChallengeResponseAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no
#KerberosUseKuserok yes

# GSSAPI options
#GSSAPIAuthentication yes
#GSSAPICleanupCredentials no
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no
#GSSAPIEnablek5users no

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
# WARNING: 'UsePAM no' is not supported in Red Hat Enterprise Linux and may cause several
# problems.
UsePAM yes

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#UsePrivilegeSeparation sandbox
#PermitUserEnvironment no
#Compression delayed
ClientAliveInterval 20m
#ClientAliveCountMax 3
#ShowPatchLevel no
#UseDNS yes
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
#Banner none

# Accept locale-related environment variables
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS

# override default of no subsystems
Subsystem       sftp    /usr/libexec/openssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#       X11Forwarding no
#       AllowTcpForwarding no
#       PermitTTY no
#       ForceCommand cvs server

</code>
sshd status
ssh debug mode result:
<code>debug2: load_server_config: done config len = 669
debug2: parse_server_config: config /etc/ssh/sshd_config len 669
debug3: /etc/ssh/sshd_config:22 setting HostKey /etc/ssh/ssh_host_rsa_key
debug3: /etc/ssh/sshd_config:24 setting HostKey /etc/ssh/ssh_host_ecdsa_key
debug3: /etc/ssh/sshd_config:25 setting HostKey /etc/ssh/ssh_host_ed25519_key
debug3: /etc/ssh/sshd_config:32 setting SyslogFacility AUTHPRIV
debug3: /etc/ssh/sshd_config:47 setting AuthorizedKeysFile .ssh/authorized_keys
debug3: /etc/ssh/sshd_config:65 setting PasswordAuthentication yes
debug3: /etc/ssh/sshd_config:69 setting ChallengeResponseAuthentication no
debug3: /etc/ssh/sshd_config:96 setting UsePAM yes
debug3: /etc/ssh/sshd_config:101 setting X11Forwarding yes
debug3: /etc/ssh/sshd_config:112 setting ClientAliveInterval 20m
debug3: /etc/ssh/sshd_config:126 setting AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
debug3: /etc/ssh/sshd_config:127 setting AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
debug3: /etc/ssh/sshd_config:128 setting AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
debug3: /etc/ssh/sshd_config:129 setting AcceptEnv XMODIFIERS
debug3: /etc/ssh/sshd_config:132 setting Subsystem sftp /usr/libexec/openssh/sftp-server
debug1: sshd version OpenSSH_7.8, OpenSSL 1.0.2k-fips  26 Jan 2017
debug1: private host key #0: ssh-rsa SHA256:Gd4H0gToGhergccDgoCrmH03UPAfWcUd1NKusBGlls4
debug1: private host key #1: ecdsa-sha2-nistp256 SHA256:NxfjZIJ7oRPjfsBJKeSw/N3kf4iZMedZFnjePbLbyoc
debug1: private host key #2: ssh-ed25519 SHA256:CWwG5eZVSaU3hSizraB1blaeYfws4KI6NOWn1I8KC9Y
debug1: rexec_argv[0]='/usr/sbin/sshd'
debug1: rexec_argv[1]='-ddd'
debug3: oom_adjust_setup
debug1: Set /proc/self/oom_score_adj from 0 to -1000
debug2: fd 3 setting O_NONBLOCK
debug1: Bind to port 22 on 0.0.0.0.
Server listening on 0.0.0.0 port 22.
debug2: fd 4 setting O_NONBLOCK
debug3: sock_set_v6only: set socket 4 IPV6_V6ONLY
debug1: Bind to port 22 on ::.
Server listening on :: port 22.
</code>
I am trying to figure the problem and I tried to run sshd in debug mode and it didn't show any error.
After 1 min the sshd service fails then it auto restarts.
I am able to login to the server, but when it fails and before starting again, I get Connection refused.
So If anyone please can suggest a solution for this issue?
Comment: Why don't you just stick to the distro version and keep your system updated regularly?
Comment: You shouldn't post pictures of text, instead you should show the (text) output of sshd in debug mode.
Comment: @Thomas The two big reasons I see for people doing things like this are: They don't know that the distro packages have security updates and are misled by the version number not changing (in which case they should just update the system); or they don't actually have a RHEL subscription (in which case they should subscribe or use CentOS instead). Even if neither of these apply, compiling it yourself is not usually a good business practice and there needs to be a really good overriding reason for it.
Comment: That is the startup, everything seems fine. Is there no messages before the server terminates?
Comment: @Thomas
The issue is that a security vulnerability scan is done over my server and a report is generated where they recommend to upgrade the ssh version to  7.8p1 which is not supported by RHEL rpm repository. So I downloaded the package and compile it myself. I referred to the security administration that all patches in higher versions are added to our package 7.4 as it's always up to date but they insisted to upgrade it in order to get rid of the security breach in version 7.4.
Comment: @MichaelHampton Please check the comment above.
Comment: @RalfFriedl I added the sshd output
Comment: No, you don't upgrade by source code when a security scan identifies a vulnerability. You install the Red Hat provided update which resolves the vulnerability and then document it.
Comment: @RalfFriedl no messages.
Answer: I've found what was missing and making the service unable to start through systemd. The ssh service was compiled successfully but can't be set to start in the systemd. So I downloaded the package from  http://www.linuxfromscratch.org/blfs/downloads/svn/blfs-systemd-units-20180105.tar.bz2 , extracted the content and executed sudo make install-sshd.
After this I was able to start the service through sudo systemctl start sshd.service the status was active (running).


Expected value of minimum of exponential random variables

Question: I'm working on the following question:
A device contains two components, A and B. The lifespans of A and B are both exponentially distributed with expected lifespans of 5 years and 10 years respectively. The device works as long as both components work. What is the expected lifespan of the device?
I'm aware that A ~ Exp(1/5) and B ~ Exp(1/10). initially I thought that knowing the expected value of both variables (10 and 5) would allow me to use the linearity of expectations:
E[A + B] = E[A] + E[B] = 15
Then I realised that would be the expected total years of life of both components, which isn't what we're looking for.
The answer given in the textbook is λA + λB = λ(3/10) . The expected value of this is 3.3 years.
Intuitively , this seems correct, even though I didn't know how to sum exponentials like that. What I'm trying to understand though is how my application of the linearity of expectations is not accurate. Why is E[A + B] = 3.3 when E[A] + E[B] = 15 ?
Comment: $E[A + B]=E[A]+E[B]$ would be the expected time until $B$ stops where $B$ does not start until $A$ stops.  But  "The device works as long as both components work" means that you actually want $E[\min(A,B)]$ which is going to be less than either of $E[A]$ and $E[B]$.
Comment: Could you fix the title to say "expected value of minimum of ..."?
Answer: This is a problem where you want to examine the lifetime of a system composed of two components operating in series.  It is part of the broader subject of reliability analysis (also called survival analysis when looking at survival of organisms).  I recommend you read some introductory resources to get a general understanding of this subject area, including an understanding of the analysis of series and parallel systems.
In this particular case we have a system time-to-failure $T_\text{sys} = \min(A,B)$ and we want to find the expected system time-to-failure $\mathbb{E}(T_\text{sys})$.  To do this, we first need to derive the distribution of the system time-to-failure and then we use this to find the expected time-to-failure for the system.  Since the times-to-failure for the two components are independent exponential random variables we have:
$$\begin{align}
F_\text{sys}(t)
&= \mathbb{P}(T_\text{sys} \leqslant t) \\[6pt]
&= \mathbb{P}(\min(A,B) \leqslant t) \\[6pt]
&= 1 - \mathbb{P}(\min(A,B) > t) \\[6pt]
&= 1 - \mathbb{P}(A > t, B > t) \\[6pt]
&= 1 - (1-F_A(t)) (1-F_B(t)) \\[6pt]
&= 1 - \exp(-\lambda_A t) \exp(-\lambda_B t) \\[6pt]
&= 1 - \exp(-(\lambda_A + \lambda_B) t), \\[6pt]
\end{align}$$
so we can see that $T_\text{sys} \sim \text{Exp}(\lambda_A + \lambda_B)$.  Now, taking its expected value we get:
$$\begin{align}
\mathbb{E}(T_\text{sys})
&= \int \limits_0^{\infty} (1-F_\text{sys}(t)) dt \\[6pt]
&= \int \limits_0^{\infty} \exp(-(\lambda_A + \lambda_B) t) dt \\[6pt]
&= \Bigg[ - \frac{1}{\lambda_A + \lambda_B} \cdot \exp(-(\lambda_A + \lambda_B) t) \Bigg]_{t=0}^{t \rightarrow \infty} \\[6pt]
&= \Bigg[ ( 0 ) - \bigg( - \frac{1}{\lambda_A + \lambda_B} \bigg) \Bigg] \\[6pt]
&= \frac{1}{\lambda_A + \lambda_B}. \\[6pt]
\end{align}$$
Substitution of your particular parameters gives you the result given by your textbook.  As you can see from the above working, when you have components in series and these components operate independently with exponential time-to-failure, the system time-to-failure is exponentially distributed with hazard rate equal to the sum of the hazard rates of the components.  This is a well-known result for series systems in reliability analysis.


Erro Ao criar tabela no bd com Sequelize | postegres

Question: No terminal ao executar o comando yarn sequelize db:migrate pra criar a tabela users do GoBarber no banco de dados, retorna o seguinte erro:
yarn run v1.21.1 $ /home/dev/Documentos/GoBarber/node_modules/.bin/sequelize db:migrate

Sequelize CLI Node: 12.14.1, CLI: 5.5.1, ORM: 5.21.4

Loaded configuration file "src/config/database.js". == 20200208221655-create-users: migrating =======

ERROR: Cannot read property 'toString' of undefined

error Command failed with exit code 1. info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

No PostBird em Info tenho esse retorno do erro:
Type: table

Estimate rows count: 0

Total size on disk: 8 KB (Table: 0 Bytes, Indexes: 8 KB, Toast: 0 Bytes)

Source SQL Loading...
Error happen while running pg_dump:
    pg_dump: server version: 12.1 (Debian 12.1-1.pgdg100+1);
    pg_dump version: 10.10 (Ubuntu 10.10-0ubuntu0.18.04.1)
    pg_dump: aborting because of server version mismatch

Algo relacionado a alguma version, será que instalei algo errado?
Answer: não consegui identificar o erro, mas, fiz uma limpeza no docker com o comando prune Ex.: docker images prune
docker container prune
e instalei novamente , também refiz a migration users e funcionou.


Ask requestVisibleActions permission using Passport.js for moment insertion in Google+ API

Question: I'm working on a Node.js application that uses Passport.js for authenticating with Google Plus. In a later stage now, we have introduced of adding activities using Google+'s moment.insert to the user's Google+ feed when they leave reviews at our site. Posting using moment.insert needs a special permission called requestvisibleactions. The passport.js documentation doesn't say how I can ask for such permissions while logging in.
My current auth handler setup is like this:
app.get('/auth/google', redirect, passport.authenticate('google', {
    scope: ['https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/plus.moments.write'],
    accessType: 'offline'
}));

Any pointers on how I can specify the requestvisibleactions permission mentioned in this page during passport.js authentication is appreciated.
Answer: The problem is that passport.js doesn't include support for requestvisibleactions, and the pull request to update it has been sitting there for a while. As we discussed on Google+ insert moment with nodejs client You will need to do two things:
1) Apply this patch, which lets passport.js be able to set the parameter correctly.
2) Set the action that you wish to be able to do as part of the call to passport.authenticate
I have not tested this (since I don't use passport.js), but once you have done (1), you should be able to use something like this to be able to post Add and Review moments:
app.get('/auth/google', redirect, passport.authenticate('google', {
    scope: ['https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/plus.moments.write'],
    accessType: 'offline',
    requestVisibleActions: 'http://schema.org/AddAction http://schema.org/ReviewAction'
}));

Comment: i just have accesType and requestVisibleActions , but not work ? And try use google api explorer , request sent but nothing in my google plus activity,  why ??

where is i can find the post??
Comment: @masadizainul - It sounds like you should post this as a separate question, with illustrative code, so we can help figure out whats going on.


Determine the nth term in a series if:

Question: Given a sequence $f$ where after the first term, the $n$th term is derived by $3+2(f_{n-1}+n)$, how do you find the $n$th term given that the first term is 3, and $f_n=671088573$? I don't know of any ways you can find the position of the term when the position is part of the derivation of the term.
Answer: Hint: the general solution of this non-homogeneous linear recurrence is $f_n =g_n + p_n$ where $g_n$ is the general solution of the homogeneous recurrence $g_n = 2 g_{n-1}$ and $p_n$ is a particular solution.  Look for a particular solution of the form $p_n = a n + b$.
But in this case the answer turns out to be that there is no such $n$.  With $f(1)=3$, I get $f(26) = 402653125 < 671088573$ and $f(27) = 805306307 > 671088573$.
Or if you meant $f(0)=3$, that produces $f(26)=671088581$: close, but not quite.  Maybe that $671088573$ came from a numerical computation that suffered from roundoff error.
Comment: I did mean the $f(0)=3$, and I got the same answer, accomplished by guessing and checking using: $$10(\frac{1-2^n}{1-2})-7$$ essentially, I found how much the growth from each term grows by, and then I used summation of a geometric series to find the same estimation. I came close at $671088623$
Answer: $$f_n=3+2(f_{n-1}+n)\qquad \text{with} \qquad f(0)=3$$ making the story short, we have
$$f_n=5\times 2^{n+1}-2 n-7$$ and the solution of $f_n=k$ is given by
$$n=-\frac{W_{-1}\left(-5\times 2^{-\frac{k+7}{2}} \log (2)\right)}{\log
   (2)}-\frac{k+7}{2}$$ where $W_{-1}(.)$ is the second branch of Lambert function.
For $f_n=671088573$, this gives $n=25.9999999828$ and $f_{26}=671088581$ just a bit higher.
If you cannot use Lambert function, since its argument $$x=-5\times 2^{-\frac{k+7}{2}} \log (2) $$ is very small, you can use the approximation
$$W(x)\approx L_1-L_2+\frac{L_2}{L_1}+\frac{L_2(L_2-2)}{2L_1^2}+\frac{L_2(2L_2^2-9L_2+6)}{6L_1^3}+\cdots$$ where $L_1=\log(-x)$ and $L_2=\log(-L_1)$.
In the practical case, since $k$ is large, we can expect $n$ to be large and you could even make a first approxiamtion neglection the $(2n+7)$ terms and get, as an estimte
$$5\times 2^{n+1}\simeq k \implies n_0=\frac{\log \left(\frac{k}{5}\right)}{\log (2)}-1$$
Now, taking logarithms, we can write the equation to be solved as
$$g(n)=n\log(2)+\log(10)-\log(k+2n+7)$$ which almost the equation of a straight line
$$g'(n)=\log (2)-\frac{2}{k+2 n+7}$$ and a better solution
$$n_1=n_0-\frac{g(n_0)}{g'(n_0)}$$ For the working case $n_0=25.9999998560$ and $n_1=25.9999999828$.

Determine the nth term in a series if:


maven-assembly-plugin one jar per slf4j implementation

Question: in the maven project I'd like to produce additional *-nodep.jar files, however these should pack misc implementations of the slf4j API.
The trouble is that for maven-assembly-plugin I need to provide all dependencies on the project classpath. That results in tests into:
------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.AppTest
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/home/peterb/.m2/repository/org/slf4j/slf4j-log4j12/1.7.7/slf4j-log4j12-1.7.7.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/home/peterb/.m2/repository/org/apache/logging/log4j/log4j-slf4j-impl/2.0-rc1/log4j-slf4j-impl-2.0-rc1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.171 sec

It sounds like log4j was chosen kind of randomly (maybe classpath order matters here).
But how can I use log4j in my tests AND provide multiple *-nodep.jar packages with misc slf4j imlpementations packaged?
My test project configs follow:
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com</groupId>
    <artifactId>foo</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>foo</name>

    <properties>
        <slf4j-build>1.7.7</slf4j-build>
        <log4j-build>1.2.17</log4j-build>
        <log4j2-build>2.0-rc1</log4j2-build>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
            <version>4.11</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j-build}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j-build}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j-build}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>${log4j2-build}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${log4j2-build}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${log4j2-build}</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.4</version>
                <executions>
                    <execution>
                        <id>nodep</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <configuration>
                            <appendAssemblyId>true</appendAssemblyId>
                            <descriptors>
                                <descriptor>src/main/assembly/log4j2-nodep.xml</descriptor>
                                <descriptor>src/main/assembly/log4j-nodep.xml</descriptor>
                            </descriptors>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

log4j-nodep.xml:
<assembly
    xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">

    <id>log4j-nodep</id>
    <formats>
        <format>jar</format>
    </formats>
    <includeBaseDirectory>false</includeBaseDirectory>

    <dependencySets>
        <dependencySet>
            <includes>
                <include>com:foo:jar</include>
                <include>org.slf4j:slf4j-api:jar</include>
                <include>org.slf4j:slf4j-log4j12:jar</include>
                <include>log4j:log4j:jar</include>
            </includes>
            <unpack>true</unpack>
            <fileMode>0644</fileMode>
            <useProjectArtifact>true</useProjectArtifact>
            <scope>provided</scope>
        </dependencySet>
    </dependencySets>
</assembly>

log4j2-nodep.xml:
    <assembly
    xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">

    <id>log4j2-nodep</id>
    <formats>
        <format>jar</format>
    </formats>
    <includeBaseDirectory>false</includeBaseDirectory>

    <dependencySets>
        <dependencySet>
            <includes>
                <include>com:foo:jar</include>
                <include>org.slf4j:slf4j-api:jar</include>
                <include>org.apache.logging.log4j:log4j-slf4j-impl:jar</include>
                <include>org.apache.logging.log4j:log4j-api:jar</include>
                <include>org.apache.logging.log4j:log4j-core:jar</include>
            </includes>
            <unpack>true</unpack>
            <fileMode>0644</fileMode>
            <useProjectArtifact>true</useProjectArtifact>
            <scope>provided</scope>
        </dependencySet>
    </dependencySets>
</assembly>

I tried to provide other slf4j implementations to maven-assembly-plugin's <dependencies> section only, but these seem to be completely ignored during assembly.
Answer: As no volunteers out there, let me document what I ended up with.
I decided to go for the solution suggested in the question and live with the warning in my junit tests.


Do frameworks (e.g. Keras) use the wrong distribution for Glorot/Xavier weight initialization?

Question: When looking at the paper describing the Glorot/Xavier uniform weight initialization, the weights are sampled according to a uniform distribution according to equation 16
$$W \sim U[-\frac{\sqrt{6}}{\sqrt{n_j+n_{j+1}}}, \frac{\sqrt{6}}{\sqrt{n_j+n_{j+1}}}]$$
If I interpret the paper correctly, $n_j$ is the number of neurons in the current layer, and $n_{j+1}$ is the number of neurons in the next layer.
Looking at the implementation in Keras the bounds of the uniform distribution are calculated using a square root over fan_in + fan_out and fan_in is the numbers of neurons in the previous layer, and fan_out is the number of neurons in the current layer. So the implementation seems to be going in the "opposite" direction.
Can someone explain why you are allowed to use the opposite direction? I assume this is done because it is just difficult to get the number of neurons of the next layer when doing an initialization locally in the layer itself (since it is not known what the next layer will be).
Answer: The implementation is correct. There is no concept of the neurons in the typical library. Layers with parameters store weights that connect to layers of neurons, but the neuron is just an abstraction. In the simple case, lets say you have 4 input neurons and 3 output neurons. For this case, you will have 4x3 weight matrix. The shape of the matrix tells you number of input neurons and number of output. Layer that initializes values for the weights already knows all the values that it needs to know.
Layer that initializes weights has already pre-specified output shape, it just needs to know output shape from the previous layer in order to know the shape of the weight matrix.


Can anyone help me explaining line 2 of this python program?

Question: I am doing leedcode problem and I found this solution online. I haven't understood line 2 lookup = {x[0]: i for i, x in enumerate(pieces)}. Can anyone tell me how is it working? Also it will be cool if you can help me understanding whole program.
def canFormArray( arr, pieces):

    lookup = {x[0]: i for i, x in enumerate(pieces)}

    i = 0
    while i < len(arr):
        if arr[i] not in lookup:
            return False
        for c in pieces[lookup[arr[i]]]:
            if i == len(arr) or arr[i] != c:
                return False
            i += 1
    return True

arr = [15,88]
pieces = [[88],[15]]
p = canFormArray(arr,pieces)
print(p)

Comment: Which specific part of it do you not understand?
Comment: @LeonardusChen How is it workin?  for c in pieces[lookup[arr[i]]]:
Comment: here https://docs.python.org/3.9/tutorial/index.html
Answer: Google list comprehension.
lookup = {x[0]: i for i, x in enumerate(pieces)}
can be translated as
lookup = {} # init empty dict
for i, x in enumerate(pieces):
    lookup[x[0]] = i

Comment: You should be reading more tutorial about the data structure and the syntax in Python before moving on. This line assigns `i` to the key `x[0]` in `lookup`
Comment: ```lookup[x[0]]``` creates a new key for the dictionary @DiptinKharel
Comment: @coderoftheday and what about values? how they are created? when I print lookup, it shows me both value and key. How are these created?
Comment: ```i``` is the value, ```i``` takes a new value every iteration.


how to partition the data with specific row size

Question: Say I have the following matrix:
X = matrix(rnorm(4000), nrow=400, ncol=10)
size = c(80,80,79,80,81)

I want to partition the matrix row-wise according to the above size in a concise way. To illustrate,
x1 = X[1:80,]
x2 = X[81:160,]
.
.
x5 = X[320:400,]

I usually have different sizes and different matrices, so I won't be able to do this manually every time. Your help is very much appreciated.
Answer: You can get start and end points using cumsum and use Map to subset them and create list of matrices.
X = matrix(rnorm(4000), nrow=400, ncol=10)
size = c(80,80,79,80,81)

val <- cumsum(size)
result <- Map(function(x, y) X[x:y, ], c(1, val[-length(val)] + 1), val)

where c(1, val[-length(val)] + 1) creates the starting row numbers and val are the ending ones.
c(1, val[-length(val)] + 1)
#[1]   1  81 161 240 320

val
#[1]  80 160 239 319 400

Answer: Using map2
library(purrr)
size1 <- cumsum(size)
map2(size1, c(1, size1[-length(size1)] + 1), ~ X[.x:.y,])

Answer: Try the code below
e <- cumsum(size)
b <- c(1, head(e + 1, -1))
out <- Map(function(rb, re) X[rb:re, ], b, e)

and you will see
> str(out)
List of 5
 $ : num [1:80, 1:10] 0.253 -0.368 0.804 -0.603 -0.119 ...
 $ : num [1:80, 1:10] 0.467 -0.743 -0.401 1.48 0.853 ...
 $ : num [1:79, 1:10] -1.123 -0.873 -1.039 -0.247 -0.774 ...
 $ : num [1:80, 1:10] -1.409 -0.683 -0.514 0.485 -0.347 ...
 $ : num [1:81, 1:10] 0.58 0.529 -0.803 0.49 -0.847 ...

Furthermore, if you want to create variables, try
list2env(setNames(out,paste0("x",seq_along(out))),envir = .GlobalEnv)


PostgreSQL Trigger apos update

Question: Vamos imaginar o seguinde cenário:
CREATE TABLE invalido (
   ds_valor character varying(255)
)

CREATE TABLE email (
    email character varying(255)
)

agora preciso de uma trigger que toda vez que eu execute um UPDATE ou INSERT na tabela email ele verifique se o valor está na tabela  invalido, se estiver então deve substituir o que seria inserido na tabela email por email invalido.
Answer: Primeiro, crie uma função que retorna o tipo trigger:
CREATE FUNCTION validar_email()
RETURNS trigger AS '
BEGIN
  IF EXISTS (SELECT
               FROM invalido
              WHERE ds_valor = NEW.email) THEN
    NEW.email := ''email invalido'';
  END IF;
  RETURN NEW;
END' LANGUAGE 'plpgsql'

Depois crie um trigger que dispara antes do INSERT e do UPDATE que irá permitir que o valor seja alterado e execute a função acima:
edit:
CREATE TRIGGER trg_before_iu_email
BEFORE INSERT OR UPDATE ON email
FOR EACH ROW
EXECUTE PROCEDURE validar_email()

Comment: syntax error at or near "UPDATE", removendo o UPDATE roda...
Comment: tenta colocar BEFORE INSERT OR UPDATE e me confirma se deu certo, por favor
Comment: Aprovae então ^^
Comment: @Sorack Eu sei que esse post é um pouco antigo mas eu consigo aplicar essa ideia se eu tiver o seguinte cenário, possuo uma tabela 01 com colunas id_cliente e nome_cliente e a tabela 02 também com colunas id_cliente e nome_cliente, eu preciso que se eu alterar o registro da coluna nome_cliente na tabela 01 o registro que tiver o mesmo id_cliente na tabela 02 altere o registro nome_cliente também, é possível?
Comment: @R.Santos boa pergunta. Teria que dar uma pesquisada pra ver se você pode fazer alteração em outra tabela com `trigger` no `Postgres`. Mas você pode abrir uma pergunta e a gente dá uma olhada
Comment: Eu abri uma assim: https://pt.stackoverflow.com/questions/204026/trigger-que-atualize-registro-em-uma-tabela se por acaso tu achar alguma ideia eu te agradeço, não precisa ser necessariamente via trigger, se tu tiver qualquer ideia que eu possa fazer isso já é um caminho :)
Answer: Olá... @Sorack sim dá para fazer... sim...
somente coloque um Update dentro da trigger ex:
CREATE OR REPLACE FUNCTION public.func_before_update_c0220 ( )

RETURNS trigger AS $body$ begin

    if new.nome_cliente  <> old.nome_cliente then

       update public.table_02
          set nome_cliente  = new.nome_cliente
        where id_cliente = new.id_cliente;
           end if;

    return new;

end;
$body$
LANGUAGE 'plpgsql'

VOLATILE CALLED ON NULL

INPUT SECURITY INVOKER COST 100;

PostgreSQL Trigger apos update


Calculating matrix exponential for $n \times n$ Jordan block

Question: I want to calculate exponential of the matrix which on diagonal has some $a \in \mathbb{R}$ and ones above. The $n\times n$ matrix looks like following
$$ A = \left( \begin{matrix} a & 1 & 0 & 0 & \cdots & 0 \\ 0 & a & 1 & 0 & \cdots & 0 \\ 0 & 0 & a & 1 & 0 & 0 \\ 0 & 0 & 0 & a & \ddots & 0 \\ 0 & 0 & 0 & 0 & \ddots & 1 \\ 0 & 0 & 0 & 0 & 0 & a \end{matrix} \right) $$
I tried to do it by counting determinant of matrix $A-\lambda I$ by the following algorithm :

Divide last row by $a-\lambda$, so the $n$-th row is just $0$ and $1$ in the $n$-th column.
Subtract $(n-1)$-th row by $n$-th row. Then the $1$ in the $n$-th column and $n-1$ row disappears.
Divide $n-1$ row by $a-\lambda$, so the $(n-1)-$ th row is just $0$ and $1$ in the $(n-1)$-th column.

And so on so on. By algorithm above we get matrix with only ones at diagonal, so the determinant of that matrix is just $(a - \lambda)^n$. So we have $n$-th fold  eigenvalue equals to $\lambda$. I now I have a problem with derivation of eigenvectors of matrix $A$. Can you give me some advice? Is there any simplest way to calculate that?
Answer: Actually this matrix only has a one dimensional eigenspace, spanned by the first unit vector. This is an example of a 'Jordan'-block, you will find lots of theory if you google it.
Maybe a simpler way to calculate the matrix exponential is to write
\begin{align}
A=a\mathbb{I}+B
\end{align}
where $\mathbb{I}$ is the unit matrix and $B$ has only one's above the diagonal. Since $\mathbb{I}$ and $B$ commute, you get
\begin{align}
\exp(A)=\exp(a\mathbb{I})\cdot \exp(B)
\end{align}
Calculating the exponential of $a\mathbb{I}$ is straightforward and calculating the exponential of $B$ is also not too difficult, since $B$ is nilpotent, i.e $B^k=0$ for some appropriate $k$.
Comment: Okey, so calculating $aI$ is really simple. But B is a nilpotent matrix, but using your notation the $k$ that $B^k=0$ equals to $n$. $B^2$ is a matrix $B$ "moved by one unit" to right side, $B^3$ is moved by two etc. But it's nightmare to write this in formal way $n-th$ times. There is no other way that strictly calculation ?
Comment: I would simply prove by induction how the $k$-th power of $B$ looks like. I don't think that this calculation is a 'nightmare'.


How would we automate networking in a puppet environment?

Question: Our infrastructure: we run a puppet master for about 250 nodes (about 100 hardware servers). The OS on the nodes itself is fully puppetized.
Now we're looking into extending this puppet setup to the following domains:

IP/DHCP management
APC configuration
switch configuration (via SNMP, we have Arista switches)
inventory management (where is server x racked? how long does the warranty still work?)

Is there a software (opensource or not doesn't matter) that lets us achieve this?
I imagine it has a relational data schema like server or switch which can be filled out by web ui. Then, for each of those 4 points there are scripts to extract the data from the tables and push them to the devices.
right, why don't we just take puppet for this?
We'd love to, since we want to have all configuration in one place, but...
1+2 could be done in puppet, but for 250 nodes that looks like a hell of a big puppet manifest. Additionally we want to add VM provisioning via puppet foreman soon, so the "IP reservation system" needs to be "reactive" and hence IMO needs to be outside of puppet.
3 is probably not possible since the switches are not yet ready for puppet,
4 is probably possible with puppet when we'll add a "hardware" layer above the node-layer in puppet.
Any thoughts?
Comment: for number 3: http://puppetlabs.com/blog/puppet-network-device-management
Answer: AFAIK The Foreman already leads into the right direction, so maybe you should start to play with that.
Besides that take a look at Custom Facts. They are a powerful way to access all kinds of data and make it usable in Puppet manifests. E.g. create a custom fact like $::inventory_ipaddress or even overwrite the $::ipaddress fact with the canonical one to be used for configuration.
For 1: For a large number of hosts it is generally advisable not to have hundreds of node definitions, but rather have a set of roles and profiles.
The general design challenge here is to have a clear flow of information from single source(s) of truth to the provisioning.
For 2+3: you could use puppet to call all kinds of auxillary scripts and tools, but I doubt it is the best tool for the job, because it probably will not be the "source of truth".
For 4: This is somewhere in between. I myself use puppet on EC2 instances to periodically trigger a Zabbix inventory update and use facter to fill e.g. role, OS version, security groups. Caveat here: my normative source of truth is a provisioning tool and my puppet manifests where I can change settings; on the other hand this inventory is only the final outcome to verify results.
Answer: It is possible to configure Arista switches using Puppet running on the EOS operating system on the switch itself. Arista even provides an tutorial how to install Puppet themselves: Installing Puppet on EOS So that doesn't have to be a problem.
For the inventory tasks (IP's, locations, waranty) I would recommend Zabbix.


Plot Line Chart of Binary Variable Against Continuous Data

Question: I am looking for a way to help better visualize the relationship between a independent continuous variable and a binary response variable.
I am trying to understand how I can add a 2nd y axis to the existing plot I have below.  I want to get a sense of the response rate over different numerical ranges visually.

How can I add in the response percent at any given histogram bin?  For example if there were 10 observations in a bin and 2 were the positive class, then this would show a response of 20%.
Ideally it's possible that this  would be dynamic in that I might change the # of bins.  For instance, I have 10 here, I might want 20 the next time.
This would be a connected line-chart with the corresponding percentages from #1 on the right y axis.

Or in other words, I want a line chart of the positive class to be displayed as a line chart with % show in Y axis.
library(mlbench)
library(tidyverse)
data(Sonar)   ## from mlbench
library(ggplot2)

ggplot(Sonar, aes(x=V11, fill=Class)) +
  geom_histogram(col='black', bins = 10) +
  scale_fill_manual(values=c("purple", "green"))  +
  labs(title = "Count Left Y Axis; 'R' class percent of BIN in Right Y Axis" ,
       x = 'Variable Value in this case V33', y ='Count of Observations' )

Answer: Not sure if this is what you are after but the description you gave sounded very similar to a conditional density plot.
ggplot probably has an alternative to this, but with base R:
cdplot(Class ~ V1, Sonar, col=c("cornflowerblue", "orange"), main="Conditional density plot")

And the result:
Comment: Yes, sorry ultimately I'm trying to plot continuous vs a categorical (binary) response.  I'd like to see the percent positive of this response over various numerical ranges.   This is in-line with that idea and helpful, but I'd like to be able to see the actual percentage of 'R' at any given numerical range of V1 in a cleaner way.  It's also helpful to have some sense of the distribution of V1 or the frequency of V1 which this plots masks.


Interpretando código com classes empacotadas

Question: Tenho 3 classes no pacote com\scja\exam\planetas. Tenho também uma classe com método main no pacote com\scja\exam\teste. O método main é responsável por imprimir o nome dos planetas.
Compilei normalmente da seguinte forma:
C:\Users\marci_000\Documents\OCA\exercicios>javac -d bin -cp .\src\com\scja\exam\planetas\*.java .\src\com\scja\exam\teste\ImprimePlaneta.java

Mas ao executar o comando java, para interpretar, está surgindo a seguinte mensagem:
Erro: Não foi possível localizar nem carregar a classe principal .\bin\com\scja\exam\teste\ImprimePlaneta

O comando utilizado para interpretar é o seguinte:
C:\Users\marci_000\Documents\OCA\exercicios>java -cp .\bin\com\scja\exam\planetas .\bin\com\scja\exam\teste\ImprimePlaneta

Verifiquei as variáveis de ambiente e estão ok. E este erro só ocorre quando estou compilando classes empacotadas. Para classes não empacotadas executa normalmente
Comment: Possível duplicata de [Comando javac com mais de uma classe empacotada](http://pt.stackoverflow.com/questions/185887/comando-javac-com-mais-de-uma-classe-empacotada)
Comment: Você chegou a ler as outras repostas? Me parece que essa duvida já foi respondida na outra pergunta sua.
Comment: Oi @diegofm, perdão, não tinha visto a pergunta duplicada quando respondi. Ainda que a pergunta agora, do ponto de vista da OP esteja do lado do `java` ao invés do `javac` acabei repetindo muita coisa que foi respondida na outra pergunta. De qualquer forma vou deixar a resposta aqui por enquanto já que lá ela estaria ligeiramente descontextualizada.
Answer: Sobre a compilação
A primeira coisa que você tem que ter em mente é que src não faz parte da estrutura de pacotes, ele é apenas o diretório base que contém o código fonte da aplicação.
javac -d bin src\com\scja\exam\planetas\*.java src\com\scja\exam\teste\ImprimePlaneta.java

O diretório src é um excelente candidato para entrar na lista de caminhos em que o javac procura código fonte durante a compilação. Essa lista é o sourcepath.
A vantagem de usar o sourcepath é que, sabendo onde estão os fontes, o javac é esperto o suficiente para encontrar e compilar transitivamente todos os arquivos .java necessários para fazer ImprimePlaneta funcionar. Por exemplo, se ImprimePlaneta possui um import:
import com.scja.exam.planetas.PlanetaEnum;

O javac sabe encontrar o arquivo PlanetaEnum.java no diretório com\scja\exam\planetas dentro de algumas das entradas do sourcepath:
Ou seja, podemos simplificar a compilação para:
javac -d bin -sourcepath src src\com\scja\exam\teste\ImprimePlaneta.java

Se o sourcepath não foi específicado o javac usa o valor de classpath como sourcepath. Logo, também é possível usar a variação abaixo:
javac -d bin -cp src src\com\scja\exam\teste\ImprimePlaneta.java

Dito isso é importante notar que -cp é utilizado para disponibilizar arquivos .class para a aplicação. Ainda que um bom projeto por convenção não tenha nenhum arquivo .class na pasta src, vale a pena deixar a intenção de buscar apenas arquivos de código fonte explícita utilizando  -sourcepath.
Terminada a compilação você terá um diretório bin com uma estrutura parecida com a seguinte:
bin
└───com
    └───scja
        └───exam
            ├───planetas
            │       PlanetaEnum.class
            │
            └───teste
                    ImprimePlaneta.class

Executando a aplicação
Veja que o diretório bin é uma contrapartida de src. Conforme vimos o -cp pode ser utilizado para especificar caminhos em que a aplicação busca por unidades compiladas. Logo a maneira correta de rodar a sua aplicação a partir do diretório exercicios é:
java -cp bin com.scja.exam.teste.ImprimePlaneta

Note que o comando java recebe o nome qualificado da classe que deve ser executada. Isso faz sentido pois a classe poderia, por exemplo, estar dentro de um jar.
Como no exemplo do javac o comando java é inteligente o suficiente para encontrar as classes utilizadas por ImprimePlaneta no classpath.
Comment: Obrigada pela ajuda. Consegui executar meu código. Eu estava usando barra, e no caso teria que usar a seguinte estrutura.java -cp bin com.scja.exam.teste.ImprimePlaneta. Valeu pela dica
Comment: Oi Marcia, tudo bem? Fico feliz em ter ajudado, aqui no Stack Overflow sinalizamos boas respostas com votos positivos, a resposta que resolveu seu problema pode ser marcada como correta.


Power of a number in the difference of two factorials

Question: What is the highest power of 3 available in  $58! - 38!$ ( ! stands for factorial)
I can take $38!$  out as common to get $38! ( \frac{58!}{38!} - 1).$
I know how to find out the power of 3 in $38!$ But it is the difference term inside the brackets which I am not able to handle. What power of 3 will be contained in that term?
Is my approach correct in the first place? If yes then how to proceed further and if not then what approach should I take.
Answer: Hint: $$\frac{58!}{38!} = 3\cdot 13\cdot\frac{58!}{39!}.$$
Comment: Absolutely. ${}$
Comment: Let's see if I have got it right. The expression essentially becomes 38!*( 3n-1) where n is any integer. But 3n-1 cannot contain any power of 3 so the only power of 3 in the whole expression will be contained in 38!. 38! contains 17 powers of 3 so that is the power of 3 in the whole expression.


Remove PDF pages with IText causes new output hash each time

Question: I´m working with a code like this to remove certain pages from a pdf file.
PdfReader reader = new PdfReader(src);
reader.selectPages("1,2");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.close();

My problem is that everytime I run this (same input file, same pages), the output file has distinct hash (Using md = MessageDigest.getInstance("SHA1"))
I need something like this
inputFile.pdf (hash_A)
selectPages("1,2")
outputFile.pdf (hash_B)

inputFile.pdf (hash_A)
selectPages("1,2")
outputFile.pdf (hash_B)

but I get this
inputFile.pdf (hash_A)
selectPages("1,2")
outputFile.pdf (hash_B)

inputFile.pdf (hash_A)
selectPages("1,2")
outputFile.pdf (hash_C)

inputFile.pdf (hash_A)
selectPages("1,2")
outputFile.pdf (hash_D)

Code
public String quitarPagBlancasPDF(String origen, String destino, int blankPdfsize) {
        try {

            com.itextpdf.text.pdf.PdfReader r = new com.itextpdf.text.pdf.PdfReader(origen);
            String paginas = "";
            boolean editado = false;

            for (int i = 1; i <= r.getNumberOfPages(); i++) {
                byte bContent[] = r.getPageContent(i);
                if (bContent.length > blankPdfsize) {
                    paginas += String.valueOf(i) + ",";
                } else {
                    editado = true;
                }

            }

            if (editado) {
                r.selectPages(paginas);
                PdfStamper stamper = new PdfStamper(r, new FileOutputStream(destino));
                stamper.setFullCompression();

                stamper.close();
                stamper = null;
                r = null;
            } else {
                r = null;

                return "Sin Cambios";
            }
        } catch (Exception e) {
            return e.getMessage();
        }
        return "OK";
    }

Comment: Pdfs contain information on the date and time when a document was last changed and a unique ID. Both factors will result in different hash values all the time.
Comment: Possible duplicate of [Remove page from PDF](https://stackoverflow.com/questions/7312824/remove-page-from-pdf)
Answer: Finalmente decidí armar un hash con el contenido de cada página del PDF para ver si dos pdf's son iguales
 public static String getPdfSha(String origen, String metodo) {
        try {

            com.itextpdf.text.pdf.PdfReader r = new com.itextpdf.text.pdf.PdfReader(origen);
            String Sha = "";

            for (int i = 1; i <= r.getNumberOfPages(); i++) {
                byte bContent[] = r.getPageContent(i);
                Sha = Sha + Arrays.toString(bContent);
            }
            Sha = encriptar(Sha, metodo);
            return Sha;

        } catch (Exception e) {
            return "";
        }
    }

public static String encriptar(String texto, String algoritmo) {
String sha;
try {
    java.security.MessageDigest md = java.security.MessageDigest.getInstance(algoritmo);
    byte[] hash = md.digest(texto.getBytes());
    java.util.Formatter formatter = new java.util.Formatter();
    for (byte b : hash) {
        formatter.format("%02x", b);
    }
    sha = formatter.toString();
    formatter = null;
    hash = null;
    md = null;

} catch (java.security.NoSuchAlgorithmException e) {
    return "";

}
return sha;

}
Comment: **A** English, please. **B** your hash now only considers immediate page content instructions. Does that really suffice for your task? There is much more in a pdf than that.


iOS 11 public beta 9 : UITextField textcolor can't be changed when no keyboard

Question: I am developing an app which required to change text colour of UITextfield.
I wrote following code for it.
<code>-(IBAction)changedSegment:(UISegmentedControl *)segment{
    UIColor *color = arrColors[segment.selectedSegmentIndex];
    txtDemo.textColor = color;
}
</code>
It is working fine in iOS 10. But in iOS 11 beta 9, when keyboard is hidden (resigned from responder), text color can't be changed.
Answer: Just add
<code>[txtDemo setNeedsLayout];
</code>
Comment: This workaround did the trick for me:  txtDemo.text = txtDemo.text.
Comment: @AgentChocks: I assume it is an Apple bug or their attempt at a performance optimization.
Comment: I tried it my friend. But didn't work. So, for solution, I call becomeFirstResponder() before color change. then resignFromResponder() after it.
Comment: @lifjoy thanks for the workaround it helped, but do you know why this happens?
Comment: I also discovered this problem, tried Arek's suggestion (didn't work) and then @lifjoy's suggestion, which did work.


PHP upgraded to 5.3.8 - Can't install/upgrade extensions

Question: I managed to upgrade php from 5.2.10 to 5.3.8 in CentOS 5.4. Some of the extensions were lost in the process (mbstring, mysql).
One quick run for:
yum list installed | grep php

Returns:

php.x86_64
php-cli.x86_64
php-common.x86_64
php-pear.noarch
php-pecl-igbinary.x86_64
php-pecl-memcached.x86_64

When I try to install new extensions:
yum install php-mbstring

I get this error message:

Transaction Summary
  ================================================================================ Install       3 Package(s) Upgrade       0 Package(s)
Total size: 3.6 M Is this ok [y/N]: y Downloading Packages: Running
  rpm_check_debug Running Transaction Test Finished Transaction Test
Transaction Check Error:   package
  php-common-5.3.8-5.el5.remi.1.x86_64 (which is newer than
  php-common-5.2.10-1.el5.centos.i386) is already installed   file
  /etc/php.ini from install of php-common-5.2.10-1.el5.centos.i386
  conflicts with file from package php-common-5.3.8-5.el5.remi.1.x86_64

Practically the same happens with yum install php-mysql
How do I get rid of those old versions?
Answer: I guess that the remi repo is disabled by the default, verify with yum repolist or grep enabled /etc/yum.repos.d/remi.repo. When you install php-mbstring, it is pulling from base repo. So, try this:
# yum --enablerepo=remi install php-mbstring


How to send headers from HTML / UI in an API request to server?

Question: I want to add HTTP headers on every request from client. Not able to figure out how.
Had tried to add following script to HTML to set headers like:

Comment: Can you add the code of the javascript request. Something like $.ajax({ url: '....' })
Comment: I am using only what i wrote probaby i am missing smoething
Answer: You can only add headers while making an API call from AJax or other API request modules  for client-side and not via submiting <form> and adding action to your <form>
Via Ajax call you can do something like this:

You need to call this function in place of using
<form action="submitAPI" method="POST"><input type="submit" value="Submit" /></form>
Use this:
<form><input onclick="submitForm()" value="Submit" /></form>


SQL query that returns the best match (row that has the most matching columns)

Question: My database looks like this:
<code>id | A | B | C | D
</code>
and for each letter, there's a random value between 0 and 3.
These values change for each ID.
How can i select the row that has the most matching columns, even if it is not a perfect match?
(This shows exactly what i mean:)
http://prnt.sc/elkyzn
I hope this picture helps,
I need to create a 15 questions quiz that matches a dog for you.
each question of the 15 returns a value from 0 to 3, and then there are 11 yes or no questions (0 = no and 1 = yes)
at the end of the quiz, i get something like this: (changes from pereson to person) 0-3, 0-4, 0-2, 0-2, 0/1, 0/1, 0/1, 0/1, 0/1, 0/1, 0/1, 0/1, 0/1, 0/1, 0/1.
and i need to collect these values and get the best match, the dog that has the most matching columns.
Comment: Edit your question and provide sample data and desired results.  It is rather unclear.  Also, tag with the database you are using.
Comment: You'll probably be looking at `select id from tablename order by sum((A=1) + (B=1) + (C=1) + (D=1)) desc limit 1` (find row with most 1s, in this example)
Comment: `How can i select the row that has the most matching columns` If one row have "0" in all columns, and another row have "1" in all columns, then which one row do you want to select ? both ?
Comment: http://prnt.sc/elkyzn

I hope this picture helps,
I need to create a 15 questions quiz that matches a dog for you.
each question of the 15 returns a value from 0 to 3, and then there are 11 yes or no questions (0 = no and 1 = yes)

in the end of the quiz, i get something like this: (changes from pereson to person) 0-3, 0-4, 0-2, 0-2, 0/1, 0/1, 0/1, 0/1, 0/1, 0/1, 0/1, 0/1, 0/1, 0/1, 0/1.

and i need to collect these values and get the best match, the dog that has the most matching columns.

hope i was clear this time, and thank you for answering!
Answer: I think you need to come with a scoring system because you aren't looking for an exact match. An example of an idea would be.
Select  Id from
{
Select A -B, A-C, A-D, B-C, B-D, C-D, id
From table
}  Outer
Where (use some logic here to determine what you think fits)
One idea is to sum up all the differences from the inner query. But, that could give false results if you have one that's really big and one that real small.
You could also do AVG of the sum of all of the differences.
The other thing you could do is to order by columns in the inner query where the difference is 0. Order by case when 0 else 1 end.
Or a combination.
It really depends on what exactly your trying to get
Comment: http://prnt.sc/elkyzn

I hope this picture helps,
I need to create a 15 questions quiz that matches a dog for you.
each question of the 15 returns a value from 0 to 3, and then there are 11 yes or no questions (0 = no and 1 = yes)

at the end of the quiz, i get something like this: (changes from pereson to person) 0-3, 0-4, 0-2, 0-2, 0/1, 0/1, 0/1, 0/1, 0/1, 0/1, 0/1, 0/1, 0/1, 0/1, 0/1.

and i need to collect these values and get the best match, the dog that has the most matching columns.

hope i explained myself better, and thank you for answering!
Answer: you can select all the elements that have the sum of the columns the same as the sum from input
then you can foreach through them and see the matches, and keep a variable "$best" which you will updated when you fill find an element with more matches
Comment: actually, if you won'y have thousands of entries in your database you can fetch all the data and simply keep that $best
Comment: what do you mean lessan?
Comment: that thing with the sum, now i realised its not a good ideea, because you may have cases when only one column is matched, so you have to select all the entries with column_sum<=input_sum but considering how few elements this eliminates, its not worth, i think its faster to simply select all of your elements and foreach through them looking for matches
Comment: but that depends on how many entries you can have in your database, how many columns etc. for like 1500 elements with 4 columns, the fastest way would be to simply select all the data
Comment: I hope that you saw that i updated the main thread with more detail, including my database.

i still dont get it - if i did that, how could i store the data in a var? i'd have to check for each column which row matches it, and then display the row that was returned the most?

could you give me a code example for the first 2 columns? http://prnt.sc/elkyzn

thanks again for answering


Fire UILocalNotification every day, but everyday at a specific time

Question: I want to fire UILocalNotification's for 8 days long, but everyday I want to fire them on a different specific time. So e.g.:
Day 1: fire notification at 11:00 and 12:00
Day 2: fire notification at 12:00 and 14:00
Day 3: fire notification at 13:00 and 16:00
Day 4: fire notification at 14:00 and 18:00
Day 5: fire notification at 16:00
Day 6: fire notification at 18:00
Day 7: fire notification at 18:00
Day 8: fire notification at 18:00
(The times are just examples)
I've already been doing things with repeatInterval, but that's probably not the thing;
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar] ;
NSDate *now = [NSDate date];
NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:now];
[components setHour:22];
[components setMinute:15];

UILocalNotification *notification1 = [[UILocalNotification alloc]init];
notification1.fireDate = [calendar dateFromComponents:components];
notification1.repeatInterval = NSDayCalendarUnit;
[notification1 setAlertBody:@"Test notification"];

[[UIApplication sharedApplication] scheduleLocalNotification:notification1];

Comment: What do you except from us? Code? Why should we give you code for free? We'll help you if you have problem, but not this way. [ask]
Answer: No, you can't. The -repeatInterval property can be used to repeat a notification at specific unit(day,week...) at the same time. Furthermore you can't set more than 64 notif per app. what you can do is set your notifications with different times with a
repeatInterval on a week unit.


arrays/lists and their dimensions

Question: I have a problem analysing the following code:
 for (int argI = 1; argI < args_.size(); ++argI) //size(): Return the number of
 {                                       //arguments.
      argListString += ' ';         //Space into string
      argListString += args_[argI]; //new argument into string

      if (args_[argI][0] == '-')    // ????
      {
           const char *optionName = &args_[argI][1];   //????

My problem are the lines marked with ????. When I look up the object args_ it ist of type stringList and stringList is templateclass of List<T>. List<T> ist defined as
Template<class T>
class Foam::List< T >
A 1D array of objects of type <T>, where the size of the vector is known and used for subscript bounds checking, etc. Storage is allocated on free-store during
construction.

So if args_ is a 1D array why is it accessed like a 2D array in line 415 and 417?
greetings
streight
Answer: It is an vector/list of strings. Strings are a sequence of chars. Thus the index operator( [] ) will likely provide access to the single chars of the string.
415 therefor checks the first char of the string and 417 accesses the substring from the second char to the end.
Comment: It returns the address of the second char. A c string is basically an array of chars (multiply chars in a row with a NULL-char at the end ('\0')). Therefor a c string `char* foo` is nothing more than a pointer to one element of this array. Thus you can always add an offset (e.g `foo + 4`) to acquire a substring (because your just moving forward in that sequence of chars). Im not quite sure, how they retain the original relation to the c string in the [] operator here, but my guess is, that they return a `const char &`.
Comment: Ok, just one more question: With the operator & in line 417 I generally should get the adress of a object. So, do I get here the adress of the second char?
Answer: Presumably, args_[argI] is a string type, and the string type overloads [] to access the characters within the string.
So this looks for options of the form -flibble; the first marked line checks whether the argument begins with -, and the second sets optionName to point to flibble.
Answer: You have a one-dimensional vector args_ where each element is of type T. Now, it would seem that this type T is a string (either a string type or a pointer to a C-style string) the elements of which can be accessed using the index operator [].
As such, it is not actually "accessed like a 2D array". Instead, each item is accessed as a one-dimensional array and the resulting object is in turned indexed.
So, assuming T is char* (which makes sense for text strings), this would make args_[argI] an element of type char* which is a pointer to a string. This string is then indexed as an array, so that args_[argsI][1] refers to the second character in the argIth string in the vector called args_.

arrays/lists and their dimensions