What method should be used if the clusters contains different classes?

Question: Assume that you having $N$ clusters. Each cluster have multiple classes. So we know the class ID for every major clusters, but not the class ID for the data points inside the major clusters.
Each colour is its own class ID. E.g red can be class ID 1 and blue can be class ID 2.
Assume that you are using Support Vector Machine to classify each major clusters. But in this case, SVM cannot classify each data point.
How should this be solved If I got $X$ number of points and I don't know which class they belong to, but I know which major cluster they fit in.

I found the major clusters with K-means clustering and then I'm using SVM with a linear kernel to find the mathematical expression how to classify each data point into the major clusters, but not succeed to find the class ID of the individual data points.
Do you have any suggestion?
Comment: If it's correct that the information being clustered into major clusters is categorical, discrete or nominal, which it sounds like it is, then k-means is NOT the appropriate algorithm. K-means is intended for use with continuously scaled information, ideally at the  interval scale level. A more appropriate routine for categorical information or mixtures of scales is latent class clustering as originally developed by academics like Clifford Clogg, James Coleman, William Dillon and James Heckman. If the data is massive, then see Dunson's recent work on Bayesian Pyramids.
Answer: The trouble with your example is that these clusters are not particularly informative about the color you aim to predict. If one cluster were mostly blue, another mostly yelllow, etc, then the cluster (or the location in 2D space) would be informative about color/category. If your real work looks like the posted example, you probably do not have adequate data to make accurate predictions.
Distinct outcomes need to be different in the features for them to be distinguished from each other. Your example lacks this characteristic.
If there is a third feature (interpret it as being in and out of the image) and the colors in each cluster correspond to how far out of the image the points stick (might ot be the same for each color in each cluster), then knowing both the cluster (or just the $x$-$y$ coordinates) and the height might allow you to improve performance.
Comment: I understand that I need to find more dimension that can separate the data from each other.
Comment: The last two images in my answer [here](https://stats.stackexchange.com/a/625461/247274) seem related.
Comment: Thank you so much. You this problem is impossible to solve? Do you recommend for example UMAP or t-sne for reducing the dimension before linear SVM classification?
Comment: @euraad If nothing in the feature space differentiates one category from another, then there isn't much you can do. UMAP and t-SNE are nice tools for reducing the dimension to something that can be visualized, but if you just have two features like you have in your example, you can plot the entirety of the data set and examine, visually, if there is anything that distinguishes one color from any others. Your example seems to lack that. Perhaps your real data do not. // My answer at the link I gave is worth reading. This questions is, arguably, a duplicate in disguise.
Comment: Thank you so much. I will think a while which method I could use. My data is just typical image classification with object detection.
Comment: Then you have way more features that just two. Why not use those features instead of the cluster membership? Clusters don't have to relate to the outcome categories of interest. The outcome categories of interest do not even make an appearance in the clustering, and the clustering will be the same no matter what outcome you aim to predict.
Comment: Well, the data of the images comes from interest points e.g `corners` or `edges`. One edge can be found in a lot of different images. The edge can be described as a binary feature e.g `0b110101010111`. So my goal is to classify on that type of data. This is a simple 5 minute tutorial how to classify images with object detection. Very simple with K-NN, but very CPU expencive. https://www.youtube.com/watch?v=25GkgxClSaU&ab_channel=CyrillStachniss
Comment: I want to use SVM instead of K-nn.
Comment: What keeps you from running SVM? I don't follow why the clustering is useful.
Comment: I'm writing C code from scratch, real ANSI C (C89), and I have built 1-layer linear Neural Network with SVM. So when I'm using SVM, then I'm often using multi-class SVM with a kernel. Sometimes a kernel, depending on the data.
Comment: Most people using Python, R or Matlab for machine learning....but I'm using C.
Comment: That doesn't explain to me why you want to use this clustering in your pipeline. However, even if you have a reason, the fact remains that, if your clusters are highly diverse in the outcome categories they contain, then they are not informative of the category to which a new point in that cluster will belong. You need something to differentiate the yellows from the pinks from the greens.
Comment: The reason why I'm using SVM is because SVM gives me a model back, multi-class or single class, but K-NN requries that I need to save the data so I can compare the unknown data and predict the unknown data with the saved data, e.g L2 norm or hamming distance in this case.
Comment: But why are you clustering at all?
Comment: I'm clustering because my data belongs to different classes. The ideal is to have like...one cluster is one specific class. But that's a dream.
Comment: I recommend posting a new question about using clustering in classification.
Comment: Thank you. I will do that.
Comment: By the way! I solve the issue....K-means clustering -> Linear SVM two times. Done....
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/149506/discussion-between-dave-and-euraad).
Answer: This problem violates the so-called cluster hypothesis which states that points in the same cluster should generally belong to the same class. Here the clustering appears uninformative for determining the actual class of each individual. We have no useful measure of similarity of samples that actually belong to the same class, as the clustering seems to capture nothing useful about the classification under study. A clustering is useful when it groups items in some logical way according to similarities you actually care about. This is not a useful clustering in the context of this classification, as it does not group items of the same class together. It's a fundamental disconnect between the clustering and the classes, one is not useful for predicting the other.
Comment: @euraad It doesn't look like it, although there's no hard cutoff between "possible" and "not possible", just a decreasing ability to get a good result. The data you show looks very close to "not possible", as there is virtually no association whatsoever between the clustering and the classes you actually care about. It'd be like grouping people by the first letter of their last name, and trying to predict their favorite genre of movie - there just isn't any useful relationship between the two to leverage.
Comment: @euraad You can always make predictions, but what you've shown in your example makes it seem like those predictions cannot consistently be accurate. For instance, if you know that a new point belongs to that cluster on the right, doesn't it seem like there is a one-in-seven chance that it belongs to each color group? That seems to be about all you can say.
Comment: @euraad You could possibly do very slightly better than random guessing by recognizing that being in the top two clusters gives a slightly increased probability of being in the brown class, while being in the bottom right cluster implies that it's not the yellow class. But with almost all classes observed in all clusters, even if the performance is "better than random", it's still likely in the range of "not useful".
Comment: So you are saying that this is not possible to make predictions if the same clusters shares the same classes?
Comment: I understand! Well, perhaps I need to add some dimension reduction. If you wonder what the data is, it's binary data e.g `0b110100101001001`. I want to classify this. The data comes from ORB or SIFT classification for images. The most common tool is to use K-NN with `sum(XOR(Class Image data, Unknown Image data))`. If the sum is small, then the image belongs to a specific class.
Comment: To be honest, I could classify with K-means + linear SVM and then make a histogram how often e.g. cluster 1 and cluster 2 and cluster 3 and cluster `N` gets its points. Then I use K-NN to classify the histogram. But the problem with that method, is that is very sensitive for noise.


What is the bare minimum requirement for a monad to participate in the composition offered by LINQ?

Question: I recall that the C# compiler, when translating from the query expression syntax to calls to the relevant operator methods on the monad, doesn't really care about and doesn't require the monad to have implemented some interfaces.
It doesn't even care of the operator methods are extensions or real instance methods.
But I can't recall the details at all. It seems like there is a bare minimum requirement for the sequence itself, which, in my query below would be the new Foo<string>() expression.
I recall it doesn't necessarily have to adhere to an interface but it either did have to have a method named GetEnumerator or it did have to implement the IEnumerator<T> methods. But I could be wrong since my example query shown below works with or without the presence of a GetEnumerator method in the Foo<T> class.
However, when I introduce a where query expression, that doesn't resolve the type of the receiver.
The Select expression works just fine.
I used to know this at the back of my hand until 18 months ago, which was the time I implemented a trivial LINQ provider. I have since forgotten much of it.
Could you please list the bare minimum requirements for all this to work?
using System;

namespace CompilerDoesNotCareAboutTypeLINQQuerySyntax
{
    class Program
    {
        static void Main(string[] args)
        {

            // What are the minimum requirements on Foo<T>()?
            // How does it resolve this expression new Foo<string>
            // such that it knows that Foo<string> has many Bar<string>
            // or whatever foo in the query below might resolve to?
            var query = from foo in new Foo<string>()
                        /* where foo. // when I do foo., only the system.object inherited properties of Foo show up */
                        select foo;
        }
    }

    public class Foo<T>
    {
        public string Name { get; set; }

        public Foo<T> Where<T>(Func<T, bool> predicate)
        {
            return new Foo<T>();
        }

        /*IEnumerator<Foo<T>> GetEnumerator()
        {
            return new List<Foo<T>>().GetEnumerator();
        }*/
    }

    public static class Extensions
    {
        public static Foo<R> Select<T, R>(this Foo<T> foo, Func<T, R> transformer)
        {
            return new Foo<R>();
        }
    }
}

Update
Here's an update of the Where method declaration after implementing the fix that Servy pointed out.
class Foo<T>
{
  public Foo<T> Where(Func<T, bool> predicate)
  {
    return new Foo<T>();
  }
}

That fixes the bug due to which foo in the above query expression query resolved to system.object. However, it now resolves to string, which, by inference, is the generic type parameter type of the Where method.
It earlier resolved to object because I had overloaded the generic type parameter T as Servy pointed out, and now it resolves to T, which is the generic type parameter of the declaring type Foo<T>.
The question still remains:
What is the bare minimum requirement on the sequence expression new Foo<string>()? It looks like there is none? Then what is the correlation between the value of the expression that will sit in the place of the sequence and the type of the range variable foo? If I had to make it such that new Foo<T> returned many foos and therefore the foo in the query from foo in new Foo<T>()... resolved to a single Foo<T>, what would need to be done?
Answer: The problem here is that you're overloading T in your implementation of Where.
You define T as the generic argument to the type itself, and you also define T as the generic argument to the Where method.  Since the method's argument is "closer" it takes precedence.  This means that the T in Func<T, bool> is the method arguement's T, *but not the class's T.  The class's T is string, but the method's T cannot be inferred to be anything, which is why you're not seeing string members of the parameter.
In this case, it doesn't seem like you need the method to be generic at all, since the type itself is already supplying you with the generic argument.  You'd only need that method to be generic if it was an extension method not on the type itself.  Just make the method not generic and your code will work just fine.
Comment: Thank you. My bad. So it turns out there is absolutely no requirement on anything at all to conform to anything?
Comment: When I do a `where foo.` after correcting the problem you highlighted, why does `foo` evaluate to `string`?
Comment: @WaterCoolerv2 The generic argument of the type is a `string`, and that same generic argument is the parameter to the method, so it has to be a string.
Comment: @WaterCoolerv2 It needs to be a method named `Where` accepting a single argument that is a delegate single argument and returning a value.
Comment: Sorry I had understood your answer and implemented the fix in my code but had not updated the question. I have now updated the question. I am still at a loss of understanding about the correlation between the sequence expression and the range variable in the above query. I have updated my question to try to be more precise about my confusion.


Does the MLE estimator of the covariance of a multivariate Gaussian have a non-zero determinant?

