Estimating the parameters of a Beta distribution using the sample average and standard deviation

Question: This is a simple question, but I just want to be sure.
Imagine that we have a sample of $n$ data $\{x_1, \dots, x_n\}$ and that we want to fit them to a Beta distribution. Imagine that we have calculated $\bar{x}$ and $s_{n-1}$ (or simply $s$), where
$$
\bar{x}= \frac{\sum_{i=1}^n{x_i}}{n}
$$
and
$$
s= \sqrt{\frac{\sum_{i=1}^n{(x_i - \bar{x})^2}}{n-1}} \text{.}
$$
I think that we can estimate the parameters $\alpha$ and $\beta$ of the Beta distribution by $\hat{\alpha}$ and $\hat{\beta}$, respectively, where the values of $\hat{\alpha}$ and $\hat{\beta}$ are obtained from the following equations:
$$
\bar{x} = \frac{\hat{\alpha}}{\hat{\alpha} + \hat{\beta}} \quad,
\quad
s^2 = \frac{\hat{\alpha}\hat{\beta}}{(\hat{\alpha} + \hat{\beta})^2(\hat{\alpha} + \hat{\beta}+1)} \text{.}
$$
Am I right?
Answer: This is (a version of) method of moments.
It's certainly possible to estimate parameters this way, though it may not be as efficient as some other estimators.
Note, however, that if you want a four-parameter beta, rather than one on (0,1), things are more complicated.
In the case in your question you can simplify the calculations; note that $\frac{\bar{x}(1-\bar{x})}{s^2}=\hat{\alpha}+\hat{\beta}+1=\hat{\alpha}(\frac{\hat{\beta}}{\hat{\alpha}}+1)+1$,
and $1/\bar{x}=\frac{\hat{\beta}}{\hat{\alpha}}+1$.
From there we can readily obtain an equation just in $\hat{\alpha}$; once you have that you can immediately find $\hat{\beta}$.
Comment: (i) Method of moments can certainly be biased, (maximum likelihood usually is as well), but that's not what I was getting at; I referred to *efficiency*, not bias. (ii) No, method of moments is *not* equivalent to maximum likelihood in general, and in the case of the beta they're certainly different.
Comment: So, @Glen_b, do you mean that this estimation (the method of moments in this case) can be biased? I thought that it was somehow equivalent to the maximum likelihood method, in this case of the Beta distribution.
Comment: I've seen an explanation of the MLE method for the parameters of a Beta distribution here: http://www.math.uah.edu/stat/point/Likelihood.html#bet, which also refers to a nice simulation experiment, but it deals with the case in which either $\alpha$ or $\beta$ are supposed to be known. Then I've seen this link: https://en.wikipedia.org/?title=Beta_distribution#Two_unknown_parameters_2 . There I read that I can numerically solve a 2-equation system (this one: https://upload.wikimedia.org/math/6/9/5/695e9b843d07f239ed9b833951c08818.png) in order to get the MLE of $\alpha$ and $\beta$. [...]
Comment: [...] Did I understand it right?  Now, my question is: Do statistic software such as Statgraphics use MLE methods in order to estimate parameters?
Comment: I answer my last question in the previous comment. According to a help document in Statgraphics, _"Estimates are obtained using Maximum Likelihood Estimation (MLE)"_ (in the context of parameter estimation and distribution fitting  of uncensored data). So, thank you, @Glen_b, for your answer, which gave me some information I didn't know/remember and made me think and do some extra research.  ;)
Comment: The Wikipedia page on the Beta has a section that [discusses finding the MLE](https://en.wikipedia.org/?title=Beta_distribution#Two_unknown_parameters_2) that's reasonably clear, though parts of it might be new to you.


Got 6 hours for rendering one frame in blender, What am I doing wrong?

Question: I'm new to blender, after creating an animation, I want to render it. With the help of a large number of guides on the Internet, I think, I got the optimal animation rendering settings, as a result, but  the beginning of the animation rendering I get 6 hours to render only 1 frame.
A computer:
RTX 3050 Ti 4gb
Ryzen 7 5800
16gb RAM
Settings:

I realize that the problem is in my settings, but I do not understand where.
Also, for some reason, when rendering 1 picture, the entire background I created change to orange due to technical error:
View in blender:

After render:

Thank you a lot for your time, I would really appreciate your help
(Im using Blender 3.4)
Answer: To reduce the render time make sure you head onto Edit > Preferences > System in that make sure you have CUDA enabled in Cycle render services. And for the change in background, that can be caused by some bug. So, upgrade your Blender to at least 3.8, because that's more stabler the its previous ones. Also make sure you have all the dependcy files(.dll) fixed and your DirectX version is 11.


Explain eigenvalues of a distance/cost matrix

Question: Assume there are N countries. The cost of making a phone call from country $i$ to country $j$ is $C_{ij}$. We know that all costs are non-negative.
(Q1) Can you think of a verbal interpretation of eigenvalues of the matrix $C_{ij}$?
(Q2) Does anything change, if we allow weights to be negative?
I am aware that an eigendecomposition of a transformation $T$ is given by $T = R^{-1}DR$, which means that, if a matrix were to be used as a transformation, it could be interpreted as rotation, scaling, and rotation back to the original basis. However, I'm not necessarily using my matrix to transform anything, so my intuition does not quite help
Comment: Is the cost calling from $i$ to $j$ is equal to the cost calling from $j$ to $i$?
Comment: @Lee if it helps you to make progress, you may assume it. Ultimately I'd love to have some intuition for both symmetric and non-symmetric matrices, but if you provide an intuition that works only for symmetric matrices I would also be happy
Comment: At least we know that sum of eigenvalues are determined by the sum of domestic call cost. And also the product of eigenvalues by the determinant, which I expect to be negative since the international calls are more expensive. Thus if we take only two countries, one eigenvalue must be positive and one negative
Comment: The largest eigenvalue correspond to a nonnegative eigenvector which likely has some nice interpretation (you can have a look at [eigencentrality](https://en.wikipedia.org/wiki/Eigenvector_centrality))
Comment: You may also be interested in looking at the eigenvalues of the graph Laplacian.
Comment: What do you mean by "I'm not necessarily using my matrix to transform anything"? Eigenvectors and eigenvalues are defined in terms of transformations, and one could argue that any matrix multiplication is effecting a transformation whether you interpret it as such or not. What's the context you're thinking about?
Comment: @rob3c I have nothing to add besides what is already written in the question. I have a matrix whose elements I know how to interpret. Now I want to know if I can find an interpretation of its eigenvalues.
Answer: You may want to take a look at eigenvector centrality. This states that the centrality of node $i$ is the weighted average of the centrality of nodes it is connected to:
\begin{align}
v_i &= \frac{1}{\beta}\sum_{j\in N}C_{ij}v_j\\
\implies \beta\vec{v} &=C\vec{v}
\end{align}
Thus the eigenvalue can be interpreted as the *inverse of the weights/frequencies that each node attaches to its neighbor's centralities. Mathematically, though, the eigenvalues determines the spectrum of the graph. Naively speaking, larger eigenvalues should correspond to more compact graphs (e.g. stars).
Comment: This was the only answer posted in the duration of the bounty - that is the main reason why I awarded the bounty here. But if somebody posts something more about this topic, I am certainly wiling to add another bounty and reward a new answer.
Comment: Thanks for your answer. I can see how this line of thought could lead to the answer I want. But at the moment it is too brief. Eigencentrality was already mentioned in the comments. From an answer I would expect a slightly more detailed explanation of eigencentrality and how it applies to this particular problem, as well as a demonstration and/or proof of the conclusions you have made


Erro na linha mysql_fetch_array

Question: Isto é um buscador de informações de universidades, meu TCC.
Este é o erro:

$mysqlli = new mysqli($servidor,$user,$senha,$banco);

if(mysqli_connect_errno()) trigger_error(mysqli_connect_error());
else
echo "sucesso";

//@mysql_select_db("faculdadesbd",$mysqlli);

?>

Unigle

    body{
        font-family:Verdana, Geneva, sans-serif;
        color:#333;
        font-size:12px;
    }

<?php
    if(isset($_POST['botao'])){
        $busca = $_POST['busca'];

        $busca_dividida = explode(' ',$busca);
        $quant = count($busca_dividida);

        for($i=0;$i<$quant;$i++){
            $pesquisa = $busca_dividida[$i];

            $sql = ("SELECT * FROM busca WHERE nome_fac LIKE '%$.pesquisa.%'");
            $query = $mysqlli->query($sql);
            while($linha = mysql_fetch_array($sql)){
                $nome_fac = $linha['Nome'];
                $data_vest = $linha['Data Vestibular'];
                $data_taxa = $linha['Data Taxa'];
                $nota_corte = $linha['Nota de corte'];
                $nota_enem = $linha['Nota ENEM'];

                echo"

".$nome_fac."

".$data_vest."

".$data_taxa."

".$nota_corte."

".$nota_enem."

                    ";
        }
    }
    }
?>

Comment: Ajude-nos a te ajudar. O que diz o erro?
Comment: Na outra [perguntar](http://pt.stackoverflow.com/q/41466/91) estava `mysql_fetch_array($sql)` fique atento para usar somente um driver de conexão com o banco de preferência o mysql**i**. Veja como o site funciona na [tour](http://pt.stackoverflow.com/tour), [como perguntar](http://pt.stackoverflow.com/help/how-to-ask) e não esqueça de fazer um debug ;)
Comment: Eu confundi na hora de colar o código só.
Comment: Coloque: ´$query->fetch_assoc()` no lugar de `mysql_fetch_array($sql)`
Comment: Ocorreram os seguintes erros ao substituir mysql_fetch_array($sql) por ´$query->fetch_assoc()`: http://i.imgur.com/QVBLwv6.png?1
Comment: No código da pergunta não tem nenhuma variável chamada consulta. Verifique os nomes das variáveis, se precisar edite a pergunte e coloque o código correto.
Comment: A variável consulta é a $query. Me desculpe, postei o erro em português, aqui está ele em inglês se ajuda em algo: http://i.imgur.com/GLrStAL.png
Comment: `query()` retorna false quando a consulta tem algum erro, exiba assim o erro do banco: `$query = $mysqlii->query($sql); if(!$query){ echo $mysqlii->error;}`
Answer: Parece ser apenas um erro de digitação, seu objeto de conexão é $mysqlli e na hora de chamar o método query() você chama uma variável que não existe $mysqli. Para corrigir troque a chamada de:
$query = $mysqli->query($sql);

por:
$query = $mysqlli->query($sql);

Quando uma tela em branco é exibida, isso significa duas coisas aconteceu um erro e a exibição dos erros foi ocultada(geralmente por motivos de segurança). Nesse caso é possível os erros sobrescrevendo essa configuração, as linhas a seguir devem estar no o início do seu arquivo.
 <?php
 ini_set('display_errors', true);
 error_reporting(E_ALL);

 echo '...';

A linha abaixo pode ser removida, e evite usar @ pois ela oculta os erros, o que dificulta mais a resolução do bug.
@mysql_select_db("faculdadesbd",$mysqlli);

Erro na linha mysql_fetch_array


Separation of variables (ODEs)

Question: Here is the question I am currently stuck on:

Here is what I have done so far:

My apologies as I understand this post seems fairly lengthy. However I cannot seem to get the final answer with x in terms of t (the solution is x(t)=((t^2) + C)^3 + 1). I am stuck on what to do after the last stage of my working which I have shown in the images.
any help is appreciated, thank you
Answer: since c is a constant it can be anything put c=3d where d is a new constant.now we can cancel 3 for all the sides.now cube both the sides and you get a matching answer.Though your answer was also right it seemed wrong due to the constant which can be anything.If you would reverse steps and make a differential equation out of your answer it would also give the question as it is.

Separation of variables (ODEs)


metric characterization for connectedness

Question: Is there a metric characterization of connectedness? I'm looking for something like the following metric characterization of compactness: A metrizable topological space is compact if, and only if, every metric inducing the topology is complete and totally bounded.
So, is there any property $P$ of a metric such that a metrizable topological space is connected if, and only if, every metric inducing the topology has property $P$.
If no such $P$ exists, is there a property $P$ such that every meteric space satisfying it is connected, and a metrizable topological space is connected provided there is some metric inducing the topology and which satisfies $P$.
Comment: I'm not sure I understand what kind of condition you're looking for. You can obviously take $P$ to be "the topology induced by the metric is connected"... What kind of property $P$ would be acceptable or not?
Comment: @NajibIdrissi I'm looking for a metric property, just like the one for compactness I mention above.
Answer: Let us first consider a different characterization of compactness: a metrizable space is compact iff the range of every metric is
compact.  Necessity follows from continuity of the metric, and sufficiency
can be obtained from the fact that every non-compact metrizable space
admits an unbounded metric.
This suggest the analogous statement: a metrizable space is connected iff
the range of every metric is connected. This turns out to be true, and even
simpler.
Necessity again follows from continuity of the metric.
To show sufficiency, let $(X, \rho)$ be a disconnected metric space and
let $A, B$ be a separation of $X$. We can define a topologically
equivalent metric by
$$
   \sigma(x, y) = \cases{
                     \min\{ 1, \rho(x, y) \} & if $x,y \in A$ or $x, y \in B$,\\
                     2                        & otherwise.
                  }
$$
Clearly the range of $\sigma$ is not convex, since it contains 0 and 2, but not
3/2, therefore it is disconnected.
Corollary: a metrizable space is a continuum iff the range of every metric
is a closed bounded interval.
P.S.: There is a question you did not ask, but which is suggested by your example: is there a property $P$ of metrics such that the existence of a metric
with property $P$ implies connectedness and connectedness implies that all
metrics have property $P$. Equivalently: is there a property $P$ such that a
metric space is connected iff its metric has property $P$. I don't have an
answer to that.
Comment: Thanks for this answer. I'm looking for something that is less dependent on special properties of the reals.
Comment: Depending on exactly which properties you consider special, that may not be a realistic goal. The fact that nontrivial connected metric spaces exist at all is intimately related to the fact that the codomain of a metric is locally homeomorphic to $\mathbb{R}$.
Comment: I understand this is somewhat vague. By comparison to the compactness case, the metric characterization (complete and totally bounded) is a more inherently metric property than saying "the image of the metric is complete in $\mathbb R$ with the Euclidean topology". I hope this makes things slightly less vague.
Comment: @IttayWeiss I still don't see what you don't like about this answer.  "Complete and totally bounded" fundamentally uses the structure of $\mathbb{R}$; are you looking for a characterization of connectedness which doesn't *look like* it uses any properties of $\mathbb{R}$?
Comment: @PaulSiegel of course under the hood things will depend on properties of the reals. "Complete and totally bounded" uses the reals, bot not (directly) their completeness or total boundedness. Not to mention the fact that I'd rather not to use the concept of connectedness (of the reals) for defining connectedness for general metric spaces.
Answer: There is for compact spaces:

A compact metric space $X$ is connected if and only if for all $a,b\in X$ and all $\varepsilon>0$ there exist points $a=p_0, p_1, \ldots, p_k=b$ such that $d(p_i,p_{i+1})<\varepsilon$.

And it's not hard to prove this. It's difficult for me to imagine there's some general characterization given examples of connected spaces like the Knaster–Kuratowski fan.
Comment: To complement this answer, the above property is known as _uniformly connected_, or [_Cantor connected_](http://en.wikipedia.org/wiki/Uniformly_connected_space) (even if the wikipedia link does not make this obvious) and you might get some references if you google the above terms.
Comment: Thank you, this is helpful, particularly if compactenss can be avoided.


Openedge SDO -> smart data browser - I want to filter the query results

Question: I have an SDO supplying data to a read-only browser. The SDO query joins several tables and has calculated fields as well as natural data fields.
The users now want a search facility so the browser will only show rows where the search word appears in ANY of the text fields.
For example they want to see rows where
customer.name matches "*bob*" OR
customer.address1 matches "*bob*" OR
product.description matches "*bob*" OR
calc_field_1 matches "*bob*" OR
calc_field_2 matches "*bob*" OR ...

Ideally the answer will filter the SDO output as it is created - but I am also happy to filter the data on the way to the smartbrowser or in the smartbrowser.
Comment: That sounds like kind of an odd requirement - almost as if the underlying data is bad. I'd suggest finding out what problem the users feel this would fix and address that question instead.
Comment: Hi Tim, the table for the sdo query is an audit table of changes to another table. Right now the only filter is by the date of the change. The users want a simple way to zoom in on the records they are interested in. A simple search box like Google is something they will all understand and use.
Comment: In that case I'd suggest adding another column to the table, putting all the words from the other columns in it, applying a word-index to the new column, and then searching that. It'll be much faster and easier to use.
Answer: The business problem you're trying to solve in fraught with performance issues if you implement it as written. I'd suggest

adding another character column to the table or db,
putting all the words from the other columns in it,
applying a word-index to the new column,
doing a search on that column, and then linking back to the source tables.

It'll be much faster and easier to use.
Answer: I used a very simple solution in the end. Users can enter a string they are looking for. If the string is in a cell in the browser then the cell is highlighted in yellow.
Before this the users had to scroll up and down trying to spot the cells of interest in hundreds of rows. We did not have the time or budget for anything fancier.
The important bit of code in the smartbrowser is like this...
on row-display of br_table in frame f-main
do:
    if rowObject.field1 matches "*BOB*" then
       rowObject.field1:BGCOLOR in browse br_table = 14.
    if rowObject.field2 matches "*BOB*" then
       rowObject.field2:BGCOLOR in browse br_table = 14.
    if rowObject.field3 matches "*BOB*" then
       rowObject.field3:BGCOLOR in browse br_table = 14.

    ... etc ...

it's not hard-coded to only look for Bob - but you should get the idea.


Get random phrases from an array in PHP?

Question: I have this phrases ex: test 1, test 2, test 3, now how to show on load page in random mode?
ex function
function random()
{
    $array = ['test 1', 'test 2', 'test 3'];

    return $random_array;
}

Answer: Put them in an array and use array_rand to get a random key.
function random()
{
  $phrases = array(
    'random test 1',
    'random test 2',
    'random test 3'
  );

  return $phrases[array_rand($phrases)];
}

Comment: @Federal09 You're welcome :). Please accept the answer if this question is answered to your satisfaction (thanks).
Answer: Put them in an array and pick a random element:
$array = array();
$array[] = 'test1';
$array[] = 'test2';
$array[] = 'test3';
$array[] = 'test4';

echo $array[ mt_rand( 0 , (count( $array ) -1) ) ];

Or you could just shuffle the array and pick the first element:
shuffle( $array );

echo $array[0];

OR, another method I've just discovered:
Use array_rand(); See some of the other answers.
Comment: You have [`array_rand`](http://php.net/manual/en/function.array-rand.php) for picking a random key.
Comment: Very good. In php 7 instead of `mt_rand` use newer and faster function called `random_int`.
Answer: <?php

function random(){
    $phrases = array(
        "test1",
        "test2",
        "test3",
        "test4"
        );

    return $phrases[mt_rand(0, count($phrases)-1)]; //subtract 1 from total count of phrases as first elements key is 0
}

echo random();

and a working example here - http://codepad.viper-7.com/scYVLX
edit
Use array_rand() as suggested by Arnold Daniels
Answer: The best and shortest solution in php is this:
$array = [
    'Sentence 1',
    'Sentence 2',
    'Sentence 3',
    'Sentence 4',
];

echo $array[array_rand($array)];

Update: for above answers in as PHP 7.1 is to use random_int function instead of mt_rand since it's faster:
$array = [
    'Sentence 1',
    'Sentence 2',
    'Sentence 3',
    'Sentence 4',
];

echo $array[random_int(0, (count($array) - 1))];

For more information about mt_rand v.s random_int see the link below:
  https://stackoverflow.com/a/28760905/2891689
Answer: Put them in an array and return a random value.
Comment: how to create array in php?? Sorry i'm developer of C#, php is very similar but i don't know


How does PERMANOVA use degrees of freedom in comparison to a linear model (R software)?

Question: I am a long time user of the forum but first time poster. My question is unrelated to a specific dataset but on the internal workings of a PERMANOVA in R (adonis2 function, vegan package) vs a nested linear model in R (linear mixed model, package lmer or nlme). I will explain step by step what my concern is.
Lately I have been working on ecological experiments with complex designs, meaning that we have several sampling times, two spatially nesting variables and two treatments with two levels each. However, the number of replicates per treatment combination was of 4. This means that the number of degrees of freedom (or, in other words, independent data points) that we have in order to perform tests were extremely limited.
When performing a linear model on one of our response variables with all the aforementioned explanatory variables and covariates, including two spatial nests, the test could not be performed due to lack of degrees of freedom (this was identical for the lmer and the nlme packages).
However, reading the statistical analyses of other similar experiments in the literature, I came across the PERMANOVA test. The experiments had the same number of replicates and comparatively complicated designs, and therefore I decided to test them. I am aware that the PERMANOVA test is multivariate in opposition of the univariate nature of the linear model, but it can be used with a single response variable. This unique response variable is transformed into a distance matrix and the analysis is performed.
To my surprise, the test worked correctly, with absolutely no errors in the output. However, I am not sure if I can confidently use this test until I understand why the number of degrees of freedom was not enough for the linear model whereas it was enough for the PERMANOVA. My only educated guess is that is related to the permutational nature of the test, but I could not find an answer neither in the original literature explaining the PERMANOVA test nor in papers or online forums.
Answer: PERMANOVA uses a permutation test for the tests of covariates. The key assumption is that the observations (or residuals) are exchangeable under the NULL hypothesis. It doesn't sound like your data are exchangeable under the NULL model implied by the default permutation scheme, which is simple randomization.
You may be able to specify the constraints implied by your design in the permutation test; vegan uses the permute package for permutation schemes so look at the help for permute to see if your design fits within the possibilities.
The other way to deal with these issues is to include the experimental design in the model by including extra terms.
You don't give enough information on the design etc to speculate further.
Comment: Thank you very much for your answer. I understand that one of the assumptions in PERMANOVA is the excheangability of the permutational units. In order for the units to be exchangeable, I added the nesting design to the PERMANOVA to avoid the violation of this assumption.

I we assume that I added all the correct covariates to my PERMANOVA model (including the nesting design), I am still unsure why it is possible to run it whereas in the case of the linear mixed model this is impossible.

Therefore, my question is still partially unanswered.


Cannot uninstall modules due to missing table br_schedule

Question: When I hit the Uninstall tab in the UI or try to uninstall a module with Drush I get the following errors:
Drush:
SQLSTATE[42S02]: Base table or view not found:
1146 Table 'DATABASENAME.br_schedule' doesn't exist

Drupal Log:
Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S02]:
Base table or view not found:
1146 Table 'DATABASENAME.br_schedule' doesn't exist:
SELECT base_table.vid AS vid,
base_table.id AS id FROM {br_schedule}
base_table LIMIT 1 OFFSET 0; Array ( ) in
Drupal\Core\Entity\EntityStorageBase->hasData()
(line 552 of MYSITEPATH/core/lib/Drupal/Core/Entity/EntityStorageBase.php).

I have no idea what br_schedule is so I don't know how to rebuild that table. I have Businesses Rules installed but I see no br_schedule module.
Comment: br_schedule is the base table for the business_rules_schedule entity type. Perhaps the module was previously installed before the entity type existed in the current version. Maybe `drush updb` could solve the issue (it should run entup as well these days).
Comment: It doesn't have to be a module necessarily, a module can create as many tables as it needs to. An easy way to get out of this is to create a bare table using a database editor/interface called br_schedule then try to uninstall the module. This will get you around the error. The rest sounds like a bug for the Business rules module.
Answer: Found the issue. My database updates are not happening. Ran updatedb:status with drush and I get:
file_entity                           8004        hook_update_n   Fix entity field mismatches on the file type field.
business_rules_schedule entity type               entity-update   The Schedule entity type needs to be installed.
file entity type                                  entity-update   The File type field needs to be updated.
node entity type                                  entity-update   The node.field_zipcode field needs to be updated.

"Fix entity field mismatches on the file type field." is failing so the "business_rules_schedule" update isn't happening.
Answer: Perhaps the easiest workaround as @kevin mentions would be to download adminer or use existing phpmyadmin if you have and create that table with no content running the following (or similar) SQL command
CREATE TABLE br_schedule (
    ID int
);

then try again to see if it can uninstall
NOTE: use with caution its not a bulletproof technique, I have used it a few times and was able to complete broken uninstalls on messed up databases but as mradcliffe mentions it might screw things up as well.
Comment: This might cause further errors because the table is provided by a content entity type.
Comment: @mradcliffe perhaps you are right its a trial and error not to be tried on live site, I am not aware of what `br_schedule` is but the above technique has saved me a few times when I get in my hands a broken DB
Answer: I spun up a blank D8 with Business Rules installed and exported the br_schedule table and imported it into the effected site. Now I can uninstall modules.
Answer: Just run "drush entity-updates" to create the entities before you run drush updb.
Comment: `Drupal removed its automatic entity-updates API in 8.7. See https://www.drupal.org/node/3034742. `.


What is a "Variant" in Drupal?

Question: I tried to read a bit about what is actually a Variant in Drupal (and especially in Ctools).
But the 2-3 explanations I read were not clear enough for me. It was a wired experience for me since I've already learnt some "similar" Drupal unique terms such as Drupal argument, Contexual filter, Page (Drupal), Entity, Node, etc.
So what is a Variant and why do we need them? Please use the simplest explanation you can.
Answer: "Variants" are typically used / related to "Page Manager", which is part of the CTools module. The "simplest explanation***" is ... not "simple" to provide. However there is an interesting (amazing?) video intro about it: refer to Learn Page manager! Part 3: Variants and selection rules.
While you're at it, you may want to look at the entire (impressive) video series around there, i.e. Learn Page manager!. Here is a summary of the entire set of videos about this topic:

Page manager allows you to collect and manage contextual information in a flexible and consistent way. It is an important part of building infrastructure on Drupal websites, and you should know how to use this module.
The screencast series is targeted at experienced Drupal developers.
Episodes 1, 2 and 3 introduces the most basic concepts, such as custom pages, variants, selection rules and (to some extent) contextual objects.
Episodes 4, 5, 6 and 7 talk about Panels, with emphasis on Views integration but also some words on efficient caching.
Episodes 8 and 9 about access control, menu items, and not least the little-known but very useful Contextual Administration module.
Episodes 10 and 11 talks more about using contextual objects in Page manager, including using Views as context. This is, imho, where the real power in Page manager is.
Episodes 12 and 13 collects various bits and pieces, such as how to use Panels to easily rearrange the node edit form, import/export settings, and some extra modules that can be used with Page manager.

Some more recommended (free) tutorials that you may want to consider, and which will help a lot to understand the typical Drupal terminology in your question:

The 32 (!!!) great video tutorials Learn the Rules framework, organized in 7 chapters, about the Rules module.
A similar set of 8 video tutorials about the Flag module.
The set of 30 video tutorials about the Views module.

In Drupal 8, Page Manager has become a separated module, while formerly (up to Drupal 7), it was part of the CTools module. Here are some more quotes from the (D8 related) project page:

It supports the creation of new pages, and allows placing blocks within that page.
Like Drupal 7's Page Manager, it provides a concept of "page variants", each with their own selection conditions.
Additionally, it can be used to take over an existing page, like overriding /node/% to change what is displayed when viewing a node.
It utilizes the core Conditions, Context, and Blocks APIs to accomplish this.

So that's part of the changes coming up in the CTools module in D8.
Comment: I've heard something like this: In Drupal8 Ctools is going to change very much, some of the terms would be replaced (or something of the sort)... Have your also heard of such thing?

What is a "Variant" in Drupal?


since a symmetric tridiagonal matrix contains only two distinct vectors

Question: I don't understand meaning of "since a symmetric tridiagonal matrix contains only two distinct vectors" I write example for symmetric tridiagonal matrix. The 1st row vector and 1st column vector are the same, the 2nd row vector and 2nd column vector are the same. This way they are all eliminated. What does "contains only two distinct vectors" mean?
Answer: The subdiagonal elements and the superdiagonal elements can be represented as the vector $(\beta_1, \beta_2, \dots \beta_{n-1})$. It has  length $n-1$. The diagonal elements can be represented as the vector $(\alpha_1, \alpha_2, \dotsc, \alpha_n)$. It has length $n$. Tridiagonal solvers such dpttrs (based on the LDLT-factorization) from LAPACK capitalize on this fact to reduce the storage requirement from $n^2$ words of memory needed for a dense matrix to a mere $2n-1$ words of memory.

Personally, I would prefer to write: "since a symmetric tridiagonal matrix can be represented using only two distinct vectors, it customary to replace the generic notation ...", but this is a matter of taste.
Comment: Now it makes sense, thanks!


In how many ways can numbers be arranged?

Question: There are nine (horizontally) contiguous square cells. We have numbers from one to nine. We have to arrange these numbers in the cells so that the sum of the adjacent three cells is completely divisible by three. How many ways can we do this?

(i could be wrong)I solved a part of it. 3, 6 and 9 are always divisible by three, so I can remove them. I'll just product the answer that I found at the end  to three factorial. Now I have a question for six cells.
the answer was given as follows: 6^4
Comment: Note that specifying the first two entries determines the string.  Thus, starting with $1,0$ the string must be $1,0,-1,1,0,-1,1,0,-1$.  Note too that you can't start with $1,1$ nor with $-1,-1$ nor with $0,0$.
Comment: Again, it's easier to work $\pmod 3$ at first.  Three of your digits are $0\pmod 3$ and so on.  You can do the $\pmod 3$ count in your head, and then you just need to multiply by $(3!)^3$.
Comment: $(3,6,9)$ are all $0\pmod 3$.  $(1,4,7)$ are all $1\pmod 3$.  And $(2,5,8)$ are all $-1\pmod 3$.
Comment: My solution gives $6^4$.  I get six patterns, each with $(3!)^3=6^3$ ways to populate them.
Comment: Not sure the rules are clear.  What does "adjacent" mean here?  Perhaps it would help if you provided an example of a successful arrangement.
Comment: I shall add picture.
Comment: For instance, is this good:  $$
$$
\begin{bmatrix}
1 & 2 & 3 \\
5 & 6 & 4 \\
9 & 7 & 8 \\
\end{bmatrix}
$$
$$?  all columns, all rows, and diagonals sum to $0\pmod 3$.  Is this overkill?
Comment: Whatever the rules, I would solve the problem assuming we had three each of $0, \pm 1$.  For each such pattern, you have $(3!)^3$ ways to populate the cells.
Comment: no, the alignment should be horizontal only
Comment: Ok. My hint still applies.  I don't understand the bit about removing those $\equiv 0 \pmod 3$.
Comment: That is, 3, 6, 9 are always divisible by 3, so we can ignore the their arrangement.
Comment: But that's wrong.
Comment: numbers can be 1 2 3 4 5 6 7 8 9
Comment: I don't understand, the numbers in the question are 1..9, but I can't give 0
Comment: Do you know what $\pmod 3$ means?
Comment: 2 ( mod 3) = 2 I know that
Comment: One could also write $2\equiv -1\pmod 3$.  Personally, I think that clarifies things, but there is nothing wrong with using $(0,1,2)$ instead of $(0,1,-1)$.
Comment: can you please write the solution in order how to get the answer 6^4
Comment: the answer was given as follows: 6^4
Comment: My hints form a nearly complete solution.  I suggest studying them.
Comment: your solution: 6^3 but the answer is 6^4. If I'm wrong, please explain
Comment: Ok thanks. I understand
Answer: To summarize the discussion in the comments:
We start by reducing $\pmod 3$.  There are three digits $\equiv 0\pmod 3$, and three each $\equiv \pm 1 \pmod 3$.  Thus, for any good pattern in $0,1,-1$ we have $(3!)^3=6^3$ ways to populate it.
How many such patterns are there? Well, any good string is entirely determined by the first two characters.  Thus $1,0$ would give the string $$1,0,-1,1,0,-1,1,0,-1$$
In principle there are $9$ ways to choose the starting two characters but three of these ($(0,0), (1,1), (-1,-1)$) fail to generate acceptable patterns.  The other $6$ all work (Note:  these correspond to the three permutations of $1,0,-1$).
Thus there are $6$ patterns, each of which can be populated in exactly $6^3$ ways, making the answer $6\times 6^3=6^4$ as desired.


How to find out if a set of daily measurements  are random or not?

Question: There is a set of daily measurements. Time and measured values are both discrete. I want to find out whether measured values depend on the day the measurement was taken, or whether measurements are completely random.
In other words, I want to find out if it is possible to predict measured values of a certain day or not.

What subjects of statistics should I study to be able to solve this problem?

Please give me some keywords or direction.
Edit
Some more information. Imagine the following situation. A machine chooses each day a letter (simply a byte) and displays it on a screen. The process which is used to choose daily letter is unknown, but it is clearly algorithmic (not measure the wind speed or count people in the room or similar). Someone collected part of daily letter over a period of time and now wants to understand if it is possible to produce the next (or any) daily letter. Some methods possibly employed by the machine are considered "hard" (or random). For example use a secret key to encrypt the current date (predicting the next letter will be equivalent in most cases to braking the encryption). Other are considered "easy", for example xor of all bytes in date's representation. If the method is random, then there is no hope to produce the next daily letter.
Comment: First graph your data to see if there are any obvious patterns.  Do you have any theory suggesting the data might be non-random?  That may guide your choice of statistical model.
Comment: @Michael: Unfortunately graphing your data doesn't always disclose the "unusual" due to background variability. In trivial cases the human eye is as good as a good statistical program whose focus is separating signal from noise and partitioning the noise into randomness and the exceptional. In non-trivial cases my bet would be on good/superior analytics and not on "tired/confused eyes". Save your eyes ! Use Statistic Methods to do what it was designed to do !
Comment: @Irish I don't think @Michael was suggesting that the analysis be limited to graphing.  It would be foolhardy at best to trust the output of "good/superior analytics" without ever looking at the data.  Given a choice between some statistical output and a good graph of a dataset (but not both), I will take the graph every time.
Comment: @whuber:When one is faced with analyzing/characterizing a large number of problems,one needs to use "productivity aids". Good luck with relying on graphs when one has noisy data  with large background variability.In trivial cases where the eye can catch the anomaly one doesn't need to acquire "expensive software" as one can use the human brain/eyesight as a proxy for the "expensive software".Where I come from "human time" is more expensive than software but perhaps lacking software they can use their eyes.Academics are often unable to acquire "better eyes" & that's why they often need glasses.
Comment: Are you measuring a single thing, or multiple things each day? (E.g. are you measuring temperature, or are you measuring temperature, humidity, rainfall, etc?) Are you making only one measurement of each thing, or multiple measurements of each thing per day? If you are measuring one thing, you have a univariate time series, otherwise multivariate, for example.
Comment: @Wayne Updated my question
Answer: In my opinion you want to focus on time series analysis which deals directly with the subject you raise. When dealing with time series data one can use memory models (ARIMA/Autoprojective Structure) to capture the importance of previous values in predicting future values. Google Box-jenkins or ARIMA for more. An equally interesting approach is to use a fixed-effects (X) approach which might incorporate day-of-the-week effects, weekly effects, Holiday/Event effects, Particular days-of-the-month effects. What is even more powerful is to incorporate both the ARIMA component and the X structure into an ARMAX model or a Transfer Function Model. Care should also be taken to identify unusual data via Intervention Detection to accomodate Pulses, Level Shifts, Seasonal Pulses and even Local Time Trends. It also might be important to validate a Gaussian Error Process and to take steps to ensure same. I have made a number of comments on this board about such things. You might review my posts and other posts that you may find equally informative.
Modified my answer to deal with the need for models to detect anomalies that if untreated inflate the variance of the errors causing incorrect acceptance of the hypothesis of randomness. Prof.J.K.Ord has referred to this as "the Alice in wonderland effect".  The problem is that you can't catch an outlier without a model (at least a mild one) for your data. Else how would you know that a point violated that model? In fact, the process of growing understanding and finding and examining outliers must be iterative. This isn't a new thought. Bacon, writing in Novum Organum about 400 years ago said: "Errors of Nature, Sports and Monsters correct the understanding in regard to ordinary things, and reveal general forms. For whoever knows the ways of Nature will more easily notice her deviations; and, on the other hand, whoever knows her deviations will more accurately describe her ways."
Comment: Though you did not mention them directly, I found out through your post about autocorrelation and ARMA and as these are more basic I think I will read about them first. Regarding the second paragraph. I am not sure I understood. Do you mean that I always must have a guess about the model of the series?
Comment: @Artium" If you want to contact me directly please do so and I will try and help. Essentially the values that represent unusual activity increase the error sum of squares thus reducing the probability of finding anything non-random.  Please refer to my email address and send me  your contact info and I will try and help. Essentially the characteristics of the data can suggest a starting model which can then be iteratively re-constructed which can then be used to detect errant observations which can then result in a model that may  be useful in separating signal and noise.
Answer: Your edited question sheds new light on the issue, thanks!
My first thought is that you'd want to do some kind of Chi-squared test to determine if the output is random. If the test indicates that is is not random (actually not pseudo-random, of course), then you'd have to attempt to model it as a time series or in other ways, perhaps trying to model possible letter generation algorithms. I'm not expert enough to go beyond this, and am not sure if a time series approach (ARIMA, etc) will work without external data.


IIS6 returning 404 for all requests containing "Translate:f" header

Question: I have written a custom WebDav implementation which is now hosted in IIS6, which now accepts "Translate:f" as a header but as it does so bypasses my custom http module (ASP.NET 3.5) and returns a 404 error.
It is correct that there is no resource at the given address, but my custom module should be handling the request - it seems that the "Translate:f" header causes IIS6 to bypass it and go straight for the resource.
I can't prevent the app from sending "Translate:f" as a header but is there any way of configuring IIS6 to always run my module even if it sees this header.
Cheers,
Adam.
Answer: Answered my own differently worded question
Is it possible to configure IIS6/7 to ignore certain request headers?


Finding Time and Space Complexity Of Recursive Functions

Question: I am stumbling at anlayzing the time and space complexities of recursive functions:
consider:
def power(a, n):
    if n==0:
        return 1
    else:
        return a*power(a, n-1)

When finding time complexity of this: I think T(n) = c + T(n-1) where c is the constant cost of the multiplication.
This will probably lead to: c*n cost, i.e. linear cost O(n). But recursions are usually exponential in cost.
Also, consider this function:
def power(a,n):
    if n==0:
        return 1
    if n%2 ==0:
        return power(a*a, n//2)
    else:
        return a*power(a*a, n//2)

The above function will go on till: T(n) = c + T(n/2) which means the cost will be c*log(n) means log(n) complexity.
If the analysis is correct then recursion looks to be as fast as iterative algorithms, so where does the overhead come from and are there any exponential recursive algorithms?
Comment: You might to separate the Order of the function from how quickly it operates in practice (on small datasets) - a simple power function, done iteratively, has vastly smaller overhead than a recursive function, where you set up a new stack frame and branch every time through.

Recursive functions aren't necessarily exponential, as your analysis shows. Howevr they tend to be practically useful on things like tree-walks, where they bifurcate unpredictably, and in this case, they are exponential (but much easier to implement, and just as good as,non recursive functions.)
Answer: It is not true that recursions are exponential in complexity. In fact there is a theorem that each recursive algorithm has an iterative analogue and vice versa(possibly using additional memory). For explanation on how to do this see here for instance. Also have a look at the section in wikipedia that compares recursion and iteration.
When a recursive function calls itself more than once in some of its flows, you may end up with exponential complexity as is the famous example with fibonacci numbers:
def fib(n):
   if n < 2:
       return 1
   return fib(n - 1) + fib(n - 2)

But this does not mean there is no faster recursive implementation. For instance using memoization you can get that down to linear complexity.
Still recursive implementations really are a bit slower, because the stack frame should be stored when doing a recursive call and it should be restored when returning the value.
Comment: Good start. One more thing to note is that you compute some values multiple times - for instance both T(n - 1) and T(n-2) depend on `T(n-3)`. Can you estimate how many times the function is called for each argument?
Comment: could you state the theorem or name/links to it..also how to show the above algo has exponential complexity by analysis? Thanks!!
Comment: I have added a link to a constructive proof - an example algorithm to do the conversion
Comment: @AndyMarkman as for showing why the above algorithm has exponential complexity I prefer to leave that bit to you. From your question it seems you have pretty good handle of it and both your estimates are correct
Comment: Thanks, I will try: T(n) = T(n-1) + T(n-2) and T(n-1) = T(n-2) + T(n-3) and T(n-2) = T(n-3) + T(n-4) => there are two function calls for every value of n... and then, it looks like: there are n levels and at each level there are branches: no. of branches = function calls = 2*2 * 2 n times => 2^n. I was thinking why it is not: 2 + 2 + 2 + 2...  but for that new function calls have to be stopped...
Comment: it appears it is a fibonnaci series. n is called 1 times, n-1 = 1 time, n-2 = 2, n-3 = 3, n-4 = 5.... so total number of base calls made = fibonacci(n) .. then it looks complexity is less than exponential bcz is fibonacci is slower than exponential https://www.burgundywall.com/post/fibonacci-vs-exponential-growth
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/165039/discussion-between-ivaylo-strandjev-and-andy-markman).


closed solution for non linear system

Question: For linear systems of the form $Ax = \dot x$, one can find a close solution of the form:
$
\dot x(t) = e^{At} x(0)
$
Is there a way to show that a nonlinear solution of the form, $A(x) x = \dot x$ has no closed-form solution? You could have a solution in small time steps, for example, $\dot (x+ \tau) = e^{A(x) \tau} x(t)$. But given that $A(x)$ is dependent on x, I guess it is possible to have a closed solution because, at each time step, the x vector needs to be accounted for in A.
Is there a way to formally show that?
The reason I ask is people keep seeking this closed for solution for the nonlinear system, and it seems to me impossible, am I wrong?
Thanks!
Comment: It could be interesting you give an example for $A(x)$
Comment: No, the first claim is not true as special cases most likely exist. // A solution in terms of the matrix exponential does already not exist in general for time-variable $A=A(t)$. // Of course one may apply the Euler method or the exponential Euler method, but that only gives first-order approximations to a solution.
Comment: @LutzLehmann Thanks for your answer. But how can I prove that the matrix exponential does already not exist in general for time-variable A = A(t)?
Comment: The matrix exponential as operation does exist, it just has no relation to the solution in similarity to the scalar case. The exception is the special case that all matrices for all parameters commute. In some interesting cases one can express the solution or a factor of it as matrix exponential, but then the exponent has a non-trivial relation to the system matrix of the ODE.
Answer: "Is there a way to show that a nonlinear system has no closed-form solution?"
Yes, there is!
The existence of a "closed-form" solution is constrained to an resonance condition. More precisely:
Corollary: If the eigenvalues of $f(x)$ around a fixed point $x_*$, where the Jacobian matrix is semi-simple, are $\Bbb N$-independent, then there is no formal first integral.
This is Corollary 5.2 from Goriely's Integrability and Nonintegrability of Dynamical Systems.
Comment: Thanks! Can you just let me know what is ℕ
-independent? I took a look at the book, but I am not that familiar with nonlinear dynamics.
Comment: A set of numbers $a_1,a_2,...,a_k$ is $\Bbb N$-independent if there's no solution (in $\Bbb N$) to $n_1a_1+n_2a_2+...+n_ka_k=0$ other than $n_1=n_2=...=n_k=0$. Also consider accept the answer.
Comment: Thanks again. I accepted the answer. In my case, at the equilibrium point, my system is diagonal, and the eigenvalues are all equal except the last diagonal element, which is zero! So the set will be $n_1 \lambda + n_2 \lambda + \cdots + n_n \cdot 0  = 0$, which has only $n_1 =n_2 = ...=n_n = 0$. So it is an N-independent set. Right?
Comment: The last term can be any number. But your matrix is not semi-simple.
Comment: Isn't semi-simple just the fact that the matrix can be written through the sum of the other two square matrices?
I have another question, if I may. In the book, the author states rational integral and formal integral. Can you walk me trough the difference?
Comment: Sorry.. I might not have explained right. My system is $\dot x = (A + f(x)) x$. A is a diagonal matrix, but the nonlinear matrix f(x) is not. However, in the equilibria point, f(x) turns out to become diagonal, but just in the $x^{*} point$. My goal is to check if there is any closed form solution to this non linear system.
Comment: These definitions (rational and formal first integrals) are in the first chapter and I strong suggest you to read it. About the matrix note that the result uses the jacobian .

closed solution for non linear system


Adding dynamic markup to menu items

Question: In Drupal 7, how can I add additional dynamic markup to a menu item?  As an example, I'm trying to show the number of nodes 'needing attention' to the right of link in my primary navigation as noted in the attached graphic.
It seems like a theme function would be appropriate here, but I'm struggling to find which hook I should be implementing.
Answer: Hope this will help you,

As answered theme_menu_link OR theme_menu_tree wil help you to do this. If you go through the above links you can get an idea to change the html of required menu item.

On page load:

for example im using theme_menu_link in template.php refer this code. Node count will be update on every page load, if any changes.
I have updated l() for you requirement. For example I have used a simple function , modify the function as per your requirement.
$output = l($element['#title'] . ''.get_node_count($parms).'', $element['#href'], array('html'=>TRUE));

function get_node_count($parms){
    //you code goes here for get node count
    return $node_cnt;
    }

If you don't want on page load, it can also be done using ajax callback, but not preferable to make ajax callback again and again.

If you want to do refer ajax callback, then the only change has to be done in the l(). Add the unique menu id, which is used to show the node count for the corresponding menu id.
$output = l($element['#title'] . '', $element['#href'], array('html'=>TRUE));

On sucessfull ajax callback you have to update the node count for each menu.
using
...
success: function(data) {
// Change node count
$('#menu_title__node_count').html(data);
}
You will get the class for each node count, you can style as required. And also you can add a common class for common style, based on your requirement.
Answer: To alter the menu item markup, you can use:

theme_menu_link
theme_menu_tree

Note: there are actually functions available for specific menus there too:

Targeted overrides (suggestions) available for theme_menu_link() and
  theme_menu_tree()
In addition to other changes to menu rendering, a Drupal 7
  theme can implement a THEMENAME_menu_tree__MENU_NAME() and/or
  THEMENAME_menu_link__MENU_NAME() function to override
  theme_menu_tree()/theme_menu_link() for a specific menu. For example,
  THEMENAME_menu_link__management() would override theme_menu_link() for
  links within the "Management" menu. This is similar to how
  "node--article.tpl.php" overrides "node.tpl.php".

Source: https://drupal.org/node/254940#theme-suggestions-for-menus

Adding dynamic markup to menu items


What can cause ALL services on a server to go down, yet still responding to ping? and how to figure out

Question: It has happened to me already twice within very few days that my server goes down completely, meaning http, ssh, ftp, dns, smtp, basically ALL services stop responding, as if the server had been turned off, except it still responds to ping, which is what most buffles me.
I do have some php scripts that cause a huge load (cpu and memory) on the server in short bursts, used by a little group of users, but usually the server "survives" perfectly well to these bursts, and when it goes down it never coincide with such peaks in usage (I'm not saying it can't be related, but it doesn't happen just after those).
I'm not asking you to magically be able to tell me the ultimate cause of these crashes, my question is: is there a single process whose death may cause all these services to go down simultaneously? The funny thing is that all network services go down, except ping.
If the server had 100% of the CPU eaten up by some process, it wouldn't respond to ping either. If apache crashed because of (for example) a broken php script, that would affect http only, not ssh and dns.... etc.
My OS is Cent OS 5.6
Most importantly, after hard-rebooting the server, what system logs should I look at? /var/log/messages doesn't reveal anything suspicious.
Answer: (tl;dr still responding to ping is an expected behaviour, check your memory usage)
ICMP echo requests (i.e. ping) are handled by the in-kernel networking stack, with no other dependency.
The kernel is known as being "memory resident", which means it will always be kept in RAM, and can't be swapped to disk like a regular application can.
This means in situations where you run of out of physical memory applications are swapped to disk, but the kernel remains where it is. When both the physical and swap memory are full (and the system can no long manage your programs) the machine will fall-over. However because a) the kernel is still in memory and b) it can respond to ping requests without the help of anything else, the system will keep responding to ping despite everything being dead.
In regard to your problem I'd strongly suspect memory issues. Install "sysstat" and use the "sar" command to see a log of memory/cpu/load/io load etc. I would expect at the times of crash you'd see both 100% physical and swap used.
I would also consider looking at dmesg or /var/log/messages for any sign of the OOM-killer (out-of-memory-killer) being invoked. This is the kernel's emergency system which will start killing processes in the event of memory being exhausted. It's effectiveness depends largely on what processes are being killed. A single process eating up the memory will be efficiently killed and memory freed, however an apache-based website will spawn replacement processes as soon a child process is killed.
Comment: @matteo Linux has what it calls "overcommit": just because you `malloc()` 1GB of ram doesn't actually mean you're going to use it, so the memory manager keeps track of how much memory your program thinks it has and how much memory the program has actually used, and it actually works well, most of the time. At least, until more than one program actually wants to use all of the 1GB it thinks it has.
Comment: @matteo I see *no* indication that this is an OOM issue. Typically, the OOM-killer will pick specific or processes that meet certain criteria, but it wouldn't always kill a daemon like ssh. This is definitely on the I/O side. You didn't explain your hardware situation/specs as I requested in my answer.
Comment: Thanks a lot, I'm almost sure this is the problem, as both the RAM and the swap were full prior to the server failure. (I can see on ovh's Manager's stats). And it's probably some of my crazy php scripts using a lot of memory. It does puzzle me however for a couple of reasons. (1) looks like the memory eaten up by php is not freed afterwards, but that wouldn't make sense; (2) in any case, I wouldn't expect a proper operating system to die completely just because of one (or even a few) processes using too much memory... I would expect it to
Comment: refuse to allocate memory to programs asking for it when there's not enough ram for the system to keep working correctly... I mean a buggy or even malicious program should never be able to destroy the whole system...
Comment: no sign of oom-killer in either dmesg nor messages, btw - at least I grepped (case insensitive) for both oom and killer
Comment: @matteo The log message would appear as `Out of Memory: Killed process [PID] [process name].`, so greping for `oom` or `killer` wouldn't find it.
Comment: @matteo - more details of finding the log entry here: http://stackoverflow.com/questions/624857/finding-which-process-was-killed-by-linux-oom-killer
Comment: @JonathanCallen: thank you, but "grep -i kill /var/messages*" returned nothing.
Comment: So, I guess OOM-killer never kicked in at all. On one side I'm curious about why (why didn't it kill any process when there was a sudden peak of ram usage to 100% and swap to 80%), but that's just curiosity. On the other hand, is there something I could do so that, next time this happens, I will be able (after the crash and reboot) to figure out WHAT process ate up so much memory?
Comment: @ewwhite if by "OOM issue" you mean "many processes like ssh, httpd and the like having been killed by OOM-killer", no, it is most surely not an OOM issue, but if by "OOM issue" you mean "my server ran out of memory", then I do have the absolute certainty that it was an OOM issue, because I saw the graph where there was a spike in RAM usage from normal levels to 100% and in swap from almost 0 to about 80% within a matter of minutes (an "instant" in the precision of the graph)
Comment: my server is at OVH, it's a dedicated server and they have a thing they call Manager on their site which remotely monitors your server, that's where I see the memory usage graph I'm talking about (which stopped collecting data when the server stalled, of course) and from where I (hard)rebooted it
Answer: Usually, it's an I/O or disk subsystem issue. Often times, this will be coupled with an extremely-high system load average. For example, the system detailed in the graph below became unresponsive (yet was pingable) when a script ran awry, locked a bunch of files and the load rose to 36... on a 4-CPU system.

The services that are running in RAM and do not require disk access continue to run... Thus, the network stack (ping) is up, but the other services stall when disk access is required... SSH when a key is referenced or password lookup needed. SMTP tends to shut down when load average hits 30 or so...
When the system is in this state, try a remote nmap against the server's IP to see what's up.
Your logging probably doesn't work if this is a disk or storage issue...
Can you describe the hardware setup? Is this a virtual machine? What is the storage layout?
More than logging, you want to see if you can graph the system performance and understand when this is happening. See if this correlates to a specific activity.
Comment: If it's I/O, you need to get to the bottom of the issue. If it's a disk array timeout or driver interaction, that's different than a script that executes poorly or a resource contention issue.
Comment: Supposing this is the issue, Is there a way to tell SSH to keep the password(s) in memory, so even if the server is in this state I may at least be able to log into it via ssh and run some commands to see what's going on?


React: Is it better to pass something as a prop to a child component, or have that child component get it from Redux?

Question: I have components <Parent> and <Child>, and <Parent> accesses a Redux state prop called prop1 using mapStateToProps(). <Child> needs to access prop1 as well.
What's the difference between passing it to <Child> as a prop like <Child prop1={this.props.prop1}> vs having <Child> get it via mapStateToProps()? Is one way better than the other?
Comment: This will probably be closed as opinion-based. But my view is that, once you've decided to keep that value in Redux (which itself is not necessarily an obvious decision), you should get it from Redux in all components which need it, rather than only fetch it in one and pass it manually down to the others. Part of the point of Redux, after all, is to avoid having to manually pass values down as props all over the place.
Comment: If you don't want it to be possible for the parent to alter the prop before they pass it to the child, then getting it from the store is better, otherwise there is no harm in passing down props IMO.
Answer: TLDR: Get it via mapStateToProps from Child
In this simplified example you provided I would say that the best option is to get the prop1 directly in the Child component for the sake of encapsulation. It would be easier for other developers or the future you to identify the component's dependencies when it gets revisited.
Another benefit of this approach is that it limits updates in case the prop1 changes.  Only Child component will be updated in contrast to the other approach where Parent will be updated along with all of it's children.
However there is a use-case where prop drilling from Parent may be preferred.
If Child component is a reusable one and you don't want to bind it with a specific redux state slice. This way you can keep it unaware of redux and reuse it in another parent component with some other value as prop.
Answer: If the value is already stored in redux you should use redux.
The main drawback of using redux is the sheer amount of boiler plate. However, you already crossed that line in this case.


AttributeError 'Button' object has no attribute scrlFBtn

Question: from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.core.window import Window
from kivy.uix.scrollview import ScrollView
from kivy.effects.scroll import ScrollEffect
from kivy.uix.widget import Widget
from kivy.uix.button import Button

class BSGameMain:
    def sas(self):
        # blmain.remove_widget(scrlFBtns)
        self.scrlFBtns.remove_widget(blbtns)

    blmain = BoxLayout(orientation = 'vertical') # MainBoxLayout init

    scrlFBtns = ScrollView(effect_cls = 'ScrollEffect')

    blbtns = BoxLayout(
        orientation = 'vertical',
        size_hint_y = None
        ) # BoxLayout for buttons

    blbtns.bind(minimum_height = blbtns.setter('height'))
    scrlFBtns.add_widget(blbtns)

    for i in range (2):
        blbtns.add_widget(Button(
            text='asd',
            size_hint_y = None,
            height = 40,
            on_press = sas
            ))

    lblmain = Label(text = 'asd')
    blmain.add_widget(lblmain)
    blmain.add_widget(scrlFBtns)

class BSApp(App):
    def build(self):
        game = BSGameMain()
        return game.blmain

if __name__ == "__main__":
    BSApp().run()

AttributeError 'Button' object has no attribute scrlFBtn. What is the problem? I'm trying to make it so that when you clicked, the screen was cleared (Widget was deleted). Рelp me please =)
Answer: Your code has several errors and bad programming practices:

if you declare variables that are inside a class and outside any method of the class will be class variables and not attributes of the class, so it is not a good practice to do so if you want to use later self, all that code must be within a method of a class.
on_someproperty wait as parameter a function that receives parameters, in your case sas() does not receive them so the solution is to use a lambda method.

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.scrollview import ScrollView
from kivy.effects.scroll import ScrollEffect
from kivy.uix.button import Button

class BSGameMain:
    def __init__(self):
        self.blmain = BoxLayout(orientation = 'vertical') # MainBoxLayout init

        self.scrlFBtns = ScrollView(effect_cls = 'ScrollEffect')

        self.blbtns = BoxLayout(
            orientation = 'vertical',
            size_hint_y = None )

        self.blbtns.bind(minimum_height = self.blbtns.setter('height'))
        self.scrlFBtns.add_widget(self.blbtns)

        for i in range(2):
            self.blbtns.add_widget(Button(
                text='asd',
                size_hint_y = None,
                height = 40,
                on_press = lambda *args: self.sas()))

        lblmain = Label(text = 'asd')
        self.blmain.add_widget(lblmain)
        self.blmain.add_widget(self.scrlFBtns)

    def sas(self):
        self.scrlFBtns.remove_widget(self.blbtns)

class BSApp(App):
    def build(self):
        game = BSGameMain()
        return game.blmain

if __name__ == "__main__":
    BSApp().run()


content access does not work after changing domain

Question: after designing and developing a website I changed its domain. Now any of the permissions are not working. every thing is OK appearently but the functionality is not OK at all.(I mean all the checkboxes and settings are correct but anonymous users have access to all contents!!)
I am using content access module and check the  Enable per content node access control settings  option in content type setting.
Answer: Rebuild the permissions table.

Go to /admin/reports/status/rebuild
Or find the link on the status report: Reports -> Status report and the link is under the Node Access Permissions row.
Comment: wow. thanks. you saved my time and also my life!!!


What does 'vector-valued' mean?

Question: What is the difference of a feature vector and a 'vector-valued observation' as described here?
The term 'vector-valued' is used in the following context:

"Most state-of-the-art [Automatic Speech Recognition] systems use vector valued observations, which are modeled with Gaussian mixture emission densities."
Answer: Saying that something is vector-valued is simply another way of saying that something is a vector, e.g. in regression model
$$ \mathbf{y} = \mathbf{X}\boldsymbol{\beta} + \boldsymbol{\varepsilon} $$
$\mathbf{y}, \boldsymbol{\beta}, \boldsymbol{\varepsilon}$ are all vectors and $\mathbf{X}$ is a matrix, so $\boldsymbol{\beta} = (\beta_0, \beta_1, \dots, \beta_k)$ is vector-valued parameter.

What does 'vector-valued' mean?


Change the Default Empty Node Content

Question: I want to change the default empty node content of my Drupal site installation.

I want to customize its text display as well as the "Add new content" link. How can I achieve this?
Answer: You can try this:
<code><?php
function THEMENAME_preprocess_page(&$vars, $hook) {
    unset($vars['page']['content']['system_main']['default_message']);
}
?>
</code>
Answer: Create a view with the content listet instead of using the default node page. That allows you to customize the "No results behaviour" with custom HTML.
Answer: You can use Empty Front Page module as well.
This ultra lightweight module modifies this behavior to show no default content on the frontpage. Only the blocks will be displayed.
More Options
Empty Page module.
Front Page module.

Change the Default Empty Node Content


Erro Um namespace não pode conter diretamente membros, como campos ou métodos

Question: O meu esta dando esse erro duas vezes.
aqui esta o meu comando:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Porta : MonoBehaviour {
    private Animator porta;
    private bool colidindo;
    // Start is called before the first frame update
    void Start() {
        porta = GetComponent<Animator> ();
        porta.SetInteger ("abreFecha", 0);
        colidindo = false;
    }

    // Update is called once per frame
    void Update() {
        if ((Input.GetKeyDown (KeyCode.E)) && (colidindo = true)){
            if ((porta.GetCurrentAnimatorStateInfo (0).IsName ("portaParada"))  (porta.GetCurrentAnimatorStateInfo (0).IsName ("fechaPorta"))){
                porta.SetInteger ("abreFecha", 1);
            } else {
                porta.SetInteger ("abreFecha", 2);
            }

        }

    }
}
    void OnTriggerEnter (Collider other)
{
        if (other.gameobject.CompareTag("Player")){
                    colidindo = true;
        }
    }
    void OnTriggerExit (Collider other){

        if (other.gameobject.CompareTag("Player")){
                    colidindo = false;
        }
    }

Answer: Acredito que o problema ocorre pois o metodo OnTriggerEnter e OnTriggerExit está fora do escopo da classe Porta.
Segue exemplo corrigido.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Porta : MonoBehaviour {
    private Animator porta;
    private bool colidindo;
    // Start is called before the first frame update
    void Start() {
        porta = GetComponent<Animator> ();
        porta.SetInteger ("abreFecha", 0);
        colidindo = false;
    }

    // Update is called once per frame
    void Update() {
        if ((Input.GetKeyDown (KeyCode.E)) && (colidindo = true)){
            if ((porta.GetCurrentAnimatorStateInfo (0).IsName ("portaParada"))  (porta.GetCurrentAnimatorStateInfo (0).IsName ("fechaPorta"))){
                porta.SetInteger ("abreFecha", 1);
            } else {
                porta.SetInteger ("abreFecha", 2);
            }

        }

    }

    void OnTriggerEnter (Collider other)
    {
        if (other.gameobject.CompareTag("Player")){
                    colidindo = true;
        }
    }
    void OnTriggerExit (Collider other){

        if (other.gameobject.CompareTag("Player")){
                    colidindo = false;
        }
    }
}


How prove this $(xy+yz+xz)\left(\frac{xy}{z^2+1}+\frac{yz}{x^2+1}+\frac{zx}{y^2+1}\right)\le\frac{1}{10}$

Question:
let $x,y,z>0$ and such $x+y+z=1$, show that
  $$(xy+yz+xz)\left(\dfrac{xy}{z^2+1}+\dfrac{yz}{x^2+1}+\dfrac{zx}{y^2+1}\right)\le\dfrac{1}{10}$$

my idea:
$$\dfrac{xy}{z^2+1}=\dfrac{xy}{z^2+(x+y+z)^2}=\dfrac{xy}{2z^2+2xy+2yz+2xz+x^2+y}$$
Maybe this is old inequality,and It is said can use Cauchy-Schwarz inequality to solve it
Thank you
Answer: we can suppose that $ x=\dfrac{a}{a+b+c} , y=\dfrac{b}{a+b+c} , z=\dfrac{c}{a+b+c} $ where $ a,b,c>0 $ are three real numbers.
suppose that $ s=a+b+c $
now $ inequality \Leftrightarrow (\sum{\dfrac{ab}{s^2}})(\sum{\dfrac{(\dfrac{ab}{s^2})}{(\dfrac{c^2+s^2}{s^2})}}) \le \dfrac{1}{10} $
so we must prove that $ \dfrac{(\sum ab )}{s^2}(\sum {\dfrac{ab}{c^2+s^2}}) \le \dfrac{1}{10} $
for $ a,b,c>0 $
Answer: By C-S and AM-GM $$\sum_{cyc}\frac{xy}{z^2+1}=\sum_{cyc}\frac{xy}{2(x+z)(y+z)+x^2+y^2}\leq\sum_{cyc}\frac{xy}{(8+2)^2}\left(\frac{8^2}{2(x+z)(y+z)}+\frac{2^2}{x^2+y^2}\right)=$$
$$=\frac{8}{25}\sum_{cyc}\frac{xy}{(x+z)(y+z)}+\frac{1}{50}\sum_{cyc}\frac{2xy}{x^2+y^2}\leq\frac{8}{25}\sum_{cyc}\frac{xy}{(x+z)(y+z)}+\frac{3}{50}.$$
Thus, it remains to prove that
$$\frac{8}{25}\sum_{cyc}\frac{xy}{(x+z)(y+z)}\leq\frac{(x+y+z)^2}{10(xy+xz+yz)}-\frac{3}{50}$$ or
$$\frac{8}{25}\sum_{cyc}\frac{xy}{(x+z)(y+z)}\leq\frac{\sum\limits_{cyc}(5x^2+7xy)}{50(xy+xz+yz)}$$ or
$$\sum\limits_{cyc}(5x^2+7xy)\prod_{cyc}(x+y)\geq16(xy+xz+yz)\sum_{cyc}(x^2y+x^2z)$$ or
$$\sum_{cyc}(5x^4y+5x^4z-4x^3y^2-4x^3z^2-8x^3yz+6x^2y^2z)\geq0$$ or
$$5\sum_{cyc}(x^4y+x^4z-x^3y^2-x^3z^2)+\sum_{cyc}(x^3y^2+x^3z^2-2x^3yz)-6xyz\sum_{cyc}(x^2-xy)\geq0$$ or
$$\sum_{cyc}(x-y)^2(5xy(x+y)+z^3-3xyz)\geq0,$$
which is true by AM-GM:
$$5xy(x+y)+z^3-3xyz\geq xy(x+y)+z^3-3xyz\geq$$
$$\geq2\sqrt{x^3y^3}+z^3\geq3\sqrt[3]{x^3y^3z^3}-3xyz=0.$$
Done!


Print a view within another view

Question: Here is my situation,

I have a view-1 which will list the node titles based on Content: Taxonomy term CONTEXTUAL FILTERS
View-2 which will list all the taxonomy terms (of a vocabulary) with node count.

Now how do I print the view-1 as a custom field within view-2.
The reason I am trying to do this is, I am trying to construct a UI which will display the nodes on click on taxonomy terms with count.
I tried using below code to print view-1 as a custom PHP field on view-2, but it did not work for me.
<code>    print views_embed_view('view-1','block_1', $row->tid);
</code>
$row->tid is the term ID argument I am trying to pass
Answer: The module Views Field View may work for you. It's worth to try.

This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.
This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.

OR
You can even create two displays in a view - one is Page and the other is Attachment.
For your case, view-2 would be Page and view-1 would be Attachment.
You can select various settings in the attachment view such as Attach to, Contextual filter, etc.

Check this answer about an attachment view. I had a book Drupal 6 Attachment Views, but could not find a book for D7.
Answer: I got it working using the below code in 'Global: PHP' > 'Output code' field.
<code>    <?php print views_embed_view('view-1','default', $row->tid); ?>
</code>
Comment: Mind that you need the Views PHP (https://www.drupal.org/project/views_php) module to enable the field *Global: PHP*.

Print a view within another view


AMPLPY decrypt and encrypt

Question: I am using amplpy to access AMPL from my python.
I want my dat file to not be in plain text.
Is it possible?
I cannot find any api to do it
Answer: Yes, it's possible. You can import data from Excel or CSV files. Then fed into the data to the .mod file. Here, I am feeding a pandas dataframe to the .mod file. One thing to be remembered Pandas dataframe and amplpy dataframe is completely different.
from amplpy import AMPL, DataFrame, Environment
df_mpij=DataFrame.fromPandas(df_mpij, index_names=('nodes','dertype'))
ampl.set_data(df_mpij)

AMPLPY decrypt and encrypt


SSH tunnels with multiple outbound IPs

Question: I have a VPS with multiple IP addresses allocated to it (we can use debian, centos or ubuntu).  I can ssh tunnel through the server using any of the IP addresses.  However, any ssh tunnel I set up always shows just one IP address to the final destination site.
me --ssh to IP1 --> |server|----> http:// whatismyip.com (displays IP1)
me --ssh to IP2--> |server|----> http:// whatismyip.com (displays IP1)
me --ssh to IP3--> |server|----> http:// whatismyip.com (displays IP1)
How do I configure the server so that when I ssh tunnel into IP1, its outbound IP is IP1.  And when I ssh tunnel into IP2, its outbound IP is IP2?
What I want:
me --ssh to IP1 --> |server|----> http:// whatismyip.com (displays IP1)
me --ssh to IP2--> |server|----> http:// whatismyip.com (displays IP2)
The IPs are in different subnets (actually different Class As entirely).
Comment: I don't understand the question. If you initiate the SSH tunnel from C1 to P1 those two will always be the end points. The server can't respond from another IP. Please clarify.
Comment: Clarified Above (I hope)
Comment: Tell us more about the IP addresses you have assigned.  Are they all in the same subnet?
Comment: Added that the IPs are in different subnets.
Answer: The IP address you use to make your connection to the SSH server really has nothing to do with what IP address that is used by SSH when it initiates outbound connections on your behalf.
The source address of packets being transmitted via a tunnel is going to depend a lot more on route table(s) and default gateway of the SSH server.
If all your addreses are in the same subnet I don't believe there is any way that you will be able to set the source address using only ssh.
As an alternative I believe you could  setup multiple instances of OpenVPN each with their own tun and ip address range.  Then setup different NAT rules for packets coming from each VPN instance.
Answer: thats a dirty solution and can cause problems.
> iptables -t nat -A POSTROUTING -j SNAT --to IP2
>
> so
> IP1 ---> IP2
> IP2 ---> IP2
> IP3 ---> IP2

If you need to change and dont have any other iptables rules, just restart iptables, than everything should be flushed.
I have the same trouble like you, and thats the best i could found out.
Answer: This isn't a tunneling problem.  If you are on the server and SSH from it (that's how you make a tunnel, right?), you'll see that those tunnels are setup using the same IP address.
This is a TCP routing problem.  if you run netstat -rn, you'll see your routing table.  Most likely, you are routing all packets out the same interface -- your default route.  You need very specific routes that have a higher priority than your default route to take precedence.
Answer: You can add different users for every ip, and match them on their userid:
useradd IP1
iptables -t nat -m owner --uid-owner IP1 -A POSTROUTING -j SNAT --to IP1

user IP1 will now always use IP1, even trough ssh.
Answer: Sorry, this is no answer -- I was hoping to be able to append a comment to the above instead but I'm new to this site.
I just wanted to add that I heard it may be possible to set which interface is used for outgoing traffic per shell user (UID). Not entirely sure how, I'm trying to figure it out myself because it's been a long time now I've wanted to use the 3 outgoing IPs on my VPS (without setting up dedicated proxy software).
Answer: Better you edit file ~/.ssh/config file. If not exist you may create that file. Sample....
Host server1
     HostName server1.cyberciti.biz
     User nixcraft
     Port 4242
     IdentityFile /nfs/shared/users/nixcraft/keys/server1/id_rsa

Then you may easily type ssh server1 from your command shell.
Comment: This doesn't even remotely address the question.

SSH tunnels with multiple outbound IPs


PHP 8 $_SERVER['SSL_PROTOCOL'] is missing on some servers, how to determine encryption protocl and version

Question: We recently upgraded our servers to PHP 8 and on one of the servers the $_SERVER['SSL_PROTOCOL'] variable is missing.

I couldn't find any reference to it on php.net.
I am aware that some variables are pulled from other parts of the system though I'm not familiar with where PHP gets this particular variable from.
All search results I've found using quote operators revealed only irrelevant data.
I attempted to see if the variable name was changed to something like TLS_PROTOCOL because SSL has been irrelevant for some time.

My goal is to ensure that clients are using TLS 1.2 or TLS 1.3 and this was the critical component to that. How do I either get $_SERVER['SSL_PROTOCOL'] or at least determine the protocol and protocol version of the network encryption type being used by clients via PHP?
Comment: Probably a stupid question, but is that server serving https pages with Apache?
Comment: @SiebeJongebloed Not a stupid question, I should have mentioned Apache and yes.
Comment: "My goal is to ensure that clients are using TLS 1.2 or TLS 1.3" can you not disable other protocols on the HTTP server?
Comment: @miken32 Yes, I've disabled 1.1 and older: https://www.immuniweb.com/ssl/jabcreations.com/2pIGVaRM/
Comment: Then no such clients will ever reach your PHP code.
Comment: @miken32 Please clarify...no one should be accessing server code.
Comment: I mean, what you're trying to do is unnecessary because they will never connect.
Comment: @miken32 Oh, no I'm aware that people using IE6 from 2001 won't connect and frankly I do suspect that I'll be able to live with myself.
Answer: The SSL/TLS encryption is handled by your web server, not by PHP, so this variable has to be set there. The upgrade of PHP is coincidence - it's something else you've upgraded or re-built that has caused the difference.
If you are using Apache, this information is disabled for performance unless you set SSLOptions +StdEnvVars. See the documentation at https://httpd.apache.org/docs/current/mod/mod_ssl.html
A quick search suggests Nginx doesn't set this variable natively at all.
Comment: I know Apache handles it, I just didn't make the full connection after doing all of the searching, testing this out now...
Comment: I'm having trouble getting this to work; the documentation says that it'll work with `.htaccess` files and I've even outright rebooted the server a couple times for tests and nothing; e.g. `SSLOptions +StdEnvVars +ExportCertData`. What am I doing wrong?
Comment: @John You say it's missing "on one of the servers"; presumably, there is some difference in the configuration of that server. Maybe something is specifically turning it _off_?
Comment: *sigh* It's a cPanel server so I'll call my host and check. Usually when it's something off like that it's cPanel... Will report back.


What is it called when a song ending fades out while repeating a theme

Question: I find it very pleasant when a song (mostly progressive rock songs, in my case) ends by looping through a somewhat repeating theme before fading out.
Good examples would be:

Gentle Giant - Three Friends (from "Three Friends" album)
Dream Theater - Scarred (from "Awake" album)

(I am sure there are dozens of other examples but these two are very representative).
The question is: regarding compositional structure, is there a specific name to describe that?
Answer: It's called a Repeat and Fade.  It's hardly a compositional structure, more a cop-out for having not being able to think of a good ending :-)
Comment: Earliest example I know of a fade-out:  "The Planets" by Gustave Holst, 1916.  In a live performance, the chorus is off-stage and the door is slowly and silently closed.  Holst didn't give the effect a name, as far as I know.
Comment: Actually that is completely wrong. Fading out is a very strong psychological device. Surely you are not suggesting that many of the greatest pop composers that fade out their material are simply taking an easy way out? After all, They can't fade them out life and have to play and ending... why wouldn't they just do in the recording then?
Comment: Seems to me like the "cop-out" comment was meant as a joke, especially given the use of the smiley.
Comment: Absolutely — a studio fade can be quite effective. That said, you can do a fade when performing live, but it's usually used quite differently than what a studio fade would be.
Comment: I accepted the answer because even [Wikipedia](https://en.wikipedia.org/wiki/Conclusion_(music)#Repeat_and_fade) mentions the term, but I'm still unsure if the cop-out part was ironic or not ;-P
Comment: @AbstractDissonance: Why they'd do it in the studio recording if it's not possible live – well, live endings needn't be very sophisticated, often it's just a lot of repeating the last chorus (which may be great live when everybody sings along, but can easily get boring on a recording) followed by some kind of cued ritardando to the last chord, which rock bands tend to hold a couple of seconds with much guitar-flailing and drum filling. That wouldn't work well on the radio, hence the easy way out of fading away during the repetitions.
Comment: @MarkLutton I suppose a rock band could slowly load all their gear on a trolley and move it away from the audience?
Comment: @leftaroundabout But if an ending works live then it should also work on a recording. The point is, that there is more of a "fade because we couldn't come up with an ending". As you said, it is very easy to come up with an ending... hence fading is not because of a "cop out"... which was my point.
Comment: @AbstractDissonance The drummer could stop playing and the guitars could just gradually lower the volume on their amps.
Comment: @MarkLutton lol, that's not a fade of the music though. That is just a ringing out. That happens anyways. Guitars and other instruments naturally fade out when not being played.  While they could lower the guitars and use a volume pedal to slowly reduce the amplitude, again, that is not a "studio fade".  Guitar sound different at different volumes. Also, most guitarist use a whole host of pedals including compressors and natural OD of the amp and sometimes noise gates. These tend to make it impossible to play at low enough volumes.
Comment: At most, you could have the sound engineer lower the "masters" and make everyone go direct in so he has full control(except for acoustic instruments).  This is about as close as you can get to a true studio fade(since that is effectively what happens).
Comment: The 'cop-out' was only partly a jest.  A RTF can be effective on a recording.  It's horribly weak in live performance.
Answer: As has been mentioned in some other posts it is also called a vamp.
Comment: A vamp is more typically a repeated section waiting for a cue in order to carry on.   'Vamp until ready' is frequently seen in theatre music.   I've never seen 'Vamp and fade'.
'Vamp' also refers to a type of 'oom-pah' piano part.  Sort of the equivalent of 'just strumming' on a guitar.
That's probably enough things for 'vamp' to mean.  Let's allow a Repeat and Fade to be called just that.
Answer: I just had the same question, here are a couple answers I found on Wikipedia.
al niente: to nothing; fading to silence.
perdendo or perdendosi: losing volume, fading into nothing, dying away
Answer: Smorzando
[smort-SAN-do]
1.
(music, especially as a direction) in a way that dies away.
2.
(adjective, of music) dying away.


i m not able to store the input data of form on the redirect page ...both form has same input data form

Question: this is playingcards-quote.php

            First Name*:

            <input type='text' name='name' id='name'  maxlength="50" value="<?php if(isset($_POST['name'])) { echo htmlentities($_POST['name']);

        }?>" />

The redirect page has same input form data as playingcards-quote.php

            First Name*:

            <input type='text' name='name' id='name'  maxlength="50" value="<?php if(isset($_POST['name'])) { echo htmlentities($_POST['name']);

        }?>" />

I m not able to store the input data of form on the redirect page ...both form has same input  data form
I have two page .both having same input form value
When i submit the form value of one page the same value should be seen in redirect form page
Comment: If you store the data you could just fetch them from the database for the second form
Comment: It's not clear to me what you're describing.  Can you elaborate on the problem?  What "redirect" are you talking about?  This just looks like the same code twice, what's the difference?
Comment: If I get it right he wants when a user submits first form to redirect to a new page with the second form and set the field from the first form
Comment: @David i want a input form  value shoul not lose the value even after redirecting the another page . my 1st form and   redirecting page  form is exact same form .i want to preserve the value in the from 1st form to 2nd form
Comment: @l.g.karolos my first form is getting stored but after redirecting to redirecting page the input data loses it value
Comment: @Neetuyadav: How is it "redirecting"?  Where do you pass along or store the values?
Comment: @David first form page is playingcardsquote.php which has one input value name it has action as thankyou.php when i click submit button of the form it is going to thankyou.php but my input data is lost at thankyou.php form
Comment: @l.g.karolos  i m  not using mysql or database at all .i have no mysql code in my form
Comment: you can use $_SESSION right?
Comment: @Neetuyadav: That's not a "redirect", it's just a form post.  Show the form and show the code that's using the form values.  We can only help with code we can see.
Comment: @David i m talking about $_SESSION ...how i can use the $_SESSION on the redirecting page so that i cannot lose the 1st form input value
Comment: @Neetuyadav: There's no mention of session in the question.  Did you try a Google search for something like "PHP session example"?  What have you tried and where are you stuck?  What does *any of this* have to do with the code you're showing in the question.  Nothing about what you're asking is clear or answerable.  Be specific about the actual problem you're encountering.
Comment: @AshishSrivastava if i want to store name .how can i use it with session .how to write full code i want to store name
Comment: I guess this [answer](https://stackoverflow.com/a/31038876/5588347) should help you.
Answer: try this .hope this gives you an idea. unless I misunderstood

    <form action="pass2.php" method="Post">

    <input type='text' name='name' id='name'  maxlength="50" />

    <input type="submit" value="Submit"/>
    <form/>

Your Form 2 which is "pass2.php"

<input type='text' name='name' id='name'  maxlength="50" value=<?php echo $_POST["name"]?> />

Comment: Thank you .That all i was in need


"bad" language in questions

Question: I've come across a post edit and I wasn't sure what to do with it.
OP used the term Googling my ass of which was removed in an edit by another user. For me this kind of language is no issue but I guess some people might find it offending.
Is it ok to always approve these kinds of edits or do we draw a line at cursing and stuff like that?
Or, optionally, am I just overthinking it way to much :)
Answer: I don't find it offensive... But, for some reason, with other men it's all fine, if a girl reads that, I would have some objections.
I had the opportunity to work in teams with very smart programmers. In that environment there was a lot of swearing. After spending 1 day in that team you could swear for 30 minutes without repeating yourself.
Some code comments would involve swearing.
Now, the difference is that this is a public space. It's like an open space... You don't swear and use bad language when a customer is visiting your company.
And then is the debate, can Googling my ass of be considered bad language. From my point of view ass doesn't qualify.
What I would consider offensive:

remarks about 1st and 2nd grade relatives
phrases involving genital organs
TBD ... (feel free to pitch in)
Comment: Thanks, I agree. I've never worked with developers that don't swear. Diseases, genitals and remarks on family members are definitely not ok but the rest is fine by me too.
Comment: how about combining remarks about relatives and some organs? :)
Comment: @Marius I think I know a few of those in Romanian that you might be talking about and they are DEFINITELY not appropriate ;)

