Restrict what content can be added to a panel page (using panels & organic groups)

Question: We are using Organic groups and Panels with Drupal 7.
We want each group to have one panel node (that is, a node which content type is "Panel"). The group administrator can then use different kind of layouts and display existing content.
I created two groups A and B. I also created panel node (a node which content type is "Panel") for each group and some nodes that belong to group A and some nodes that belong to group B
Now, when admin of group A edits the panel node's content (through a tab "Panel content") of group A and selects Existing node when adding content to a panel pane, he can choose nodes that belong to group B. Is there a way to make panels respect OG access control? So that group A admin could not select contents of group B to be displayed in a panel pane of group A.
The content in the groups still need to be public so that if anonymous user visits content belonging to each group he will be able to see them.
Answer: I guess that by:

when admin of group A edits the panel page

you mean edit the group's node that is being viewed through a panel,and not that he can edit the panel's settings,
and when you're saying

selects Existing node when adding content to a panel pane

you mean that selects content through field (entity-reference). That said, you don't need to make panels respect OG permissions -I am not sure if that's possible- but to filter out the content showing in that field based on Group A or B. To achieve that you may use field_get_items, see the contents of the field and check which node belongs to which group (every node belonging to a group has a Group id (gid) by that gid you can node_load the group node and access its fields) and configure set/unset the field's values accordingly or even you may use hook_form_alter to do so.
Comment: Thank you for your answer but that was not quite what I meant. By "when admin of group A edits the panel page" I mean modifying a node, which content type is panel and which has for example tabs "view", "edit", "panel layout" and "panel content". And modifying here happens by using the "panel content tab" to add existing nodes to be shown when this panel node is viewed.  I also tried to clarify my original question.


Como adicionar novos encodings em python?

Question: Estou tentando instalar o pybraces mas não consigo.
Como faço para instalar-lo ?
Estou usando python 2.7 e windows 10
Answer: você não deveria instalar o "pybraces" - se quer aprender Python,  recomendo aprender Python e não instalar uma modificação à linguagem que vai trorna-la não padrão. Se você realemtne usar o Pybraces vai usar algo que não é igual a Python para quem sabe Python, e não é igual à linguagens derivadas de "C" com java e Javascript, que usam  "{" e "}" para delimitar blocos.
Aliás, como não é um projeto extensivamente testado dificilmente terá sequer suporte sintático às declarações que usam chaves normalemente no Python como dicionários, conjuntos, dict comprehensions e set comprehensions.
Ademais, nenhum exemplo de Python que vocẽ encontrar na internet (ou no stack overflow) vai funcionar.
Se "{" e "}"  são  tão importantes para você, talvez seja melhor estudar Javascript em vez de Python.
Dito isso, as instruções para instalação estão no README, no próprio link que você colocou:
You'll need to copy or symlink braces.py into your Python lib/encodings
directory, and ensure that your user has rights to create the .pyc or .pyo
file there.

Ou seja, simplesmente coloque o arquivo braces.py na pasta lib/encodings de sua instalação de Python - e declare o encoding de cada arquivo com # coding: braces na primeira linha.
O próprio projeto do Pybraces avisa que ele é "silly": uma forma de poder colocar "{" e "}" necessários às linguagens
Comment: Eu só quero instalar para ver como é (curiosidade).


Google spreadsheet API. Cannot specify axisPosition of a series

Question: I want to specify the axis of a series. If i specify targetAxis to be "RIGHT_AXIS", it doesn't work..
The Axis-titles for LEFT_AXIS and RIGHT_AXIS are also not showing. Only the bottom one.
I want the graph to look like this:

But it ends up looking like this:

Here the red axis is at the bottom, because this column contains much lower numbers then the column with the numbers for the blue bars.
Someone who knows how i can solve this?
Here is my code:
          {
            addChart: {
              chart: {
                spec: {
                  title: "Graf - tibber",
                  basicChart: {
                    chartType: "COMBO",

                    axis: [

                      // X-AXIS
                      {
                        position: "BOTTOM_AXIS",
                        title: "TID",
                      },

                      // Y-AXIS LEFT
                      {
                        position: "LEFT_AXIS",
                        title: "FORBRUK(KWH)",

                      },

                      // X-AXIS RIGHT
                      {
                        position: "RIGHT_AXIS",
                        title: "PRIS",
                      },

                    ],
                    legendPosition: "BOTTOM_LEGEND",

                    domains: [
                      {
                        domain: {
                          sourceRange: {
                            sources: [
                              {
                                sheetId: 0,
                                startRowIndex: 0,
                                endRowIndex: endIndex,
                                startColumnIndex: 0,
                                endColumnIndex: 1
                              }
                            ]
                          }
                        }
                      }
                    ],

                    series: [
                      {
                        series: {
                          sourceRange: {
                            sources: [
                              {
                                sheetId: 0,
                                startRowIndex: 0,
                                endRowIndex: endIndex,
                                startColumnIndex: 5,
                                endColumnIndex: 6,
                              },
                            ],
                          },
                        },
                        targetAxis: "LEFT_AXIS",
                      },
                      {
                        series: {
                          sourceRange: {
                            sources: [
                              {
                                sheetId: 0,
                                startRowIndex: 0,
                                endRowIndex: endIndex,
                                startColumnIndex: 3,
                                endColumnIndex: 4,
                              },
                            ],
                          },
                        },
                        targetAxis: "RIGHT_AXIS",
                      }
                    ],
                    headerCount: 1,
                  },
                },
                position: {
                  newSheet: true,
                },
              },
            },
          },
        ],

Answer: Improved request
Disclaimer, there is a bug in the API for the right hand axis, see end of answer
{
  "requests": [
    {
      "addChart": {
        "chart": {
          "spec": {
            "title": "Graf - tibber",
            "basicChart": {
              "chartType": "COMBO",
              "legendPosition": "BOTTOM_LEGEND",
              "axis": [
                {
                  "position": "BOTTOM_AXIS",
                  "title": "TID"
                },
                {
                  "position": "LEFT_AXIS",
                  "title": "FORBRUK(KWH)"
                },
                {
                  "position": "RIGHT_AXIS",
                  "title": "PRIS"
                }
              ],
              "domains": [
                {
                  "domain": {
                    "sourceRange": {
                      "sources": [
                        {
                          "sheetId": 0,
                          "startRowIndex": 0,
                          "endRowIndex": 8,
                          "startColumnIndex": 0,
                          "endColumnIndex": 1
                        }
                      ]
                    }
                  }
                }
              ],
              "series": [
                {
                  "series": {
                    "sourceRange": {
                      "sources": [
                        {
                          "sheetId": 0,
                          "startRowIndex": 0,
                          "endRowIndex": 8,
                          "startColumnIndex": 1,
                          "endColumnIndex": 2
                        }
                      ]
                    }
                  },
                  "targetAxis": "LEFT_AXIS",
                  "type": "COLUMN"
                },
                {
                  "series": {
                    "sourceRange": {
                      "sources": [
                        {
                          "sheetId": 0,
                          "startRowIndex": 0,
                          "endRowIndex": 8,
                          "startColumnIndex": 2,
                          "endColumnIndex": 3
                        }
                      ]
                    }
                  },
                  "targetAxis": "RIGHT_AXIS",
                  "type": "LINE"
                }
              ],
              "headerCount": 1
            }
          },
          "position": {
            "newSheet": true
          }
        }
      }
    }
  ]
}

Note that the row and column indices I changed because I was working with some sample data. "type": "COLUMN" and "type": "LINE" entries in the series. In fact, for me, I would get 400 bad request without it. This produces a chart with BOTTOM_AXIS and LEFT_AXIS but not RIGHT_AXIS (see below for info on that). The chart also has two different scales so the line doesn't get overshadowed by the columns.

Right Axis
Unfortunately this is a current bug with the API: https://issuetracker.google.com/issues/153528225 - be sure to mark it with a ☆ to let Google know that this affects you.
Reference

Sample Chart Requests - I used the sample to navigate the documentation to find out if there were any attributes missing.


List Everything that uses a linked server in sql

Question: I am currently facing an issue communicating with a SQL server which has been moved and the database which I was looking info has been removed. I have been using an alias manager to divert all traffic from the old server to the new server, but still need it to look at the new table in this new server. Is it somehow possible to list everything that uses this linked server?
Answer: The are system views sys.sql_modules. The definition column contains the create script for the object. You could run this on each database:
select object_name(object_id)
from sys.sql_modules
where definition like '%LINKED_SERVER_NAME%';


How does eigenvalues measure variance along the principal components in PCA?

Question: I understand that eigenvalues measure variance along the principal components.
Questions

