Does anyone have references/metrics on the value of installing antivirus software - especially on servers?

Question: I strongly dislike antivirus software.  In my opinion, the av software behaves much like a virus.  The recent Symantec incident of actually causing server crashes, resource use, software interference, and user safety bias are each very problematic.
If I have locked down servers behind a firewall, with admins following security protocol (no surfing, no downloads, etc.).  What benefit would I have from installing antivirus software on these machines?  I must install something for insurance purposes...
When i researched AV products a few years ago, the coverage was 95% at best - and these are of known security issues.   That means that the best AV protection is vulnerable to thousands of known viruses and worms.
Every single infection I have encountered has been on a machine with AV software on it.  The user always says - but I have antivirus software...
Can anyone provide metrics on the utility of av software on servers that will make me feel better about having to do it?
Comment: Make you feel BETTER? nope, sorry. I do know that one AV solution we used here would cut the bandwidth of a server in half, or in some cases down to only 10-15mb/s instead of 100mb/s, so watch out for ones that include firewalls.
Answer: Plenty of data provided by the companies selling their anti virus software.
Best practices and regulatory practices in certain industries require its installation.  For example, the PCI DSS requires it.
If you have a workstation that gets compromised by a self propagating worm, it's likely that any Windows servers on the same subnet will be compromised as well.  Unless the servers are storing restricted data, the only risk is to availability.
If you are able to justify the potential risk, go for it.  I believe the argument you provide is technically legitimate.  You also risk the perception of those who can influence your success within your career, as most people believe it to be absolutely necessary for Windows.
Of course, if you want to make this risk, you should enforce certain practices including but not limited to:

Outbound traffic filtering to limit potential exposure in case of compromise.
Policies preventing accessing the Internet  from servers.
Strictly enforced update policies.
Strictly enforced workstation policies, which prevent the potential installation of malware.

Ultimately, good anti virus software will potentially reduce the technical risk.  However, it's unlikely to be much if you have good security policies.  Usually the most risk will be introduced with unrestricted users who are not very technical.
Servers on more restricted subnets with specialized purpose and software will often not have anti virus software installed.  At one point, it was recommended not to install on certain server roles.  I believe this is less common these days.
Comment: In my opinion, running any computer (At least those running Windows operating systems) without any type of AV or anti-malware software is like running across a busy highway. You may get away with it a hundred times but eventually you're going to get hit by a bus.
Comment: Just one example: we had a busy quad-core server that went from 100% CPU usage with Symantec AV (25% directly attributable to realtime scanning) to 50% CPU usage with our current AV product.  Symantec had exclusions defined for entire drives and directory trees that had frequent reads/writes; service process names also were excluded from scanning.  The replacement AV product uses very little CPU on the same server, and it didn't require anything to be excluded from protection.  Don't know your specific requirements, but the ESET management console is very powerful.
Comment: You know, it's funny you say that-- I've never personally had an issue when not running AV software, which I typically won't on my personal workstations.  In contrast, I had an issue with some newer type of malware a few weeks ago on a work laptop running Symantec corporate.  Go figure.
Comment: Symantec AV is a cruel joke: cruel because it uses server resources excessively even when exceptions *are* defined, and a joke because it offers very little protection even when exceptions *aren't* defined.  If you have been led to believe that all enterprise AV software is this bad, you may be pleasantly surprised when you [explore the alternatives](http://serverfault.com/questions/73023/enterprise-level-anti-virus-software-with-these-requirements).
Comment: I've used to like AVG before it turned into adware.  When we assessed multiple enterprise grade AV software recently, my colleagues picked Symantec and I trust their judgment.  I argued against it but when they tested it, my arguments were proven false.  If I recall correctly, NOD32 could not meet our central management and auditing requirements but I have heard good things about it.
Comment: NOD32 has always been top tier, it has been very highly rated for a long time.  Also if your considering scanning speed, NOD32 is blazing fast.  I also have read really positive things about Kaspersky, apparently they were 1. in detection for a while.  Kaspersky also made a fairly fast benchmark, compared to other AV scanners.


Evaluating the quality of a classifier which provides probability per class

Question: I am looking for a metric to evaluate the quality of a classifier which answers the question for a class of an object with a probability per known class. Say I use the classifier to classify an object of class A and the classifier classifies the object with 75% probability as A and 25% probability as C.
One option is, just to pick the probabilities, in this case the 75%. Are there any other metrics?
The Classifier uses a database of classes with different objects but not all objects of one class share the same properties found in an query object, so not all objects of a class may be relevant.
Answer: If your objects do belong 100% to one class each, then you can

