Error for invalid css when trying to compile sass

Question: I am new to sass, after having downloaded bulma, installed gem, and sass, I tried to compile a default sass file with sass style.scss style.css, here is my directory structure

But I get errors likes this:
/*
Error: Invalid CSS after "$pink": expected selector or at-rule, was ": #ffb3b3 "
        on line 2 of styles.scss

1: $blue: #72d0eb
2: $pink: #ffb3b3
3: $orange: #FFA500
4: $family-serif: "Georgia", serif
5:
6: $danger: $orange
7: $family-primary: $family-serif

Backtrace:
styles.scss:2
/usr/local/share/gems/gems/sass-3.4.23/lib/sass/scss/parser.rb:1207:in `expected'
/usr/local/share/gems/gems/sass-3.4.23/lib/sass/scss/parser.rb:1137:in `expected'
/usr/local/share/gems/gems/sass-3.4.23/lib/sass/scss/parser.rb:42:in `parse'
/usr/local/share/gems/gems/sass-3.4.23/lib/sass/engine.rb:406:in `_to_tree'
/usr/local/share/gems/gems/sass-3.4.23/lib/sass/engine.rb:381:in `_render_with_sourcemap'
/usr/local/share/gems/gems/sass-3.4.23/lib/sass/engine.rb:298:in `render_with_sourcemap'
/usr/local/share/gems/gems/sass-3.4.23/lib/sass/exec/sass_scss.rb:391:in `run'
/usr/local/share/gems/gems/sass-3.4.23/lib/sass/exec/sass_scss.rb:63:in `process_result'
/usr/local/share/gems/gems/sass-3.4.23/lib/sass/exec/base.rb:52:in `parse'
/usr/local/share/gems/gems/sass-3.4.23/lib/sass/exec/base.rb:19:in `parse!'
/usr/local/share/gems/gems/sass-3.4.23/bin/sass:13:in `<top (required)>'
/usr/local/bin/sass:23:in `load'
/usr/local/bin/sass:23:in `'
*/
body:before {
  white-space: pre;
  font-family: monospace;
  content: "Error: Invalid CSS after \"$pink\": expected selector or at-rule, was \": #ffb3b3 \"\A         on line 2 of styles.scss\A \A 1: $blue: #72d0eb \A 2: $pink: #ffb3b3 \A 3: $orange: #FFA500\A 4: $family-serif: \"Georgia\", serif\A 5: \A 6: $danger: $orange\A 7: $family-primary: $family-serif "; }

I can't seem to find a fix for this
Answer: Try terminating the line by a semi-colon (;)
For example -
$font-stack:    Helvetica, sans-serif;
$primary-color: #333;

Comment: I tried it, I even created two files `styles.sass` and `style.scss` and put semi colons at the end of the variable values, but I get errors saying invalid css, `expected expression (e.g. 1px, bold), was ";" on line 1 of styles.sass`
Answer: You're compiling a real Sass file, with the Sass indented syntax (no braces, no semi-colon, indentation alone is sufficient).
But the extension of your file is *.scss, meant for CSS-like syntax (there's a c, see ^^)
Either rename your file to styles.sass with an a or write your styles as you'd write CSS (but with nested rules, variables, etc provided by this preprocessor :) )
Sass the compiler compiles both Sass indented syntax and Scss one, which is not straightforward...
EDIT: try to compile a plain CSS file (no variable, no mixin, no nesting just CSS) renamed to .scss. CSS is valid LESS and Scss so if it doesn't compile, the problem isn't with your file.
You can also try to compile the content of your file in http://www.sassmeister.com and play with the options.
Comment: I don't understand, if you check out http://bulma.io/documentation/overview/start/ in the final example, shows that I need to include the code in my "sass" file, which can only mean `foo.sass` as for the indentation, I just copy-pasted it as is. What can I do more than that?
Comment: That's what I'd do too. But test that your compiler is working fine with a CSS file renamed as `*.scss`. Also what happens if you add your variables after 1st line of https://github.com/jgthms/bulma/blob/master/bulma.sass and then try to compile that file?


How can i fix problem of "illuminate/filesystem conflicting version" while installing laravel breeze?

Question: I am trying to install Laravel breeze but having this error:
$ composer require laravel/breeze --dev
Using version ^1.2 for laravel/breeze
./composer.json has been updated
Running composer update laravel/breeze
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - laravel/breeze[v1.2.0, ..., 1.x-dev] require illuminate/filesystem ^8.42 -> found illuminate/filesystem[v8.42.0, v8.42.1, 8.x-dev] but it conflicts with another require.
    - Root composer.json requires laravel/breeze ^1.2 -> satisfiable by laravel/breeze[v1.2.0, 1.x-dev].

Installation failed, reverting ./composer.json and ./composer.lock to their original content.

Here is my composer.json (i.e. fresh install of laravel):
"require": {
        "php": "^7.3|^8.0",
        "doctrine/dbal": "^3.1",
        "fideloper/proxy": "^4.4",
        "fruitcake/laravel-cors": "^2.0",
        "guzzlehttp/guzzle": "^7.0.1",
        "laravel/framework": "^8.40",
        "laravel/tinker": "^2.5"
    },
    "require-dev": {
        "facade/ignition": "^2.5",
        "fakerphp/faker": "^1.9.1",
        "laravel/sail": "^1.0.1",
        "mockery/mockery": "^1.4.2",
        "nunomaduro/collision": "^5.0",
        "phpunit/phpunit": "^9.3.3"
    },

Can anyone please help me out?
Answer: You can tell composer to update your packages which conflicts with the target package requirements using --with-dependencies and --with-all-dependencies commands. Read more
So, you can tell composer to update your package to resolve the conflicts.
composer require laravel/breeze --dev -W


Converting an equation into R code

Question: I have a very long expression that I want to convert into R code. Here is an example showing what the expression looks like/how it is written:
(a exp(-a t) t^4)/(24 (a-b) (a-c) (a-d))

In order to be understandable by R, the multiplication sign * should be added between the variables, brackets etc. Is there a way to do this automatically rather than inserting it manually?
The expression should look like this:
(a *exp(-a*t) *t^4)/(24* (a-b)* (a-c)* (a-d))

Comment: How your expression is stored?
Comment: I stored it as a CDF file and then copied the text into R studio.
Answer: If the input is of the form shown then it would be sufficient to replace each space with a * using gsub like this:
expr <- "(a exp(-a t) t^4)/(24 (a-b) (a-c) (a-d))"
gsub(" +", "*", expr)
## [1] "(a*exp(-a*t)*t^4)/(24*(a-b)*(a-c)*(a-d))"

Comment: Yop thats absolutely a good idea. Also, I can do the replacement using Notepad++ which is really handy! Thank you.

Converting an equation into R code


Ajax loading bar function

Question: I know there are a few post about this but they dont cover what i need to achieve.
I'm trying to get the youtubelike loading bar to work properly.
And i found this :
var data = [];
for (var i = 0; i < 100000; i++) {
    var tmp = [];
    for (var i = 0; i < 100000; i++) {
        tmp[i] = 'hue';
    }
    data[i] = tmp;
};

       xhr: function () {
                var xhr = new window.XMLHttpRequest();
                var percentComplete = 0; <--------------------------added this
                $('.progress').removeClass('hide');<----------------and this
                xhr.upload.addEventListener("progress", function (evt) {
                    if (evt.lengthComputable) {
                        var percentComplete = evt.loaded / evt.total;
                        console.log(percentComplete);
                        $('.progress').css({
                            width: percentComplete * 100 + '%'
                        });
                        if (percentComplete === 1) {
                            $('.progress').addClass('hide');
                        }
                    }
                }, false);
                xhr.addEventListener("progress", function (evt) {
                    if (evt.lengthComputable) {
                        var percentComplete = evt.loaded / evt.total;
                        console.log(percentComplete);

                        $('.progress').css({
                            width: percentComplete * 100 + '%'
                            });
                    }
                }, false);
                return xhr;
            }

I have added 2 lines because it would only work once as the hidden value was not being removed after the completion. Also put the width back to 0. I also like the fact that it seams to be calculating the real percentage of the event.
This is working great. Howerver, i want to turn this into a function that can be called for all my ajax call like this:
$(document).ready(function () {
    $("a").on("click", function (event) {
        event.preventDefault();
        var id = ($(this).attr("id"));
        var container = ($(this).attr("data-container"));
        var link = ($(this).attr("href"));
        var text = ($(this).text());
        var html = ($(this).html());
        MY_LOADING_BAR_FUNCTION();<-----------------------------------Here i guess?
        $.ajax({

            url: 'ajax-php.php',
            type: 'post',
            data: { 'action': 'click', 'id': id, 'text': text, 'link': link, 'html': html },
            success: function (data, status) {
                if (container == '#formbox') {
                    $("#screen").addClass("visible");
                }
                $(container).html(data);
            },
            error: function (xhr, desc, err) {
                console.log(xhr);
                console.log("Details: " + desc + "\nError:" + err);
            }
        }); // end ajax call
    }); // end on click
}); // en document ready

But i also ran across the Ajax setup that looks like this.
   $.ajaxSetup({
    beforeSend: function() {

    },
    complete : function() {

    }
});

Right now i got it to work by putting the entire code of the xhr: function () inside my ajax call. But i dont want to do it every time.
So these are the 2 options i have found that could work but i cant get them to work the way i want. I try to make a MY_LOADING_BAR_FUNCTION() but i'm getting a deprecated error.
Can anyone tell me how to make this work please.
Thank you everyone!
Comment: Like youtube? This is not a single request. This is many requests. For first all requests should add into "queue". And after success, each request should update loading bar. For improved you can set percentage weight of each request.
Comment: Huh No! this is one single request sending a Json array to a php file!?
Answer: It's late to reply, but its worth to share some knowledge, so others may get help from it.
You can extend jQuery AJAX XHR object as below.
jQuery.ajaxSettings.xhr = function ()
{
    var xhr = new window.XMLHttpRequest();
    //Upload progress
    xhr.upload.addEventListener("progress", function (evt) {
        if (evt.lengthComputable) {
            var percentComplete = evt.loaded / evt.total;
            //Do something with upload progress
            console.log('percent uploaded: ' + (percentComplete * 100));
        }
    }, false);
    //Download progress
    xhr.addEventListener("progress", function (evt) {
        if (evt.lengthComputable) {
            var percentComplete = evt.loaded / evt.total;
            //Do something with download progress
            console.log('percent downloaded: ' + (percentComplete * 100));
        }
    }, false);
    return xhr;
}

Ajax loading bar function


What is the Fourier Transform of an absolute function?

Question: I would like express that the Fourier transform of the function
$$
|f(x)|
$$
as
$$
\widehat{|f|}(\xi) = \text{a function of } \widehat{f}(\xi)
$$
In fact, I want to know the relation of $\widehat{|f|}(\xi)$ and $\widehat{f}(\xi)$.
I think a identity $|f|^2 = f \overline{f}$ may help.
Comment: I agree that the link given by @BLAZE is not related. I can also add that I've never seen some formula for the Fourier transform of the absolute value of a function in  terms of the Fourier transform of the function...
Answer: Let $f\in L^1$, $f\ge0$ and $a\in\mathbb{R}$. Define $f_a(x)=e^{iax}f(x)$. Then
$$
\widehat{f_a}(\xi)=\hat f(\xi+a),\quad \widehat{|f_a|}(\xi)=\hat f(\xi).
$$
There is no functional relation between the Fourier transforms of $f$ and $|f|$.


Getting error trying to get authenticated user

Question: Using dingo/api along with lucadegasperi/oauth2-server-laravel. Authenticating a user is fine and I get an access token back but any time I make another request I get the following error:
call_user_func() expects parameter 1 to be a valid callback, no array or string given
I'm using the Service Provider option listed in the dingo/api docs and it's definitely setting the user resolver (I'd var_dump'd the resolver in the setUserResolver method).
My OauthServiceProvider is below.
<?php namespace App\Providers;
use Dingo\Api\Auth\Auth;
use Dingo\Api\Auth\Provider\OAuth2;
use App\User\User;
use Illuminate\Support\ServiceProvider;

class OAuthServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->app[Auth::class]->extend('oauth', function ($app) {
            $provider = new OAuth2($app['oauth2-server.authorizer']->getChecker());

            $provider->setUserResolver(function ($id) {
                return User::first();
                // Logic to return a user by their ID.
            });

            $provider->setClientResolver(function ($id) {
                // Logic to return a client by their ID.
            });

            return $provider;
        });
    }

    public function register()
    {
        //
    }
}