How are eigenvalues and variance same for PCA?
What is the intuition behind this being the same?
What is the mathematical proof behind this theory?
Comment: Eigenvalues of X'X are the sums of squares along the principal dimensions of data cloud X (n points by p original dimensions). That is the property of eigen-decomposition. Sums of squares of the original dimensions form the diagonal of X'X. Now, covariance matrix given by X [is just a particular case of](https://stats.stackexchange.com/a/22520/3277) "X'X" matrix. If you center columns of X and then divide by sqrt(n-1) then X'X is the cov. matrix with variances on the diagonal. Hence you can deduce that eigenvalues of the cov. matrix are the variances of principal dimensions of X centered.
Answer: We start from data covariance matrix
$$ S = \mathbb E(XX^{T})- \mathbb E(X) \mathbb E(X)^{T}$$
Say $\mu$ is a column vector of the same dimension of $X$ and $\mu^{T}\mu = 1$, then
$$\mu^{T}S\mu=\mu^{T}(\mathbb E(XX^{T})- \mathbb E(X) \mathbb E(X)^{T}) \mu = \mathbb E((\mu^{T} X)(\mu^{T} X)^{T})-\mathbb E(\mu^{T} X) \mathbb E(\mu^{T} X)^{T}$$
Note that $\mu^{T}X$ is the projection of $X$ onto $\mu$, such that
$$\mathbb E((\mu^{T} X)(\mu^{T} X)^{T})-\mathbb E(\mu^{T} X) \mathbb E(\mu^{T} X)^{T} = Var(\mu^{T} X)$$
Since $Var(\mu^{T} X)$ is simply a number, so we denote it as $\lambda$, so we have $$\mu^{T}S\mu = \lambda$$
Since $\mu^{T}\mu = 1$, so
$$\mu \mu^{T} S\mu = S\mu= \lambda \mu$$
which means the $\mu$ that we define in the first place is actually an eigenvector of the data covariance matrix, and the eigenvalue of which is the variance that the data has in that direction.
I cannot think of an intuitive way to make sense of this, but once you are familiar with the math, I think you will accept this.
Comment: This answer is incomplete. You have $\mu^T\mu=1$ but in the last eq., you're using $\mu\mu^T=1$ (even dim's aren't OK). This leads to the absurdity that $\mu$ could be any unit vector, the other arguments still hold. $\mu$ is not related to $X$ in the answer. It cannot be that all arbitrary unit vectors are eigenvectors of $S$ (unless $S=$const. times Id). I think you could refer to the [Rayleigh quotient](https://en.wikipedia.org/wiki/Rayleigh_quotient#Special_case_of_covariance_matrices) in the [Wikipedia article](https://en.wikipedia.org/wiki/Principal_component_analysis#First_component).
Comment: This may be helpful: https://math.stackexchange.com/a/3853794/1261174: Let A be any symmetric matrix. If we minimize xTAx/xTx  over all nonzero x (or, equivalently, minimize xTAx  over all x with ∥x∥=1), then we get the smallest eigenvalue back, with x  being its eigenvector.
Answer: Variance:
Variance is the square of the deviation from zero, so the total variance of a vector is the sum of its squared values.
https://en.wikipedia.org/wiki/Variance
Eigenvectors and Eigenvalues:
Eigenvectors are basis vectors that capture the inherent patterns that make up a dataset. By convention these are unit vectors, with norm = 1 so that they are the linear algebra equivalent of 1. Eigenvectors come in pairs, 'left' and 'right'. http://mathworld.wolfram.com/Eigenvalue.html
Convention (based on preferred orientation of data matrix as column matrix) is that the right eigenvector (I'll use the notation I'm familiar with $L^T$ which is used in various applied fields when talking about PCA) is the basis functions and is what is variously known as principal components, loadings, latent factors amongst many other. The right eigenvector can be projected onto any dataset with the same variables, so is useful for model building.
The left eigenvector ($S$) is the weights that each sample takes for each right eigenvector, and as such can be considered a series of functions for linear transformation of your original matrix. In practice this means that $S$ is the weightings that are given to each sample in order to construct the right eigenvector, which means that by definition they represent the total amplitude that each right eigenvector explains in that particular sample.
$$L^T=S^†D$$
Summing the individual variances explained per sample gives the total variance explained in the dataset.
Eigenvalues are a set of scalars such that a linear transformation S is scaled with the right eigenvectors produces the same result as multiplying the right eigenvectors themselves by that value
$$SL^T = \lambda L^T$$
Since linear algebra multiplication involves summation of the products of the row and column entries in the two multiplicands then multiplication by a scalar that is the total variance of the linear transform gives the same result. This means that eigenvalues are the variance of the by definition.
Eigendecomposition and PCA:
Thinking about it a bit more I realise that while NIPALS (see original answer below) is more intuitive for understanding how PCA is calculated, the SVD method is more intuitive for understanding eigenvalues themselves.
In SVD the data is decomposed into two sets of unit vector matrices with a diagnonal scaling matrix in between.
$$D = U*sv*L^T$$
the scores matrix $S$ in PCA is $U*sv$ and $L$ is the eigenvectors
The singular values are related to eigenvalues as:
$sv = \sqrt{ev}$
Note this relationship between the two is subject to constraints as described in https://math.stackexchange.com/questions/127500/what-is-the-difference-between-singular-value-and-eigenvalue
Original Answer using NIPALS:
For me the best algorithm for understanding PCA in an intuitive way is NIPALS
https://folk.uio.no/henninri/pca_module/pca_nipals.pdf
With the NIPALS approach the following steps are taken
Inner product of data $D$ to get covariance matrix (correlation in scaled appropriately) whose diagonal is the sum of squares
$D^TD$
Project an initial vector of weights $W$ onto the data (various sources recommend using random samples to do this, I prefer the unit vector of the square root of the sum of squares). I will refer to the eigenvectors as $L$
$$L^T_0=W^†D$$
This gives an initial guess at the prinicpal component, which is then projected onto the data to reconstruct it based on the initial guess.
$$D_{recon} = WL^T_0$$
The residual is calculated $D-D_{recon}$ and its sum of squares is calculated. OLS is then preformed until the sum of squares reaches a predefined stopping criteria, each time calculating the unit vector arising from projecting the updated weightings onto the data. This unit vector is the iterated principal component or eigenvector.
In NIPALS we subtract the final reconstructed data from the original data then use the residual to calculate PC2, and always proceed to the next PC with the final residual after iterating. This means all variance accounted for by $PC_i$ is removed from consideration by $PC_{>i}$
Initially the product of $WD$ is a vector with a norm that is not equal to 1, so we calculate the norm of the vector and use it to scale the vector to a unit vector.
The reason for creating unit vectors is that they are numericlly more stable than unconstrained vectors and have the nice property of behaving the same in linear algebra multiplication and inverse matrix operations (basically they are the linear algebra equivalent of the number 1).
How is eigenvalues and variance same for PCA?
So what is this norm that was used to scale the eignevector? It is the square root of the sum of squares of the coefficicents in the vector, i.e. the square root of the variance. The eigenvalue is the square of this value, i.e. it is the sum of squares = total variance.
If the characteristic vectors (the eigenvectors) are not unit vectors then the eigenvalues would not be their variance, but since we define eigenvectors as unit vectors then it falls out naturally that they are the variance of that vector in the data. If we calculate the scores by projecting the eigenvectors onto the data (note the formula below only works because L is comprised of unit vectors)
$$S = LD$$
Then the scores, since they have being multiplied by unit vectors, take on the total variance that is captured within the data by each unit vector. By definition eigenvalues are scalars that map the characteristic vectors of a matrix onto the matrix, i.e. they scale the vectors in order to reconstruct the original data based on the characteristic vectors.
Whats is the intuition behind this being the same.
Whats is the mathematical proof behind this theory?
They are this way by definition as described above


While loop and bool make program end

Question: Code analyzes a integer and asks the user if he wants to analyze another integer at the end.  I have it set up in a while loop to run only when 'again' is true. At the end a user inputs a 'n' for no, do not run another number.  The problem is the program runs again even after again = false.
How can I fix my loop?
I think the main focus is at the bottom where my switch is but i posted it all just in case i over looked something in the main part of the code.
int main()
{
bool again = true;
bool flag = false;
int usernum;
int count = 0;
int userhold1, userhold2;
userhold1 = 0;
userhold2 = 0;
char choice;

while ( again = true )
{
    cout << "Please enter a positive integer: ";  // Getting the number to test
    cin >> usernum;
    cout << endl;

    //////////////////////////////////  Finding the Factors

    cout << "The factors of " << usernum << " are: ";

    for (int i=1 ; i <= usernum/2 ; i++)
    {
        if( isAfactor ( usernum , i , flag) )
        {
          cout << i << ", ";
          count = count + i;  // Keeping track of sum of factors
        }
    }
    cout << "and " << usernum << endl;
    count = count + usernum;

    ////////////////////////////////// Sum of Factors

    cout << "The sum of the factors is: " << count << endl;

    ////////////////////////////////// Prime Factorization

    cout << "The prime factorization is: ";
    getPrimeFac ( usernum );
    cout << endl;

    ////////////////////////////////// Even/Odd Checker

    cout << usernum << " is an ";
    if ( checkeven( usernum ) == true)
        cout << "EVEN number." << endl;
    else
        cout << "ODD number." << endl;

    ////////////////////////////////// Prime Checker

    PrimeCheck (usernum);

    ////////////////////////////////// Perfect , Abundant , Deficient

    count = 0;

    for ( int i = 1 ; i <= usernum/2 ; i++ )  // Adding the factors of the number
    {
        if( isAfactor ( usernum , i , flag )  )
            count = count + i;  // Suming of factors
    }

    if ( count == usernum )
        cout << usernum << " is a PERFECT number." << endl;
    else if ( count > usernum )
        cout << usernum << " is an ABUNDANT number." << endl;
    else if ( count <usernum )
        cout << usernum << " is a DEFICIENT number." << endl;

    ////////////////////////////////// Squares

    SquareCheck ( usernum );

    ////////////////////////////////// Twin Primes

    if ( PrimeCheck2 ( usernum ) == true )
    {
        if ( PrimeCheck2 ( usernum -2 ) == true )
        {
            userhold1 = ( usernum - 2 );
            cout << usernum << " has a twin prime: " << userhold1 << " ";

            if ( PrimeCheck2 ( usernum + 2 ) == true )
            {
                userhold2 = ( usernum + 2 );
                cout << "and " << userhold2;
            }
        }

        if ( PrimeCheck2 ( usernum + 2 ) == true )
        {
            userhold1 = ( usernum + 2 );
            cout << usernum << " has a twin prime: " << userhold1 << " ";

            if ( PrimeCheck2 ( usernum - 2 ) == true )
            {
                userhold2 = ( usernum - 2 );
                cout << "and " << userhold2;
            }
        }
    }
    cout << endl << endl;

    //////////////////////////////////  End program again?

    cout << "Would you like to analyze another number? (y/n) :";
    cin >> choice;

    switch (choice)
    {
     case 'y': again = true;
         break;
     case 'n': again = false;
         break;
    }
}

system ("pause");
}

Comment: This is an assignment statement `again = true`. Some people write it like `true == again`. Then the compiler will warn you if you leave off an equals sign -- because you can't update the value of true.
Comment: @user814064 - you're on the right track, but modern compilers should warn for the first version. If you use "Yoda conditions" such as `true == again`, the mistake becomes `true = again` which is an *error* (not just a warning) because it's not possible to modify the literal value `true`.
Answer: This line will set again to true and then return the new value of again, so it will always be true.
while ( again = true )

Try this instead:
while ( again == true )

Or even better:
while ( again )

Comment: Why is `while (again)` better than `while(again==true)`? Isn't it just  a shorter way to write it?
Comment: @RUJordan if use (again == true), the final assembly code after compilation will looks like: mov true,eax;mov again,ebx;cmp eax,ebx;jnz IF_NOT_EQUAL;#CODES IF EQUAL; IF_NOT_EQUEAL:#CODES IF NOT EQUAL;   however, if use (again), the final assembly code will just like: mov again,eax; cmp eax,$0; jnz IF_NOT_TRUE;
Comment: @House.Lee - for the last 20 years or more, compilers would return the same code for both, with the possible exception of disabling all optimisations. It's best to omit the `== true`, though, because it's a stereotypical thing that newbies do when they don't really understand `if` and booleans. As a result, it tends to trigger ridicule. There *are* times when including the `== true` can improve readability slightly, but this isn't really one of them.
Comment: What about a while(true) loop? Is it best to improve readability by using while (true == true) instead? :P
Comment: @moander - I've been trying to resist saying this, but I give up. So... no, I prefer `while (false == false)`.
Answer: Change
while(again=true)

to
while(again == true)

or
while(again)

Answer: Using = is an assignment statement. To compare, you use ==
while (again == true) {
    //do code
}

While loop and bool make program end


Spring security with AngularJS - 404 on logout

Question: I'm working with tutorial that describes how to write simple single-page app using Spring Boot, Spring Security and AngularJS: https://spring.io/guides/tutorials/spring-security-and-angular-js/
I cannot logout currently logged user - when I perform POST request to "/logout", I get "404 not found" - screen from Google Chrome debugger:

Why GET? I performed POST. Why "/login?logout", not "/logout"? Here is the code that is invoked when user clicks logout button:
$scope.logout = function() {
            $http.post('logout', {}).success(function() {
                $rootScope.authenticated = false;
                $location.path("/");
            }).error(function(data) {
                console.log("Logout failed")
                $rootScope.authenticated = false;
            });
        }

Spring code:
@SpringBootApplication
@RestController
public class UiApplication {

    @RequestMapping("/user")
    public Principal user(Principal user) {
        return user;
    }

    @RequestMapping("/resource")
    public Map<String, Object> home() {
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("id", UUID.randomUUID().toString());
        model.put("content", "Hello World");
        return model;
    }

    public static void main(String[] args) {
        SpringApplication.run(UiApplication.class, args);
    }

    @Configuration
    @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
    protected static class SecurityConfiguration extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.httpBasic().and().authorizeRequests()
                    .antMatchers("/index.html", "/home.html", "/login.html", "/").permitAll().anyRequest()
                    .authenticated().and().csrf()
                    .csrfTokenRepository(csrfTokenRepository()).and()
                    .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
        }

        private Filter csrfHeaderFilter() {
            return new OncePerRequestFilter() {
                @Override
                protected void doFilterInternal(HttpServletRequest request,
                        HttpServletResponse response, FilterChain filterChain)
                        throws ServletException, IOException {
                    CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class
                            .getName());
                    if (csrf != null) {
                        Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
                        String token = csrf.getToken();
                        if (cookie == null || token != null
                                && !token.equals(cookie.getValue())) {
                            cookie = new Cookie("XSRF-TOKEN", token);
                            cookie.setPath("/");
                            response.addCookie(cookie);
                        }
                    }
                    filterChain.doFilter(request, response);
                }
            };
        }

        private CsrfTokenRepository csrfTokenRepository() {
            HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
            repository.setHeaderName("X-XSRF-TOKEN");
            return repository;
        }
    }

}