Question: The MLE estimator of the covariance of a multivariate Gaussian is
$$
\mathbf{\Sigma} = \frac{1}{N} \sum_{n=1}^N \left( (\mathbf{x}_n-\boldsymbol{\mu}) (\mathbf{x}_n-\boldsymbol{\mu})^\intercal \right).
$$
Can we prove that its determinant is non-zero?
Comment: The determinant is $0$ when $N$ is less than the number of scalar components of $\mathbf x_n,$ and is $0$ when the determinant of population covariance matrix is $0.$ Otherwise, the probability is $0$ that the determinant of the MLE is $0.$ If you use $\mathbf\Sigma$ to denote the MLE, then how do you denote the population covariance matrix that you're estimating? $\qquad$
Answer: Determinant of $\Sigma$ may be zero.
Let $k$ be the dimension of the space to which the sample vectors $x_n$ belong. If $N < k$ then $\Sigma$ is not full rank and therefore $\det \Sigma = 0$.
Moreover, even when $N \ge k$ it is still possible that $\det \Sigma = 0$. For a simple example, suppose that $k=2$ and that the sample vectors $x_n \in\mathbb{R}^2$ originate from the distribution $(X, X)$ where $X \sim \mathcal{N}(0, 1)$, i.e. the two components are perfectly correlated. In this case
$x_n = (a_n, a_n) = a_n (1, 1)^T$ for some real numbers $a_n$ for all $n=1,\dots,N$. Therefore,
$$
\det \Sigma = \det \left(\frac{1}{N} \sum_{n=1}^N x_n x_n^T\right) = \det \left(\frac{1}{N} \sum_{n=1}^N a_n^2 \begin{pmatrix}1 & 1 \\ 1 & 1\end{pmatrix} \right) = \det \begin{pmatrix}a & a \\ a & a\end{pmatrix} = 0
$$
where $a = \frac{1}{N} \sum_{n=1}^N a_n^2$.

On the other hand, note that the set
$$
\mathcal{X}_0 = \{(x_1, x_2, \dots, x_N)\,|\, \det \Sigma(x_1, x_2, \dots, x_N) = 0\}
$$
of $N$-tuples of samples $x_n$ for which $\det \Sigma = 0$ has dimension one less than the dimension of the set of all $N$-tuples of samples $x_n$. Therefore, if $N \ge k$ and $\det \Sigma' > 0$ where $\Sigma'$ denotes the covariance matrix of the underlying distribution, then the set $\mathcal{X}_0$ has measure zero and consequently $\det \Sigma > 0$ with probability $1$.

Remark about practical applications: Note that in a practical application one would probably not care about strict equality $\det \Sigma = 0$, but about whether $\Sigma$ is nearly singular (in fact one may care about a stronger condition that $\Sigma$ is well-conditioned).
By the multi-dimensional variant of the Central Limit Theorem as $N\to \infty$, the sample covariance $\Sigma$ converges to $\Sigma'$. Therefore, if the eigenvalues of $\Sigma'$ are large then for large $N$ it becomes increasingly unlikely that $\det \Sigma$ is near zero.
On the other hand, if $\Sigma'$ does have small eigenvalues then one can use Principal Component Analysis to identify a subspace $V$ on which the eigenvalues of the restriction $\Sigma'|_V$ are large and therefore $\det \Sigma|_V > 0$ with high probability.

Lower bounds: There are lower bounds on the eigenvalues of $\Sigma$. For example, for isotropic distributions, i.e. ones with $\Sigma' = \alpha I$ lower bounds on the smallest eigenvalue of $\Sigma$ are derived in this paper.


Qual é a diferença entre $digest e $apply?

Question: No AngularJS, temos dois métodos que executam os $watchers sincronamente: $digest e $apply.
Eu gostaria de tirar umas dúvidas:

Qual é a diferença entre eles?
Quando devo usar um ou outro?
Comment: Essa pergunta é útil. Linkei ela em outra pergunta, para o assunto não ficar muito amplo e fora do foco da resposta.
Answer: Olá, vou tentar responder essa pergunta usando os conceitos apresentados no livro: AngularJS Up & Running(Shyam Seshadri & Brad Green) e na própria documentação do AngularJS encontrada aqui.
AngularJS LifeCycle

Primeiramente precisamos entender o que acontece em uma aplicação angularjs quando a mesma é iniciada.
Vamos abstrair toda a parte que navegador ler o que está escrito, assets, html em sua página e vamos pular direto pra parte onde é disparado o evento document.ready onde, em uma inicialização não manual, o angularjs irá buscar através da DOM a diretiva ng-app, ou utilizando o angular.bootstrap, é especificado manualmente onde a(s) aplicação(ões) irá(ão) executar.
Após encontrar o ng-app, o angularjs irá iniciar sua "mágica" que é o passo onde o que está no contexto atual é compilado, nesse processo o código definido nas diretivas encontradas é executado, e no final de cada execução é gerado a função link das respectivas diretivas.
Com as funções link geradas o angularjs as combina com o nosso conhecido escopo, no qual contem as variáveis e conteúdos que é preciso pra gerar nossa UI, com a combinação é gerado a view, que é o que o usuário irá ver e interagir. Nesse passo também é instanciado o escopo de cada controller e subcontroller, e agora que entra a parte que queremos... "É ele que a gente quer...", aqui é onde aparece os nossos amigos:  watcher e listener, o angularjs irá criar um para cada diretiva que ele encontrou e compilou, assim o nosso querido framework sabe onde encontrar cada coisa e que dado vincular à aquela diretiva.
Beleza, até ai tudo bem... Mas como ele atualiza tudo dinamicamente??
The Digest Cycle

Bom para manter tudo atualizado o angularjs usa uma estratégia bem inteligente. Como sabemos o model da aplicação não atualiza randomicamente, ele irá mudar em resposta a eventos (requisições, cliques, focos...), logo o angularjs adicionar watchers a todos binds e ng-models e o mesmo pode verificar se os valores contidos naquele escopo difere do que está na UI, e assim pode atualizá-la,

Mas ele não fica em um loop verificando a cada segundo se está tudo
  atualizado.

Provavelmente qualquer pessoa "normal" se inclinaria para essa ideia, porém obviamente isso é bastante ineficiente.
Como foi falado, o nosso model não atualiza randomicamente, porém há certas ações que provavelmente irão modificar ele, logo cada ng-model que pode mudar tem o seu respectivo watcher e sempre que um evento é disparado o angularjs verifica os watchers e bidings procurando por alterações e fazendo as devidas atualizações necessárias, e essa operação é  chamada de
Digest Cyle.
O digest cycle é o que mantém a UI da nossa aplicação atualizada, e o trabalho que ele faz pode ser explicado nos seguintes passos:

Sempre que um evento que pode mudar o model dispara, o angularjs executa o digest cycle.
O digest cycle começa pelo $rootScope e vai verificando cada escopo procurando se existe alguma diference com o que está na UI.
Se estiver tudo ok no escopo atual ele vai recursivamente até o seu escopo pai verificando todos adjacentes até o fim.
Se por acaso o AngularJs verificar que um watcher reportou uma diferença ele é reiniciado.
Ele reinicia pois uma alteração pode modificar um o estado de um watcher previamente verificado, e assim desencadear varias outras, ele somente para quando todos os watchers não reportarem modificação.

Para prevenir um loop infinito o angularjs reinicia o digest apenas
  10 vezes.

Todas as atualizações da UI são acumuladas e assim que o ciclo é estabilizado, todas as atualizações são aplicadas.

Imagem para entender melhor todo esse ciclo:

FONTE: https://stackoverflow.com/questions/50594246/is-there-a-config-option-to-lower-the-amount-of-angularjs-1-x-digest-cycles
$scope.$apply() e $scope.$digest()
A similaridade entre estes dois métodos é basicamente chamar o que foi explicado anteriormente, o digest cycle, a diferença entre eles está baseada nos escopos.
Enquanto o $scope.$apply() força a execução do digest cycle direto do $rootScope (Basicamente toda a aplicação atual) o $scope.$digest() força a execução do digest apenas em o escopo atual.
Com isso em mente é possível imaginar em quais casos é bom ou não utilizar o $scope.$apply() e $scope.$digest(), a dica é: Em certos casos não precisamos verificar todos os watchers de nossa aplicação, apenas o escopo atual.
É preciso tomar cuidado ao utilizar componentes de terceiros que utilizam um life cycle diferente da sua aplicação, e nesse caso o mais indicado é utilizar o $scope.$apply() pois a atualização deve ser feita através do $rootScope, e não apenas no escopo atual com o $scope.$digest().


matching regular expression in R

Question: I am trying to extract the matching pieces from a text paragraph using stringr- one of the text is
if returnValue is not null then
1. if  instrument type is "Bond" then
      Status is equals to 138 if the instrument is sensible coupon,
      coupon type is not null and not equals to "ZERO COUPON" and previous value
      is not equals to current value, and iinstrument creation date is not D
- Status is equals to 137 if the instrument is sensible bbg, previous value
      is not equals to current value, and iinstrument creation date is not D or D-1
- Status is equals  to the previous status if  the value is not manual
        and previous status is 138, or 137

2. if attribute SEC_PAYT_DTE is not null then
    if attribute SEC_PAYT_DTE (typed as date) is fresher than
        returnValue (typed as date) then
    set status to 136 that is "Functional Error"
3. if acrual date (DEBT_STRT_ACRL_DTE) is not null  and instrument
        category is "Structured Product", and acrual date is different
        frorm return value then
  set status to 150 that is "Non blocking functional error".

what i want to extract is 'status 138','status 137', 'status 136','status 150'.
what I did is str_extract_all(x,'(S|s)tatus[a-z\s]{1,10}[0-9]{1,3}[^\.]'). but it doesn't work.
Comment: What are the rules here?  Please explicitly define what you want the regular expression to do
Comment: I want the regex to find the string 'S(s)status'+ 0-3 digit numbers that follows right after it. for example, 'the Status is equals to 138', regex should find 138. however, 1 in 'not D or D-1' should not be returned
Comment: So what should the line `and previous status is 138, or 137` return?
Comment: this should return 138 and 137. the 'status' string isn't important, but the number(s) right after it.
Comment: So do you just want all three-digit numbers then?
Comment: yes and no. first, the number is not necessarily 3 digit, can 1-3 digit. second,it has to be one RIGHT after 'status', otherwise, it is not really the status code. but I want the number, yes
Comment: @hwnd - `paste(text, vector)` usually.  I went to the chat room you invited me to. Did you check it?
Answer: The regex matching in str_extract_all uses the POSIX standard, which does not continue looking on new lines, so you need to do this yourself.
matches <- sapply(strsplit(val, "\n")[[1]],
  str_extract_all, "[Ss]tatus is(?: equals to)? [0-9]+")
matches <- gsub(fixed = TRUE, "is ", "", gsub(fixed = TRUE, " equals to", "",
  Filter(length, matches)))
# [1] "Status 138" "Status 137" "status 138"

matching regular expression in R


how to replace blank & NULL in SELECT

Question: Please let me question about how to replace blank & NULL value in SELECT.
I have a column that is defined by VARCHAR like below. It has blank and NULL values in some row. How can I replace both blank and NULL in SELECT?
Replacing NULL with 0 in a SQL server query
-> This thread answered replacing only NULL
col1
------------
abc
------------
def
------------
NULL         <<<<<<<<<< NULL
------------
ghi
------------
             <<<<<<<<<< Blank