Comment: Can we see a stack trace to help further...
Comment: https://gist.github.com/Johnathan/ab3f26d4a9bf1185f42c
Answer: So turns out I was completely off in where I was looking. In config/api.php, in my auth settings I had
        'oauth2' => Dingo\Api\Auth\Provider\OAuth2::class,

Should have just been
        'oauth' => Dingo\Api\Auth\Provider\OAuth2::class,


I encountered the problem that the execution result of javascript is not as expected

Question: Code is as follows:
/**
 * this is calculate Timer
 * @param delay Timing steps
 * @returns object Provide calling interface
*/
function countTime(delay = 20) {
    let millseconds = 0,
        seconds = 0,
        timer = null;
    // calculate
    function calculate() {
        millseconds += delay;
        if (millseconds === 1000) {
            seconds += 1;
            millseconds = 0;
        }
    }
    // start the calculate
    function start() {
        timer = setInterval(calculate, delay);
    }
    // end the calculate
    function end() {
        clearInterval(timer);
        timer = null;
    }

    return {
        start,
        end,
        seconds
    };
}
const obj = countTime();
obj.start();
// Wait for a while to execute
obj.end();
// execute output
console.log(obj.seconds); // always output 0

Has anyone encountered a similar issue?
I really want to know what mechanism is causing javascript, Or is there something missing in my own writing?
Comment: Please add a proper problem/error description in your question and not only two small comments hidden in your script
Comment: _"// Wait for a while to execute"_ - Nothing in your script prevents `obj.end()`/`console.log(obj.seconds)` to execute _before_ the first "tick" of the interval/`calculate`
Comment: add console logs in `start` `calculate` and `end` and things will start to make sense.
Answer: There are 2 problems with the code. First one is that when your function gets executed it returns object with "seconds" property. Unfortunately, that property is not being calculated each time you check against it. So basically it's a stale value. To fix that you can create a new function in your code `getSeconds:
function countTime(delay = 20) {
  function getSeconds() {
    return seconds;
  }
  ...

  return {
    start,
    end,
    getSeconds
  }

Another issue is that you are not waiting enough time before checking for the seconds. So you should have something like that:
const obj = countTime();
obj.start();

setTimeout(() => {
  obj.end();
  console.log(obj.getSeconds());
}, 3000)


ActiveRecord Query - Rails

Question: Within my rails app, I have a Book model and a User model.
I'm using the acts_as_votable gem to allow voting on the books model.
In one of my views, I am currently rendering a list of all books that the current user has not voted for and then grabbing a single random book from that list:
@books = Book.where.not(id: current_user.find_voted_items.map(&:id))
@book = @books.sample

I have now added categories to both users and books, using the acts-as-taggable-on gem.
A book or a user can have up to 9 predefined categories(tags) selected, as part of the tag_list.
tag_list = "math, science, history, design, art, film, music, philosophy, poetry"

Books and users share these same 9 categories/tags.
I'm trying to retrieve a list of all books that share any similar tags to what the current user has selected under their settings, excluding all books that the user has already voted for, and excluding all books that belong to the current user (book.user != current_user).
Lastly I'm trying to select one single random book from this list.
How would I go about doing this?
Answer: Something like the following code should work.  It feels pretty hacky, though.
Book.tagged_with(current_user.tags, any: true).
  where.not(user: current_user).
  where.not(id: current_user.find_voted_items.map(&:id)).
  sample

If you find you are using parts of this query in other places, I'd suggest extracting them into class methods.  Since you will need to pass in the current user as an argument, note that the preferred way (According to Rails Guides) is to use a class method instead of a scope.

ActiveRecord Query - Rails


Perguntar antes de excluir dados do banco

Question: Tenho esse codigo:
<?php
if ($result = $mysqli->query("SELECT * FROM usuario ORDER BY id"))
{
    if ($result->num_rows > 0)
    {
        echo "
";

        // definir cabeçalhos de tabela
        echo "
 ID	 Nome	 Email
";

        while ($row = $result->fetch_object())
        {
            // cria uma linha para cada registro
            echo "
";
            echo "" . $row->id . "	";
            echo "" . $row->nome . "	";
            echo "" . $row->email . "	";
            echo "id . "'>Editar	";
            echo "id . "'>Deletar	";
            echo "
";
        }

        echo "
";
    }
}
?>

e preciso que uma caixa de texto pergunte antes se realmente quero excluir os dados, qual a melhor forma de se fazer isso?
grato.
tentei usar dessa forma:

mas não sei como usar a variavél $confirm
Comment: delete foi apenas como exemplo, a variável que utilizei foi idlink e o que eu não consigo compreender é o erro de sintaxe que acorre nesta linha     **echo "Deletar";**
Comment: Ah, o nome da sua função é `delete`. `delete` é uma palavra reservada do JavaScript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete. Muda o nome da função (para `remove`, por exemplo) e tudo deve funcionar.
Comment: Eu editei minha resposta. Como o @People mencionou, faltou escapar as aspas duplas por causa do `echo`.
Answer: A forma mais simples de se fazer isso é usando JavaScript, através da função confirm e do evento onclick:
Ir para o Google!

Você pode ver isso funcionando nesse exemplo: http://jsfiddle.net/tbcww98q/
Abaixo você pode ver como ficaria o seu código:
echo "
";
echo "" . $row->id . "	";
echo "" . $row->nome . "	";
echo "" . $row->email . "	";
echo "id . "'>Editar	";
echo "id . "' onclick=\"return confirm('Tem certeza que deseja deletar esse registro?');\">Deletar	";
echo "
";

Comment: Você esqueceu de escapar as aspas duplas dentro da string, a linha com o **onclick** deve ficar assim: `echo "Deletar";`
Comment: eu estava na dúvida de como usar confirm, obrigado por esclarecer minhas dúvidas, porem acusa erro de sintaxe, não sei como empregar a função junto com _row->id_
Comment: Por que você precisaria utilizar `$row->id` no `confirm`?
Comment: Tem como você editar sua pergunta e postar seu novo código?
Comment: é uma tabela com vários dados, '$row' busca o id para poder deletar.
Comment: Mas no seu código tu não tá usando confirm. Tem como postar a maneira que você tentou utilizar e erro que ocorreu?
Comment: Obrigado, já arrumei :)
Comment: com ajuda de vocês deu certo, agradeço muito!
Answer: Teste este código assim, ele faz exatamente o que você quer ... se escolher cancelar ele simplesmente para o script e não dá refresh na página, se der um Ok, ele parte para delete.php com captação do id por GET e faz o que quiser conforme as instruções no script em andamento, no caso delete.php.
if ($result = $mysqli->query("SELECT * FROM dados ORDER BY id"))
{

        if ($result->num_rows > 0)
        {

            echo "
";

                // definir cabeçalhos de tabela
               echo "
 ID	 Nome	 Email
";

                while ($row = $result->fetch_object())
                {
                // cria uma linha para cada registro
                echo "
";
                echo "" . $row->id . "	";
                echo "" . $row->nome . "	";
                echo "" . $row->email . "	";
                echo "id . "'>Editar	";
                echo "id . "' onclick=\"return confirm('Tem certeza que deseja deletar esse registro?'); return false;\">Deletar	";
                echo "
";
                }

            echo "
";

         }

}

Answer: Eu não entendo pq ainda insistem em passar o id via GET através de um link.
Será que não perceberam que o link vai aparecer completo para o usuário com o id no final, daí se ele quiser fazer o "mau" com seu DB, pode ficar trocando o id e dando enter deletando os mesmo só para zoar com vc.
Faça um submit via POST atrelando um pop up ou até mesmo uma nova página onde lá vc configura um confirmar com outro submit que irá levar até ao arquivo que delata por require, dessa forma este arquivo não vai ficar exposto e nem o id, impossibilitando que qualquer um que tenha o link de delete simplesmente lhe cause grandes dores de cabeça.


VAR model: combining multiple short samples generated by similar DGPs