Whole AngularJS code:
angular.module('hello', [ 'ngRoute' ]).config(function($routeProvider, $httpProvider) {

    $routeProvider
.when('/', {templateUrl : 'home.html', controller : 'home'  })
.when('/login', { templateUrl : 'login.html',   controller : 'navigation'   })
.otherwise('/');

    $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

}).controller('navigation',

        function($rootScope, $scope, $http, $location, $route) {

            $scope.tab = function(route) {
                return $route.current && route === $route.current.controller;
           };

            var authenticate = function(credentials, callback) {

                var headers = credentials ? {
                    authorization : "Basic "
                            + btoa(credentials.username + ":"
                                    + credentials.password)
                } : {};

                $http.get('user', {
                    headers : headers
                }).success(function(data) {
                    if (data.name) {
                        $rootScope.authenticated = true;
                    } else {
                        $rootScope.authenticated = false;
                    }
                    callback && callback($rootScope.authenticated);
                }).error(function() {
                    $rootScope.authenticated = false;
                    callback && callback(false);
                });

            }

            authenticate();
            $scope.credentials = {};
            $scope.login = function() {
                authenticate($scope.credentials, function(authenticated) {
                    if (authenticated) {
                        console.log("Login succeeded")
                        $location.path("/");
                        $scope.error = false;
                        $rootScope.authenticated = true;
                    } else {
                        console.log("Login failed")
                        $location.path("/login");
                        $scope.error = true;
                        $rootScope.authenticated = false;
                    }
                })
            };

            $scope.logout = function() {
                $http.post('logout', {}).success(function() {
                    $rootScope.authenticated = false;
                    $location.path("/");
                }).error(function(data) {
                    console.log("Logout failed")
                    $rootScope.authenticated = false;
                });
            }

        }).controller('home', function($scope, $http) {
           $http.get('/resource/').success(function(data) {
               $scope.greeting = data; }) });

I'm new to Spring. Here is the whole code from tutorial - doesn't work too:
https://github.com/dsyer/spring-security-angular/tree/master/single
Comment: In case you want to understand what happened. You "get GET instead of POST" because there are actually 2 requests for logout. The first one is POST you done manually that receives a response with a redirect code to "login?logout" resource. Then GET request to this resource is performed. When you "override" logoutSuccessHandler you will exclude redirection from logout request (i.e. there will be just one POST request to "logout" resource).
Comment: did you try my answer?
Answer: In fact what you need is just to add a logout success handler
@Component
public class LogoutSuccess implements LogoutSuccessHandler {

@Override
public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication)
        throws IOException, ServletException {
    if (authentication != null && authentication.getDetails() != null) {
        try {
            httpServletRequest.getSession().invalidate();
            // you can add more codes here when the user successfully logs
            // out,
            // such as updating the database for last active.
        } catch (Exception e) {
            e.printStackTrace();
            e = null;
        }
    }

    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

}

}

and add a success handler to your security config
http.authorizeRequests().anyRequest().authenticated().and().logout().logoutSuccessHandler(logoutSuccess).deleteCookies("JSESSIONID").invalidateHttpSession(false).permitAll();

Answer: In newer version of Spring Boot there is a class called HttpStatusReturningLogoutSuccessHandler which returns HTTP 200 per default. Its JavaDoc says:

"This is useful in REST-type scenarios where a redirect upon a
  successful logout is not desired".

to use it write something like:
        //...
        .formLogin()
        .and()
        .logout().logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler());

Answer: Try to change $http.post('logout', {}) to this $http.post('\logout')
So it will be like this:
$scope.logout = function () {
    $http.post('\logout')
        .success(function () {
            // on success logic
        })
        .error(function (data) {
            // on errorlogic
        });
}


Finding the Moment Generating Function of chi-squared distribution

Question: I'm tasked with deriving the MGF of a $\chi^2$ random variable.
I think the way to do is is by using the fact that $\Sigma_{j=1}^{m} Z^2_j$ is a $\chi^2$ R.V. and that MGF of a sum is the product of the MGFs of the individual terms.  Although that may not be right and it may be $E(e^{tX})$ way.
I don't need it solved really just need to get down the track a little further.
Comment: What's wrong with the formula given by http://en.wikipedia.org/wiki/Chi_squared ? _i.e._ $(1-2t)^{-m/2}$
Answer: Yes, since $\chi^2$ is a sum of $Z_i^2$ the MGF is a product of individual summands. But then you need the MGF of $Z_i^2$ which is $\chi^2$ with 1 degree of freedom. The obvious way of calculating the MGF of $\chi^2$ is by integrating. It is not that hard:
$$Ee^{tX}=\frac{1}{2^{k/2}\Gamma(k/2)}\int_0^\infty x^{k/2-1}e^{-x(1/2-t)}dx$$
Now do the change of variables $y=x(1/2-t)$, then note that you get Gamma function and the result is yours. If you want deeper insights (if there are any) try asking at http://math.stackexchange.com.
Answer: I think the easiest way is to simply start with a single squared gaussian:
$$E[e^{tX^2}]
= \int_{-\infty}^\infty e^{tx^2}\tfrac1{\sqrt{2\pi}}e^{-x^2/2}dx
= \tfrac1{\sqrt{2\pi}}\int_{-\infty}^\infty e^{-(1-2t)x^2/2}dx
= \tfrac1{\sqrt{1-2t}},$$ for $t<1/2$.
Since the Chi-squared is just a sum of independent squared gaussians, you get the factor $k$ in the exponent.
Comment: +1 It's nice to see a clever approach that might even generalize to other situations.  Of course this answer is limited to integral degrees of freedom.
Comment: I've never even thought about non-integral degrees of freedom. To me "the sum of $k$ squared gaussians" has basically been the definition of Chi-Squared. It's nice to see there is more to it than that :-)
Comment: Arbitrary df show up in various contexts, such as the Satterthwaite and CABF t-tests.
Answer: You can also do this calculation by brute-force straight from the general chi-squared distribution, without appeal to any intermediate appeal to sums of random variables.  For $X \sim \chi_n^2$ we have moment generating function:
$$\begin{equation} \begin{aligned}
M_X(t) \equiv \mathbb{E}(\exp (tX))
&= \int \limits_0^\infty \exp(tx) \cdot \text{Chi-Sq}(x | n) dx \\[8pt]
&= \frac{1}{2^{n/2} \Gamma(n/2)} \int \limits_0^\infty \exp(tx) \cdot x^{n/2-1} \exp(-x/2) dx \\[8pt]
&= \frac{1}{2^{n/2} \Gamma(n/2)} \int \limits_0^\infty x^{n/2-1} \exp((t -\tfrac{1}{2})x) dx. \\[8pt]
\end{aligned} \end{equation}$$
For the case where $t < \tfrac{1}{2}$, using the change-of-variable $r = (\tfrac{1}{2} - t)x$ we have:
$$\begin{equation} \begin{aligned}
M_X(t)
&= \frac{1}{2^{n/2} \Gamma(n/2)} \int \limits_0^\infty x^{n/2-1} \exp((t -\tfrac{1}{2})x) dx. \\[8pt]
&= (\tfrac{1}{2} - t)^{-n/2} \cdot  \frac{1}{2^{n/2} \Gamma(n/2)} \int \limits_0^\infty r^{n/2-1} \exp(-r) dr. \\[8pt]
&= (1 - 2t)^{-n/2} \cdot \frac{1}{\Gamma(n/2)} \int \limits_0^\infty r^{n/2-1} \exp(-r) dr. \\[8pt]
&= (1 - 2t)^{-n/2}. \\[8pt]
\end{aligned} \end{equation}$$
Comment: The details are nicely laid out, but the approach appears identical to that of the accepted answer.


ext3 mount options differ from linux kernel doc

Question: I'm playing in my server lab with ext3 filesystem mount options, looking the kernel doc
https://www.kernel.org/doc/Documentation/filesystems/ext3.txt

I'm using redhat 5.8, if try to mount the fs in this way
mount -o noload /dev/vgmirror/lvmirror /mnt/
mount -o norecovery /dev/vgmirror/lvmirror /mnt/
mount -o journal=noload /dev/vgmirror/lvmirror /mnt/
mount -o journal=norecovery /dev/vgmirror/lvmirror /mnt/

