Facebook error 210 "User not visible"

Question: [php]
I've got an error "User not visible" with error code 210 as response while publishing content on friends wall via application.
:::Scenario is as follow:::
User1 authorized my application with all the required permission ( including publish_stream and offline_access ) and now I am trying to post on User1's friends wall...
At this time it gives me the error. I am using old rest API
$facebook->api_client->stream_publish($message,$attachment,$actionLink,$invV);
Help please!!!
Answer: Your app may not have permission to post on the given friend's wall.
When a user authorizes your app, they give you permissions to act on their behalf.
This permission does not ensure that you can always post on friends' walls, just as the user may not be able to post on the wall using the UI.
Answer: I also got this error because I was using a Facebook Test User account when playing around with my app.
Answer: Assuming you do have "publish_stream" permissions, this occurs when you try to post to a wall, who is not friends w/ the user you are posting as.
Make sure there is a friends relationship between the two users, before posting to the others wall.
Answer: It also appears when user is not allowing post on his wall( from Facebook setting).if is the case You should notify to user that "This user has privacy setting to himself only"
Comment: You can check that using FQL, querying the user.can_post attribute <- https://developers.facebook.com/docs/reference/fql/user/
Answer: I had this exact issue when having restricted usage of the Facebook app to a specific country. When trying to use the app from another country, I got an error.
Country Restrictions are available on https://developers.facebook.com/apps/ > Settings > Advanced.
Answer:
Facebook support has answered this question:
This error is returned when the posting user (A) does not have sufficient permission to post on User B's wall. This would be a privacy setting by user B and outside the control of User A or your app.

Facebook error 210 "User not visible"


DAX: How to check if (All) value selected for specific Dimension

Question: I have a task to convert existing MDX measures (from multidimensional model) into DAX (tabular model).
There is a part of code which I'm doing right now:

IIF(
 [Product].[Status].Level IS [Product].[Status].[(All)]
AND
[Product].[Brand].Level IS [Product].[Brand].[(All)]
AND
[Product].[Category].Level IS [Product].[Category].[(All)]
,[Measures].[Full_Amount]
,NULL
)

How can I do the same on DAX?
The problem is to check that .[(All)] member is selected. Do we have the same option n DAX?
Comment: Check DAX functions ISFILTERED and ISCROSSFILTERED. Absense of filters is equivalent to ALL.
Answer: As @RADO mentions you can do something like this in DAX:
IF(
   NOT ISFILTERED( Product[Status] )
   && NOT ISFILTERED( Product[Brand] )
   && NOT ISFILTERED( Product[Category] ),
  [Measures].[Full_Amount],
  BLANK()
)


How to save excel file to amazon s3 from python or ruby

Question: Is it possible to create a new excel spreadsheet file and save it to an Amazon S3 bucket without first saving to a local filesystem?
For example, I have a Ruby on Rails web application which now generates Excel spreadsheets using the write_xlsx gem and saving it to the server's local file system.  Internally, it looks like the gem is using Ruby's IO.copy_stream when it saves the spreadsheet.  I'm not sure this will work if moving to Heroku and S3.
Has anyone done this before using Ruby or even Python?
Answer: I found this earlier question, Heroku + ephemeral filesystem + AWS S3.  So, it would seem this is not possible using Heroku.  Theoretically, it would be possible using a service which allows adding an Amazon EBS.
Answer: You have dedicated Ruby Gem to help you moving file to Amazon S3:
https://rubygems.org/gems/aws-s3
If you want more details about the implementation, here is the git repository. The documentation on the page is very complete, and explain how to move file to S3. Hope it helps.
Once your xls file is created, the library helps you create a S3Objects and store it into a Bucket (which you can also create with the library).
S3Object.store('keyOfYourData', open('nameOfExcelFile.xls'), 'bucketName')

If you want more choice, Amazon also delivered an official Gem for this purpose: https://rubygems.org/gems/aws-sdk
Comment: Okay, but from my understanding of Heroku, the excel file cannot be saved to the file system. Using the write_xlsx gem, closing the workbook saves the file to disk. How can this be accomplished using Heroku and S3?


Deriving a particular form of Stirling's Approximation of the Gamma function?

Question: I am working from some notes concerning bounds on Dedekind zeta functions and am trying to derive a supposed version of Stirling's approximation contained therein:

Let $\sigma$ be fixed and $|t|\rightarrow \infty$, then a version of Stirling's approximation formula yields
  $$|\Gamma(\sigma+it)| \sim |t|^{\sigma-\tfrac{1}{2}}e^{-\tfrac{\pi}{2}|t|}\ll |t|^{\sigma-\tfrac{1}{2}}e^{-|t|}$$
  where we define
  $$f(z)\ll g(z) \text{ iff } \exists c\in \mathbb{R}: \exists z_0\in \mathbb{C}: \forall |z|>|z_0|: |f(z)|<c|g(z)|$$

I started working from what appears to be the standard rendering of Stirling:
$$\Gamma(s)=\frac{\sqrt{2\pi}s^{s-\frac{1}{2}}}{e^s}\big(1+O(\tfrac{1}{s})\big) \qquad \underset{\text{Since }O\big(\tfrac{1}{s}\big)\ll \tfrac{1}{s} \text{ by definition}}{\Rightarrow} \qquad \Gamma(s)\ll \Big|\frac{\sqrt{2\pi}s^{s-\frac{1}{2}}}{e^s}\Big|\cdot (1+|\tfrac{1}{s}|)$$
But making the relevant substitutions, shuffling things around, and ignoring the negligible contribution of $\sigma$ to the modulus when applicable, I have only been able to find
$$|\Gamma(\sigma+it)|\ll |t|^{\sigma-\tfrac{1}{2}}+|t|^{\sigma-\tfrac{3}{2}}$$
Comment: There should indeed be a decay behavior for large $t$, for example $|\Gamma(10+100i)|$ is less than $10^{-48}$. Intuitively this is caused by cancellations in the integral defining $\Gamma(\sigma+it)$ when $|t| \gg \sigma$.
Comment: @Ian I see what you mean and have edited the question. I will update if I find the answer you hint at.
Comment: It comes from $z^z=\exp(z \log(z))$. When $|t/\sigma|$ is large, $\log(z)$ has imaginary part close to $\pm \pi/2$ (with the same sign as $t$ has), so $z^z$ has a modulus not much bigger than $e^{-\pi/2 |t|}$.
Comment: @Ian Ah, thank you! If you care to write your comment in answer form I will mark it as accepted and upvote.
Answer: The decay comes from $z^z=\exp(z \log(z))$. When $|t/\sigma|$ is large, $\log(z)$ has imaginary part close to $\operatorname{sign}(t) \pi/2$, so that the real part of the exponent behaves like $\sigma \log(\sigma) - \pi/2 |t|$ which is dominated by the second term, giving the decay.


Why does my class std::vector member always throw a segfault?

Question: I've searched endlessly on SE for a logical explanation for why this is happening.  It is probably something very simple that I've overlooked, however I cannot spot it and would really appreciate some assistance with this.
Last week I implemented a class to read the output of a system call from a .ini file and then find and store the required information into custom objects that are then stored in a vector inside a Config class.  It is a Singleton config class storing a unique_ptr for each instance of my custom class that is created.
The thing is, when I implemented this last week on my laptop, I had zero issues reading and writing to my member vector and was able to get it working exactly how I needed it.  Since pulling to my desktop computer, this vector, and any STL container that I use as a member of my class, throws a segmentation fault when I try to do anything on it, even get it's size.
I've tried to shorten the code below to only include sections that actually use this vector.  I have replaced my config with A, and custom class with T, and no matter where I try to use my member container, or any other test STL containers that I add to the class, I get a segfault.
For the record, I am using Qt with C++11.
Update: This example breaks on line 50 of c.cpp when debugging, and anywhere that tries to call the vector.
Debug points to this line in stl_vector.h
  // [188.8.131.52] capacity
      /**  Returns the number of elements in the %vector.  */
      size_type
      size() const _GLIBCXX_NOEXCEPT
      /*-> this line */ { return size_type(this->_M_impl._M_finish - this->_M_impl._M_start); }

main.cpp
#include "c.h"

int main(int argc, char *argv[])
{

    C *c = C::getInstance();

    delete c;

    return 0;
}

t.h - Class stores information from file
#include <string>

class T
{
public:
    T();

    bool Active();

    std::string getA();
    void setA(std::string);

private:

    std::string a;
};

t.cpp
#include "t.h"

T::T()
{

}

bool T::Active()
{
    if(a == "")
    {
        return false;
    }
    return true;
}

std::string T::getA()
{
    return this->a;
}

void T::setA(std::string newa)
{
    this->a = newa;
}

c.h - Class stores T objects and parses file for information
#include "t.h"
#include <QDebug>
#include <vector>
#include <algorithm>
#include <iostream>
#include <memory>
#include <sstream>
#include <fstream>

class C
{
public:

    static C* getInstance();

private:
    C();

    static C* instance;
    static bool init;

    std::vector<std::unique_ptr<T>> t_list;
    void readLines(const std::string&);
};

c.cpp
#include "c.h"

bool C::init = false;
C* C::instance = nullptr;

C::C()
{
    system("echo this is a test command > a.ini");
    instance->readLines("a.ini");
}

C* C::getInstance()
{
    if(!init)
    {
        instance = new C;
        init = true;
    }
    return instance;
}

void C::readLines(const std::string &path)
{
    T* new_t;
    std::ifstream file(path.c_str());

    if(!file.is_open())
    {
        qDebug() << "Unable to open " << path.c_str();
    }

    std::ofstream o("test.txt");
    std::string line;
    while(std::getline(file, line))
    {
        // Split string before searching
        std::stringstream ss(line);
        std::string seg;
        std::vector<std::string> split;
        std::string left, right;

        // Search patterns
        size_t find_a = line.find("a");

        size_t del = line.find(':');

        if(find_a != std::string::npos)
        {

            o << "test_Size: " << t_list.size() << std::endl;

            if(new_t->Active())
            {
                T* temp = new_t;
                std::unique_ptr<T> move_t(temp);
                t_list.push_back(std::move(move_t));
            }

            o << "test: " << t_list.size() << std::endl;

            std::string n;

            // Check if previous ahas any null elements

            // Split string to find a
            n = line.substr(line.find("a "));
            n = n.substr(n.find(" ", +2));

            new_t->setA(n);

        }

        else
        {
            continue;
        }
    }

    // Add last a
    T* t = new_t;
    std::unique_ptr<T> move_t(t);
    //t_list.push_back(std::move(move_t));

    o << "a: " << t_list.back().get()->getA() << std::endl;
    o << t_list.size() << std::endl;

    o.close();
    file.close();

}