Question: I have a problem which only has 35 observations. I like to apply around 6 variables in a VAR model to predict 25 observations into the future. Clearly, the data set is way too small. However, I do have the same sets of data for over 5000 markets. I wonder if I can leverage the large number of markets (each with 35 observations) by treating it like a sampling problem, where the coefficients derived from single market data are collected and merged to arrive at a meaningful mean with a small variance. Does this make sense?
Comment: I changed your title, but feel free to undo this if it distorts your idea.
Answer: It depends on the application. I will give you some ideas without going much into details.
For example (a very contrived example, I must admit!), if the 5000 markets are all independent and behave in exactly the same way (the 35-observation samples have been generated independently by the same data generating process), then you effectively have a sample of $35 \times 5000$ observations. You could then create the response vectors and the design matrices (containing lagged variables) for each market separately and then stack them and feed into a VAR model. You would end up with $(35-p)\times 5000$ effective observations, where $p$ is the lag order of the VAR model.
Since the above example is too ideal to be interesting, you may consider softening the assumption that the data generating process is exactly the same for all the markets. But if the data generating processes are similar, then you could estimate 5000 VAR models jointly imposing some shrinkage of parameters towards common values, something like doing a fused lasso, so that you would incorporate the information of similarity between the markets.
For some related literature on regularized VAR models, see the Google Scholar profile of Christophe Croux and the website on Ines Wilms, especially the "software" section. E.g. Gelper et al. "Identifying Demand Effects in a Large Network of Product Categories" (2016).
Further, if the data is gathered at the same time in 5000 different markets, some of the markets may be hit by common shocks, and thus the information from each different market will likely not be entirely "original". In an extreme case, you would be observing the same 35-observations-long process 5000 times, contaminated by some measurement error. Something should be done to account for such dependence, which effectively reduces the sample size you have. (At the moment I do not have a good idea of what could be done, though, but this should be a known problem and solutions should exist.) Maybe take a look at the panel data literature?
Comment: So one at at time. If we assume the dgp is identical, isn't there a problem stacking the different market data sets back to back? This is forcing the first observation from market 2 to follow the last observation of market 1. That is a false continuity. On the second idea of imposing shrinkage, and still train each market independently, that does not solve the problem of not having enough observations. Panel data requires each unit having sufficient data as well.
Comment: 1. That is why I say first create the data matrices and then stack them. If you first stack them and then create lag matrices, then you are in trouble, of course. 2. I did not say train each independently. There must be a way to make use of all the data through shrinkage towards common values. You (or someone) need to figure out how exactly to do this. 3. Panel data is a way of using information more efficiently than in separate models, so I think there is something to learn from there. But indeed I do not give any clear directions here.
Comment: for 1, I am afraid the vars package does not accept pre-designed data matrix. it simply accepts raw data and ask you to input the lag value. Are you aware of another r package that does accepted pre-designed data matrix?
Comment: No, I am not. But it is not difficult to construct the matrices yourself using function `embed` and then use functions like `lm` or `glmnet` for fitting.
Comment: Great. Let us know how it goes.
Comment: Another question came up. It is possible that some markets within one group share one model well, but there may be a number of groups which differ significantly from each other. So the goal would be to cluster the entire collection of markets into similar behaving (from VAR perspective) groups. Would the straightforward way be simply using the same features set used for VAR to do k-means clustering?
Comment: @bhomass, I doubt it would be this straightforward. I am not convinced the "mechanics" of k-means clustering does what you need here.
Comment: If you could throw some ideas for me to chew on.
Comment: For some literature on regularized VAR models, see the [Google Scholar profile](https://scholar.google.be/citations?hl=en&user=5jtt4GgAAAAJ&view_op=list_works&sortby=pubdate) of Christophe Croux and the [website](http://feb.kuleuven.be/ines.wilms) on Ines Wilms, especially the "software" section. E.g. [this](http://www.sciencedirect.com/science/article/pii/S0022435915000536) paper. With regards to clustering, I could imagine clustering *after* VAR modelling based on VAR coefficients or some other properties of these estimated models.


In statistical terminology, what is the opposite of "peak"?

Question: When we see a curve (or a normal distribution), we describe the highest value as "peak".
Let's imagine we have a curve with only a minimum value (like an inverted hat), what do we call that minimum value?
Comment: I've also heard trough.
Comment: what do you mean by curve? I guess curve is more mathematical that statistical.  if you mean a mathematical concept it is called minima. I am interested in knowing a continues density function with just a minima.
Comment: Basically it just like a function and then you have one minima.
Answer: "Trough" is commonly used, although perhaps somewhat colloquial.
Comment: I say "trough" all the time, but I've never thought of it as particularly informal.
Answer: In signal processing, a commonly used term is negative peak. In mathematics, you use the terms vertex of parabola, highest or lowest point, maximum or minimum.
Comment: This doesn't look like an accurate description of how mathematics understands parabolas.  Indeed, it is rare indeed for any neighborhood of any local extremum of a density function to be part of a parabola, so the term "vertex of parabola" would almost never apply in this context.
Answer: The peaks are called "local modes" (specifically, the x-value is called the mode, the height would be the density at the mode).
The highest one is sometimes called "the mode".
The bottoms of troughs are often called "antimodes"
Comment: It's worth noting that this term actually appears in statistical literature. It sounds a lot clunkier than "trough" though. Statisticians aren't always known to come up with clever terminology.


confusion about NSOperationQueue working

Question: Apple says that
Operation queues usually provide the threads used to run their operations. In OS X v10.6 and later, operation queues use the libdispatch library (also known as Grand Central Dispatch) to initiate the execution of their operations. As a result, operations are always executed on a separate thread, regardless of whether they are designated as concurrent or non-concurrent operations.
As far as i understood from above lines that NSOperationQueue executes operations in parallel, lets put dependency thought aside.
I need to know does really NSOperationQueue initiate all operation in parallel? Does it call
 -start method of each operation at a moment or one by one in queue order?
Comment: How have you configured the queue? Did you try testing it?
Answer: As Tim has already answered, look at the maxConcurrentOperationCount, if you set this to 1, the operations will be executed in serial.
In addition, if you are concerned about the order in which operations are executed but want to utilize parallel execution, you can set up dependencies between NSOperation objects really simple by calling - (void)addDependency:(NSOperation *)operation.
For example, you need that operation1 is executed BEFORE operation 2, you would to something like this:
NSOperation *operation1;
NSOperation *operation2;
[operation2 addDependency:operation1];

Comment: I added some NSInvocationOperations to operation queue.Logged time at the start and end of operations inside queue(operationCount=0) with different maxConcurrentOperationCount and found that time taken was different for different maxConcurrentOperationCount. Thanks @MeXx
Answer: You might be interested in the maxConcurrentOperationCount property of an NSOperationQueue - it determines how many tasks the queue is allowed to start at a time.


Statistical test to compare multiple treatments on the same 'individual' over time

Question: I'm looking for a statistical test or tests to compare the effects of different 'treatments' on a single 'individual' over time. The single 'individual' could be one person or a group acting as a single entity (e.g. a team, a company, etc.). A simple example is comparing the effects of two different exercise regimes on one person's weight loss.
The main concern I have with using a 'standard' statistical test (in this case, something like a t-test, Mann-Whitney U test or Kolmogorov-Smirnov Test seems appropriate) is the obvious non-independence of the data.
I could check for independence by running some form of ABAB study (i.e. alternating the regimes several times to check that they are not interacting). This seems to be the approach that the author of this 'Self Experimentation' paper (Roberts, S.) seems to take. He then uses repeated chi-squared tests (first A against first B, second A against first B, etc.). Is it a valid statistical approach to perform multiple tests on the same data or does this increase the chance of type I errors as indicated in this paper?

The more often one analyses the accumulating data, the greater the
  chance of eventually and wrongly detecting a difference, thereby
  drawing incorrect conclusions from the trial.

Should I worry about the non-independence? Can I simply perform multiple tests against the same data? Is there a specialised test for this kind of experiment?
Comment: It would help to know more about your specific situation and the specific question you want to answer.  If you do an ABBA study (perhaps repeatedly) you might be able to calculate the difference between the first A and B, the difference between the second A and B, and so on.  You could then do a t test to see if these differ from zero.
Answer: If the time aspect is very important then you may want to consider some type of structured dependency model that can deal with a time series, but if I'm understanding your question correctly here's my answer.
The problem with conducting those standard statistical tests repeatedly is called alpha inflation or the problem of multiple comparisons.
Analysis of Variance is a procedure that allows conducting those standard tests simultaneously. The most basic version is a generalized t-test. There are variations of ANOVA like Kruskal-Wallis which is nonparametric. ANOVA is discussed thoroughly on this site. Here is an example of how to do it in SAS, SPSS, and R.
Since you're measuring the same individual repeatedly you'll want to use a repeated measures design. If you're testing multiple hypotheses you'll want to also use a correction factor like Bonferroni, but as far as your question seems to be concerned this may not be the case so this last part may be unnecessary. rANOVA can be sensitive to assumption violations though so if you see your data violates them you may need to consider some other linear model.
I hope this helps. More information about your problem would be useful to give more specific of an answer. Feel free to follow up if this leads to other questions.
Answer: It is good to assume that the time series data would not be independent. It is highly likely hat there would be some serial correlation (auto-correlation) within the subsequent measurements of each treatment. You may estimate time series models for each treatment and then compare the time series to see if the treatments differ in their efficacy.
Here are the resources for comparing time series that I wrote as answer to another question.
Answer: If you are using survival analysis, you could introduce a time dependent covariate to model the problem. This method can accept time dependent variants - in your case, you could say that patient A was in treatment X from day 1 to day 60 and was in treatment Y from day 61 to day 100.
Here are some useful links.
https://cran.r-project.org/web/packages/survival/vignettes/timedep.pdf
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6015946/
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Rewrite rule for everything except a folder

Question: I have an application that uses Zend Framework but has a WordPress blog under the public directory (folder is named "blog").
Accessing the blog's homepage is fine, but when I try to access the posts, my htaccess rules have it go through Zend Framework. What do I need to modify in my /public/.htaccess file to have it ignore requests to the /public/blog directory?
Here's the current .htaccess file:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

Thanks!
Answer: I think, this should work
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/public/blog/
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

Comment: Thanks for your answer Andrey, but I'm afraid it still goes through ZF for URLs like /blog/about or /blog/2012/somepost. Accessing /blog though is fine, it gets routed through WordPress.
Comment: Answer is partially correct though. The thing that was messing up was the WordPress .htacess file located under /public/blog. The .htaccess file under /public was routing fine to that directory, but the RewriteRule parameter used by WordPress needed a bit of tweaking to this:

`RewriteRule . /blog/index.php [L]`

Thanks!


Rails3 structure, engines, plugins, slices, gems, modules..?

Question: Do you have a working example of a Rails3 mvc application?
How will it be organized?
I hope something like:
<code>-app
--controller
--views
-plugins
--myapp1
---app
---controller
---views
---...
</code>
Can app1 use a model from app2?
Will "routes" file be deprecated?
reference:
https://web.archive.org/web/20170704120345/http://yehudakatz.com/2009/07/19/rails-3-the-great-decoupling
https://www.slideshare.net/jacobian/django-in-the-real-world-1750000
Answer: You should check out the Rails 3 screencasts at http://rubyonrails.org/screencasts/rails3.  They're a great introduction to the structure of a Rails 3 app and how it's changed from Rails 2!
Answer: Many of your questions will probably be answered in the Rails 3 Release Notes.
Answer: Try "Creating a weblog in 15 minutes with Rails 2." Some of the code is outdated, but for the most part everything is still organized the same way.


Number Picker displays numbers out of margin

Question: I've been trying to fix this issue for hours now but it looks like I'm the only one having it.

I shouldn't see the number above and below the blue line. Here is the XML
<code>    <android.support.v7.widget.GridLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:useDefaultMargins="true"
            android:layout_margin="3dp"
            app:columnCount="3"
            app:rowCount="7">

    ........

    <NumberPicker
            app:layout_column="1"
            app:layout_row="3"
            android:id="@+id/n_of_dies"
            style="@style/inputNumbers"
            android:layout_width="wrap_content"
            app:layout_gravity="fill_horizontal"
            />
     <NumberPicker
            app:layout_column="1"
            app:layout_row="4"
            app:layout_gravity="fill_horizontal"
            android:id="@+id/carbon_content"
            style="@style/inputNumbers"
            android:layout_width="wrap_content"
            app:layout_gravity="fill_horizontal"
            />
      ........
</code>
The content of Input numbers is
<code> <style name="inputNumbers">
    <item name="android:padding">10dp</item>
    </style>
</code>
any ideas?
Comment: You should put the content of your `@style/inputNumbers` too
Comment: And here is the issue. Basically the padding in the style spoil the component... I removed the padding and everything looks good now.
Answer: Given the problem is how you're using the paddings I'd recommend to take a look at the widget style (the Holo variation) if you want to change the default look:
<code>...

<style name="Widget.NumberPicker">
  <item name="android:internalLayout">@android:layout/number_picker</item>
  <item name="android:orientation">vertical</item>
  <item name="android:fadingEdge">vertical</item>
  <item name="android:fadingEdgeLength">50dip</item>
</style>

...

<style name="Widget.Holo.NumberPicker" parent="Widget.NumberPicker">
  <item name="android:internalLayout">@android:layout/number_picker_with_selector_wheel</item>
  <item name="android:solidColor">@android:color/transparent</item>
  <item name="android:selectionDivider">@android:drawable/numberpicker_selection_divider</item>
  <item name="android:selectionDividerHeight">2dip</item>
  <item name="android:selectionDividersDistance">48dip</item>
  <item name="android:internalMinWidth">64dip</item>
  <item name="android:internalMaxHeight">180dip</item>
  <item name="virtualButtonPressedDrawable">?android:attr/selectableItemBackground</item>
</style>
</code>


What is the attribute for a uicontrol object equivalent to deprecated uititle method

Question: I want to pretty much replicate the GUI implemented here:

and here is what I have got so far:
// first create the GUI panel
figw = 220;
figh = 160;
close(1)
f = figure(1, "position", [0 0 figw figh]);
//PUSH TO STOP
hstop = uicontrol(f, "style", "pushbutton", "Min", 0, "Max", 1, "string", " STOP",..
    "position", [10 10 61 50], "callback", "infiniteloop=%F");
// TRIGGERED MODE
htrig = uicontrol(f, "style", "radiobutton", "Min", 0, "Max", 1, "string", "free/trig", "value", 0,..
    "position", [80 10 20 20]);
//httrig=uititle(htrig,"free/trig","r")
// BINNING x2
hbin = uicontrol(f, "style", "radiobutton", "Min", 0, "Max", 1, "value", 0,..
    "position", [80 40 20 20]);
//htbin=uititle(hbin,"bin x2","r")
// GREYSCALE
hbri = uicontrol("style", "slider", "Min", 1, "Max", 255, "value", 128,..
    "position", [10 70 200 20]);
//htbri=uititle(hbri,"greyscale")
// EXPOSURE (only for untriggered)
hexp = uicontrol("style", "slider", "Min", 1, "Max", 1200, "value", 40,..
    "position", [10 120 200 20]);
//htexp=uititle(hexp,"exposure time")

my main issue at this moment is that I can't find the equivalent attribute / property for the uicontrol objects which corresponds to the deprecated uititle method.
I could indeed use textboxes and find a workaround but that's not the ideal solution given all the positioning headaches. I was wondering if there is still such an attribute which accepts a stering and the put in the described position like r, t, l and b? Thanks for your help in advance.
Answer: The famous uititle from Enrico Segre (emeritus Scilab contributor) could reborn like this, thanks to new layout features of uicontrols:
function t=uititle(h,text)
    pos = h.Position;
    pos(4)=pos(4)*2;
    f = uicontrol("style","frame","position",pos,"layout","grid")
    lay_opt = createLayoutOptions("grid", [2,1])
    set(f,"layout_options",lay_opt);
    c = createConstraints("grid");
    h.parent = f;
    t=uicontrol(f,"style","text","string",text,"horizontalalignment","center",...
                "constraints",c);
endfunction

clf
sl=uicontrol("style","slider","position",[10 10 200 20])
uititle(sl,"a slider")

Comment: Thanks for pointing out the missing peace of code, I have edited my answer. The size of the textbox is not defined a priori. What really matters is the size of the frame which will contain the two uicontrol. To control the position you have to play with the dimensions of the grid, `[2,1]` or `[1,2]` and with the order the two child widgets are packed, i.e. the two lines `h.parent=f` and `t=uicontrol...` should be swapped if necessary. You can also try to use the `gridbag`layout.
Comment: It allows quite nice things like `sl.callback="t.string=string(sl.Value)"`
Comment: Dear Stéphane, Thanks for the kind and clever respond. what a coincidence, Enrico Segre is who initiated the Serial Toolbox which I'm working on  So to be clear this method or anything similar to this does not exists by default? I tried modifying your code to include the relative position option too, please see the current code [here](https://gist.github.com/Foadsf/4076d4bb629577529b7fc9b778e65534). However I get the error `Undefined variable: lay_opt`
Comment: ok figured out that you have forgotten to define `lay_opt` probaby in your example it should be `lay_opt = createLayoutOptions("grid", [2,1])`. I updated [the gist](https://gist.github.com/Foadsf/4076d4bb629577529b7fc9b778e65534) to incorporate this issue. However there are two issues: first width / height of the textbox is not necessarily twice the original uicontrol object. secondly I can't control to put the text exactly on left / right / top / bottom.
Comment: Thanks for the correction. I decided to start collecting Scilab GUI examples and documentation. I will create a GitHub repo and will send it to you.
Comment: I added an `if statement` to take care of the `h` and `t` order. the only issue is now that the text odes not necessarily fit in the specified width.


What is the correct MS Access SQL syntax for creating a union query

Question: The Microsoft documentation states:
CREATE VIEW view [(field1[, field2[, ...]])] AS selectstatement
and lists a number of provisions. I am trying to create a union query with the CREATE VIEW statement using ADODB. The union itself I can run in Access (2013) and save (it shows it is saved as a union query with the two little interlocked circles icon). But the Microsoft.ACE.OLEDB.12.0 engine complains either Unions not allowed in a subquery or  Only simple SELECT queries are allowed in VIEWS. Do I need to use DAO or is there a different syntax? My create view statement is:
uString = "CREATE VIEW vwSpendingTotals (Spending, Name) as SELECT Spending, Name FROM " & _
" (SELECT  Sum( tblA.Amount) as Spending, 'Auto' as Name from tblGeneral_Ledger  gl " & _
" inner join tblAccount_AUTO as tblA on gl.Trans_ID = tblA.Trans_ID " & _
" where gl.Debit_Credit < 0 AND Trans_Date > DateSerial(Year(Now()),1,1)  Union " & _
" SELECT  Sum( tblH.Amount) as Spending, 'Household' as Name from tblGeneral_Ledger  gl " & _
" inner join tblAccount_Household as tblH on gl.Trans_ID = tblH.Trans_ID " & _
" where gl.Debit_Credit < 0 AND Trans_Date > DateSerial(Year(Now()),1,1) union " & _
" SELECT  Sum( tblL.Amount) as Spending, 'Living' as Name from tblGeneral_Ledger  gl " & _
" inner join tblAccount_Living as tblL on gl.Trans_ID = tblL.Trans_ID " & _
" where gl.Debit_Credit < 0 AND Trans_Date > DateSerial(Year(Now()),1,1)  union " & _
" SELECT  Sum( tblM.Amount) as Spending, 'Medical' as Name from tblGeneral_Ledger  gl " & _
" inner join tblAccount_Medical as tblM on gl.Trans_ID = tblM.Trans_ID " & _
" where gl.Debit_Credit < 0 AND Trans_Date > DateSerial(Year(Now()),1,1) union " & _
" SELECT  Sum( tblP.Amount) as Spending, 'Personal' as Name from tblGeneral_Ledger  gl " & _
" inner join tblAccount_Personal as tblP on gl.Trans_ID = tblP.Trans_ID " & _
" where gl.Debit_Credit < 0 AND Trans_Date > DateSerial(Year(Now()),1,1) union " & _
" SELECT  Sum( tblU.Amount) as Spending, 'Utilities' as Name from tblGeneral_Ledger  gl " & _
" inner join tblAccount_Utilities as tblU on gl.Trans_ID = tblU.Trans_ID " & _
" where gl.Debit_Credit < 0 AND Trans_Date > DateSerial(Year(Now()),1,1)) order by Name"
objConnection.Execute uString

objConnection has been instantiated a little earlier in the script.
Should the Microsoft documentation be updated to reflect the error being returned by the Jet 12 engine or am I barking up the wrong tree?
Thanks in advance,
Harold
Comment: Format()? Make subqueries views to circumvent Error (Unions not allowed in a subquery)!
Comment: That is a possibility worth pursuing
Comment: Yep, that seems to be the only palatable way to do it. I can construct and execute pretty sophisticated unions and fairly nested joins against an Access database using the ucanaccess 4.0 library and in the Access Query design SQL window, But Access is a real weinie when it comes to creating views. Nested joins have to be broken down into a series of inter-dependent views Thanks for the direction
Answer: Have you run it with an alias after your subquery:
uString = "CREATE VIEW vwSpendingTotals (Spending, Name) as SELECT Spending, Name FROM " & _
" (SELECT  Sum( tblA.Amount) as Spending, 'Auto' as Name from tblGeneral_Ledger  gl " & _
" inner join tblAccount_AUTO as tblA on gl.Trans_ID = tblA.Trans_ID " & _
" where gl.Debit_Credit < 0 AND Trans_Date > DateSerial(Year(Now()),1,1)  Union " & _
" SELECT  Sum( tblH.Amount) as Spending, 'Household' as Name from tblGeneral_Ledger  gl " & _
" inner join tblAccount_Household as tblH on gl.Trans_ID = tblH.Trans_ID " & _
" where gl.Debit_Credit < 0 AND Trans_Date > DateSerial(Year(Now()),1,1) union " & _
" SELECT  Sum( tblL.Amount) as Spending, 'Living' as Name from tblGeneral_Ledger  gl " & _
" inner join tblAccount_Living as tblL on gl.Trans_ID = tblL.Trans_ID " & _
" where gl.Debit_Credit < 0 AND Trans_Date > DateSerial(Year(Now()),1,1)  union " & _
" SELECT  Sum( tblM.Amount) as Spending, 'Medical' as Name from tblGeneral_Ledger  gl " & _
" inner join tblAccount_Medical as tblM on gl.Trans_ID = tblM.Trans_ID " & _
" where gl.Debit_Credit < 0 AND Trans_Date > DateSerial(Year(Now()),1,1) union " & _
" SELECT  Sum( tblP.Amount) as Spending, 'Personal' as Name from tblGeneral_Ledger  gl " & _
" inner join tblAccount_Personal as tblP on gl.Trans_ID = tblP.Trans_ID " & _
" where gl.Debit_Credit < 0 AND Trans_Date > DateSerial(Year(Now()),1,1) union " & _
" SELECT  Sum( tblU.Amount) as Spending, 'Utilities' as Name from tblGeneral_Ledger  gl " & _
" inner join tblAccount_Utilities as tblU on gl.Trans_ID = tblU.Trans_ID " & _
" where gl.Debit_Credit < 0 AND Trans_Date > DateSerial(Year(Now()),1,1))a order by Name"
objConnection.Execute uString

Comment: As I understand the concept of a union, each subquery equates to a row in the result set and each subquery must contain the same number and names of columns. Aliasing the subqueries would be useful for a join statement but I am not sure how it would facilitate the union. The point is that in Access, in the query design, SQL view, I can enter all the above SQL and run and save the query (which is saved as a union) and query from that saved query (in reality a view) but the create view mechanism doesn't accommodate my wishes. Works in Oracle, SQLServer, etc. just not MS Access


How to be expressive?

Question: Joe Satriani said:

There are a lot of good guitarists out there. Their technique is great,
  their fingers stretch really wide and they can play really fast. But
  very few of them can be expressive and that is the most important
  thing.

I have a feeling that Joe said something very important here, please help me to understand what this is.
How can you define "playing expressively" in terms of music?
Are there any exercises, practices, songs, or principles that might help one to be "expressive"?
Answer: I'm a pianist, and the Joe citation can be applied to pianist too.
Playing the correct notes, or playing fast, or even playing wide intervals is relatively easy. After some time trying out you'll eventually get it right.
If you play the right notes or eventually miss one or two notes it does not matter. What really matters is the meaning you give to those notes.
And this is what means to play one instrument expressively.
Being expressive is being able to transmit a well defined mood(or many, but always well defined), to give a meaning to all the notes being played, to play consistently, to phrase correctly.
You should be able to make a listener feel the music and not just listen to it.
I guess the following pertinent questions are:
How do you do it? What should be taken into account?
Imagine you're studying a piece of music, you should first of all determine the voices and the phrases they're speaking, this is a good start. After knowing "who" is speaking, you have to determine "how" they'll speak.
I recommend watching videos of well known players and listening to their interpretation carefully, writing down the dynamics and articulation they're playing and ask yourself: "why are they playing it like that?".
http://en.wikipedia.org/wiki/Articulation_%28music%29
http://en.wikipedia.org/wiki/Dynamics_%28music%29
Pay very close attention to modulations, how they're introduced (are the softly introduced or are they very harsh and dissonant?)
And mark your conclusive cadences very well, it's very important to phrase correctly.
(As Chopin said to a student: "One who does not know how to phrase (musically) is like a person who can't speak her own language").
http://en.wikipedia.org/wiki/Phrase_%28music%29
The best way to learn it is to try it out, experiment, trial and error.
Get your guitar, play the song multiple times, with different approaches,
ask somebody to give you some feedback.
It's also highly advisable to read about music theory and musical interpretation.
Hope it helps.
Answer: He definitely said something important there.
Expressive playing in rock-like music styles does incorporate elements that a classical musician might also use, like dynamics and articulations, but it's actually much more, more about "having the blues". What that means is hard to define, so this is just my interpretation —
It means, for instance, bending notes to pitches that can't be exactly described in a score. It does, in fact, mean playing notes that you could not really define yourself: playing "from the heart" rather than from the mind. This may include notes that would classically be described as plainly wrong.So, in contrast to what Victor said, correct phrasing is not always necessary or even desirable – you do have to find the right balance, but technically perfect may be not musically ideal.
To give a concrete example: consider the guitar solo in Since I've Been Loving You, by Led Zeppelin. This is by no means a technically perfect performance, the fast passages are sort of huddled together rather than phrased out properly. But that just gives it this incredibly emotional, desperately screaming character: I consider it one of the best soloes of all time.
Of course, there are more nuances of expression than just blues, those are typically closer to the classical expressive elements. Still, expressive guitar playing has a lot to do with letting go of from-the-head control over what your hands are doing; so it is not much good trying to practise this type of expression with specific exercises, and most certainly not with any "principles". You rather just have to practise so well that you can stop thinking about what you actually are playing, so that you can start letting the emotions "float into the music". The best way to get there is probably: lots of improvisation, preferredly with a band. When practising alone, avoid playalongs, better just jam around on your own.
That said: all this does, of course, not mean you should abandon technique and discipline. Sometimes an "expressive" part simply will sound outrightly wrong, and what sounds amazing when played in some climatic solo may be rather annoying in other songs. Most often, you're on the safe side when going the classical way as described by Victor: subtle and conscious modifications of pitch, attack and articulation. These are best practised on actual romantic pieces played on classical guitar, which I would definitely recommend over practising any parts from songs on electric guitar.
By the way, "conscious" modification will not necessarily be subtle: a prime example for excessive and greatly effective use of such elements is Jaqueline du Pré's Elgar Cello Concert, which is at least as expressive as any blues guitar solo but still considered close to technical perfection.
Answer: If you consider music to be a language, then technical proficiency corresponds to rhetoric, grammar, and logic. But how well you speak is only important if you have something to say. Expressivity in music has more to do with the meaning you invest into each note than any transcribable detail of the notes themselves.
Consider a high-school student playing Polonius from Hamlet versus Bill Murray. The speech from Polonius to Laertes ("Remember, neither a borrower nor a lender be....") is about imparting all the wisdom of his entire life to his fledgling son in one condensed paragraph. Bill Murray layers this desire in every inflection, every pitch of his performance; investing the words with meaning. But the poor high-school kid, bless his heart, simply has no such wisdom to give; so he can merely speak the words.
So the question to ask when reviewing a performance is: what is that note doing there?
Answer: All these answers are great but I would like to add something.
To bring expressiveness you have to be extremely comfortable with your instrument and confident. The instrument should be part of your body, like an organ.
And the music piece you are trying to interpret should holds no surprises for you. For example you should be able to play it completely in your mind, you should be able to play it and your eyes are closed.
Personally, sometimes I play in the dark. This is useful for me.
Answer: Being able to express feeling through music is a combination of a wide range of factors, and none of them need to include technical ability.
Speed can be nice, but I can think of many fast guitarists whose technical ability is incredible, but who turn me off completely - there is no feeling to their music. Other guitarists, such as Dave Gilmour of Pink Floyd, don't play fast music but their note choice, bends, harmonics, timings (not always on the beat) and other factors provide expression.
Think about Kurt Cobain - looking at how he played, it is evident he wasn't a technical wizard on the guitar, but the way he played moved people.
Although I do like fast guitar (Vai, Satriani, di Meola etc are in my list of heroes) I far prefer to play solos that are full of feeling. They may have the odd fast bit, but our audiences seem to really like a solo that moves them, and changes with their mood.

How to be expressive?


If one group's mean differs from zero but the other does not, can we conclude that the groups are different?

Question: I have many pairs of measurements. A paired-samples t-test on these produces a 2-tailed p > .1 (so non-significant by typical alpha values).
When I run two separate one-sample t-tests comparing against some common null (say 0), one such test produces a p ~= .01 (therefore significant), while the other produces p ~= .6 (therefore non-significant).
The 95% confidence intervals of the two measurements overlap substantially. The non-significant measurement's 95CI additionally overlaps 0, whereas the significant measurement's 95CI does not overlap 0.
So whereas the pairwise differences between the measurements are too small to reach significance, one is significantly different from 0 overall while the other is not.
There seems to be a logical contradiction between saying that the two measurements do not differ, when they differ in their proximity to a common value.
Comment: I am also interested in whether one or other of the approaches in my question is [in]valid for the problem at hand, and if they are both valid (while permitting different interpretations) what difference this makes for 'decision behaviour'. I often see the 'double t-test' approach deployed when the pairwise test fails to reach significance. People talk up their understanding of the conceptual difference yet go on to treat the latter result essentially as if the former (pairwise result) had worked. Hope that makes sense
Answer: There is no contradiction, because The Difference Between "Significant" and "Not Significant" is not Itself Statistically Significant (Gelman & Stern, The American Statistician, 2006). Gelman posted a PDF version of the article here.
Comment: +1. See also http://www.nature.com/neuro/journal/v14/n9/abs/nn.2886.html.
Comment: Thank you both for the links, they look insightful. I may post a follow-up question asking whether any test exists which jointly compares two groups and a common reference value, so as to avoid computing two separate tests against the value and then erroneously comparing the tests' significances.
Comment: I'm looking forward to that follow-up question (best to link the two questions together explicitly). You'll need to be specific as to which alternative hypothesis you'd be testing: that *either* or *both* groups differ from the reference.


Options to concatenate strings in std::string

Question: I have a requirement to concatenate multiple small strings into an std::string in an efficient manner.
Let's say there are five strings abc, def, ghi, lmn and pqr. These need to be concatenated thus: /abc/def/ghi/lmn/pqr
The strings would be received in the order opposite to their final positions in the concatenated string: pqr, lmn, ghi, def and abc.
To make this operation efficient, I use the reserve() API of std::string since I know the sizes of all the strings.
Given all this, which of the two is efficient:

Use a stack to store the strings and concatenate them by popping one by one.
Use insert() API of std::string to move the rest of the string to accommodate the new string at the beginning.

Please note that the number of strings to be concatenated can be up to two thousand.
Comment: Why don't you just implement both methods and profile them?
Comment: Have a look at http://www.cplusplus.com/reference/sstream/stringstream/. It overloads the "<<" operator. In terms of performance: Be careful about premature optimizations. Implement and profile. Reimplement when in doubt.
Comment: Method 1 if implemented properly should at least be not slower than method 2
Comment: @mutex36 recommending `std::stream` for efficiency, are you in your mind? Why OP needs << if `std::string::operator +=` is sufficient in this case?
Comment: Question unclear: "The strings would be received in the opposite order" / "  I know the sizes of all the strings.". Either you have all the strings, and then you can walk through them in either order, or you receive them sequentially and do _not_ know all sizes.
Comment: Missing option: reverse each string as it arrives, append, reverse result. I.e. receive `pqr`, store `rqp`. Receive `lmn`, append `\nml` to get `rqp\nml` etc.
Answer: Just out of curiosity wrote this program to see the running time of various methods for this on Debian. To add 100,000 words in reverse order
stack is the best option among these
// concatenate by + operator
real    0m2.286s
user    0m2.268s
sys     0m0.016s

// concatenate by insert
real    0m0.695s
user    0m0.692s
sys     0m0.000s

// concatenate by stack
real    0m0.051s
user    0m0.044s
sys     0m0.004s

#include <cstdio>
#include <iostream>
#include <string>
#include <random>
#include <algorithm>
#include <stack>

using namespace std;

int main() {
  random_device dev;
  mt19937 gen(dev());
  string chars = "abcdefghijklmnopqrstuvwxyz";
  uniform_int_distribution<> dis_index(0, chars.size()-1);
  int size = 3; // word size
  int count = 100000; // 100K words
  string out; // final string
  stack<string> st;

  int i = 0;
  while (i < count) {
    // create a random word of length = size
    string s;
    generate_n(back_inserter(s), size, [&](){return chars[dis_index(gen)];});
    //cout << s << endl;

    // concatenate by + operator
    // out = s + out;

    // concatenate by insert
    // out.insert(0, s);

    // concatenate by stack
    st.push(s);

    ++i;
  }
  while (!st.empty()) {
    out += st.top();
    st.pop();
  }
  //cout << out << endl;
}

Comment: I wrote my own sample code, and found the stack approach to be slightly better for my use cases.


categorical data: design of the analysis

Question: There is a dataset of about 8500 different kinds of mushrooms, each datapoint has about 20 features. The features are purely categorical: color of the cap, its shape and so on. None of them are ordered. For every datapoint it is known if the mushroom is poisonous or not. My task is to determine which features distinguish the edible mushrooms from the non-edible ones.
My knowledge of statistics is limited, I have read the following example on analysing categorical data. Following that example, my intent is to do the following:

For every feature, perform a $2 \times 2$-table Chi-square test to understand if there is any kind of an association.
For every feature with an association, compute and odds ratio to see if the association is significant or not.

My concern is that I will be treating each feature separately. So, I will have about 20 separate experiments. Maybe, I am missing some statistical test which would take into account the fact that there are many (not just one) categorical features which determine if the mushroom is edible or not.
Comment: How much data do you have? How many parameters need to be estimated when you sum the number of levels for each categorical feature?
Comment: @gung there are 8416 datapoints and if I sum the number of all the distinct levels of all the categorical features, I get 119.
Answer: Since your outcome is categorical, I think that this case calls for a logistic regression. Since your predictors are also categorical, as far as I know, they should be coded, using dummy variables. See more details on dummy coding (in R) on this page and on logistic regression on this website.
Now, a couple of notes about performing logistic regression, using different statistical languages and environments. Since logistic regression is a part of generalized linear models (GLM) family, if you use R, you can use glm() function for the analysis: http://data.princeton.edu/R/glms.html. If you use SAS, you can use LOGISTIC procedure. If you use SPSS, this tutorial might be helpful.


How to interpret r's output for a multiple linear regression model

Question: Context: Two properties that may influence the pull strength of a wire bond in a semiconductor
manufacturing process are the wire length and the die height. A scatterplot matrix of the pull strengths, wire lengths and die heights is given below:

A multiple linear regression model fit to these data is summarised in the computer output:

I know how to interpret the intercept, but not sure about the rest.  Like what is the length and the height estimate means (2.744 and 0.013). Are these the slopes? How do you interpret slope when I have two predictors? Is this interpretation correct: A unit increase in length is associated with a 2.744 unit increase in strength for some fixed height? Like I don't know how to interpret the second predictor when talking about the slope of the first predictor.
Many thanks.
Answer: Here is your regression equation: $
\hat y = \hat\beta_0 + \hat\beta_{L} x_{L} + \hat\beta_{H} x_{H}
$.
Let's look at the partial derivatives.
$$
\dfrac{\partial \hat y}{\partial x_{L}}
=
\hat\beta_{L}\\
\dfrac{\partial \hat y}{\partial x_{H}}
=
\hat\beta_{H}
$$
Therefore, in the equation that lacks interactions and high-order terms (quadratic, etc), the slope coefficients are the partial derivatives.
Partial derivatives mean that, holding all other variables constant, the slope in the direction of the denominator variable is the value of the partial derivative. Since these partial derivatives are constants, then we can interpret the regression to mean that, holding height constant, increasing length by $1$ results in a change in $\hat y$ of $\hat\beta_{L}$; and, holding length constant, increasing height by $1$ results in a change in $\hat y$ of $\hat\beta_{H}$.
Comment: Hi Dave, thanks for that,. So I can only interpret the a slope when the other slope is held constant? Also what about the residuals. any comments? Many thanks Dave.
Comment: @CountDOOKU You can do any of the tricks that you would do in multivariable calculus. You can take gradients and directional derivatives, for instance. // I do not follow what you mean about the residuals, but if you have a new question, please post it as a new question.


Why is multilinear PCA rarely used for nonlinear dimensionality reduction, compared to, say, t-SNE?

Question: I'm only starting to understand some of the subtleties that arise when choosing one dimensionality reduction technique over another. Now I'm wondering why it seems that in recent years, one of the more popular methods for nonlinear dimensionality reduction was/is t-SNE, while multilinear Principal Component Analysis seems to be rarely used -- at least in the literature I look at, machine learning, and usually for the purpose of visualization of high-dimensional data.
Could someone comment on what might be the reason for this (unless of course my assumption is wrong to begin with)? In particular, it seems that (linear) PCA has a number of advantages over t-SNE (e.g. learning a function that can be applied to new data, 'preservation' of global structure), so I am wondering whether these advantages are also present in multilinear PCA. If so, I wonder why MPCA doesn't seem to be used that commonly.
Related to the question above: I recently read about Isomap, which by my (very incomplete understanding) looks like it should be another useful nonlinear method for interpreting high-dimensional data. In that case, what would be the distinguishing features between t-SNE, MPCA and Isomap?
Comment: Do you mean this https://en.wikipedia.org/wiki/Multilinear_principal_component_analysis ? What relationship does this have to t-SNE? MPCA is a *linear* method of dimensionality reduction of "multi-way" tensors. T-SNE is a *nonlinear* method for dimensionality reduction of usual matrices. They have completely different scope.
Comment: @amoeba I see, thank you very much for clearing this up. The patience of contributors on this site with imbeciles like me and the questions they ask is admirable.
Answer: As you can see in this paper: http://jmlr.org/papers/volume9/vandermaaten08a/vandermaaten08a.pdf
Isomap is not as good in separation (in that specific type of cases) as t-SNE.
And here is MPCA against t-SNE: http://journals.plos.org/plosone/article/file?id=10.1371/journal.pone.0056883&type=printable
t-SNE seems to produce the best results for visualisation in 2D. Visualisation is often the ultimate purpose of any data-analysis, so t-SNE is the best method of these three (for these particular cases and applications). It is though to be understood that t-SNE may fail in other cases, but in those cases and the purpose of 2D visualisation for clustering it performs well.
Comment: Thanks. I skimmed the van der Maaten/Hinton one before but didn't notice they cover Isomap. One question though: I want to visualize/interpret the global structure as much as that is  possible. So t-SNE performing better at clustering the different classes (and avoiding the crowding problem) is definitely useful, but I shouldn't draw too many conclusions from the organization of the clusters in relation to each other, right? Put differently: if the goal is less aiming for (optimal) local clustering, and more about interpretable differences on a larger scale, is t-SNE still the right choice?
Comment: Not necessarily. You should **always** play with the data. You take a sample of data and apply some methods. Each of the methods have their own advantage, often by design. t-SNE is the right choice only if it works, if not choose an another method. This is why there is so many methods in use. PCA-type of methods have those principal components that can make sense as themselves. It is not only Euclidean distance that can be used. While people live in Euclidean space it can be nonsensical; especially the distance of binary-vectors as Euclidean rarely makes sense.


Python: Nested Class Inheritance

Question: Would it be OK to declare an instance of the sub-classed class from its Base (super?) class as I do it here:
if 'classB_args' in dictArg.keys() and dictArg['classB_args']:
    self['classB']=ClassA( dictArg['classB_args'] )

Are there any side effects of doing so? What should I be aware before moving forward. I have a feeling sooner or later something would go wrong... with cPickle , pickle or may be it would be a PyQt drag-and-dropt?.. if so then why would the problem arise?
class Base(dict):
    def __init__(self, *args, **kwargs):
        super(Base, self).__init__(*args, **kwargs)
        self.setdefault('id', -1)
        self.setdefault('name', None)
        self.setdefault('classB', None)

        if not args or len(args)==0: return
        dictArg=args[0]

        if 'classB_args' in dictArg.keys() and dictArg['classB_args']:
            self['classB']=ClassA( dictArg['classB_args'] )

    def getClassB(self):
        return self['classB']

class ClassA(Base):
    def __init__(self, *args, **kwargs):
        if not (args or kwargs):   raise Exception('you need to give me *something*!')
        super(ClassA, self).__init__(*args, **kwargs)
        self.setdefault('win', None)
        self.setdefault('mac', None)

myDictArg= {'id':1, 'name':'MyName', 'win':'c:/windows', 'mac': '/Volumes/mac/', 'classB_args': {'id':1, 'name':'MyProject'}}

myInstance=ClassA(myDictArg)
print myInstance.getClassB()

Comment: [XY Problem](http://meta.stackexchange.com/a/66378/174568)...
Comment: There are no nested classes in your code, so the title of your question is misleading.
Answer: If you're asking whether it will work, the answer is yes, but I can't think of a situation where it is a good idea.  The reason is that this locks your base class down to being really only useful with ClassA ... I think that the solution would probably be cleaner to do something like:
myDictArg = {'id':1, 'name':'MyName', 'win':'c:/windows', 'mac': '/Volumes/mac/', 'classB': ClassA(id=1, name='MyProject')}

and forgo all of the extra classB_args craziness in Base.__init__.  It's more explicit so the user ends up knowing what to expect.
If you really don't like that, you could use the type of self to determine what to use rather than specifying ClassA directly which is a little better:
self['classB'] = type(self)(dictArg['classB_args'])

Now, if you derive a new class from Base, that will be used instead:
class Foo(Base): pass

instance = Foo(myDictArg)
print type(instance.getClassB())  # Foo !

a few other non-related points.

Don't do x in dct.keys() -- It's horribly inefficient in python2.x.  You can just do x in dct :-).
Generally speaking, writing simple wrappers like getClassB are considered "unpythonic".  You can just access the data directly in python.
You can rewrite the if clause to clean it up a little:

Here's how:
   if 'classB_args' in dictArg.keys() and dictArg['classB_args']:
        self['classB']=ClassA( dictArg['classB_args'] )

goes to:
   # with this, you can remove the `self.setdefault('classB', None)` statement.
   item = dictArg.get('classB_args')
   self['classB'] = type(self)(item) if item else item

Comment: Thanks for the terrific info!
Comment: After testing it unfortunately remains unclear to me a syntax and a purpose of type(self)(item). Would you please clarify what it is.... Thanks in advance!
Comment: `type(self)` returns the class associated with the instance.  So, for example, if you call this using subclass `classA()`, `type(self)` will be `classA`.  if you make another subclass of `Base` `ClassB` (e.g. `class ClassB(Base): ...`), then `type(self)` will be `ClassB`.
Comment: but you use it like: type(self)(item)  ...... why is there (item) that follows after type(self)?...here is your code................. type(self)(item) if item else item
Comment: `type(self)` is the class -- I'm creating an instance of that class with `type(self)(item)`.  You do the same in your code except you have  `ClassA( dictArg['classB_args'] )`.  I hope you see the parallels -- `ClassA` -> `type(self)`, `dictArg['classB_args']` -> `item`.
Comment: I would appreciate if you post an entire code with this type(self)(arg) trick implemented and working. All my attempts to run it unfortunately failed with some massive errors.

Python: Nested Class Inheritance


Qual a forma correta de montar interfaces em páginas PHP?

Question: Em vários projetos que vi por ai, em que são necessárias consultas a bancos de dados para conseguir informação, e posteriormente montar tabelas, notei a seguinte abordagem apresentada no trecho de código abaixo:
<?php
    while($row = mysql_fetch_array($res)) {
?>

        <?php echo $row['nome']; ?>
        <?php echo $row['idade']; ?>
        <?php echo $row['dia']; ?>
        <?php echo $row['turno']; ?>

<?php
    }
?>

Nela, a pessoa abre diversas vezes <?php ?> para extrair informações do banco, e montar a página.
Isso não me parece correto, não seria melhor usar javascript(ajax) para recuperar informação, e depois DOM para montar a página?
Minha dúvida é qual seria a melhor maneira de construir páginas em que é necessário fazer consultas a bancos de dados para obter informação.
Comment: @GaMen e por que o código apresentado seria má prática? Não tem nada errado. Exceto quanto ao uso da função mysql_* : http://pt.stackoverflow.com/questions/579
Comment: A tua pergunta, apesar de interessante, é baseada em opiniões. Por exemplo, como sou desenvolvedor PHP eu defenderia o PHP, o mesmo com JS, AJAX e tal. Não existe resposta certa, somente opiniões.
Comment: Não da pra considerar errado, com ajax é mais bonito, fluido e rápido, mas com um loop do php é mais simples de se executar.
Comment: @ThiagoSantos Não seria considerado uma má prática utilizar o PHP dessa forma?
Comment: Não é nem questão de gosto, é dependente do alvo do projeto.
Montar os dados por JavaScript traz complicações para SEO. Se o projeto necessita de compatibilidade para SEO, é uma roubada montar o conteúdo pelo JavaScript / DOM. Não tem uma forma "mais correta". Tem aquilo que é mais adequado para o projeto com o qual se trabalha.
Comment: @DanielCosta Realmente, utilizando Ajax seria um pouco mais complicado, só quero confirmar se fazer dessa forma com PHP não é considerado uma má prática.
Comment: Me parece que na verdade o grande problema da pergunta é que ela é ampla ou talvez não clara, e por isso indica ser ampla. Abrir o PHP várias vezes não é um grande problema, é assim que é feito mesmo. Tem como fazer diferente, mas muda muito pouco. Usar AJAX pode ser mais interessante mesmo, em muitos casos, mas não em todos. Mas se não souber como fazer direito pode ser pior. Não parece que tenha um problema específico que queira resolver aqui.
Comment: @DanielOmine Sim, a função mysql_* foi só pra ilustrar, imagina que eu usei PDO no exemplo. Eu não sou muito experiente com PHP, e isso de abrir várias vezes  me pareceu errado, por isso a pergunta.
Comment: @bigown Não sou muito experiente com PHP, eu só queria saber mesmo se isso era errado e se não tinha uma maneira melhor de resolver o problema.
Comment: Não tem nada errado em abrir e fechar as tags. Isso até facilita para evitar misturar com HTML. No exemplo da pergunta está muito simples, mas se vc coloca outros elementos como imagens, textos, javascript, css, aí fica complicado pois precisa escapar caracteres especiais. Fica um código mais "sujinho".
Comment: @DanielOmine Sim, achei que o código fica meio bagunçado fazendo dessa forma. Principalmente na parte em que a chave do `while` é aberta numa tag `` e depois fechada em outra. Mas já que não é errado fazer isso, vou utilizar menos DOM nos meu códigos. Muito obrigado!
Comment: o que eu disse é que fica mais organizado mesmo com muitos elementos.  E que de outra forma é que fica bagunçado..
Comment: @GaMem tenha em mente que mesmo com PHP existe várias formas de se trabalhar. Se você preza por um código organizado pode tranquilamente adotar um template engine e aplicar MVC. Dá para carregar previamente todos os dados antes de montar a página HTML. Tudo depende do que você quer, PHP é conhecido pela sua extrema flexibilidade.
Comment: @AdrianoLuz Vou pesquisar mais sobre isso, obrigado. Fiz essa pergunta, por que fazer coisas como `Link` me pareciam bem erradas.
Comment: @DanielOmine Ah sim, te entendi mal. Mas não acho muito agradável de se ver de qualquer forma. Muito obrigado por se dispor a ajudar.
Comment: @GaMen em vez de utilizar `` pode utilizar ``
Comment: Não tem nada de errado, mas muita gente chama a esse método de código esparguete, apesar do código ser fácil de compreender e de criar no inicio, a logo prazo é uma dor de cabeça de manter.
Answer: Não tem nada de errado em abrir e fechar as tags para compor o conteúdo do HTML.
Tudo que está delimitado pela tag do PHP é parseado pelo compilador do PHP.
Se você passa coisas não referentes ao PHP, isso tem um custo a mais para o compilador processar os dados.
Vejamos um exemplo:
echo '

'.$variavel.'

';

Aqui nesse exemplo, o PHP vai apenas "cuspir" de volta o trecho estático

 e

.
Ou seja, enviou para o compilador processar um texto que não tem o que ser processado. É uma informação estática. O PHP teve que ler essa informação, aumentando o consumo de memória e processamento.
De outro modo,

<?php echo $variavel;?>

O compilador vai receber apenas o trecho $variavel;.
O que seria uma prática ruim, é algo assim
<?php
echo $variavel;
?>
<?php
echo $outra_variavel;

function alguma_coisa() {
    return null;
}

echo alguma_coisa();
?>

Aqui nesse caso sim, temos até um problema pois fechou e abriu desnecessariamente pois o código seguinte é também PHP. Poderia apenas continuar na mesma tag
<?php
echo $variavel;

echo $outra_variavel;

function alguma_coisa() {
    return null;
}

echo alguma_coisa();
?>

Além disso, ao fazer
?>
<?php

Está gerando um output que normalmente é a causa comum entre novatos com o famoso "header already sent". Mas não vou entrar nesse assunto pois é mais extenso e desvia do foco da questão.
Escapando aspas
Uma dificuldade quando passa tudo pelo PHP é ter que escapar caracteres:
echo '
texto com aspa simples \''.$variavel.'
';

Pode-se resolver usando aspa dupla
echo "
texto com aspa simples '".$variavel."
";

Mas isso depende muito também do padrão de código do projeto. Particularmente utilizo aspa simples e há quem prefira aspa dupla. Isso é questão de opinião e um tanto polêmico. No entanto, mesmo com aspa dupla cai na mesma cilada quando o texto estático possui aspa dupla. É preciso fazer o escape:
echo "
texto com aspa dupla \"".$variavel."
";

Até aqui são exemplos muito simples. Na vida real você vai ter coisas assim
lorem ipsum single quot'e double "quote"

<?php echo $variavel_do_php;?>

Isso aqui ainda é um nível bem criança... mas é apenas para ilustrar
Veja como fica de outra forma:
echo '
lorem ipsum single quot\'e double "quote"

'.$variavel_do_php.'
';

Diz aí qual dos dois é melhor para leitura de código?
Em termos de performance não fazem diferença. Por isso eu normalmente opto pelo que é mais simples e legível e, lógico, tudo depende da finalidade de uso e isso é o que mais importa.
JavaScript Template
Quanto ao uso de JavaScript para montar a view, deve-se avaliar os requisitos do projeto. Se é um projeto web, normalmente um website tem que ser compatível com SEO. Se montar as páginas via JavaScript terá problemas com SEO pois os mecanismos de busca não interpretam o JavaScript.
O esquema de montagem do layout com JavaScript foi muito usado no passado antes da "Era Google". Era muito comum os sites montarem o conteúdo das páginas com JavaScript pois reduz bastante o código HTML. Infelizmente todos foram forçados a aumentar conteúdo redundante nas páginas devido ao SEO.
Atualmente é usado mais para projetos privados, intranets ou mesmo websites que não se importam com SEO.
MVC
Se analisar o código da pergunta para um projeto em MVC, podemos sim dizer que não é uma boa prática pois no MVC normalmente não invoca funções do PHP diretamente na View. É normalmente usando um template engine, helpers, etc.
Resumindo
Destaquei apenas pontos óbvios. E ainda há muitos outros pontos para mencionar mas isso torna o assunto extenso demais.
No geral, evite pensar em "o que é o melhor para X ou Y?". Enxergue essa pergunta como "o que é mais adequado para o projeto X ou situação Y?". Pois não existe algo que seja "a solução universal". Existem soluções diversas que se adequam melhor para uma determinada situação.
Minimizando a sujeira visual
Para quem se incomoda com o uso de <?php echo $variavel;?>, é possível reduzir usando short tag.
O equivalente a isso <?php echo $variavel;?> pode ser escrito como <?=$variavel;?>
Lembrando que houve uma época em que cogitou-se a eliminação da short tag. Nessa época, por precaução, eu parei de usar. Um tempo depois voltaram atrás e decidiram manter mas mesmo assim continuo evitando o uso por precaução. Mas isso é escolha pessoal. Não quero dizer que deve pensar igual.
O uso de <?php é recomendado para evitar confusão com documentos XML que também usam <? como tag.
<?xml version="1.0" encoding="UTF-8"?>
<note>
  <to>Tove</to>
  ....


Electrical networks, calculating voltage of a vertex

Question: Given a finite graph $G$, and three vertices $v,s,t$, I am wondering about the probability that simple random walk starting at $v$ will reach $s$ before it reaches $t$. I know this is equal to $\phi(v)$, where $\phi$ is the unique harmonic function on $G$ with boundary $\{s,t\}$ such that $\phi(s) = 1,\phi(t) = 0$. Alternatively, if treat $G$ as an electric network, where current flows into $s$ and out from $t$, we get that $\phi(v)$ is the voltage at $v$.
Is a way to interpret $\phi(v)$ in terms of spanning tree counts? In practice, what are efficient ways to calculate/approximate $\phi(v)$ with a program?
Answer: Let $G*$ denote $G$ with an additional edge $e$ connecting $s$ to $t$.  Denote by $A$ the collection of spanning trees in $G*$ that contain $e$. Then the voltage $\phi(v)$ is the fraction of  trees in $A$ that contain a path from $v$ to $s$ that does not include $e$. This follows from the property of the uniform spanning tree in $G$ with $s,t$ identified,  that the random path from $v$ to the conjoined vertex $\{s,t\}$ in the tree is obtained by a loop-erased walk; This result is due to Pemantle, extended by Wilson; see an exposition and detailed references in Chapter 4 of [1].
Let $n$  denote the number of vertices in $G$. While $\phi(v)$ can be estimated via random sampling, and also by relaxation methods the most efficient methods rely on $\phi(\cdot)$ being the unique solution of $n-2$ equations in $n-2$ unknowns. These equations reflect the harmonicity of $\phi$ at all nodes different from $s,t$. There are many linear systems solvers available online. The equations that arise here have a special nature, they are often sparse and specialized algorithms have been developed for them.
See e.g. [2] for a masterful 2010 survey and [3] for a more recent algorithm.
[1] Lyons, Russell, and Yuval Peres. Probability on trees and networks. Vol. 42. Cambridge University Press, 2017. Available from
https://rdlyons.pages.iu.edu/prbtree/
[2] Spielman, Daniel A. "Algorithms, graph theory, and linear equations in Laplacian matrices." In Proceedings of the International Congress of Mathematicians 2010 (ICM 2010) (In 4 Volumes) Vol. I: Plenary Lectures and Ceremonies Vols. II–IV: Invited Lectures, pp. 2698-2722. 2010.
[3] Kyng, R., Lee, Y.T., Peng, R., Sachdeva, S. and Spielman, D.A., 2016, June. Sparsified cholesky and multigrid solvers for connection laplacians. In Proceedings of the forty-eighth annual ACM symposium on Theory of Computing (pp. 842-850).


Best Practice of Extending Another's Theme?

Question: I have a standard theme developed by others that I would like to add a custom view template to.
Is it OK to just create a new "views-view-table--MYVIEWNAME.tpl.php" file in the theme directory itself?
Or, is there a way to create a "sub-theme" for my stuff that inherits everything from the original theme?
Thanks. Bill
Comment: Is the theme a custom theme developed for that website or is it a theme from drupal.org or some other paid theme or something?
Comment: A custom theme from our headquarters.
Answer: This is partly up to developer preference and specific use case but generally, if it is a custom theme, as in this case, you would add templates and modify css/template.php/etc. in the custom theme you already have.
If it is a theme from drupal.org or some other theme source, where updates for that theme may come in future, then it is best to create a sub theme of that theme (which you can do even if that theme is already a sub theme of another theme).
Comment: Thanks, I checked with the original theme developer and they basically said "go ahead and start with adding custom template files to our theme, then when you get comfortable with how it all works, migrate to a sub-theme."
Answer: Templates are used by a theme on a most-granular-first basis.
This means that the system looks for something that is very specific to what is being rendered and then moves up the tree looking at more and more general options until it finds one that matches.
So a custom views-view-table--MYVIEWNAME.tpl.php file won't cause the standard views-view-table.tpl.php file to fail for other views with different names because they won't match that template file.
You can even make it more specific by name the display as well as the view if you have more than one display in your view.


Trocar endereço padrão utilizado pelo Docker (172.17.0.1)

Question: Eu gostaria de trocar (ou remover) o endereço 172.17.0.1 utilizado pelas redes do docker, tem como fazer isso?
Eu utilizo docker para desenvolvimento php e tenho um repositório remoto (git) configurado através de uma VPN utilizando a faixa de IP 172.17.X.X.
Sempre que meus containers estão up, a rede do docker utiliza essa faixa de IP e eu fico impossibilitado de fazer qualquer requisição ao repositório remoto.
Obrigado.
OBS: Eu utilizo um ambiente Linux (Mint 19)

Consegui resolver meu problema, definindo uma subnet na rede utilizada pelos meus containers no arquivo docker-compose.yml. Dessa forma:

networks:
  frontend:
    driver: bridge
    ipam:
      config:
        - subnet: 172.18.0.0/16
  backend:
    driver: bridge
    ipam:
      config:
        - subnet: 172.19.0.0/16
Answer: As configurações da rede padrão (bridge ) do Docker podem ser alteradas editando o arquivo daemon.json, no diretório /etc/docker/. Segue um exemplo do arquivo daemon.json:
 {
  "bip": "192.168.1.5/24",
  "fixed-cidr": "192.168.1.5/25",
  "fixed-cidr-v6": "2001:db8::/64",
  "mtu": 1500,
  "default-gateway": "10.20.1.1",
  "default-gateway-v6": "2001:db8:abcd::89",
  "dns": ["10.20.1.2","10.20.1.3"]
}

Uma opção seria configurar uma nova rede, usando o docker network create ...
Na documentação você ver mais informações, sobre os drivers de rede disponíveis, como configurar uma nova rede e como alterar as configurações de bridge padrão.
Comment: Eu já havia incluído nesse arquivo uma configuração para a rede bridge começar pelo 172.30.0.1 (coloquei apenas a opção bip). Será que eu tenho que especificar todas as opções que são indicadas na doc? Obrigado
Comment: O seu `daemon.json` tá igual esse da documentação?
Comment: Não. Está um json com a opção bip apenas.
Comment: Eu não entendi se o gateway e se o dns devem ser definidos com base na minha rede real ou deixar esses valores padrões mesmo. Por isso deixei só a opção bep
Comment: Na doc fala que você edita apenas o que for customizar (*Only specify the settings you need to customize.*), pode deixar o seu `daemon` só o `bip` mesmo. Reiniciou o *Docker* depois que fez as alterações?
Comment: Sim. Reiniciei sim
Comment: Então.. eu recomendaria você configurar uma nova `bridge` e adicionar no `daemon.json`(`{"bridge" : "minha_rede"}`)  , normalmente só com isso já era pra ter dado certo.


If a sequence is increasing and has a Cauchy subsequence, is the original sequence Cauchy?

Question: I am having difficulty answering whether an increasing sequence with a Cauchy subsequence  implies that the original sequence is Cauchy, and how I would go about showing that using some key analysis theorems and logic.
Answer: Hint: By relating the general indices and the indices of the subsequence, try to bind the distance between an arbitrary term and a term of the Cauchy subsequence.
Answer: HINT: You know that the Cauchy subsequence converges; let $a$ be its limit.

Show that $a$ is an upper bound for the original sequence. (This is not strictly speaking necessary, but doing it may give you a better feel for what's going on.)
Show that the original sequence converges to $a$. Then use the fact that every convergent sequence is Cauchy.


How to communicate between the different pieces when using MVVM in iOS

Question: I did my research but because I don't have enough experience I don't know what is the best way to implement communication of the UserManger class when using MVVM design pattern.
So my timer app that got sync to the Cloud.
So far I'm having HomeViewController, TimerViewModel, TimerModel, UserManager.
The UserManager object is taking care of authenticating User and also of communicating the authentication state to other classes.
The states are:
.notSigned, .signing and .signed
Here I would need more explanation. To which object should the UserManager communicate the updated authentication state? Is it owned by the view controller or view model?
And another question. I don't know if UserManager suppose to communicate only to one class or is it ok to talk to many objects at the same time.
I think that most of the objects simultaneously need to know if the user is signed or not. If this is true, what kind of communication do I implement?
For one to many, I'm thinking to implement the Observable protocol described in this article. If necessary I can copy the code  instead of the article link.
I hope I described it well. I will appreciate any kind of answer. Or any new insights, big picture ideas about how to set up object communication throught the app. Do you know any good article about that?
Answer: All the business logic should be inside the ViewModel. The ViewModel should be the thing that invokes any method inside the UserManager. The UserManager should return the result parsed as the Model to the ViewModel. The ViewModel then needs to format the data and alert the ViewController to the event/data/network completion etc.

Examples of formatting the data:

Lets say a networking request gives you firstName and lastName. But you only have 1 label to display the full thing. The viewModel should add those strings together (with a space) and provide a fullName property to the VC.
If you got back a Double, but need to format it into currency and display a symbol.
Taking a timestamp and formatting to a date string.

These are the kinds of things that a ViewModel should do. So that they can be tested independently of the UI code and lifecycle.

Communication:
You can use the standard Apple API designs and create a ViewModel protocol, with a delegate and a callback. Each VM would confirm to the protocol, VC would set itself as the delegate of its VM and run your code inside the VC's delegate callback function.

Naming:
The word "Manager" has fallen out of favour because it is typically a default word used when the use of the class is unclear. For this reason it has a thousand different definitions. A class responsible for making networking requests and/or storing state should be called a "Service". i.e. "UserService".

Sharing state:
I'm probably going to make a lot of people angry with this one. But when state needs to be shared across multiple VC's, components, VM's etc. I follow the design patterns / architecture that Angular has setup. I make my service classes singletons. Have them store the state. Then Each ViewModel has one source of truth for each item and can format it at will.
Other people use frameworks such as RxSwift and use Observables and similar technologies. My personal opinion is that this is tremendous overkill, involves a huge learning curve, means adding a lot of big libraries and brings in a lot of risk to the project. I prefer to stick to the patterns already available and working in the eco-system and keep things simple.

Edit: one-to-many:
It can depend on your use case and architecture decisions. I've found it possible to avoid the one-to-many issue in the majority of my uses cases, by having the singleton store the state and have the VC trigger something in the ViewModel on each call to viewDidAppear. Each time the VC opened, it got the latest data and continued on. The reason I bring up avoiding the one-to-many is that in the majority of cases there is only 1 VC on screen and running code at any point in time (using childViewControllers is the exception). I've found it possible to just side step this issue entirely and keep the apps simple by changing how I interact with the data, rather than changing the structure of Apples APIs.
Now depending on your use case, this might not work if you have multiple timers and lots of screen switching, there could be a chance to miss an event.
NotificationCenter is not my favourite approach, but if I had a one-to-many situation I couldn't avoid, I would give it a go. As mentioned in the article there are some downsides with swift features you can access through this means. It at least has the added benefit of being something thats been around for a long time and is well understood and unlikely to change much. There won't be any huge learning curve if other developers are working on this app.
The other approach mentioned in the article is interesting, building your own stripped down version of RxSwift to add Observers into the project. My problem at the minute with RxSwift is when people don't use it in conjunction with singletons or some sort of central point of control. When you have an Observable on object A, Observed by B that also has another Observable Observed by C, which calls a function on D which is Observed by E, F and G .... and so on. This style of code is incredibly messy, hard to read, error prone and difficult to debug. So long as that is avoided and its the singleton that has the observable and all the ViewModels are observing, I think something like that would be ok if you are willing to put the effort in to build and maintain it.
Comment: Great explanation and I find it very useful. Only for the last paragraph, I would like to know more about how singleton notifies other view models. Looks like its one-to-many? As far as I know, delegates are only one to one, by default. Do you use notification center, or what?
Comment: @KlemenZagar I edited the question as my reply was too long