Every above commands fails with error
mount: wrong fs type, bad option, bad superblock on /dev/vgmirror/lvmirror,
missing codepage or other error
In some cases useful info is found in syslog - try
dmesg | tail  or so

This mount options was removed on redhat? or the kernel doc is deprecated? or i'm using the wrong commands?
Answer: The man-page you are linking to refers to the latest version of the linux kernel, while you are on Red Hat 5.8 which uses a quite older kernel.
You are better out using the online documentation on the server.
Use the following command on the server and use this as your reference instead.
man 8 mount

Comment: Thanks, i found the mount options using man 8 mount, i will try to do the same commans in fedora 18 and i will let you know, maybe the problem is the man pages are updated, but redhat are using an old kernel
Comment: Just remember that the mount options might be different in Fedora 18 so you should read the manual page on that system as well. The real problem is that you did not read the correct manual page for the correct system.
Comment: using the man 8 mount, i just found norecovery option in the xfs filesystem mount options session, for ext3 nothing found
Comment: Why would you do anything on Fedora 18, which has reached end of life?
Comment: @c4f4t0r Then it is probably not available for `ext3` on your system.


Kill child process when the parent exits

Question: I'm preparing a script for Docker, which allows only one top-level process, which should receive the signals so we can stop it.
Therefore, I'm having a script like this: one application writes to syslog (bash script in this sample), and the other one just prints it.
#! /usr/bin/env bash
set -eu

tail -f /var/log/syslog &

exec bash -c 'while true ; do logger aaaaaaaaaaaaaaaaaaa ; sleep 1 ; done'

Almost solved: when the top-level process bash gets SIGTERM -- it exists, but tail -f continues to run.
How do I instruct tail -f to exit when the parent process exits? E.g. it should also get the signal.
Note: Can't use bash traps since exec on the last line replaces the process completely.
Comment: Isn't this what things like `supervisord` are supposed to handle?
Comment: @MichaelHampton, you're right, but in this case I really need to print something out. Supervisor is not good at printing :)
Comment: I read your other question too. You really should describe what's actually going on, and name the applications you're working with.
Comment: Could you try tail -f --pid="$$" filename?
Comment: @MichaelHampton, okay, let's say that's Apache. It can only log to files or syslog, and not to stdout. I need to have logging to stdout :)
Comment: I got that part already. But it isn't Apache. What is it really?
Comment: @MichaelHampton, supervisor running multiple processes: apache, redis,  cron (bundled them to simplify the setup). In other cases this can be any app which only can write to logfiles. stdout logs is a requirement for 12-factor apps to run in a cloud, namely, CoreOS
Comment: @kupson hahaha oh my gosh, never thought `tail` can do that! Amazing! Post as an answer, I'll accept it :)
Comment: Apache can log to anything you want, including an external command. So using it as an example makes absolutely no sense.
Comment: @MichaelHampton, ErrorLog `|cat` does not output anything since when Apache launches this external command - it discards its output
Answer: If you are lucky^Wusing tail command from GNU coreutils you can use --pid=<number> option. The capital -F option would make you safe against log rotation.
tail --pid="$$" -F /var/log/syslog &

More info: http://www.gnu.org/software/coreutils/manual/html_node/tail-invocation.html


Custom 500 Error page: Is there a way to theme a fatal error?

Question: In /core/includes/errors.inc, when there is a fatal error it outputs a response with the message "The website encountered an unexpected error. Please try again later." and a back-trace, if error_level is set to verbose, and without the back-trace otherwise.
It seems like at this point, there's no way, with an event subscriber to capture the response and alter it.
Is that correct?
Or is there a way to wrap the output from line 268 of errors.inc in Drupal 8.4 with markup?
Note, there's another answer that works if it's not a fatal error, but that doesn't offer a complete solution.
Also, I looked into .htaccess and Apache ErrorDocument directive, but that was misguided. Once Apache passes off to PHP, it can no longer use that directive.  That's for real server errors.
Answer: Symfony's HttpKernel uses the event dispatcher to allow subscribers to handle exceptions and send custom responses. Only if no subscriber does so will it throw the exception further up and let it reach the global error handler. (At which point it's indeed too late to do anything else.)
Drupal already comes with such a subscriber (or rather several of them, which check particular conditions) for HTTP exceptions (These are implementors of \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface, such as NotFoundHttpException.)
If you absolutely need to intercept non-HTTP exceptions wherever they happen, and return custom responses, you can create your own subscriber (see  Drupal\Core\EventSubscriber\HttpExceptionSubscriberBase), and give it a very low priority (< -128) to avoid interfering with the core HTTP exception subscribers.
However, architecture-wise I would suggest this is not a good way to go. If you have a controller that triggers a particular exception, then it should catch it and throw the appropriate HTTP exception instead. This also requires much, much less code than messing around with event subscribers. ;)
If need be, you can even throw a ServiceUnavailableHttpException (503) or set a custom status like new HttpException(500) if there is no class for it.
Drupal core's exception subscribers don't actually handle 5xx errors, but you can create your own that does, which would probably look something like the following:
class Custom5xxHtmlSubscriber extends HttpExceptionSubscriberBase {
  public function on5xx(GetResponseForExceptionEvent $event) {
     // Do stuff
     (new Response())->send();
  }

With a corresponding service definition like the following:
  custom5xxsubscriber:
    class: ...
    tags:
      - { name: event_subscriber }

Comment: Theoretically, this is true but in practice, it's not working with 5xx errors which come from fatal errors. is this true?
Comment: Yes, there are fatal errors in PHP which cannot be intercepted, even with custom error handling, and the server will generally serve its own 5xx response for those (which might be customized outside of PHP through nginx/apache config). This answer only deals with HTTP 5xx responses generated inside PHP.
Comment: thanks for the explaination. but I guess if in fatals PHP still generate 5xx responses.
for the sample, just try to change the crednetial to connect to database. you see still php return 500 to the browser.
Answer: you can use https://www.drupal.org/project/custom_500_error module.
go to the setting and enter your custom message and markups which you want.
after that on all 500 errors, instead of the default message your customized message and markup will be shown.
Answer: You can generate custom 500 error responses by implementing a custom error handler and a custom exception handler, depending upon your needs, in your MODULE.module script.
Custom Unhandled Exception Handler
To catch any unhandled exceptions that would typically bubble up to drupal_register_shutdown_function and halt processing on the spot (no more "The website encountered an unexpected error. Please try again later." error):
// Set a custom exception handler.
set_exception_handler('MODULE_exception_handler');

/**
 * Handles uncaught exceptions.
 *
 * @param mixed $exception
 *   Exception that was uncaught.
 */
function MODULE_exception_handler(\Throwable $exception) {
  $exceptionType = get_class($exception);
  $exceptionMessage = $exception->getMessage();

  $content = "
An error occurred.

    Error Type: $exceptionType

    Message: $exceptionMessage
";

  echo $content;
}

Custom Error Handler
This also catches errors that would normally bubble up, though you must use exit to halt processing. If you do not exit, then the messages will stack until Drupal fires the shutdown function.
// Set a custom error handler.
set_error_handler('MODULE_error_handler');

/**
 * Provides a top-level error handler.
 *
 * @param int $errno
 *   Level of the error raised.
 * @param string $errstr
 *   Error message.
 * @param string $errfile
 *   Filename that the error was raised in.
 * @param int $errline
 *   Line number where the error was raised.
 *
 * @return bool
 *   True to halt additional PHP processing, false otherwise.
 */
function MODULE_error_handler(int $errno, string $errstr, string $errfile = NULL, int $errline = NULL): bool {
  // $errstr may need to be escaped:
  $errstr = htmlspecialchars($errstr);

  switch ($errno) {
    case \E_USER_ERROR:
      echo "My ERROR [$errno] $errstr
\n";
      echo "  Fatal error on line $errline in file $errfile";
      echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")
\n";
      echo "Aborting...
\n";
      // Immediately stop all additional processing.
      exit(1);

    case \E_USER_WARNING:
      echo "My WARNING [$errno] $errstr
\n";
      // Uncomment to immediately stop all additional processing.
      // exit(1);
      break;

    case \E_USER_NOTICE:
      echo "My NOTICE [$errno] $errstr
\n";
      // Uncomment to immediately stop all additional processing.
      // exit(1);
      break;

    default:
      echo "Unknown error type: [$errno] $errstr
\n";
      // Uncomment to immediately stop all additional processing.
      // exit(1);
      break;
  }

  /* Don't execute PHP internal error handler */
  return true;
}

PLEASE NOTE: In the grand flow of things, the custom error handler is executed before the custom exception handler. Keep that in mind when deciding which one to use and when to call exit in the error handler.


Tracking down pesky PHP 5.3 errors

Question: We have a site that is throwing errors when uploading files to a simple "Page" node. I've done a lot of work trying to track down the actual source of the error, and I posted a half dozen messages to various likely threads at drupal.org.
The errors we get on file attach/upload:

warning: Parameter 2 to wysiwyg_form_alter() expected to be a
  reference, value given  in /var/www/drupal/includes/common.inc on line
  2892.
warning: Parameter 2 to simple_access_form_alter() expected to be a
  reference, value given in /var/www/drupal/includes/common.inc on line
  2892.

I understand about passing by reference versus value. I understand about fixing the problem in the offending module by using the two calls to drupal_alter(), as described on
http://drupal.org/node/930992#comment-4066840, but so far I have not been able to find what module is making the call incorrectly.
I tried installing and enabling the same set of modules on a test site but cannot reproduce these errors.
It's hard to post a bug report when you don't know the offending module.
See also http://drupal.org/node/1200970#comment-5463436.
Answer: Assuming you do not have a debugger going (getting XDebug to run for your local development environment is probably the single most useful thing you can do the entire year), you could use debug_backtrace() at the place of the error (i.e. in the two form alter functions) to find out what is calling them. If you shoot its output into watchdog(), hopefully you can cross reference the time of the error with a particular invocation of these functions. Do be aware that these are form alter hooks, which get called for each and every form Drupal is building (and you might be surprised there can actually be several forms on a single page; just think of search and login forms). I.e. not every call will be the offending one.
Comment: I had already placed a `dsm(debug_backtrace());` at the beginning of the wysiwyg_form_alter function. It showed the following:
[0] wysiwyg_form_alter
[1] call_user_func_array from common.inc (core)
[2] drupal_alter from form.inc (core)
[3] drupal_prepare_form from form.inc (core)
[4] drupal_get_form (from node.pages.inc, core)
[5] node_page_edit
[6] call_user_func_array (menu.inc)
[7] menu_execute_active_handler (index.php)
Comment: Not sure where to go from here, since it seems to be all core stuff, and I thought core was OK with php 5.3.
Comment: It should be, but core can have bugs just like any other piece of software :) I do find a few issues on D.o about your error message (specifically, code going through common.inc line 2892 throwing this error), but there doesn't seem to be a clear cut solution yet.
Comment: Thanks for the hint - I applied a patch to common.inc as described in the comment below, and that fixed the problem. I also along the way (in response to other error messages and problems) patched the core upload.module and applied two patches to the private_upload module. Whew! Fixing common.inc based on: http://drupal.org/node/710892#comment-3884210