Comment: "I've tried to shorten the code below to only include sections that actually use this vector." -- this accomplishes nothing useful. Just because your code crashes while it does something with a vector doesn't mean that there's a bug with how the code uses a vector. C++ does not work this way. The bug can be anywhere in your program, which is why a [mcve], as explained in stackoverflow.com's [help], is required in order for anyone to be able to reproduce your problem. Unless someone can copy exactly the shown code in your [mcve], and observe the same bug, it's unlikely that anyone can help you.
Comment: I think wintermute's answer is relevant.   Also, no need to use `std::move()` for the argument of `push_back()`..
Comment: What's an `Adapter`? What's `T`?
Comment: @SamVarshavchik I removed redundant code that repeats the logic in the readLines function to find "a", it is minimal and complete since getInstance is the only point of entry from my main function.  If you want me to include the class T then I will, however it makes literally no appearance up to the point at which this error occurs, if I try to access the vector in the constructor of T it still happens.
Comment: @Tas I've edited it now since that was an accident, T is the class that contains the information read in from the .ini file and is then stored in a unique_ptr and moved to the vector.
Comment: The nature of undefined behaviour is that code which causes a crash is not necessarily the code where a crash occurs.   For example, one section of code might do an invalid operation with a pointer (undefined behaviour).  The actual consequence of that is overwriting some area of memory that is used by completely unrelated code.   Some time later, that unrelated code is executed, and the overwritten memory is used in a calculation, and then results in a crash.   That's why it is necessary to provide a [mcve].  Just presenting the code where the crash occurs does not help find the cause.
Comment: @Peter I've now changed it.  The code I originally put up excluded the T class that the vector was storing, but it is irrelevant in regards to the error itself.  The error is caused by the vector and the C object (not clang) that is accessing it, everything that happens here is happening inside the C class, the getInstance() method is called from main, which triggers this logic.  Providing the full implementation which I've now done won't affect the error, it will however allow you to debug it if you wish to help me and so I've included it now, thanks in advance if you do :)
Comment: Compiler say "warning: 'new_t' may be used uninitialized in this function" and highlights: `if(new_t->Active())`. Never ignore compiler warnings until after you have justified them. They are your first line of defence against trivial (and sometimes not so trivial) logic errors. Anyway, you are still putting garbage in the `vector`.
Comment: style note: the `_t` suffix is often used to denote a datatype, so using this for the name of anything else may result in confusion among readers.
Comment: @user4581301 Thanks, noted.  Even after adding the initialisation it doesn't stop the error.  It is any action that calls the vector which is causing the exception, none this is even before new_t gets added.
Comment: @Peter I modified my code according to his comment, however the issue has nothing to do with the data types being stored, the problem arises when I try to access a member variable from within the class, in this case it is a vector.  There is no other class or method trying to access this vector, removing mentions of the vector fixes the issue, using local variables fixes the issue.  I  cannot access members without a segfault and that is what I need to be doing.
Comment: Please update the code with how you are initializing `new_t` and any other modifications you made. There is still plenty of room for crouching tigers and hidden dragons. There are almost countless ways pointers can get messed up, smart or not. Wintermute's suggestion of ditching them entirely is highly recommended.
Comment: By the way, it looks like `C` is a lazy-loaded singleton. The first answer to [C++ Singleton design pattern](https://stackoverflow.com/questions/1008019/c-singleton-design-pattern) gives a rundown on the Meyers Singleton, a much easier and safer (even thread-safe in C++11 or later) way to write one. Note zero pointers are involved.
Comment: `new_t` is obviously being used before it is initialized. Kaboom! There's your bug.
Comment: @SamVarshavchik That's not the cause of this bug, I've said this already:

The issue has nothing to do with the data types being stored.  Remove any instance of an object being added and simply call the vector from anywhere, including .size() inside the constructor and it segfaults.  I have said this a few times and yet everyone is still focusing on the way I'm using my T class.
Comment: The only thing anyone can comment on is the code that's shown. As shown, this is dereferencing an initialized pointer, undefined behavior, and a bug. Nobody knows, except you, what other changes were made with the alleged crash still allegedly still occurring, and because of that nothing further can be said about it.
Comment: @SamVarshavchik Well you're obviously not one of those trying to help and hence didn't bother debugging it, since you'd have noticed the problem lies in any call to the vector, even before I try to add new_t to it, it is written into the example too so you don't really have an excuse there.

Also it turns out that you were wrong anyway, something further was said about it and I managed to fix the problem without even touching new_t, but thanks for offering no help and simply criticising the way I wrote my post, it's good to know that some people are here to not help others.
Answer: UPDATE after code change:
I see two things now: One is that new_t in C::readlines is never initialized, so this could break when new_t->Active() is called a bit later in the function. However, I believe that the main problem you're running into is in C::C(), where it says
instance->readLines("a.ini");

At this point in the execution, C::instance is not yet initialized -- you're only just constructing the object that would later be assigned to it. Because of this, this in the readlines call is invalid, and any attempt to access object members will cause UB. This latter problem can be fixed by just calling
readLines("a.ini");

in which case the currently constructed object (that will later be instance) is used for this. I have no idea what you want to happen for the first, though, so all I can say is: If you want to have a vector<unique_ptr<T>>, you will have to create objects of type T with either new T() or (arguably preferrably) std::make_unique<T>() and put them in there.
I'll also say that this is a rather ugly way to implement a singleton in C++. I mean, singletons are never really pretty, but if you're going to do it in C++, the usual way is something like the accepted answer of C++ Singleton design pattern .
Old answer:
The problem (if it is the only one, which I cannot verify because you didn't provide an MCVE) is in the lines
T move_t = new_T;
std::unique_ptr<Adapter> ptr_t(&move_t); // <-- particularly this one

m_ts.push_back(std::move(ptr_t));

You're passing a pointer to a local object into a std::unique_ptr, but the whole purpose of std::unique_ptr is to handle objects allocated with new to avoid memory leaks. Not only will the pointer you pass into it be invalid once the scope surrounding this declaration is left, even if that weren't the case the unique_ptr would attempt to delete an object that's not on the heap at the end of its lifecycle. Both problems cause undefined behavior.
To me, it looks as though you really want to use a std::vector<T> instead of std::vector<std::unique_ptr<T>>, but that's a design issue you'll have to answer yourself.
Comment: @MattIan Once you cause undefined behavior, anything can happen.
Comment: @Wintermute I have tried refactoring to store the objects themselves, and also pointers to the objects, I have also tried a test vector and then adding numbers in both the initializer list and the constructor, they all cause a segfault.  I believe it is something above specifically using the vector itself but I don't know what.
Comment: It is possible that there are other bugs in the code, but I have no way of knowing that. My advice is to run the code in a debugger to see where it breaks and in what state the objects involved are. It can also help to run the code in valgrind or to pass various `-fsanitize=stuff` or `-fstack-protector` options to the compiler. In order for me to help you here, however, you'll have to trim the code down to a minimal example that I can just copy&paste out of my browser and throw into a compiler and debugger. It's entirely possible that in doing so you'll find the error yourself, too.
Comment: @Wintermute You should be able to copy and paste it now, it gets the same error and points to the same line in st_vector.h as before.
Comment: @Wintermute I was going to write an answer to my own question last night, but I didn't get a chance to do so.

For the record, I did try not using this->instance and it still threw the segfault.  I managed to fix it by writing a public function read() and calling it from a separate class, since for this implementation that is where this object will be kept anyway.
Comment: Well, if you only fixed one of the errors it's not a surprise that it'd still throw a segfault, although I'd expect the segfault to be thrown in a different place (when accessing objects in the vector rather than just the vector). It is the nature of undefined behavior that its results are sometimes difficult to predict -- broken code may even sometimes appear to work until you change something completely unrelated. Frankly, I don't see why you're so set on ignoring these issues.
Comment: @Wintermute It's not throwing a segfault anymore, and have not had any issues since.  This example does not include the checks I have in place because they are completely irrelevant to the problem I was having, considering the example throws the fault before new_t is even used, I don't see why everyone was so hellbent on ignoring that.  Simply debugging the program would've showed that, and while everyone was too busy calling out an uninitialised T object, moving the instance() call fixed all segfaults. I do appreciate the feedback, especially on Singleton design, thanks.
Comment: Well, the uninitialized `T` pointer (not a T object, because the program never creates any) is still a UB-causing problem, and with UB-causing bugs like this all bets about the behavior of the program are off. It's not unreasonable to say "well, as long as this is in there, you have no guarantees about anything," although it's not the way I would argue. If it interests you, my take is that as long as all that was in there, it wasn't really a minimal example, and stripping it down to a minimal example would have exposed the error more clearly and have gotten you more  pertinent suggestions.
Comment: I'm trying to be nice here, but I also have to be frank: In the first iteration, you slapped an incomplete example into your question that no one had any way of running through a debugger. In the second, you slapped in a grand total of five different files and several hundred lines of code in there after people asked for a **minimal** verifiable example. The point of MCVEs is both to help you narrow down where the error could be and to make it easy for others to reproduce it and understand your code within a few minutes. This was not making it easy, and so you didn't get lots of effort. Sorry.
Comment: @Wintermute Uh, the example is close to 100 lines of code, not several hundreds, and took me less than 1 minute to copy and paste. I also said many times that the error is related to the member vector, NOT the objects it is storing.  It's hard to justify why every single person ignored me every time I say that and then say it's reasonable for you to call out unrelated issues instead of looking at the problem I've asked for help with.  I gave an MCVE of my problem because I genuinely wanted insight, there's no justifying ignorance.  Still, I do thank you for your help, but I resolved it myself.
Answer: Answering my own question here.  I am trying to call a member variable from within the constructor of the object that holds it, so the vector I am trying to access is not yet instantiated and doesn't exist in memory.  That is what causes the Segmentation fault to occur, I am trying to access memory that is not allocated yet, hence any call acting on any member of my C class was causing this issue.
I fixed this problem by adding a public function to the  class that then calls the private readLines() function.  I call that public function from the object that will take ownership of it, and since this occurs after it has been instantiated, the memory is accessible and the problem disappears.
Comment: This is incorrect. Once the constructor body is entered, all member variables are initialized. The problem you had wasn't that the member vector of the singleton object you were constructing wasn't initiialized; as I pointed out in my answer, it was that you weren't *using* it. Instead of calling `this->readLines()`, you were calling `instance->readLines()`, at a time when the `instance` pointer was not yet initialized (more precisely: still zero-initialized, i.e. `nullptr`). What you did likely works because it postpones the `readLines` call until after the `instance` pointer is initialized.


Como criar um método de pesquisa por elementos em uma ArrayList?

Question: Supondo uma ArrayList que armazene objetos, e esses objetos possuem atributos de diversos tipos (int, String , float,etc...). Sabendo disso eu quero criar um método para achar um objeto na ArrayList através de uma palavra chave ou numero que pode está dentro de um elemento da Array ou não. Sem ser pelo index de cada elemento.
Comment: Seja mais especifico no que está a tentar fazer. Dê um exemplo dos objetos que tem e do tipo de procura que pretende fazer.
Answer: Você pode fazer algo como:
public class Pessoa {

    private int id;
    private String nome;
    private int idade;

    public Pessoa(int id, String nome, int idade) {
        this.id = id;
        this.nome = nome;
        this.idade = idade;
    }

    public int getId() {
        return id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public int getIdade() {
        return idade;
    }

    public void setIdade(int idade) {
        this.idade = idade;
    }
}

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {

        ArrayList<Pessoa> pessoas = new ArrayList<Pessoa>();

        pessoas.add(new Pessoa(1, "José", 32));
        pessoas.add(new Pessoa(2, "João", 25));
        pessoas.add(new Pessoa(3, "Maria", 43));

        Pessoa pessoaPeloNome = buscaPeloNome(pessoas, "João");
        Pessoa pessoaPelaIdade = buscaPelaIdade(pessoas, 43);

        if(pessoaPeloNome != null) {
            System.out.println("Pessoa pelo nome: " + pessoaPeloNome.getId() + " | " + pessoaPeloNome.getNome() + " | " + pessoaPeloNome.getIdade());
        }

        if(pessoaPelaIdade != null) {
            System.out.println("Pessoa pela idade: " + pessoaPelaIdade.getId() + " | " + pessoaPelaIdade.getNome() + " | " + pessoaPelaIdade.getIdade());
        }
    }

    public static Pessoa buscaPeloNome(ArrayList<Pessoa> pessoas, String nome) {

        for(Pessoa pessoa : pessoas) {
            if(pessoa.getNome().equals(nome)) {
                return pessoa;
            }
        }
        return null;
    }

    public static Pessoa buscaPelaIdade(ArrayList<Pessoa> pessoas, int idade) {

        for(Pessoa pessoa : pessoas) {
            if(pessoa.getIdade() == idade) {
                return pessoa;
            }
        }
        return null;
    }
}

Saída:

Pessoa pelo nome: 2 | João | 25
Pessoa pela idade: 3 | Maria | 43
Comment: Existem várias formas de fazer isso, uma delas é criando um campo de `id` na classe em questão, receber esse id pelo construtor e fazer apenas o método _getter_ dele e não o setter. Vou editar a publicação para incluir isso. @Ogarov
Comment: Sua solução me ajudou bastante, muito obrigado.
Comment: @Ogarov legal. Ficou feliz por ter ajudado. Poderia marcar a resposta como solução, por favor? É o sinal de "check" debaixo do número de votos da resposta.
Comment: Você sabe como eu posso gerar um id para cada objeto que eu adicionar a ArrayList ? Tipo um ID que  não possa ser alterado e que seja pra sempre de um objeto ?
Comment: @Ogarov resposta editada.
Answer: A forma mais fácil é:
Arrays.asList("Débora", "Luan").stream().filter(string -> string.equals("Luan"))
    .collect(Collectors.reducing((a, b) -> null)).get();

Ou até, o que seria mais protegido em caso de não haver nenhum item que se assemelha à informação dada:
Arrays.asList("Débora", "Luan").stream().filter(parametroFiltro -> parametroFiltro.equals("Luan")).findFirst().get();

Eu usei algumas ferramentas disponiveis a partir da versão 1.8 do Java. Com as expressões lambda fica mais fácil escrever pequenas classes anonimas funcionais com apenas um método, que recebe um parâmetro (o parametroFiltro), e define ele dentro de um método (por isso utiliza-se a flecha, ->, para indicar como será sua execução).
Por exemplo, o método filter utilizado depois do stream é utilizado para "filtrar" a coleção a partir de uma dada verificação.
O código .filter(parametroFiltro -> parametroFiltro.equals("valor") pode ser substituído por:
.filter(new Predicate<String>(){

    @Override
    public boolean test(String parametroFiltro) {
        return parametroFiltro.equals("Luan");
    }
})

No caso do filter, como ele espera um objeto instanciado da interface Predicate, ele sabe que deve executar o código definido é parametroFiltro -> parametroFiltro.equals("valor") como um método que tem algo como retorno e recebe somente um parâmetro tipo String.
O segundo uso de lambda foi utilizado para definir como parâmetro de reducing uma instancia da classe BinaryOperator, que tem o método apply como um método que recebe duas variáveis e retorna um tipo T, definido na criação da classe anonima. nesse caso:
Collectors.reducing(new BinaryOperator<String>() {

    @Override
    public String apply(String a, String b) {
        return null;
    }
}

Não se cobre quanto a isso, eu falei por que achei bacana dividir formas mais divertidas de tratar o assunto.
E de todas as formas, por favor, se pessoas mais estudadas no assunto conseguirem completar as informações fico imensamente grato.
Comment: @Ogarov, Oook, pelo que você não entende suponho que sejam as expressões lambdas. Vou explicar da minha melhor forma. Fica aberto para outros melhorarem a explicação.
Comment: Obrigado pela ajuda, ainda sou iniciantes e tem umas coisas no seu código  que não entendo.
Answer: tu cria uma classe que implementa um ArrayList e então tu pode implementar um método de busca e sobrescrevê-lo para cada atributo desejado. As coleções já implementam esses métodos padrões.
sort: Classifica os elementos de uma List.
binarySearch: Localiza um objeto em uma List usando o algoritmo de pesquisa binária de alto desempenho introduzido.
Para utilizá-los os objetos que tu colocar no ArrayList precisam ter o método
compareTo que é declarado na interface Comparable e, às vezes, é chamado método natural de comparação. A chamada sort pode especificar como um segundo argumento um objeto Comparator, que determina uma ordem alternativa dos elementos.
Referência é o Java - Como Programar 10ª ed.


Is the functor $\mathrm{op} \colon \mathcal{C} \longrightarrow \mathcal{C}^\mathrm{op}$ equal to the identity?

Question: In Kashiwara-Schapira (Categories and abelian sheaves), it is written

A contravariant functor from $\mathcal C$ to $\mathcal{C}'$ is a functor from $\mathcal{C}^\mathrm{op}$ to $\mathcal{C}'$.

It is convenient to introduce the contravariant functor $\mathrm{op} \colon \mathcal{C} \longrightarrow \mathcal{C}^\mathrm{op}$
defined by the identity of $\mathcal{C}$.

There is an isomorphism of categories
$$
  \mathrm{Fct}(\mathcal{C}, \mathcal{C}')^\mathrm{op} \simeq \mathrm{Fct}(\mathcal{C}^\mathrm{op}, \mathcal{C}'^{\mathrm{op}}),
  \quad F \longmapsto \mathrm{op} \circ F \circ \mathrm{op}.
$$

By 1), $\mathrm{op}$ is a functor from $\mathcal{C}^\mathrm{op}$ to $\mathcal{C}^\mathrm{op}$.
So, how could it be identity of $\mathcal{C}$? It perhaps the identity of $\mathcal{C}^\mathrm{op}$.
But in this case, in 3), we have $\mathrm{op} \circ F \circ \mathrm{op} = F$
which is not an element of $\mathrm{Fct}(\mathcal{C}^\mathrm{op}, \mathcal{C}'^{\mathrm{op}})$.
Comment: The language of categories so much easier when you simply erase the word "contravariant functor". This has been discussed multiple times here already. Your question is an example of which confusions may arise.
Comment: @MartinBrandenburg If $F \colon \mathcal{C} \longrightarrow \mathcal{D}$ and
$G \colon \mathcal{D}^\mathrm{op} \longrightarrow \mathcal{E}$ are two (covariants) functors, what is the meaning of $G \circ F$?
Comment: It is not defined. Why should it be? The domain of G is not the target of F. But you can do G composed with F^op for example, and also G^op composed with F.
Comment: @MartinBrandenburg So if $G$ is the covariant functor $\mathrm{op}_{\mathcal{B}} \colon \mathcal{B}^{\mathrm{op}} \longrightarrow \mathcal{B}^{\mathrm{op}}$, we can't write $G \circ F$
(where $F \colon \mathcal{A} \longrightarrow \mathcal{B}$ is a covariant functor),
but if $G$ is the contravariant functor $\mathrm{op}_{\mathcal{B}} \colon \mathcal{B} \longrightarrow \mathcal{B}^{\mathrm{op}}$, then we can write $G \circ F$.
Answer: For any category $\mathbf{C}$, there is the functor $\text{op}_\mathbf{C}\colon\mathbf{C}\to\mathbf{C}^\text{op}$ sending each object to itself (as the objects of a category and its opposite category are the same!), and sending any morphism $f\colon C\to D$ to the corresponding unique $f^\text{op}\colon D\to C$. While it is identity on objects, it is not that on morphisms (unless you only have identity morphisms in your category). We can then consider the functor $\text{op}_{\mathbf{C}^\text{op}}\colon\mathbf{C}^\text{op}\to\mathbf{C}$, and compose this with our previous functor and these satisfy $\text{op}_{\mathbf{C}^\text{op}}\circ\text{op}_\mathbf{C}=1_\mathbf{C}$ and $\text{op}_\mathbf{C}\circ\text{op}_{\mathbf{C}^\text{op}}=1_{\mathbf{C}^\text{op}}$. If there is even one non-identity morphism in $\mathbf{C}$, then $\text{op}_\mathbf{C}$ is not the identity functor.
How the claim in Kashiwara-Schapira should be read is $F\mapsto \text{op}_{\mathbf{C}'}\circ F\circ\text{op}_{\mathbf{C}^\text{op}}$, as this is a composite $$\mathbf{C}^\text{op}\xrightarrow{\text{op}_{\mathbf{C}^\text{op}}}\mathbf{C}\xrightarrow{F}\mathbf{C}'\xrightarrow{\text{op}_{\mathbf{C}'}}\mathbf{C}'^\text{op}.$$ What probably confused you is that they denote each of those opposite functors by $\text{op}$ without mentioning the category (as is usually the case). I'll let you figure out its inverse functor yourself to confirm this is indeed an isomorphism! :)


Basic Gini impurity derivation

Question: From wikipedia:    https://en.wikipedia.org/wiki/Decision_tree_learning

I am unable to get my head around two of the steps:

The first equation:  $f_i(1 - f_i)$.  This does not immediately become apparent as the "probability of being chosen times the probability of miscategorization". Instead it looks to me like "probability of being chosen times the probability of others being chosen" (but not necessarily incorrectly)
The arithmetic of the last simplification eludes me: how to get from $1 - \sum(f_i^2)$ to $\sum(f_if_k)$

Tips appreciated.
Answer: I think it's best to answer your question in reverse order as we'll back into your first question by answering your second.
Question 2
Imagine you have a probability distribution function ($f_i$) that distributes its probabilities as such:

I can then square the probabilities ($f_i^2$) and get:

Another way of looking at it is putting each probability distribution along the axis of a grid. Each cell now represents the product of the function along the respective axes.

The grid itself sums to 1, just like you'd see in a two dice roll probability table. It should be clear that 1 minus the sum of the diagonal probabilities is the same as the non-highlighted squares below.

If we call one of the axis k to differentiate it, but still have it render the same function, we can then make the statement.

$1-\sum f_i^2$ = $\sum_{i \neq k} f_if_k$
Question 1
We can now use some of the intuition from answering question 2 to drive the intuition for question 1.
Let's take our same table from question 2, but change what the two axes mean. Across one axis we'll have labels for objects, while on the other we'll have the actual object.
For a concrete example, let's assume we have a bowl of fruit: apples, oranges and pears. In another bowl we'll have labels corresponding to apples, oranges and pears in the same proportion as the actual objects.

If we then look at the probability of choosing each at random we get the following distribution.

Now we want to look at the joint distribution. The Geni impurity tells us the probability that we select an object at random and a label at random and it is an incorrect match. The Geni impurity is the sum of the probabilities in the black shaded areas. These are where the label does not match the object, thus the impurity.

This should look very familiar to the answer to question 2. If the explanation for question 2 convinced you that $1-\sum f_i^2$, you should be able to work backwards through the algebra you provided to see that also equals $\sum f_i(1-f_i)$
Comment: @Josmoor98 that is correct, the two distributions are identically distributed compared to each other. There may be some example I'm not aware of that is not IID, but is in this example and all I've seen are.
Comment: Hi Scott, thanks for your great answer. To clarify, in your example, when picking the object and label at random, are you simply considering randomly selecting two objects from two identical distributions? Is this to simulate the effect of considering a test observation prediction vs the test observation label? Does this mean that the Gini index relies on the observations node samples being i.i.d?
Answer: I don't know about the algebra, but you can prove the identity with a probabilistic argument. If I roll two dice with $m$ sides and the probability of side $i$ is $f_i$, then the probability of a double is $\sum f_i^2$. Thus $1-\sum f_i^2$ is the probability that I roll distinct values. But arguing differently, the probability, say, that I get $i$ followed by $j$ is $f_if_j$. Summing over all possibilities, with $i \neq j$, I get the probability of rolling distinct outcomes: $\sum f_if_j$, and the identity is proven.
As for the first point, If you role the $m$ sided die, there is a probability $f_i$ that side $i$ comes up. Suppose I have to guess the value, and I do this by rolling a die of my own with the same weights. The probability that I guess wrong, conditional on value $i$ being true,  is $1-f_i$. The probability that I get it wrong, summing over the possible values, is $\sum f_i(1-f_i)$.
Comment: nice explanations. I feel closer to an understanding.
Answer: 1) Remember that the classification is done randomly proportional to the frequency of the value.  $i$ is then miscategorized with probability $(1-f_i)$.
2) The $f_i$ sum to 1.  So if I sum all $f_if_j$ this equals 1*1.  So if I sum just the ones where $i\neq j$ this equals $1- \sum f_if_i$.
Sorry for the brevity, answering from my phone.  Comment with questions.
Comment: Reasonable explanation. The other one with a bit more verbosity served me a bit better (given I needed bit more handholding). I upvoted here in any case.
Answer: Gini index
Main idea is here. We can make an example based on this
statquest.
Let's say there is a machine that
can detect Heart Disease (HD). The machine can predict HD 30% of the
time. Following is the sample we have:

HD
!HD

Machine
30%
70%

This means the following cases are possible:

Machine classify as HD and it is HD (P = 0.3*0.3)
Machine classify as !HD and it is !HD (P = 0.7*0.7)
Machine classify as HD but it is !HD
Machine classify as !HD but it is HD

We pray that cases 3&4 happen less often. The sum of all probabilities
is 1. P(3&4) is therefore given by 1-(0.3^2)-(0.7^2)=0.42. P(3&4)
is the impurity or how bad the machines' prediction is, AKA
GINI=0.42.
The alternative is to check if someone is clutching his chest or not
due to chest pain (CP) and then guess based on probability data if he
has HD or not. The following is the sample we have. For each case we
calculate the GINI. Then we take the average of it (assuming similar
sample size) and this estimates the GINI impurity using CP to predict
HD.

HD
!HD
GINI

!CP
25%
75%
0.375

CP
80%
20%
0.32

avg
NA
NA
0.38

Smaller the impurity the better. So we decide instead of buying the
machine (GINI=0.42) we can just use CP as an indicator (GINI=0.38).
P.S.
This is also an explanation of what happens at each node of a decision tree, which is where I came across GINI index.

Basic Gini impurity derivation


Como fazer requisicão via post para a action pelo AJAX?

Question: Não consigo acessar minha action através da requisição ajax:
        <legend>Procedimento:</legend>
@Html.HiddenFor(p => p.CodigoProcedimento, new { id = "codProcedimento", name = "codProcedimento" })

@Html.HiddenFor(p => p.CodigoPessoa, new { id="codigoPessoa",name="codigoPessoa"})

@Html.Label("Descrição: ")
@Html.TextBoxFor(p => p.Descricao, new { maxlength = "30", id = "descricao", name = "descricao" })
@Html.Label("Palavra chave: ")
@Html.TextBoxFor(p => p.PalavraChave, new { maxlength = "50", id = "palavraChave", name = "palavraChave" })
@Html.Label("Pergunta Panico: ")
@Html.TextAreaFor(p => p.PerguntaPanico, new { maxlength = "50", id = "perguntaPanico", name = "perguntaPanico" })
@Html.Label("Resposta Panico: ")
@Html.TextBoxFor(p => p.RespostaPanico, new { maxlength = "50", id = "respostaPanico", name = "respostaPanico" })

@Html.Label("Procedimento Panico: ")
@Html.TextAreaFor(p => p.ProcedimentoPanico, new { maxlength = "80", id = "procedimentoPanico", name = "procedimentoPanico" })
@Html.Label("Adicionar Contactado: ")
@Html.DropDownListFor(s => s.CodContactadoPessoa, Model.ContactadoPessoa, new { id = "CodContactadoPessoa", name = "CodContactadoPessoa" })

         function atualizarCampos(){
    var codigoPessoa = $("#codigoPessoa").val();
    var descricao = $("#descricao").val();
    var palavraChave = $("#palavraChave").val();
    var perguntaPanico = $("#perguntaPanico").val();
    var respostaPanico = $("#respostaPanico").val();
    var procedimentoPanico = $("#procedimentoPanico").val();
    var temp = $("#CodContactadoPessoa").val();
    var codigoContactado = temp.options[temp.selectedIndex].value;
    var codigoProcedimento = $("#codProcedimento").val();

    $.ajax(
        {
            type: 'POST',
            url: '/Master/EditarProcedimentoAContacto',
            data:
                {
                    CodigoPessoa: codigoPessoa,
                    Descricao: descricao,
                    PalavraChave: palavraChave,
                    PerguntaPanico: perguntaPanico,
                    RespostaPanico: respostaPanico,
                    ProcedimentoPanico: procedimentoPanico,
                    CodPessoaProcedimento: codigoContactado,
                    CodigoProcedimento: codigoProcedimento,
                },
            success: function (data) {
                //alert("oi");
                $('#procedimentoresult').html(data);
            }
        });
}

Answer: Caso você tenha as versões mais recentes do jQuery tente utilizar a versão mais recente para declaração de AJAX:
$.ajax({
    type: 'POST',
    url: 'SuaURL',
    data: {
        valor1: valor1,
        valor2: valor2
    }
}).done(function (data) {
    console.log(data);
}).error(function (data) {
    console.log(data);
});

Como outros usuários disseram verifique:

Se sua URL é valida;
Se você está mandando um retorno; ou seja -> (echo json_encode($retorno)) na página onde você recebe o post;

Exemplo: http://jsfiddle.net/rafaelwithoeft/dr1mdynL/5/
Answer: A URL é válida?
Está ocorrendo algum erro de JavaScript antes de completar a requisição?
Na chave data encontrei um erro, no ultimo valor você adicionou uma virgula no final da linha (CodigoProcedimento: codigoProcedimento,), remova-a.
Para ver o retorno da reposta você pode usar console.log(data)
Answer:  var dados = { codigoPessoa: codigoPessoa, descricao: descricao};
$.ajax({
                        type: "POST",
                        url: "@Url.Action("Action", "Controller")",
                        contentType: "application/json",
                        data: JSON.stringify(dados),
                        datatype: "html",
                        success: function (data) {})
    });


Bounded sequences in the box topology

Question: Could anyone explain to me why the set of all bounded sequences of real numbers is open in the box topology? Can we say the same for the set of all unbounded sequences?
Answer: If a sequence $(x_n)$ is bounded, so is every sequence in its box open neighbourhood $U = \prod_n (x_n -1 ,x_n +1)$. So bounded sequences form an open subset.
If that sequence is unbounded, so is every sequence in $U$ as well, making the unbounded sequences open as well.
So the set of bounded sequences is both open and closed. This shows that the infinite box product of connected spaces need not be connected.
Comment: :How do we conclude that a bounded sequence has a neighbourhood like this one?
Comment: @user391120 I have defined a basic box open set, haven't I?
Comment: Yes you have. My question is if we can do the same for any sequence or it is relative with a dounded or unbounded sequence only?
Comment: @user391120 we can define it for any sequence. If the $x_n$ are bounded by, say, $m$, all sequences in this neighbourhood are bounded by $m+1$. If the sequence is unbounded, then so are all sequences in that neighbourhood (why?).
Answer: Let $U_n = \{(x_i)\mid |x_i| < n \text{ for all }i\in \Bbb N\}$, i.e. all sequences that never exceed $n$. This is an open set, because it's an element in the standard box topology basis. The set of all bounded sequences is the union of all these open $U_n$'s.
Similarily, an unbounded sequence is one that is not bounded, so the set of unbounded sequences is the complement of the set of bounded sequences. Therefore the set of unbounded sequences is closed in the box topology.
One would think we could do something similar with unbounded sequences, i.e. define the open $V_n = \{(x_i)\mid |x_i| > n \text{ for at least one } i\in \Bbb N\}$. This does not work because in this case we want the intersection of all the $V_n$, and an infinite intersection of open sets is not necessarily open. In fact, if you use $\geq$ in the definition of $V_n$ instead, they become closed (they're the complements of the $U_n$), and you get that the set of unbounded sequences is an intersection of closed sets, and therefore closed.
Comment: $U_1$ is the basis element $(-1,1)\times (-1,1)\times \cdots$, so, for instance, $(1/2, 1/3,1/4,1/5,\ldots)$ and $(1/2,-3/4,7/8,-15/16,\ldots)$ are in there. So is a lot of other sequences, just as long as (the absolute value of) each element is strictly less than $1$.
Comment: Could you please write some elemements of set Un because i cannot understand why is this an element in the box topology basis?

Bounded sequences in the box topology


Find the domain and range of $f(x) = \frac{x+2}{x^2+2x+1}$:

Question: The domain is: $\forall x \in \mathbb{R}\smallsetminus\{-1\}$
The range is: first we find the inverse of $f$:
$$x=\frac{y+2}{y^2+2y+1} $$
$$x\cdot(y+1)^2-1=y+2$$
$$x\cdot(y+1)^2-y=3 $$
$$y\left(\frac{(y+1)^2}{y}-\frac{1}{x}\right)=\frac{3}{x} $$
I can't find the inverse... my idea is to find the domain of the inverse, and that would then be the range of the function. How to show otherwise what is the range here?
Comment: Near $-1$ the function approaches $\infty$ so it's not upper bounded, for lower bound, $c$ is a lower bound if $f(x) - c\geq 0$ for all $x$, and it's a minimum if $f(x_0)=c$ for some $x_0$.
Answer: Notice that
\begin{align*}
f(x) = \frac{x+2}{x^{2} + 2x + 1} = \frac{(x+1) + 1}{(x+1)^{2}} = \frac{1}{x+1} + \frac{1}{(x+1)^{2}}
\end{align*}
If we set $y = 1/(x+1)$ and consider $c\in\textbf{R}$, we arrive at the following equation
\begin{align*}
y + y^{2} = c \Longleftrightarrow y^{2} + y - c = 0\Longleftrightarrow y = \frac{-1\pm\sqrt{1+4c}}{2}
\end{align*}
which has real roots if and only if $c\geq-1/4$.
So the answer is $\text{Im}(f) = [-1/4,\infty)$.
Answer: How about using calculus?
$$f(x)=\frac{x+2}{(x+1)^2}=\frac{1}{x+1}+\frac{1}{(x+1)^2} \\ f'(x) =\frac{-1}{(x+1)^2}-\frac{2}{(x+1)^3} =0 \\ \implies x=-3$$ which you can see clearly corresponds to a minimum. We see $f(-3) =-\frac 14$. Now, $\lim_{x\to\pm\infty}f(x)=0$ and also $\lim_{x\to -1} f(x) =+\infty$ which means that $-\frac 14$ is the global minimum. There is no upper bound and hence the range is $$\left[-\frac 14,\infty\right)$$
Answer: Why? Just write the function as follows:
$$f(x) = \frac{(x+1)+1}{(x+1)^2} = \frac{x+1}{(x+1)^2}+ \frac{1}{(x+1)^2}
$$
later,
$$f(x)= \frac{1}{(x+1)}+\frac{1}{(x+1)^2}=u+u^2 = (u+0.5)^2-0.25 = \left(\frac{1}{x+1}+0.5\right)^2-0.25$$
Since here you should be able to continue, just see the variation of $x$ and transform to $f(x)$
Answer: $$f(x)=\frac{x+2}{(x+1)^2}$$
$$f'(x)=\frac{(x+1)-2(x+2)}{(x+1)^3}$$
$$=\frac{-x-3}{(x+1)^3}$$
so
$$f((-\infty,-1))=[f(-3),+\infty)$$
and
$$f((-1,+\infty))=(0,+\infty)$$
thus, the range is $$[-\frac 14,+\infty).$$
Answer: Alternate way to find the range :
$$f(x) = y =\frac{x+2}{x^2+2x+1}$$
$$yx^2+(2y-1)x+(y-2)=0  $$
Now this quadratic has real roots (since real points exist belonging to the function for all values of x (we can remove the case of -1 later)) . So applying the condition for real roots : ($b^2-4ac \geq 0$)
$$(2y-1)^2-4(y)(y-2)\geq0$$
$$-4y+1 +8y\geq0$$
$$y\geq\frac{-1}{4}$$
$$y \in  \left[ -\frac{1}{4},\infty \right)$$
Now the value of $y$ at $x=-1$ $\to \infty$ so no need to remove it from the range
Answer: $$\text{You wrote: } x=\frac{y+2}{y^2+2y+1} $$
$$x(y^2+2y+1)=y+2$$
$$
xy^2 + ( 2x-1 )y +(x-2)=0 \tag 1
$$
$$
ay^2 + by + c = 0, \quad\text{where } a=x,\, b=(2x-1), \, c = x-2 \tag 2
$$
$$
y = \frac{-b\pm\sqrt{b^2-4ac}}{2a} = \frac{1-2x\pm \sqrt{(2x-1)^2 -4x(x-2)}}{2x} \tag 3
$$
except that $(2)$ can be a valid solution of $(1)$ only when $a=x\ne 0.$ When $x=0,$ equation $(1)$ becomes
$$
y+2=0, \text{ so } y=-2.
$$
Thus the domain of the function defined on line $(3)$ excludes only those values of $x$ for which the expression under the radical is negative. So we want
$$
(2x-1)^2 - 4x(x-2)\ge0.
$$
$$
-4x + 1+8x\ge0
$$
$$
x \ge \frac {-1} 4.
$$


Geany syntax highlighting questions

Question: 1) Are there any Geany users here who have gotten good syntax highlighting for Scala?
2) What should I do about syntax highlighting when I'm editing (Mako) templates that are generating things other than HTML/CSS/JS? (say, C/C++ code, or w/e)  Is good syntax highlighting too much to ask out of Geany in this case (or any other editor, for that matter)?
Answer: I just wanted to chime in to note that the latest version of geany (1.22) does have syntax highlighting for Scala - it's rudimentary, but it will at least highlight comments and a few keywords. Annoyingly, the support is initially only activated for files named Foo.scl, rather than using the standard convention of Foo.scala, but this can be changed by modifying /usr/share/geany/filetype_extensions.conf (the format is pretty obvious).

Geany syntax highlighting questions


Topics are not getting associated with forum

Question: I am testing out the Drupal 8 core Forum module.  I am using a theme that I based off of Acquia Lightning.  I have successfully installed the module and added Containers, Forums and Topics.  My issue is that the Topics I create don't seem to get associated with the Forum taxonomy.  In other words, when I go to /forum I see my containers and forums but every forum has Topics: 0, Posts: 0, Last Post: n/a.
I have tried clearing cache, running cron, looking at the watchdog logs but nothing seems to indicate why it isn't working.  I am not receiving any memory errors, white screen of death, etc.  All other site functions seem to work properly: I can save content and taxonomies, create new views, assign blocks, etc.
See the attached screen grab.  I could use some ideas on what might be causing this.  Any assistance would be greatly appreciated.
Answer: Try:
<code>drush state:set comment.maintain_entity_statistics TRUE
</code>
Explanation:
core/modules/comment/src/CommentStatistics.php in the update() function says this:
<code>// Allow bulk updates and inserts to temporarily disable the maintenance of
// the {comment_entity_statistics} table.
if (!$this->state->get('comment.maintain_entity_statistics')) {
  return;
}
</code>
In my case, somehow this was not set, causing this function to bail out and not update the comment_entity_statistics table. Drupal needs this table updated to display the proper forum posts.
"drush state:get comment.maintain_entity_statistics" can be used to check if this is already set.
Comment: The *comment_entity_statistics* database table contains statistics about the comments. It's not used to count the number of posts a forum contains, since those are nodes, not comments. That table is used to show *new* close to a node title, to mean there was new activity on that node, for example a new comment.


What is the simplest way to factor the following polynomial $x^4-8x^2+x+12$?

Question:
What is the simplest  way  to factor the following  polynomial  $$x^4-8x^2+x+12$$ ?

Note : I already knew the factorization which is
$$(x^2-x-3)(x^2+x-4)$$
I need the way to get that
Thank you for your help.
Comment: What do you mean 'simplest'. For example, I beleive it's really simple to find the roots of it (its only a quartic) and from there go to the two quadratics but I don't think thats what you want.
Answer: We can write $$x^4-8x^2+x+12=(x^2+ax+b)(x^2+cx+d)$$
Comparing the coefficients of $x^3,$ $$0=a+c\iff c=-a$$
Comparing the coefficients of $x,$  $$1=ad+bc=a(d-b)$$
$$\implies a=d-b=\pm1$$
Comparing the constants,  $$bd=12$$
If $d-b=1, d=4,b=3$ or $d=-3.b=-4$
What if $d-b=-1?$
Comment: @prayersmith, Yes. $$d=-3,b=-4$$  or $$d=4,b=3$$
Comment: $d=-4 ،b= -3$ , isn't that right?
Comment: @prayersmith, Of course, we need to check which combination of values of $a,b,c$ satisfies the coefficient of $x^2$
Answer: I like the following way.
$$x^4-8x^2+x+12=(x^2+k)^2-((2k+8)x^2-x+k^2-12).$$
Now, we need to find a value of $k$, for which $(2k+8)x^2-x+k^2-12=(ax+b)^2$,
for which we need $$1-4(2k+8)(k^2-12)=0$$ or
$$(2k+7)(4k^2+2k-55)=0.$$
Easy to see that $k=-3.5$ is valid.
Indeed, $$x^4-8x^2+x+12=(x^2-3.5)^2-(x^2-x+0.25)=$$
$$=(x^2-3.5)^2-(x-0.5)^2=(x^2-x-3)(x^2+x-4)$$
and we are done!
In the general case we'll get a cubic equation with the variable $k$ and one of this equation roots always gives difference of squares and possibility of the factorization.
Answer: You can apply the algorithm described here. In your case, the resolvent of the polynomial is $x^3-16x^2+16x-1$. Clearly, $\alpha=1$ is a root of the resolvent and furthermore it is different from $0$ and it is a perfect square in $\mathbb Q$. So, you can factor your polynomial as $(x^2+x+\beta)(x^2-x+\gamma)$ (the coefficients of $x$ in these two polynomials are the square roots of $\alpha$, that is , they are $\pm1$) where $\beta$ and $\gamma$ are such that$$\left\{\begin{array}{l}\beta\gamma=12\\\beta+\gamma=\alpha+(-8)=-7.\end{array}\right.$$So, you can take $\beta=-3$ and $\gamma=-4$.


Choosing elements from an abelian group $\mathbb{Z}_n$ that make the enumeration of partitions incomplete.

Question: Take an abelian group $(\mathbb{Z}_n,+)$ and enumerate all partitions of two elements (i.e. $x=x_1+x_2$) of each element $\{0,1,...,n-1\}=\mathbb{Z}_n$. Take, for example, abelian groups $\mathbb{Z}_9$ and $\mathbb{Z}_{10}$. Now, the enumerations of the partitions of these groups would be the following (note that $x=x_1+x_2$ where $x_1=x_2$ is not allowed, i.e. $x_1$ and $x_2$ may not be equal!):
$\mathbb{Z}_9:$
$0=8+1,7+2,6+3,5+4$
$1=8+2,7+3,6+4,0+1$
$2=8+3,7+4,6+5,0+2$
$3=8+4,7+5,0+3,1+2$
$4=8+5,7+6,0+4,1+3$
$5=8+6,0+5,1+4,2+3$
$6=8+7,0+6,1+5,2+4$
$7=0+7,1+6,2+5,3+4$
$8=0+8,1+7,2+6,3+5$
$\mathbb{Z}_{10}:$
$0=9+1,8+2,7+3,6+4$
$1=9+2,8+3,7+4,6+5,0+1$
$2=9+3,8+4,7+5,0+2$
$3=9+4,8+5,7+6,0+3,1+2$
$4=9+5,8+6,0+4,1+3$
$5=9+6,8+7,0+5,1+4,2+3$
$6=9+7,0+6,1+5,2+4$
$7=9+8,0+7,1+6,2+5,3+4$
$8=0+8,1+7,2+6,3+5$
$9=0+9,1+8,2+7,3+6,4+5$
Now, my question is the following: how many ways can we choose the total of $\lfloor \frac{n-1}{2}\rfloor$ distinct elements from $\mathbb{Z}_n$ such that when these elements are deleted, there exists at least one remaining element in $\mathbb{Z}_n$ that may not be expressed as a partition $x=x_1+x_2$ anymore. For instance, if we look at $\mathbb{Z}_9$ then $\lfloor \frac{9-1}{2} \rfloor=4$ and if we delete $\{8,2,3,5\}$ from $\mathbb{Z}_9$ then we cannot express $0$ as a partition $0=x_1+x_2$ where $x_1,x_2\in \mathbb{Z}_9 \setminus \{8,2,3,5\}$.
I noticed that no $\lfloor \frac{n-1}{2} \rfloor$ consecutive elements may be deleted from $\mathbb{Z}_n$ so there must be at least $n$ different ways to do this. However, there have to be more than $n$ due to, for instance, my previous example of $\mathbb{Z}_9\setminus \{8,2,3,5\}$.
Comment: $n\cdot 2^{(n-1)/2}$ for $n$ odd.
Comment: It cannot be. Take $\binom{n}{\lfloor  \frac{n-1}{2}\rfloor}-n2^{\lfloor \frac{n-1}{2} \rfloor}$. This quantity may be negative, which would not make sense.
Comment: sorry about that. now i got it right (for prime $n$). see answer below.
Answer: The answer is $p\cdot 2^{(p-1)/2}-\frac{p(p-1)}{2}$ for prime $p > 2$.
You want the number of $A \subseteq \mathbb{Z}_p$ of size $|A| = \frac{p+1}{2}$ so that $|A\hat{+}A| \le p-1$, where $A\hat{+}A := \{a+a' : a,a' \in A, a \not = a'\}$.
Take $A \subseteq \mathbb{Z}_p, |A| = \frac{p+1}{2}$. It's known that $|A\hat{+}A| \ge \min(p,2|A|-3) \ge p-2$ (see, e.g., here).
We first claim that for any distinct $a,b \in \mathbb{Z}_p$, there's exactly one $A \subseteq \mathbb{Z}_p, |A| = \frac{p+1}{2}$ with $|A\hat{+}A| = \mathbb{Z}_p\setminus\{a,b\}$. By translation and scaling, it suffices to show this for $a=0,b=1$. Since, by Cauchy-Davenport $A+A = \mathbb{Z}_p$, we must have $2^{-1}0,2^{-1}1 \in A$. I.e., we must have $0,\frac{p+1}{2} \in A$. Since $1 \not \in A$, we must have $p-1 \in A$. You can keep playing this game.
And for any $a$, there are $2^{(p-1)/2}$ subsets $A \subseteq \mathbb{Z}_p, |A| = \frac{p+1}{2}$ with $a \not \in A\hat{+}A$. The number of them with $A\hat{+}A = \mathbb{Z}_p\setminus\{a\}$ is thus $2^{(p-1)/2}-(p-1)$.
So the answer is $p(2^{(p-1)/2}-(p-1))+{p \choose 2} = p\cdot 2^{(p-1)/2}-\frac{p(p-1)}{2}$.

For odd $n$, the answer is $$n\cdot\left(2^{(n-1)/2}-\sum_{j=1}^{n-1} \gcd(j,n)\right)+\sum_{0 \le x < y \le n-1} \gcd(x-y,n).$$ To see this, one first shows $|C\hat{+}C| \ge n-2$ for any $C \subseteq \mathbb{Z}_n, |C| = \frac{n+1}{2}$ and that the number of $C$ with $C\hat{+}C = \mathbb{Z}_n\setminus\{x,y\}$ is $\gcd(x-y,n)$ (by translation, it suffices to prove this for $y=0$).
All such $C$ are a union of cosets of a subgroup and part of one coset.
Comment: Thank you for the insightful answer! Do you think this reasoning can be generalized into the case of choosing any other number of elements except $\frac{p-1}{2}$ for primes $p>2$? This would be interesting as well.
Comment: @polygonlink1 How many elements did you have in mind? I think a general result would be quite hard..
Comment: @polygonlink1 See the updated answer.
Comment: Thank you! How about if instead of $\frac{p-1}{2}$ we choose to delete $\frac{p-1}{2}+1$ elements? Or $\frac{p-1}{2}+2$? Would it be possible to somehow derive these cases? I am just curious. If not, that's okay, but this would be highly appreciated.
Comment: @polygonlink1 In $\mathbb{Z}_p$, for prime $p$, I think it should be possible. One should show that if $|C| = \frac{p+1}{2}-\Delta$ has $|C\hat{+}C| = p-\delta$ (for $0 < \delta \le 2\Delta+2$), then, after multiplicatively scaling, $C$ is very close to an interval (the regime is $\Delta$ fixed, $p$ large). I'm pretty sure I know how to do this. It would take some work though. Feel free to email firstname.lastname@example.com if this is important enough to you


Mapping a wrapped Cauchy distribution to a uniform distribution?

Question: I'm investigating model mismatch and have a wrapped Cauchy distribution of
f(x,p) = (1-p^2)/ (2*pi*(1+p^2-2p*cos(x)))

Is there a way to map this to a random uniform distribution, like
random.uniform(100, minval=-q, maxval=q)

i.e. If I have a value of q, what p does that equate to? Thanks

Edit:
I have decided to match the moments to map the parameter. The means would be 0, but the variance would give:
$\frac{1}{12} (q--q)^2 = 1- e^\gamma$
Using the substitution for $\gamma$ to get to $p$, and rearranging, I get:
$p = \sqrt{\frac{1 - \tanh (-log(1-q^2/3))}{1 + \tanh (-log(1-q^2/3))}}$
but this does not behave as expected. i.e. when $p$ is close to 1, the distribution should be tight and therefore I would expect $q \rightarrow 0$ and when $p \rightarrow 0$, $q$ should be high, but this is not what happens - does anyone spot a mistake?
Comment: Probability integral transform?
Comment: Thanks, yes looks like a probability integral transform is good to make a map between the distributions. Yes @Xi'an the $x$ is between - pi and pi
Comment: You mean you are looking for a quantile function? https://math.stackexchange.com/questions/2911792/cdf-and-inverse-cdf-of-wrapped-cauchy-distribution
Comment: Are you just trying to replace the wrapped Cauchy with scale parameter $p$ with a Uniform distribution with support (or scale) parameter $q$ by equating some moments? The graph of the density of a wrapped Cauchy distribution shows how much it differs from a Uniform. Besides, its support is always $(-\pi,\pi)$, for all $p$'s, which would suggest using $q=\pi$.
Answer: Since the wrapped Cauchy distribution is made of the superposition of truncated scaled Cauchy distributions$^1$ translated by $2n\pi$ for all $n$'s $(n\in\mathbb Z)$:
$$f_{WC}(\theta;\gamma)=\sum_{n=-\infty}^\infty \frac{\gamma}{\pi(\gamma^2+(\theta+2\pi n)^2)}\,\mathbb I_{(-\pi,\pi)}(\theta)\qquad \gamma>0$$
it can be simulated by

Simulating a regular Cauchy variate $X$ with scale$^2$ $\gamma$
Translating the realisation $x$ of $X$ by the proper amount $2n\pi$ so that it belongs to $(-\pi,\pi)$ and returning the resulting $\theta=X+2n\pi$

Furthermore, the Cauchy distribution enjoys closed-form pdf and closed-form inverse pdf, which means that $X$ can be generated by the inverse pdf transform as
$$X = \gamma\tan(\pi U-\pi/2)\qquad U\sim\mathcal U(0,1)$$
Therefore the random variable $\theta\sim f_{WC}(\theta;\gamma)$ can be written (and simulated) as
$$\theta = [\gamma\tan(\pi U-\pi/2)+\pi]\ \text{mod}\,(2\pi) - \pi\tag{1}\qquad U\sim\mathcal U(0,1)$$
As an R code, this translates into
rwauchy <- function(n=1,gamma=1) (tan(pi*(runif(n)-.5))*gamma+pi)%%(2*pi)-pi

and the fit of the histogram with the density $f_{WC}$ is illustrated below

$^1$Formula cut&pasted from Wikipedia.
$^2$The correspondence between $\gamma$ and $p$ is$$\gamma=\tanh^{-1}\frac{1-p^2}{1+p^2}$$
Comment: Thanks @Xi'an I forgot to mention my wrapping for the Cauchy distribution, but I also get this. Now I'd like to have a map between a uniform distribution and the wrapped Cauchy....if this is even possible, perhaps a rough map would work for low values?
Comment: thanks, so I start with my uniform distribution $U(q)$ and generate a random number between $-q$ and $q$. I put this into eqn (1), and I'd like to find $p$. We know how $p$ and $\gamma$ relate. Eqn(1) gives me $\theta$ given some $\gamma$ and my random number. I'm not sure we know enough?
Comment: Because all I know is the $q$ I used to generate the random number from $U[-q,q]$ and now I'd like an equivalent $p$, if possible?
Comment: Could I pick a $\theta$ to assess the equation at, say, in the tail of the distribution?
Comment: So I decided to test the distributions at 25%. For the uniform distribution, that occurs at $x=0.25*(q--q) + -q = -0.5q$. I wrote code to find the 25% in the wrapped cauchy: ```prange = np.linspace(0.05,0.95,1000)
twentyfive = np.zeros(len(prange))

for pp in range(len(prange)):

  wc_int = np.arctan2(prange[pp]-1,(prange[pp]+1)*np.tan(x/2))/np.pi
  plt.plot(x,wc_int+1)
  twentyfive[pp] = wc_int.flat[np.abs(wc_int +1 - 0.25).argmin()]

plt.show()

plt.plot(prange,twentyfive)
plt.show()
plt.plot(twentyfive/-0.5) ``` but I'm not sure it matches well


How to obtain the values used in plot.gam in mgcv?

Question: I would like to find out the values (x, y) used in plotting plot(b, seWithMean=TRUE) in mgcv package.  Does anyone know how I can extract or compute these values?
Here is an example:
library(mgcv)
set.seed(0)
dat <- gamSim(1, n=400, dist="normal", scale=2)
b   <- gam(y~s(x0), data=dat)
plot(b, seWithMean=TRUE)

Comment: I'm not familiar with `gam` models, but have you examined the different attributes of that object? You can look at the names of the objects with `names(b)`. I'm guessing whatever details you are after will be retained within that object somewhere.
Answer: Starting with mgcv 1.8-6, plot.gam invisibly returns the data it uses to generate the plots, i.e. doing
pd <- plot(<some gam() model>)
gives you a list with the plotting data in pd.

ANSWER BELOW FOR mgcv <= 1.8-5:
I've repeatedly cursed the fact that the plot functions for mgcv don't return the stuff they are plotting -- what follows is ugly but it works:
library(mgcv)
set.seed(0)
dat <- gamSim(1, n = 400, dist = "normal", scale = 2)
b <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat)

plotData <- list()
trace(mgcv:::plot.gam, at = list(c(27, 1)),
  ## tested for mgcv_1.8-4. other versions may need different at-argument.
  quote({
    message("ooh, so dirty -- assigning into globalenv()'s plotData...")
    plotData <<- pd
    }))
mgcv::plot.gam(b, seWithMean = TRUE, pages = 1)

par(mfrow = c(2, 2))
for (i in 1:4) {
  plot(plotData[[i]]$x, plotData[[i]]$fit, type = "l", xlim = plotData[[i]]$xlim,
    ylim = range(plotData[[i]]$fit + plotData[[i]]$se, plotData[[i]]$fit -
      plotData[[i]]$se))
  matlines(plotData[[i]]$x, cbind(plotData[[i]]$fit + plotData[[i]]$se,
    plotData[[i]]$fit - plotData[[i]]$se), lty = 2, col = 1)
  rug(plotData[[i]]$raw)
}

Comment: Many thanks for your help. When I reproduce your code up to  `plotData <<- c(plotData, pd[[i]])}))
`, the following message occurs `Error in fBody[[i]] : no such index at level 3`. Any ideas why it does not work?
Comment: The "trace" trick used to work for me. However, it recently failed me. I suspect it has to do with a new version of mgcv package (I'm currently using v 1.8-3), which may require a different "at" argument in the trace function. Can anyone help me on how to get the correct vector for the "at" argument of the trace function? Many thanks in advance!
Comment: @Pepijn see my edit.
Answer: Package visreg can make effect plots similar to GAM (but perhaps not identical?) and does give the plot components as output as well, formatted as a list. Using plyr one can make a dataframe of the output. Example:
plot <- visreg(model, type = "contrast")
smooths <- ldply(plot, function(part)
  data.frame(x=part$x$xx, smooth=part$y$fit, lower=part$y$lwr, upper=part$y$upr))

Answer: This will not be a complete answer. All the plotting for gam objects is being done with function plot.gam. You can look at its code by simply typing
> plot.gam

in R console. As you will see the code is huge. What I've gleaned from it, that all the plotting is done by gathering relevant information in pd object which is a list. So one of the possible solution would be to edit plot.gam, using edit for example, so that it returns that object. Adding pd before last } will be enough. I would advise adding invisible(pd), so that this object is returned only if you ask for it:
> pd <- plot(b,seWithMean = TRUE)

Then inspect this object and search in the code of plot.gam for the lines with plot and lines. Then you will see which of the relevant x and y values appear in the plot.
Comment: oops, I didn't see yours when I posted my answer. Well, it's a little more detailed anyway....
Comment: @fabians, no worries, I would not have posted mine if I saw yours. I outlined general idea, you have provided the code. Since the question asks for code, your answer is better.
Answer: ## And this is the code for multiple variables!
require(mgcv)
n      = 100
N      = n
tt     = 1:n
arfun  = c(rep(.7,round(n/3)),rep(.3,round(n/3)),rep(-.3,ceiling(n/3)))
arfun2 = c(rep(.8,round(n/3)),rep(.3,round(n/3)),rep(-.3,ceiling(n/3)))
int    = .1*(tt-mean(tt))/max(tt)-.1*((tt-mean(tt))/(max(tt)/10))^2
y      = rep(NA,n)
s.sample <- N
x        <- 10*rnorm(s.sample)
z        <- 10*rnorm(s.sample)
for(j in 1:n){
  y[j]=int[j]+x[j]*arfun[j]+z[j]*arfun2[j]+rnorm(1)
}

mod = gam(y ~ s(tt) + s(tt, by=x) + s(tt, by=z))
## getting the data out of the plot
plotData <- list()
trace(mgcv:::plot.gam, at=list(c(25,3,3,3)),
      # this gets you to the location where plot.gam calls
      #    plot.mgcv.smooth (see ?trace)
      # plot.mgcv.smooth is the function that does the actual plotting and
      # we simply assign its main argument into the global workspace
      # so we can work with it later.....

      quote({
        # browser()
        print(pd)
        plotData <<- c(plotData, pd)
      }))

# test:
mgcv::plot.gam(mod, seWithMean=TRUE)

# see if it succeeded
slct = 3
plot(plotData[[slct]]$x, plotData[[slct]]$fit, type="l", xlim=plotData$xlim,
     ylim=range(plotData[[slct]]$fit + plotData[[slct]]$se, plotData[[slct]]$fit -
                plotData[[slct]]$se))
matlines(plotData[[slct]]$x,
         cbind(plotData[[slct]]$fit + plotData[[slct]]$se,
               plotData[[slct]]$fit - plotData[[slct]]$se), lty=2, col=1)
rug(plotData[[slct]]$raw)


Add MySQL as a resource to pacemaker

Question: I am trying to enable fail over strategy using pacemaker on a mysql Master-Master replication on two virtual machine running openSUSE 12 created by VritualBox.
I managed to complete the mysql dual-master replication, and it seems to work. Server A has 192.168.X.a as IP while server B's IP is 192.168.X.b. I followed the instruction here, so basically my corosync.conf looks like the one presented in the guide, except the interface section which is written below:
interface {
    ringnumber: 0
    bindnetaddr: 192.168.X.c
    mcastaddr: 18.104.22.168
    mcastport: 5405
    ttl: 1
}

My first question is: what exactly is bindnetaddr:? Is it the virtual IP of my cluster? If not, should it be the other nodes IP or it own IP? (I mean IP of the server has this config or the other server)
My second question is: what are mcastaddr and mcastport and what should they be set to?
Then I tried to add MySQL as a resource, so I did as described here. But when I enter crm configure primitive ip_mysql ocf:heartbeat:IPaddr2 params ip="192.168.X.c" I get
crm configure primitive ip_my ocf:heartbeat:IPaddr2 params ip='192.168.114.8'
crm_verify[23888]: 2012/12/29_12:25:51 WARN: cluster_option: Using deprecated name
'stonith_enabled' for cluster option 'stonith-enabled'
Warnings found during check: config may not be valid

My third question is: when providing the params ip to configure primitive, should it be the virtual IP? (the one set in the corosync.conf file)
My forth question is: should I ignore the warnings?
To be honest I didn't go any further when I faced the warnings, and since I had lots of uncertainties, I thought It's better fisrt to make sure I'm on the right path.
On a different note, I would be more than thankful if anybody could link me to a simple/good tutorial on using Pacemaker/Corosync and mySQL replication NOT DRDB or using XtraDB and ....simple dual-master replication...most of tutorial availabe on web are for DRDB and XtraDB, or other tools. I know the procedure should be the same (adding a resource to pacemaker) but I was not successful on extracting the similarities from those tutorials...
Comment: Nice first post!
Comment: Also can you compare your setup to this tutorial that shows pacemaker being used to HA apache, http://andriigrytsenko.net/2011/07/pacemaker-and-apache/
Comment: I think `bindnetaddr: 192.168.X.c` should be `bindnetaddr: 192.168.1.0`. It's the network address is it not?
Comment: yes, `bindnetaddr` seems to be the network address to bind to. My IP addresses is `192.168.114.x`, that is why I set it to `bindnetaddr: 192.168.114.c` instead of `bindnetaddr: 192.168.1.0`... am I correct? anyhow, my question would be if this is the virtual IP I have my pacemaker set to.
Comment: OK, you're example didn't show the .114 subnet so that makes more sense. Yeah I would expect that param to be the virutal ip. This SF post might be helpful, http://serverfault.com/questions/418634/secure-iptables-rules-for-corosync
Answer: Answer of question one
bindnetaddr is the network address we want pacemaker/corosync(?) to bind to. So if your servers have A.B.C.x and A.B.C.y as IP address, then in corosync configuration file, you have to assign bindnetaddr to A.B.C.0.
Answer of question two
mcastaddr is the IP address to use for multicasting and mcastport is the port to use for cluster communication. In order to communicate with each other, all nodes belonging to the same cluster need to use the same bindnetaddr, mcastaddr and mcastport.
Answer of question three
params ip is the virtual IP. If you have set your bindnetaddr to A.B.C.0 then your virtual IP should be A.B.C.z.
Answer of question four
Those warnings didn't affect my cluster. SO yes I ignored them.
Beside the links @slm (see resources below) provided in his comments on my question, this tutorial on HeartBeat MySQL resource agent and this high availability guide helped me to setup and configure my cluster.
Resources

Secure IPTables rules for Corosync
Pacemaker and Apache - Howto Configure Pacemaker Apache fail-over

Add MySQL as a resource to pacemaker


weka J48 classifier does not generate any result

Question: I have a data set of about 40000 data points. Each data point has 15 nominal features.
The data set has 6 classes.
When i load the arff file into weka and try running the J48 classifier, i get no output at all.
Weka runs for a few seconds and terminates after printing the attribute count and attribute list.
I get no additional information despite turning the debug flag on.
What could this mean? and how do i fix it?
Comment: please add some code to your question
Comment: I used the Weka UI, so i do not have any code to share. Checking the "Output Source Code" option does not generate code either
Comment: Perhaps a screenshot/printout of the training and the Parameters of the J48 Classifier could assist if possible.
Comment: I had used a confidence factor of 0.25 and a minNumObj of 2
Answer: I increased the java heap size by editing the maxHeap in the RunWeka.ini and that seemed to fix the problem for me. It strange because i'd usually see a visible error for low heap cases.


Why is $\sum_{i=1}^n\frac n{n-i+1}=n\sum_{i=1}^n\frac1i$?

Question: While reading through my (algorithms and) probability script, I have seen this equality for calculating the first moment of the coupon-collector problem. However, I don't quite see how the sum of the fraction on the left can be split up in such a way, that the sum of the fraction on the right is equal to it.
$$\sum_{i=1}^n\frac n{n-i+1}=n\sum_{i=1}^n\frac1i$$
I assume it is about partial fraction decomposition, but I don't know how to apply it here.
Comment: $$\frac44+\frac43+\frac42+\frac41=4\left(\frac11+\frac12+\frac13+\frac14\right)$$
Answer: Pull $n$ out of the sum and make the chage of variable $j=n-i+1$.
Answer: It's just reverse summation order:
$$\sum_{i=1}^n \frac1i = 1 + \frac12 + \frac13 + ... + \frac1n$$
$$\sum_{i=1}^n \frac1{n-i+1} = \frac1n + \frac1{n-1} + \frac1{n-2} + ... + 1.$$
Answer: This is just reindexing. As $i$ runs from $1$ to $n$, $n-i+1$ runs from $n$ to $1$. So we may rewrite the LHS as $\sum_{i=1}^n\frac ni$.


Question about absolute value

Question: In $\mathbb{R}$, I know that
\begin{equation*}
|x|=
\begin{cases}
x&\mbox{$x\geq0$}\\
-x&\mbox{$x<0$}
\end{cases}
\end{equation*}
What's the $|\cdot|$ in $\mathbb{R}^d$? Is it $|x|=(|x_1|,\ldots,|x_d|)$?
Comment: it usually means the euclidean norm $\sqrt{\sum_{i=1}^d |x_i|^2}$
Comment: @PrahladVaidyanathan: *usually* being the operative word.
Comment: Perhaps ([tag:notation]) and ([tag:norm]) would be suitable tags for the questions; although it depends on the context.
Answer: The notation $|x|$ is really asking for the size of $x$, i.e. how far away it is from zero. Hence, both $+2$ and $-2$ are two units away from zero and so we have $|-2|=|+2|=2$.
In two dimensions we can ask about the "size" of the point $(x,y)$. We usually write this $\|(x,y)\|$. If you use Pythagoras' Theorem, you will see that the point $(x,y)$ is a distance $\sqrt{x^2+y^2}$ from the origin $(0,0)$. You can think of this as the "size" of $(x,y)$.
The same idea extends into three, four, and even higher dimensions. In three dimensions, the point $(x,y,z)$ is a distance $\sqrt{x^2+y^2+z^2}$ from the origin $(0,0,0)$.
In $\mathbb{R}^d$, the point $(x_1,x_2,\ldots,x_d)$ is a distance $\sqrt{x_1^2+x_2^2+\cdots+x_d^2}$ from the origin $(0,0,\ldots,0)$.
Answer: This really depends on the context. For example, $\mathbb R^d$ with pointwise ordering could be considered as a Riesz space (vector lattice).
In such spaces the absolute value is defined as $|x|=x^-x^-$, where $x^+=x\vee 0$ and $x^-=(-x)\vee 0$.
So in $\mathbb R^d$ with partial ordering $$(x_1,\dots,x_n)\le (x_1',\dots,x_n') \qquad \Leftrightarrow \qquad x_1\le x_1' \land \dots \land x_n\le x_n'$$ you indeed get $$|x|=(|x_1|,\dots,|x_n|).$$
Answer: There are multiple meaning for $||x||$ or $|x|$when $x\in \mathbb{R}^d$. Generally $||x||$ is called the norm of $x$.
The norm is defined only by certain characteristics. Any function that follows these characteristics can be considered a norm. So based on the context one can choose the norm one wants. The norm given in Fly by Night's answer is called the Euclidean norm and commonly written with single lines as you have $|x|$ when $x\in \mathbb{R}$ (Can use single line in higher spaces too, a matter of preference). Other norms in Euclidean space include Manhattan norm, p-norm etc. The characteristics of a norm function are: absolute scalability, follow triangle inequality and zero only at zero. From these non-negativity follows.
Please refer http://www-solar.mcs.st-andrews.ac.uk/~clare/Lectures/num-analysis/Numan_chap1.pdf and http://mathworld.wolfram.com/VectorNorm.html for a quick reference.
And refer Symbol for Euclidean norm (Euclidean distance) for a discussion on notation.
Comment: Also can read http://en.wikipedia.org/wiki/Norm_(mathematics).

Question about absolute value


GET/POST Requst to REST API using Spring Boot

Question: I have a REST Service an external server like https://api.myrestservice.com and I have a Spring Boot Application running locally on http://localhost:8080. Now I want to make GET or POST request to the REST API address i.e https://api.myrestservice.com/users to get all users, using my locally running Spring Boot App i.e through http://localhost:8080/users. I am not getting how to redirect local app request to external server request.
Comment: You need to make an external API request to `https://api.myrestservice.com/users`. For this, you can use services such as `REST Template(Spring) ` or even external ones such as `Unirest`. Search for examples, you will find a lot of them
Answer: I hope I got your question right. You are trying get your local app to get data from app running on your server.
You can use the below sample code in your spring boot application.

private void getUsers() {

     final String uri = "https://api.myrestservice.com/users";
     RestTemplate restTemplate = new RestTemplate();
     Users result = restTemplate.getForObject(uri, Users.class);
     System.out.println(result);
}

Then your getUsers can be invoked by getUsers Controller in your spring boot app.
I am adding the reference if you want to look at more examples -
https://howtodoinjava.com/spring-restful/spring-restful-client-resttemplate-example/
Answer: Making post Api call from your code to another server:
suppose you have a server     https://searchEmployee... which returns you list of employees belonging to a particular city or belonging to a particular organization:
request body:
{
"city" : "Ranchi",
"organisation" : "Bank Of America"
}

json response: [{"name": "Vikash"},{"name":"kumar" },{}...etc]
Then to make a post api call you can use RestTemplate in java like this:
public void makeApiCall(){
    final String uri = "https://searchEmployee...";

    RestTemplate restTemplate = new RestTemplate();

    String reqBody = "{"city": "Ranchi"}";
    String result = restTemplate.postForObject(uri, reqBody, String.class);

    // convert your result into json

    try {
                jsonResponse = new JSONObject(result);
        } catch (JSONException e) {
            e.printStackTrace();
        }
   //extract a value "name" from your json data:
   try{
    String value = jsonResponse.getString("name");
    }catch(JSONException e) {
            e.printStackTrace();
        }
}

/********************************************************************/
if you have more than one request body parameters to set do it like this:
String reqBody = "{\"quantity\":100,\"name\":\"product1\",\"ifBoolean\":false}";

false is a boolean value here in your request body and 100 is an integer.
NOTE
if you are having problem in setting request body copy it directly from postman request body and paste it inside double quote.
Answer: There are many ways to do it. Like Apache HTTP Components and other. Sample
String type = "application/x-www-form-urlencoded" Or Set your desire content type;
String encodedData = URLEncoder.encode( rawData, "UTF-8" );
URL u = new URL("your remote url");
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty( "Content-Type", type );
conn.setRequestProperty( "Content-Length",
String.valueOf(encodedData.length()));
OutputStream os = conn.getOutputStream();
os.write(encodedData.getBytes());

There are a couple of thing going on here, Like URLEncoding is really mattered when came to security.
Note: Source of above code:here.
Comment: Also different server does not matter. Only matter is Server Up and running or not
Answer: This is very Simple By using Java Clients you can Use RestTemplate or UniRest
That one running on Remote is simply Producer and the one which  is in local is Consumer So you can exchange method of Resttemplate or get method of Unirest
Example Code is here.
@RequestMapping(value = "/testclient")
    public String testclient()
    {
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        return restTemplate.exchange("https://www.mocky.io/v2/5185415ba171ea3a00704eed", HttpMethod.GET, entity, String.class).getBody();
}

For Unirest code is like this
HttpResponse<JsonNode> jsonResponse = null;
    try {
        jsonResponse = Unirest.get("https://www.mocky.io/v2/5185415ba171ea3a00704eed")
                .header("accept", "application/json").queryString("apiKey", "123").asJson();
    } catch (UnirestException e) { // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return jsonResponse.getBody().toString();


Stepwise Generalised Linear Model

Question: As a statistics student I am in search of R code for a GLM, which is calculated stepwise. So far, the best I've found is for a Poisson Regression, but I need to find a Gaussian version of this:
library(MASS)
poisreg = function(n, b1, y, x1, tolerence) {  # n is the number of iterations
  x0 = rep(1, length(x1))
  x  = cbind(x0, x1)
  y  = as.matrix(y)
  w  = matrix(0, nrow = (length(y)), ncol = (length(y)))
  b0 = b1
  result = b0
  for (i in 1:n) {
    mu = exp(x %*% b0)
    diag(w) = mu
    eta = x %*% b0
    z = eta + (y - mu) * (1/mu)   # dot product of (y - mu) & (1/mu)
    xtwx = t(x) %*% w %*% x
    xtwz = t(x) %*% w %*% z
    b1 = solve(xtwx, xtwz)
    if(sqrt(sum(b0 - b1)^2) > tolerence) (b0 <- b1)
    result <- cbind(result,b1) # to get all the iterated values
  }
  result
}
x1 <- c(-1,-1,0,0,0,0,1,1,1) # x1 is the explanatory variable
y  <- c(2,3,6,7,8,9,10,12,15)  # y is the dependent variable
b1 = c(1,2) # initial value
poisreg (10, b1, y, x1, .001)   # Nicely converge after 10 iterations
glm(y~x1, family=poisson(link="log"))   # check your result with the R GLM program

I'd be very grateful for any help in searching for code like this that calculates Gaussian GLM. If y you're interested: my ultimate aim is to play about with the tolerances of the GLM so that the fitted model lies between specified upper and lower bounds.
Comment: This is confusing. Do you mean stepwise regression, as in fitting several different models to choose the best one, or do you mean stepping through each iteration in the fitting algorithm for a single model?
Answer: I'm not sure why you're rolling your own code; stepwise regression is already available in R via the step function. This works with any specification of generalized linear model, including ordinary linear regression (which is what we usually call a Gaussian GLM).
From the ?step examples:
lm1 <- lm(Fertility ~ ., data = swiss))
slm1 <- step(lm1)

# <...many lines of output...>

summary(slm1)

# Call:
# lm(formula = Fertility ~ Agriculture + Education + Catholic +
#     Infant.Mortality, data = swiss)
#
# Residuals:
#      Min       1Q   Median       3Q      Max
# -14.6765  -6.0522   0.7514   3.1664  16.1422
#
# Coefficients:
#                  Estimate Std. Error t value Pr(>|t|)
# (Intercept)      62.10131    9.60489   6.466 8.49e-08 ***
# Agriculture      -0.15462    0.06819  -2.267  0.02857 *
# Education        -0.98026    0.14814  -6.617 5.14e-08 ***
# Catholic          0.12467    0.02889   4.315 9.50e-05 ***
# Infant.Mortality  1.07844    0.38187   2.824  0.00722 **
# ---
# Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#
# Residual standard error: 7.168 on 42 degrees of freedom
# Multiple R-squared:  0.6993,  Adjusted R-squared:  0.6707
# F-statistic: 24.42 on 4 and 42 DF,  p-value: 1.717e-10

On re-reading the question, maybe you're actually not asking about stepwise modelling at all.
If you actually want to ask, why don't we have an interative algorithm for Gaussian GLMs, the answer is we don't need one! The usual algorithm for fitting a GLM, iterative (re)weighted least squares, works by fitting least-squares regressions for specially weighted and transformed versions of the data. If your model has a Gaussian error and identity link, then the weights and transformations disappear, so IRLS reduces to standard least squares. Hence you don't need to do any iterations.

Stepwise Generalised Linear Model


Geometric meaning of Line-bundle product

Question: I was wondering,

What could be a geometric/intuitive meaning of taking the (tensor) product of two line bundles on a smooth variety. Could you depict this to me with some example?

Computationally it is very clear in terms of transition functions: we are just taking the product of the two. What I miss is a mental picture of $L_1\otimes L_2$.
These thoughts originated from considering the Adjunction Formula
$K_V = (K_X \otimes [V])_V$
Here $X$ is a compact manifold and $K_V$ is the canonical bundle of a smooth hypersurface $V\subset X$, expressed in terms of the canonical bundle of $X$ times $[V]$, the line bundle of $X$ associated to $V$.
So a second and more specific question is about the geometric meaning of the adjoint bundle $K_X \otimes [V]$ on $X$. Could you depict this to me with examples? Thanks!
Answer: About your first question:
Since you're variety is smooth, you can think of (isomorphism classes of) line bundles as (equivalence classes of) Weil divisors. The tensor product then corresponds to the sum of Weil divisors, which is very geometric.
Intuitively this correspondence also makes a lot of sense, since you would certainly expect the zeroes of a product to be the union of the zeroes of the two individual sections.
As an example i would take lines in the projective plane $\mathbb{P}^2$. A bundle with degree 2, normally denoted $\mathcal{O}_{\mathbb{P}^2}(2)$ corresponds to a Weil divisor given by a conic. Similarly a bundle of degree 1 $\mathcal{O}_{\mathbb{P}^2}(1)$ corresponds to a degree 1 curve: a line.
The tensor product is $\mathcal{O}_{\mathbb{P}^2}(3)$, the sum of the Weil divisors is a conic plus a line, which is a (degenerate, but nonetheless a) cubic curve. This makes total sense: the tensor product has degree three so we know a priori that a corresponding Weil divisor must have degree 3.
As for the second question, a nice proof is given in Georges' answer to a question of mine posted earlier:
Adjunction for varieties with higher codimension
I don't think you're interested in the question, but you might be in the answer, it is relevant for your question.
Finally, i don't know any specific geometric interpretation of the adjoint bundle. Maybe someone else knows.
I can however tell you two places where it pops up a lot.
First, it is part of the Riemann-Roch formula on surfaces which is an immensely useful theorem in the theory of algebraic surfaces. Possbily it is also used in other Riemann-Rochs, i don't know.
Second, if the dimension of $X$ is $n$, Serre duality gives roughly an isomorphism
$$
H^i(X, \mathcal{L}) \cong H^{n-i}(X, K_X \otimes \mathcal{L}^{-1})
$$
again an occurence of this adjoint bundle as you call it.
Note that i wrote roughly: the precise statement of Serre duality is different and i am simplyfing a bit (in a harmless way for the mental picture).
I hope this helps.


Why the largest singular value of a magic matrix is its magic constant?

Question: A magic matrix is a square matrix such that the sums of the elements of each row, each column and diagonal equal to a same number, the magic constant.
As reported here, the largest singular value of a magic matrix is its magic constant.
Can someone provide a proof or an intuition for that?
Comment: Trivially, if $A$ is a magic square with magic constant $M$, then the vector of all $1$'s is an eigenvector of $A^TA$ with eigenvalue $M^2$, so $M$ is a singular value of $A$. Now, how to show it is the largest?
Answer: It sounds like a magic matrix is a special case of a doubly stochastic matrix, (and in turn a special case of a stochastic matrix), scaled by a scalar value: the magic constant.
A stochastic matrix is just a square matrix of nonnegative real numbers with each row summing to $1$.
The Perron–Frobenius theorem ensures that every stochastic matrix has an eigenvalue equal to $1$, and that is the eigenvalue with the largest absolute value.
Answer: Consider a magic square matrix $\mathbf{A}\in \mathbb{R}^{n\times n}$. Denote the magic constant by
$$
s=\frac{n(1+n^2)}{2}.
$$
Since the sum of each row or column equals to $s$, we know that $s$ is a singular value of $\mathbf{A}$, i.e.:
$$
\mathbf{A}^\text{T}\mathbf{Av}=s^2\mathbf{v} \text{, where } \mathbf{v}=[1,\dots,1]^\text{T}.
$$
We know that the singular values of $\mathbf{A}$ satisfy that
$$
\sum_i\sigma_i^2=\text{tr}(\mathbf{A}^\text{T}\mathbf{A})=\sum_i\sum_j a_{ij}^2.
$$
The sum of squares of all entries equals to $\sum_{k=1}^{n^2}k^2=\frac{1}{3}n^6+\frac{1}{2}n^4+\frac{1}{6}n^2$. We have $s^2=\frac{1}{4}n^6+\frac{1}{2}n^4+\frac{1}{4}n^2$, so
$$
\sum_i\sigma_i^2  < 2s^2.
$$
This indicates that all other singular values are smaller than $s$.
Hope this could be helpful.


How do I redirect cucumber failed scenarios to stderr?

Question: Unluckily it seems that everything goes to stdout...
Comment: It's outputting test failures, not an error that happened while running Cucumber itself, so it wouldn't have been correct to send it to stderr.
Comment: I agree the concept of 'error' in a testing tool is more complicated than normal... but consider this: when some features/tests are failing cucumber or rspec exit to the shell with a '1' value. That signals an 'error' to the shell.
Answer: The cucumber formatters take a single IO object, which will either be a file if you specify the --out option on the command line, or STDOUT if it is the last or only formatter specified.
Cucumber scenarios tend to fail partially, with the first few steps passing before a failure occurs, so you'd have to consider exactly what information you'd want to be written to STDOUT.
You could certainly create a custom cucumber formatter that wrote different bits of information to different IO streams, it's fairly easy to see how they work by looking at the built-in formatters.  As Andrew Marshall pointed out in the comments though, it's not really the correct use of stderr.
Comment: I posted a comment to the previous answer that applies here too: why cucumber returns '1' to the shell when failing some features?
Comment: Interesting point, one that's bitten me recently because I was trying to figure out how to differentiate between a cucumber run that *failed to execute properly* (i.e. crashed during startup), and one that ran successfully but had failing tests - it didn't really seem possible!  But to answer your question, it's standard for testing tools to return a non-zero exit code when tests fail, it's how build runners detect the failed tests and know whether to fail the build or not.
Comment: Exactly. The genesis of my question comes from a bunch of scripts I wrote for a continuous integration bot. Obviously I send an email to the devs when cucumber exit with a '1' value. What I wanted to do was to filter out non-relevant output to send devs infos about failing scenarios only.

[Regarding 'cucumber crashes' it would be nice to have an exit value different from 0 or 1 (not to break CI tools) or even better to return a value of '1' for crashes and another non-zero value for failing scenarios. But that's another story.] Thanks for your answers anyway.


Search specific word and delete it from file in linux

Question: I have a file (file1.txt) which contains below text:
mon
tue
tue_day
tuesday
wed

and I want to search for a word "tue" and delete it from this file.
I used
sed -i "/tue/d" file1.txt

but it deletes all the lines containing tue word i.e. line 2,3 and 4. I want to delete the only line 2 which conatins exact same text that i want to remove from file.
could you please suggest?
Comment: google `regexp tutorial` and take it.
Answer: Just tell sed that you want lines that are exactly "tue". How? Prepending and appending ^ and $ to indicate beginning and end of line:
$ sed '/^tue$/d' file
mon
tue_day
tuesday
wed

To replace with something given in a variable, use double quotes like this:
var="tue"
sed -i "/^$var$/d" file

Comment: Consider making the section of your script exposed to shell as brief as possible: `sed -i '/^'"$var"'$/d' file`. I don't think it'll matter in this case but it's a more robust style to get into the habit of using so you aren't surprised by gothcas when your scripts get larger and/or more complicated.
Comment: Thanks it worked...
one more query how do I use variable in place of "tue" in sed command?
like now I use:
sed -i "/$var/d" file
Comment: @SagarPatil just say `var="tue"` and then `sed -i "/^$var$/d" file`. Note you have to use double quotes to have the variables expanded. I have updated my answer to reflect this.


Material Design Lite Icons missing when using in Angular

Question: So I started to use MDL inside my Angular project, which works mostly fine, but the MDL icons are just not working in there...
I'm using them like this share and the browser just writes "share" as normal font and not as Icon like it should do it. I've got the mdl css and js included and also got the angular-material-design-lite package included.
Answer: You have to make sure all fonts assets(.woff,.svg,.tff etc) are correctly installed, also the font-face in your css sheet is referred in the correct path.
Answer: Seems like I just had to install the font via bower : bower install material-design-icons --save and add this to my css :
.material-icons {
    font-family: 'Material Icons';
    font-weight: normal;
    font-style: normal;
    font-size: 24px;
    line-height: 1;
    letter-spacing: normal;
    text-transform: none;
    display: inline-block;
    white-space: nowrap;
    word-wrap: normal;
    direction: ltr;
    -webkit-font-feature-settings: 'liga';
    -webkit-font-smoothing: antialiased;
}