------------
jkl

Comment: Please tag DB engine that you use
Answer: You can use a case expression or nullif().  Something like this:
select coalesce(nullif(col, ''), <replacement value>) as col

If the logic is more complicated -- say strings of blanks -- then case is simpler:
select (case when col is null or replace(col, ' ') = ''
             then <replacement value>
             else col
        end) as col

how to replace blank & NULL in SELECT


How to instantiate an imageview by using if else condition?

Question: In my project, I am parsing an XML file. I have used if else condition to print the value in the Log cat. But, I need to know how to instantiate an ImageView by using if else condition. Here is the sample code which I am using.
For example,
if (parentTag.equals("Owners")) {

    **it must instantiate an ImageView**

                        }

Please help. Thanks in advance.
XML:
<Contents>
    <Owners>
        <Owner>
            <Name>Joselito Dimaculangan</Name>
            <Age>16</Age>
            <EmailAddress>email@example.com</EmailAddress>
        </Owner>
        <Owner>
            <Name>Noemi De Galileo</Name>
            <Age>14</Age>
            <EmailAddress>email@example.com</EmailAddress>
        </Owner>
    </Owners>
    <Dogs>
        <Dog>
            <Name>Barky</Name>
            <Birthday>June 29, 2012</Birthday>
        </Dog>
        <Dog>
            <Name>Jumbo</Name>
            <Birthday>December 30, 2012</Birthday>
        </Dog>
    </Dogs>
</Contents>

Main Activity:
while (i.hasNext()) {

                    dataItem = (ParsedDataSet) i.next();

                    /*
                     * parentTag can also represent the main type of data, in
                     * our example, "Owners" and "Dogs"
                     */
                    String parentTag = dataItem.getParentTag();

                    Log.v(LOG_TAG, "parentTag: " + parentTag);

                    if (parentTag.equals("Owners")) {

                        Log.v(LOG_TAG, "Name: " + dataItem.getName());
                        Log.v(LOG_TAG, "Age: " + dataItem.getAge());
                        Log.v(LOG_TAG,
                                "EmailAddress: " + dataItem.getEmailAddress());

                    }

                    else if (parentTag.equals("Dogs")) {
                        Log.v(LOG_TAG, "Name: " + dataItem.getName());
                        Log.v(LOG_TAG, "Birthday: " + dataItem.getBirthday());
                    }

                }

Answer: If I understand you correctly:
Create the image view in the layout itself, but set it's visibility to 'invisible' or 'gone' depending on how your layout params work.
Then in your condition set the visibility to View.VISIBLE.
Layout
...
<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/myImage"
    android:src="@drawable/your_image"
    android:visibility="invisible"/>
...

Activity
ImageView myView = (ImageView) findViewById(R.id.myImage);
if (parentTag.equals("Owners")) {
    myView.setVisibility(View.VISIBLE);
} else {
    myView.setVisibility(View.INVISIBLE);
}

or
If you'd like to programatically create the view:
ImageView imageView = new ImageView(this);
LinearLayout.LayoutParams vp =
    new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
imageView.setLayoutParams(vp);
imageView.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.myImage));
yourParentView.addView(imageView);

Comment: Thanks dude, I will try and let you know


.NET COM Interop with references to other libraries

Question: I'm up against a problem when loading a class in a managed library from a COM Interop library.
basically I have some Unmanaged C++ code and a COM Interop library written in C#. And finally a 3rd library which is referenced by the COM Interop library which contains a class:
<code>public class MyClass{
  public MyClass(){}
}
</code>
What I'd like to do is from my unmanaged c++ code, call a function in the Interop library
The C++ code doesn't need to know of the existence of the third library, it's only used within the Interop.
    Init(){
      MyClass _class = new MyClass();
    }
for some reason this line in Init fails "MyClass _class = new MyClass();", and I don't get very usefull error messages, all I have to go on is a few of these in my output window:
"First-chance exception at 0x7c812afb in DotNet_Com_Call.exe: Microsoft C++ exception: [rethrow] at memory location 0x00000000.."
and the HRESULT of the "HRESULT hr = pDotNetCOMPtr->Init();" line in my C++ code is "The system cannot find the specified file"
I'm new to COM so if anyone has any ideas or pointer to get me going the right direction, I'd appreciate it,
Thanks
Comment: I'd look at what the Init is actually doing - the error you see is probably being returned from Init on "behalf" of call it made that failed.
Answer: Nevermind, I think I just figured it out on my own. It looks like the Interop DLL and the third DLL referenced by the interop need to be located in the same directory.


Scalable way of handling font definitions in React.js application

Question: Usually in my code there are few distinct fonts I'm using with some variants like:

Arial, font-weight: 400, font-style: normal
Arial, font-weight: 400, font-style: italic
Arial, font-weight: 700, font-style: normal
Helvetica, font-weight: 400, font-style: normal
Helvetica, font-weight: 400, font-style: italic

I'm using CSS-IN-JS library styled-components for that, so not using some styles.css. Sometimes designer comes to me and asks to change e.g. Arial to Comic Sans for font-style: italic; and font-weight: 400;
This can't be code by simple replacing across the project codebase as there are other variants of this font.
I want to minimise the amount of work needed to incorporate that change, thus need to isolate those font objects in one place.
QUESTION :
I've devised 3 approaches for this and 3rd one seems to be the best one, but please advice from your experience. Maybe there are some extra cons or pros to each of those specified below?
APPROACHES :
First approach
I thought about extracting those text definitions into separate style-components, like:
const ArialGeneral = styled.span`
  font-family: Arial;
  font-style: normal;
  font-weight: 400;
`

const ArialNormal = styled(ArialGeneral)``
const ArialNormalItalic = styled(ArialGeneral)`
  font-style: italic;
`

And then wrapping all text occurrences with relevant style.
...
<HeroText>
  <ArialNormal>
    Welcome to our system!
  </ArialNormal>
</HeroText>
...

Cons of this are:

Extra JSX tags
Maybe some computational cost to re-render those extra components along with CSS computations by browser

Pros:

I will have 1 place to govern all occurrences of any given [font-family, font-style, font-weight] combination

Second approach
Use the same technic, but instead of defining styled-components use global styles.css with basically same definitions in form of classes e.g.:
.font-arial-normal {
  font-family: Arial;
  font-style: normal;
  font-weight: 400;
}

This will require to decorate text elements with some classes e.g.:
...
<HeroText className="font-arial-normal">
  Welcome to our system!
</HeroText>
...

Cons:

Using two formats CSS-in-JS and styles.css
Addition of classNames to JSX

Pros:

In contrast with variant 1, will not require resources for additional JSX compilation
Same benefit as in variant 1

Third approach
I've see in this article WebType Best practices for using font-weights and also in examples for web-fonts packages I'm downloading that each combination of [font-family, font-style, font-weight] is defined as a separate font e.g. like in this example from mentioned resource (Assuming those are all font-style: normal;):
{ font-family: "Interstate Light"; font-weight: normal; }
{ font-family: "Interstate Medium"; font-weight: normal; }
{ font-family: "Interstate Regular"; font-weight: normal; }
{ font-family: "Interstate Semibold"; font-weight: bold; }
{ font-family: "Interstate Bold"; font-weight: bold; }
{ font-family: "Interstate Extrabold"; font-weight: bold; }
{ font-family: "Interstate Black"; font-weight: bold; }

Cons:

Requires more initial work (but those webfont packages already provide the needed css)

Pros:

We are not using anything more then fonts.css where we define fonts (I use this in all variants) thus eliminating the using two formats CSS-in-JS and styles.css issues from second method
Can be used in JS-IN-CSS as I'm using it now and codebase-wide replace will change only those fonts (what I'm trying to achieve), so the same benefit as in variant 1
Comment: 3rd solution is what I use in my projects. Would recommend you to abstract away the font-family name. Say you are using a certain type of font-family with particular font-weight for all your headers, call it 'HeaderFont'. This way you don't have to change the name of the font-family everywhere you are using it and you can simply get away by changing the internal font-family in that one place only.
Comment: @DanglingCruze Thank you for comment. What do you do when your abstraction suddenly refers to more components then header, let's says after change of mind of designer? Will you create new font with different name but with same definition? Or will you rename it?
Comment: for the second approach, maybe i am being pedantic but instead of `className` you can just regular html `class` if you use `babel-plugin-react-html-attrs`
Comment: I will take time initially to figure out the sets of related and un-related components. Then define some global fonts and some related name-spaced fonts. There will be times when you will have to rename but chances of that will be very less. What you will generally get is change the font category of a particular component to a different one which I have already defined. So, I will just change the font abstraction it belonged to.
Answer: I think the biggest thing you need answer is where the font variants will take place inside your app. Are they global? Do you only need them for certain tags (i.e. h1, h2, etc)? Do you need specific overrides specific to few components?
In my experience, generally you only declare 1 or 2 fonts per app, and these generally tend to be app-wide. Its rare that I see these fonts used very specifically (i.e. 1 or 2 elements with a specific class or ID), and rather tend to be placed on body.
First approach
Assuming that are only using a single font family (i.e. "Arial", "open sans", etc), the first approach will be very hard to scale. As you mentioned, not only does it create a lot of noise, but if you name the component after the font name, it will quickly get out of date the moment you switch font families. This will require quite a few edits to your application. I don't recommend this approach unless you enjoy editing many many files when it comes time to update.
Second approach
This approach is a little bit better since you have now cut down on the HTML noise, but you have gained very little here. You still suffer from the same problem as the first approach, just in a slightly different form. Changing fonts likely means renaming the class selector, which also means updating any component that uses that class name.
Third approach
This is the closet approach to solving your needs in my opinion, though it does seem you want to keep everything inside of styled-components as much as possible. This being the case, I would tweak this approach slightly.
Alternate approach
I believe the @font-face approach paired with styled-component's injectGlobal API is going to get you the most mileage (they even mention @font-face in the docs!)
Swapping out font-families means updating your @font-family definition and updating your font-family declaration all in one go. Better yet, you avoid .css files and keep everything within styled-components!
Again, assuming your goal is to target font app-wide, with maybe a variant on a tag or two (h2, h2, etc), this allows you to make all of your edits in 1 place and I believe best accomplishes your goal.
Take a look at the @font-face documentation to get a feel for declaring your font styles in case you aren't familiar with it. I know there are plenty of resources out there to help guide you declaring @font-face as well (assuming you aren't using something like Google fonts already).
Answer: Maybe you can use css and .extend to solve this problem?
DEMO
import styled, { css } from 'styled-components';

const apply = (tag, styles) => {
  return styled[tag]`${styles}`.extend
};

// BASE STYLES

const arial400 = css`
  font-family: Arial;
  font-weight: 400;
`;

const arial400italic = css`
  ${arial400};
  font-style: italic;
`;

const helveticaNormal = css`
  font-family: Helvetica;
  font-weight: normal;
`;