Thanks for your help Eelke Blok!!
Answer: The errors reported are for functions contained, respectively, in the Wysiwyg module and the Simple Access module. wysiwyg_form_alter() is the implementation of hook_form_alter() done from the first module, and simple_access_form_alter() is the implementation of the same hook done from the second module.
The function names of function implemented from a module are generally prefixed by the short name of the module. In the case of hook implementations, the list of the hooks used by Drupal is listed under Hooks (Drupal 7) and Hooks (Drupal 6); that helps because the hook name is the second part of the hook implementation.
For example, wysiwyg_form_alter() could be the function implemented by a module using "wysiwyg_form" as short name, but looking at the installed modules, you will see that you don't have any "wysiwyg_form.module" file; instead, you have a "wysiwyg.module" file that is generally inside a "wysiwyg" directory.

Tracking down pesky PHP 5.3 errors


Typescript - Type KeyValuePair is not assignable to type KeyValuePair

Question: I am been shown the following error
Type 'KeyValuePair<string, Date>' is not assignable to type 'KeyValuePair<number, string>'.
  Type 'string' is not assignable to type 'number'.

based on the following code
class KeyValuePair<TKey, TValue> {
    constructor(public key: TKey, public value: TValue) {}
}

class KeyValuePairPrinter<T, U> {
    constructor(private pairs: KeyValuePair<T, U>[]) {}

    print() {
        for (let p of this.pairs) {
            console.log(`${p.key}: ${p.value}`);
        }
    }
}

let now = new Date(Date.now())
let pair1 = new KeyValuePair<number, string>(1, "First");
let pair2 = new KeyValuePair<string, Date>("Second", new Date(Date.now()));
let pair3 = new KeyValuePair<number, string>(3, "Third");

var printer = new KeyValuePairPrinter([
    pair1,
    pair2,
    pair3,
]);
printer.print();

as shown in the screenshot below

What could be causing this error?
Comment: `Pair2` is a different type than the others, while the constructor signature requires an array of the same type of objects.
Comment: @Alejandro Makes sense...
Comment: If you switch the signature in your class to  it should work. @Alejandro is correct that it takes in the first parameter and infers the type for the rest
Comment: If you use `` you might as well not bother using typescript/generics at all
Comment: *What could be causing this error?* the error message seems to tell you what? `'KeyValuePair' is not assignable to type 'KeyValuePair'`. i.e. `KeyValuePair` isn't the same type as `KeyValuePair`. It's not clear what exactly you don't understand?
Comment: @Liam Until Alejandro explained it, was not that obvious to me.
Answer: In your case, typescript infers the type of the generic argument based on what you first pass to the constructor.
let pair1 = new KeyValuePair<number, string>(1, "First");
let pair2 = new KeyValuePair<string, Date>("Second", new Date(Date.now()));
let pair3 = new KeyValuePair<number, string>(3, "Third");

var printer = new KeyValuePairPrinter([
    pair1, // KeyValuePair<number, string> => T = number, U = string
    pair2, // wrong type
    pair3, // correct type
]);

You can explicitly set the type of the generic arguments to circumvent typescripts inferred type:
var printer = new KeyValuePairPrinter<number | string, string | Date>([
    pair1,
    pair2,
    pair3,
]);

Comment: It should just use  in the constructor to avoid all this mess. Trying to be fancy with generics is not always the best solution to things.
Comment: @BenBrown `any` should be avoided since it actually breaks the whole concept of having types. It may look like a mess, but this still forces you to check and cast variables, whereas `any` just lets you write happy but ugly javascript.
Comment: this seems to make a mockery of using generics at all? why try and pass types when your going to make them so loose that those types become meaningless. `KeyValuePair` should probably just become `constructor(public key: any, public value: any)` without the generics as they're pretty pointless
Comment: @Liam In this scenario yes, but you can still use the class somewhere else where typescript correctly infers the types
Comment: IMO typescripts `Type | Type` syntax is stupid. It's either a strongly typed language or it's not. Trying to make it a little bit strongly typed seems dumb. If these things share properties, that's what interfaces are for, but hey that's just me :)
Comment: @BenBrown there's no point in using generics at all if your not going to restrict the types. Rather than using `KeyValuePair` it should be `KeyValuePair` as these are essentially identical and involve less setup. Again, IMO you should never use `any` in typescript; again, you're either using types (typescript) or you not (javascript). There's no point being half hearted about it.


Why write notes with same letter name an octave apart but in different positions

Question: What would be the reasons for composers to write notes with the same letter name (eg C) an octave apart and have one in root position and the second one in first inversion.  For example, the first C will be middle C in root position and the second C in first inversion an octave apart.
Any specific reason for writing the chords this way?  If yes, what would be the functions of these 2 chords?
Do these chords normally resolve to certain chords?
Thank you all for the contributions.  I'd like to share the following to explain what I mean because I think I made a mistake with one of the chords.  This is ABRSM G7 model answers for its Q1 chord notation question.
I've seen a few composers write in this manner - first chord C in root position (CEG) followed by A in first inversion - (CAE) with the C in the bass written an octave apart from the C of the previous chord and then followed by D#.  Are there any reasons for writing the harmony this way?  Thanks.
Comment: Welcome! There's a little confusion here. Is the question really "why would people use first inversion chords?" Note, an inversion just tells you which note is in the bass. A first inversion C chord could have the C two octaves higher, or four, or missing entirely!
Comment: @AndyBonner - not sure how an inversion of a C chord could be missing a C note.
Comment: first inversion means taking the third chord factor and using it as the bass (lowest) note in voicing. Could you give an example? image of the score or how it is written? Maybe you mean something else, I don't think it's possible to write a C as a first inversion of a C chord. @AndyBonner I don't think you can omit the C from a C chord? if you inverted a C chord and didn't play the C then it would be a different chord? I'm confused haha
Comment: Is this question about notes or chords?
Comment: Perhaps your question is really focused on octave leaps in the bass? This excerpt contains a lot. In the measure you drew a square around, one is root position and one is 1st inversion, but that's kind of just a coincidence of which chords were needed.
Comment: Thank you for providing feedback to my question.  Much appreciated and my apologies for not making the question clearer
Answer: Octaves are equivalent harmonically but not equal. The octave above a given note has twice the frequency; when sounded together, there's not much difference in tone.
However if sounded with a different note, there is a difference. The interval C to E is a major third; the interval from this E to the C above is a minor sixth; they do not sound the same. Either interval can be the constituent of a C-major chord. We could also add a G above the E and compare the sounds of C-E-G with E-G-C. These are both C-major chords; they do not sound the same. They have the same root, C, but the arrangement of notes is different.
When composing a harmony (or improvising one, the same thing but occurring more quickly), there are two "progressions" that one must be aware of. They are both important. The movement of chordal roots (called the harmonic progression) matters (or at least for a plurality of music from the 1500s to today) is audible; it is often used structurally to signal phrases or sections of music and to create feelings of movement, repose, or finality.
The other "progression" is the succession of the lowest notes. This is the bass line; in root position chords, the bass note coincides with the chordal root. (Statistically, this occurs for about 70% of the chords, according to a few articles I have read.) When all chords are in root position, the music can tend to become stagnant (boring). When the third of a chord (E in a C major chord)  is in the bass, the chord sounds different but functions similarly.
Comment: Thank you very much for responding to my question.  Much appreciated!  Apologies for not making the question clearer....
Answer: I'm guessing - just that, the question means why use different inversions of a particular (here C) chord in their playing/works.
With C at the bottom, it's a root position, and sounds very solid and grounded. In 2nd inversion, it still sounds pretty solid, whereas in 1st inversion, a little unstable. But that actually works in its favour if the next chord is root F, as the bass leads up from E to F. One reason it's called a leading note, in this example, not of key C but key F. So voicing can play a big part in which inversion gets used.
It's also dependant on what the melody may be - some inversions work better than others. Also using root with every chord change can get pretty tedious to listen to. There's also the fact that a bass instrument may be looking after the root, so on piano or guitar, it gives the opportunity to vary what would otherwise be a boring (quoting ttw) accompaniment.
Of course, this may be not what the question is asking, in which case, forgive me, and make it a tad clearer!
Comment: Thank you very much for the feedback!  Much appreciated!  Apologies for not making the question clearer.
Answer:
I've seen a few composers write in this manner - first chord C in root position (CEG) followed by A in first inversion - (CAE) with the C in the bass written an octave apart from the C of the previous chord and then followed by D#. Are there any reasons for writing the harmony this way?

