Why does an action for a view (Button in this case) have to take a View as a parameter?

Question: I'm a newbie with android development, but not really with Java.
What I don't understand is why a method I define in the Button must to take View as a paremeter.
For example..
in  XML
<Button
        android:id="@+id/button1"
        //etc..
        //etc..
        android:onClick="displayText" />

As can be seen, this is the onClick method.
When I'm writing Java code the method displayText will be defined like so
public void displayText(View view){
        TextView myTextView = (TextView)findViewById(R.id.textView1);
        myTextView.setVisibility(View.VISIBLE);
    }

When everything works fine, the text I have originally hidden, will be displayed via a simple click of a button.
When I remove the parameters View view from this method, the app crashes when I try to click the button.
I fail to understand why.
I'm not necessarily doing anything with the view in the parameter.
In non android development I could use the view that is in the parameter and do things with it.. but I don't see that I'm doing anything WITH this parameter.. so why is it required in this method?
Comment: **"...so why is it required in this method?"** Because you can have multiple Buttons (or other classes which extend View) that might use the same OnClickListener. In order to work out which one has been clicked you would use a switch/case block switching on `view.getId()` which returns the resource id set by `android:id=`.
Answer: Potentially, the same method could be used to handle several views' click event. The View view parameter would let you know which one is the source of the event. I.e. which button was clicked.
The reason it is required it's because it has to match the interface. When trying to match the function name in the XML to the functions available, it can't be found.
Answer: A Button is a subclass of a View. So when methods take a View, it means they can be get a Button as input, but also other subclasses of View.
The View is given in the parameter, so you can modify the View that was clicked.
BTW, I didn't know you could implement click listeners like this. I normally do it like this:
button.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View view){
        // handle
    }
});

Comment: Yes, that I do that too sometimes. Edited my answer to avoid making statements about what is **normal** in general.
Comment: **"Normally you'd do it like this:"** - I rarely do it like that. Normally I have an `Activity` implement the `View.OnClickListener` interface directly and then override `onClick(...)` as a method in the `Activity` itself. Much cleaner if you have a lot of buttons as you don't have multiple anonymous `OnClickListener` instances.
Answer: I have searched Stackoverflow but never found a question that suited what I was looking for so I made this question.
The two answers given here we're a little too short for me to wrap my head around a method having parameters but never using them.
Then I looked at the "Related" section on the side and found a question better worded than mine and answers that were longer and satisfied my question and answered it in more detail.
Thank's to all those that responded here. If anyone else finds them selves in the same problem, here is the question/answer that helped me understand it.
Why do android methods accept View objects, but the objects are unused?


Traverse to the second table using dom parser

Question: I have code like

i want to traverse to the second table using jquery. How do i do it.
Comment: Last time I checked `` is the markup for tables, not `` :s
Answer: You can get the second table element by this expression:
var secondTable = $('table').eq(1); // index is zero-based


How to use URL parameters

Question: How do you make url parameters like this work?:
/searchtestingv4.php?categories=rockandpop&sort=PriceLow
or
/searchtestingv4.php?sort=PriceLow&page=2
Here is where i'm trying it: http://tinyurl.com/bv6fm7b
and here's my code:
Pagination:
$tableName="searchacts";
    $targetpage = "searchtestingv4.php";
    $limit = 5;

    $query = "SELECT COUNT(*) as num FROM $tableName";
    $total_pages = mysql_fetch_array(mysql_query($query));
    $total_pages = $total_pages[num];

    $stages = 3;
    $page = mysql_escape_string($_GET['page']);
    if($page){
        $start = ($page - 1) * $limit;
    }else{
        $start = 0;
        }

    // Get page data
    $query = "SELECT * FROM $tableName LIMIT $start, $limit";
    $result = mysql_query($query);

    // Initial page num setup
    if ($page == 0){$page = 1;}
    $prev = $page - 1;
    $next = $page + 1;
    $lastpage = ceil($total_pages/$limit);
    $LastPagem1 = $lastpage - 1;

    $paginate = '';
    if($lastpage > 1)
    {

        $paginate .= "
";
        // Previous
        if ($page > 1){
            $paginate.= "previous";
        }else{
            $paginate.= "previous";   }

        // Pages
        if ($lastpage < 7 + ($stages * 2))  // Not enough pages to breaking it up
        {
            for ($counter = 1; $counter <= $lastpage; $counter++)
            {
                if ($counter == $page){
                    $paginate.= "$counter";
                }else{
                    $paginate.= "$counter";}
            }
        }
        elseif($lastpage > 5 + ($stages * 2))   // Enough pages to hide a few?
        {
            // Beginning only hide later pages
            if($page < 1 + ($stages * 2))
            {
                for ($counter = 1; $counter < 4 + ($stages * 2); $counter++)
                {
                    if ($counter == $page){
                        $paginate.= "$counter";
                    }else{
                        $paginate.= "$counter";}
                }
                $paginate.= "...";
                $paginate.= "$LastPagem1";
                $paginate.= "$lastpage";
            }
            // Middle hide some front and some back
            elseif($lastpage - ($stages * 2) > $page && $page > ($stages * 2))
            {
                $paginate.= "1";
                $paginate.= "2";
                $paginate.= "...";
                for ($counter = $page - $stages; $counter <= $page + $stages; $counter++)
                {
                    if ($counter == $page){
                        $paginate.= "$counter";
                    }else{
                        $paginate.= "$counter";}
                }
                $paginate.= "...";
                $paginate.= "$LastPagem1";
                $paginate.= "$lastpage";
            }
            // End only hide early pages
            else
            {
                $paginate.= "1";
                $paginate.= "2";
                $paginate.= "...";
                for ($counter = $lastpage - (2 + ($stages * 2)); $counter <= $lastpage; $counter++)
                {
                    if ($counter == $page){
                        $paginate.= "$counter";
                    }else{
                        $paginate.= "$counter";}
                }
            }
        }

                // Next
        if ($page < $counter - 1){
            $paginate.= "next";
        }else{
            $paginate.= "next";
            }

        $paginate.= "
";

}
 echo $total_pages.' Results';
 // pagination
 echo $paginate;

Categories filtered by where:
if($_GET['categories'] == 'rockandpop') {

        $query = "SELECT * FROM searchacts WHERE category='Rock and Pop'";
    }

        if($_GET['categories'] == 'tributebands') {

        $query = "SELECT * FROM searchacts WHERE category='Tribute Bands'";
    }