"bad" language in questions


Problema com erro de sintaxe no else python

Question: Estou tendo um problema nesse código em Python onde, quando tento executar, ele me informa que existe erro de sintaxe em um else. Segue o código e o erro abaixo:
n=int(raw_input(''))
i=0

for i in xrange(0,n):
 num_poco=int(raw_input(''))
 tipo_do_poco=raw_input('')
 custo_poco=float(raw_input(''))

 if tipo_do_poco.upper() == P or tipo_do_poco.upper() == G:
    vazao=float(raw_input(''))
    enxofre=float(raw_input(''))
    if enxofre == E:
      taxa_enxofre=float(raw_input(''))
    elif enxofre != E:
      taxa_enxofre=0.0
 else:
    vazao=0.0
    taxa_enxofre=0.0
    lucro=0.0
    receita=0.0
 print'============================================'
 print('Empresa de Perfuracoes Furo Certo S/A.')
 print('Poco no.: %d'%(num_poco))
 print('Custo do Poco                : R$%11.2f'%(custo_poco))

 if tipo_do_poco == P:
    print('Volume de Petroleo encontrado: %11.2f'%(vazao))
    receita = vazao * 5.50 * (1 - taxa_enxofre)
 elif tipo_do_poco == G:
    print('Volume de Gas      encontrado: %11.2f'%(vazao))
    receita = vazao * 2.20 * (1 - taxa_enxofre)
 else:
    print('Volume de          encontrado: %11.2f'%(vazao))
    receita = 0.00
 lucro=receita-custo_poco

 if (receita - custo_poco)>50000.00:
     print('Lucro do Poco (gusher)       : R$%11.2f\n'%(lucro)
 else:
     print('Lucro do Poco                : R$%11.2f\n'%(lucro)
     #print('============================================')
     #print('')

 custo_total = (total_custo+custo_poco):
 total_receita = (total_receita+receita):
 total_lucro = (total_lucro+lucro):
print('=======================================')
print"Empresa de Perfuracoes Furo Certo S/A."
print('Total de Pocos          : %d'%(num_poco)
print('Total dos Custos        : R$%11.2f'%(total_custo)
print('Total da Receita        : R$%11.2f'%(total_receita)
print('Total do Lucro          : R$%11.2f'%(total_lucro)
print('=======================================')

Traceback (most recent call last):   File "python", line 41
      else:print('Lucro do Poco                : R$%11.2f\n'%(lucro)
         ^ SyntaxError: invalid syntax
Comment: São tantos erros de sintaxe que é difícil listar todos. Parenteses nas linhas 40 e 42, 51, 52, 53 e 54; Dois pontos sobrando nas linhas 46, 47 e 48; Função `print` com parenteses na versão 2.7 do Python; Indentação muito esquisita para um programa em Python; e segue em frente.
Comment: Faltou parênteses no `print` do último `else`. E parênteses no `print` do último `if` também
Answer: Erros de sintaxe basta você ler a mensagem que saberá o que está errado: o erro aponta para a linha 41 e se nessa linha não tem algo errado, veja a linha acima. Neste caso, faltou fechar um dos parenteses da linha 40.
print('Lucro do Poco (gusher)       : R$%11.2f\n' % (lucro))
# (faltou este parenteses) --------------------------------^

Além disso, aproveito para listar outros erros:

O mesmo erro supracitado na linha 42;
Dois pontos sobrando nas linhas 46, 47 e 48;
Parenteses faltando também nas linhas 51, 52, 53 e 54;
Na linha 10, há caracteres que não foram definidos devidamente como strings:
if tipo_do_poco.upper() == "P" or tipo_do_poco.upper() == "G":

O mesmo problema do 4 acontece nas linhas 13, 15, 27 e 30;
Não faz sentido você definir a variável enxofre como float na linha 12 e depois compará-la com strings;
O elif da linha 15 é completamente desnecessário e pode ser substituído por um else;
Nenhum raw_input possui a identificação para o usuário de qual dado está sendo lido;
A indentação do código está completamente errada e inconstante; busque sempre utilizar 4 espaços para cada nível de indentação;
A variável total_custo é utilizada na linha 46, mas ela não é definida no código;
O mesmo para a variável total_receita na linha 47;
E para a variável total_lucro na linha 48;
Na linha 52 você exibe a variável total_custo, mas só define a custo_total;

Corrija isso e o programa (provavelmente) executará sem erros - o que não significa que está correto.
Comment: Gostei particularmente da ultima frase! lol
Answer: Arthur, quando voce for usar o % para demarcar aonde voce quer o valor de determinada variavel dentro de seu print o mesmo deve seguir a seguinte sintaxe:
print('quero falar dessa % variável ' %(variavel))

No seu caso foi omitido o parêntesis no final. Por isso esta mostrando o erro de sintaxe.
Comment: Exato, ja editei. perdão


Comparing string ArrayList

Question: I have 2 array list that contain strings:
List1 = [no, yes, ok, not]
List2 = [no, but, vote, check]

Now, how do I compare List1 with List2 and remove the words in List1 if the same word are found in List2. The sorted word(without the same word) are stored in another arraylist.
Outcome should be like this:
List3 = [yes, ok, not]

Answer: If you want to store the result in a new list, you need to clone List1 first:
ArrayList list3 = (ArrayList) list1.clone();

or
ArrayList list3 = new ArrayList(list1);

Then use removeAll:
list3.removeAll(list2);

Answer: ArrayList provides method to remove all object present in another list.
Refer Removing elements present in collection
In your case list1.removeAll(list2) should solve your problem
Answer: You can create third list , add to it your two lists and find in it third list same words. When you find them , delete one.So you'll check your third list with equals().
Answer: I suppose you didn't know about the removeAll(Collection c) method present for ArrayLists or just want another way of doing it.
Since you mention that you need to remove the duplicated words from list1, initialize a HashSet and add all the values in list2 to the Set, like so,
Set<String> set = new HashSet<String>();
for(String s: list2)
    set.add(s);

Now, do the same with a clone of list1, taking care to remove the strings from list1.
String[] list3 = new String[list1.size()];
list1.toArray(list3);
for(String s: list3)
    if(!set.add(s))
        list1.remove(s);

This is done in O(n) time, but takes some auxiliary storage. Please let me know if this solved your problem.

Comparing string ArrayList


SSRS 2008 How to automate sending of reports depending on parameter in a DB table

Question: I need to send aa report on a regular basis. Depending on the wanted parameters, I should configure manually 260 subscritions.
I'm guessing there is a way to automate this, I can't see exactly what to use...
Actually all my parameters are stored in a db table, with column name corresponding to my report parameter.
Any idea?
Thanks a lot
Answer: you need to use a 'data driven subscription' Data Driven Subscriptions SSRS Standard Edition 2008