First, those are C♯s and G♯s, not Cs and Gs.  Also note that the chord changes on the third beat, so the D♯ is the bass of a first-inversion B major chord, D♯-F♯-B.
But to answer your question, at the time this music was written the modern theory of inversions was in its infancy and had been rejected by many of the composers who were active when it was first published, J. S. Bach among them.  The driving force in this music is melody and counterpoint.  Harmony is definitely present, of course, but the reason for writing the piece this way is that the composer wanted a bass line that falls an octave and then moves up a whole step and then a half step.
(Looking at the bigger picture, the bass line is characterized by repetition of a small number of three-beat patterns at various pitch levels, and one of the patterns comprises three quarter notes ascending by step.  The octave drop is necessary to keep the bass part in the desired range; had the A in the bass been an octave lower, the C♯ would most likely have been repeated in the same octave instead.)
A common way to harmonize stepwise motion in the bass line was known as the "rule of the octave."  This "rule" is more of a guideline, and you can find several variants of it.  It allows the composer or continuo player to avoid the parallel fifths that would result if every bass note were to be harmonized in root position.  Typically most of the chords are 6 chords, which in the descending version are often decorated with 7-6 suspensions.  In the ascending version, the analogous approach yields a sequence of alternating 5/3 and 6/3 chords, or, in modern terminology, alternating chords in root position and first inversion.
In this case it's not even clear that the given figuration is correct, as the A and G♯ in the first beat are both arguably ornamental; you could argue for either one being the "true" chord tone there.
Comment: Thank you very much!  This is the answer that I was looking for.  Much appreciated for the corrections and the answers.  Apologies to everyone for not making the question clearer in the first place.
Answer: When playing a chord, the note at the top tends to me more prominent.  So in a triad in C, C-E-G, the G is more readily heard than the C or E.  If the chord is inverted, then C becomes the top note, and dominates. (For that reason, if I intend to end a piece on a chord, I will often choose the first inversion of the tonic.)
There's another pragmatic reason to use inversions - to keep the accompaniment and melody a suitable distance apart.  If the accompaniment drifts too high, it crashes into the melody and you end up trying to play the same notes in both hands at the same time.  If the accompaniment drifts too low, it sounds muddy.  You can find that one triad crashes into the melody, while a triad an octave below sounds bad.  In that case, a solution is to switch to an inversion of the chord to find a nice place between those two. (You can also cheat and use one of the notes in the melody to complete a chord in the accompaniment.  For example, if you decide that a G needs a C chord, play the C and E only in one hand, and the G from the melody completes the chord.)
Comment: "If the chord is inverted, then C becomes the top note, and dominates": Inversion is determined only by the bass note.  The top note can be C in any inversion. (In three voices, however, in root position, then either the third or the fifth must be omitted for both the bass and top voice to have C.  But three-voice part writing typically has many incomplete chords.)
Comment: For example, the first movement of Beethoven's Moonlight Sonata ends with a root position C-sharp minor chord with C sharp as the highest pitch, and the final chord of Bach's mass in B minor is a D-major chord in root position with the highest pitch being a D.
Comment: The 3rd sentence is slightly misleading. Cleared up partially in the 4th, but could be more clear. Probably the reason for dv.


Using Glusterfs Dist-Replica Storage Pool for Hyper-V Virtual Machine Storage

Question: Am chasing down some information regarding an upcoming project.
So Basically we have a large Glusterfs Dist-Replica Storage pool running on ubuntu and we want to have several virtual machines running off this from our windows 2012 server,
Now we are using Hyper-V to run the Virtual machines and so far I am having a bit of trouble getting the VHDX to actually create on the Gluster Storage pool.
I've created a mount point with Gluster and have tried to share it out with Samba yet it would never create the VHDX or run an existing one on the cluster as it continously would throw errors like: Error Incorrect Function on the hypervisor.
Changed Permissions, Allowed Anon access, Made sure it could RW etc etc still would not allow any VHDX to be created.
Then Tried to share it out with NFS and the Hyper-V when creating a VM would throw out errors like this:
File System limitation
Found out this is rather common:
https://slog.starwindsoftware.com/hyper-v-vms-on-nfs-share/
So I'm curious if anyone out there does have Hyper-V Virtual machines running on Glusterfs and if so how you got it configured?
Any information at all would be fantastic :)
On a side note please let me know if anyone has used VMware with Samba/NFS and if this performed better than Hyper-V.
Thanks team
Answer: Hyper-V can do SMB3 and iSCSI while SMB3 is clearly preferred: CSVFS is a joke compared to VMFS5, Microsoft has no scalable clustered file system so has to use network redirector crutches.
VMware can do NFS and iSCSI pretty much same way: proper configuration will saturate network.
P.S. We prefer to use VMware with NFS only because it's easier to configure though.
Answer: If you want to use file-based storage (a file server of one kind or another), Hyper-V requires that the protocol be SMB 3.0 or later.  NFS isn't supported.
If you can expose an iSCSI LUN from Gluster, that would work, too.


Probability of orthogonal vectors.

Question: If I pick two uniformly random vectors over integers
$$(a_1,\dots,a_{n}),(b_1,\dots,b_{n})\in[-m,m]^n\cap\Bbb Z^n$$ what is the probability that
$$\sum_{i=1}^na_ib_i=0$$ holds?
Comment: @JohnBentin integers.
Comment: By $[-m,m]$, do you mean an interval in $\Bbb Z$ or an interval in $\Bbb R$ ? In the latter case, the probability is obviously zero.
Answer: The orthogonal space of a line given by a vector is a hyperplane, and such a hyperplane has measure $0$ over the ambient space, so I would say such a probability is $0$. Just notice that given a direction, the quantity of other directions that are orthogonal to the first is very tiny compared with all the possible directions.
Answer: For $n=1$ the probability is zero if your vectors are independent, because:
\begin{align*}
  P(a_1b_1 = 0) &= P(\{a_1 = 0\} \cup \{b_1 = 0\})\\
  &= P(a_1 = 0) +  P(b_1 = 0) - P(\{a_1 = 0\}\cap \{b_1 = 0\})\\
  &= P(a_1 = 0) +  P(b_1 = 0) - P(a_1 = 0)P(b_1 = 0)\\
  &= 0.
\end{align*}
You could try to do the same with induction for any $n \in \mathbb{N}.$

Probability of orthogonal vectors.


Interactive App: Make sure certain output is found every 30 minutes

Question: So, due to some very poor design choices I'm stuck with a complex and unreplaceable interactive console application running forever on a Debian machine.
This apps does some tasks, repeatedly, and returns to stdout results like:
InvetoryOpt: Finished
PBridged: Finished
FLoot: ERROR

I need to make sure that every x minutes I get the string InvetoryOpt: Finished on the output of the program. If not I need to kill it, run other a script, start the program again and the check.
How may I accomplish this? I was thinking about expect but I don't have much experience with with and I'm not sure I'm able to check if output matches string every x minutes.
Notes:

The program also outputs lots of other garbage that I don't care about;
The program can output the same string InvetoryOpt: Finished multiple times in 30 minutes or just don't output anything at all. So tailing the end of a file won't do it because it would match the last output of that string.

Thank you.
Comment: `expect` seems a good fit here.
Comment: @alexus can you point me to some examples of people accomplishing what I need? Or similar things?
Comment: I would run the app inside of `tmux` to make it easier to watch what his happening.
Answer: You can use the script below as a wrapper-controller. I assume bash is known, so no technical comments. I can add them if you want them.
The variables PROGRAM and OTHER_SCRIPT for the script you mentioned need to be defined.
The time control is rigid, ie. it doesn't reset the countdown to the last InvetoryOpt: Finished message time, just checks every 30 mins. I can think of a way to improve this if you need it.
UPDATE: Trap added.
#!/usr/bin/env bash

trap '
kill %1
rm $OUT
exit
' 2

#provide the program command below
PROGRAM=
#provide the other script below
OTHER_SCRIPT=
PHRASE="InvetoryOpt: Finished"
INTERVAL=1800
OUT=/tmp/out$$

message () {
    echo "$(basename "$0")": "$1"
}

start_app () {
    eval "$PROGRAM | tee $OUT &"
}

action () {
    if ! grep -q -e "$PHRASE" $OUT
    then
        message "Check failed. Restarting." >&2
        kill %1
        eval "$OTHER_SCRIPT"
        start_app
    else
        message "All fine."
    fi
    > $OUT
}

start_app
while true
    do {
        sleep $INTERVAL
        action
    }
    done


I want to learn the sax. Where should I start?