Up to price filtered by where eg:
// process form when posted
if(isset($_GET['upto'])) {
    if($_GET['upto'] == 'upto100') {

        $query = "SELECT * FROM searchacts WHERE price <= '100'";
    }

Sort by options eg:
// process form when posted
if(isset($_GET['sort'])) {
    if($_GET['sort'] == 'PriceLow') {

        $query = "SELECT * FROM searchacts ORDER BY price ASC";
    }

Forms eg:

 Sort By:
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='get' name='form_filter' class="sortoptions" >
  <select name="sort">
      <option value="all">All</option>
      <option value="PriceLow">Price (Low to High)</option>
      <option value="PriceHigh">Price (High to Low)</option>
      <option value="NameAZ">Name (A-Z)</option>
      <option value="NameZA">Name (Z-A)</option>
      </select>

    <input type='submit' value = 'Re-Order your results'>
</form>

 Sort By:
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='get' name='form_filter' class="sortoptions" >
  <select name="upto">
      <option value="upto100">Up to £100</option>
      <option value="upto200">Up to £200</option>

      </select>

    <input type='submit' value = 'Re-Order your results'>
</form>

and collecting my data to the div:
<?php
$i=0;
while ($i < $num) {

$image=mysql_result($result,$i,"image");
$name=mysql_result($result,$i,"name");
$category=mysql_result($result,$i,"category");
$description=mysql_result($result,$i,"description");
$stamps=mysql_result($result,$i,"stamps");
$stickmen=mysql_result($result,$i,"stickmen");
$price=mysql_result($result,$i,"price");
$view=mysql_result($result,$i,"view");
$actpagelink=mysql_result($result,$i,"actpagelink");

?>

  <a href="<?php echo $actpagelink; ?>" class="searchitem">

<img src="<?php echo $image; ?>"/>

<?php echo $name; ?>

<?php echo $category; ?>

<?php echo $description; ?>

<img src="<?php echo $stamps; ?>" />

<img src="<?php echo $stickmen; ?>" />

from£<?php echo $price; ?>

<img src="<?php echo $view; ?>" />

  <?php
$i++;
}

mysql_close();
?>

Comment: This is a lot of code. What exactly is the problem?
Comment: Ok go to my link put this on the end: ?categories=rockandpop&sort=PriceLow it doesn't work. My question is what do you have to use to make them work
Comment: You can access those parameters through the `$_GET` array.
Comment: Then you need to write some logic that makes use of them? We need a more detailed explanation of what you need fixed.
Comment: Ok I'll organize the code a bit better in the post
Comment: Ok i've tried to explain the code in my post
Comment: Check out what Jeffrey posted. That seems to answer your question
Comment: [**Please, don't use `mysql_*` functions in new code**](http://bit.ly/phpmsql). They are no longer maintained [and are officially deprecated](http://j.mp/XqV7Lp). See the [**red box**](http://j.mp/Te9zIL)? Learn about [*prepared statements*](http://j.mp/T9hLWi) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://j.mp/QEx8IB) will help you decide which. If you choose PDO, [here is a good tutorial](http://j.mp/PoWehJ).
Answer: First of all suppressing errors with @ is a very bad idea.
While it's true that mysql_* functions aren't going to disappear any time soon, it is suggested to use PDO or mysqli instead because the mysql extension is deprecated.
For:

/searchtestingv4.php?categories=rockandpop&sort=PriceLow

you can access variables with:
$_GET['categories']; // rockandpop
$_GET['sort']; // PriceLow

For:

/searchtestingv4.php?sort=PriceLow&page=2

you can access variables with:
$_GET['sort']; // PriceLow
$_GET['page']; // 2

You can check the existence of a var with:
(isset($_GET['key'])) // is true only if the GET var with key `key` exists

And you can make any sort of logic with them. For example if you want sort to be required you can do:
if (!isset($_GET['sort'])) { /* print error */ }

or:
if (!in_array('sort', $_GET)) { /* print error */ }

Comment: Isn't that what i'm already doing?

How to use URL parameters


Por que é muito utilizado Varchar(255)?

Question: Por que em vários bancos de dados, dizem para definir o tamanho como varchar(255)?
Por exemplo, em um campo email por que colocar varchar(255)? Não seria melhor (em questão de armazenamento e velocidade de processamento) colocar varchar(80) ou talvez varchar(100)? Além disso são poucas pessoas que tem mais de 80 caracteres no e-mail.
No meu caso eu estava olhando na internet, procurando sobre utf8mb4 e vi que em alguns campos já é dito para colocar varchar(255), independente do contexto.
Comment: Você não queria referência?
Answer: O VARCHAR por definição tem tamanho variável, pode-se colocar o tamanho que desejar ali, pelo menos dentro do padrão ANSI. Esse 255 é apenas uma informação de como ele deve ser mostrado em uma seleção, não quer dizer que ela ocupará esse espaço em disco. Não há desperdício.
Você pode definir o que quiser, não muda algo significativamente. 255 é um número que comporta a maioria das informações. No passado este era o tamanho máximo de um VARCHAR, então podia mostrar tudo.
Alguns bancos de dados usam isto como constraint e não deixam passar deste valor, ou seja ele é apenas um máximo possível.
Especificamente sobre o e-mail se quiser ter espaço suficiente para qualquer e-mail que pode ser de tamanho até 254 de acordo com a RFC. Não pode modelar o banco para tratar as inserções de 99,999%, ele tem que ser adequado para 100% dos cadastros.
É o oposto do que em tese deve acontecer com o CHAR que tem tamanho fixo. Em tese se um CHAR tiver 255 de tamanho é isso que ele vai ocupar mesmo que o valor só tenha um caractere. Digo em tese, porque tem SGDBs que podem armazenar até um CHAR com tamanho variável, ainda que preserve a semântica do CHAR. Se a linha tem alguma coluna de tamanho variável não tem porque manter uma de tamanho fixo, não há ganho nisso.
Isso pode ser confirmado em resposta no SO de um dos maiores especialistas em banco de dados. A Wikipedia fala nisso. E ainda tem a documentação dos tipos nos bancos de dados:

Oracle
SQL Server
MySQL
PostgreSQL
SQLite

Coloquei no GitHub para referência futura.
Comment: Está escrito na resposta que não.
Comment: Pelo que eu entendi na referência no caso do MySQL quando você fixa o tamanho do VARCHAR em 255 sem necessidade causa consumo maior de memória nos _joins_.
Comment: @Piovezan no `JOIN` é possível mesmo
Comment: Muito obrigado, só queria uma referência
Answer: O VARCHAR por definição tem tamanho variável, mas não se pode colocar o tamanho que desejar ali, como respondido acima. Esse 255 é o tamanho máximo permitido para a coluna, que no caso do Oracle, o máximo possível é 4000.
De fato, ele só utiliza o que for necessário. Então, por exemplo, no caso de uma string de 10 caracteres (em Charset de 1 byte), somente serão armazenados os 10 caracteres.
Answer: O Varchar(255) é muito utilizado pois é o valor padrão e muitos desenvolvedores mantém esse valor sem parar pra pensar se realmente são necessários 255 caracteres para armazenar aquela informação.
Não vejo como problema do banco de dados e sim da falta de atenção aos detalhes de quem configurou a tabela pela primeira vez.
Answer: Acredito que antigamente em vários bancos de dados, o tamanho máximo era 250, por isso acabou "padronizando" esse tamanho comum.
Answer: De fato, o tamanho máximo do varchar era 255. Como podemos notar, 255 seria exatamente o tamanho de 1Byte, ou 8 bits, que era o tamanho máximo do endereçamento. O número 255 em binário é 11111111, ou seja, todos os bites "setados" em "UP". Hoje em dia, nos SGBDs mais modernos, já é possível aumentar esse armazenamento.
Comment: "o tamanho máximo do varchar era 255" => pode compartilhar a fonte? A pergunta é sobe MySQL se acreditarmos nas tags, porém você diz depois "nos SGBDs mais modernos", indicando que a frase que eu destaquei era uma verdade em muitos SGBDs

Por que é muito utilizado Varchar(255)?


Pass request uri to proxy as query param Nginx

Question: I would like to pass a url like a query param to a proxy if the user agent is a crawler. I have:
if ($http_user_agent ~* "googlebot|yahoo|bingbot|baiduspider|yandex|yeti|yodaobot|gigabot|ia_archiver|facebookexternalhit|twitterbot|Facebot|developers\.google\.com") {

 // Get the request Url, such as http://my-page.com/foo/bar/
 // pass to the proxy as query param such as: http://localhost:3030?page=http://my-page.com/foo/bar/:

}

Comment: What does your `server` block look like?
Answer: This is quite tricky. I think that you don't want to generate HTTP 301 or 302 redirects which can be done easily with this config:
if ($http_user_agent ~* googlebot|yahoo|bingbot|baiduspider|yandex|yeti|yodaobot|gigabot|ia_archiver|facebookexternalhit|twitterbot|Facebot|developers\.google\.com) {
    return 301 http://localhost:3000?page=$scheme://$http_host$request_uri;
}

but want a "transparent" proxying, when crawlers does not see a redirect but gets a normal (HTTP 200 OK) response instead.
We can't use proxy_set_header directive inside an if block, and without it we cannot achieve a "transparent" proxying, but we can use the following workaround:
if ($http_user_agent ~* googlebot|yahoo|bingbot|baiduspider|yandex|yeti|yodaobot|gigabot|ia_archiver|facebookexternalhit|twitterbot|Facebot|developers\.google\.com) {
    set $args page=$scheme://$http_host$request_uri;
    rewrite (.*) /passtoproxy$1 last;
}

location ~ ^/passtoproxy/.* {
    proxy_set_header Host localhost;
    proxy_set_header X-Real-IP $remote_addr; # optional, if needed
    proxy_pass http://localhost:3000?$args;
}

In this example a virtual /passtoproxy location is defined (of course, this path must not exist within your real site), but you can choose something more unique, like randomly generated string of enough length.
If you want to pass a request to a different proxy, for example my-proxy.com, you must also change first proxy_set_header directive to proxy_set_header Host my-proxy.com;.
Update
You may need to add a resolver directive to your server block in order to get this to work.
For testing you can add "curl" to the list of robots and check how this config works with the curl utility.


Simple addition in FSCL does not update result array

Question: open FSCL
open FSCL.Compiler
open FSCL.Language
open FSCL.Runtime

[<ReflectedDefinition; Kernel>]
let SimpleAdd(a: float32[], b: float32[], c: float32[], wi: WorkItemInfo) =
    let i = wi.GlobalID(0)

    c.[i] <- a.[i] + b.[i]

[<EntryPoint>]
let main argv =
    let a = [| 1.0f; 2.0f |]
    let b = [| 2.0f; 3.0f |]
    let c = Array.zeroCreate 2
    let workItem = WorkSize(a.LongLength)
    <@ SimpleAdd(a, b, c, workItem) @>.Run() |> ignore
    printfn "%A" c
    0

This outputs [| 0.0f; 0.0f |]
I'm using F# compiler, which comes with VS2015. Console app targets F# 4.0 on .NET 4.5.1
Update
Strangely, this works as exptected:
[<ReflectedDefinition; Kernel>]
let SimpleAdd(a: float32[], b: float32[], wi: WorkItemInfo) =
    let i = wi.GlobalID(0)
    let c = Array.zeroCreate a.Length

    c.[i] <- a.[i] + b.[i]

    c

Comment: That is, because the last expression in a F# function is the return value of the function.
Comment: Hi Functional_S, if you're talking about why 2nd sample works - that I know. Question is: why 1st does not?
Answer: The second example DOES work, because the last expression in a F# function is the return value of the function.
The first example does NOT work
because the F# quotation adds an other level of abstraction.
Its quotation looks like this
val x : Quotations.Expr<unit> =
  Call (None, SimpleAdd,
      [PropertyGet (None, a, []),
       PropertyGet (None, b, []),
       PropertyGet (None, c, []), Value (1)])

And this does not allow (or depends on the evaluation implementation of the quotation) the side effect of the mutation of the Array (.NET reference type) back over the interface.
You can check the compiler implementation here https://github.com/FSCL/FSCL.Compiler
or maybe contact the author email@example.com of the FSCL.


Binding ViewModel events outside of the init

Question: I am using RxSwift and Swinject in my project. The way I bind the inputs / outputs is not exactly the same as in the example given by RxSwift. In RxExample/GitHubSignup, the binding is done in the init(), right? But I found it difficult to implement because I use Swinject+SwinjectStoryboard to do Dependency Injection to the View Controller. Thus, the init() is unavailable because the one instantiating the View Models is the Swinject container. So, is there a way to bind the view controller and view model together besides using init()?
I was thinking that I can maybe use var instead of let for the output observables and make a func bind(observables: [Observable]) or something that will do the bindings and transformations from input to output instead. But because they will be vars and not lets, that means it seems like we are permitted to change the bindings throughout the code. Unlike when we just use lets and bind them in the init(). And also, by using a function instead of the initializer, I have to store the dependencies into a member variable. While if I use the initializer, I can just transform the dependencies inside of a map or flatMap.
And also I have another question. Say, if I have this:
class MyViewController: UIViewController {
    @IBOutlet weak var refreshButton: UIButton!
    @IBOutlet weak var tableView: UITableView!

    var viewModel: MyViewModel!
    private let disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel = MyViewModel(refreshTap: refreshButton.rx.tap, dataProvider: ApiAdapter().getData)

    }

    private func setupEvents() {
        viewModel.tableDTOs.bind(to: tableView.rx.items(
            cellIdentifier: reuseId, cellType: TableViewCell.self)) { _, dto, cell in
                cell.fill(with: dto)
        }.disposed(by: disposeBag)
    }
}

final class MyViewModel {
    let tableDTOs: Observable<[TableDTO]>

    init(refreshTap: Observable<Void>, dataProvider: () -> Observable<[TableDTO]>) {
        tableDTOs = Observable.merge(.just(), refreshTap) //Merge with .just to emit at once for initial values
             .flatMapLatest { dataProvider().asDriver() }
    }
}

So in this case, if the dataProvider returned complete or error, the disposable will be disposed, right? So the scene will be unresponsive because the UI is already unbound. Any idea how to fix that?
Thanks.
Answer:
So, is there a way to bind the view controller and view model together besides using init()?

Yes there is. Give the view model a function that takes the inputs and returns the outputs.

But because they will be vars and not lets, that means it seems like we are permitted to change the bindings throughout the code.

Don't ever make an Observable (or Subject, or Observer) a var always use let Functional Reactive Programming is a functional paradigm so no vars.

So in this case, if the dataProvider returned complete or error, the disposable will be disposed, right? So the scene will be unresponsive because the UI is already unbound. Any idea how to fix that?

Yes and no. If the dataProvider emits a completed event, that will not dispose because the flatMapLatest only disposes if all of its inputs complete. Since the refreshTap has not yet completed, the flatMapLatest will continue to accept events from it and call it's closure for each one.
If the dataProvider emits an error event, that will dispose because and error event short circuits the chain. However, since you use .asDriver() on your dataProvider, the Driver returned from the closure can't possibly emit an error event. You're safe.
Other ways of stopping the error from breaking the chain are to use .materialize() or any of the .catchError operators. For example:
.flatMapLatest {
    dataProvider
        .map { Result<[TableDTO], Error>.success($0) }
        .catchError { Observable.just(Result<[TableDTO], Error>.failure($0) }
}

Comment: Exactly correct. If you keep going down this road, you will begin to wonder why you are even putting the function in a class to begin with.
Comment: I see. So the whole binding of inputs and outputs would be from that function, right? That means I don't have to store the outputs as a member variable, right? Thanks.


Is the "Bayesian approach" about prior beliefs, viewing parameters as random variables, or both?

Question: It seems to me like the concepts of incorporating prior beliefs about parameters VERSUS viewing parameters as latent random variables are two VERY separate concepts, and yet I've found that they're often confounded and treated as one. Can't we have prior beliefs about what the most likely value of a parameter is without actually believing that the parameters are "random variables" i.e they do have a single "true" value, but there's just uncertainty about what that value is. The fact that we have "prior knowledge" about what the value of the parameter might be and that we encode that via a prior probability distribution doesn't seem to me to exclude the possibility that that thing we're talking about (the "parameter") is a fixed, albeit latent value.
I've taken a course in Bayesian statistics, and have read online about Bayesian analysis, but I actually still do not fully understand this.
EDIT: Just to be a bit more concrete, suppose we conduct an analysis "as a frequentist," and  infer the value of some parameter. However, because we have some prior knowledge about the parameter, we use a prior that reflects our uncertainty about the value of the parameter. But just because we used a prior doesn't require us to assume that the parameter we're inferring is inherently random. The resulting probability distribution of the inferred parameter is simply arising because of uncertainty, not inherent randomness in the parameter. We still believe, as frequentists, that the parameter has a fixed, latent value. So are we being Bayesian, or frequentist, or a combination of both in this type of scenario?
Comment: What does "inherit randomness" mean? think of a coin flip. If you could measure all the relevant physical parameters (exact force applied to the coin, surrounding air density etc.) then you could perfectly predict the outcome. But when you don't have that information, you treat is a random process. So the statement $P(heads)=1/2$ really only reflects your own (subjective) uncertainty about the process, not an inherit property of it.
Comment: @AnIgnorantWanderer The "things that will happen in the future" are themselves physical processes that, given enough information on initial conditions, can be predicted, so that argument is just kicking the can down the road.  Regarding the question in your edit, there is no coherent way of "using a prior" inside a Frequentist analysis:  those are fundamentally different  (and contradictory) concepts.
Comment: If you have a prior belief that you can quantify with probabilities (e.g., there's 90% probability that $X>0$) then you are effectively treating $X$ as a random variable. From a Bayesian viewpoint uncertainty and randomness are essentially synonyms.
Comment: To a frequentist, they are very different concepts. In a case where a rv X has a pdf depending on the value of a 'parameter' which is itself regarded as a rv with a known pdf, then a frequentist could/would use the Bayesian approach.
Comment: @J.Delaney but why not make the distinction between "being a random variable because of uncertainty" VS "being a random variable because of randomness." It's interesting that you mention that for a Bayesian, uncertainty and randomness are synonyms. I feel like that's misleading and confounding separate concepts for no apparent reason (at least in my limited/possibly naive view) What are your thoughts?
Comment: @GrahamBornholt right but the random variable could have a pdf because of INHERIT randomness in the process we're modeling or because of uncertainty, which I feel are CAN be different things (although I can think of situations where it makes sense to treat them the same way). I feel like prior beliefs on their own could simply reflect that we have reason to restrict uncertainty, without assuming any randomness
Comment: I added an edit to my question to be more concrete
Comment: If you take the subjective Bayesian approach with degrees of belief, then you are in effect saying that your degrees of belief can be represented by a distribution which obeys the axioms of probability (non-negative, $1$ in total, and countable unions of disjoint effects).  At this point the sort of distinction you are trying to draw is one of words rather than philosophy.
Comment: @J.Delaney so I feel like you're assuming in your case that the initial conditions determine the eventual state of the coin. I agree that if you measure those quantities you mentioned, you will have a "better", but not complete picture of the eventual outcome. There are things that will happen in the future, after the coin is flipped, that will also affect its final state, and these things which you cannot possibly measure lead to "inherit randomness."
Comment: I was talking about the case where the data generating process involved a rv parameter. Using a pdf to model one's own uncertainty about a parameter's fixed value is not of interest to a frequentist.
Comment: @GrahamBornholt interesting. So it seems pretty limiting to me then to categorize oneself as a "frequentist" or "bayesian"...
Comment: We are not supposed to chat here, so let me say finally that I find it useful to try to model the underlying data generating process. Whereas I don't see any benefit from trying to model (probabilistically or otherwise) my own uncertainty. It is what it is. However, I recognize that, in the face of a complex problem, a Bayesian answer might provide a 'quick and dirty' answer whose frequentist properties could then be checked.
Answer: The mathematical concept of a "random variable" does not require a belief in randomness
You seem to be reading more into the mathematical concept of a "random variable" than is actually contained in the concept.  Mathematically, the concept of a random variable is just a mapping from a sample space in a probability space to the real numbers, complex numbers, or some other set of values for a quantity of interest.  This means that every random variable has a probability distribution and every quantity with a probability distribution is a random variable.  So in fact these are not very seperate concepts; they are identical.  Treated purely as a mathematical concept, this does not necessarily entail any particular metaphysical properties of the quantity, and in particular, it does not imply that the quantity is actually random in an aleatory sense.  Perhaps this is a bit naughty and confusing on the part of the mathematics community, and I can see why it would lead to misunderstandings, but it arises largely for historical reasons relating to the evolution of probability theory.
The most commonly applied paradigm for Bayesian statistics treats probability as an epistemological concept that describes our own uncertainty in a quantity, but does not take a position on metaphysical issues relating to determinism, indeterminism, and randomness.  There is a good treatment of the philosophical and mathematical foundations of Bayesian statistics in Bernardo and Smith (1994), which discusses the epistemological interpretation of probability in the "subjective Bayesian paradigm".  This approach is agnostic on the metaphysical issue of whether or not randomness actually exists in nature --- either way we need a tool to describe our own uncertainty about quantities, and probability does this job.
Comment: When modelling a data generating process, it may often be convenient to signify whether or not we are acting as if randomness was involved. Somewhat tongue-in-cheek, should we clarify by describing the rvs as random random variables in such cases (with the alternative circumstances said to  involve nonrandom random variables)?
Comment: Perhaps in Bayesian analyses it does not matter whether or not randomness is involved, however the distinction is important to frequentist analyses. The issue is not mathematical (since the term rv is agnostic in this regard) nor specifically philosophical but rather one of adequately describing the statistical modelling. Perhaps instead of random random variable, to signify rvs with randomness it would be better to say X is a 'chance random variable' for clarity.
Comment: There is generally little loss of understanding with referring to quantities as "random variables" in the usual sense, so long as it is understood that this is a mathematical setup, not a philosophical discussion pertaining to aleatory randomness.  If you want to avoid this language, an alternative is just to call things "quantities" and the apply probabilities to them as needed, according to the chosen methodology.
Comment: I disagree.  My view is that adding new terminology of that kind would add more confusion, rather than clarifying the model.  My experience is that the model can be specified clearly with standard mathematical terminology and notation.  As noted in my answer, I do not think there is any distinction between RVs with and without aleatory randomness that need be made in statistical/mathematical modelling.
Comment: Fair enough, that's your view.
Answer: I like to view Bayes rule intuitively as a situation where we know that some (not directly measured) unknown value B follows a known probability distribution (e.g. it is sampled from a population with a reasonably well know distribution) and there is another known value A that has a statistical relationship with the value of B.

(Image from the question: Bayes' Theorem Intuition)
In this picture of Bayes rule, the parameters A and B are shown to follow a particular joint distribution. In an application of the rule, often A is measured/observed and B is unknown.
So we consider B to follow a certain (known/estimated) distribution, because it can be considered as being sampled from a larger population with a certain distribution, but that doesn't mean that B doesn't have a fixed value. It is just that this value is unknown.
Example: Say, B, could be the 'intelligence' of a person and A could be the score on an intelligence test. The joint distribution expresses that people with a same intelligence B might score differently on the intelligence test A. So people with a particular score A are not to be considered as having intelligence A, but instead they are considered to follow a posterior distribution B|A.

without actually believing that the parameters are "random variables" i.e they do have a single "true" value, but there's just uncertainty about what that value is.

Eventhough the value of B might be fixed, it is in a certain sense a random value to is, when we don't know what the value actually is. In that case we describe the value B in terms of what we do know and that is that the value B follows a particular know probability distribution.
The randomness expresses uncertainty.

That can be either for a single entity having variations all the time (according to some distribution).
Or it is a single entity having a fixed value, but being sampled from a population that fixed value is random to us as we do not know the value.

Having a fixed value, when that value is unknown, we can treat it as random. Maybe the world is deterministic or it is not, but for our analyses does it matter?
Answer: You can find a very good answer to your question in the Who Are The Bayesians? thread and How exactly do Bayesians define (or interpret?) probability? that discusses the specific way how Bayesian approach probability, which is one of the core concepts of the approach.
But making the answer more specific, it is not about latent variables, because there are many non-Bayesian models with latent variables. There is a whole class of latent variable models that can be treated as Bayesian models but do not have to (e.g. you can find their parameters with maximum likelihood). It's more about using priors and specific definition of probability, as you can learn from the threads mentioned above.
Answer: There are cases where frequentist and Bayesian inference converge on the same answer, so within these limits, one could argue that the distinctions are only philosophical.
I feel that the wording "incorporating prior beliefs" already implies that the parameter you are infering is a random variable.

Your "prior belief" has to be a probability distribution rather than a fixed value, otherwise it would be a "present certainty" rather than "prior belief," and it wouldn't make sense to perform inference if you already know what the answer is.
"Incorporating" implies that it needs to contribute to your answer. If I thought 1+1=3 and observe that it is 2, my original 3 is entirely discarded and not incorporated into my observation of 2. Our prior beliefs are "incorporated" via multiplication in Bayes' theorem.
A probability distribution, whether multiplied by another probability distribution or a fixed value, equals another probability distribution. Hence, our answer is in the form of a probability distribution and is therefore a random variable by definition. If we insist that the answer is a fixed value in some way, how can we claim that we've multiplied in our prior beliefs as defined above?

I am having trouble understanding your "concrete scenario" because I don't know how you could actually "use a prior that reflects our uncertainty" in practice, other than via Bayes' theorem. Allow me to ignore that for the time being. You then propose that "the resulting probability distribution of the inferred parameter is simply arising because of uncertainty, not inherent randomness in the parameter." Allow me to be even less rigorous in my mathematical terminology... I would say that "the resulting distribution" you speak of has some variance, and this final variance consists of two components: A) the variance originating from your prior probability distribution, and B) the variance originating from your sampling distribution. Your claim about variance "simply arising because of uncertainty, not inherent randomness in the parameter" can only apply component B of the final variance but not component A. Since there is some component of variance remaining in your final answer, even assuming your claim is true, your final answer must still be a random variable.


Is possible to transfer files with FTP?

Question: I connected to a site using SSH with Drush. Is there a way to use FTP with Drush?
Answer: Drush does not have a built-in wrapper for ftp / sftp, but you can do the same operation using rsync.  If you have rsync, setup your drush aliases for it. You can then copy the code and (upload) files for the site via:
drush rsync @mysite.dev @mysite.live
You can copy just the (upload) files via:
drush rsync @mysite.dev:%files @mysite.live:%files
This will use the same credentials that you already set up to use ssh with Drush.

Is possible to transfer files with FTP?


Which hook is invoked when an order is updated?

Question: Which hook is invoked when an order is updated?
I created a module that must perform some operations when an order is modified, for example when its status is changed or when an item is changed.
Answer: The documentation for commerce_order_status_update() says:

While there is no explicit Rules event or hook devoted to an order
  status being updated...

It is possible to use hook_commerce_order_presave():
/**
 * Implements hook_commerce_order_presave().
 */
function my_module_commerce_order_presave($order) {
  if ($order->status != $order->original->status) {
    drupal_set_message("The order status changed from {$order->original->status} to {$order->status}");
  }
}

Here's an optional helper function for use elsewhere if you have an $order object, and are curious if its status has changed from what is stored in the database:
/**
 * Given an order object, this returns FALSE if the order status has not
 * changed. If it has changed, it returns an associative array with the
 * following keys: new_order_status, old_order_status
 */
function my_module_order_status_changed($order) {
  $result['new_order_status'] = $order->status;
  $result['old_order_status'] = db_select('commerce_order', 'co')
    ->fields('co', array('status'))
    ->condition('co.order_id', $order->order_id)
    ->execute()
    ->fetchField();
  if ($result['new_order_status'] == $result['old_order_status']) {
    return FALSE;
  }
  return $result;
}

Comment: The hook is `hook_commerce_order_presave()` with the boolean outlined above. There is no hook called `hook_order_status_changed()`, that is just a helper function I've created.
Comment: Where did you pull out hook_order_status_changed. Doesnt work and I dont see anywhere hook_order_status_changed  documented?
Answer: Commerce doesn't provide an explicit hook for that (these are the hooks it does define for orders).
Since a commerce order is an entity, you're looking for hook_entity_update(), which is used to

Act on entities when inserted.
Comment: thanks. I am working on it. My issue is do some operations when an entity with type "commerce_order" is updated. so I used "hook_entity_update" and in my function I used this condition if($type == 'commerce_order') {}
Answer: Try: hook_commerce_order_presave($order);
It allows you to prepare order data before it is saved.
Comment: can you provide some example code?


MongoUserDetailsService in java config returns null

Question: Anybody can see why I get null when returning Customer?
I'm using java config and are able to connect to DB by my mongoConfig.
But when wants to login it seems the problem is my mongouserdtailsservice.
Thanks
<code>   public class MongoUserDetailsService implements UserDetailsService
   {

  @Override
  public UserDetails loadUserByUsername(String username) throws        AuthenticationServiceException
  {
    MongoOperations mongoOperations = null;

    try
    {
        mongoOperations = new MongoTemplate(new MongoClient(), "booking");
    }
    catch (UnknownHostException e)
    {
        e.printStackTrace();
    }
    catch (MongoException e)
    {
        e.printStackTrace();
    }
    try
    {
        Query query = new Query(Criteria.where("email").is(username));
        System.out.println("query ready to go");
        Customer customer = mongoOperations.findOne(query, Customer.class);
        System.out.println("query done");
        System.out.println("user: "+customer);

        if (customer == null)
        {
            throw new AuthenticationServiceException("Authentication failed   for user " + username);

        }
        boolean enabled = true;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;

        return new User(customer.getUsername(),   customer.getPassword().toLowerCase(), enabled, accountNonExpired,   credentialsNonExpired, accountNonLocked,
                getAuthorities(2));

    }
    catch (Exception e)
    {
        System.out.println("query failed");
        throw new RuntimeException(e);
    }
  }
  public Collection<? extends GrantedAuthority> getAuthorities(Integer role)
  {
    List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(role));
    return authList;
    }

   public List<String> getRoles(Integer role)
  {
    List<String> roles = new ArrayList<String>();

    if (role.intValue() == 1)
    {
        roles.add("ROLE_USER");
         roles.add("ROLE_ADMIN");

    }
    else if (role.intValue() == 2)
     {
        roles.add("ROLE_USER");
    }

     return roles;
   }

    public static List<GrantedAuthority> getGrantedAuthorities(List<String>   roles)
    {
     List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
     for (String role : roles)
    {
        authorities.add(new SimpleGrantedAuthority(role));
    }
    return authorities;
   }

   }
</code>
Answer: Solved
It was a conflict in my MongoUserDetailsService.
Here is the new one which is working well!(OBS! The new log in is with email)

@Component
public class MongoUserDetailsService implements UserDetailsService
{
    public MongoOperations mongoOperations;

    private User userDetails;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException
    {

        boolean enabled = true;
        boolean accountNonLocked = true;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        try
        {
            mongoOperations = new MongoTemplate(new MongoClient(), "booking");
            Customer user = getUserByEmail(email);

            userDetails = new User(user.getEmail(), user.getPassword(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked,
                    getAuthorities(user.getRoleAsInt()));
        }
        catch (UnknownHostException e)
        {
            e.printStackTrace();
        }

        return userDetails;
    }

    public List getAuthorities(Integer role)
    {

        List authList = new ArrayList();
        if (role.intValue() == 2)
        {
            authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            authList.add(new SimpleGrantedAuthority("ROLE_USER"));
        }
        if (role.intValue() == 1)
        {
            authList.add(new SimpleGrantedAuthority("ROLE_USER"));
        }

        return authList;

    }

    public Customer getUserByEmail(String email)
    {
        Query query = new Query();
        query.addCriteria(Criteria.where("email").is(email));
        Customer customer = mongoOperations.findOne(query, Customer.class);

        return customer;
    }

}


Is there a formula for $S_n=\sum_{k=1}^nk^i=1^i+2^i+3^i+\dots$?

Question: After playing around with power series $S_{n, p}=\sum_{k=0}^nk^p$ and finding a formula for each natural power, I tried to also find formulae for imaginary power but couldn't figure out how.
$S_n=\sum_{k=0}^nk^i$, where $i=\sqrt{-1}$
I tried expressing the series using cis and got $S_n=\sum_{k=0}^ncis(ln(n))$ but this didn't help me at all. Any hints or full answer will be appreciated.
Comment: @DietrichBurde No, the exponent is an imaginary unit.
Comment: Have a look at [this](http://math.stackexchange.com/questions/18983/why-is-sum-limits-k-1n-km-a-polynomial-with-degree-m1-in-n?noredirect=1&lq=1) and its linked posts.
Answer: By the Euler-Maclaurin formula,
$$\sum_{k=1}^nk^i=\zeta(-i)+\frac{n^{i+1}}{i+1}+\frac{n^i}2+\frac{in^{i-1}}{12}-\frac{i(i-1)(i-2)n^{i-3}}{720}+\mathcal O(n^{i-5})$$
this is not an exact formula, but rather an approximation to the problem, where $\zeta(-i)\approx0.0033002237+0.4181554491i$ is the Riemann zeta function.  A few values are given to show how it approximates:
$$\begin{array}{c|c}n&\sum&\zeta\\\hline1&1&0.49913+0.00010i\\2&1.76924+0.63896i&1.38459+0.31946i\\3&2.22407+1.52954i&1.99665+1.08425i\end{array}$$
Ok, not so good for small values, but it gets better.
$$\begin{array}{c|c}n&\sum&\zeta\\\hline10&0.41898+7.84548i&0.37600+7.47349i\\20&-8.93237+11.8340i&-8.43768+11.76128i\\30&-18.82708+10.93402i&-18.34384+11.06237i\end{array}$$
As you can see, the accuracy increases as $n\to\infty$.
Alternative forms include
$$\sum_{k=1}^nk^i=\zeta(-i)-\zeta(-i,n+1)=H_n^{(-i)}$$
where $\zeta(s,q)$ is the Hurwitz zeta function and $H_n^{(p)}$ is the generalized harmonic number.
Comment: Whats the O at the end of the first equation?
Comment: @Brian010515 So the first line goes on forever.  It's an infinite series approximation.  But everything that comes after what I have is $\mathcal O(n^{i-5})$, meaning as $n\to\infty$, the extra left over stuff behaves like $n^{i-5}$.
Answer: It has been pointed out that OP's question is about the finite sum, so my answer does not address the question.
The sum $\sum^\infty_{k=1} k^{-s}$ is absolutely convergent only when $\Re s>1$. So the infinite sum $\sum^\infty k^i$ does not converge. However in the region $\Re s>1$, the sum is analytic, so admits a unique continuation to a maximal domain on the complex domain. This continuation is called the Riemann zeta function, and its value at -i is in some sense related to the infinite sum $\sum^\infty k^i$. That value is approximately 0.0033 + 0.418$i$.
By the way, when $s$ is a natural number, the formula for the sum is called Faulhaber's formula.
$$
\sum_{k=1}^nk^s=\frac{1}{s+1}\sum_{j=0}^s(-1)^j{s+1\choose j}B_jn^{s+1-j}
$$
where $B_j$ is the $j$th Bernoulli number. This formula does not make any sense for values of $s$ which are not natural numbers, though.
Comment: Obviously the infinite sum does not converge, but the OP is looking for the finite sum.  Please reread the question.
Comment: @SimplyBeautifulArt oops, you're right
Comment: That's $\sum k^{-s}$. The sum $\sum k^s$ is $\zeta(-s)$ and so converges when $\operatorname{Re}(s)<-1$.
Comment: Your formula does not extend to complex $s$.  Check the upper bound of the summation.
Comment: @SimplyBeautifulArt good point.


How to output hostname in "service Description" for nagios core?

Question: I have currently the following two service defined as below:
define service {
        use                             my-webapp-service
        hostgroup_name                  all
        service_description             System check - PING
        check_command                   check_ping!100.0,20%!500.0,60%
        }
define service {
        use                             my-webapp-service
        hostgroup_name                  all
        service_description             System check - Swap Usage
        check_command                   check_nrpe!check_swap
        check_interval                  1
        }

What I want is output string to be:
System check - PING - "Actual hostname where this alarm got fired off"
System check - Swap Usage - "Actual hostname where this alarm got fired off"
I think this could be possible but I just don't know how to make it possible.
Would sincerely appreciate your guidance on that.
Many Thanks
Answer: Output are handled by scripts. Default behavior is that script don´t return hostname, because it is not necessary.
If you wanna add hostname in output, you must edit already exist scripts or create new one.
Here is basic info how create script for Nagios - http://www.yourownlinux.com/2014/06/how-to-create-nagios-plugin-using-bash-script.html
For your needs you must add $HOSTNAME to echo. For instance:
echo "$HOSTNAME - WARNING- $output"

Comment: Yep, this is possible, because some script work only with specific OS.  You must modify these script for your OS (and version).
Answer: If you want the script that is executing to be aware of the hostname, you'll need to pass the hostname as an argument to the Nagios command. That also means that the script will need to accept the hostname as an argument. Take for example:
define service {
        use                             my-webapp-service
        hostgroup_name                  all
        service_description             System check - PING
        check_command                   check_ping!100.0,20%!500.0,60%
        }

check_ping probably looks something like:
define command {
       command_name                             check_ping
       command_line                             $USER1$/check_ping -H $HOSTADDRESS$ -w $ARG1$ -c $ARG2$ -p 5
}

The problem here is that the executable at $USER1$/check_ping doesn't know that you want to pass the host's name as an argument. So you'll need to make a wrapper script. I'm not going to write the script for you, but to give you a hint, the command definition would look something like:
define command {
       command_name                             check_ping_print_hostname
       command_line                             $USER1$/my_check_ping_wrapper.sh --hostname $HOSTNAME$ -H $HOSTADDRESS$ -w $ARG1$ -c $ARG2$ -p 5
}

And then the script at $USER1$/my_check_ping_wrapper.sh is obviously going to need grab that --hostname argument, and then pass the other arguments directly to check_ping, wait for the output, and then amend the output with the information given in the --hostname arg.
Hope this helps!


How to strum a ukulele chord with skipped string?

Question: I'm a beginner ukulele player (been playing for about a year), and I've got a question about this song from Famous Solos & Duets for the 'Ukulele by John King:

How do I play the circled bar with the skipped C string?  The fingering arrow indicates that I am to strum it with the index finger, rather than simultaneously pluck three strings.  The chords don't sound bad with a C added, so I've been playing them with the C string open.  I've tried muting the string, but I'm finding that quite difficult to do while holding the other strings in the chord (although I suppose that might get better with practice).  Is that the right thing to do here, or is there a better way that I haven't thought of yet?
Answer: Muting is the way to do it. If you can't put the tip of a spare finger gently on that string, then use the pad of the next finger that is pressing the adjacent string down. It's a technique (trick) that guitarists use often.If all this proves impossible, which it shouldn't, then try to find another note from the same chord that can be played on that string with a cross on it. It won't be perfectly accurate, but I doubt anyone will notice.
Comment: Thanks.  I kept trying to use a spare finger to mute the string and struggling, but using the finger fretting the fourth string to mute the third string works well.
Answer: If you want to stick with the written tab, then the way to do it would be to use the middle finger on the G string and lay it down a bit so it rests on the C string, muting it.
But I think there's a far easier way to play that measure.  You're already in 5th position, and you already have an F chord fretted.  Just play this measure as:
-x-x-x-x-
-5-5-5-5-
-5-5-5-5-
-5-5-7-7-
Editing to address Ben Miller's question:  I see 3 immediate ways to play this:

You could skip the A string.  This is probably the most "pro" way to do it.
You could mute the A string with your barring finger.
You could ignore the strum direction indicated, do them all as downstrokes, and come to a stop on the A string.  This is least desirable, since there is a difference in tone between upstrokes and downstrokes.
Comment: +1 for the alternate chord.  How would you play this?  Would you only strum 3 strings, or would you mute the A string?  If you would mute it, which finger would you use?
Comment: @BenMiller edited to answer your question
Answer: I too have had trouble muting strings, and one way to kind of bypass the issue (though you really should develop muting technique) is to find another inversion that doubles a note instead of having to mute one. I this case, a few inversions work here, like:
5-5-5-3 (left side is G-string), then 5-5-5-5
or the less comfortable
5-5-1-0, then 7-5-1-0
Both of these play the exact same notes as the muting passage on the paper, they just play a note twice. Additionally, one can do the strumming easily with these inversions as well. If you really can't mute, the first one's your best bet. If you want to learn how to mute this particular chord, if you know how to play an Fmaj7 chord like this (2-4-1-3), then you can just not press down on the C-string when you play it. You could also try a triple-stop, where you just pluck all three notes at once, but that loses the sound of the downstrum. Another thing I've seen some players do is just leaving the G-string opne at almost all times, and on this chord you could play some 3-note F-chord high on the neck and leave the G-string open, which would sound different but not too bad.
TL;DR: Options one has are:
Learn to mute (ideal)
Inversions that avoid string muting (optimal alternative)
Triple Stop (Not a strum, so loses downstroke feel)
Leave the G-string open (sounds different, but it could sound really cool too)
Remove one of the strings from your instrument (If you want to get really radical)(Please do not do this)


Tooltip only shows up when I write something in the textbox

Question: This is my code for a button in C# windows forms. I want the Tooltip to show whenever I hover, but it only works after I insert some text in the textbox
this is the code
<code> private void passwordTextBox_TextChanged(object sender, EventArgs e)
    {
        ToolTip toolTip3 = new ToolTip();
        toolTip3.AutoPopDelay = 5000;
        toolTip3.InitialDelay = 1000;
        toolTip3.ReshowDelay = 500;
        toolTip3.ShowAlways = true;
        toolTip3.SetToolTip(this.passwordTextBox, "Not more than 50 characters, no special charachters!");

    }
</code>
Comment: If you create the tooltip in the TextChanged event it is only normal that you  could see it only after you start typing in the textbox. Just move this code after the InitializeComponent and you should see it even if you don't type anything
Answer: you have set tooltip on wrong event. Best way is to set tooltip on Form Load Event.
<code>private void Form1_Load(object sender, EventArgs e)
{
    this.setToolTip();
}

private void setToolTip()
{
    ToolTip toolTip3 = new ToolTip();
    toolTip3.AutoPopDelay = 5000;
    toolTip3.InitialDelay = 1000;
    toolTip3.ReshowDelay = 500;
    toolTip3.ShowAlways = true;
    toolTip3.SetToolTip(this.passwordTextBox, "Not more than 50 characters, no special charachters!");

    //Tooltip for other controls
}
</code>
Let me know if you still face any issue.


Show that If $\phi$ is a homomorphism, then $\phi(a^{-1}) = [\phi (a)]^{-1}$

Question: It makes sense that this is true, but I am having trouble coming up with a way to show that it is true. Any ideas? Thanks!
Comment: Don't forget $\phi(a)\phi(a^{-1})=\phi(aa^{-1})=\phi(e)$ where $e$ is the identity!
Answer: Hint: $\phi(aa^{-1})=\phi(1)=1=\phi(a)\phi(a^{-1})$
Answer: Your question is not very clear since the domain and codomain of your function $\phi$ is not defined.
Let $G$, $H$ be groups, $\phi:G\rightarrow H$ be a homomorphism.

$$\phi(1_G)=1_H$$

This can be done by considering the equation $\phi(1_G)=\phi(1_G1_G)=\phi(1_G)\phi(1_G)$.

For $a\in G$, $$\phi(a^{-1})=\phi(a)^{-1}$$

Since $\phi(a)\phi(a^{-1})=\phi(aa^{-1})=\phi(1_G)=1_{H}$ and also $\phi(a^{-1})\phi(a)=\phi(1_G)$, by definition of inverse of a group, your problem is solved.


Number of Crossings on a Graph with cn edges

Question:
Show there exists a family of graphs, universal constants $c$ and $c'$ s.t. for each graph with at most $cn$ edges, $n$ being the number of vertices, there are at least $c'n^2$ crossings.

I have tried to use complete graphs as complete graphs have ~$cn^4$ (n choose 4) crossings and ~$n^2$ (n choose 2) edges but this does not satisfy the condition of each graph having at most $cn$ edges. Complete bipartite graphs do not work for the same reason. I am stuck to think of which kind of graph has this property.
Answer: Take a graph consisting of a complete graph $K_t$ and $n-t$ isolated vertices, for suitably chosen $t$.
Note that complete graphs actually have crossing number less than $\binom n4$, but the crossing number inequality still gives an $\Omega(n^4)$ lower bound for them, so this shouldn't affect you except in the choice of $c$.
Comment: A complete graph on $n$ vertices has $\Omega(n^2)$ edges. Here, I'm suggesting a complete graph on only $t$ of the vertices: that has $\frac{t(t-1)}{2}$ edges. You should choose $t$ to satisfy your constraint.
Comment: sorry might be a dumb question but how does this relate to the problem? because the graphs have to have cn edges (n being number of vertices) so complete graph aways have $Ω(n^2)$ edges?
Comment: got it thank you


Apply client_max_body_size for a single URL only

Question: I want to allow client to upload files on our system, and I want them to be able to upload files larger than the default body set in nginx.
So I've set the following in our site configuration:
client_max_body_size 10m;

So far, so good, but I really only need this larger body size on a single URL; the one users POST to.
So I've tried the following configuration:
location /api/files/ {
  client_max_body_size 10m;
}

But this doesn't work at all, I get the following error in the log:

2016/04/24 13:52:51 [error] 17853#0: *1569513 client intended to send too large body: 1083334 bytes, client: 203.0.113.7, server: example.com, request: "POST /api/files HTTP/1.1", host: "example.com"

So I tried the following change:
location = /api/files {
  client_max_body_size 10m;
}

But this just results in a different error:
2016/04/24 14:25:50 [error] 19500#0: *171 open() "/usr/share/nginx/html/api/files" failed (2: No such file or directory), client: 203.0.113.7, server: example.com, request: "POST /api/files HTTP/1.1", host: "example.com"
This makes me assume that location actually refers to locations on the local file system, even though the documentation says:

Sets configuration depending on a request URI.

So, how do I apply this configuration change for this single request location only?
Answer: I think the solution lies in a nested location. So "location /api/files "should be inside your php location block.
Your fastcgi config should be inherited to the "files" location.
http://nginx.org/en/docs/http/ngx_http_core_module.html#location
location ~* \.php$ {
     try_files $uri =404;
     fastcgi_pass backend;
     # [...]

     location /api/files {
          client_max_body_size 10m;
     }
}

If you have location /api/files outside your php location nginx would find 'api/files' and remember it. But before using it, it would check whether there is a location with a matching regular expression, which would be the php location for php file requests. It would then use the php location and discard 'location api/files'.
Comment: Indeed, it seems it's not working for me for the same reason. So, what's the solution? Duplicate the complete content of my main `location` block?
Comment: Sorry for lots of edits.
Comment: From what I can tell (and what my tests seemed to confirm), nested location blocks don't inherit (all) settings from their "parent". The only real solution seems to be duplication, which can be abstracted with includes. Either way, you were correct. What I found particularly helpful in debugging this was to use `add_header X-Location foo` to mark which `location` was picked.


Starting a css site but format issues

Question: The link of the site is here progerdevs.co.nf just a test site. When I load the page on my android it is displayed horribly, everything is all over the place. Does anyone know what it is called so it changes when theres a different screen size? I still have a lot to learn :/
By changes i mean for example the images are all displayed verticaly and also the top navigation bar.
Comment: You're looking for responsive design. Try frameworks like [Bootstrap](http://getbootstrap.com/) for that.
Comment: Regarding the style of your question: I would suggest you to format it more properly so people tend to read the whole thing and find an answer. Think about including images which allows answerers to fully understand your question :)
Answer: You must be talking about media queries.
Suppose you want to change how your site looks depending on a set of screen resolutions like (width)
320px
768px
1024px
Then you must define a media query for each resolution, and put in it all your css rules for any element you want to adapt. Example: you want to change font-size of all your document:
<code>@media screen and (min-width:0px) {
    body {
        font-size:10px;
    }
}

@media screen and (min-width:320px) {
    body {
        font-size:12px;
    }
}

@media screen and (min-width:768px) {
    body {
        font-size:14px;
    }
}

@media screen and (min-width:1024px) {
    body {
        font-size:16px;
    }
}
</code>
Depending on the screen resolution of your device, font-size will change, so you can do the same with any property of any HTML element.
Or you can use Bootstrap, but that requires a deeper knowledge.
Comment: The problem is i am using bootstrap, and neighborhood-guides /thumbnail acts really strange. When i size down the window, the 3 images are really stubborn, changing from 3 horizontaly to 3 vertically, even whens theres loads of space. Im also using col-md-4 for each image, im not sure if this affecting it but what i want is: 2 images made smaller and side by side, and then 1 large image bellow
Answer: Yes, better you follow previous answer but here is a quick solution. Add this code and it will work as well

<code>.jumbo2 .jumbotron {
  background-image:url(http://progerdevs.co.nf/elderly.jpg);
  background-repeat:no-repeat;
  background-size:cover;
}</code>

I just remove the height;
Thanks

Starting a css site but format issues


Especificar apenas um campo obrigatório de um objeto

Question: Queria saber se é possível especificar apenas um campo obrigatório para um objeto com typescript. Um exemplo para explicar a dúvida:
interface Data {
    id: string | number,
}

function log (data: Data) {
    console.log(data)
}

log({id: 1, name: 'foo'})

Neste exemplo eu queria que o objeto passado para a função log tenha o campo id obrigatoriamente, mas pudesse ter qualquer outro campo nesse objeto.
Answer: Pode utilizar uma funcionalidade chamada dynamic properties que consiste na criação de propriedades dinamicas a partir de um modelo:
interface Data {
  id: string | number,
  [key: string]: string | number | boolean
}

function log (data: Data) {
  console.log(data)
}

log({id: 1, name: 'arroz'})
log({id: 1})
log({id: 1, name: 10, test: true})

Pode ver o exemplo funcionando aqui.
Comment: Muito obrigado!


Why is it common to write tuba sheet music in concert pitch?

Question: I play E♭ tuba in a wind orchestra, and we always get the notes written in concert pitch, and we have to logically "transpose" to the instrument key on the fly.
How common is this approach? Why is it done?
Additional info to clarify:
When I was first learning to play tuba as a child in the school band, I always got to play sheet music written in G clef transposed for E♭ tuba. This means when the sheet note say C, it is really the tone E♭ in natural concert key.
This site gives a good basic understanding about what this is all about.
Example:
Concert pitch:

These notes read and sound as:

E D♭ C B B

Note that this is using bass-clef (or F-clef), which is below the G-clef - think of the lowest line in a note system for piano.
Transposed for E♭ tuba:

These notes read as:

C♯ B♭ A G♯ G♯

but sound as:

E D♭ C B B

Note that this is written in the G-clef, because it is transposed to look the same as if you played a transposed sheet for trumpet (or any other instrument).
Conclusion
It is most common to write tuba notation in concert pitch, and not the transposed version.
My question is WHY?
Comment: According to Wikipedia "Some instrument families, like trombones and tubas, are not written transposed." - but no reason is given. http://en.wikipedia.org/wiki/Transposing_instrument
Answer: The composers/arrangers/publishers of tuba parts and sheet music have no idea what key of instrument you play!
In Europe, the Eb tuba is fairly widespread, but the standard issue tuba in American school bands is actually keyed in Bb!
In a conservatory, you will find tuba players who own multiple instruments for a wide variety of different playing engagements. What's more, these instruments will further vary by size (tuba size, i.e. 3/4, 4/4, 5/4). Tuba players don't want to use their largest equipment for playing in a brass quintet, for example, but they will need the largest instrument they have if they're going to play in an orchestra! Due to the wide variety of instruments out there being played for different reasons, it's impractical for publishers to ship three copies of music written in Bb, C, and Eb for every piece. You also don't want to exclude people who only own one type of tuba from playing your music.

A side note about differences between American and European bands: Most American wind bands include brass, reeds, and percussion. The low brass can be easily grouped together because the trombone, euphonium/baritone, and tubas all read concert pitch music in bass clef despite being pitched in Bb.
In contrast, western Europe has a very popular brass band tradition that excludes reed instruments. The brass instruments are more diverse as a result, and for instruments such as the euphonium, playing technique is taken from the top of the ensemble instead of grouping with the bottom. That is, cornet technique is very similar to euphonium technique, and as a result, euphoniums read treble clef music in Bb just like the cornets do. The same is true for trombones for a similar reason. The tuba is still excluded from this for the reasons mentioned above, but the cultural distinction is very interesting and relevant for all of the other brass instruments that typically don't transpose.
Comment: I understand and agree with all of this. But somehow it's still amusing that the reason for treating clarinets as transposing is ultimately "Most players own multiple instruments" and the reason for *not* treating tubas as transposing is somehow exactly the same...
Comment: Western European brass bands tend to include both E♭ and B♭ tubas (or "basses", as they are known). Like other brass instruments, learning to play transposed music makes it easier to switch between them.
Comment: My experience in Norway is that in brass bands, it's most common to have tubas pitched in B♭, but in wind bands, it's more common with E♭ tubas. I believe that a reason for this might be that most school bands are wind bands, and it is practical for kids to start with the smaller size E♭ tuba. Brass bands are not so common in school bands for kids. They start with that in young adult age.
Comment: As a counterpoint, as a trumpet player it is quite easy, in most cases, to find Bb, C, and Eb transcriptions of just about anything.
Answer: Here is a plausible explanation paraphrased from a discussion elsewhere.
Trumpets and horn used to be valveless instruments. You could use a "crook" to adjust the pitch.
If you wanted to play trumpet in the key of C you put in the C crook and you could play using the C major triad. To play in D you put in the D crook,and so on.
So, they would write all music for natural trumpet or horn as if in the key of C. The player would link a particular action to a particular stave position.
Trombones have always been fully chromatic, so there was never a need to transpose.
Tuba is a recent invention, and always had the benefit of valves.
This isn't fully convincing because it must be inconvenient if you've learned the fingerings for a C tuba, and move to a Bb tuba. But conventions aren't always fully rational.
Transposed scores for tuba are the exception, but some do exist. It seems Richard Strauss wrote his tenor tuba parts transposed.
Comment: Most tubaists stick to one kind of tuba, or use one low (Bb _or_ C) and one high (Eb _or_ F) kind. So you seldom need to transition from C to Bb and if you do it's often a one time affair plus it's quicker than you'd think to relearn the music reading.
Comment: For school bands in Norway (and probably other parts of Europe) it is quite common to see transposed for Eb tuba. In US and generally brass bands, it is common to have Bb tuba transposed.
Answer: I can't say as to your original education, but in the United States, the tuba is not treated as a transposing instrument. Most students of the tuba learn to read music in concert pitch regardless of how their particular instrument is tuned. So, in the US, you wouldn't have been taught based on transposed music.
This is primarily because the tunings of a tuba are not nearly as standardized as for other instruments. An alto sax is always an Eb instrument, a tenor sax is always a Bb instrument. But the tuba can have partials tuned to Bb, C, Eb, or F, and which is more prevalent depends on region. Tenor tubas and trombones can have similar partial tunings; schools in the US typically have school instruments in Bb partials, but trombones in C are not unheard of, and C euphoniums are even more common. Bb tubas are most common in the US primarily because the sousaphone, which high school and college band students use for at least half the school year, is usually tuned to Bb.
So, to solve your problem, I would suggest you simply "forget" the names of the notes produced by different valve positions as you originally learned them. The fundamental note of your instrument, the lowest note you can play without using any valves, is Eb, the note one leger line below the bass clef. The partial above that should be Bb, and then the partial above that should be the octave Eb. Pressing the second valve from any of these open partials will lower the note by one half-step, the first valve by a whole step, and the first and second, or the third, by a step and a half. Valves 2 and 3 lower the pitch by a major third, 1 and 3 (or 4 if you have a four-valve instrument) by a fourth, and 1,2, and 3 (or 2 and 4) by a tritone.
It'll be rough, but if you are given concert-pitch music, you must play it in concert pitch; transposing on the fly is the very last option for any musician.
Comment: When I was learning to play in the school band, we got all sheets transposed for E♭ tuba in G clef. See my examples: For the transposed version for E♭ tuba in G clef, the notes has the same positions on the note lines as the concert key in bass clef. The only difference is in the sharps and flats. As a general rule when transposing for E♭ tuba, I am just thinking "remove 3 flats (or add sharps)". This works just fine until we get something like A♯ in concert pitch, which translates to F♯♯ in my head, which is really G.
Answer: In addition to other brilliant answers here, I would also point out another benefit of generally being able to read concert pitch bass clef.
From time to time, we have compositions that include parts written for contrabass or string bass, and those are naturally written in C natural. If there are important sections in those parts that are missing in the tuba parts, our conductor would want us to play that (as we are a wind orchestra and thus not have string instruments that those parts were originally written for...).
Answer: In the British brass band tradition, Eb and Bb bass (that's what they call a tuba) have specific parts, and follow the system where all valved instruments read transposed treble clef, thus allowing easy movement between instruments - learn the fingerings for one, you've learnt them all.  (No need to discuss the bass trombone anomaly now.)
In orchestra, there's a tuba part.  Maybe the composer had a particular size instrument in mind.  The player MAY own a selection of tubas, to match what was available in different ensembles in different eras.  But mostly he'll just bring along whatever he's got.  Maybe an Eb instrument or a C one.  Maybe even something else.  So we tell him the notes we want, he sorts out how to deliver them.
Answer: Concert band music always contains two euphonium parts - one bass clef part at true pitch and one treble clef part transposed for a Bb instrument.   I assume that this is done because of the large number of euphonium players who started off their musical career by reading treble clef euphonium parts in brass bands or in Salvation Army bands.   In 100-year-old music I often see this duplication for trombones and tubas but modern publications always use bass clef true pitch for the trombones and tubas.
Today a lot of sheet music can be purchased through the Internet, downloaded and printed by the buyer.   Hopefully the music publishers will consider providing both bass and treble clef parts for the tubas and trombones just as they already to for euphoniums, now that they would not face additional printing costs.
Answer: In Australia, following the British Brass Band tradition, all instruments in the band, other than bass trombone and sometimes Bflat Bass, are learned in transposed treble clef. The reasoning behind this is that a player can jump from valved instrument to valved instrument and not be concerned with learning a new scale etc (despite the pitch being different between Eflat and Bflat instruments).
Concert bands and orchestras on the other hand generally have parts in concert pitch bass clef (for lower brass). Orchestras for the reasons given above, concert bands because generally the brass players are doing nothing so have time to think about the transposition :)
Peter.
Comment: "brass players are doing nothing".. well - I play in a wind orchestra, and our conductor does a lot of his own arranging. When we get a peace that he arrange for the orchestra where the original is a pop/rock peace, and the tuba is basically a transcription of what the bass player played around with on a specific recording, it can be somewhat non-trivial for tuba players. Especially when it is a song by Frank Zappa...


C# generics: failure of generic type inference means I cannot use anonymous type

Question: I have a class Exporter which has a generic method which accepts an IEnumerable<T> and creates an export document by enumerating its property values using reflection:
  public class Exporter
  {
    public string Export<T>(IEnumerable<T> enumerable)
    {
      //Implementation omitted
    }
  }

Because of generic type inference, I can supply this with an anonymous collection type. Note the absence of the generic parameter in the method call below:
string fooString =
        new Exporter().Export(new List<Foo>()
                                {
                                  new Foo() {Name = "cats", NumberOfHams = 1},
                                  new Foo() {Name = "dogs", NumberOfHams = 8}
                                }
                       .Select(x => new { TwiceTheHams = x.NumberOfHams * 2 }));

We all love C#3. However, I would like to adapt this class so that I can enter more information about the columns in the export document, for example the width.
I have created a new method in the export class which looks like this:
public string Export<T>(IEnumerable<T> enumerable, IEnumerable<ColumnDetails<T>> columnDetails)
    {
      //Implementation omitted
    }

Ideally, the syntax would be like this, where foos is of type IEnumerable<Foo>:
fooString = new Exporter().Export(foos,
                                      new List<ColumnDetails<Foo>>
                                        {
                                          new ColumnDetails<Foo>(x => x.Name, 12),
                                          new ColumnDetails<Foo>(x => x.NumberOfHams, 4),
                                        });

However, when I call the new Export() overload as above, the generic type inference doesn't seem to be clever enough to infer that the generic parameter T for the ColumnDetails<T> should be the same as the generic parameter T for the IEnumerable. This means that I must specify List<ColumnDetails<Foo>> as the parameter, and therefore I cannot use this with anonymous collections.
I'm really new to generics and type inference. Is what I'm trying to do possible? Do I need to restructure the code somehow?
Edit: this is what I cannot do, because Visual Studio needs the generic parameter for ColumnDetails, which I don't have:
fooString = new Exporter().Export(foos.Select(x => new {TwiceTheHams = x.NumberOfHams * 2}),
                                          new List<ColumnDetails>
                                            {
                                              new ColumnDetails(x => x.TwiceTheHams, 12)
                                            });

Comment: When you talk about "anonymous collections" and "anonymous types" I don't think you *really* mean anonymous types - at least, you haven't shown any calls to `Export` using an anonymous type. It would really help if you could give a complete example where it's failing...
Comment: @David: Ah, I'd misread the call to Select as being *after* the Export. It would be simpler to just show a plain collection of anonymous type values, e.g. `new[] { new { X="x" }, new { X="y" }`. Again, a complete example would be useful. (How are you creating the `List>` when `T` is anonymous for example?)
Comment: I do not see any reason for generics in provided code.
Comment: @Tomas: it means you can provide an IEnumerable of any object (for example a business entity) and export it in a kind of report. Or the output of a Linq query. I can't see a way of doing this without generics.
Comment: @Jon: the second code block calls the Export method with collection of anonymous type (which is what I mean by anonymous collection). The IEnumerable supplied to it is projected to an anonymous type using the Select() method.
Comment: @David there are no anonymous types in your code sample.
Comment: @Davy8: There's one - the `Select` call in the second example. I agree it's not very obvious though.
Comment: Ah, I was confused because he mentioned "Ideally, the syntax would be like this" and in that example there are no anonymous types.
Comment: Sorry, I've made a real balls-up of explaining what I want. But Jon's question 'how are you creating teh List> when T is anonymous' is precisely my question! Thank you Jon!
Comment: @David In cases like this, i make business entity interface constraint on generic type, thus omitting reflection.
Comment: Tomas - I'd love to see what you mean. Can you provide an example?
Comment: @David: Okay, in that case it's probably a matter of using inference again (within the method call) but it's hard to know how to do that without knowing anything about what ColumnDetails is meant to be.
Comment: I'm going to repost this question more clearly to see if anyone can make more sense of it.
Answer: Would this be sufficient to fix it?
Export<Foo>
fooString = new Exporter().Export<Foo>(foos,
     new List<ColumnDetails<Foo>>
          {
               new ColumnDetails<Foo>(x => x.Name, 12),
               new ColumnDetails<Foo>(x => x.NumberOfHams, 4),
          });

Comment: The code works at present with known types such as Foo. It doesn't work with collections of anonymous types.
Comment: I see. Anonymous types might be tougher because you must use inference. You can always switch to Export and let it fly without a safety net.
Comment: @Micheal it's doable without `dynamic` even though it's a little ugly.  See the latest edit to my answer.
Answer: So you want to pass in a List<ColumnDetails< *anonymouse type with TwiceTheHams property* >> ?
It looks to me like you need a generic helper function that will take an IEnumerable<T> parameter and construct a list of ColumnDetails objects from it. Then insert a call to that function as the second parameter to Export.
Answer: How about something like this?
The anonList lets you have a reference IEnumerable<anontype> and the T foo in CreateColumnDetails<T> lets the compiler infer what type T is, allowing you to construct the object with an anonymous type as the value of T
class Program
{
    public static ColumnDetails<T> CreateColumnDetails<T>(T foo, Func<T, object> func, int x)
    {
        return new ColumnDetails<T>(func, x);
    }
    static void Main(string[] args)
    {
        IEnumerable<Foo> foos = new List<Foo>();
        var anonList = foos.Select(x => new {TwiceTheHams = x.NumberOfHams*2});
        var fooString = new Exporter().Export(anonList,
                                      anonList.Select(y => CreateColumnDetails(y, z => z.TwiceTheHams, 12)));
    }
}
public class Exporter
{
    public string Export<T>(IEnumerable<T> enumerable, IEnumerable<ColumnDetails<T>> columnDetails)
    {
        return string.Empty;
    }
}

public class ColumnDetails<T>
{
    public ColumnDetails(Func<T, object> func, int x)
    {

    }
}
public class Foo
{
    public string Name { get; set; }
    public string NumberOfHams { get; set; }
}

Comment: I've explained this poorly. What I mean is I can't call `Export(IEnumerable x, IEnumerable> y)` if `x` is a collection of an anonymous type, because then I can't instantiate the collection of `ColumnDetails`. God, this is hefty stuff.
Comment: @David Can you show what ColumnDetails looks like?  That might help.
Comment: This works, but as you say it's a little ugly. I think basically my original thought was correct - generic type inference just doesn't go this far.


Why the set of maximal ideal of a domain with jacobson radical zero is infinite?

Question: Let $R$ be a commutative Noetherian domain (is not a field) with $\operatorname{Jac}(R)=(0)$. Why the set of maximal ideal of $R$ is infinite?
Comment: The noetherian condition is not needed at all as the solution demonstrates
Answer: If there were only finitely many maximal ideals $m_1,\ldots,m_n$ then pick non-zero $x_i\in m_i$ and you will find $\prod x_i\in Jac(R)=\bigcap m_i$. But certainly in a domain this product is not zero, so we have found a non-zero element in the Jacobson radical.


Alternative Definitions of Resolvent Set of an Unbounded Operator and Their Equivalence

Question: Between alternative sources, there appear to be subtle differences in the definitions of the resolvent set for an unbounded operator on a Hilbert space. I am not able to reconcile the differences between two of the more precise definitions that I have found and would appreciate any insights that would help resolve and clarify these.
Suppose $H$ is a Hilbert space and $T: H \supset \mathfrak{D}(T)\rightarrow H$ is an unbounded linear operator. Then, I have the following two definitions of the resolvent set (adapted to the current setting, notation harmonized for consistency, and augmented for my questions)
From A.W. Naylor and G.R. Sell, Linear Operator Theory in Engineering and Science, Springer-Verlag, 1982, pp. 412:
6.5.2 Definition. The set of all [complex numbers] $\lambda$ such that the range of $(\lambda I - T)$ is dense in $H$ and $(\lambda I - T)$ has a continuous inverse defined on its range is said to be the resolvent set $\rho_1(T)$ of $T$.
From B.C. Hall., Quantum Theory for Mathematicians, Springer,2013, pp. 177:
Definition 9.16. A number $\lambda \in \mathbb{C}$ belongs to the resolvent set $\rho_2(T)$ of $T$ it there exists a bounded operator $B$ with the following properties: (1) For all $x \in H$, $B x$ belongs to $\mathfrak{D}(T)$ and $(T- \lambda I) B x=x$, and (2) for $x \in \mathfrak{D}(T)$, we have $B (T- \lambda I) x=x$.
Because a densely defined bounded operator in $H$ has a unique extension to the entire Hilbert space $H$, the required operator $B$ in the second definition appears to be the extension, to all of $H$, of the bounded inverse for $(T - \lambda I)$ defined over its dense range in the first definition. However, the two definitions do not appear to be equivalent. Because the resolvent set would be trivially empty for operators that are not closable, it would also be okay if I could show the second definition is equivalent to the first for closed operators. Specific questions and my line of reasoning associated with those are below:
The first property in the second definition seems to imply that the range of $(T- \lambda I)$ is $H$, which is a more stringent condition than the requirement from the first definition that the range of $(T- \lambda I)$ is dense in $H$. Based on this observation, it seems to follow that $\rho_2(T) \subset \rho_1(T)$ for any unbounded operator $T$.
Question 1. Is there an example of an unbounded operator for which $\rho_2(T)$ is a strict subset of $\rho_1(T)$?
Question 2. Does the second definition coincide with the first in the more meaningful setting of closed operators, i.e., is $\rho_1(T) = \rho_2(T)$ for any closed operator $T$?
Based on the preceding discussion, to answer the second question affirmatively, we only need to show that for any closed operator $T$, $\rho_1(T) \subset \rho_2(T)$. I outline below my attempted sketch at a proof till the point I hit a wall. I would really appreciate answers to the above questions and guidelines for completing the proof sketch if the answer to the second question is a yes.
Suppose $T$ is a closed operator and $\lambda \in \rho_1(T)$. Define the bounded operator $B$ as the unique extension of the bounded inverse of $(T - \lambda I)$ from its dense range to all of $H$. $B$ is bounded and therefore closed. However, I cannot show that for all $x \in H$, $B x$ belongs to $\mathfrak{D}(T)$, which seems like a non-intuitive a posteriori imposition of a constraint on the operator $T$. If I could establish that $B$ is injective (which it needs to be), it seems like I could use the fact that $T$ is closed. However, the fact that the restriction of $B$ to the (dense in $H$) range of $(T - \lambda I)$ is injective does not seem to readily imply that $B$ is also injective. My guess is that the Closed Graph Theorem should play a role here and, if so, would also like a pointer to the specific statement of the Closed Graph Theorem applicable for this setting.
Responses are much appreciated; thanks in advance for your help!
Answer: For question 2, you're right that an operator $T$ that is not closed has an empty resolvent by the second definition (which is the more common one.)  The graph of $B$ is closed because it's bounded.  The graph of $T-\lambda I$ is obtained from the graph of $B$ by swapping the coordinates.  So the graph of $T-\lambda I$ is closed, so $T-\lambda I$ is closed, and it's simple to show that $T$ is closed iff $T-\lambda I$ is closed for any $\lambda\in\Bbb{C}$.
To complete your proof - the extended $B$ maps into $\mathfrak{D}(T)$.  Let $v\in H$.  The range of $T-\lambda I$ is dense, so there is a sequence $x_n\in\mathfrak{D}(T)$ such that $(T-\lambda I)x_n\to v$.  Since $B$ is bounded, $x_n=B(T-\lambda I)x_n\to Bv$.  So $x_n\to Bv$ and $(T-\lambda I)x_n\to v$.   Since $T$ is closed, so is $T-\lambda I$ and it follows that
$Bv\in\mathfrak{D}(T)$ and $(T-\lambda I)Bv=v$.   We are already assuming that for $v\in\mathfrak{D}(T), B(T-\lambda I)v=v$ so nothing further to prove.  It also follows that $B$ is injective because if $Bv=0$  then $v=(T-\lambda I)Bv=0$.
For your first question, let $T$ be densely defined, closable but not closed.  Let $\lambda$ be in the resolvent of $\overline{T}$ and $B$ a bounded inverse to $(\overline{T}-\lambda I)$.  Then $B':=B\rvert_{\operatorname{range(T-\lambda I)}}$ gives an inverse for $T-\lambda I$ by the first definition.  OTOH, since $T$ is not closed, its resolvent by the second definition is empty.
Comment: Thank you so much Chad K for outlining how to complete the proof. I can now see how I needed to change my approach, injectivity comes in the end instead. A few remarks:
Comment: 1) For a closable operator $T$, $\rho_1(T) = \rho_2(\bar{T})$. In that sense, the first definition provides a slight generalization of the second (though little gain for lot of complexity)
2) The Closed Graph Theorem is not required for establishing the equivalence, though it is useful in further simplification to provide an inverse free definition of the resolvent set


Output matplotlib figure to SVG with text as text, not curves

Question: When I use matplotlib.pyplot.savefig("test.svg", format="svg") to export the figure as SVG, then the resulting SVG file is huge.
This is caused by the fact that there are a lot of text annotations in my figure, and each text ends up as paths in the SVG.
I want my text to end up as text strings in SVG, and not paths. It gets too hard to interpret the output too, if the text strings are exported this way.
Is there a way to force matplotlib to output text as text, not curves?
Currently, I see these code fragments in my SVG file:
<path d=" M9.8125 72.9062 L55.9062 72.9062 L55.9062 64.5938 L19.6719
64.5938 L19.6719 43.0156 L54.3906 43.0156 L54.3906 34.7188 L19.6719
34.7188 L19.6719 8.29688 L56.7812 8.29688 L56.7812 0 L9.8125 0 z "
id="DejaVuSans-45" />

Answer: Matplotlibs SVG text rendering can be configured either in the matplotlibrc or in code.
From Customizing Matplotlib with style sheets and rcParams:
#svg.fonttype : 'path'         # How to handle SVG fonts:
#    'none': Assume fonts are installed on the machine where the SVG will be viewed.
#    'path': Embed characters as paths -- supported by most SVG renderers
#    'svgfont': Embed characters as SVG fonts -- supported only by Chrome,
#               Opera and Safari

This translates to the following code for neither embedding the font nor rendering the text as path:
import matplotlib.pyplot as plt
plt.rcParams['svg.fonttype'] = 'none'

Comment: I don't understand why this isn't the default
Comment: @ShrirajHegde  I was not around when the default was picked, but I suspect the trade off was svg sizes vs svg not rendering the text.
Comment: Is this another one of these options that need to be set before first doing anything with matplotlib?
Comment: For PDF exports, the following does the trick: plt.rcParams['pdf.use14corefonts'] = True
Comment: svg.fonttype = none not only gives you smaller files, but easier editability if you want to edit it by hand afterward
Comment: Thanks, works great. With 'none' my svg output is a lot smaller.


React: Reload logic on route change

Question: I currently have four routes in place using the same controller:

    <Route
        component={App}
        path='/'
    >
        <Route
            component={Search}
            path='/accommodation'
        />
        <Route
            component={Search}
            path='/accommodation/:state'
        />
        <Route
            component={Search}
            path='/accommodation/:state/:region'
        />
        <Route
            component={Search}
            path='/accommodation/:state/:region/:area'
        />
    </Route>

The component connects the mapStateToProps to a function that loads data from an api.

// ACTIONS
// ==============================================

function mapStateToProps ({destination, properties}) {
    return {destination, properties};
}

// CONNECT & EXPORT
// ==============================================

export default connect(mapStateToProps)(
    connectDataFetchers(Search, [loadSearch])
);

and renders a list of results.
When the route is changed to any of the others using the same controller, the data is not reloaded with a relevant call to the api to fetch the new set of results.
Is this possible to do either with react-router of any of the componentWill functions?
SOLUTION
Thanks to @john-ruddell the following solution works:

componentWillReceiveProps = (nextProps) => {
  if (this.props.params != nextProps.params) {
    loadSearch(nextProps.params);
  }
}
Answer: You need to add logic to request the data and your store needs to capture that and pass it down to the component
componentWillReceiveProps(nextProps){
    //boolean to check if the props.params have changed
        //fetch data request
}

Your store needs to update with the new data that is returned. this data should be passed down to this same component as props to be rendered.
You can also update your routes to simplify it a ton
<Route component={App} path='/'>
    <Route path='/accommodation(/:state)(/:region)(/:area)' component={Search} />
</Route>

Note, the parenthesis () specify an optional parameter. so instead of four routes for the same component you can have only one that works in all four states :)
Comment: Love the simplified route. This may need another question but will ask here anyway but once it hits the function to load the data again the dispatch method is not completed `export function loadSearch (params) {
    return (dispatch) => {
        return dispatch(
            loadDestination(params)
        ).then(() => {
            return dispatch(
                loadProperties(params)
            );
        });
    };
}`
Comment: You have to dispatch with a constant. Look at a basic redux store setup and it'll make sense :)
Comment: It was a mixture - posted the full code at http://stackoverflow.com/questions/36996668/react-dispatch-not-firing-on-route-change/36997219#36997219
Answer: You can modify connectDataFetchers to handle this issue. Here is the example https://github.com/WebbyLab/itsquiz-wall/blob/master/shared/lib/connectDataFetchers.jsx#L26
So, it tracks URL changes and runs connected action creators after change.

React: Reload logic on route change


How to approach finding lines that are perpendicular to each other with as little calculations as possible?

Question: Say we are given equation of a line in $ \mathbb{R^2}$ : $$k:2x+4y-1=0$$Now we want to find a line that is perpendicular to the line $k$ with as little calculations and transformations as possible, so that we can find it relatively quickly,
How one would go about doing that? - I'd suggest using vectors, but I, myself have trouble with expressing these relations simply...
Comment: Can we not rearrange it into the form $y=mx+c$ and use the fact that the gradients of perpendicular lines multiply together to give -1?
Comment: We can forget about the 1 (because of parallellism), and then all $x$ and $y$ that satisfy this equation are exactly those that are perpendicular to the vector (2,4). Hence, the lines $y-2x+k=0, k \in \mathbb{R}$ are all those that are perpendicular
Comment: I am using the dot product. Having the condition $2x+4y=0$ is the same as the condition $(2,4) \cdot (x,y)$=0
Comment: And hence, $(2,4)$ is perpendicular to $(x,y)$
Comment: @LukasRollier Yes, that's true, but what about using properties of vectors, possibly the dot product and vector multiplication? - would that be manageable to do quickly?
Answer: Note that the vector of the line $k$ is $n=(2,-1)$. Assume that the perpendicular line passes the point $(x_1,y_1)$, then, in vector form, its equation is given by
$$(x-x_1,y-y_1)\cdot n=0$$
Comment: @UndergraduateWannabe - If you carry out the dot product, you get the equation $2(x-x_1)+4(y-y_1)=0$.
Comment: Haven't really seen the equation of a line in the vector form like this before, if we were to express it in the same form as the line $k$ what would we get?
Because as I understand we have two cases when lines are either parallel or perpendicular, and these come from the vector properties of dot product?
Comment: That's correct, thanks!
Answer: If your question is limited to $\mathbb{R}^2$ you can

find the slope $m$
take all lines with slope $-1/m$ of the form $y=b -x/m$ for any $b$.
Comment: Sure, but could we use properties of two vectors that are perpendicular and use vector multiplication/ dot product to find this line?