set a cutoff and calculate "hard" memberships from that => gives normal sensitivity & Co. (for explanation of their meaning, see e.g. my answer here
varying this cutoff yields receiver operating curves or specificity-sensitivity diagrams etc.

If you want to stay with the 0 - 100% scores as output, sensitivity & Co. can be extended for that. You can also use more regression-type performance like MAE, RMSE, but in that case you should calculate those values separately for each (reference) class.
Some presentations about the basic idea are at softclassval.r-forge.r-project.org (most of the extensions will not be needed unless the reference also takes values in between 0 and 100%). [Paper is waiting for the OK from the co-authors].


Volume of a convex hull in $n$ dimensions

Question: Given $a_1,\cdots,a_n$, s.t. $a_i>0$ for all $i$, consider the set of points:
$$
P=\{ \hat{\mathbf{p}}_i= \langle p_1,\cdots,p_n \rangle \;|\; p_i=a_i, p_j = 0 \text{ for } i\neq j \}
$$
The set of points $P$ define the hyperplane:
$$
\frac{1}{a_1}x_1+\cdots+\frac{1}{a_n}x_n=1
$$
Let $C$ be the convex hull of the points $P\cup \{\langle 0,\cdots,0 \rangle\}$.

Does $C$ have a special name in geometry? That's a special case of a simplex, right?
How can I compute the volume of $C$.
Answer:
Yes, this is a simplex.
The volume is $1/n!$ times the determinant of the matrix with rows $\hat{\mathbf p}_1, \dotsc, \hat{\mathbf p}_n.$
Comment: Could you elaborate more on #2. How is it derived?
Comment: The linear transformation which maps $0$ to $0$ and the standard basis to $p_1, \dotsc, p_n$ multpilies volume by its determinant, and the volume of the standard simplex (one with vertices at $0, e_1, \dotsc, e_n$ has volume $1/n!,$ which you can prove by induction by integrating...
Comment: Nice! I got it. Could you please include your comment in the answer and add a couple of references, if possible. I'll tag it as accepted then. I also made a small edit in your answer. Thanks.


How to determine the quality of a multiclass classifier

Question: Given

a dataset with instances $x_i$ together with $N$ classes where every instance $x_i$ belongs exactly to one class $y_i$
a multiclass classifier

After the training and testing I basically have a table with the true class $y_i$ and the predicted class $a_i$ for every instance $x_i$ in the test set. So for every instance I have either a match ($y_i= a_i$) or a miss ($y_i\neq  a_i$).
How can I evaluate the quality of the match ? The issue is that some classes can have many members, i.e. many instances belong to it. Obviously if 50% of all data points belong to one class and my final classifier is 50% correct overall, I have gained nothing. I could have just as well made a trivial classifier which outputs that biggest class no matter what the input is.
Is there a standard method to estimate the quality of a classifier based on the known testing set results of matches and hits for each class? Maybe it's even important to distinguish matching rates for each particular class?
The simplest approach I can think of is to exclude the correct matches of the biggest class. What else?
Comment: I am not sure if I understand the question correctly. Do you know the [Confusion Matrix and derived measures](http://en.wikipedia.org/wiki/Sensitivity_and_specificity#Terminology_in_information_retrieval) ? Is this the answer to your question ? Or do you refer to something more complicated ?
Comment: I think this is the source of my confusion: In the first paragraph you state _..where yi is the real classes and..._: Do you mean that an instance $x_i$ can belong to / has more than one class ? Or does every $x_i$ belongs to / has exactly one class ? Can you please clarify ?
Comment: @steffen: I've seen the confusion matrix. In my particular case I have 4 classes. So I'm not sure which derived measures can be used and would make sense. Each $x_i$ belongs to only one class. However there are more than two possible classes overall $i\in [1,\cdots,N]$.
Comment: @steffen Those derived measures are primarily applicable to **binary** classification, whereas this question explicitly is dealing with more than two classes.  This then requires a modified understanding of terms like "true positive."
Comment: @MichaelMcGowan I have asked the OP for clarification and afterwards performed an edit to explicitly reflect the multiclass issue, which was not obvious before the edit (IMHO).
Comment: I suppose the meaning of positive depends on the particular problem and the importance of the classes. I was playing around with different self-made measures. Maybe there is a more standardized approach.
Comment: Someone can find this work helpful. The work is dedicated exactly to the problem of qualifying multivariate cases in classification tasks. http://arxiv.org/abs/1202.6221
Answer: Like binary classification, you can use the empirical error rate for estimating the quality of your classifier. Let $g$ be a classifier, and $x_i$ and $y_i$ be respectively an example in your data base and its class.
$$err(g) = \frac{1}{n} \sum_{i \leq n} \mathbb{1}_{g(x_i) \neq y_i}$$
As you said, when the classes are unbalanced, the baseline is not 50% but the proportion of the bigger class. You could add a weight on each class to balance the error. Let $W_y$ be the weight of the class $y$. Set the weights such that $\frac{1}{W_y} \sim \frac{1}{n}\sum_{i \leq n} \mathbb{1}_{y_i = y}$ and define the weighted empirical error
$$err_W(g) = \frac{1}{n} \sum_{i \leq n} W_{y_i} \mathbb{1}_{g(x_i) \neq y_i}$$
As Steffen said, the confusion matrix could be a good way to estimate the quality of a classifier. In the binary case, you can derive some measure from this matrix such as sensitivity and specificity, estimating the capability of a classifier to detect a particular class.
The source of error of a classifier might be in a particular way. For example a classifier could be too much confident when predicting a 1, but never say wrong when predicting a 0. Many classifiers can be parametrized to control this rate (false positives vs false negatives), and you are then interested in the quality of the whole family of classifier, not just one.
From this you can plot the ROC curve, and measuring the area under the ROC curve give you the quality of those classifiers.
ROC curves can be extended for your multiclass problem. I suggest you to read the answer of this thread.
Comment: Is it not necessary to divide the weighted empirical error by the number of classes, to be on the same scale as the empirical error? Otherwise it would be much bigger...
Answer: To evaluate multi-way text classification systems, I use micro- and macro-averaged F1 (F-measure). The F-measure is essentially a weighted combination of precision and recall that. For binary classification, the micro and macro approaches are the same, but, for the multi-way case, I think they might help you out. You can think of Micro F1 as a weighted combination of precision and recall that gives equal weight to every document, while Macro F1 gives equal weight to every class. For each, the F-measure equation is the same, but you calculate precision and recall differently:
$$F = \frac{(\beta^{2} + 1)PR}{\beta^{2}P+R},$$
where $\beta$ is typically set to 1. Then,
$$P_{micro}=\frac{\sum^{|C|}_{i=1}TP_{i}}{\sum^{|C|}_{i=1}TP_{i}+FP_{i}}, R_{micro}=\frac{\sum^{|C|}_{i=1}TP_{i}}{\sum^{|C|}_{i=1}TP_{i}+FN_{i}}$$
$$P_{macro}=\frac{1}{|C|}\sum^{|C|}_{i=1}\frac{TP_{i}}{TP_{i}+FP_{i}},
R_{macro}=\frac{1}{|C|}\sum^{|C|}_{i=1}\frac{TP_{i}}{TP_{i}+FN_{i}}$$
where $TP$ is True Positive, $FP$ is False Positive, $FN$ is False Negative, and $C$ is class.
Answer: <code># Function in R, using precision, recall and F statistics

check.model.accuracy <- function(predicted.class, actual.class){

  result.tbl <- as.data.frame(table(predicted.class,actual.class ) )

  result.tbl$Var1 <- as.character(result.tbl$predicted.class)
  result.tbl$Var2 <- as.character(result.tbl$actual.class)

  colnames(result.tbl)[1:2] <- c("Pred","Act")

  cntr <- 0
  for (pred.class in unique(result.tbl$Pred) ){
    cntr <- cntr+ 1
    tp <- sum(result.tbl[result.tbl$Pred==pred.class & result.tbl$Act==pred.class, "Freq"])
    tp.fp <- sum(result.tbl[result.tbl$Pred == pred.class , "Freq" ])
    tp.fn <- sum(result.tbl[result.tbl$Act == pred.class , "Freq" ])
    presi <- tp/tp.fp
    rec <- tp/tp.fn
    F.score <- 2*presi*rec/(presi+rec)
    if (cntr == 1 ) F.score.row <- cbind(pred.class, presi,rec,F.score)
    if (cntr > 1 ) F.score.row <- rbind(F.score.row,cbind(pred.class,presi,rec,F.score))
  }

  F.score.row <- as.data.frame(F.score.row)
  return(F.score.row)
}

check.model.accuracy(predicted.df,actual.df)
# For multiclass, average across all classes
</code>
Comment: Can you add some text to explicate this?


Trying to replace one Fragment with another in android studio (Kotlin)

Question: I am trying to create an OnClickListener that changes the fragment inside of a NavController and I keep getting nothing to happen on button press. Here is my code so far:
MainActivity:
 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val navView: BottomNavigationView = binding.navView

        val navController = findNavController(R.id.nav_host_fragment_activity_main)

        val appBarConfiguration = AppBarConfiguration(
            setOf(
                R.id.navigation_check_in, R.id.navigation_dashboard, R.id.navigation_new_emp
            )
        )
        setupActionBarWithNavController(navController, appBarConfiguration)
        navView.setupWithNavController(navController)
 }

CheckInFragment:
 override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.newEmpBtn.setOnClickListener(View.OnClickListener {
            requireActivity().supportFragmentManager.commit {
                replace(R.id.nav_host_fragment_activity_main, NewEmpFragment().newInstance())
                setReorderingAllowed(true)
                addToBackStack(null)
            }
        })

    }

Currently, this code is not giving an error it just seems to not be working and I've been searching through forums for the last couple of hours. Any ideas would be great!
Answer: I think you are missing beginTransaction(). You can try this.
    binding.newEmpBtn.setOnClickListener(View.OnClickListener {
       val fragmentManager = parentFragmentManager
       val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
       fragmentTransaction.replace(
           R.id.nav_host_fragment_activity_main,
           NewEmpFragment()
       )
       fragmentTransaction.addToBackStack(null)
       fragmentTransaction.commit()
    })


How do I interact with UI and async functions by a button press?

Question: So I have a login button that would initiate an async function logMeIn() for logging in, which returns a Future<bool> indicating if logging in was successful.
What I want to achieve is after pressing the button, the text within the button would change into a CircularProgressIndicator, and become plain text when logMeIn() has finished.
I know that I could use a FutureBuilder for one-time async tasks, but I simply can't think of a way to use it here.
How am I supposed to achieve this?
Thanks in advance.
Edit
I didn't provide more information because I'm pretty sure it wasn't how it's supposed to be done. But I'd share what I tried whatsoever.
My original button looks somewhat like this:
RaisedButton(
  child: Text("Login")
)

I have a async login function that returns a Future<bool> which indicates if the login is successful or not.
Future<bool> logMeIn() async {
  // login tasks here
}

What I want to do is to change the button to the following and run logMeIn() when I press the button, and change it back to the plain text version after it's finished:
RaisedButton(
  child: CircularProgressIndicator()
  onPressed: () {}
)

What I tried
I tried adding a logging_in boolean as a flag to control it, here I call the button with plain text StaticButton(), the other named ActiveButton:
Then I wrapped the ActiveButton with a FutureBuilder:
logging_in ? FutureBuilder(
  future: logMeIn(),
  builder: (_, snapshot) {
    if(snapshot.hasData)
      setState(() {
        logging_in = false;
      });
    else
      return ActiveButton();
  }
) : StaticButton();

and when I pressed the button it would setState and set logging_in = true.
StaticButton:
RaisedButton(
  child: Text("Login"),
  onPressed: () {
    setState(() {
      logging_in = true;
    });
  }
)

The above is what I tried. Should accomplish the effect, but is definitely not elegant. Is there a better way to achieve this?
Comment: What have you tried? Please share any relevant code.
Comment: @ChristopherMoore Added details of what I tried. Looking for just a heads up on what I should be searching for, a keyword is basically enough :(
Comment: Have you tried my answer?
Comment: @ChristopherMoore Yup, thanks for explaining the logic. Was too focused on FutureBuilder and got lost. Your answer worked well :)
Answer: What you have isn't that far off. You have a logging_in variable that tells you when to show the CircularProgressIndicator already, which is a good start. The only thing is that FutureBuilder has no use here. It's meant for retrieving data from Futures that need to be displayed in the UI.
What you need to do is call logMeIn in the onPressed of your "Static button" as shown here:
StaticButton:
RaisedButton(
  child: Text("Login"),
  onPressed: () async {
    setState(() {
      logging_in = true;
    });
    await logMeIn();
    setState(() {
      logging_in = false;
    });
  }
)

You don't need to switch out the whole button when logging_in changes, just the child of the button.
StaticButton(with child switching):
RaisedButton(
  child: logging_in ? CircularProgressIndicator() : Text("Login"),
  onPressed: () async {
    setState(() {
      logging_in = true;
    });
    await logMeIn();
    setState(() {
      logging_in = false;
    });
  }
)

You also probably want to add another bool to prevent multiple clicks of the button while its loading. As a note in using FutureBuilder and essentially any other builder in flutter, you always need to return a widget from the builder function, which your current implementation does not do.


Como obter uma instancia em .net core sem usar construtor

Question: Normalmente uso o contrutor para obter dependencias algo do tipo:
public class Test
{
    private IServiceDependency serviceDependency;
    Test(IServiceDependency serviceDependency)
    {
         _serviceDependency = serviceDependency;
    }
}

Como faço para obter a dependencia sem usar o construtor
GetDependence(); é apenas um método para ilustrar a forma como gostaria de obter a dependência em .net core
 public class Test
 {
     private IServiceDependency serviceDependency;
     Test()
     {
        _serviceDependency = GetDependence();
     }
 }

Comment: Viu a resposta?
Comment: Não viu? perguntou e não tem interação?
Answer: O seu exemplo não condiz com a realidade de Injeção de Dependência que pode acontecer no caso .NET Core de duas formas, pelo construtor ou pelo método, a primeira já sabe como funciona a outra é com [FromServices] que precede as configurações de um método na declaração das variáveis, por exemplo:
public IActionResult Create([FromServices] IServiceDependency dependency)
{
    dependency....
}

Esse tipo de recurso pode ser usado para um ou várias injeções de dependência que é necessário para o seu codigo.
Referencia: Dependency injection into controllers in ASP.NET Core


O que é linguagem simbólica no contexto de Assembly

Question: Realizando uma lista de Organização de Computadores me deparei com a seguinte pergunta:
Reescreva os programas escritos em linguagem de montagem (assembly) no exercício anterior para linguagem simbólica. Considere
que a primeira instrução de cada programa seja "montada" na posição de memória 512 e que cada instrução ocupa exatamente 1 posição
dessa memória. Os dados são armazenados na memória a partir da posição 640 considerando o rótulo das variáveis em ordem alfabética
Encontrei problema em resolver tal atividade em razão da 'linguagem símbolica', que não sei oque é nesse contexto de OC. Pesquisando não encontrei a definição exata de linguagem símbolica no contexto de Assembly, mas encontrei essa resposta no Quora que indica oque são símbolos em Assembly, mas não responde: quais símbolos representa as diretivas do Assembly, tais como ADD, SUB, etc. Nesse caso eu suponho que tenha que escrever o número da operação e o número dos operandos em binário ou uma representação fornecida pelo autor (certo ?), transformando a linguagem Assembly em algo mais 'abstrato', parecido com:

Minha interpretação está correta ? Se sim, na atividade nada é informado, como eu resolveria isso ?!?
Obs: Não quero que façam a atividade, quero entender como eu posso fazer.
Answer: A linguagem de máquina normalmente é acompanhada de uma versão "legível" chamada Linguagem Simbólica ou simplesmente de Assembly.
Simbólica pois esta linguagem não é composta de números binários ou hexadecimais. A linguagem Assembly é na realidade uma versão legível da linguagem de máquina. Ela utiliza palavras abreviadas, chamadas mnemônicos, indicando a operação a ser realizada pelo processador.
Exemplo:
A instrução em Linguagem de Máquina padrão x86:
00000105h

Pode ser atribuida ao mnemônico MOV (abreviação de movement) tendo dois registradores como parâmetro, R1 e R5. Quando o processador executa essa instrução, ele comanda o movimento do conteúdo de R5 para R1.
Então a instrução em linguagem de máquina 00000105h pode ser escrita em linguagem simbólica como:
MOV R1, R5


What is the order of Android call state change when out going or incoming happened?

Question: The following are the changes in phone state in android

CALL_STATE_OFFHOOK
CALL_STATE_IDLE
CALL_STATE_RINGING

When i am making an outgoing call ,one received my call and after some time I or He ends the call.
When i have a incoming call ,I received the call and after some time I or He ends the call.

Where i want to use the broadcast receiver and Listener and why service is using for doing this.
Answer:
What is the order of android call state change when out going or
  incoming happened?

incoming call:
nothing happened : CALL_STATE_IDLE
someone calls you: CALL_STATE_RINGING
call recieved:     CALL_STATE_OFFHOOK
call ended:        CALL_STATE_IDLE

outgoing call:
nothing happened :                        CALL_STATE_IDLE
start a call (pressing green button):     CALL_STATE_OFFHOOK
call ended:                               CALL_STATE_IDLE


How to build HTTP Response with ESP8266 and Arduino

Question: I want to toggle some LEDs with my Android device. These LEDs are connected to the digital Pins of my Arduino which is also connected to a ESP8266. Now, my ESP8266 is defined as an AccessPoint and my Tablet can send HTTP requests (e.g. http://192.168.4.1:80/?pin=11).
I found the code here http://allaboutee.com/2015/01/20/esp8266-android-application-for-arduino-pin-control/
It works fine but my question is which HTTP header fields should be used? In this code he used some (e.g. Content-Length) but there are so much more possible (Date, Server, Content-Language,...).
Are these fields optional or which of these have to be used to build the right response?
Here is the piece of code I do not understand:
<code>void sendHTTPResponse(int connectionId, String content)
</code>
{
<code> String httpResponse;
 String httpHeader;

 httpHeader = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n";
 httpHeader += "Content-Length: ";
 httpHeader += content.length();
 httpHeader += "\r\n";
 httpHeader +="Connection: close\r\n\r\n";
 httpResponse = httpHeader + content + " ";
 sendCIPData(connectionId,httpResponse);
</code>
}
Comment: The list of possible header fields can be found here: https://en.wikipedia.org/wiki/List_of_HTTP_header_fields
Answer: It largely depends on the client (i.e. consumer) which fields are required and which are mandatory.
The only one that is always required is "HTTP/1.1 200 OK". Of course you need to replace that status code if you're not sending an OK message.
Comment: If your Android device expects HTTP then you need to declare the response as being an HTTP response. "HTTP/1.1" is the protocol and "200 OK" is the status. You also need to have the "\r\n" in place as shown in the example you posted. I suggest you familiarize yourself with http://code.tutsplus.com/tutorials/http-headers-for-dummies--net-8039.
Comment: Thanks for the fast reply @MarcelStör ! So if I want to get a feedback on my Android device I need to have this "HTTP/1.1 200 OK" but the other fields are optional right ? And what does this HTTP/1.1 200 stand for ?


Adding Wordpress .htaccess code to Apache config (for all sites)

Question: The default .htaccess code for WordPress is:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

How can I insert the code into the Apache config to avoid having to use .htaccess? I need the code to apply to all addon domains on the server (all domains on the server are running WordPress).
In addition, WordPress recommends adding this code:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^wp-admin/includes/ - [F,L]
RewriteRule !^wp-includes/ - [S=3]
RewriteRule ^wp-includes/[^/]+\.php$ - [F,L]
RewriteRule ^wp-includes/js/tinymce/langs/.+\.php - [F,L]
RewriteRule ^wp-includes/theme-compat/ - [F,L]
</IfModule>

Though I'm not sure if it's needed anymore as when I removed it and tried to load these pages, they went to 404 anyways.
My goal is to completely get rid of .htaccess files to speed up the loading of my sites.
Apache 2.4+/CentOS
Comment: The effect of having rules in configuration vs `.htaccess` is quite minimal. You should concentrate on caching on WordPress side instead, that will provide bigger benefits.
Comment: @Tero Kilkanen I already have maximum caching. I don't need .htaccess files as I own every site on the server and they're all Wordpress.
Comment: Anyway, the speedup from moving the rules to main Apache configuration is so small so that you cannot notice it. Therefore I don't think it is worth any effort to deviate from WP standard.
Comment: "Questions involving web hosting control panels are off-topic" - although the question doesn't appear to have anything to do with "web hosting control panels"; the question would seem to have been incorrectly tagged. (?)
Answer:
I need the code to apply to all addon domains on the server

How you configure this will depend on whether you have a separate <VirtualHost> (vHost) for each Addon domain, or whether you have a single vHost for all Addon domains.
Separate <VirtualHost> for each Addon domain
There are two options here. You can either inherit the common (WordPress) directives from the server config, or include a common config file into each vHost.
Inherit from server config
If your "addon domains" are served from separate <VirtualHost> containers then you could place these "common" mod_rewrite directives in the main server config (outside of the vHost) and enable mod_rewrite inheritance.
But note that in a server (or virtualhost) context these directives need to be altered slightly. For example:
RewriteEngine On

# Enable all (child) vhost configs to inherit these directives
# (Requires Apache 2.4.8+)
RewriteOptions InheritDown

RewriteRule ^/index\.php$ - [L]
RewriteCond %{LA-U:REQUEST_FILENAME} !-f
RewriteCond %{LA-U:REQUEST_FILENAME} !-d
RewriteRule ^/. /index.php [L]

Changes explained:

Removal of RewriteBase (not valid in server context)
Use of lookahead (LA-U:) to retrieve the filename the request is mapped to.
The URL-path that is matched and substitution strings are all root-relative and start with a slash.
The <IfModule> wrapper is not required.

# Enable all (child) vhost configs to inherit these directives
# (Requires Apache 2.4.8+)
RewriteOptions InheritDown

As noted, this requires Apache 2.4.8 or later. The rewrite engine still needs to be enabled in the child vHost config. These directives (in the server config) are essentially copied in-place after any existing directives in the vHost container. (The WordPress front-controller generally needs to come after other directives.)
If you are not on Apache 2.4.8+ then you will instead need to include the following in all the child vHost configs in order to inherit the parent config.
# Inherit mod_rewrite directives from the server config after the current directives
RewriteOptions Inherit

RewriteOptions Inherit in all child configs (<VirtualHost> container) is the same as specifying RewriteOptions InheritDown in the parent config.
UPDATE: Include additional config file
Instead of using mod_rewrite inheritance as mentioned above, you could simply Include the common (WordPress) config file at the appropriate place in each vHost container.
This would also allow you to keep the original directives from the .htaccess file and include these unaltered in the relevant <Directory> container. (Instead of using them directly in the vHost container or main server config.)
For example, if the contents of your original .htaccess file was in the config (include) file /etc/apache2/sites-enabled/wordpress.conf. Then in your vHost container:
DocumentRoot /var/www/example.com/public_html

<Directory /var/www/example.com/public_html>
    AllowOverride None
    Require all granted
    Include /etc/apache2/sites-enabled/wordpress.conf
</Directory>

.htaccess and <Directory> containers in the server config are both "directory" context, so the directives work unaltered.

A single <VirtualHost> for all Addon domains
Alternatively, if all your "addon domains" are served from the same <VirtualHost> container (or even all from the server config diretcly - no vHosts - although I think vHosts are easier to manage) then the above mod_rewrite code block (as modified for the server config) would just go directly in the vHost container (or use the original .htaccess directives inside a <Diretcory> container). No need for the RewriteOptions directive - no mod_rewrite inheritance required.
However, this requires additional directives to route the request for each addon domain to the appropriate WordPress installation directory. By either:

Use mod_rewrite to internally rewrite the request to the appropriate subdirectory or filesystem path. But note that all sites have the same DocumentRoot. You may need additional directives to prevent direct access to the "addon" subdirectory. You might need to explicitly "correct" the DOCUMENT_ROOT that WordPress uses.

OR, use VirtualDocumentRoot (mod_vhost_alias) based on the domain being requested to route requests to the appropriate subdirectory. This creates a dynamic DocumentRoot.

For example, using mod_vhost_alias:
<VirtualHost *:443>
    UseCanonicalName Off
    ServerAlias www.*.com
    VirtualDocumentRoot /var/www/%2+/public_html
    <Directory /var/www/*/public_html>
        AllowOverride None
        Require all granted
        Include /etc/apache2/sites-enabled/wordpress.conf
    </Directory>

    # SSL config etc. ...

</VirtualHost>

The DocumentRoot would be /var/www/example.com/public_html (or whatever hostname is requested, less the www prefix). This has the advantage that new sites can be added by simply creating a new subdirectory, no changes required to the server config and consequently no need to restart the server.
This would be more suited if all your WordPress sites require the same config. If certain sites require specific customisations then it may get more complex or "tricky" to implement. However, you could create another/separate vHost in this case.
This would also likely require additional/different steps to later separate the access/error logs for the different domains. (Although you would likely need to do something like this anyway if you are hosting many separate vHosts.)
Reference:
https://httpd.apache.org/docs/2.4/vhosts/mass.html
https://httpd.apache.org/docs/2.4/mod/mod_vhost_alias.html

If you are moving away from using .htaccess then you need to ensure you completely disable .htaccess overrides in the vHost to get the full benefit. ie:
<Directory /var/www>
    AllowOverride None
</Directory>

Otherwise, Apache still wastes time searching for the .htaccess files.
Comment: I am going to accept your answer even though sadly, I'm using Apache 2.4.46 and the latter method you mentioned (for non-2.4.8+) is not one code that will affect all domains. At least, as I understand it, you said each domain's vHost config would need to have that code added.
Comment: "sadly, I'm using Apache 2.4.46" - 2.4.46 is much more recent than 2.4.8 (that's not "80", if that's what you were thinking?).


How to validate machine learning models with imbalanced datasets?

Question: I'm trying to train a neural network model. Let us suppose that I have a dataset with 4 classes:
Class 1 - 500 samples
Class 2 - 2000 samples
Class 3 - 15000 samples
Class 4 - 60000 samples
In my first approach, I have used downsampling for training my model. Thus, I have selected 400 random samples of each class for training and 50 samples for validation. But I'm not sure about how to test my model.
Should I use all the remaining samples of each class for testing? Or should I test in a balanced way, let's say, using only 50 samples?
Comment: Unbalanced classes are almost certainly not a problem, and oversampling or downsampling will not solve a non-problem:
[Are unbalanced datasets problematic, and (how) does oversampling (purport to) help?](https://stats.stackexchange.com/q/357466/1352)
Answer: Well,
dealing with unbalanced data requires a lot of attention. Despite the fact that many algorithms rely on the premise of balanced data in the training phase, they can easily make you misinterpret your results.
To validate on unbalanced datasets the most practical way is to downsample it exactly how you did for the training. In your example, you can randomly choose 50 samples of each class for it.
The other non-obvious way is to give different weights for each class when calculating your eval metric, like accuracy. I believe your preferred framework will have functions like balanced accuracy on scikit-learn to handle it for you.
But again, be careful to not forget they are unbalanced when looking for some results, and analyze precision and recall for each class individually.


Why all debug buttons disabled?

Question: I have installed flashdevelop in windows XP, and although I've installed java 6, all buttons of debugger are disabled ..
Any idea? please see attached image
Answer: They are disabled because the debugger isn't connected to any SWF.
Comment: Do you mean, I must compile first?
Comment: Yes the buttons will be enabled when you'll launch the compiled SWF from FlashDevelop.

Why all debug buttons disabled?


let f be a continuous function such that $f(0)\le1$ and for all real x, $f(x)^2 - 3f(x) + 2 \ge 0$. Prove that $f(x)\le 1$ for all real x

Question: Question:
let $f:\mathbb{R}\rightarrow\mathbb{R}$ be a continuous function such that $f(0)\le 1$ and for all real $x$, $f(x)^2 - 3f(x) + 2 \ge 0$. Prove that $f(x)\le 1$ for all real $x$.
I think you would start by factorising to get $(f(x)-2)(f(x)-1)\ge0$ and then $f(x)\ge1$ but I'm not really sure where to go from there? I think maybe you can use the intermediate value theorem but I'm not exactly sure how. TIA
Answer: Factorizing is a good start. Suppose now, there were some $x$ with $f(x) > 1$. By the intermediate value theorem due to $f(0) \le 1$, there is some $x_0$ with $1 < f(x_0) < 2$. But then $$\bigl(f(x_0) - 2\bigr)\bigl(f(x_0) - 1\bigr) < 0$$
Contradiction.


Inconsistent socket latency between ESP32 and Kotlin server

Question: Context:

I have a Server (Mac Mini) and a Client (ESP32) that are communicating through a socket connection via the WifiClient class.
The server is connected to the router by ethernet and the client is connected to the router using 2.4ghz WiFi.
The server is written in Kotlin and is using the default Java socket implementation.
The client is to assign the colors to Neopixel LEDs (led 1 and 2, respectively) using the FastLED library.

For the sake of testing, the server is sending FF0000|FF0000 and 0000FF|0000FF (as strings) in an alternating pattern 60 times per second. This test works well because if the color updates at a rate of 60 times per second, the LEDs should look purple. If the system is performing poorly, then I will see the individual colors.
Client Github Repo and Server Github Repo for additional context.
The Problem:
I am very clearly seeing alternating blue, red, and purple. This tells me that there are performance problems somewhere, but there are also brief moments where it performs as expected.
My Findings:
I've been logging the times it takes to read out each message on the client:
std::string SocketManager::getNextCommand()
{
    unsigned long start = micros();

    // TODO: Flush isn't working
    // flush(): fail on fd 56, errno: 11, "No more processes"
    // client.flush();

    // We need to read in our next command; wait until command is available.
    String message;
    while (client.connected() && message.length() == 0)
    {
        message = client.readStringUntil('\n');
    }

    unsigned long end = micros();
    Serial.print("Time: ");
    Serial.println(end - start);

    return message.c_str();
}

The times that print out are generally good, but I get periodic spikes about 10 times per second. I have added a log to Pastebin here.
I thought that the clients buffer was becoming saturated when I first saw this. I then lowered the message rate on the server to 2 times per second, but I still was seeing significant variation in message times. That log is here.
I printed out the system time whenever the server sent a message to verify that it is being written at the correct rate. Updating 2 times a second consistently yields gaps of 500ms, so I think it is reasonable to rule out the server. This would suggest that the issue is either the transit time or ESP32 (considering the server is posting at the specified intervals).
The ping between the two devices is 5-10ms when the socket is not active, but is 50-400+ when the socket is active...even if I'm not sending any messages back and forth! Heck - it's that high even when I completely comment out the client's while loop (i.e. it immediately returns an empty string).
The Question:
It would seem that my central problem is the latency between the devices while the socket is active. At the very least - the ping increase when the socket is active seems within the ballpark of the latency increase while attempting to read the next command.
Do you think that the socket is the primary problem here? If so - why?
It seems strange to me that such a massive latency increase would occur simply by virtue of a socket being active...especially when not transmitting any sizable data back and forth.
Answer: I set the performance preferences and disable TCP delay on the server's socket connection based on this thread.
In the server code I set the ServerSocket performance preferences to 1, 2, 0.
val server = ServerSocket(9999)
server.setPerformancePreferences(1, 2, 0)

I also disabled TCP delay on the connection.
while (true) {
    val client = server.accept()
    println("Client connected: ${client.inetAddress.hostAddress}")

    client.soTimeout = 1000
    client.tcpNoDelay = true;

    // Run client in it's own thread.
    thread { ClientHandler(client).run() }
}

This appeared to make a drastic improvement. There are definitely moments where the lights are (mostly) purple. It does seem like the latency degrades over time and the connection may die, so there is still fine tuning to be done.
So - I think this issue is mostly solved (with some fine tuning). That said, I would still appreciate any further input that anybody has.
Comment: Just a few thoughts off the top of my head: Do you have a way to see if you are getting many TCP retransmits? Do you have a way to see if using the String class is reducing the size of the largest allocatable continuous memory on the heap? Do you have the same performance problems with UDP (no retransmits, no ACKs)?
Comment: (I'm not particularly well versed in networking, so please bear with me.) I installed Wireshark and was able to watch the traffic between the server and client. And, sure enough, I did stumble across retransmissions. In fact - I recorded one extreme instance where the color was stuck for a substantial amount of time.

It looks like the length still grew during the period of retransmits. The period following the freeze was perfectly purple, so I suspect the ESP32 was processing the backlog.

https://docs.google.com/spreadsheets/d/1lHE1nXRTgeuh8olLRJvDX6EOGXrpgAqlB4GgXOqMYPA/edit?usp=sharing
Comment: I'll look into UDP sockets and see if that helps.


using Python, how can I get and print to html Twilio logs?

Question: I want to get Twilio SMS logs and print them out as HTML. The code is:
from twilio.rest import TwilioRestClient

@application.route("/logs", methods=['GET', 'POST'])
def logs():

    client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)
    data = client.sms.messages.list()
    return data

this returns an error as follows:
File "/Library/Python/2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Library/Python/2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1478, in full_dispatch_request
response = self.make_response(rv)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1577, in make_response
rv = self.response_class.force_type(rv, request.environ)
File "/Library/Python/2.7/site-packages/werkzeug/wrappers.py", line 841, in force_type
response = BaseResponse(*_run_wsgi_app(response, environ))
File "/Library/Python/2.7/site-packages/werkzeug/wrappers.py", line 57, in _run_wsgi_app
return _run_wsgi_app(*args)
File "/Library/Python/2.7/site-packages/werkzeug/test.py", line 867, in run_wsgi_app
app_rv = app(environ, start_response)
TypeError: 'list' object is not callable

Does "list object is not callable" mean the object is empty or somehting else? What is the correct way to do this and get an object returned that I can parse as json?
Many thanks in advance.
Comment: `app` is a list, that's what that means. Why? Short a [mcve] that's not clear.
Comment: thank you and sorry I don't understand what you mean, there seems to be mutual miscomprehension. The error indicates something has gone wrong and I don't know what has gone wrong. I want to be able to read the http response and print some if it out as html. The http response is json data and an example is here: https://www.twilio.com/docs/api/rest/sms#list
Comment: Try `data = client.sms.messages.list`, i.e.: without the parentheses.
Comment: thank you, sorry does not work. The error is "StopIteration".
Answer: The output from data = client.sms.messages.list() should look like this:
"page": 0,
    "page_size": 50,
    "uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SMS/Messages.json"
    "first_page_uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SMS/Messages.json?Page=0&PageSize=50",
    "next_page_uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SMS/Messages.json?Page=1&PageSize=50",
    "previous_page_uri": null,
    "sms_messages": [
        {
            "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
            "api_version": "2008-08-01",
            "body": "A message from StackOverflow.",
            "date_created": "Mon, 16 Aug 2010 03:45:01 +0000",
            "date_sent": "Mon, 16 Aug 2010 03:45:03 +0000",
            "date_updated": "Mon, 16 Aug 2010 03:45:03 +0000",
            "direction": "outbound-api",
            "from": "+14158141829",
            "price": "-0.02000",
            "sid": "SM800f449d0399ed014aae2bcc0cc2f2ec",
            "status": "sent",
            "to": "+14159978453",
            "uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SMS/Messages/SM800f449d0399ed014aae2bcc0cc2f2ec.json"
        },
        ...
    ]
}

Check out the FAQ about retrieving logs and let me know if this helps at all.
Comment: thank you, this has now been fixed by using the API Explorer. The snippet of code I was looking for was for m in messages print m.sid thank you


Xamarin Resource ID #0x7f050000 type #0x12 is not valid

Question: I read few similar threads here, but none of the solutions works. I am pretty new in Xamarin Programming.
This is the code that creates the problem:
try
{
    var combo = FindViewById<Spinner>(Resource.Id.spinner);
    ArrayAdapter adapter = new ArrayAdapter(this, Guardian.Resource.Id.spinner, gdm.Porgram_names);
    combo.Adapter = adapter;
}
catch (Exception exc)
{

}

My app crashes and this message appears (try catch block dosen't catch it):

Android.Content.Res.Resources+NotFoundException: Resource ID #0x7f050000 type #0x12 is not valid

When i comment this line: combo.Adapter=adapter; the program doesn't crash.
Any idea what is wrong?
Comment: What is `Guardian.Resource.Id.spinner`? Is that a layout or just a single item?
Comment: yeah I had the same issue.. thanks for posting this question
Answer: The second parameter to ArrayAdapter needs to be a Resource.Layout resource that determines how each row in the List is displayed.
It cannot be a Resource.Id value.
In other words, you've found the Spinner by an ID, then you need to say how you'd like to show the items within that Spinner using a layout.
For example,
new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, gdm.Porgram_names);

Comment: Thank you so much!  omg that was driving me insane.. so much more complicated than creating comboboxes in WPF/Winforms lol.. helped me a lot =]


removeObject removes random object instead of the specific one

Question: I'm making this 2D shooter game in Java as a Learning project.
I currently have one enemy Class in the game as a start. If I have multiple of those enemies on the screen and one of them dies by my bullets, a random enemy will die out of those on the screen. I know that having the same enemy in several classes with a seperate Health is a solution, but a very bad one. There must be Another way of doing this?
Comment: The solution is to fix the bug in your program, but it will be hard for any of us to help based on what you've posted so far. Please try to improve this question. You could look at the [tour], the [help] and especially at the [how to ask good questions](http://stackoverflow.com/help/how-to-ask) sections to see how.
Comment: Please provide a [Minimal, Complete and Verifiable example](http://stackoverflow.com/help/mcve)
Comment: There is no bug. It is me not knowing how to make it remove the specific enemy.
Comment: And that is the bug. Again I don't see how we can help based on what you've posted so far. I would imagine that Enemy has a health field, and when an individual Enemy object is hit, his health goes down, right? And how much it goes down will depend on how he was hit and with what. So why not have him die when his health is < 0, and when this happens have the Enemy object itself remove itself from the enemies list. But all the details of how this is implemented will depend on the details and structure of your code, something we know nothing about.
Comment: I have one enemy class, and it got 100 Health. Once my bullet hits it, his Health goes down by 20. After 5 hits a random enemy dies instead of the one I shot because all of the enemies share the same Health. So I either have to make many enemy classes doing the same thing with a seperate healthbar. Every enemy need a seperate healthbar.
Comment: `"...because all of the enemies share the same Health..."` -- This makes no logical sense, and looks like a bug. Why not have every enemy **object** have its own health field? And you shouldn't be posting important details about your question in comments. Instead this key information should go into your question as an [edit to the question](http://stackoverflow.com/posts/34111666/edit), and then then notify us of changes in comments.
Comment: the best answer could be: 1 put your objects (ennemies) in an array 2 use a random function to select one 3 remove this ... can you code this, please ?
Comment: Hahaha I know it sounds stupid but when the enemies spawn they are basically the same enemy duplicated, which means the same Health.
Answer: I think you use static field in Enemy class instead of normal one, for example:
Enemy {
    static Health health;
    ...
}

instead of
Enemy {
    Health health;
    ...
}

Use non-static fields and in this case you can just have List < Enemy > enemies and get only one enemy object from it's, for example:
  enemies.get(3).setHealth(Health.Died) // died enemy with number 3

Comment: public static float BEHealth = 100; So this is the problem?
Comment: Yes, it's main problem in your code, replace to "public float BEHealth = 100;" and you can change health for every enemy separately.
Comment: Yeah it worked :) Thank you for helping me :D
Comment: If it's working fine, could you acept my answer that show this question is closed and not need new answer?
Comment: Yes of course but how do I do that? :D
Comment: Just tick this answer (tick at the left of answer before 0). More info this: http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work
Comment: There we go. Thank you again :)
Comment: I cannot ask Another question for 90 minutes so maybe you can help me again? When I press SPACE a bullets spawns, but now at my player position, here is the bullet spawn code:
    // Player Shoot
    if(key == KeyEvent.VK_SPACE){
     int x = 4;
     int y = 8;
     handler.addObject(new PlayerBullet(x, y, ID.PlayerBullet, handler));
Comment: I realize X and Y is in need of a change but don't know what to do.
Comment: You need use something like this: Player Shoot if(key == KeyEvent.VK_SPACE){ int x = 4; int y = 8;
PlayerBullet bullet = new PlayerBullet(x, y, ID.PlayerBullet, handler)
handler.addObject(bullet); for(int i=0; i< len; i++) { bullet.setX(x + i); bullet.setY(y + i); sleep(100);} }


GIt connection closed by remote host

Question: I just configure two ssh keys on git, but when i test ssh connection it returns a error,here is the
debug log:
debug1: key_load_public: No such file or directory

Connection to code.aliyun.com closed by remote host.
Connection to code.aliyun.com closed.
Transferred: sent 2528, received 1472 bytes, in 0.0 seconds
Bytes per second: sent 12863830.2, received 7490331.5
debug1: Exit status -1

I don't know where went wrong, I have send the public key to the sever and still got a error,thanks
Comment: Possible duplicate of [Multiple GitHub Accounts & SSH Config](https://stackoverflow.com/questions/3225862/multiple-github-accounts-ssh-config)
Answer: It depends on the exacy SSH URL you are using once you have configured those two keys.
Configuring multiple SSH keys should be done in a ~/.ssh/config file
Host key1
 HostName code.aliyun.com
 IdentityFile ~/.ssh/my_key1
 User git
Host key2
 HostName code.aliyun.com
 IdentityFile ~/.ssh/my_key2
 User git

The URL would then be:
key1:aUSer/aRepo

Comment: Thanks,I found that I must change the config in that project, Then it worked.

GIt connection closed by remote host


Adapt layout to Android platform or API level

Question: For the application I am currently developing, I need to adapt the layout of the different activities to the user's Android API level.
Is there a way to do this?
Answer: If what you're trying to do is show a different layout depending on which API version is available on the device, you want to use configuration qualifiers. The specifics for alternative resources are also documented.
The most basic way to do it is to create a layout folder for each API level you want to use, formatted as follows:
res/layout/mylayout.xml       (Default)
res/layout-v4/mylayout.xml    (Android 1.6)
res/layout-v11/mylayout.xml   (Android 3.0)

and so on, where vN is the API level. The specific API levels can be found on this page.
Comment: @FredericYesidPeñaSánchez It will fall backwards to the next most-matching layout. So res/layout will always be matched last, making it required, but any other is optional. You don't need a folder for every platform unless you need something to be different on each.
Comment: The links are now dead. The second one is probably this: https://developer.android.com/guide/topics/resources/providing-resources.html#AlternativeResources
Comment: If I only had the three files described above, but I use a GB Device, which file will it use? (layout-v4 or layout)? Do I have to create a different folder for every platform? I plan to support from GB onwards
Answer: As Andrew Koester said you can use the different version folders, but I found this to be a lot of work because it would not fall back to the default layout. If you used layout-v14, it will work,but any api after 14 will also have this layout and you must use another layout-v? to override it again. It all depends on what your doing, but I found if your doing a lot of stuff programmatically this works wonders:
if(Build.VERSION.SDK_INT == Build.VERSION_CODES.ICE_CREAM_SANDWICH || Build.VERSION.SDK_INT == Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1){
            //ex. if ics is met then do this

        }else{
            //if api is not ics then do this
        }

Answer: If you already have drawable resources for each of the platform level, you can use the information provided in http://developer.android.com/guide/topics/resources/providing-resources.html#AlternativeResources
More specifically, look at the 'Platform Version (API Level)' row in Table 2.


Using the normal equations to calculate coefficients in multiple linear regression

Question: I am trying to understand how to get the coefficient of a multiple linear regression.
The formula is:
$b = (X'X)^{-1}(X')Y$
I try to calculate $b$ without package and with the lm package inside R.
Doing so, I got different results.
I want to know why. Did I made a mistake? Or does the lm package calculate differently because of the intercept?
> y <-  c(1,2,3,4,5)
> x1 <- c(1,2,3,4,5)
> x2 <- c(1,4,5,7,9)
> Y <- as.matrix(y)
> X <- as.matrix(cbind(x1,x2))
> beta = solve(t(X) %*% X) %*% (t(X) %*% Y) ; beta
            [,1]
x1  1.000000e+00
x2 -1.421085e-14
> model <- lm(y~x1+x2) ; model$coefficients
 (Intercept)           x1           x2
1.191616e-15 1.000000e+00 1.192934e-15

Update
As Alex and the other told me, it was a question of roundoff error. Therefore, I decided to take another data from the book "Essential Statistics for business and economics" by Anderson and all. In this case, the coefficients are the same in both lm function and in my own matrix.
> y <- c(9.3, 4.8, 8.9, 6.5, 4.2, 6.2, 7.4, 6, 7.6, 6.1)
> x0 <- c(1,1,1,1,1,1,1,1,1,1)
> x1 <-  c(100,50,100,100,50,80,75,65,90,90)
> x2 <- c(4,3,4,2,2,2,3,4,3,2)
> Y <- as.matrix(y)
> X <- as.matrix(cbind(x0,x1,x2))

> beta = solve(t(X) %*% X) %*% (t(X) %*% Y);beta
         [,1]
x0 -0.8687015
x1  0.0611346
x2  0.9234254
> model <- lm(y~+x1+x2) ; model$coefficients
(Intercept)          x1          x2
 -0.8687015   0.0611346   0.9234254

Comment: You forgot to include a vector of 1 representing the intercept. The rest looks correct.
Comment: I changed only the  'X' as you suggested, but then I got different coefficients again.
Comment: For general information about the effects of suppressing (ie, not fitting) the intercept in a regression model, it may be useful to read this excellent CV thread: [Removal of statistically significant intercept term boosts $R^2$ in linear model](http://stats.stackexchange.com/questions/26176/).
Answer: @MichaelMayer has it right. Try the following:
> y <-  c(1,2,3,4,5)
> x0 <- c(1,1,1,1,1)   # vector of ones representing the intercept
> x1 <- c(1,2,3,4,5)
> x2 <- c(1,4,5,7,9)
> Y <- as.matrix(y)
> X <- as.matrix(cbind(x0,x1,x2))
> beta = solve(t(X) %*% X) %*% (t(X) %*% Y) ;

Update: Even with the above changes you will still get slightly different results when you use lm due to roundoff error. If the estimated intercept and coefficient for x2 are nonzero, this is no longer visible.
x1 <- c(1,2,3,4,5)
x2 <- c(1,4,5,7,9)
y <-  x1 + x2 + rnorm(5,mean=0,sd=0.3);
Y <- as.matrix(y);
X <- as.matrix(cbind(1,x1,x2));
beta = solve(t(X) %*% X) %*% (t(X) %*% Y) ; beta
model <- lm(y~1+x1+x2) ; model$coefficients

Output is:
         [,1]
   -0.2948504
x1  0.8081534
x2  1.1741777
(Intercept)          x1          x2
 -0.2948504   0.8081534   1.1741777

For more info, see: https://en.wikipedia.org/wiki/Machine_epsilon
Comment: Those two answers are the same up to floating point roundoff error.  You should be comparing the coefficients *relative to their standard errors.*
Comment: When I do it I get different coefficient between 'lm' function and the manual way. lm gives 1.191616e-15 1.000000e+00 1.192934e-15  and the manual way gives 4.263256e-14 1.000000e+00 0.000000e+00. Where the first number is the intercept then x1 and x2.


Let $(X,d)$ be a complete metric space and suppose that $A$ and B are both dense and $G_δ$ subsets of X, show that $A\cap B\neq \emptyset$.

Question: A set is said to be $G_\delta$ set if it can be expressed as countable intersection of open sets.
Let us suppose on the contrary that $A\cap B=\emptyset$
Now, choose $x\in B$. Then there exists a seq $(x_n)$ in $A$ such that $x_n\to x$. (as $\bar{A}=X$)
Now, no $x_n\in A$ for all $n\in\Bbb{N}$.
But for any $\epsilon>0,\exists\ N\in\Bbb{N}$ such that $x_n\in B(x,\epsilon)\ \forall n\ge N$.
Since $B=\bigcap B_k$ where each $B_k$ is open. $x\in B_k\ \forall n$
So, for all $x\in B_k, \exists \epsilon_k>0$ such that $B(x,\epsilon_k)\subset B_k$.
Now, for each $\epsilon_k,\exists N_k\in\Bbb{N}$ such that $x_n\in B(x,\epsilon_k)\ \forall n\ge N_k$.
So, $x_n\in B_k\ \forall n\ge N_k$
From this I cannot proceed further, basically the maximum of $\{N_k|k\in\Bbb{N}\}$ exists (say $N$), then I can say $x_n\in B_n\ \forall n\ge N\implies x_n\in B\ \forall n\ge N$, which is a contradiction.
But this maximum will not exist in most of the cases. But I even have not used the dense nature of $B$ and $G_\delta$ property of $A$, and not the completeness of $X$.
Can anyone give me an idea about the solution? Thanks for assistance in advance.
Answer: It follows from:
$$\left (\bigcap _n A_n \right ) \bigcap \left (\bigcap _m B_m \right ) = \bigcap_{n,m} A_n \cap B_m $$
and the fact that the intersection of two dense open sets is also a dense open set. By Baire's Category Theorem the right hand side is more than just not empty: it's dense in $X$.


Does every Noetherian domain have finitely many height 1 prime ideals?

Question:
Let $A$ be a Noetherian domain. Is the set $\{P\subset A \mid P \mbox{ prime ideal, } \dim A_P=1\}$ always finite?

I can prove for $f \neq 0, f\in A$, the set $\{P\subset A \mid \dim A_P=1, f\in P\}$ is finite (by using the primary decomposition of $\sqrt{(f)}$). The above statement is just the case when $f=0$.
Comment: If you think about this geometrically, the primes of height 1 correspond to the subvarieties of codimension 1 of $\text{Spec}(A)$ (at least if A is nice). There are lots of examples of noetherian domains A such that $\text{Spec}(A)$ has an infinite number of codimension 1 subvarieties, for example $A = \mathbb{C}[x,y]$
Answer: No. Look at the ring $A=\mathbb{Z}$.
Comment: This example shows the value of looking at examples!
Comment: Yes, you are right!
Answer: If $\dim A=0$, then the answer is obviouly yes.
If $\dim A=1$, then the answer is yes if and only if $A$ is semi-local (i.e. has only finitely many maximal ideals). This is because height one prime ideals are then maximal.
If $\dim A>1$, then there are always infinitely many prime ideals of height 1. Actually, $A$ has a prime ideal $\mathfrak m$ of height $>1$. EDIT [After taking the quotient of $A$ by a minimal prime ideal appearing in a chain of prime ideals contained in $\mathfrak m$ of positive length, one can assume that $A$ is integral.]End of Edit. Let $a\in \mathfrak m$ be non-zero. Then the minimal prime ideals over $a$ have height $1$ by Krull's principal ideal theorem. Pick one of them $\mathfrak p_1$. Pick $a_1\in \mathfrak m\setminus \mathfrak p_1$ and let $\mathfrak p_2$ be a minimal prime ideal over $a_1$. Then $\mathfrak p_2\ne \mathfrak p_1$. Let $a_2\in \mathfrak m\setminus (\mathfrak p_1\cup \mathfrak p_2)$ and pick a minimal prime ideal $\mathfrak p_3$ over $a_2$ and so on. You get an infinite sequence of prime ideals of height $1$.
Comment: Dear @GeorgesElencwajg, for future reference this "unexpected" result is Theorem 144 in Kaplansky, *Commutative Rings*, 1974.
Comment: Thank you for your comprehensive answer!
Comment: A really unexpected result (for me), dear QiL! A little nitpick : a minimal prime ideal  over $a$ might have height $0$, not $1$, if $a$ is nilpotent. But of course that would only *strengthen* your argument that there exists $a_1\in \mathfrak m\setminus \mathfrak p_1$ ! Et meilleurs voeux pour 2012.
Comment: @GeorgesElencwajg, you are right as usual. Thanks ! I will edit the answer. Très bonne année 2012 !
Comment: Thanks for the reference, user26857.


Content changes history

Question: is it possible to view content changes history (author - date) ? We have many users modifying content in our website, and I'd like to know who made each change.
Answer: The Revisioning-module is exactly what you are looking for. It keeps revisions of every change and offers you the possibility to moderate the content.
I use it for a few project and I'm very happy with the results!
Comment: You can configure the module so users aren't able to delete content (permissions can do this too). The Revisioning module will keep a log with revisions (archived) and you can revert the current version of a node to any previous one. So yes, it can be archived!
Comment: Thanks! I read the documentation and saw information about authoring-moderating workflow. I just need to select a node and view changes history. Documentation does not mention that, do you know if that can be achieved? For some bureaucratic reasons, it's difficult for me to install the module just to try it out.
Comment: Thanks for your answer, in this case I don't want to prevent anybody from doing changes, just need to check who was the last user to modify a node and when it happened.
Comment: Yep that's right. And if you take the diff module BetaRide suggested, the circle is complete. You have a overview of what, who and when something has changed!
Comment: Did you successfully applied this module?
Comment: Sorry, I haven't had the chance yet, but will do so soon and let you guys know the results.
Comment: Alright, great :)
Answer: If you want to see the differences between revisions the diff module would be handy as well.

Content changes history


32-bit code runs on 64-bit linux machine

Question: My linux is 64 bit Red Hat 6.5. GCC is 4.4.7. I have a code originally running on 32 bit machine, which means, there are a lot of conversion from a pointer to a int. When I make, I get error: cast from 'void*' to 'int' loses precision. I know that is because in 64-bit OS pointer type is 8 bytes.
I don't want to fix all of this one by one because there are too many, so I add -m32 flag in the makefile CFLGAS, which make 32 bit code run on a compiler configured for 64-bit object by default.
Good thing is this compiling error is gone. However, compiler gives me this main.o: could not read symbols: File in wrong format. Seems like this is still some compatible issue between 32-bit and 64-bit. Could anyone tell me how to fix this?
This is part of my makefile.common used for gmake:
CFLAGS = -m32 -g -Wall -Wshadow $(INCPATH) $(DEFINES) $(HOST) -DCHANGED
LDFLAGS = -m32

CPP= gcc -E -m32
CC = g++
LD = g++
AS = as --32
.......
S_OFILES = switch.o

OFILES = $(C_OFILES) $(S_OFILES)

$(PROGRAM): $(OFILES)
    $(LD) $(OFILES) $(LDFLAGS) -o $(PROGRAM)

$(C_OFILES): %.o:
    $(CC) $(CFLAGS) -c $<

Comment: amongst other things, unless your source files are actually written using the C++ language (classes, iterators, STL calls, etc etc) then you should use gcc instead of g++.   Otherwise all the compiler calls should be g++.    Note: the make file is missing certain items, like the local header file dependencies for each source file.   the linker takes/processes parameters in the order given.. so $(LD) $(LDFLAGS) $(OFILES) -Llibrarypath -llibrrayshortnames -o $(PROGRAM)  the compile step should be something like: %.o:%.c then $(CC) $(CFLAGS) -c $< -o $@ -I$(INCPATH)
Comment: is there a rule for compiling the *.s files?
Comment: your code is already bad at the beginning. Leaving it as-is would make future maintenance a horrible pain. Pointers should not be stored as ints, and in cases needed should always be stored in `intptr_t` or `uintptr_t`
Answer: You did not enter your linker (g ++) that the assembly code are 32bit instructions.
try:
CPP= gcc -E -m32
CC = g++ -m32
LD = g++
AS = as --32

Comment: If you mean adding to LD = g++ -m elf_i386, then it gave me this "/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../lib64/crt1.o: could not read symbols: File in wrong format"
Comment: If you know your answer is wrong, delete it rather than editing to apologise for your mistake


Nunit3: how to save the test results while tests are running via Console Runner

Question: NUnit3 Console runner saves test results in xml at the end of the test run. But in my case I want to save the partial results on each test failure, so that in case console runner crashes or is stopped, I can still get partial results for completed tests.
Is there a way to do that?
Answer: Test Results are saved regardless of failures or successful test runs. The XML file is generated for every test run. You could also write every test result to a log file if the XML is not generated for a particular test run.


what does this mean "Property atomicity is not synonymous with an object's thread safety"?

Question: As stated in apples documents. I always thought that specifying a property as 'atomic' meant that it was thread safe, where only a single thread can set/access the property at a time. Whats the point of have atomic if its not thread safe and is alot slower. And if it is said to be not thread safe, what makes it considerably slower if you can still access it simultaneously?
Comment: Read this blog post [Atomic, properties, threading](http://www.friday.com/bbum/2008/01/13/objectivce-c-atomic-properties-threading-andor-custom-settergetter/) by bbum.
Answer: Atomic mean that the individual property will be thread safe, that is an entire correct value will be operated on. But you may have many atomic objects and there may be several that are inter-related and more than one thread operation on them.
Suppose there is a first and last name. Each is atomic. no name will be partially changed. But thread 1 is changing the first and last while the other thread is accessing them. The first name is atomically changed, the other task accesses both the first and last, but they are not consistent with each other at tis point in time. The other thread changes the last name and they are now consistent. But the second thread has a mashup of first and second names.
Initial: Bob, Ace
Thread 1 accesses the first name: Bob
Thread 2 changes the first name to Carol
Thread 1 accesses the last name: Ace
Thread 2 changes the last name: Ventura
Thread has the name as Bob, Ventura
Thread has the name as Ace, Ventura
Each name, first and last were atomic properties.
If they were not atomic the first name might end up as Bce if the two threads swapped execution just after the first letter was changed.

what does this mean "Property atomicity is not synonymous with an object’s thread safety"?


É obrigatório fazer rebuild?

Question: Sempre que eu apertava o botão Start pra executar meu programa e testar, ele executava corretamente. De um tempo pra cá, sempre que eu altero algo e executo o programa, ele não atualiza, é preciso eu clicar com o botão direito no projeto em em 'Rebuild' pra poder atualizar.
O que pode ser? Não lembro de ter mexido em nada diferente.
Comment: Verifique no menu `Build | Configuration Manager` se o `Active solution..` está `debug` e se todos projetos estão marcados como `build`
Comment: Isso mesmo @PabloVargas resolveu. Se quiser, pode escrever a resposta pra eu dar seus pontos. Abraço.
Answer: Verifique no menu Build | Configuration Manager se o Active solution.. está como debug e se todos projetos estão marcados como build

É obrigatório fazer rebuild?


String concatenation in bash 3.2.57 (macOS)

Question: My goal is to concatenate two strings.
Here's a copy-paste of my bash script:
str1="Hello"
str2="World"
str3=$str1$str2
echo $str3

The expected output is HelloWorld but I'm getting World instead.
It works fine when I run it in the terminal.
Here's the output when I run cat -v on my script:
str1="Hello"^M
str2="World"^M
str3=$str1$str2^M
echo $str3^M

Am I missing something?
Comment: Doesn't the definition of `str1` end with a windows line-end?
Answer: That's probably because you have a carriage return (\r) at the end of $str1. I'm getting the same output with the following:
#!/bin/bash
str1="Hello"$'\r'
str2="World"
str3=$str1$str2
echo $str3

It often happens when you create the script on a MSWin machine.
It prints Hello, but then \r moves the cursor back to the beginning of the line, and overwrites the Hello with World.
You can verify it by running it through a hex dump or cat -v.
Comment: @EtienneMartin: Yes, that's it. Remove the carriage returns.
Comment: Thanks, see the updated question with the output of `cat -v`.
Comment: You're the man @choroba, changing the line endings to unix in my editor fixed the issue.
Comment: Thank you sooo much! Been stuck on this for over an hour


Como pegar o numero do celular no ionic usando cordova ou phonegap

Question: Estou desenvolvendo um app e preciso pegar o número do celular.
Pesquisei bastante na internet e não consegui achar muita coisa.
Um dos exemplos que eu encontrei foi esse: cordova-plugin-sim mas não consegui fazer ele retornar o número. Segue um exemplo do meu código:

// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a  attribute in index.html)
// the 2nd parameter is an array of 'requires'
angular.module('starter', ['ionic', 'ngCordova'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    if(window.cordova && window.cordova.plugins.Keyboard) {
      // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);

      // Don't remove this line unless you know what you are doing. It stops the viewport
      // from snapping when text inputs are focused. Ionic handles this internally for
      // a much nicer keyboard experience.
      cordova.plugins.Keyboard.disableScroll(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})

.controller('mainController', ['$scope','$cordovaGeolocation','$interval',function ($scope,$cordovaGeolocation,$interval) {

  $scope.geolocation = function() {
    $interval(function(){
        var geoSettings = {frequency: 30000, timeout: 100000,enableHighAccuracy: false};
        var geo = $cordovaGeolocation.getCurrentPosition(geoSettings);
        geo.then(function (position) {
                $scope.latitude = position.coords.latitude;
                $scope.longitude = position.coords.longitude;
                console.log($scope.latitude)
                console.log($scope.longitude)
            },
            function error(err) {
                $scope.errors = err;
            }
        );
    },3000);
  }
}]);
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src  'self' 'unsafe-inline' *">

    <title></title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <ion-pane>
    <ion-header-bar class="bar-stable">

Ionic Blank Starter

    </ion-header-bar>
    <ion-content ng-controller="mainController">
    <button class="button button-full button-assertive" ng-click="geolocation()">
    Localização
    </button>
    <sapn>Latitude: {{latitude}} </sapn>

    <sapn>Longitude: {{longitude}} </sapn>

    <sapn>Info: {{infoPhone}} </sapn>

    </ion-content>
  </ion-pane>

Answer: Não sei que versão do SDK você está usando mas apartir do 23 tem que pedir permissão para leitura.
// Checar permissão
function hasReadPermission() {
  window.plugins.sim.hasReadPermission(successCallback, errorCallback);
}
// Pedir permissão
function requestReadPermission() {
  // no callbacks required as this opens a popup which returns async
  window.plugins.sim.requestReadPermission();
}
Comment: Adicionei as permissões. Funcionou no meu emulador genymotion, mas não no celular. Estou testando pelo Ionic View, não sei se pode ser isso. Para fazer um teste mais preciso, vou gerar um apk e testar novamente para ver se funciona.
Comment: No final acabei não conseguindo obter o número em um celular específico. Pesquisei um pouco e descobri que alguns celulares não guardam o número no cartão SIM. Por esse motivo não foi possível resgatá-lo. Mas acredito que sua resposta deva resolver o problema para versões mais recentes e como eu ainda não estava usando isso, marquei ela como correta! ;)
Answer: Segundo a própria documentação do plugin, o conteúdo que representa o número do telefone não é confiável, podendo retornar um string em branco (ou nulo):
"Notice: the content of phoneNumber is unreliable (see this, this, and this article). Sometimes phoneNumber is only an empty string."
Além disso, em alguns casos, pode até retornar um número antigo, que foi armazenado no SIM card previamente.
Pelo que li, o fato dessa informação estar presente no SIM card ou não (e de estar atualizada ou não), depedende até da operadora - algumas armazenam essa informação no SIM card, e outras não (fazendo tudo via rede).
Nos meus testes que fiz em um celular TIM, voltaram várias informações, mas não voltou o número do aparelho (sendo que pedi a permissão direitinho, como tem que ser feito a partir da versão 23). Quero em breve testar o mesmo código em outros celulares e com chips de outras operadoras.
Comment: Depois de alguns testes, vi que era isso msm. Na época ao testar em outros celulares funcionou. Ou seja, para alguns celulares ele retornava o número e para outros não. Então para não ter problemas, acabei mudando um pouco o aplicativo e fazendo com q o usuário informasse o número quando eu não conseguisse obtê-lo!
Comment: Acabei também fazendo a mesma coisa, pedindo pro usuário digitar o número, já que - pelo menos nos testes que consegui fazer - apenas SIM cards da Oi tinham essa informação (nos TIM e Vivo que testei, o número não era armazenado, provavelmente porque as operadoras pegam essa informação dinamicamente via rede de telefonia).
Comment: Além disso, decidi nem tentar verificar automaticamente antes de pedir pro usuário digitar, pois além dessa funcionalidade funcionar apenas pra uma minoria de usuários, seria outro plugin pra manter no app, além dele exigir uma permissão que pode parecer meio intrusiva pro usuário ("Permitir que o app ... faça e gerencie chamadas telefônicas").
Comment: Sim. Eu negaria essa permissão. Mas o projeto que estava fazendo era para uma empresa especifica e os usuários eram os funcionários q ja sabiam que teriam de fornecer essa informação e a sua localização para o app. No final eu fiquei muito satisfeito com o resultado. O desempenho e a praticidade em desenvolver com o IONIC e Cordova me surpreenderam bastante! :)


Desiging Websites for Retina style devices: What dimensions should you use when designing?

Question: The dimensions of the iPhone is 320x480
The dimensions of a Retina iPhone is 640x960
When designing a design for a retina device, do you set the size of your document to 320 x 480 or 640 x 960?
I would have thought you would have set the size to 320 x 480.
The reason for this is that although a retina device has more pixels, these are still being displayed on a 3" screen size. If you did set your size to 640 x 960, then when viewed on a retina display, all the text would be  small, as although there are more pixels, the screen isn't physically bigger.
Is that correct?
UPDATED: Do you also use 320 x 480 as a base size for CSS (see comments below)
Answer: Yes, that's correct. I'm an iOS developer, not a web designer, but in iOS devices you specify everything in points (which is one pixel on a non-retina device, and a 2x2 pixel block on a retina device) so everything is the same size. The extra pixels on the retina display simply make everything look better.
You can get away with smaller text on a retina screen since you have more detail, but accessibility wise that's not a good move, since lots of people can't then see your text without zooming, whatever kind of display they have.
Comment: Thanks for the reply. How does this effect a CSS style sheet? Do you specify measurements in pixels or points? And if its pixels, do you specify all measurements in relationship to 320x 480?
Comment: As I said, I'm not a web developer, so I can't help you with the CSS question. You may wish to re-tag the question, the current tags will only show the question to iPhone developers rather than web experts.


error: 'leftHeight' was not declared in this scope

Question: I have the following function to computer height of a node in a binary tree (and its descendants):
void computeHeight(Node *n) {
    // Implement computeHeight() here.
    if (n->left) {
        computeHeight(n->left);
        int leftHeight = n->left->height;
    } else {
        int leftHeight = -1;
    }
    if (n->right) {
        computeHeight(n->right);
        int rightHeight = n->right->height;
    } else {
        int rightHeight = -1;
    }
    n->height = std::max(leftHeight, rightHeight) + 1;
}

When I run the code I have error: 'leftHeight' was not declared in this scope, it happens at line n->height = std::max(leftHeight, rightHeight) + 1;. The error happens during compilation.
I don't understand why it happens because I defined leftHeight above.
Other code:
In main.cpp:
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <queue>
#include "main.h"

void computeHeight(Node *n) {}

int main() {
    Node *n = new Node();
    n->left = new Node();
    n->right = new Node();
    n->right->left = new Node();
    n->right->right = new Node();
    n->right->right->right = new Node();
    computeHeight(n);
    std::cout << std::endl << std::endl;
    delete n;
    n = nullptr;
    return 0;
}

In main.h:
class Node {
public:
  int height; // to be set by computeHeight()
  Node *left, *right;
  Node() { height = -1; left = right = nullptr; }
  ~Node() {
    delete left;
    left = nullptr;
    delete right;
    right = nullptr;
  }
};

Comment: You have to declare `leftHeight` and `rightHeight` outside of the `if` block, then initialize them inside.
Comment: What's defined in the braces stays in the braces.
Comment: Thank you, I got it
Comment: A couple quick notes about `Node`. It needs to observe [the Rule of Three](https://en.cppreference.com/w/cpp/language/rule_of_three). In this case I would most likely disable the copy constructor and assignment operator with `= delete` to prevent bugs from accidental copies. Recursive destruction means you have to watch out for the tree's depth. Too long and the program will recurse off the end of Automatic Storage.
Answer: Comments and Anoop answer your question. You need to read more about scopes in programming. Functions, loops, conditional statements create their own scopes. Variables created inside those scopes are local to those scopes.
In C++ you can create your own scope by just putting braces:
int main () {

   int y  = 1;
   {
      int x = 2;
      y = x; // no error
   }
   x = y; // error

}

A cleaner working version of your code is the following:
void computeHeight(Node *n) {
  int leftHeight = -1;
  int rightHeight = -1;
  // Implement computeHeight() here.
  if (n->left) {
    computeHeight(n->left);
    leftHeight = n->left->height;
  }

  if (n->right) {
    computeHeight(n->right);
    rightHeight = n->right->height;
  }
  n->height = std::max(leftHeight, rightHeight) + 1;
}

Answer: The problem is that you have defined leftHeight inside if else block and therefore they are not visible outside of those blocks. Similarly the variable rightHeight is also visible only inside the blocks in which it was defined.
To solve this just define leftHeight outside(of those blocks) once and then just assign value to them inside if and else blocks which would look like:
void computeHeight(Node *n) {
    int leftHeight = -1;//define and initialize leftHeight
    int rightHeight = -1;//define and initialize rightHeight
    // Implement computeHeight() here.
    if (n->left) {
        computeHeight(n->left);
        leftHeight = n->left->height;//note this is assignment
    }
    if (n->right) {
        computeHeight(n->right);
        rightHeight = n->right->height;//note this is assignment
    }
    n->height = std::max(leftHeight, rightHeight) + 1;//this works now
}

Comment: Thanks, I got it! The only remark is that it's better to initialize the height to -1 and remove `else` blocks
Comment: @pascalamin You're welcome .Yes you do it according to your needs. I was just pointing out how to solve the error you mentioned and didn't take a notice that you could do this without using `else`. Can you mark my answer(or any other) as correct if it helped you.

error: ‘leftHeight’ was not declared in this scope


How to find why a server is slow?

Question: Since I changed a vTiger website from one CentOS server to another, generating PDF files has become extremely long. Before, I had to wait a few seconds, but it can now last up to 5 minutes.
When I generate a PDF file, I can't do anything else. The Apache server doesn't answer anymore.
The uptime command shows 0.06, 0.06, 0.01 load avg. It doesn't seem to be a performance problem.
How could I find where the problem comes from?
Comment: It's usually either CPU or I/O. Since it doesn't seem to be CPU (unless you have a VPS and `uptime` is lying to you), I'd look at I/O. (Was that `uptime` output done right after you had waited for a minute or so? If not, redo it.)
Comment: It's not a VPS server, and CPU load is normal (uptime / top commands). I'll check I/O, thanks :)
Comment: You can use `iostat` and/or `iotop`. (The packages you need to install are probably `systat` and `iotop` depending on your distribution.)
Comment: I'll edit my question to tell which distribution I'm using.
Comment: My bet for the subsystem to check is domain name resolution AND/OR network timeouts.
Comment: There's no name resolution, as we use the server's local IP address. This problem only occurs on PDF file generation and can be reproduced very easily.
Comment: I/O stays at 0kb/s all the time, but peaks at 100kb/s for 1 second when I generate the PDF file. I still have to wait 5 minutes though... I'm waiting for the server to do nothing... Great!
Comment: What program generates the PDF files?
Comment: vTiger generates the PDF files, but I think it uses a PHP library.
Answer: The command htop show very information about the process, with it you navigate and sort (shift + P => sort by process ; shift + m => sort by memory used).

How to find why a server is slow?


How to Store images downloaded from the web in cache?

Question: I m parsing some images and showing it in list view... but whenever i scroll it up and down it is just disappearing ...Can it be solved by storing it in cache... And if it is possible please suggest me the way,.... thank you...
Answer: ya you can store it, you can use the concept of LazyList see


Evaluate expression with stack

Question: Hi I'm trying to write a program in c++ that evaluates expression using a stack but the result is a random number(an address memory maybe but it's not a pointer).
Here's the Stack template`
#ifndef STACK_H_
#define STACK_H_
template <class Item>
class Stack {
public:
    static const size_t Capacity=100;
    Stack(){used=0;};
    void push(const Item& insert){data[used]=insert; used++;};
    void pop(){used--;};
    Item top(){return data[used-1];};
private:
    Item data[Capacity];
    size_t used;
};

#endif /* STACK_H_ */
`

and this is the main with the 2 functions used
#include <iostream>
#include <cstring>
#include "Stack.h"
using namespace std;

double manage_stack(istream& insert);
void evaluate(Stack<double> numbers, Stack<char> operations);

int main(){
    double result;
    result=manage_stack(cin);
    cout<<result;
    return 0;
}

double manage_stack(istream& insert){
    double number;
    char symbol;
    Stack<double> numbers;
    Stack<char> symbols;
    while(insert.peek()!='\n'){
    if(isdigit(insert.peek())||insert.peek()=='.'){
        insert>>number;
        numbers.push(number);
    }
    else if(strchr("+-*/",insert.peek())!=NULL){
        insert>>symbol;
        symbols.push(symbol);
    }
    else if(insert.peek()==')')
        evaluate(numbers, symbols);
    else
        insert.ignore();
    }
    return numbers.top();
}

void evaluate(Stack<double> numbers, Stack<char> operations){
    double n1, n2;
    n2=numbers.top();
    numbers.pop();
    n1=numbers.top();
    numbers.pop();
    switch(operations.top()){
    case'+':numbers.push(n1+n2);
            break;
    case'-':numbers.push(n1-n2);
            break;
    case'*':numbers.push(n1*n2);
            break;
    case'/':numbers.push(n1/n2);
            break;
    }
    operations.pop();
}

Can anyone help me? Thanks in advance!
Comment: Consider what `used` refers to:  the element at the top of the stack, or the one just past the top.
Comment: Not seeing any signs of storage being allocated to `data`
Comment: `Item data[];` This is not legal C++ and certainly not an infinite array.
Comment: What did you see when you debugged your code?
Answer: Item data[]; is a non-standard extension and is being used improperly. See this answer to see how it's supposed to be used. You haven't allocated any memory for it, as such you are in undefined behavior. Your program can have any behavior, including running and returning random values. For your application, you should consider using std::stack instead of your Stack class. It looks like you can substitute it directly.
#include <stack>
template<class T>
using Stack = std::stack<T>;

I've tried to run your example and the result is still incorrect, but it doesn't return random values. It always returns the first operand twice.
I've answered why the result appears random. If you want to know why your parser still doesn't give the correct result, I suggest using a debugger. There is a quite a bit of work left to do. For example, there doesn't seem to be any iteration over the input. You will need some sort of loop or recursion.
Comment: @Xdroid You never call `evaluate` in `manage_stack` if the user doesn't use parentheses. You should call evaluate on your stacks as long as the numbers stack contains more than 1 number at the end of `manage_stack`. The original question has been answered. If you have *new* problems, please use a debugger and create new question for problems you cannot solve yourself **and for which you cannot find existing ressources**. Prolonged Q&A on stackoverflow comments is not the best way to learn to program.
Comment: I've corrected the capacity of the stack and added the loop but still not properly working. I've edited with the new code

Evaluate expression with stack


Live stream Text-To-Speech audio

Question: Goal: To play an audio file generated by TTS, at the same time as animating a characters mouth.
Background: While streaming to Twitch I have several illustrated characters. Viewers can make one of the characters talk by triggering a command that uses the characters name; ie "!norman This mead tastes funny". this sends the text to googles-TTS and creates an mp3. In the past I've run a script that automatically plays the file on my PC through VLC player. But now I want to add an animated mouth to each character that moves "in sync"(looking into Forced Alignment for better sync). I want to use a browser source in OBS to overlay the mouth on top of the character.
Node Modules: phonemify, express, ejs, cors, @twurple, @google-cloud/text-to-speech
Blocker:
Audio files require me to manually press the play button as soon as the new mp3 is created. and even then it will often just play the cached file instead of fetching the new version of output.mp3. I need the new file to play automatically as soon as it's created.
proposed solution: (but open to suggestions)
After much reading I suspect that the solution is to have an audio element(client side) that points at a m3u8 file. Then from the server take the newly created mp3 and add it to the m3u8 play list. My assumption is that this will make the client automatically play the audio. But I can't figure out how to do this part.
app.js
<code>const express = require('express');
const app = express();
const phonemify = require('phonemify');
const path = require("path");
const fs = require('fs');
const visemify = require(path.join(__dirname + `/public/visemify.js`));
const textToSpeech = require('@google-cloud/text-to-speech');
const util = require('util');
const client = new textToSpeech.TextToSpeechClient();
const cors = require('cors'); // SSE
const { StaticAuthProvider } = require('@twurple/auth');
const { ChatClient } = require('@twurple/chat');

let clients = []; // SSE
let phrases = []; // SSE
let streamClients = []; // Stream

app.set(`view engine`, `ejs`);
app.set(`views`, path.join(__dirname + `/views`));
app.use(express.static(path.join(__dirname, "public")));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cors()); // SSE

const clientId = '##############################';
const accessToken = '############################';
const authProvider2 = new StaticAuthProvider(clientId, accessToken, ['chat:read', 'chat:edit', 'channel:moderate']);
const chatClient = new ChatClient({ authProvider2, channels: ['bingo_bob'] });
chatClient.connect();
const commandListener = chatClient.onMessage(async (channel, user, message, msg) => {
    const REGnorman = /^!norman+./i;
    if(REGnorman.test(message)){
       const phrase = message.replace(REGnorman, "");
       loader(phrase);
       const load = loader(phrase);
        clients.forEach(client => client.response.write(`data: ${JSON.stringify(load.vis)}\n\n`))
    }
});

app.get('/events', eventsHandler); // SSE
app.get('/stream', streamHandler); // Stream
app.get('/', function (req, res) {
    if(req.query.phrase){
    const phrase = req.query.phrase;
    const load = loader(phrase);
    res.render(`index`, { load: load });
    }
    res.render(`index`, { load: [{ vis: 21 }] });
});
function loader(phrase){ // Phonemify & Visemify
    const load = {};
    const text1 = phonemify(phrase);
    const re = /\s+/;
    const text2 = text1.split(re).join('-');
    const re2 = /\d/g;
    const text3 = text2.replaceAll(re2, '-');
    const re3 = /\W+/;
    const text4 = text3.split(re3);
    load.pho = text4
    load.vis = visemify(load.pho);
    quickStart(phrase);
    return load;
}
async function quickStart(phrase) { // Google-TTS
    const text = phrase;
    const request = {
        input: { text: text },
        voice: { languageCode: "en-GB", name: "en-GB-Wavenet-D", ssmlGender: 'MALE' },
        audioConfig: { audioEncoding: 'MP3', speakingRate: "1.0", pitch: "-4.0", effectsProfileId: ["large-home-entertainment-class-device"] }
    };
    const [response] = await client.synthesizeSpeech(request);
    const writeFile = util.promisify(fs.writeFile);
    await writeFile(path.join(__dirname + `/public/audio/output.mp3`), response.audioContent, 'binary');
    console.log('Audio content written to file: output.mp3',phrase);
}
function eventsHandler(request, response, next) { // SSE
    const headers = {
      'Content-Type': 'text/event-stream',
      'Connection': 'keep-alive',
      'Cache-Control': 'no-cache'
    };
    response.writeHead(200, headers);
    const data = `data: ${JSON.stringify(phrases)}\n\n`;
    response.write(data);
    const clientId = Date.now();
    const newClient = {
      id: clientId,
      response
    };
    clients.push(newClient);
    request.on('close', () => {
      console.log(`${clientId} Connection closed`);
      clients = clients.filter(client => client.id !== clientId);
    });
  }
function streamHandler(req,res,next) { // Stream
    const headers = {
        'Content-Type':'audio/mp3',
        'accept-ranges': 'bytes',
        'Connection': 'keep-alive',
        'Cache-Control': 'no-cache'
    };
    res.writeHead(200, headers);
    const audioPath = path.join(__dirname + `/public/audio/output.mp3`);
    const readStream = fs.createReadStream(audioPath);
    // res.sendFile(path.join(__dirname + `/public/audio/output.mp3`));
    // res.send(readStream);
    // res.write(readStream);
    const clientId = Date.now();
    const newClient = {
        id: clientId,
        res
    };
    streamClients.push(newClient);
    req.on('close', () => {
        console.log(`${clientId} Connection closed`);
        streamClients = clients.filter(client => client.id !== clientId);
    });
}
app.listen(3000)
</code>
index.ejs
<code>  <!-- omitted animated mouth -->
<audio id="audioStream" controls src="/audio/norman.m3u8"></audio>
<script src="/script.js"></script>
</code>
script.js
<code>// omitted animated mouth functions
const evtSource = new EventSource(`http://localhost:3000/events`); // SSE
evtSource.onmessage = function(event) { // SSE
    const newElement = document.createElement("li");
    const eventList = document.getElementById("list");
    newElement.textContent = `message: ${event.data}`;
    eventList.appendChild(newElement);
    visemes = JSON.parse(event.data);
    runMouth(visemes);
  }
  const mp3Source = new EventSource(`http://localhost:3000/stream`); // Stream
  mp3Source.onmessage = function(event) { // Stream
    const audioStream = document.getElementById("audioStream");
    audioStream.src = `${event.data}`;
    console.log(event.data);
  }
</code>
Answer: this was my solution. I still have to refactor and make adjustments. But this is really what I was looking for.
<code>_sinks = new Map();
app.get('/stream', (req,res)=>{
  const { id, responseSink } = makeResponseSink();
  req.app.sinkId = id;
  res.set('Content-Type','audio/mpeg');
  responseSink.pipe(res);
});
function makeResponseSink() {
  const id = Math.random().toString(36).slice(2);
  const responseSink = PassThrough();
  _sinks.set(id, responseSink);
  return { id, responseSink };
};
function startStreaming(){
  const currentSong = readDir().filter(isMp3)[0].name;
  const bitRate = getBitRate(currentSong);
  const songReadable = fs.createReadStream(path.join(__dirname + `/public/audio/`,currentSong));
  const throttleTransformable = new Throttle(bitRate);
  throttleTransformable.on('data', (chunk) => {broadcastToEverySink(chunk);});
  throttleTransformable.on('end', () => playLoop());
  songReadable.pipe(throttleTransformable);
}
const readDir = () => fs.readdirSync(path.join(__dirname + `/public/audio/`), { withFileTypes: true });
const isMp3 = item => item.isFile && extname(item.name) === '.mp3';
function getBitRate(song) {
  try {
      const bitRate = ffprobeSync(path.join(__dirname + `/public/audio/`,song)).format.bit_rate;
      return parseInt(bitRate);
  }
  catch (err) {
      return 128000; // reasonable default
  }
};
function broadcastToEverySink(chunk) {
  for (const [, sink] of _sinks) {
      sink.write(chunk);
  }
}
function playLoop(){
  startStreaming();
}
startStreaming();
</code>

Live stream Text-To-Speech audio