Question: I do not have any prior musical training. I do not know how to read music.
The only instrument I have played are a keyboard and a harmonica. I think I can learn the saxophone if I remain as passionate as I am now, but I seek advice first because buying a saxophone is a costly affair.
Does learning a saxophone involve a very steep learning curve? I know most people start playing in their school-days. Is it too late for me to start? (I am 22)
I really want to play like David Sanborn some day.
All suggestions are welcome!
Comment: It's never too late to learn music :)
Comment: I started learning clarinet in my 30s, together with my kids. Soon I got a sax too. As long as you 1. get a teacher and 2. practice often you can learn anything you want. OK you may not make it to Carnegie Hall, but you can jam with your mates. These days I play with 2 big bands and people pay to get in! It's never too late to start. Start with a used or borrowed instrument - your teacher may help you here.
Answer: As has been said so many times - get a good teacher - at least for a while. I believe anyone can learn to play an instrument by themselves - if they live long enough !! A teacher will guide you to a suitable sax, be it soprano, alto tenor or baritone (quite expensive). Watching videos and using tutor books is good, but they won't answer a question you suddenly come up with while you're playing. A teacher will.
Some music schools will let you rent an instrument which can eventually be bought. You should go to music shops and talk with the guys there about your dreams - they have lots of experience playing, and maybe know a person to point you to.
Learning to play an instrument and learning to read music are two different skills, and I always advocate getting to know the instrument and making sounds with it well before starting to correlate dots to fingering.
No, even in retirement it's never too late. Just make the time to practise and play.It's worth the effort !
Comment: I'd also add the very usual: a teacher will tell you what you do wrong. This is especially important in the early stages of learning, where you have to learn how to *produce sound*: how to take your mouthpiece, how to "hit" the reed with your tongue — you don't want bad habits there, and with a saxophone, it's easy enough to "force" sound just by blowing harder. Plus they'll tell you when you need to switch to harder reeds, help you find the right mouthpiece. When you want to buy an instrument, they can even try them for you — because a good serial number never guarantees a good instrument.
Answer: Even if the question has an accepted answer I would like to leave my answer to tell you about my encouraging experience with the saxophone.
I never had any musical education but that didn't stop me from buying a Xaphoon In July 2006. I played the thing by ear for a few months. It was dreadful at start but the sound got better sounding after 6 months. Around this time (Feb 2007) I met a sax player at a party and asked him if he would give me some classes which he did; and after trying a Tenor and a Alto sax I bought myself a Alto saxophone: a beautiful copper coloured Jupiter Colorado (I don't mean to publicize it but I'm so proud of it still today that I cannot resist... :-) Note that at this point I still had no musical education but had some money to spend on it and definitely a huge willingness to learn music and how to play it.
A couple of months after starting these classes I realized that to play by hearing it, would require much more time practicing than I could afford so I decided to join a music academy where I started learning music and the instrument. This was September 2007.
Three years later (August 2010) I was doing this, and 2 more years on there was some improvement... :-) The video is the same but the sound track was replaced by a more recent one and I guess you can tell the difference (also the recording equipment was much better). Today, two years after that last recording I feel I have progressed even further and all of it was due to a great, great teacher (see Tim's answer ;-). I have also started composing a few pieces and harmonizing them.
Oh, and in 2014 I'm 43 so I started with 36 and to me being 22 is probably what you refer to as "school days"!!! ;-)
Answer: To learn to play the saxophone, you just need to get your notes and hearing right. Practice with a lot of sample notes and before you know it, you are developing speedily. Check out saxophonist who started to play just three months back.


Add static route to AWS VPC

Question: I have a VPC 10.0.0.0/16. It has subnetwork 10.0.4.0/22. In that subnetwork i have openvpn server with clients in 10.8.0.0/24. How can i add a route to my openvpn clients from ec2 instances. I need that my servers in 10.0.4.0/22 can connect to openvpn clients to 10.8.0.0/24. Something like this:
<code>route add -net 10.8.0.0/24 via 10.0.4.23
</code>
(ip of my openvpn instance is 10.0.4.23)
How can i do it in aws console? Should i reboot instances after changes to obtain new route?
Answer: You need to add a route pointed at the VPN concentrator's ENI. You also need to disable SRC/DST check on the VPN instance.

Add static route to AWS VPC


How to add a block to a region in html.tpl?

Question: I'm using Drupal 7.
I have a custom template html--custom.tpl.php.
I have a custom block that contains the main menu. This block is enabled in the header region of block admin.
Up to this point, everything but the menu block prints.
How can I print the custom block in the header region of the html.tpl file?
Answer: You should make a new theme region similarly to how the header section works and add your block through the block admin into your new region. Rather than trying to get a block to come out in any other way
See this for more: https://www.drupal.org/docs/7/theming/assigning-content-to-regions


PHP PDO foreach or while in slider?

Question: I have the following code:
I'm trying to mix a jquery slider, with some php and mysql to retrieve the slider images from a database and all its info.
It connects sucessfully but I could only retrieve just 1 row, from the results and I need to retrieve at least 6 rows... I can't just duplicate the number of slides no matter what. Yes, I've tested the slider with local values and it works perfect
I'll be appreciated for any help here.
PD: One of my errors, could be bad formatted HTML, after  tag

   <?php
   function getContent() {
    try {
       $handler = new PDO('mysql:host=127.0.0.1;dbname=xx', 'xx', 'xx');
       $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     } catch(PDOException $e) {
         echo $e->getMessage();
         die();
     }
     $sql = "SELECT * FROM homeslider ORDER BY id DESC LIMIT 6";
     $query = $handler->prepare($sql);
     $query->execute();
     $row = $query->fetchAll();
     return $row;
   }
   ?>

                <?php
             $data = getContent();
             foreach ($data as $row) {
             $id = $row['id'];
             $titulo = $row['titulo'];
             $descripcion = $row['descripcion'];
             $link = $row['link'];
             $imgurl = $row['imgurl'];
             $ultimo_update = $row['ultimo_update'];
                }

                echo'

               '.$titulo.'
'.$descripcion.'Leer más

         ';?>

SK-Servicios.com

Comment: WHY ALL CAPS IN TITLE?
Comment: a var dump of data? a var dump inside the function after the fetch?
Comment: Move the echo statement inside your foreach loop
Comment: how can i do that? it giving me headaches!! thank you!!
Answer: Move the echo statement inside the foreach() loop
   <?php
$data = getContent();
foreach ($data as $row) {
 echo '

';
   $id = $row['id'];
   $titulo = $row['titulo'];
   $descripcion = $row['descripcion'];
   $link = $row['link'];
   $imgurl = $row['imgurl'];
   $ultimo_update = $row['ultimo_update'];
 }

 echo'

 '.$titulo.'
'.$descripcion.'Leer más

';?>

Comment: Hello, thank you for your interest to help me, it worked partially, as last favor, what could i've done wrong here? It looks like this  http://prntscr.com/5iingl THANK YOU!!!
Comment: Sorry for bothering you, its looking much better now, the only problem is... http://prntscr.com/5iisht

THANK you, really, im appreciated!
Comment: I cant see the problem, are you using a layout frame work e.g. Bootstrap, JQueryUI?
Comment: Hello, im using bootstrap 3.2.0 and jquery 1.9.0 loaded in that order.

Thank you for your interest!
Answer: change your loop like this
<?php
 $data = getContent();
         foreach ($data as $row) {
         echo '

';
         $id = $row['id'];
         $titulo = $row['titulo'];
         $descripcion = $row['descripcion'];
         $link = $row['link'];
         $imgurl = $row['imgurl'];
         $ultimo_update = $row['ultimo_update'];
            echo'

           '.$titulo.'
'.$descripcion.'Leer más

     ';
     }

?>

Comment: Hello, thank you for your interest to help me, it worked partially, as last favor, what could i've done wrong here? It looks like this  http://prntscr.com/5iingl THANK YOU!!!

PHP PDO foreach or while in slider?


What exactly is react-native upgrade command doing? particularly to the gradle files?

Question: I want to understand what the react-native upgrade command is doing, it sometimes changes the gradle files:

android/app/build.gradle
android/settings.gradle

Why does it asks if I want to Y/N to update does files? If I keep answering No is this gonna have bad impact on the application?
Comment: It's upgrading your project to the new RN version. For example, if new RN version is using higher Android SDK version, gradle file will be updated to the new version. This upgrade should be pretty safe, as it's performed using git, so in the worst case you will have a conflict but your code won't be harmed ofc.
Answer: The upgrade command is intended to run after updating RN version in existing projects (and after running npm install so the new version is in your node_modules).
Essentially, the command copies all files from the app template which is used to initialize a new RN app. The template is what you get when you run the react-native init command. This is also the reason why it needs to run after the new RN version is installed, because the templates app comes with the react-native dependency itself.
The reason that it asks you if you want to replace each modified file is that it doesn't know why the content has changed. It's possible that you made changes to a file yourself after you initialized your RN app.
If you haven't made any changes - it is safe to replace the existing files; it would be as if you got the file after initializing a new RN app. If you did modify a file - I think that you'd still like to see what changes were made in the new version (they can sometimes be required), in this case you can approve the replace (assuming that you're using source control...) so you can review the changes and in the worst case you can reset them if they're not necessary.
Alternatively, you can use React Native Git Upgrade which can help you resolve conflicts more easily.


Geometric reason for 3/4-power growth rate?

Question: It seems pretty well established that organisms grow
according to a 3/4-power law.
For example,
Niklas and Enquist, in their paper
"Invariant scaling relationships for interspecific plant biomass production rates and body size,"
PNAS 2001, 98(5):2922
-2927, say:

Annualized rates of growth $G$ scale as the 3/4-power of body mass $M$
  over 20 orders of magnitude of $M$ (i.e., $G \propto M^{\frac{3}{4}}$).

Does anyone know if there is some geometric reason to expect such
a growth-rate law?
$$\frac{d M}{d t} \sim M^{\frac{3}{4}}$$
Apparently attempts to derive this growth-rate law from
Kleiber's Law, which
claims that metabolic rate scales
as $M^{\frac{3}{4}}$, are controversial.
So I was wondering if there might be some geometric viewpoint
that makes growth proportional to $M^{\frac{3}{4}}$ not unexpected.
Comment: Interesting topic! There's an accessible discussion of the geometry here: http://mathbench.umd.edu/modules/misc_scaling/page18.htm
Comment: The literature of allometric growth rates is littered with geometric descriptions of rates that ended up not being supported by data.  It looks like it's easy to come up with an explanation but hard to know that your explanation is right.
Comment: @minopret: Thanks for the useful link!  Note that those pages focus on *metabolism* rate, rather than *growth* rate, but there is a (conjectured) connection.
Answer: h=height, M=mass, A=cross-sectional area of stem d=density of stem V=volume of plant
The total cross-sectional area of a plant remains roughly the same at the top as at the bottom. (Da Vinci's rule).
Plants collect light for photosynthesis along their cross-sectional area.
The thickness of stem A needed to support a plant is proportional to $h^3$.
$A\propto h^3$
$M = Ahd$
$A \propto M^{3/4}$
growth rate $\propto$ area exposed to the sun for photosynthesis $\propto \frac{V}h \propto A$
Comment: Why is the thickness of stem $A$ needed to support a plant proportional to $h^3$?  That seems to be the key step, but I am not seeing the logic behind it...
Comment: Nice! $\mbox{}$


How do i put a condition for matching the above requirement

Question: I have a table designed this way

mysql> select * from categories limit 50;
+-------------+-------------+-----------------+------------+------+------+------+------+------+------+------+
| category_id | T1          | T2              | T3         | T4   | T5   | T6   | T7   | T8   | T9   | T10  |
+-------------+-------------+-----------------+------------+------+------+------+------+------+------+------+
|           1 | Popcorn     | Regular Pack    | NULL       | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
|           1 | Popcorn     | Regular Pack    | NULL       | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
|           1 | Popcorn     | Regular Pack    | NULL       | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
|           2 | Popcorn     | Bucket          | NULL       | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
|           2 | Popcorn     | Bucket          | NULL       | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
|           2 | Popcorn     | Bucket          | NULL       | NULL | NULL | NULL | NULL | NULL | NULL | NULL |

|           7 | Soft Drinks | Fountain        | Apple      | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
|           7 | Soft Drinks | Fountain        | Apple      | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
|           8 | Soft Drinks | Fountain        | Orange     | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
|           8 | Soft Drinks | Fountain        | Orange     | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
|           9 | Soft Drinks | Fountain        | Lemon      | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
|           9 | Soft Drinks | Fountain        | Lemon      | NULL | NULL | NULL | NULL | NULL | NULL | NULL |

I need to map the data of the above table .
a sample xml file , just to repersent structure
For example ,
Under Popcorn i must have  Regular Pack , Bucket
And under Soft Drinks i must have  Fountain ,  and  under Fountain  i  must have different categories Apple ,Orange and Lemon
 <Popcorn>
    <Popcorn items>
     < Regular Pack>
     <Bucket >
    </Popcorn items>
    </Popcorn>

    <Softdrinks>
    <Softdrinks items>
    <Fountain>
<Fountain items>
    <Apple>
    <Orange>
    < Lemon>
</Fountain items>
    </Softdrinks items>

Once i retrive the values , how to put a condition that matches the above requirement ??
A psecoude code will be also sufficient for me to proccedd
while(rs.next())
{
  String T1 = rs.getString("T1");
  String T2 = rs.getString("T2");
  String T3 = rs.getString("T3");
  String T4 = rs.getString("T4");
  String T5 = rs.getString("T5");
  String T6 = rs.getString("T6");
  String T7 = rs.getString("T7");
  String T8 = rs.getString("T8");
  String T9 = rs.getString("T9");
  String T10 = rs.getString("T10");
}

Comment: Is this possible to do ??
Answer: According to me

You need to get two different resultset for this by quering like this

select DISTINCT T2 from tabelName where T1='PopCorn'; and
select DISTINCT T2 from tabelName where T1='SoftDrink';

You better use PreparedStatement for this and ps.setString(0,"PopCorn");
Apply same thing for T2 and T3.
Now you will have RegularPack and Bucket after first query and Fountain after second and than use these values as you want to.
Comment: hey really thanks for this , now i could take some break and start with your logic . Thanks once again .


Custom access method for a Page Manager page

Question: I've created a page using Page Manager, at the route /project/(node}/attendance.
I need to add a custom access check on it, comparing information about the current user with the node to see if they should have access.
I have added a route subscriber, but when I loop through the route collection, my route does not appear. I have read that this is because pages added through the page manager are they themselves nodes.
Is there a way to add a custom access method to a Page Manager route?
Answer: The module already allows you to create Condition plugins by extending the ConditionPluginBase class.
There is an evaluate() method that you can put your logic in.
This plugin will be available then under the Page manager UI under "Page access" menu:
Answer: So, what I ended up doing is extending the Page Manager PageAccessCheck service:
services:
  custom_route_access.page_access_check:
    class: Drupal\custom_route_access\Entity\PageAccessCheck
    tags:
      - { name: access_check, applies_to: _page_access }

And then:
<?php

namespace Drupal\custom_route_access\Entity;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityAccessCheck;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\Routing\Route;

/**
 * We're overriding the page access checks so that we can add our own.
 * Mimics the generic entity access but with a custom key to prevent collisions.
 */
class PageAccessCheck extends EntityAccessCheck {

  /**
   * {@inheritdoc}
   */
  public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account) {

    // Backup the original requirements.
    $original_requirements = $route->getRequirements();

    // Replace it with our entity access value and run the parent access check.
    $route->setRequirement('_entity_access', $route->getRequirement('_page_access'));
    if($route->getPath() === '/project/{node}/take_attendance'){
      return self::takeAttendanceAccess($account);
    }
    $access = parent::access($route, $route_match, $account);

    // Restore the original requirements.
    $route->setRequirements($original_requirements);

    return $access;
  }

  /**
   * Check that user is admin or staff OR has an active team leader registration.
   */
  private static function takeAttendanceAccess($account){

    // ... my custom access check code
  }

}

Comment: You could also create Condition using the Drupal\Core\Condition\ConditionPluginBase and use it under "Access" tab on the Page manager UI.


Default to 'this display' when editing views

Question: I am working on a display of a view I have. I want to make changes that apply only to the display that I'm working on; however the various editing widgets (relationships, filters, fields, etc) keep defaulting to apply to all displays. For the most part I remember to change it to "this display", but sometimes I don't, and I end up changing all displays.
Is there a way to change the default application to "this display"? Or have views remember which I chose?
Comment: Not that Im aware of, Im afraid this is the default behaviour. I often catch myself out by not selecting "This block override". :-(
Comment: Actually - Breaking the default behaviour for the very first display when you create a new view would mean that every new display you add would have its own settings for filters etc. You would just have to remember to do this everytime you add a view.
Comment: @Collins Since "No" seems to be the answer, can you post that as an answer? Then I will accept it : )
Answer: Not that Im aware of, Im afraid this is the default behaviour. I often catch myself out by not selecting "This block override". :-(
But actually - Breaking the default behaviour for the very first display when you create a new view would mean that every new display you add would have its own settings for filters etc. You would just have to remember to do this everytime you add a view


Ajustando saida de dados em C

Question: Gostaria que a saida mostrasse a tabuada de cada operação de lado a lado, e não uma embaixo da outra(que é a forma que ta imprimindo). Eis o codigo:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main()
{

  int i, num, rsoma, rsubtracao, rmultiplicacao;
  float rdivisao;

  i = 1;
  printf("Informe um numero inteiro: \n");
  scanf("%i", &num);
  printf("Adição\n\n");

  for ( i = 1; i < 11; i++)
  {
    rsoma = num + i;
    printf("%i + %i = %i\n", num, i, rsoma);
  }

  printf("\nSubtração\n\n");
  for ( i = 1; i < 11; i++)
  {
    rsubtracao = num - i;
    printf("%i - %i = %i\n", num, i, rsubtracao);
  }

  printf("\nMultiplicacao\n\n");
  for ( i = 1; i < 11; i++)
  {
    rmultiplicacao = num * i;
    printf("%i x %i = %i\n", num, i, rmultiplicacao);
  }

  printf("\nDivisao\n\n");
  for ( i = 1; i < 11; i++)
  {
    rdivisao = (float)num / i;
    printf("%i / %i = %.2f\n", num, i, rdivisao);
  }

 return 0;
}

Comment: Substitua este \n (nova linha) do printf por um \t (tabulação).
Answer: Segue um exemplo conforme solicitado, utilizando \t (tabs):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main()
{
    int i, num, rsoma, rsubtracao, rmultiplicacao;
    float rdivisao;

    i = 1;
    printf("Informe um numero inteiro: \n");
    scanf("%i", &num);
    printf("Adição\t\tSubtração\t\tMultiplicação\t\tDivisão\n\n");

    for ( i = 1; i < 11; i++)
    {
        rsoma = num + i;
        rsubtracao = num - i;
        rmultiplicacao = num * i;
        rdivisao = (float)num / i;
        printf("%i + %i = %i\t%i - %i = %i\t\t%i x %i = %i\t\t%i / %i = %.2f\n", num, i, rsoma, num, i, rsubtracao, num, i, rmultiplicacao, num, i, rdivisao);
    }

    return 0;
}

Answer: Seria algo desse tipo, em C é complicado poder dar um "float" na resposta, porem a solucao é essa
 #include
    #include
    #include
int main()
{

  int i, num, rsoma, rsubtracao, rmultiplicacao;
  float rdivisao;

  i = 1;
  printf("Informe um numero inteiro: \n");
  scanf("%i", &num);
  printf("Adição\n\n");

  for ( i = 1; i < 11; i++)
  {
    rsoma = num + i;
    printf("%i + %i = %i\n", num, i, rsoma);
  }

  printf("\nSubtração\n\n");
  for ( i = 1; i < 11; i++)
  {
    rsubtracao = num - i;
    printf("%i - %i = %i\n", num, i, rsubtracao);
  }

  printf("\tMultiplicacao\n\n");
  for ( i = 1; i < 11; i++)
  {
    rmultiplicacao = num * i;
    printf("\t %i x %i = %i\n", num, i, rmultiplicacao);
  }

  printf("\t Divisao\n\n");
  for ( i = 1; i < 11; i++)
  {
    rdivisao = (float)num / i;
    printf("%i / %i = %.2f\n", num, i, rdivisao);
  }

 return 0;
}

Ajustando saida de dados em C


three singular points

Question: I am trying to prove the following:

Let $F$ be homogeneous polynomial of degree $3$ in $k[X, Y, T ]$ where $k$ is algebrically closed field. Assume that $V(F)$ has three
  distinct singular points. Show that $V (F )$ is the union of three lines.

Any help will be great!
Answer: Given $F$ is a degree $3$ homogeneous polynomial. We will consider the following possibilities for $F:$
(1) $F$ is irreducible; (2) $F=fg,$ where $f, g$ are distinct irreducible homogeneous polynomials of degree 1 and 2 respectively; (3) $F=fg^2$ where $f,g$ are distinct irreducible homogeneous polynomials of degree 1; (4) $F=fgh,$ where $f,g,h$ are distinct irreducible homogeneous polynomials of degree 1; (5) $F=f^3,$ where $f$ is a homogeneous polynomial of degree 1.
Now the condition that $V(F)$ has exactly three distinct singular points immediately rules out the cases (1), (3) and (5). For the case (2), $V(F)$ is a union of a line and a conic in $\mathbb P^2.$ So the number of possible singular points are $\leq 2.$ This leaves the only possibility:(4).
Comment: Could you explain why you eliminate the cases 1,3 and 5. Thank you very much..
Comment: For case (1), it is a smooth hypersurface in $\mathbb P^2.$ For case (5), it is a hypersurface in $\mathbb P^2,$ but it is singular (for example, the hypersurface given by $x^3=0$). Similar argument for the case (3) also (for example, $F=xy^2$).

three singular points


"not a git repository" ao executar git add

Question: Estou tentando executar git add . mas recebi o seguinte erro:
fatal: not a git repository (or any of the parent directories):

Como resolvê-lo?
Comment: Você precisa primeiramente dar inicio ao repositório com o comando ```git init```.
Comment: Você está fazendo o upoad de suas alterações para um repositório, correto? Como você pegou os fontes?
Answer: O erro indica que não há repositório git no seu projeto.
Para resolver este problema basta roda o seguinte código:
> git init

A partir deste momento você pode realizar os commits do seu projeto com os seguintes comandos:
Atenção: Certifique-se que seu projeto tenha algum arquivo.
> git add .
> git commit -m "Mensagem de commit"

Os passos seguintes dependerão do seu objetivo, caso queira colocar seu projeto em um repositório online como o GitHub realize as seguintes configurações alterando os valores dentro da chave para o seu link do github e removendo as chaves:
> git branch -M main

> git remote add origin [URL DO REPOSITÓRIO AQUI]

O seguinte comando empurrara os arquivos para o repositório:
> git push -u origin main

Comment: Obrigado. Funcionou perfeitamente!


How to correctly assess the correlation between ordinal and a continuous variable?

Question: I'd like to estimate the correlation between:
An ordinal variable: subjects are asked to rate their preference for 6 types of fruit on a 1-5 scale (ranging from very disgusting to very tasty) On average subjects use only 3 points of the scale.
A continuous variable: the same subjects are asked to quickly identify these fruits, which results in an mean accuracy for the 6 fruits.
Is Spearman rho the best method to analyze these data and/or are there other good methods I could consider?
Comment: Welcome to the list.  The ordinal variable looks like it is actually 6 variables (one for each fruit). It's also not clear to me how the identification variable is created, nor that it is continuous.
Comment: Thanks thats quick! So for each subject I indeed have 6 preference ratings, and 6 accuracy ratings. Accuracy is the mean hitrate over 16 identification trials (16 for each type of fruit). A hit is when they select the right fruit, miss is when they select the wrong type of fruit. Hope that this made it more clear.
Answer: You could use Spearman's, which is based on ranks and therefore OK for ordinal data. You would then have six results.
If you want to take a different approach, you could get complex and look at a multilevel model, with subject being repeated. It sounds like "accuracy" would depend on "preference". So, a mixed model could look at that and account for the non-independence of the data. But, as noted, that's a much more complex model to implement.
Answer: According to this paper* "Measures of Association: How to Choose?" (doi:10.1177/8756479308317006), you should consider kendall's tau-b if the number of items in your ordinal variable is low (<5 or <6 ... this is a bit arbitrary).
If you have a large number of items in your ordinal variable, Spearman correlation would work well.
*the paper may be behind a paywall. But I tried to summarize the essence in my post.