const helveticaItalicBold = css`
  ${helveticaNormal};
  font-style: italic;
  font-weight: bold;
`;

const HeroText = apply('h2', arial400italic)`
  color: red;
`;

const FancyButton = apply('button', helveticaItalicBold) `
  color: white;
  background: indigo;
  padding: 10px;
`;

...

  <HeroText>Welcome to our system!</HeroText>
  <FancyButton>CLICK ME</FancyButton>

...
Another approach?
Important part of this approach is a apply function, that create the new styled-component with a basic styles.
First, you need to describe the basic styles.
Second, using the apply function, you simply extend the base style with custom styles which need for specific case (if that needed).
Pros:

using weird apply function instead of classic "styled" way

Cons:

no require extra JSX tags
one place for global styles, which can easily extend each other
because global styles still be a "styled components" that means you can use props
easy to extend existing styles, all you need just to replace styled.tag to apply('tag', baseStyles)
Comment: please see description of bounty `Nobody clarified cons and pros of stated variants. only answer proposed one more variant but lacks pros and cons.`. You've proposed new variant, but please describe it more in specified way. Also how your variant relates to other variants - maybe other way has some advantages over it, and some other have disadvantages. **I see that it's clarification of variant 1 BTW :)**
Answer: I don't entirely agree with the pros and cons stated above. Most of these are related to CSS vs CSS-IN-JS. Having CSS is perfectly fine in styled-components. My thumb rule is to use CSS for generic classes and style-components for theming and variables. Rest use whatever you feel is less awkward and maintainable.
Coming to your specific problem of maintaining fonts and font-weight changes.
I have faced similar issues few times.
Platforms with themes support, design iteration or even at hackathons.
You mostly find yourself changing these with same design language at top level.
i.e changing your primary font and weight in the app entirely.
so, Have your fonts defined with @font-face with primary, secondary, tertiary etc instead of specific font-name as you would be have to change just the definition instead of the classnames everywhere.
   @font-face {
     font-family: "primary-default";
     font-weight:  regular
     src: url("/fonts/OpenSans-Regular-webfont.woff2") format("woff2"),
          url("/fonts/OpenSans-Regular-webfont.woff") format("woff");
   }

If you would have to change primary-default to have a different font-family and weight you can modify these definitions accordingly.
If it is just a specific changes or quick overrides then use helper classes
 .primary-fontStyle {
   font-family: "primary-default";
   font-weight:  regular
 }

Comment: @zmii, Sure i updated my answer. I use a combination of approaches close to second and third.
Comment: please see description of bounty Nobody clarified cons and pros of stated variants. only answer proposed one more variant but lacks pros and cons.. You've proposed new variant, but please describe it more in specified way. Also how your variant relates to other variants - maybe other way has some advantages over it, and some other have disadvantages.
Answer: You can have one option to use props with theming support. You can pass the required values through props otherwise use default values.
Here is sample,
const General = styled.span`
  ... // other properties
  font-family: ${ props => props.theme.fontFamily };
  font-style: ${ props => props.theme.fontStyle };
  font-weight: ${ props => props.theme.fontWeight };
`

With reference to the 3rd approach, we can have the combination of [font-family, font-style, font-weight].
Component behavoiur depends on the combination passed as props to it.
let arialNoraml300 = {
  fontFamily: Arial,
  fontStyle: normal,
  fontWeight: 300
};

let helveticaOblique900 = {
  fontFamily: Helvetica,
  fontStyle: oblique,
  fontWeight: 900
}

... // other combinations

Its can be used as <General theme={arialNoraml300} /> or <General theme={helveticaOblique900} />
If we asked any change, we need to replace the combination passed to component.
Hope it help you.
Comment: I think that this will create more mess for the specific use case I'm asking about. (`styled-components` theming also produces similar kind of code). Imagine you have 1000 components that have this kind of dynamic resolution of triade `[font-family, font-style, font-weight]`. **Can you please update your answer with description of what would you do when your designed will come to you and ask to change `[font-family: Arial, font-style: normal, font-weight: 300]` to `[font-family: Helvetica, font-style: oblique, font-weight: 900]` ?** Will this be simple find-and-replace in your codebase?
Comment: I upvoted this as this is fourth interesting variant. @Harish thank you for input. Can you update answer with pros and cons of this approach and compare it with other variants?
Comment: thank you for input. Can you update answer with pros and cons of this approach and compare it with other variants?


Grafana variable and Prometheus query

Question: I have a problem trying to create a custom variable of type query with this formula :
label_values(increase(nginx_ingress_controller_requests{namespace=~"$Namespace"}[10m])>0,ingress)

When I play this query against the prometheus server (without "label_values" which is a grafan templating function) it works fine.
I have the following toast error :
Template variables could not be initialized: parse error at char 9: could not parse remaining input "(nginx_ingress_"...

The aim of this variable is to list only Ingress labels that had an activity during the last 10m.
Comment: Looks to me like the error is in the template variable definition, rather than having anything to do with Prometheus.
Answer: label_values(metric,label) is a Grafana function, not a Prometheus function.  Since it only takes a metric (not a timeseries/vector), you just want:
label_values(nginx_ingress_controller_requests,ingress)

I don't think you can restrict by namespace in the custom variable query.

Grafana variable and Prometheus query


htaccess rewrite condition old site to new site with querystring

Question: I am not even going to pretend to fully understand how htaccess rewrite conditions work. I've been working on this for a while searching and searching.
I have an old Wordpress site www.old-site.com and a new site www.site.com.  Wordpress uses query strings page_id=# to redirect to pages.
On the old site page_id=2 went to a specific page but on the new site it goes the the home page.
I need old-site/?page_id=2 to go to site.com/our-company
Here is what I am trying
RewriteCond   %{HTTP_HOST} ^(www\.)?old-site.com$ [NC]
RewriteCond   %{QUERY_STRING}   ^page_id=2$
RewriteRule   ^(.*)$ http://www.site.com/our-company/ [R=301,L]

If I take out the rewrite condition for query string it redirects all traffic from old-site.com to the company page on the new site.  Where am I going wrong?
I have about 15 redirects I need to do this way.
Comment: Have you enabled rewritelog? If not, start by doing that. Usually the problem is due to something you are trying to match not being what you expect it to be. The rewritelog will tell you exactly what is being matched against what.
Comment: Your problem is btw, a good candidate for a rewrite map: http://serverfault.com/a/496796/163704
Answer: fyi answered my own question
RewriteCond   %{HTTP_HOST} ^(www\.)?old-site.com$ [NC]
RewriteCond   %{QUERY_STRING}   ^page_id=2$
RewriteRule   ^(.*)$ http://www.site.com/our-company/? [R=301,L]

without the ? after the new url it apends the query string to the end of it adding ? ends the line there
ill look into this rewrite map
thanks


Get output from keyboard in mono powered mixer

Question: I have 2 keyboards that I want to connect to a powered mixer Work Kronus PRO 6500. The mixer has 6 mono inputs and 2 stereo RCA.
First keyboard is a Korg that has 2 outputs L (mono) and R. This one I'm connecting to the mixer with a mono cable 6.3 jack cable and everything works OK.
The second keyboard is a Yamaha PSR-550, this one has only one output (stereo I'm guessing). The problem is that when I'm connecting with the same cable no sound comes out from the speakers. This is what I don't understand. Shouldn't some sound still come out?
How can I make this setup work? Can I get a stereo cable with a splitter to 2 mono jack and insert in 2 inputs of the mixer? Or should I get a cable 6.3 jack to RCA and use one of the 2 stereo inputs of the mixer?
Answer: Make sure your instrument cables are in working order by swapping them out.  If no stereo plug is needed from the Yamaha it could be the cable that is the problem. Make sure they are instrument cables and not speaker cables.
If the instrument cable for the Yamaha came with the Yamaha, look to a plug to check for stereo or mono.  Stereo will be TRS (tip ring sleeve, or three sections and mono will be TR (tip ring or two sections to the prong of the plug).
Yes, you can get a Y adapter cable that will convert a TRS (tip ring sleeve) single plug to two TR (tip ring) plugs.  The two channels receiving the signal can be full panned L and R for stereo or pan to center for mono.
You are guessing the Yamaha output is stereo.  Single jack stereo connections use TRS (tip ring sleeve) 1/4" plugs. Two jack stereo connections use TR (tip ring) 1/4" plugs on two instrument cables.  If the Yamaha is not stereo then use a TR (tip ring) single instrument cable to make the connection to one channel.
The RCA input is most likely not be compatible with the impedance of the keyboard's output.
Comment: Thank you for answering. In the end I gave up on using the Yamaha. I want to ask you, what is the difference between speaker and instrument cable? Aren't they the same TR type of cable?
Comment: The manual (https://usa.yamaha.com/files/download/other_assets/8/336078/psrs550_en_om_c1.pdf) says the output jack is stereo and line level.  When there's a cable plugged into that jack the speakers on the keyboard itself will be shut off so the only noise you'll hear is through the mixer.  With a 6.3mm Stereo (TRS) to RCA cable you should be able to get it to work.
Comment: An instrument cable is a shielded type.  Inside the insulation is a wire mesh that encases the center insulated wire.  The mesh acts as a barrier to interference.  Mic cables, guitar cords, powered speaker cables, cables for keyboard outputs etc. are all instrument cable types with woven wire surrounding the center wire.
Comment: Speaker cables do not have the mesh shielding.  They are made up of two similar wires and should only be used for connecting an amp head to a speaker.  Both have tip ring plugs.


Switch-Pitcher versus Switch-Batter

Question: A Switch-Pitcher is pitching (Can pitch with the left or right arm).
A Switch-Batter is at the plate (Can bat from the left or right side).
In the MLB, who is forced to choose what side they are going to play from first (giving the other guy the advantage)?  And are they stuck on that side for the entire at-bat?
Example Scenario
Answer: The pitcher must choose first, then the batter.  They are each allowed one change per plate appearance.
See this wikipedia link for some background.

Switch-Pitcher versus Switch-Batter


Adjust the p-values or not?

Question: This started as a simple discussion where everyone thought they new the answer, and ended up with arguments and dozens of paper quotations. Thoughts appreciated.
We have 10 samples: Control, A, B, C, ..., I, with good enough sample size, and the groups have similar variances.
The following comparisons were made using unpaired two-sided t-tests:
A - Control
B - Control
C - Control
...
I - Control
We obtained 9 p-values. Do we have to adjust these p-values to account for family-wise issues ?
Thanks!
Comment: Have you noticed that all nine comparisons are *correlated*?  (This is because they all use the same control.)
Answer: Yes, it is necessary to adjust for repeated testing to control for increasing probability of false positives. In terms of reporting, I think it is best to report both raw and adjusted p-values, specifying which correction was used (eg Bonferroni). But why did you do a series of t-tests instead of eg ANOVA with post-hoc comparisons?
Comment: In the same fashion, why not just code the samples as a categorical variable, and run a regression on it, which would yield straightforward p-values per parameter? You compare them to the same reference category anyway.
Answer: You have multiple treatment groups that are each compared to the control group, but not compared to each other. There's a method called the Dunnett procedure designed specifically for controlling the familywise error rate in this situation.

Adjust the p-values or not?


Is it problematic if one predictor in a set accounts for almost all the prediction?

Question: I am running a logistic regression with customer event data with multiple predictors.
However, one variable is extremely important, alone predicting 60% of the customers for the event. When this main predictor is included in the model, other predictors add very little to prediction over and above this main predictor.
This main predictor is not a post event variable. The variable has full business support to be in the model.

Given this, is it still okay to retain this main predictor variable in the model?
Does this suggest that there is anything wrong with the model?
Comment: @ayush Could you edit your question clarifying what you mean by "certain values" and "event rate"? Could you explain what is making the situation "not very comfortable"?
Comment: The values are the value that categorical variable is taking..Lets say when it takes value C most, 60% of the times, the event happened(in historical data)and when it took value A 50% of time event didnt happen. I am saying its not very comfortable situation to be in because generally a model is termed bad when only 1 variable is making it predict good %age of events. Any addition to this variable is improving the prediction power by decimal values. Hope that makes the question more clear
Comment: @ayush Thanks. That does clarify things. I'll update your question to make this clear.
Answer: I understand your gut feeling. But depending on the type of response and predictor, this has not to be unsual (example: response = "weight", predictors "height" and others with presumably less meaning like "state", "favorite movie" etc.).
However, you should check that for the creation of the predictor only information has been used which was available at that time.
Here is an example:
Suppose you want to predict an event of the next day. You have raw data from day 1 to 10. Now you create one predictor by calculating a statistic over all 10 days and other predictors using only "local" information (i.e. directly extracted from a single event on a single day, i.e. "event start time"). Now you build a model from day 1 to 5 using this predictors to predict the events on day 6. The model is flawed because it contains information from day 6-10, information which is never available when building the model for real (i.e. not simulation) usage.
If this check has been succesful (I guess you mean that with "not a post-event variable"), then it shouldn't be a problem. In one of my projects, something similar occurred. Checking on the meaning of the variables indeed revealed, that the detected relationship (i.e. variable importance) was trivial, but true ;).
Comment: @stefen -- thanks..Yes, I have done this check. This information is absolutely available in my model. So that gives me my answer. But there is something more which I wanted people to ponder upon..Removing this variable and keeping just others giving me a miserable prediction is indeed an indicator that when I dont keep this variable, all others fail in the combined way to give me anything fruitful..Going into detail..this itself means to business that if you want to recognize event guys just look for this indicator and you have got most of 'em. what say ??
Comment: @ayush Yes, as far as I see from here (if the predictor/predictor information is always available). Does the meaning of the predictor does not indicate this ? 1. As I said, I recommend to talk to someone with domain language, if it is not instantly clear. 2. Although you hit 60%, you still miss 40%. So your precision is solid, but not excellent. Depends if this is enough for your business.
Comment: @stefen..Thanks..Yes, I understand your point. Yes,I am hitting 60% with this and some more variables..As it seems right now, I would not be able to take it to more than 65 %.


Portando código Java para C++ ou Python

Question: Estou trabalhando em um projeto que foi originalmente escrito em Java.
Quero aprender mais sobre a matemática e a lógica por trás do código, e tive a ideia de portar o código pra outra linguagem.
Pensei em C++ e Python.
Qual delas possui mais similaridades e levaria menos tempo e esforço pra traduzir?
Comment: Sua pergunta é opinativa, porque vai da experiência e opinião pessoal de cada um. Uns falarão que C++ será melhor e outros dirão que é Python. Não há resposta clara porque isso depende de gosto e preferência pessoal. Além disso o tempo e o esforço dependem muito do tipo de aplicação de que se trata, da forma como está organizada, e também do seu conhecimento em C++ e em Python.
Comment: A resposta resolveu o seu problema? Acha que pode aceitá-la? Se não souber como faz, veja o [tour]. Isso ajudaria muito indicar que a solução foi útil para você e dar uma indicação que houve uma solução satisfatória. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver 15 pontos).
Answer: Não acho que seja um bom caminho para o que quer. Matemática e lógica se aprendem fora das linguagens de programação.
Java é considerada, bem grosso modo, uma evolução do C++ (posso te garantir que nenhum programador experiente de C++ acha isso), então em tese seria mais fácil traduzir para C++ do que Python, que não tem nenhuma semelhança com Java, a não ser pela semântica do if (nem a sintaxe) e mais alguma coisinha. Python tem uma filosofia absurdamente distante de Java.
Mas se quer algo semelhante ao Java deveria optar pelo C#. Essa sim é uma linguagem bem parecida e mais fácil. C++ é difícil para um iniciante que ainda está com dificuldade para entender a diferença básica entre linguagens.
Se não sabe nenhuma será difícil em qualquer uma. Aí a dificuldade é aprender a linguagem. Se tentar aprender durante a tradução, não conseguira nem uma coisa nem outra.
Qualquer pessoa dirá que Python é mais fácil de aprender que C++, mas isso quer dizer nada.
De qualquer forma precisa decidir se quer aprender algo ou se quer economizar tempo, essas coisas são incompatíveis (pelo menos no curto prazo, como descrito).
Qual você deve optar, eu não responderei, mas ressalto o caminho errado.

Portando código Java para C++ ou Python


Many, seemingly arbitrary time signature changes

Question: So, I'm an intuitive composer. I start noting the music down as it comes to my mind. I'm very, very exact in this, it has to be exactly as in my head. So I just have a score in 4/4 and set a tempo and start noting the notes, but I don't look at the bars, at all.
Now I'm in the process of nailing down the time signature and in the past it always came down to pretty standard stuff e.g. 6/4, with some minor adjustments here and there. But this time, I'm realising that it's - errr... - quite jumpy to say the least.
So, it looks like this (I left out the notes, but I think you catch the drift):

Now, to be clear: the music is "correct". I mean: it all fits together harmonically and rhythmically and sounds great. But I'm really wondering if this is something I can get away with. I could definitely merge some of them to 6/4 for instance, but when I put on the synced metronome this just sounds right.
I've tried shoehorning everything into less time signature changes, but it just doesn't look right and the adjustments I need to make don't sound right either.
Anyway, my question is two-fold:

is this even playable by a string quartet without a conductor?
will I get shot? No, should I try to "fix" this, otherwise the musicians will declare me crazy?
Comment: Well, since you've only written rests so far, I think it's playable by anyone.
Comment: It's impossible to comment on whether your notation makes sense with the music you've written without an example of that music: Could you provide either a short recording, or some more detail on the written score (other than the time signatures).  Thanks
Comment: According to Wikipedia, the term is [mixed meters](https://en.wikipedia.org/wiki/Time_signature#Mixed_meters).
Comment: This is fine, if you're sure. But just looking at this excerpt, it could also be, 6/4, 5/4, 6/4, 2/4, 5/4. But, I doubt you would be shot. Take a look at "Sevens", by Samuel Hazo.
Comment: What I do is write the piece without time signatures at first, then add them later so that it's easier to play (I think this is what most people do?)
Comment: *Well, since you've only written rests so far, I think it's playable by anyone.* Seems tough to me. I'm imagining trying to count all the measures, getting lost, and finally deciding just to fake it by looking around and acting like I'm done when the other musicians look like they're done.
Comment: @BenCrowell Not tough in the slightest; this is what we (I) do for a living, so we're (I am) used to looking at this stuff. Unless the tempo was quite fast and you were sight-reading, counting through these meter changes is pretty straightforward. If you really did have all these (and more) rests, a diligent composer would give you lots of cues in your part to help orientate you. I know my pronouns and tenses were all over the place there, but hopefully you get my point.
Answer: The most important element is the sound. The score should be the most organized and straightforward way of producing that sound. You can re-bar / notate the exact same music any number of ways, but if it doesn't sound right, then it's not.
The reason for my preamble here is that your time signatures should complement the music – either through pacing or phrasing. There is significant historical precedent for your question: Stravinsky's Rite of Spring, Feldman's Crippled Symmetry, Bands like Tool, Between the Buried and Me, Snarky Puppy, King Crimson, Frank Zappa; long gone are days when you establish a single metrical idea and maintain it throughout a composition (unless that's what the piece needs!).
In my own music, I freely move between time signatures like 2/4+3/16, 7/8, 5/16, 5/4+3/8, 4/6*, 7/10*, etc if that's what the piece needs.
As an exercise for the future, you could try a couple things:
1.) Write your ideas on blank staff paper with no pre-determined bar lines (if they're written down, then you'll think that way!). Then go back after and put barlines down where it makes sense. After all, their purpose is to organize the music; you don't organize your music to fit the barlines.
2.) As others have suggested, if you find you have a lot of meter changes (especially if you're writing for large ensemble,) see if you can put it into a single, larger, repeating meter with accents in appropriate places, or even just specifying the metric subdivision (saying: 3+2+3+4+2 above the staff for 14/8 and beaming it that way, for example) really helps – in both large ensemble and chamber music. With chamber music, you can get away with more meter changes, so a small addendum to my earlier point in that you also need to consider ensemble / rehearsal logistics (as any prudent composer should).
Hope this helps.
*No, I'm not being cheeky, these are real, correct meters.
Comment: What constitutes 4/6 and 7/10, please?
Comment: @Tim - great question. You can divide a whole note by any number, not just 2, 4, 8, or 16. If I want to keep my current tempo but use durations equal to quarter-note triplets ("sixth notes") I run into problems if, let's say I only want 4-5 of them. Even the name "quarter note triplet" is clunky. Same is true if I only want 6-7 "quintuplet" notes in a measure, I can divide a whole note by 10 and put 7 of those beats in a measure; it's not different; just unfamiliar.
Comment: Glad to see a band like BTBAM brought up in a discussion like this. Modern progressive metal music does all kinds of things with meter. One of my first encounters with this was a 27/16 measure in "Bone Marrow" by Protest the Hero, but the true champions of this are Meshuggah. [This academic analysis](https://doi.org/10.1525/mts.2007.29.2.219) of their rhythms is certainly of interest.
Comment: @Tim It's not absolutely clear what they mean without more context (including the actual notes!) but the general idea is that 7/10 is 7 out of the 10 notes in a "10 over something" tuplet. Sure, you *could* write that bar as say 7/4 or 7/8 with a MM mark change, but for people who can count complicated tuplets (which are common enough in contemporary art music) that would be harder to read without using a pocket calculator, not easier!  For example Boulez used time signatures like 5/3 - i.e. each bar is a quarter note (usually subdivided into shorter notes of course) plus 2/3 of a triplet.
Answer: It should be playable by anyone who can count. At least it's all counting with the same crotchet beat in time, only the number in each bar changes.
There could be another way of looking at how it's written - keep it all in the same, say 3/4 or 4/4, but accent the appropriate beats. So, in the beginning, the emphasis is on 1st beat, 1st bar. Second bar (4/4) accent 1st and 3rd beats, next bar, accent 4th beat. Probably easier to see written out side by side!
Are you certain that the original has to have the accents where they are to make time sigs change? Would there be a case for something like a regular 13/4, if a pattern follows?
Comment: Well, that's how I came to this... I started knocking the accents. Also, it is much more legible now. But I'll definitely try a 13/4 for instance. Thanks for the answer!
Comment: @Creynders hey. Can you post the version with the accents that improve legibility? I don't really understand what you mean. Also I personally would like to actually see the solution to improve my understanding.
Answer: When I saw these bars, I initially thought it was a transcription of the song Mother by Pink Floyd.
That's a song that consists of 5/4, 4/4 and 3/4, with constant changes. Especially 5/4 is never used more than a single bar at a time.
The result is (subjectively of course) an amazing song, and many Pink Floyd fans cite this as one of their top favorite songs. It sure isn't easy to play, but it is easy to listen to and it all fits together well.
The reason why I'm saying is: Mother is an example of how this is perfectly acceptable and can work very well. It's not easy to pull off, and I'm pretty sure many musicians won't be particularly happy to play this, but it can definitely work.
Answer: I'd just add that if there are changes of time signature in every bar, you may just consider leaving it out altogether, writing just barlines. I'm not sure how common that would be, but I definitely met it quite a lot in religious music. An example would be this piece from Rachmaninov's Vespers.
Answer: Constantly changing time signatures are fine, and are quite common in today's music.
Just check that the crotchet beat IS constant.   And that you aren't notating something simple in an unnecessarily complicated way.  It happens!   Want to show us the piece?


Proof of 3.461.5 of Gradshteyn Book needed

Question: The 3.461.5 Equation of Gradshteyn and Ryzhik book is as given below $$\int_u^{\infty}e^{-\mu x^2}x^{-2}\, dx=\frac{1}{u}e^{-\mu u^2}-\sqrt{\mu \pi}\left[1-\Phi(\sqrt{\mu u})\right]$$ where $\Phi(x)$ is defined as $$\Phi(x)=\frac{2}{\sqrt{\pi}}\int_0^xe^{-t^2}dt$$ I want to know how to proof this equation? Any hint or reference for this will be very helpful. I will be very thankful to you for your help. Thanks in advance.
Comment: Looks awfully similar to a Integration By Parts. That  $\Phi(x)$ is actually known as the Error function, $erf(x)$.
Comment: Are you sure it's not $u$ in the denominator of the first term?
Comment: The current (8th) edition of G&S (edited by Daniel Zwilinger) has a note ${}^{11}$ on this formula, which means it was corrected for the 7th edition.  Perhaps that was when they moved the $u$ outside the radical.
Comment: Hint differentiate both sides w.r.t to $\mu$
Comment: @MichaelSeifert yes its $u$
Answer: Let $v = e^{-\mu x^2}$ and $dw = dx/x^2$.  Then integrating by parts we have
\begin{align}
\int_u^\infty e^{-\mu x^2} \frac{dx}{x^2} &= \left[ e^{-\mu x^2} \left( - \frac{1}{x} \right) \right]_u^\infty - \int_u^\infty \left( - \frac{1}{x} \right) \left( - 2 \mu x e^{-\mu x^2} dx \right) \\
&= \left[ 0 - \left( -\frac{1}{u} e^{-\mu u^2} \right) \right] - 2 \mu \int_u^\infty e^{-\mu x^2} dx \\
&= \frac{1}{u} e^{-\mu u^2} - 2 \mu \int_{\sqrt{\mu} u}^\infty e^{-t^2} \left( \frac{dt}{\sqrt{\mu}} \right) & (t \equiv \sqrt{\mu} x) \\
&= \frac{1}{u} e^{-\mu u^2} - 2 \sqrt{\mu} \left[ \int_0^\infty e^{-t^2} dt - \int_0^{\sqrt{\mu} u} e^{-t^2} dt \right]
\end{align}
The first integral that remains is well-known to be equal to $\sqrt{\pi}/2$, and the second one is equal to $\frac{1}{2}\sqrt{\pi} \Phi(\sqrt{\mu} u)$.  Plugging these in, we achieve the desired result.
(Note that the argument of $\Phi$ in the integral should be $\sqrt{\mu} u$, rather than $\sqrt{\mu u}$.  I assume this was a typo you made in entering the equation—it's also one I made a few times while typing this up.)
Comment: Many thanks for your help. I do not know I just wrote it as its written on that book therefore I am not sure if there is typo in that book also. Nevertheless I got the idea how to get there
Comment: @FrankMoses Why not order $\sqrt\mu u$ as $u\sqrt\mu$?
Comment: @ParclyTaxel I think this will not make any difference in the answer
Comment: @FrankMoses I know, right? But it is clearer.
Comment: @ParclyTaxel Agreed completely.
Answer: \begin{align}
I(\mu) &= \int\limits_{u}^{\infty} \mathrm{e}^{-\mu x^{2}} \mathrm{d}x \\
&= \frac{1}{\sqrt{\mu}} \int\limits_{u\sqrt{\mu}}^{\infty} \mathrm{e}^{-y^{2}} \mathrm{d}y \\
&= \frac{1}{2}\sqrt{\frac{\pi}{\mu}} \mathrm{erfc}(u\sqrt{\mu}) \\
&= \frac{1}{2}\sqrt{\frac{\pi}{\mu}} - \frac{1}{2}\sqrt{\frac{\pi}{\mu}}\mathrm{erf}(u\sqrt{\mu})
\end{align}
We let $y^{2} = \mu x^{2}$.
Integrating with respect to $\mu$ we have
\begin{equation}
\int\limits_{u}^{\infty} \int \mathrm{e}^{-\mu x^{2}} \mathrm{d}\mu \mathrm{d}x
= -\int\limits_{u}^{\infty} x^{-2} \mathrm{e}^{-\mu x^{2}} \mathrm{d}x
\tag{1}
\label{eq:1}
\end{equation}
and
\begin{equation}
\frac{\sqrt{\pi}}{2}\int\frac{1}{\sqrt{\mu}} \mathrm{d}\mu - \frac{\sqrt{\pi}}{2} \int\frac{1}{\sqrt{\mu}}\mathrm{erf}(u\sqrt{\mu}) \mathrm{d}\mu
= \frac{\sqrt{\pi}}{2} I_{1} - \frac{\sqrt{\pi}}{2} I_{2}
\tag{2}
\label{eq:2}
\end{equation}
\begin{equation}
I_{1} = \int \frac{1}{\sqrt{\mu}} \mathrm{d}\mu = 2\sqrt{\mu}
\end{equation}
\begin{align}
I_{2} &= \int \frac{1}{\sqrt{\mu}} \mathrm{erf}(u\sqrt{\mu}) \mathrm{d}\mu \\
&= \frac{2}{u} \int \mathrm{erf}(x) \mathrm{d}x \\
&= \frac{2}{u} x\, \mathrm{erf}(x) + \frac{2}{u} \frac{1}{\sqrt{\pi}} \mathrm{e}^{-x^{2}} \\
&= 2\sqrt{\mu} \mathrm{erf}(u\sqrt{\mu}) + \frac{2}{u} \frac{1}{\sqrt{\pi}} \mathrm{e}^{-\mu u^{2}}
\end{align}
We let $x=u\sqrt{\mu}$.
Inserting $I_{1}$ and $I_{2}$ into equation \eqref{eq:2}, equating the result with equation \eqref{eq:1}, and simplifying, we have
\begin{align}
\int\limits_{u}^{\infty} x^{-2} \mathrm{e}^{-\mu x^{2}} \mathrm{d}x &=
\frac{1}{u} \mathrm{e}^{-\mu u^{2}} - \sqrt{\pi \mu} [1 - \mathrm{erf}(u\sqrt{\mu})] \\
&= \frac{1}{u} \mathrm{e}^{-\mu u^{2}} - \sqrt{\pi \mu} \mathrm{erfc}(u\sqrt{\mu})
\end{align}


Would like to create a POST method for my Django API

Question: I would like to create a POST method for my Django project while setting up the API. I have tried creating an override method for create but it gives me an integrityconstrain. I would like to make a post that stored all the field in a tidy JSON. I'm not sure if it's because of manytomanyfield that is causing the problems. Thank you in advances.
Models.py
class Results(models.Model):
    type = models.CharField(max_length=200, blank=True)
    question = models.CharField(max_length=200, blank=True)
    title = models.CharField(max_length=200, blank=True)
    ytid = models.CharField(max_length=200, blank=True)
    correct_answer = models.CharField(max_length=200, blank=True)
    incorrect_answers = ArrayField(models.CharField(max_length=200),
    blank=True)

    def __str__(self):
        return '{}, {}, {}, {}, {}, {}'.format(self.type, self.question,
self.title, self.ytid, self.correct_answer, self.incorrect_answers)

class Simulation(models.Model):
    sequence = models.PositiveIntegerField(unique=False)
    method = models.CharField(max_length=200)
    results = models.ForeignKey(Results, on_delete=models.CASCADE)

    class Meta:
        ordering = ['sequence']

    def __str__(self):
        return '{}'.format(self.sequence)

class respond_code(models.Model):
    respond_code = models.PositiveIntegerField(primary_key=True)
    simulation = models.ManyToManyField(Simulation)

    class Meta:
        ordering = ['respond_code']

    def __str__(self):
        return '{}'.format(self.respond_code)

Serializers.py
class ResultsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Results
        fields =
('type','question','title','ytid','correct_answer','incorrect_answers')

class SimulationSerializer(serializers.ModelSerializer):
    results = ResultsSerializer(many=False)
    class Meta:
        model = Simulation
        fields = ('sequence','method','results')

class respond_codeSerializer(serializers.ModelSerializer):
    simulation = SimulationSerializer(many=True)
    class Meta:
        model = respond_code
        fields = ('respond_code', 'simulation')

    def create(self, validated_data):
        simulations_data = validated_data.pop('simulation')
        simulation = Simulation.objects.create(**validated_data)
        for i in simulations_data:
            Simulation.objects.create(simulation=simulation, **i)
            for data in simulations_data:
                Simulation.sequence.add(simulation,**data)
                Simulation.method.add(simulation,**data)
                simulation.save()

        #return Simulation.objects.create(simulation=simulation, **i)
        return simulation

I have made an amendment to the serializer.py to this
class respond_codeSerializer(serializers.ModelSerializer):
    simulation = SimulationSerializer(many=True)
    class Meta:
        model = respond_code
        fields = ('respond_code', 'simulation')

    def create(self, validated_data):
        simulations_data = validated_data.pop('simulation')
        simulation = respond_code.objects.create(**validated_data)
        simulation.save()
        for Simulation in simulations_data:
            #d = dict(i)
            b =
Simulation.objects.get_or_create(sequence=Simulation['sequence'])
            Simulation.add(b)
            #respond_code.save()
        return simulation

Comment: IntegrityError at /api/simulation/
null value in column "sequence" violates not-null constraint
DETAIL:  Failing row contains (34, null, , null).
Answer: Try something like this,
class respond_codeSerializer(serializers.ModelSerializer):

    simulation = SimulationSerializer(many=True)

    class Meta:
        model = respond_code
        fields = ('respond_code', 'simulation')

    def create(self, validated_data):
        simulations_data = validated_data.pop('simulation')
        instance = super(respons_codeSerializer, self).create(validated_data)
        for simulation in simulations_data:
            result_data = simulation.pop('results')
            result, c = Results.objects.get_or_create(**result_data)
            sim, c = Simulation.objects.get_or_create(results=result, **simulation)
            instance.simulation.add(sim)
        instance.save()
        return instance

Comment: Thankyou so much for the help, I received this error: int() argument must be a string, a bytes-like object or a number, not 'collections.OrderedDict'                By the way what is with the 'c'
Comment: `get_or_create()` method returns a tuple of object and a boolean indicates whether it is created or not. That's what's c.
Comment: TypeError at /api/simulation/
int() argument must be a string, a bytes-like object or a number, not 'collections.OrderedDict'     (this is the error I received)
Comment: I meant entire traceback... just post it in the comments.
Comment: Actually, don't bother. I have edited my answer. Try it again.


Find common ratio with two terms

Question: I am trying to find common ratio but ...
If $b_1 = -2$ and $b_8 = -384$, how can I find common ratio (q)?
Comment: **Hint:** $\frac {b_8}{b_1} = q^7$. Also, please try defining $b_n$ in advance. I assume it means term number.
Answer: The fact that you're asking for a common ratio probably means that the sequence with terms $b_n$ form a geometric sequence but that's something you should mention. It also helps to show your own effort, ideas or relevant formulas you have seen.
You probably know that $b_n = q \cdot b_{n-1}$ and from this also $b_n = q^{n-1}\cdot b_1$. You know $b_1$ and $b_8$ so use this formula with $n=8$ to get an equation for $q$.
Comment: And if I know that b2 = 7 and b5 = 56
Comment: Does this formula help me? I think no. Am I wrong?
Comment: Then you either work your way backwards and go via $b_1$ (formula above), or you could think a bit longer/harder and come up with a direct relation between $b_2$ and $b_5$. It's not that hard: $b_3=q\cdot b_2$ so $b_4 = \ldots$.
Answer: Hint:
For a geometric progression with first term $a$ and common ratio $r$, the $n^{\text{th}} $ term is given by: $$b_n = ar^{n-1}$$
Here, $b_1 =a=-2$ and $b_8 = - 384$.
Can you take it from here?
Comment: I think the OP would prefer $b_n$ to $T_n$.
Answer: Hint: $b_n = b_0 q^{n}$. Compute $b_8 / b_1$.

Find common ratio with two terms


React component's defaultValue does not work

Question: I'm trying to use a fetched value from DB as a default value (shown until the component is clicked) of an input field.
However, using "defaultValue" attribute, the fetched value it is not displayed.
App.tsx file (value is fetched successfully):
  const [Income, setIncome] = useState<string>('0');

    useEffect(() => {

    const incomeResp = async () => {
      await axios.get('http://localhost:4000/app/income')
      .then(
        result => setIncome(result.data && result.data.length > 0 ? result.data[0].income : 0))
    }
    incomeResp();
  }, []);

  return (

          <IncomeExpensesContainer
            income={Income}
            setIncome={setIncome}
            totalExpenses={TotalExpensesAmount}
            currencySymbol={Currency}
          />

Component's file:
interface Props {
    income: string;
    setIncome: (value: string) => void;
    totalExpenses: number;
    currencySymbol: string;
}

const IncomeExpensesContainer: React.FC<Props> = ({
        income,
        setIncome,
        totalExpenses,
        currencySymbol,
    }: Props) => {

   const [insertedValue, setInsertedValue] = useState<string>(income);

return (
    <Grid container spacing={1} className="income-expenses-container">
        <InputItem
            onChange={setInsertedValue}
            onBlur={setIncome}
            title="Income"
            type="number"
            placeholder="Your income"
            defaultValue={income}
        />
    </Grid>
);

What am I missing here?
Comment: What is ur return statement in App? How do u pass the data to the components file? So many missing informations.
Comment: @Delice I've added return statement of the in App.tsx. What additional information is needed?
Answer: Edited after additional information provied
Use the passed prop in your component:
const Component = (props) => {
       return (
            <InputItem
              onChange={setInsertedValue}
              onBlur={setIncome}
              title="Income"
              type="number"
              placeholder="Your income"
              defaultValue={props.income}
        />
}

Comment: Yes, this is what I'm doing (I've just updated the code in order to show that)
Comment: I think the problem is that defaultValue is initialized on first render on component. The first time you render the component - your state is probably empty. Can you try render your input component only if your state has value? E.g. `{income && ` and see what happens?
Comment: I've replaced `defaultValue` by  `value` and it didn't help.
Comment: I've also added conditional rendering to this component { && } and it works as expected - is rendered once the state changes, however, it's initial value = 0, so, the issue is not solved
Comment: I've finally figured out the solution: 1) created const [insertedValue, setInsertedValue] = useState(income); and assigned value={insertedValue} 2) used useEffect(() => { setInsertedValue(income) }, [income]);
Answer: To anyone who encounters this problem in the future, the solution that worked for me was to use the in-built type casting methods of javascript when passing number type values.
This for example
const Component = (props) => {
       return (
            <InputItem
              onChange={setInsertedValue}
              onBlur={setIncome}
              title="Income"
              type="number"
              placeholder="Your income"
              defaultValue={props.income}
        />
}

when called should receive the defaultValue as
<InputItem
        onChange={setInsertedValue}
        onBlur={setIncome}
        title="Income"
        type="number"
        placeholder="Your income"
        defaultValue={income.toFixed(0)} // toString and toPrecision work as well
    />

I think it is something taking place under the hood of the React Native TextInput component, though I don't have any resource justifying this.
Hope it helps.


How to set up notifications about server overload?

Question:
Possible Duplicate:
What tool do you use to monitor your servers?

How to get notified (preferably by email) when my webserver reaches certain amount of incoming requests? This way I'll be able to quickly react ddos, bruteforce etc.
I'm using apache through nginx proxy, so I'm able to monitor either of them (preferably nginx)
Answer: If you have Munin, you can use it to send notifications. First, install a plugin to monitor request rate in Nginx (like this one). Then follow the instructions in Munin documentation: Sending Alerts from Munin. An even shorter introduction may be found here: Email Notifications from Munin
Comment: I did exactly like this. Works perfectly!
Answer: You can use monitoring software like nagios to setup notifications (by email/SMS etc). You can define your own notification commands. Also, you can define your check commands and the warning/critial threshold of each command.
Answer: For some basic monitoring:
Grab the Nagios check_nginx.sh script: http://exchange.nagios.org/directory/Plugins/Web-Servers/nginx/check_nginx-2Esh/details
(Nagios checks are generally scripts that will return specified exit codes for events -- 0 for OK, 1 for WARN, 2 for CRIT; you can use them outside of Nagios.)
Turn on the stub stats module in nginx and have it on http://localhost/stats or something like that: http://wiki.nginx.org/NginxHttpStubStatusModule#Directives
Point the check script at the stats URL: you'll see connections per second.  Set a threshold for it with the -w or -c option.  Wrap that in a shell script that will send you email if the script returns a non-zero exit code.  Put the script into cron.
The page about the Nginx module has some links on the bottom about other monitoring options.
Other option:
You can install Monit (there's a free, self-supported package for most Linux distros).  There's apparently some stuff on Apache monitoring here:
http://mmonit.com/wiki/Monit/MonitorApacheStatus
Answer: With monitoring software. In the upper right corner there is a search field you can use to find one.
Comment: @Poma This was a very vague question without doing any initial research.
Comment: That was very helpful answer
Comment: I'm already using monitoring software like munin. Nagios is way too complicated for my simple single server. I asked about notifications and what approach should I use (shell script + cron, standalone app, apache module etc.)
Comment: "Nagios is way too complicated"?   What? Nagios is relatively easy to get working. It is rather light weight and can do exactly what you want. If you already know better yourself, why ask us? :)


Forward single SSH key to given host

Question: How do I forward a single arbitrary SSH key to a given host?
Forwarding keys is a security tradeoff, so when you do it, it's ideal to send only what you need.
Answer: Start up a ssh-agent just for this connection, add the desired key, then SSH in the subshell.
<code>ssh-agent bash -c 'ssh-add /home/username/.ssh/some_key_id_rsa; ssh -A some_host'
</code>

Forward single SSH key to given host


Different Piano Octaves

Question: What comes after 8va and 15ma in Piano music?  I have tried searching, but nothing helpful comes up.
Answer: Well, purely theoretically, a three-octave transposition would be 22ma.  A four-octave transposition would be 29ma.  You just keep adding 7 to each previous number.
However, don't use these.  No one except true music nerds will be able to puzzle out what you mean.  It's not standard music notation.  I've never seen an example of this, and even 15ma is exceptionally rare, to the point that many musicians wouldn't know what it means.  (However, an internet search tells me, weirdly, that some music fonts include glyphs for 22ma or even 22mb!)
For piano, either use ledger lines or change clef instead.
The only utility I can think of potentially for these symbols might be in inserting cue notes for an instrument in a wildly different range and refusing to change clef.  (But cue notes frequently don't notate correct octave anyway, so this sort of thing simply isn't necessary.)
Comment: Musescore has 22ma lines in the same section as 15ma lines (if you care to use them).
Answer: There's nothing after 15ma. You'll just have to bite the bullet and draw a ledger line or two. A note on the second ledger line, marked 15ma, is the top C on a grand piano so you shouldn't need to write notes higher than that unless you're transcribing bats.
Comment: maybe the OP is in possession of a Imperial Bösendorfer
Answer: Nothing.   Look at my piano (it's a slightly short one, the full 88 notes would reach C).
And look at the notation.  Section A doesn't require an 8va line.  B and C are 8va and 15ma.   There is no section D. None is needed,  There's no more piano :-)
Comment: Unless you are fortunate enough to have one of those Bosendorfers, with the 'hidden' extra low octave...
Comment: @Laurence Payne Nice pic. Yamaha? I envy you that long stand. And the Leroy Anderson! What's in it?
Comment: Bechstein.   Don't envy the long stand, make one like I did!  Simple bit of woodwork.
Comment: Yep, but in these days of digital pianos,  not all that difficult to pitch-shift the whole dang thing a couple octaves :-)
Comment: @Tim: Even if you do have one of those extended pianos, *15ma bassa* is plenty to notate all of the notes in that octave, with just a couple ledger lines.
Comment: @CarlWitthoft - simplicity itself, on some. However, how would one then play something low with l.h. and several octaves higher with r.h. The whole dang thing shifts! And usually it's not needed on 88s; on 61s and 76s there's the problem.
Comment: iDK may come in handy when playing this https://www.youtube.com/watch?v=6ithskt49HA
Comment: @LaurencePayne Bechstein? Lovely. These hands are wholly untutored in woodwork. I'll stick with Sellotape. Literally.
Comment: Lovely, but not THAT lovely.  These were budget Bechsteins  marked in Britain in the first half of the 20th century.  Not overstrung and a rather noisy action.   A nice house piano though.
Answer: I found this use of 29ma in this Keyboard book from the musical Spamalot. When playing multiple MIDI instruments, it's sometimes necessary to pre-program octaves when you simply don't have enough hands! Thought it would be interesting anyway.
Comment: That's a really good find!

Different Piano Octaves


How to build separate classifiers for each label in the dataset?

Question: I have a list of columns and each column is to be labelled by a label from another list of labels.
Eg: Two columns namely, ALT_ID and MTRC_NM are matched with labels Alternate ID and Metric Name respectively.
This fuzzy string matching has been taken care of. Problem is, I want to incorporate a learning model in this.
Essentially, after the matched results are displayed, the user curates the matches as CORRECT or INCORRECT. Based on this feedback and other features of the column (like minimum value, maximum value), I want to train a classifier such that the learning model will eventually stop making the incorrect matches in the future.
Note: In the first run, only the name of the column is used to produce the first set of results. After this, I want to use other features(like minimum value) to train the model.
Problem is, there can be 10,000 terms (or labels), maybe even more and the user just marks these as CORRECT or INCORRECT. For incorrect classifications, the user does not tell us what the correct classification should be.
I believe one solution could be to make separate classifiers for each label and based on the Correct/Incorrect feedback for a particular classification, we can use these feature vectors to train a classifier for this classification. So in the future, if the fuzzy string matching nominates Metric Name as the classification for some column, we can let the "Metric Name" classifier decide if it is correct or incorrect.
I don't know how to make separate classifiers for each label. I also don't know if this approach is feasible. Any other solution to this problem will also help.
Answer: You do not want to create separate models for each label as training more than 10 000 models isn't really feasible. Two possible things that come to my mind are:

Create a supervised learning model with one label as input and probability of each of 10 000 labels as output which only uses correct examples for predictions.
Create a reinforcement learning model with the same input but with output which maximises reward function defined as +1 for each positive prediction and -1 for each negative prediction. This model will also try to maximise the number of correct predictions but will be able to learn from incorrect predictions at the same time i.e. predict -1 score for an incorrect pair (x,y).


Do browsers support HTML row selection

Question: I have defined the following table:

                        Date
                        Duty

                        {{getDisplayDate(s.date)}}

                        {{s.userFunction}}

                            <button type="button" (click)="onDeleteSchedule(s.id)"
                                class="btn btn-sm btn-danger btn-delete-account">
                                 Delete
                            </button>

I am wandering if there is native support in todays browsers for the row selection (e.g. ctrl-click - select and second ctrl-click unselects).
Any help appreciated.
Comment: HTML tables only define a tables layout, you can add whatever you like with JS, but the built in tables are static, non-interactive elements.
Comment: If it's a regular table. Firefox has the option to mark table cells with CTRL+click on individual `td` elements. Browsers like Chrome and Edge don't have this functionality. Unsure about Safari.
Comment: Does angular have any library to support something like that?
Comment: There is no native support for that (yet?), what you may be having to look for is a library that handles multi select on table rows or write your own module for it.
Comment: There might be such a library, but asking for recommendations here is off-topic, see the [help/on-topic]
Comment: _"Firefox has the option to mark table cells with CTRL+click on individual td elements."_ - I see a light-blue border/outline appearing - but I can't tell what actual _functionality_ this is supposed to provide. What exactly do _you_ mean, when you say "mark"? Or "select"? Mark/select for what _purpose_?
Comment: @Cbroe I use that functionality to copy table content to clipboard. If you hold down CTRL key and you  click with the mouse any cell it selects it and if you drag the selection it takes the whole range. But yet it's just for copying table content. There are extensions both for firefox and chrome that extend that behaviour
Answer: By default, HTML tables are static and do not have any built-in interactivity. They are simply used to display tabular data in a structured way.
However, it is possible to make HTML tables interactive by adding interactivity using JavaScript and CSS.
Using JS, it can be done by adding event listeners and implementing functions to handle user interactions, such as clicking on a table row or cell.
Or can done by adding tabindex attribute to each tr element in the table, and use CSS to visually indicate when they are selected or hovered over.

Examples for both JS and CSS approach can be found in this snippet:

function addRowHandlers() {
    var table = document.getElementById("tableId");
    var rows = table.getElementsByTagName("tr");
    for (i = 0; i < rows.length; i++) {
        var currentRow = table.rows[i];
        var createClickHandler =
            function(row)
            {
                return function() {
                                        var cell = row.getElementsByTagName("td")[0];
                                        var id = cell.innerHTML;
                                        alert("clicked on:" + id);
                                 };
            };

        currentRow.onclick = createClickHandler(currentRow);
    }
}
window.onload = addRowHandlers();
table tr:focus{ outline: red solid 2px}

Table row 1

Table row 2

Table row 3

Comment: An example snippet would be helpful :-)
Comment: Sure! have updated the answer with examples @node_modules
Comment: "However, it is possible to make HTML tables interactive by adding interactivity using JavaScript and CSS." — That is already noted in the question. It even has an example: ``
Comment: I think I'd rather go for third party library. Thanks everybody for help.

Do browsers support HTML row selection


Melhorias em conteúdo dinâmico

Question: Boa tarde, tenho uma função em jquery que venho melhorando desde que a descobri em fóruns, ela serve para criar elementos dinamicamente utilizando jquery
/* função que insere e remove cadeia de inputs */
    var inputnew = 0;
    function new_input() {
        inputnew++;
        $('
'
        + '<input placeholder="Modalidade" onkeyup="this.value=capitalize(this.value);" />'
        + '<input type="number" placeholder="Data" />'
        + '<input placeholder="Instituição" onkeyup="this.value=capitalize(this.value);" />'
            + 'x'
        + '
').prependTo($('section.duo div.academic_formation div.formations')); }

    $('span.remove').live('click', function() {
        if(inputnew > 1) {
            $(this).parents('li').remove();
        inputnew--; } });
    $(document).ready(function() { new_input(); });
/* função que insere e remove cadeia de inputs */

estou enfrentando os seguintes problemas, não sou experiente em jquery então não consegui passar disso, já melhorei bastante a função que achei e estudei mas estou com dois problemas, o principal é, aparentemente a função .live não funciona em jquery mais novo, então sou obrigado a usar o 1.8.3 para esta função dar certo e o segundo problema é que, eu preciso criar dentro da função new_input, todos os inputs e afins e tudo mais que eu desejo que apareça na div listada, ou seja, fica complicado de editar e ou melhorar e também fazer algumas funções funcionarem em conjunto, o problema da versão do jquery se for complicada, nem ligo muito, da para utilizar no 1.8.3 sem problemas, mas o que desejo mesmo é que eu possa escanear a div que tem os elementos que desejo duplicar.
no caso, eu teria

        <input placeholder="Modalidade" onkeyup="this.value=capitalize(this.value);" />
        <input type="number" placeholder="Data" />
        <input placeholder="Instituição" onkeyup="this.value=capitalize(this.value);" />
  +

em html na página, normalmente escrito e então uma função que ao clicar em um ADD por exemplo, clonar este trecho em baixo
Answer: Em relação ao .live() é só mudar para .on() e já podes usar versões mais recentes do jQuery.
Em relação a copiar/criar conteúdo podes usar o .clone() para exatamente copiar o que queres. Existe ainda template em HTML que permite ter HTML na página que não está ativo, serve só para ser copiado.
Um exemplo seria assim:

var inputnew = 0;

function new_input() {
  inputnew++;
  var template = document.getElementById('formations');
  var clone = document.importNode(template.content, true);
  $(clone).prependTo('section.duo div.academic_formation');
}

$(document).on('click', 'span.add', new_input);
$(document).on('click', 'span.remove', function() {
  if (inputnew > 1) {
    $(this).parents('li').remove();
    inputnew--;
  }
});

$(document).ready(new_input);
.cursor_pointer {
  cursor: pointer;
  padding: 5px;
}

<template id="formations">

    <input placeholder="Modalidade" onkeyup="this.value=capitalize(this.value);" />
    <input type="number" placeholder="Data" />
    <input placeholder="Instituição" onkeyup="this.value=capitalize(this.value);" />
    +-

</template>

Comment: @flourigh sim, usa `var clone = document.querySelector('section.duo div.academic_formation div.formations').cloneNode(true);`
Comment: puxa, ficou muito bom, não lembrava do
Comment: achei, tem um inputnew++ a mais ali no seu remover. removi e funcionou
Comment: @flourigh exato, tinha esquecido de tirar. Corrigi agora.
Comment: existe como não utilizar o template? ou seja, pegar direto do

*****

sem utilizar o getelementbyid?
Comment: pow, funciona, da para trocar sim, porém aconteceu algo inesperado, ele duplica, kkkkkkkkkkkkkkkkk, ou seja, ao apertar 1x ele exibe mais 1 = 2 ao apertar outra vez 8 e assim 16, 32, ou seja, acho que complicou, kkkkkk
Comment: @flourigh junta `li.formation` ao seletor: `var clone = document.querySelector('section.duo div.academic_formation div.formations li.formation').cloneNode(true);`
Comment: realmente, funcionou o fator de duplicar mas agora ele clona o que é digitado nos inputs, o de baixo fica com tudo que foi digitado, no caso teria que enviar um "limparinput"? se é que existe
Comment: reparei que desta forma não funciona né var clone_one = document.querySelector('template#formations').cloneNode(true); utilizar o query selector no template
Comment: @flourigh pois, a vantagem do template é teres tudo vazio. Se queres copiar do que já existe tens de limpar :)
Comment: pois é, mas ficou ótimo, só uma observação, queryselector não consegue ler template#formations mesmo?
Comment: @flourigh não, tens de usar `.content`. Mas podes ter HTML normal mas com `display: none;` no CSS... há muitas alternativas.
Comment: agradeço camarada, fiz com uma div em display none, ficou ótimo, próximo passo será criar um save para local storage

Melhorias em conteúdo dinâmico


Most Man of the match Awards in IPL

Question: Which player have the most man of the match award record in IPL (Indian Premier League)?
Answer: According to Wikipedia's List of Indian Premier League records and statistics, Chris Gayle has the most MOM awards, at 17. See the "Miscellaneous records" section.

Most Man of the match Awards in IPL


Energy functions and Lyapunov

Question:

So I found that $(\pm 1,0)$ and $(0,0)$ are steady states and its trace of the linear system is always $-1$. This implies all three points are sinks (fixed points).
Is the question for (a) implying I need a Lyapunov function for EACH point?
I know for $(0,0)$, I would do $L_0 = y^2/2 - \int_{0}^{t} t - t^3 dt = y^2/2 -x^2/2 + x^4/4$
and for $(\pm 1,0)$, $L_{\pm 1} = y^2/2 - \int_{\pm 1}^{t} t - t^3 dt$
For $L_0$, I find that $L_0' < 0$ for all $(x,y) \neq (0,0)$. But I also find that $L_0(\pm 1, 0) < 0$, so any open set works for my basin of attraction?
Comment: @sidt: Did you ever get this resolved?
Answer: In general you need a Lyapunov function for each point. Any neighborhood about a point is sufficient for local stability. The question asks for "reasonably large" which is not really well-defined, but I think it wants you to find as large a region as you can so that you can draw a goodphase portrait in part C.
Comment: I am getting a contradiction with my functions.

Energy functions and Lyapunov