Hierarchical clustering methods using a similarity metric for which d(x, x) != 0, and possibly assymmetric

Question: I want to cluster files based on an information distance, which is obtained by comparing the compressed length of two files separately and the concatenation of the two files, using a real-world compressor like zlib. (In words: given files $x$ and $y$, how easy can you express $x$ in terms of $y$?)
This "metric" does not satisfy $d(x,x) \ne0$, and it does not always satisfy $d(x,y)=d(y,x)$, depending on the compressor used. (But I'm willing to throw away one half of the distance matrix and pretend it's triangular.)
I'm told I cannot use hclust in R, because it always expects $d(x,x)=0$.
See my other question regarding my troubles with R (I'm only a beginner.)
What hierarchical clustering method would be suitable, preferably one that is implemented in R/Python? I only want to cluster up to 30 items right now, so scale is not an issue.
Answer: Hierarchical agglomerative clustering should never attempt to use $d(x,x)$ anyway. It's not a possible "merge" of two clusters.
Symmetry is a different thing. Have you considered "fixing" your similarity?
$$
d^\prime(x,y):=\begin{cases}
\min\{d(x,y), d(y,x)\} & \text{if }x\neq y \\
0 & \text{if }x = y
\end{cases}
$$
As long as your distance matrix fits into main memory this should be easy to do, and then you should be able to run many clustering algorithms (except k-means and Mclust).


Problemas IF-ELSE

Question: Tenho o seguinte código, para procurar uma determinada numeração e verificar se existe. Na variável STR é enviado um texto com números.
function verifica(str) {
if (str.match = '/\d\d\d\d\d\.\d\d\d\d\d')  {
    var old = str.match(/\d\d\d\d\d\.\d\d\d\d\d/);
    result = 1;
}

else if (str.match = '/\d\d\d\d\d\.\d\d\d')  {
    var old = str.match(/\d\d\d\d\d\.\d\d\d/);
    result = 2;

} }

Ele não está respeitando essas regras, ele só respeita o if, o else IF não respeita. O que pode estar errado ?
Comment: Provavelmente ele está respeitando, mas as regras não são as que dariam o resultado você espera. Poderia por um exemplo prático de como o problema se manifesta?
Answer: Têm dois problemas no seu código.
O primeiro problema é que quando quer comparar duas variáveis tem de usar o ==, ou ===. O que você usa é uma atribuição =, e isso não compara nada. Usando somente = vai fazer a variável à esquerda ficar com o valor que está na direita. Na verdade quando usa o = está a re-escrever a função .match(). Ou seja, o .match() passa a ter o valor que lhe atribuío e deixa de funcionar...
O segundo problema é a maneira como usar o .match(). Eu presumo que você quer usar o if no caso da str ter um certo conjunto de caracteres. Aí só precisa usar algo como str.match(/[1-2]/). Isto só por sí já retorna o que você precisa para usar no if. Por exemplo:
var str = '1233';
str.match(/[1-2]/);   // dá verdadeiro no if, mais exatamente ["1"]
str.match(/[1-2]/g);  // dá verdadeiro, mais exatamente ["1", "2"] pois usa o "g" no match que retorna não só o primeiro encontrado

Assim o que você deve usar é somente:
if (str.match(/\d\d\d\d\d\.\d\d\d\d\d/)) {

Uma vez que quer atribuír novo valor à variável old, e lembrando que uma atribuíção com = retorna um valor se não usar o var então o seu código poderia ser:
function verifica(str) {
    var old;
    if (old = str.match(/\d\d\d\d\d\.\d\d\d\d\d/)) {
        result = 1;
    } else if (old = str.match(/\d\d\d\d\d\.\d\d\d/)) {
        result = 2;
    }
    return result; // isto acrescentei eu, para a função retornar um valor
}

Comment: @brasofilo haha :) Isto de emigrar para a Suécia e participar aqui onde a maioria é brasileira em os seus _side effects_ :)
Comment: Pensei em "consertar" para `exactamente`, mas acho que você está abrasileirando seu português, *entonces* não mexi ;)
Comment: Perfeito a resposta @Sergio, obrigado!
Comment: @Sergio, aproveitando a pergunta, você sabe como posso detectar quebra de linha na string ? Exemplo: (/\d\d\d\d\d\.\d\d\d\d\d/) Depois do "." tem um ENTER..?
Comment: @user7605 `\n` pode ser usado para novas linhas.
Comment: @Sergio, no caso eu usaria assim: /\d\d\d\d\d\n.\d\d\d\d\d/ ?

Problemas IF-ELSE


Upload de arquivos em pastas separadas no banco de dados

Question: Bom dia, primeiramente desculpem a minha noobisse mas ainda estou aprendendo kkk
Estou criando um sistema (Estou utilizando HTML,CSS,Javascript,PHP e o Banco MYSQL), onde terão vários usuários cadastrados e cada usuário poderá fazer o upload de arquivos em pdf.
A minha dúvida é qual seria a melhor forma de fazer isso? Salvando eles no banco de dados MYSQL ou então salvando eles em uma pasta no servidor?
A minha ideia inicial era salvar em pasta no servidor, e que ao enviar o arquivo fosse criada uma pasta com o nome ou identificação do usuário e os arquivos ficassem salvos lá, pra ser mais fácil de identificar, porém, eu não tenho ideia de como fazer isso.
Alguém poderia me ajudar? me dar uma alguma dica?
Obrigado!!
Encontrei o seguinte código, é bem simples, teria um jeito melhor de fazer isso ou posso usar esse mesmo? segue abaixo o código:
session_start();

$message = '';
if (isset($_POST['uploadBtn']) && $_POST['uploadBtn'] == 'Upload')
{
  if (isset($_FILES['uploadedFile']) && $_FILES['uploadedFile']['error'] === UPLOAD_ERR_OK)
  {
    // get details of the uploaded file
    $fileTmpPath = $_FILES['uploadedFile']['tmp_name'];
    $fileName = $_FILES['uploadedFile']['name'];
    $fileSize = $_FILES['uploadedFile']['size'];
    $fileType = $_FILES['uploadedFile']['type'];
    $fileNameCmps = explode(".", $fileName);
    $fileExtension = strtolower(end($fileNameCmps));

    // sanitize file-name
    $newFileName = md5(date("m.d.y") . $fileName) . '.' . $fileExtension;

    // check if file has one of the following extensions
    $allowedfileExtensions = array('jpg', 'gif', 'png', 'zip', 'txt', 'xls', 'doc');

    if (in_array($fileExtension, $allowedfileExtensions))
    {
      // directory in which the uploaded file will be moved
      $uploadFileDir = './uploaded_files/';
      $dest_path = $uploadFileDir . $newFileName;

      if(move_uploaded_file($fileTmpPath, $dest_path))
      {
        $message ='File is successfully uploaded.';
      }
      else
      {
        $message = 'There was some error moving the file to upload directory. Please make sure the upload directory is writable by web server.';
      }
    }
    else
    {
      $message = 'Upload failed. Allowed file types: ' . implode(',', $allowedfileExtensions);
    }
  }
  else
  {
    $message = 'There is some error in the file upload. Please check the following error.
';
    $message .= 'Error:' . $_FILES['uploadedFile']['error'];
  }
}
$_SESSION['message'] = $message;
header("Location: index.php");

Answer: Olá, meu caro. Respondendo a sua dúvida:
A minha dúvida é qual seria a melhor forma de fazer isso? Salvando eles no banco de dados MYSQL ou então salvando eles em uma pasta no servidor?
No meu ver os dois. Eu criaria uma tabela no banco, com o nome documentos, com alguns colunas mais ou menos assim (doc_id, doc_nome, doc_tipo, user_id) e relacionaria com a tabela usuários pelo user_id. Sobre as pastas eu já cometi esse erro de criar as pasta para cada usuário, da muito trabalho fazer a manutenção disso, a solução foi renomear o arquivo no upload com um padrão, onde era fácil identificar de quem ele era.
A formação do nome era a data do dia + valor aleatório + user_id, ficaria mais ou menos assim 20200922-KASO78445589554-11.pdf, e salva tudo em uma pasta. Você pode melhorar essa nomenclatura usando funções de criptografia.
Comment: Entendi, então eu salvaria todos os arquivos pdf na mesma pasta com nome criptografado e salvaria no banco o nome dele, o nome criptografado, tipo, caminho... eu encontrei o seguinte um código aqui, vou postar ele ai em cima. acho que atende ao que vc disse
Comment: Exato, o código que você achou é bom eu só melhoraria essa linha `$newFileName = md5(date("m.d.y") . $fileName) . '.' . $fileExtension;`, para melhorar a formação do nome, da forma que está vai gerar um hash baseado no valor data e no nome original do arquivo. Esse hash é bem grande e não te indica de qual usuário vem.


Azure Point-to-Site VPN but no DNS

Question: I've got:

an Azure Virtual Network,
an Windows Server 2012 Domain Controller on that network,
a Point-to-Site VPN set up for that network all the way so that I can connect to it from my local machine and ping VM ip addresses
a registered DNS Server of the Domain Controller
a registered DNS Server for the Virtual Network (overriding the Azure Name Resolution, I guess)

But I cannot resolve DNS names of VMs in the network from a VPN-connected client.  Shouldn't this just work?  What might be wrong?
The advanced settings of my network adapters don't show this connection as something I can reorder to prioritize DNS.
The client is Windows 8.1, by the way.
Thanks!
Comment: I have a very similar setup. After connecting to the VPN I see a "PPP adapter" with a guid that matches the virtual network id. I cannot resolve the hostname of the Azure VMs, but the FQDN works (e.g. server1.domainname.com). This might be implied, but is the DNS server of your virtual network pointing to the Domain Controller? Also, have you verified your servers are registering themselves on the DNS server running on your Domain Controller?
Comment: What is the DNS setting of the client (i.e. your laptop that is connecting to the P2S VPN)?
Comment: The Azure VPN adapter doesn't give the traditional options for IP address and dns configuration.  But the main adapter is set to "obtain automatically".  Strangely, (and when connected) `ipconfig /all` doesn't show any adapter that I recognize as being the VPN!
Comment: FQDNs don't work either.  Yes, the DNS of the virtual network points to the dns/domain controller as registered in Azure.  The domain controller is the only VM - I'd like to join my laptop to that domain through the VPN which I think works fine but let me know otherwise.  I have a similar setup - same subscription, distinct Virtual Network, distinct domain, DC and member.  DNS works fine internally there and still fails over VPN (didn't have a need for that in that particular setup).
Answer: I had this same problem: downloaded and installed the Azure Point-to-Site VPN, then no DNS servers. It  turned out that I had not registered DNS servers in the network until after the package was installed, and DNS servers are not dynamic for Azure VPN clients. Once the network is completely set up, THEN download the VPN package and it should work just fine.

Azure Point-to-Site VPN but no DNS


column filling in R

Question: Hi i'm working on a logistic regression exercise, i have a database with n rows and 4 columns one of them is a theoretical probability, my aim is to compare these theoretical probabilities with a certain value that i defined if the probability is less my predicted probability is 0 else it's 1 so what i figured out that my data is a list of four lists, therefore i created another blank list that i would fill with the predicted probabilities however i seem to have a algorithmic problem in the loops that i tried to write can you help me ?
    library(readxl)
d<-read_excel("/home/ali/Downloads/roc.xlsx")
typeof(d)
#classification table

#le seuil que j'ai choisi de prendre
seuil <- 0.095
pred <- c()
for(i in d$Proba_theo){
  for(j in pred){
    if(i<seuil){
       j = 0
       pred[j]=j
    }
    else{
       j = 1
       pred[j]=j
  }
}
}
pred

Comment: Why are you looping over pred? pred is empty.
Comment: I don't know how to fill my pred column that's why i looped over pred
Comment: And changing the value of `j` in the middle of the `j`-loop is probably not a great idea!
Comment: All you need is `pred <- as.numeric(d$Proba_theo >= seuil)` - there is no need for a loop as R is a vectorised language
Answer: Try this
seuil <- 0.095
pred <- rep(NA,nrow(d))
for(i in 1:nrow(d)){
  if(d$Proba_theo[i]<seuil) {
    pred[i]=0
  } else {
    pred[i]=1
  }
}
pred

or alternatively in vectorised form
pred=ifelse(d$Proba_theo<seuil,0,1)

Answer: I think the problem might be that you are overwriting the value of the j while in the for loop.
what you could do to make your variable, you might use a mutate instead of a for cycle. I made you a small example:
library(dplyr)
df = data.frame(testVar = rnorm(100))
df %>% mutate(ifelse(testVar > 0, 1, 0))

Hence in your case it would be something like:
d <- d %>% mutate(ifelse(Proba_theo >  0.095, 1, 0))

column filling in R


Image of set of measure zero has measure zero if the function is absolutely continuous

Question: I have been trying to solve this problem from Bass.

Let $f$ be a real valued absolutely continuous function defined on $[0,1].$ Denote $f(A)=\{f(x): x \in A\}$ for $A \subset [0,1].$ Prove that if $A$ has Lebesgue-measure zero, then so does $f(A)$.

My attempt:
By outer regularity, given an $\varepsilon>0$, I have a collection of disjoint open intervals $\{(a_i,b_i)\}_{i \geq 1}$ such that $A \subset \bigcup_i (a_i,b_i)$ and $\sum_i (b_i-a_i) < \varepsilon$.
Can we link $f(A)$ and $\bigcup_i f((a_i,b_i))$ ? We know that $f(a,b)$ is an interval but what about it's length ? Is it related to $f(b)-f(a)?$
Comment: $\bf{Hint:}$ as $E$ has measure zero you can cover it by intervals which have arbitrarily small size and use absolute continuity to show $f$ of this unions is arbitrarily small.
Answer: Readers of   this problem might want to know some context for it.
A function that maps sets of measure zero to sets of measure zero is said to satisfy Lusin's condition (N).  The condition plays a key role in many investigations in real analysis.  Absolutely continuous functions (as you have seen here) satisfy the condition.  In fact there is a partial converse: a necessary and sufficient condition that a continuous function of bounded variation be also absolutely continuous is that it satisfy Lusin's condition (N).
An accessible introduction to the idea along with techniques for handling questions such as the one posed here is given in Saks, Theory of the Integral, pp. 224-228.
Saks remarks that Lusin first introduced the notion in a 1915 study of trigonometric series.  He points out for continuous functions this condition is necessary and sufficient in order that the function map measurable sets to measurable sets (a result he attributes to Rademacher and Hahn).
Answer: This answer complements the answer by Pelto making  it rigorous. In that answer it may  not be true that $\lambda (f((a_i,b_i)) \leq |f(b_i)-f(a_i)|$. To get over this problem note that $\lambda (f((a_i,b_i)) \leq \lambda (f([a_i,b_i]) \leq \lambda [f(x_i),f(y_i)])=|f(y_i)-f (x_i)|$ where $x_i$ and $y_i$ are the points in $[a_i,b_i]$ at which $f$ attains its minimum and maximum values. If $I_j$ is the interval $(x_j,y_j)$ if $x_j<y_j$ and   $(y_j,x_j)$ if $y_j<x_j$ then  the intervals $I_j,1\leq j \leq  n$ form a finite disjoint collection of intervals with total length $<\delta$ and hence $\lambda (\cup _i f((a_i,b_i))\leq \sum_i |f(y_i)-f (x_i)|\leq  \epsilon$.
Answer: Suppose $f:[0,1] \to \mathbb{R}$ is absolutely continuous and $A \subset [0,1]$ is a set of measure zero. Let $\varepsilon>0$ be given. Since $f$ is absolutely continuous there exists a positive number $\delta$ so that
\begin{equation}
\overset{N}{\underset{i=1}\sum}|f(b_i)-f(a_i)| <\varepsilon
\, \, \, \text{whenever} \, \, \overset{N}{\underset{i=1}\sum}(b_i-a_i)<\delta,
\end{equation}
and the intervals $(a_i, b_i)$, $i=1, 2, \ldots, N$ are disjoint. Now fix a compact subset $K$ of $A$. Since $\lambda$ is outer regular there exists an open set $U$ such that $\lambda(U) \leq \lambda(K) + \delta/2$. Since $U$ is open it can be expressed as the countable union of disjoint intervals. Thus a finite subcollection of these intervals $\{(a_i, b_i)\}_{i=1}^N$ covers $K$,
\begin{equation}
\overset{N}{\underset{i=1}\bigcup}(a_i, b_i) \supset K .
\end{equation}
Combining the above, notice that we have
\begin{equation}
\lambda \Big(\overset{N}{\underset{i=1}\bigcup}(a_i, b_i) \Big) = \overset{N}{\underset{i=1}\sum}(b_i-a_i)<\delta .
\end{equation}
Thus
\begin{equation}
\lambda \Big(f\Big( \overset{N}{\underset{i=1}\bigcup}(a_i, b_i) \Big) \Big) \leq \overset{N}{\underset{i=1}\sum}|f(b_i)-f(a_i)|<\varepsilon ,
\end{equation}
and so by monotonicity of $\lambda$ we have that $\lambda(f(K))< \varepsilon$. Observe that any compact set $K'$ contained in $f(A)$ will be the image under $f$ of some compact set $K \subset A$, $\, K'=f(K)$. Therefore we combine to conclude that $\lambda(f(A))=0$.
Comment: I think your argument works if $f$ is monotone, but it does not cover the general case (last inequality sign).


Change worksheet tab color if range of cells contains text

Question: I have tried code that I've found here on stackoverflow, and elsewhere but they aren't working as I think they can. I'll list them below. I'm almost certain this is an easy question.
What I'm trying to do: If in any of the cells in the range A2:A100 there is any text or number whatsoever, then make the worksheet tab red. And I will need to do this on over 20 tabs. This must execute upon opening the workbook, and thus not require manually changing a cell or recalculating.
The problems I've had with other code: As far as I can tell they require editing a cell, and then quickly hitting enter again. I tried SHIFT + F9 to recalculate, but this had no effect, as I think this is only for formulas. Code 1 seems to work albeit with having to manually re-enter text, but no matter what color value, I always get a black tab color.
Code I've tried:
Code 1:
Private Sub Worksheet_Change(ByVal Target As Range)
    MyVal = Range("A2:A27").Text

    With ActiveSheet.Tab
        Select Case MyVal
            Case ""
                .Color = xlColorIndexNone
            Case Else
                .ColorIndex = 6
        End Select
    End With
End Sub

Code 2: This is from a stackoverflow question, although I modified the code slightly to fit my needs. Specifically, if in the set range there are no values to leave the tab color alone, and otherwise to change it to color value 6. But I'm sure I've done something wrong, I'm unfamiliar with VBA coding.
Private Sub Worksheet_Calculate()
    If Range("A2:A100").Text = "" Then
        ActiveWorkbook.ActiveSheet.Tab.Color = xlColorIndexNone
    Else
        ActiveWorkbook.ActiveSheet.Tab.Color = 6
    End If
End Sub

Thanks for your help!
I posted this on superuser first, but perhaps stackoverflow is more appropriate since it is explicitly programming-related.
Comment: The answer largely depends on when you want the code to run. Both of the examples respond to a specific event, which is why you need to change a cell or recalculate.  Do you need it to run on both changes and recalculations?  When you initially open the Workbook?  With some other event?
Comment: I need it to execute upon initially opening the workbook. Having it execute upon changes or recalculations is not an option. I've edited the OP to make this clear.
Answer: Maybe test the len of the trimmed joined string of cells:
Private Sub Worksheet_Calculate()
    If Len(Trim(Join(Application.Transpose(Range("A2:A100"))))) = 0 Then
        ActiveWorkbook.ActiveSheet.Tab.Color = xlColorIndexNone
    Else
        ActiveWorkbook.ActiveSheet.Tab.Color = 6
    End If
End Sub

This code will fire off every time the sheet calculates though as it is event code, I am not sure if that is what you want? If not then post back and we can drop it into a normal sub for you and make it poll all the sheets to test.
Comment: Calculate only fires if the change the worksheet triggers a formula recalculation.  You can fill every cell row A, but as long as a formula isn't  entered and none of the cells are referenced in a formula elsewhere, this code won't run.
Comment: I based it on the code the OP posted, This sort of thing I wouldn't put at an event level personally but it's up to the OP.
Answer: Worksheet_Change function will get called everytime there's change in the target range. You just need to place the code under Worksheet. If you have placed the code in the module or Thisworkbook then it wont work.
Paste the below in Sheet1 of your workbook and check if it works. Of Course you will need to do modification to the below code as I have not written complete code.
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim WatchRange As Range
    Dim IntersectRange As Range
    Set WatchRange = Range("A1:A20")
    Set IntersectRange = Intersect(Target, WatchRange)
    If IntersectRange Is Nothing Then
        ''Here undo tab color
    Else
        ActiveSheet.Tab.ColorIndex = 6
    End If

End Sub

Comment: OP doesn't want it to be reliant on a change: "The problems I've had with other code: As far as I can tell they require editing a cell, and then quickly hitting enter again."
Answer: Only two things will be able to switch the condition in this statement:
If Range("A2:A100").Text = "" Then

You've already identified both of them, changing the contents of the one of the cells in that range on a worksheet, or a formula in one of those cells recalculating to or from a value of "".  As far as event triggers go, if the formula result changes, both the WorkSheet_Calculate and Worksheet_Change events will fire. Of the two, Worksheet_Change is the one to respond to, because WorkSheet_Calculate will only fire if any of the cells in A2:A100 contain a formula. Not if they only contain values - your "Code 2" isn't wrong, the event was just never firing.
The simple solution is to set your tab colors when you open the workbook. That way it doesn't matter if you have to activate a cell in that range and change it - that's only way the value you're testing against is going to change.
I'd do something like this (code in ThisWorkbook):
Option Explicit

Private Sub Workbook_Open()

    Dim sheet As Worksheet
    For Each sheet In Me.Worksheets
        SetTabColor sheet
    Next sheet

End Sub

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)

    If Not Intersect(Target, Sh.Range("A2:A100")) Is Nothing Then
        SetTabColor Sh
    End If

End Sub

Private Sub SetTabColor(sheet As Worksheet)
    If sheet.Range("A2:A100").Text = vbNullString Then
        sheet.Tab.Color = xlColorIndexNone
    Else
        sheet.Tab.Color = 6
    End If
End Sub

EDIT: To test for the presence of specific text, you can do the same thing but need to have the test check every cell in the range you're monitoring.
Private Sub SetTabColor(sheet As Worksheet)
    Dim test As Range

    For Each test In sheet.Range("A2:A100")
        sheet.Tab.Color = xlColorIndexNone
        If test.Text = "whatever" Then
            sheet.Tab.Color = vbRed
            Exit For
        End If
    Next test
End Sub

Comment: As far as I can tell, your code works! I've only briefly had time to try it on one of my workbooks, but I have no reason to believe it won't work on the others. I'll report back to confirm. One thing, the color code `sheet.Tab.Color = 6` didn't work, all values there returned black. Replacing "6" with "vbRed" did work, however. **For those wondering exactly how to add this code:** Open the workbook. Press ALT - F11 to open the VBA editor. Near the top left you'll see the Project window. Scroll down till you see "ThisWorkbook", double-click. Enter the code. Save the workbook, and reopen.
Comment: @rebluriast - Yeah, I had no idea what color constant 6 was, so I just went with the value in the code from the question. Apparently 6 isn't black either - vbBlack is 0. Glad it's what you were after.
Comment: Just a quick follow-up question. I'm now trying get the tabs to turn red only if a certain string of text is in the range. I thought replacing "vbNullString" with the string of text, and then replacing "xlColorIndexNone" with vbRed would do the trick (of course replacing the 'Else' 'sheet.Tab.Color = 6' to 'vbNullString' as well). But it's not working, and I'm not sure how to fix it.
Comment: @rebluriast - If you're trying to match text in *any* cell in the range, you'll need to loop over the range and check them individually.  `If sheet.Range("A2:A100").Text = vbNullString` will only work if the entire range is empty.
Comment: Sorry, I'm not sure I follow. The behavior I'm trying to achieve is as follows. If the text string, and only this text string = "lorem", color the tab red. Otherwise leave it.
Comment: apologize for the delay! Unfortunately this code isn't working. I don't get any change in the tab color by applying the code. I've tried applying it on spreadsheets with and without filtering, on individual worksheets, but to no avail. Just to be clear, I put the code from your edit in the 'ThisWorkbook' code by itself, not with the code from your original post.


compare Two variables of enum in java

Question: public enum Direction {
  UP,
  RIGHT,
  DOWN,
  LEFT,
}

i have two enum variables (a and b), in one case i have to check, if b is the next of a
for example
if a=UP and b=RIGHT.
and also if a=left and b=UP.
mabe something like this:
if(Direction.valueOf(a+1)==Direction.valueOf(b))

but when a=LEFT it would be out of bounds like an array right ?
Comment: yes, you'd need to manually wrap around
Comment: honestly I would not bother `valueOf()`. Just check their `ordinal()` with `%`
Answer: Try this.
public enum Direction {
    UP,
    RIGHT,
    DOWN,
    LEFT;

    private static final Direction[] VALUES = values();

    public Direction next() {
        return VALUES[(ordinal() + 1) % VALUES.length];
    }
  }

public static void main(String[] args) {
    Direction a = Direction.LEFT;
    Direction b = Direction.UP;
    System.out.println(a.next() == b);
}

output:
true

Answer: if (b == Direction.values()[(a.ordinal() + 1) % Direction.values().length])

Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

compare Two variables of enum in java


Penalty runs for hitting on to the helmet of the wicket keeper which he is wearing

Question: As the answers here acknowledge that if the ball hits the helmet behind the wicket keeper then 5 runs are given to the batting side as obstructing the field.
My question is will the same apply if the ball hits the helmet of the wicket keeper which he is wearing and not behind him.
Will runs be given for this also ?
If yes,
Is there any past reference for this ?
If this applies for helmet then why not for the pads worn by the fielder at silly point.
Answer: No, penalty runs will not be given if the ball hits the helmet of the wicket-keeper when wearing it.
Penalty runs are given for obstructing the ball by the fielding team without the help of any player. If the WK is not worn the helmet means the ball will surely get hit by his head,so,wearing and not wearing the helmet, both are same, but the player will get injured.
Placing helmets behind the WK is the risk taken by the fielding team. So, nowadays, Helmets are not placed behind WK in limited overs cricket since 5 runs can change the result of the match.
Additional comment: if penalty runs were given when the ball touches a worn helmet, no one would wear helmets at the end of a crucial match.
Comment: @hims056, I think there is no law for this, if any penalty will be given for this means there should be a law on that.
Comment: Nice explanation. But is there any law and it's reference for that?
Answer: According to the ICC rules penalty runs are only given in cricket if the ball hits the helmet which is not worn by any fielder on the field. This is clarified in this wiki article.

The ball strikes a fielder's helmet when it is on the field but not being worn.

So any equipment worn by a fielder becomes part of his clothing and hence cannot be penalized.
Answer: If the WK is wearing his helmut and the ball hits it then there are NO Penalty Points. If the ball hits ANY article of clothing on the field INCLUDING the helmut which is not worn by the fielding side, then Penalty Points are given to the batting side. Normally 5 runs are given
Comment: This didn't seem to add anything to the answers already given. Also, could you explain the situations in which the penalty would be other than 5 runs?


Running Xcode 4.01 and 4.2 on the same computer?

Question: I am currently running Xcode 4.02 to develop my production products for release to the AppStore. My normal dev system is an i7 iMac and I also use a MBP when away from my office. I want to start testing development for iOS 5 so have downloaded the Xcode 4.2 package and iOS 5 beta and first plan to install it on a my only other Mac, an original MBA that I know from experience of developing on it in a pinch (when my traveling MPB was down and had the MBA sent to me) will be pretty (actually, really) slow.
Preferring of course to have a fast dev system, my question is, can I safely install the Xcode 4.2 developer preview and the iOS 5 beta on my iMac and/or MBP without screwing up my production development environment?  I see from the 4.2 release notes that "You can have multiple versions of the Xcode toolset installed.", I assume by installing Xcode 4.2 in a different -Xcode- directory. What make me wary is that the release notes also state that "NOTE: Only one version of the System Tools ... can be installed on a computer at a time. The last installed set of these components replaces any previously installed set."
So is it a good or bad idea to have both Xcode installs on the same computer at the same time or should I stick with installing 4.2 on a different machine and if I really need to have a more powerful system, consider getting a newer box?
Answer: You are right, you just need to install in a different directory. Developer is the default, you just need to change it.
As for the System Tools, as far as I know they don't interfere in you ability to release apps to the AppStore. Still, you can uncheck them when installing and Xcode 4.2 will use Xcode 4.0 System Tools without problem (that's what I have right now).


sort priority queue of objects by specified value

Question: i want to add objects to priority queue by using specified value
like this
PriorityQueue<Edge> queue=new PriorityQueue<Edge>();

this is class Edge which i want to sort in priority queue by its weight
public class Edge {
private int start,end;
private double weight;

public Edge(int s, int e,Double w){
    start=s;
    end=e;
    weight=w;
}

public int getStart(){
    return start;
}

public int getEnd(){
    return end;
}

public double getWeight(){
    return weight;
}

Comment: possible duplicate of [Java: How do I use a PriorityQueue?](http://stackoverflow.com/questions/683041/java-how-do-i-use-a-priorityqueue)
Comment: i am not familiar with Comparator what that mean ?   PriorityQueue queue =
            new PriorityQueue(10, comparator);
Comment: I posted it as an answer.
Answer: You should create your priority Queue a little bit different by specifying how its elements should be compared. That is done by passing an anonymous Comparator for the Edge class:
PriorityQueue<Edge> queue=new PriorityQueue<Edge>(10, new Comparator<Edge>() {
    public int compare(Edge edge1, Edge edge2) {
        if (edge1.getWeight() < edge2.getWeight()) return -1;
        if (edge1.getWeight() > edge2.getWeight()) return 1;
        return 0;
    }
});

Maybe you will have to switch the returns of -1 and 1 depending on your sorting order.
Comment: the 10 refers to the initial capacity of the priority queue, if you already know how many edges you are going to insert, choose that number instead of 10 - otherwise 10 will be fine. it will not take up much space if you put in less than 10 and it will grow if you put more in.
Comment: this answer saved me thanks a lot, But i have only one question what 10 means ?
Answer: You can create a priority queue and a Checker (custom) class that compare the edges. like this :
  class Checker implements Comparator<Edge>
  {
      public int compare(Edge ob1, Edge ob2)
      {
          if (ob1.getWeight() > ob2.getWeight()) return 1;
          else                                   return -1;
      }
  }

 //Declared priority queue
  PriorityQueue<Edge> queue=new PriorityQueue<Edge>(5, new Checker());

Answer: Java 8 :
PriorityQueue<Edge> queue = new PriorityQueue<>((edge1, edge2) -> {
            if (edge1.getWeight() < edge2.getWeight()) {
                return -1;
            }
            if (edge1.getWeight() > edge2.getWeight()) {
                return 1;
            }
            return 0;
});

Answer: Solution 1:
Min Heap:
a -> a.getWeight()
Max Heap:
a -> -a.getWeight()
Example:
PriorityQueue<Edge> PriorityQueue = new PriorityQueue<>(Comparator.comparingDouble(a -> a.getWeight()));
PriorityQueue = new PriorityQueue<>(Comparator.comparingDouble(a -> -a.getWeight()));

Solution 2:
Min Heap:
Edge::getWeight
Max Heap:
(Edge::getWeight).reversed()
Example:
PriorityQueue<Edge> PriorityQueue = new PriorityQueue<>(Comparator.comparingDouble(Edge::getWeight));
PriorityQueue = new PriorityQueue<>(Comparator.comparingDouble(Edge::getWeight).reversed());

Solution 3:
Min Heap:
(a, b) -> a.getStart() - b.getStart()
(a, b) -> (int) (a.getWeight() - b.getWeight())
Max Heap:
(a, b) -> b.getStart() - a.getStart()
(a, b) -> (int) (b.getWeight() - a.getWeight())
Example:
PriorityQueue<Edge> PriorityQueue = new PriorityQueue<>((a, b) -> a.getStart() - b.getStart());
PriorityQueue = new PriorityQueue<>((a, b) -> (int) (a.getWeight() - b.getWeight()));
PriorityQueue = new PriorityQueue<>((a, b) -> b.getStart() - a.getStart());
PriorityQueue = new PriorityQueue<>((a, b) -> (int) (b.getWeight() - a.getWeight()));


How to handle localized connectivity issues between web services

Question: Our web application uses various web services, most of which are not managed by us, but by an external service provider (e.g. Auth0 is one of those services).
Recently, our application failed because a critical service was not reachable. Various "connection attempt failed" messages showed up in our error logs along with the problematic IP address, so we were able to tell which service it was. During analysis, we discovered that the service was reachable both from our office as well as from various other places we tested. So the service itself was not the problem. This was also confirmed by the service provider.
I suspect a networking issue to be the root cause, but I'm not sure.
What is the recommended approach to handle such situations? How can we avoid it in the future?
By the way, our application runs on Microsoft Azure as Azure Web Site, but this is probably not important for this question.
Comment: At least have the decency of telling me why you're down-voting.
Answer: The best way to handle this is to contact support for the external service provider who is managing the problem sites.
Comment: The service IS functional, I can verify that from my local network. And that's what the customer support told me as well, as I mentioned in the question.


How to add custom css file to subtheme of omega kickstart theme?

Question: I have created a subtheme of "omega kickstart theme" and I want to add some custom css files to it. I searched and got some solution(which didn't worked for me), the solution is as follows:

create your custom css file and place it in css folder of your subtheme.
edit your subtheme.info file(edit under optional css code of info file) as follows:
css[yourthemename.css][name] = 'Your custom products styles'
css[yourthemename.css][description] = 'This file holds all the product page CSS of your theme.'
css[yourthemename.css][options][weight] = '12'

The other Solutions were as follows:

Specify your custom css path file in info file as
stylesheets[all][] = mycustomcss.css

Make use of "drupal_add_css" function in template.php as follows
function MYTHEMENAME_preprocess_node(&$variables) {
  if ($variables['view_mode'] == 'full') {
    $path = drupal_get_path('theme', 'MYTHEMENAME');
    drupal_add_css($path . 'MY-THEME-PATH');//PUT UR CSS FILE PATH
  }
}

I tried this function twice with two different paths. First I gave path as '/css/mycustomcss.css' and second time I gave path as '/MYTHEMENAME/css/mycustom.css'.
UNFORTUNATELY NONE of these solutions worked for me. Am I missing something or is it something else?...please help.
Comment: Guys I got the answer.
I was missing one line in code.
here is what you have to do.
in your .info file under optional css code write the following code.

css[yourcustomcss.css][name] = Your custom products styles css[yourcustomcss.css][description] = This file holds all the product page CSS of your theme.
css[yourcustomcss.css][options][weight] = 12
settings[alpha_css][yourcustomcss.css] = 'yourcustomcss.css'

Now go and enable your 'yourcustomcss.css' in Appearance/yourthemename/settings/toggle-styles
Comment: @JayendraKainthola Last time I checked newcomers must wait 8 hours before answering their own questions. See [here](http://meta.stackexchange.com/q/209278/225745). So your comment will not be applicable for 4 hours more.
Answer: I was missing one line in code. here is what you have to do. in your .info file under optional css code write the following code.
css[yourcustomcss.css][name] = Your custom products styles
css[yourcustomcss.css][description] = This file holds all the product page CSS of your theme.
css[yourcustomcss.css][options][weight] = 12
settings[alpha_css][yourcustomcss.css] = 'yourcustomcss.css'

Now go and enable your 'yourcustomcss.css' in Appearance/yourthemename/settings/toggle-styles
Answer: To create a subtheme, follow all 10 steps mention in this article.
To add your own custom CSS files, add them in ./MYTHEMENAME/MYTHEMENAME.info if you need minimal configuration.
Otherwise, add your own MYTHEMENAME_preprocess_HOOK functions to ./MYTHEMENAME/template.php in your subtheme folder.
After you add your changes, add the following lines of code in ./MYTHEMENAME/template.php at the very bottom :
drupal_flush_all_caches();
drupal_theme_rebuild();

This should flush the cash and add your changes. Then, comment out these two lines and refresh your browsers. Your changes should now be included.
The easiest way to test whether your MYTHEMENAME_preprocess_HOOK function is actually being used, is to add nothing but one of the following options to that function (and remove it when it generates output) :
echo 'MYTHEMENAME_preprocess_HOOK used'; // native PHP
var_dump('MYTHEMENAME_preprocess_HOOK used'); // native PHP
debug('MYTHEMENAME_preprocess_HOOK used'); // Drupal specific

If you don't want to clutter ./MYTHEMENAME/template.php, you can also put your hooks in seperate files in the preprocess folder as described in the readme file.
TEMPLATE_preprocess_html() --> ./MYTHEMENAME/preprocess/preprocess-html.inc
TEMPLATE_preprocess_page() --> ./MYTHEMENAME/preprocess/preprocess-page.inc
TEMPLATE_preprocess_node() --> ./MYTHEMENAME/preprocess/preprocess-node.inc

Unfortunately, the documentation forgets to mention what would be suitable values for TEMPLATE. As you can see in the code in the process folder of inherited themes, TEMPLATE should be identical to MYTHEMENAME_alpha. It took me hours to figure that out.
For example, your page hook would be something like this if it was put in the file ./MYTHEMENAME/preprocess/preprocess-page.inc :
function MYTHEMENAME_alpha_process_page(&$vars) {
  //debug($vars);
}


How to set Tap target for Bottom navigation

Question: I use keepsafe tap target for creating tap targets. For every view, it works fine but when I use it for bottom navigation it gives me null pointer exception error.
I have read its document. In that document has been written that I should use TapTarget.forBounds but it has Null pointer exception error.
How should I use it?
This is my code:
TapTarget t = TapTarget.forBounds(bottomNavigationViewEx.getBottomNavigationItemView(R.id.ic_shoppingCenter).getClipBounds(),"Title","Description")
                    .cancelable(false)
                    .drawShadow(true)
                    .dimColor(android.R.color.tab_indicator_text)
                    .outerCircleColor(android.R.color.holo_blue_dark)
                    .targetCircleColor(android.R.color.holo_green_dark)
                    .transparentTarget(true)
                    .targetRadius(32)
                    .outerCircleAlpha(0.96f)
                    .titleTextSize(15)
                    .descriptionTextSize(12)
                    .descriptionTextColor(android.R.color.white)
                    .textColor(android.R.color.holo_blue_bright)
                    .titleTextColor(android.R.color.white)
                    .tintTarget(false);

Comment: on which line .whats in the logs?
Comment: @kelvin in first line
Answer: TapTarget.forView(navView.findViewById(R.id.ic_shoppingCenter),

I am using it like this and it works.
Comment: Thanks a lot. I'm gonna check that
Comment: I think for you that's bottomNavigationViewEx
Comment: could you please check that my problem? no one answers me! https://stackoverflow.com/questions/67659325/why-poster-library-crashes-when-i-add-video . Thank you in advance


Holomorphic vector bundles on almost complex manifolds

Question: Let $M$ be a real manifold with complex structure $J$, making $M$ into an almost complex manifold. I know that the complexification $T_{\textbf{C}}M = TM\otimes \textbf{C}$ of the tangent bundle $TM$ may be decomposed as $T^{1,0}M\oplus T^{0,1}M$, the first term of which is called the holomorphic tangent bundle and the second the antiholomorphic tangent bundle (defined by $J$ being either $i\cdot \text{id}$ or $(-i)\cdot \text{id}$ on the summands). I'm trying to understand what happens when we move from the tangent bundle to arbitrary vector bundles. My question is:

What does it mean for $E$ to be a holomorphic vector bundle on $M$?

Does this question even make sense? I'm trying to understand what Higgs bundles are, and the paper I'm reading starts off by taking a holomorphic vector bundle on a Kähler--Einstein manifold. As far as I understand, being Kähler only needs an almost complex manifold and being Einstein is a condition on the Ricci curvature (and doesn't seem to imply the manifold is complex).
It seems that $E$ should certainly be a complex vector bundle, but I can't figure out where the notion of something being holomorphic comes in here. If $M$ were complex, we would need the projection map $\pi:E\to M$ to be holomorphic, but in this case $\pi$ isn't even complex-valued. Maybe if we first project from $E$ onto $T_{\textbf{C}}M$ and then onto $M$ we could get something? I have no idea. I'm certain I'm missing some key component here. Maybe we have to have $M$ be complex to have a Higgs bundle? That would definitely solve things.
Answer:
As far as I understand, being Kähler only needs an almost complex manifold

This is false.
A Kähler manifold is a complex manifold equipped with a hermitian metric such that the associated two-form is closed. The corresponding notion for an almost complex manifold as opposed to a complex manifold is called an almost Kähler manifold.
Your confusion has little to do with the definition of Kähler, but rather with the definition of a holomorphic vector bundle.
By definition, a holomorphic vector bundle is a complex vector bundle over a complex manifold $X$ such that the total space $E$ is a complex manifold and the projection map $\pi : E \to X$ is holomorphic. If $X$ is not complex, no bundle $\pi : E \to X$ is holomorphic.
In particular, while an almost complex structure on $M$ gives rise to a splitting $TM\otimes\mathbb{C} = T^{1,0}M\oplus T^{0,1}M$, the complex bundle $T^{1,0}M \to M$ is a holomorphic vector bundle only when the almost complex structure is integrable, in which case $M$ is complex.
Note, calling $T^{0,1}M$ the antiholomorphic tangent bundle is potentially misleading as there is no such thing as an antiholomorphic vector bundle. A holomorphic vector bundle has holomorphic transition functions, but a vector bundle cannot have antiholomorphic transition functions as the composition of antiholomorphic functions is holomorphic.
Comment: My comment about Kahler manifolds was only in reference to the base manifold not necessarily being complex (which would make the question trivial). If I understand correctly, you're saying a holomorphic vector bundle may only be considered over a complex manifold (so the question is indeed trivial).
Comment: Yes, part of the definition of a holomorphic vector bundle is that the base is complex.
Answer: Take two smooth manifolds $N$ and $M$ with almost-complex structures $I$ and $J$, respectively. Consider a smooth map $f \colon N \to M$, with derivative $f_* \colon TN \to TM$.
When $I$ and $J$ are complex structures, $f$ is holomorphic if and only if $J f_* = f_* I$. If we use this characterization as the definition of "holomorphic," we get a definition that makes sense even when $I$ and $J$ are merely almost-complex structures.
Now, consider a complex vector bundle $\pi \colon E \to M$. From the definition of a complex vector bundle, $E$ comes with a complex structure $i \colon E_m \to E_m$ on every fiber. Pick an almost-complex structure $I$ on the total space $E$ which is compatible with the fiber-wise complex structure, in the sense that it agrees with the action of $i$ on vertical tangent vectors. (A "vertical tangent vector" is a vector in the kernel of $\pi_* \colon TE \to TM$. I'll leave it as an exercise to guess how $i$ is supposed to act on vertical tangent vectors.)
Now we can say $E$ is "holomorphic" if $\pi$ is holomorphic, using our earlier definition of holomorphicity for maps between almost-complex manifolds.
This answer comes with the standard caveat that even if you can generalize a definition, it doesn't mean you should. This definition of a holomorphic vector bundle may only turn out to be useful when one or both of $I$ and $J$ are complex structures. At the very least, however, this definition should help you understand which results about holomorphic vector bundles fail, and why, when the base space or the total space is merely almost-complex.
Comment: I would be tempted to call this a pseudoholomorphic vector bundle.
Comment: Aha! I *knew* there was a name I liked better than "$J$-holomorphic." @MichaelAlbanese, thanks for the tip. When I get a chance, I'll revise my answer to change the terminology.


Conditional token pattern

Question: I am looking for a module or a hook that allow me to use if conditions with tokens.
For example I want to check if a field is equal to a specific value or text
[if][field_name][eq]hello[then][field_name_alt]
any ideas will be helpful.
Comment: You has tried with hook_token ?
Comment: @vinhdv its been a long time since I posted this question. I didn't try hook_token for this issue. I remember I wrote a module to solve my issue at the time.
Answer: Here is an idea, which I have not tried yet.
Sometimes you have tokens in combination with text formats. E.g. in commerce_checkout_completion_message_pane_checkout_form() the token replacement happens first, before the text format is applied. I am not sure if I agree with this order, but in this case it gives us some interesting options.
You could define a custom text filter which detects and evaluates markup like this:
{if true}hello{else}goodbye{endif}

and then you can use tokens to insert the true/false.
{if [token-which-returns-true-or-false]}hello{else}goodbye{endif}

This still leaves a lot in the open. Most tokens do not produce true/false, so maybe instead you want real equation formulas. But it is a direction you can explore further.
Answer: You can try to build it with Rules, but I'm not sure.
Another way is to make you own token module to get it. Token api is one of the easiest api from drupal.
Comment: I am actually looking for something more handy for future projects. Something like token_logic module
Comment: What is token_logic module??

Conditional token pattern


Building a real time application USing composer

Question: Consider a scenario: I am building the Enterprise Web application, in which some part of the data resides in Blockchain and in the normal database. It is the authorized application.
.bna has two types of participant admin and normal user
Use case 1)
Customer registers as "admin" on the application form. During the process,
Username and password are saved in the normal database.
Now the same user needs to be created in the Blockchain as Participant "admin" in parallel using the API's.What is the complete process to create it. How can we achieve it?
Use case 2) Another Customers login as "normal" user.how can we authenticate to show, normal user data instead of "admin" user data.
Answer: thanks for your question.
The main point is that your application users (stored in the 'normal' database you mention) are registered and enrolled as Composer identities (ie via the Fabric Certificate of Authority (CA), and for which certificates are issued (thereby becoming blockchain identities, as issued by the CA that Composer is using for the business network). Those Composer identities are mapped to participants (your application user participant) in the runtime business network you deployed in Hyperledger Composer. So everyday transactions from your application users, will submit transactions (eg. create asset, update asset, invoke business transaction xyz ) as the mapped participant (and the accountability is traced back to the real identity that submitted it).
Not sure how you want to achieve it but you can obviously use the REST APIs (generated from your modeled, deployed network and consumed by your application and application architecture) or,  something that happens using the JS APIs immediately after a application user registration has taken place. Its up to you.
In answer to your questions
1) An example of Identity Issue (using APIs) is here
          var businessNetwork = new BusinessNetworkConnection();
          return businessNetwork.connect('admin@tutorial-network')
            .then(() => {
                return businessNetwork.issueIdentity('org.acme.biznet.Trader#Trader_001', 'usr001')
            })
            .then((result) => {
                console.log(`userID = ${result.userID}`);
                console.log(`userSecret = ${result.userSecret}`);
            })
                .catch((error) => {
                console.error(error);
            });

            var businessNetwork = new BusinessNetworkConnection();

        // Connect as the identity

        return businessNetwork.connect('usr001@tutorial-network')
        .then(() => {
          return businessNetwork.ping();
        })
        .then((result) => {
          console.log(`participant = ${result.participant ? result.participant : '<no participant found>'}`);
        })
        .catch((error) => {
          console.error(error);
        });

from the command line you can list the issued identities using
composer identity list -c admin@tutorial-network
        $class:      org.hyperledger.composer.system.Identity
          identityId:  9b49f67c262c0ae23e1e0c4a8dc61c4a12b5119df2b6a49fa2e02fa56b8818c3
          name:        usr001
          issuer:      27c582d674ddf0f230854814b7cfd04553f3d0eac55e37d915386c614a5a1de9
          certificate:
          state:       ISSUED
          participant: resource:org.acme.biznet.Trader#Trader_001

Obviously you can go on to create business cards (one time process) for those participants (to be able to submit transactions on the business network ) so that they can be securely shared with those application users, who (from their application) will transact on the blockchain (eg, as authenticated/registered application users to interact with the business network, say using the REST APIs).
I'm not entirely sure how your 'application admin' users would translate but it is an application admin that you would model as a Participant type in your business network in Composer. Its really about why you want to differentiate your participants on the business network, and what customer users (whether through your application or other means) should see when they access that blockchain ledger data - eg. a history of transactions they performed. A particular customer Admin may be able to see a history of transactions for that customer by application user ?
2) Is authentication the right word? The user has logged in at this stage. Perhaps you mean access control (authorization). The simplest way is that 'normal' users (participant type) and 'admin' users (as you've defined admin) is to use ACL rules for the business network, that means the Customer can only see data relevant to them and (if necessary) the type of participant user you want to control access for. But that's only for the data on the blockchain - you obviously would use a suitable authorization strategy for your normal database.
Comment: Thank you Paul. This is helpful


Which notation should I use for the chain rule in this situation?

Question: Let $F(x,z)$ be a differentiable real-valued function that depends on $x \in \mathbb{R}$ and $z \in \mathbb{R}$, where $z=z(x,y)$, and $y \in \mathbb{R}$. Suppose that $z$ is also a differentiable function.
Is the notation of the following equation proper to describe the change in $F$ when $x$ changes, but $y$ remains constant?
\begin{align}
  \label{eqn1}
  \frac{dF}{dx}=\frac{\partial F}{\partial x} +\frac{\partial F}{\partial z}\frac{\partial z}{\partial x}
\end{align}
I was tempted to use $\frac{\partial F}{\partial x}$ on the left-hand side of this equation, instead of $\frac{dF}{dx}$, to make clear that $y$ remains constant, but then I would have had $\frac{\partial F}{\partial x}$ on the right- and left-hand sides of this equation meaning different things. On the right-hand side of the equation, $\frac{\partial F}{\partial x}$ implies that $z$ is being held constant. Is there a better way to handle this situation in terms of notation?
Comment: You need another function $G(x,y) := F(x,z(x,y))$. Then use $\frac{\partial G}{\partial x}$ on the left-hand side.
Answer: If you want to really be precise with the notation, you should avoid using the same letters over and over again with different meanings, because sometimes you're using them as the names of your variables (the inputs of the functions) and sometimes, you're using it as the name of the actual function.
Here's how I'd do it. You have three functions in the game:

First is $F:\Bbb{R}^2\to \Bbb{R}$ (where you like to call the input variables as $(x,z)$)
Second is a function $\zeta:\Bbb{R}^2\to \Bbb{R}$
Third, is the function $G:\Bbb{R}^2\to \Bbb{R}$ obtained via composition by $G(x,y):= F(x, \zeta(x,y))$

Now, here are two ways to write down the various chain rule applications:
\begin{align}
\begin{cases}
\partial_1G_{(x,y)} &= \partial_1F_{(x,\zeta(x,y))} + \partial_2F_{(x,\zeta(x,y))} \cdot \partial_1\zeta_{(x,y)}\\\\
\dfrac{\partial G}{\partial x}\bigg|_{(x,y)} &= \dfrac{\partial F}{\partial x}\bigg|_{(x,\zeta(x,y))} + \dfrac{\partial F}{\partial z}\bigg|_{(x,\zeta(x,y))} \cdot \dfrac{\partial \zeta}{\partial x}\bigg|_{(x,y)}
\end{cases}
\end{align}
I think the first is most precise, and impossible to misinterpret, because it keeps a very clear distinction between the different functions, and keeps track of where all the derivatives are evaluated. The second is still not too bad, and I think it's about as precise as you can get with Leibniz's notation.
There are some other ways I've seen people write this down, but I think it's sloppy notation (or at the very least requires a lot of interpretation), which is why I don't recommend it. Take a look at this answer, I explain how to rewrite things clearly, and also work out an example calculation in both the precise notation and the more sloppy notation.


Elements of Statistical Learning: Variance Reduction via Bagging for Random Forests

Question: While Reading chapter 15 of ESL about Random Forests I had some confusion with this phrase:

The idea in random forests (Algorithm 15.1) is to improve
the variance reduction of bagging by reducing the correlation between the
trees, without increasing the variance too much.

If I interpret this sentence correctly it means that although the variance of the decision trees could be increased due to decorrelation the variance of the ensemble will decrease. Is this interpretation correct or am I missing something ?
Answer: Yes, the variance in the individual trees can increase since they use a bootstrap sample of the training dataset, and a subset of the columns. However, using a multiple number of trees will decrease the overall variance of the algorithm.
Answer: Say you have true labels
TL : 1 0 0 1 0

Say you have 3 trees predicting
T1 : 1 1 0 1 0
T2 : 1 0 1 1 1
T3 : 1 0 0 1 0

Bagging is computing the average from the upper tree threes.
AV : 1 0 0 1 0

This reduces the overall variance, thus single trees may have bigger variance comparing to the true labels.


Issue with IIS...SERVER APPLICATION UNAVAILABLE

Question: My web application was running absolutely fine. Just 2 days back, I got an error saying.
SERVER APPLICATION UNAVAILABLE
I am pretty certain that nothing was changed on IIS. Unless my automatic Windows updates screwed it up completely.
My event viewer had zillions of following errors in Application category.
aspnet_wp.exe could not be started. The error code for the failure is C0000005. This error can be caused when the worker process account has insufficient rights to read the .NET Framework files. Please ensure that the .NET Framework is correctly installed and that the ACLs on the installation directory allow access to the configured account.
I reinstalled IIS. After installing, i ran aspnet_regiis -i for framework v2 and now it throws error saying - The application could not be initialized properly.
Any ideas what going on?
Comment: Did you manage to solve your problem?
Answer: Make sure that your IIS_WPG group has read/write access to your deployment directory
Answer: Have you tried deleting the application from the application pool and recreating it?  Have you customized any security settings?  What version of Windows/IIS?
Answer: Alex,
By any chance do you have Symantec Endpoint Protection version 11.0.5002.333 running on your machines? I saw the same issue being mentioned on Symantec forums.
Just curious? As this update came out along the same time as the Windows Update KB 974417
Comment: Something to do with Symantec Endpoint Protection newer update. Check these links.

http://www.symantec.com/connect/forums/net-framework-crashes-when-upgraded-client-sep-ru5

http://www.symantec.com/connect/forums/aspnetwpexe-could-not-be-started-error-code-failure-c0000005-when-sep1105-installed#comment-3221691
Answer: Check this article: http://support.microsoft.com/kb/2009746.  That's caused by KB973917 froom the Dec 09 patching.  The error message is a bit different than yours though.
Also, if you recently updated your app pool identity, make sure that your custom app pool identity user is in the IIS_WPG group.
Answer: I've been fighting this one as well.  Assuming it's a 11.0.5002.333 issue.  Considering rolling back to an earlier version if that's possible.


How to use roman numeral analysis for V chords

Question: I am studying a song in Fm and the song has a the C7 V chord. I learned that you write the roman numeral V for this. Then later in the song it uses the Eb7 chord which is also the V chord but in the key of Ab. So do you also use the roman numeral V for this?
Comment: Does the E♭⁷ chord resolve to A♭? At some point there should be a x/y type symbol to indicate the modulation.
Comment: Yes it does. Full chord progression is Fm, Gm7b5, C7, Bbm, Eb7, Ab7M.....
Answer: Two basic ways to do it: show a key change, or show a secondary function...
Fm: V7 | i  Ab: V7 | I ...that shows a key change the two V7 are specific to the keys as labeled.
Fm: V7 | i  V7/iii | iii ...that shows the V7 relative to iii using a slash. A key change has not been labeled so it's called a secondary function.
Answer: Indeed, C7 is the V chord for Fm. And E♭7 is the V chord for A♭. In the same piece, which hasn't modulated or changed key, V can't be both.
If the piece has modulated or changed key, then it could be construed that A♭ is the new I, which then makes E♭7 V (V7 exactly).
In key F minor, Fm is known as 'i', but A♭ will be III, and E♭ VII.
Could it be that a new section of the piece has changed the tonic from F to A♭? If so, that's why E♭ is called V. Otherwise, to answer your direct question, E♭7 will be ♭VII7.
EDIT: now we have the full sequence, I'd put A♭ as I, and Fm as vi, as in key A♭ major. Making the C7 III7, as opposed to V/vi, which it would be if only it was followed by Fm.
Comment: From the chord progression I posted above how can I tell if the tonic has changed from Fm to AbM7? I mean the progression just follows this path...or does the fact that the AbM7 comes next mean that the piece has modulated? I would say that modulation is a strong word for the chord progression above wouldnt you since after AbM7 it goes back to The beginning Fm chord? I only got the chords from a website but I doubt the sheetmusic for the song would say a modulation has taken place.
Comment: You have to look at the rest of the piece to determine if there has been a modulation. Sometimes a V-I or V7-I (or variants) occurs, then the piece returns to the original chord progression. This is a "tonicization" (with a hard "c"). It's not always easy to tell a long tonicization from a modulation; however, either analysis is OK as the sound, not the labels, is what matters.(The correct term would be "modulation" as in FM radio, but that word now means "key change" and the term "tonicization" is used.
Comment: Ok so you say that because the C7 is not followed by the Fm chord you would say Ab major NOT Fm but later in the piece there is a time where it does resolve to Fm too... so since during the song the C7 resolves to both chords... what roman numerals do we use? We cant chop and change else it is confusing. How do we decide?
Comment: @armani - undecided - that's why the question got an upvote. Waiting for a good answer...
Answer: If the key is still in F, Eb will be called bVII 7th.
This is because Eb is the b7 from the key of F.
Btw this is a basic chord progression following harmonic minor/aeolian. Here Fm / C7 means F harmonic minor but Eb7 means it changed to F aeolian.
Comment: Yes that sounds right but what numerals do you use if it goes to F aeolian? I mean it is still the same key signature right?
Comment: You might want to take it up with Tim but he says VII7 and you say bVII7... Is there a reason?
Comment: @armani The difference between the ♭VII and VII can be summed up to conventions: https://music.stackexchange.com/q/95106/45266 (disclosure: I am one of the answerers).


Help needed with the following differentiation problem

Question: If $H$ be a homogeneous function of degree $n$, and $u = (x^2+y^2)^{-\frac{1}{2}n}$ , then prove that $\frac{\partial}{\partial x}(H\frac{\partial u}{\partial x}) + \frac{\partial}{\partial y}(H\frac{\partial u}{\partial y}) = 0$
Now, Since $H$ is a homogeneous function of degree $n$ and $u$ is of degree $-n$ ,  Because $(x^2+y^2)^{-\frac{1}{2}n} = x^{-n}(1 + \frac{y^2}{x^2})^{-\frac{1}{2}n}$
Therefore $Hu$ would be of degree $0$
Hence, $x\frac{\partial (Hu)}{\partial x} + y\frac{\partial (Hu)}{\partial y} = 0$
I don't know how to proceed from here to the form required. Please help.
Comment: Have you tried expressing $H$ in terms of it's partial derivatives, i.e. $x\frac{\partial H}{\partial x} + y\frac{\partial H}{\partial y} = nH$ ?
Answer: For a homogeneous function $H:\mathbb{R}^2\rightarrow\mathbb{R}$ we have $$ H =\frac{1}{n}\left( x\frac{\partial H}{\partial x} + y\frac{\partial H}{\partial y}\right) $$
So this PDE becomes
$$ \frac{\partial H}{\partial x}\frac{\partial u}{\partial x} +  \frac{1}{n}\left( x\frac{\partial H}{\partial x} + y\frac{\partial H}{\partial y}\right)\frac{\partial^2 u}{\partial x^2} + \frac{\partial H}{\partial y}\frac{\partial u}{\partial y} +  \frac{1}{n}\left( x\frac{\partial H}{\partial x} + y\frac{\partial H}{\partial y}\right)\frac{\partial^2 u}{\partial y^2} $$
Answer: Writing $u_n = (x^2+y^2)^{-n/2}$ we have $\nabla u_n = -n (x,y) u_{n+2}$ so we get:
$$ -\frac{1}{n}\nabla \cdot ( H \ \nabla u) = \nabla \cdot ( (x,y)H \ u_{n+2}) = 2 H u_{n+2} + (x \partial_x + y \partial_y) (H u_{n+2})= 2 H u_{n+2} - 2 H u_{n+2} = 0$$
since $H u_{n+2}$ is homogeneous of degree -2.


How do I change the default height?

Question: 9 rows is just way too small by default. Is this a text-editor for ants?
Comment: Under CKEditor Profile settings > Advanced options > custom javascript configuration > you can specify the custom js rule:  **config.height = 500 + 'px';**
Comment: There is no "Advanced options" for Drupal 8.
Comment: My solution works only for CKEditor module in Drupal 7
Answer: I rolled a module for that now: https://www.drupal.org/project/ckeditorheight

This module changes all ckeditor text fields to respect the "rows" setting of the field. How rows translate into pixels is a global setting, configured via a pixel factor and offset.
Comment: Thank you! Awesome module!
Answer: Like the comments to the previous answer mention, changing the amount of text area rows displayed in the form display doesn't change the height of the CKEditor attached to those fields. I haven't found any place yet to change the height settings through the UI so we have to do it in code.
To do this, create a simple new custom module ckeditor_change_height with these two files (or add the code under ckeditor_change_height.module to an existing one):
ckeditor_change_height.module
<code>/**
 * Change the ckeditor's settings.
 *
 * Implements hook_editor_js_settings_alter().
 */
function ckeditor_change_height_editor_js_settings_alter(array &$settings) {
  foreach (array_keys($settings['editor']['formats']) as $text_format_id) {
    if ($settings['editor']['formats'][$text_format_id]['editor'] === 'ckeditor') {
      $settings['editor']['formats'][$text_format_id]['editorSettings']['height'] = '350px';
    }
  }
}
</code>
ckeditor_change_height.info.yml
<code>name: CKEditor - Change height
type: module
description: Change CKEditor height
package: CKEditor
core: '8.x'
version: '8.x-1.0'
</code>
Just set that 350px to be any height you want, enable the module & flush your cache.
Comment: I was sure I had it working in my .theme file but it turns out it didn't! I also have a custom module to change my ckeditor settings & skin so it was actually pulling the updated height from there... So yeah, sorry about the confusion. You need to add the snippet of code to a custom module instead and enable that instead of using the .theme file. See the updated answer!
Comment: I tried adding that hook to my .theme file (replaced THEMEID with my theme name), cleared Drupal cache, browser cache, and it had no effect. How can I best test the hook? I know the .theme file is being called as I use it to clear the Generator tag.
Comment: Ah yes, sorry forgot to mention that in my site I use one theme for both viewing & editing content. You need to add that snippet of code to your admin panel theme. Or the better way would be to create a custom module for it. That way it will work in your main theme & admin theme, wherever you use CKEditor really.
Comment: I use the single theme for both viewing & editing. `<?php
function sunvan_page_attachments_alter(array &$attachments) {
  // Hide Drupal generator meta tag.
  unset($attachments['#attached']['html_head'][1]);
}
// change the ckeditor's settings
function sunvan_editor_js_settings_alter(array &$settings) {
  foreach (array_keys($settings['editor']['formats']) as $text_format_id) {
    if ($settings['editor']['formats'][$text_format_id]['editor'] === 'ckeditor') {
      $settings['editor']['formats'][$text_format_id]['editorSettings']['height'] = '500px';
    }
  }
}`
Answer: Anyone using Drupal 8-- this has changed now that Autogrow is built into core, but is still useful if you want to set the default minHeight and maxHeight. See my code below to replace code found in ckeditor_change_height.module:
<code>    function ckeditor_change_height_editor_js_settings_alter(array &$settings) {
      foreach (array_keys($settings['editor']['formats']) as $text_format_id) {
        if ($settings['editor']['formats'][$text_format_id]['editor'] === 'ckeditor') {
          $settings['editor']['formats'][$text_format_id]['editorSettings']['autoGrow_minHeight'] = '100';
        }
      }
    }
</code>
Comment: This need to be better documented somewhere. Took me far to long to find this solution. Thanks!
Answer: Check out the Autogrow module/plugin.  Works pretty slick.  I do recommend changing the default of 600 down to maybe 400.
Update:
It appears autogrow will be included by default starting in 8.3.x
https://www.drupal.org/node/2239419

How do I change the default height?


Automatically Change Source code with Version Control Metadata

Question: I am working with source files in C# and I want to add headers that are automatically changed when checked in. For example so the date of check-in shows in the file, and copyright etc.
Is there a way to add tags to the source so when checked in these automatically are created but as importantly some that are consistent between management systems (i.e. SVN, StarTeam etc) should we need to change management systems in the future?
Answer:
Is there a way to add tags to the source so when checked in these automatically are created

Yes - svn:keywords in your case

but as importantly some that are consistent between management systems

Not (in common) - different VCS uses different syntax and techiques for RCS-style keywords, some doesn't use at all (Git), but allow some emulation layer, some (Mercurial) can use and serve SVN-keywords, but require handwork etc...


Python: Memory Error while using large strings

Question: Basically, I am designing a web search engine, so I designed a crawler to get web pages.
When read in, the web pages are in html format, so all the tags are there. I need to extract keywords from the body and title, so I'm trying to remove all the tags (anything between '<' and '>')
The code below works well for small html pages, but when I try to use this on a large scale (ie starting from http://www.google.com), I run out of memory.
0 def remove_tags(self, s):
1     while '<' in s:
2         start = s.index('<')
3         end = s.index('>')
4         s = s[:start] + " " + s[end+1:]
5     return s.split()

The memory error occurs at line 4. How do I fix my code so that taking the substrings of s doesn't consume excessive memory?
Answer: Your general approach is wrong. Firstly, use a real XML/HTML parser. Something like BeautifulSoup, which is forgiving when it comes to bad HTML. Your approach with looking at < and > won't survive for long.
Secondly, you've read the whole thing into memory and are playing with it there. That's memory consuming and some of the operations you're doing might create copies which is not a good thing either. Instead, iterate over the input stream and process it as you see data. Think of remove_tags as a filter on the input rather than a text processing function.


I need suggestions on C2C (Customer2Customer) PHP CMS

Question: I need to build a website for customers advertising such as craiglist.
I want to build it in PHP, and I 'm willing to use an open source CMS.
I'm a very big fan of Drupal, but I don't now if stands well for this kind of sites.
Could anyone suggest me a suitable CMS for my domain?
Best,
Demian
Comment: Voting to close as NPR, superuser.com might be a better place to ask.
Answer: Drupal is very capable to do that, so if you are already familiar with Drupal, I would stick to it.
Jeff Robbins from Lullabot created a craigslist clone for demonstration purposes on the 'do it with drupal' seminar. You can find it at http://www.thieveslist.com/.


What is the logic behind allowing only same Monad types to be concatenated with `>>` operator?

Question: Though it is okay to bind IO [[Char]] and IO () but its not allowed to bind Maybe with IO. Can someone give an example how this relaxation would lead to a bad design? Why freedom in the polymorphic type of Monad is allowed though not the Monad itself?
Comment: You can only use operations that a typeclass instance actually supports. An instance of `Monad` only supplies `(>>=)  :: m a -> (  a -> m b) -> m b`, i.e. it restrictively requires the same `m` to be used throughout. If you can see some sensible meaning for there to be an arbitrary "bind over anything" operation, then by all means, you can specify it as a typeclass and create as many instances as you know how. A class like `(>>=)  :: m a -> (a -> n b) -> n b`, while requiring nothing of the consumer, is almost impossible to sensibly satisfy for an implementer.
Comment: The theory behind the `Monad` type class requires `m` to be the same functor; this property is what makes it suitable as a basis for handling IO; you can't escape from `IO` by switching to a different type.
Comment: How would you bind `Maybe` with `IO`? An `IO` monad does *not* alters the state, it describes *how* to alter the state.
Comment: I can understand questions of the form "why would this alternate design be bad?"; it makes sense to wonder whether you have missed some important consideration and ask others to help you think of things you haven't. Nevertheless, I feel like the person asking such a question also has a burden to say what the alternate design is and why it would be good. I don't think you've described either of those things (what would binding a `Maybe` to an `IO` do? and why would that be good?).
Answer: There are a lot of good theoretical reasons, including "that's not what Monad is."  But let's step away from that for a moment and just look at the implementation details.
First off - Monad isn't magic.  It's just a standard type class.  Instances of Monad only get created when someone writes one.
Writing that instance is what defines how (>>) works.  Usually it's done implicitly through the default definition in terms of (>>=), but that just is evidence that (>>=) is the more general operator, and writing it requires making all the same decisions that writing (>>) would take.
If you had a different operator that worked on more general types, you have to answer two questions.  First, what would the types be?  Second, how would you go about providing implementations?  It's really not clear what the desired types would be, from your question.  One of the following, I guess:
class Poly1 m n where
    (>>) :: m a -> n b -> m b

class Poly2 m n where
    (>>) :: m a -> n b -> n b

class Poly3 m n o | m n -> o where
    (>>) :: m a -> n b -> o b

All of them could be implemented.  But you lose two really important factors for using them practically.

You need to write an instance for every pair of types you plan to use together. This is a massively more complex undertaking than just an instance for each type. Something about n vs n^2.
You lose predictability.  What does the operation even do?  Here's where theory and practice intersect.  The theory behind Monad places a lot of restrictions on the operations.  Those restrictions are referred to as the "monad laws".  They are beyond the ability to verify in Haskell, but any Monad instance that doesn't obey them is considered to be buggy. The end result is that you quickly can build an intuition for what the Monad operations do and don't do.  You can use them without looking up the details of every type involved, because you know properties that they obey.  None of those possible classes I suggested give you any kind of assurances like that. You just have no idea what they do.
Answer: I'm not sure that I understand your question correctly, but it's definitely possible to compose Maybe with IO or [] in the same sense that you can compose IO with [].
For example, if you check the types in GHCI using :t,
getContents >>= return . lines

gives you an IO [String]. If you add
            >>= return . map Text.Read.readMaybe

you get a type of IO [Maybe a], which is a composition of IO, [] and Maybe.  You could then pass it to
            >>= return . Data.Maybe.catMaybes

to flatten it to an IO [a]. Then you might pass the list of parsed valid input lines to a function that flattens it again and computes an output.
Putting this together, the program
import Text.Read (readMaybe)
import Data.Maybe (catMaybes)

main :: IO ()
main = getContents >>=                    -- IO String
       return . lines >>=                 -- IO [String]
       return . map readMaybe >>=         -- IO [Maybe Int]
       return . catMaybes >>=             -- IO [Int]
       return . (sum :: [Int] -> Int) >>= -- IO Int
       print                              -- IO ()

with the input:
1

2
Ignore this!
3

prints 6.
It would also be possible to work with an IO (Maybe [String]), a Maybe [IO String], etc.
You can do this with >> as well. Contrived example: getContents >> (return . Just) False reads the input, ignores it, and gives you back an IO (Maybe Bool).


From Survival function to Cumulative density function (CDF), does CDF properties hold?

Question: Given the following CDF values

time    KM_estimate
0.0     0.00
17.0    0.05
19.0    0.10
29.0    0.20
41.0    0.25
48.0    0.30
53.0    0.35
54.0    0.40
56.0    0.55
60.0    0.60
61.0    0.60
63.0    0.68
66.0    0.76
68.0    0.92
69.0    0.92

for the following dataset with right censoring.
    T   E
0   17.0    1
1   19.0    1
2   29.0    1
3   29.0    1
4   41.0    1
5   48.0    1
6   53.0    1
7   54.0    1
8   56.0    1
9   56.0    1
10  56.0    1
11  60.0    1
12  60.0    0
13  61.0    0
14  61.0    0
15  63.0    1
16  66.0    1
17  68.0    1
18  68.0    1
19  69.0    0

It can be seen that the CDF value does not reaches 1.0 which in return violates the property of CDF which is to be non-decreasing monotonic and non-negative with max value == 1.0.
How do we ensure that in such cases the properties of CDF are held?
Code to reproduce:
from lifelines import KaplanMeierFitter
kmf = KaplanMeierFitter()
kmf.fit(T, event_observed=E)

kmf.cumulative_density_
```

Answer: In general, there's no solution.
Yes, as a probability function, the CDF $F$ is one minus the survival function  $S(t) = 1-F(t)$. However, the Kaplan-Meier estimate will only go to 0 if the last event in the sample is a death event. Otherwise, it will have a positive limit. While the Kaplan-Meier is an unbiased estimate of the survival function, the behavior can't be trusted out in the tails. If you use a parametric survival estimate instead then you're golden. You can also take a "super efficient" approach and modify the KM curve to set the survival curve to 0 for any value after, say, two times the maximum time. Why not?


Alternating groups, $A_3$ and $A_4$

Question: I have to:

Prove that $A_3$ is a simple group.

Prove that $A_4$ is not a simple by proving that the elements of order $2$ along with the neutral form a normal subgroup.

I know that the elements of $A_3$ are $\{1,(123),(132)\}, $ but how is $A_3$ a simple group then?
Comment: $A_3$ has order $3$. It really can't have very many subgroups.
Comment: 1) Every group of prime order is simple by Lagrange. 2) $V_4$ is a normal subgroup of $A_4$ - see [this duplicate](https://math.stackexchange.com/questions/990541/find-the-subgroups-of-a4).
Comment: Thanks for the help.
Answer: $A_3$ is isomorphic to $\Bbb{Z}_3$ since the order is $3$. Thus there are no other proper non-trivial normal subgroups. Hence $A_3$ is a simple group. In general, $\Bbb{Z}_p$ is simple for any prime $p$.

Alternating groups, $A_3$ and $A_4$


Evaluate $\int \frac{1}{x \sqrt{16x^2-9}}dx$

Question: I need help with this exercise.
Evaluate $\int \frac{1}{x \sqrt{16x^2-9}}dx$
This is why I've tried but it seems wrong.
$$\int \frac{1}{x \sqrt{16x^2-9}}dx$$
$$=\int \frac{1}{x \sqrt{(4x)^2-3^2}}dx$$
$$=\int \frac{4 \cdot 1}{4 \cdot x \sqrt{(4x)^2-3^2}}dx$$
$$=4\int \frac{1}{4x \sqrt{(4x)^2-3^2}}dx$$
$$=4\left(\frac{1}{3} \sec^{-1} \frac{|4x|}{3}\right) + C$$
I've checked in multiple math solvers that gives me the answer but not the process and answer is the same but without the 4 that is in the beginning. Is there a way that I can do it without trigonometric substitution? I know that this can be done with trigonometric substitution (I've already tried it and got the answer right) but this exercise appears in a section of a book of derivatives and integrals of Inverse Trigonometric Functions which is before the chapter where all the techniques of integrations appears. So this is supposed to be done without using that knowledge. So I'm wondering how I can get the answer using a simpler way.
Thanks for your help.
Comment: Try [here](https://www.integral-calculator.com/)
Comment: Try letting $u = \sqrt{16x^2 - 9}$.
Comment: Hey! @SineoftheTime thanks! but it didn't help. That solver is using rationalizing substitution which I also know I could use but like I said that technique and trigonometric subtitution is later in the book, that I'm supposed to be able to do it without that knowledge. :-/
Comment: @Accelerator maybe my book is crazy because that technique and trigonometric subtitution appear later in my book. I shouldn't be using those techniques if the exercise appear in a section of the book that is before those techniques.
Comment: Are you really not allowed to use a $u$-substitution for this problem? What techniques are you allowed to use then?
Comment: @Accelerator yes but simple $u$-substitution, not rationalizing $u$-substitution. I already found it. $u=4x$. it blew my mind how simple the substitution was. :-S
Comment: I don't know what rationalizing a $u$-substitution means, but IMO, If the problem was written such that the reader had already learned $u$-substitution, then I don't think it's much of a stretch for the reader to think of letting $u$ equal the entire square root.
Comment: @Accelerator rationalizing substitution is what you suggested, substituting the whole radical by $u$. At least that's how my book calls it, but I'm not allowed to used that substitution because is later in the book. It hasn't been discussed yet. Thanks anyway for your help.
Comment: You have $dx$ and not $d(4x)$, so your last step is wrong.
Answer: In the last step, you're forgetting to use the chain rule:
$$\int \frac{1}{4x \sqrt{(4x)^2-3^2}}dx=\frac14\int \frac{4}{4x \sqrt{(4x)^2-3^2}}dx=\frac{1}{4}\frac 13 \sec^{-1}\frac{|4x|}{3}+c$$
Hence:
$$4\int \frac{1}{4x \sqrt{(4x)^2-3^2}}dx= \frac 13 \sec^{-1}\frac{|4x|}{3}+c$$
Comment: @bdvg2302 basically, you're forgetting to derive $4x$
Comment: how chain rule is applied here. I'm sorry, not seeing it.
Answer: I have seen this taught in such a way that we find the derivatives of the inverse trig functions.
$\frac {d}{dx} \sec^{-1} x = \frac {1}{x\sqrt{x^2 - 1}}\\
\frac {d}{dx} \sec^{-1} ax = \frac {1}{x\sqrt{a^2x^2-1}}\\
\frac {d}{dx} \frac 1a \sec^{-1} \frac {x}{a} = \frac {1}{x\sqrt{x^2 - a^2}}\\
\frac {d}{dx} \tan^{-1} x = \frac {1}{x^2 + 1}$
etc.
So, rather than using the substitution $x = \frac 34 \sec t$ and simplifying. We would try to make the integral into a constant times something we can find on a table of known derivatives.
$\int \frac {1}{x\sqrt{16x^2 - 9}}\ dx\\
 \int \frac {1}{3x\sqrt{(\frac 43x)^2 - 1}}\ dx$
Which is on our table.
This is far less versitile than the substitution
$x = \frac 34 \sec t\\
dx = \frac 34 \sec t\tan t \ dt$
$\int \frac { \frac 34 \sec t\tan t \ dt}{\frac 34\sec t\sqrt {9\tan^2 t}} \ dt\\
\frac 13 \int \ dt\\
\frac 13 t + C$
and reverse the substitution.
$t = \sec^{-1} \frac 43x\\
\frac 13 \sec^{-1} \frac 43x + C$
Answer: $$
\begin{aligned}
 \int \frac{1}{x \sqrt{16 x^2-9}} d x = & \frac{1}{16} \int \frac{1}{x^2}  d\left(\sqrt{16 x^2-9}\right) \\
= & \int \frac{d\left(\sqrt{16 x^2-9}\right)}{\left(\sqrt{16 x^2-9}\right)^2+9} \\
= & \frac{1}{3} \tan ^{-1}\left(\frac{\sqrt{16 x^2-9}}{3}\right)+C
\end{aligned}
$$
Answer: I found the "simpler way". :-S
Is using substitution with $u=4x$, so $x=\frac{u}{4}$, then $du=4dx$, so $\frac{du}{4}=dx$.
$$\int \frac{1}{x \sqrt{16x^2-9}}dx$$
$$=\int \frac{1}{x \sqrt{(4x)^2-3^2}}dx$$
$$=\int \frac{1}{\frac{u}{4} \sqrt{u^2-3^2}}\cdot\frac{du}{4}$$
$$=\int \frac{1}{u\sqrt{u^2-3^2}}du$$
$$=\frac{1}{3}sec^{-1}\frac{|u|}{3}+C$$
$$=\frac{1}{3}sec^{-1}\frac{|4x|}{3}+C$$
Answer: HINT
WLOG, let us assume that $x > 3/4$. I would recommend you to notice that
\begin{align*}
\int\frac{\mathrm{d}x}{x\sqrt{16x^{2} - 9}} & = \int\frac{\mathrm{d}x}{x^{2}\sqrt{16 - 9x^{-2}}}\\\\
& = -\int\frac{\mathrm{d}(1/x)}{\sqrt{16 - 9x^{-2}}}\\\\
& = -\int\frac{\mathrm{d}u}{\sqrt{16 - 9u^{2}}}
\end{align*}
Which is (almost) a standard integral.
Can you take it from here?
Answer: This answer is the same as the answer with secant inverse, since $\arcsecx + \arccosecx = \pi/2$
Comment: Welcome to MSE. It is in your best interest that you type your questions (using [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)) instead of posting links to pictures.


How to move an image when clicked on it in PYGAME?

Question: Basically, when I click on an image I want the image to move to a new different location. When I click again, it should move again.
import pygame
import random

pygame.init()

screen = pygame.display.set_mode((1420, 750))

pygame.display.set_caption("Soccer Game")
icon = pygame.image.load('soccer-ball-variant.png')
pygame.display.set_icon(icon)

ball = pygame.image.load('soccer2.png')
ballrect = ball.get_rect()

X = random.randrange(0, 1100)
Y = random.randrange(0, 600)

def player():
    screen.blit(ball, (X, Y))

run = True
while run:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            x, y = event.pos
            if ball.get_rect().collidepoint(x, y):
                X = random.randrange(0, 1100)
                Y = random.randrange(0, 600)
                player()

    screen.fill((255, 255, 255))
    player()

    pygame.display.update()

The problem is that this program only works when i click on the left-up corner of the screen, and not on the ball. I am a biginner in the pygame module, but i think the problem is this if statement:
if ball.get_rect().collidepoint(x, y):
    X = random.randrange(0, 1100)
    Y = random.randrange(0, 600)
    player()

Answer: pygame.Surface.get_rect.get_rect() returns a rectangle with the size of the Surface object, that always starts at (0, 0) since a Surface object has no position. A Surface is blit at a position on the screen. The position of the rectangle can be specified by a keyword argument. For example, the top leftof the rectangle can be specified with the keyword argument topleft. These keyword argument are applied to the attributes of the pygame.Rect before it is returned (see pygame.Rect for a full list of the keyword arguments).
if ball.get_rect().collidepoint(x, y):
if ball.get_rect(topleft = (X, Y)).collidepoint(x, y):

However, I recommend removing the X and Y variables, but using ballrect instead:
ballrect = ball.get_rect()
ballrect.x = random.randrange(0, 1100)
ballrect.y = random.randrange(0, 600)

def player():
    screen.blit(ball, ballrect)

if ballrect.collidepoint(event.pos):
    ballrect.x = random.randrange(0, 1100)
    ballrect.y = random.randrange(0, 600)

Complete example:
import pygame
import random

pygame.init()
screen = pygame.display.set_mode((1420, 750))
pygame.display.set_caption("Soccer Game")
icon = pygame.image.load('soccer-ball-variant.png')
pygame.display.set_icon(icon)

ball = pygame.image.load('soccer2.png')
ballrect = ball.get_rect()
ballrect.x = random.randrange(0, 1100)
ballrect.y = random.randrange(0, 600)

def player():
    screen.blit(ball, ballrect)

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            if ballrect.collidepoint(event.pos):
                ballrect.x = random.randrange(0, 1100)
                ballrect.y = random.randrange(0, 600)

    screen.fill((255, 255, 255))
    player()
    pygame.display.update()


Check if index exists in WebSQL

Question: Is there a way to check if an index exists for a table in WebSQL database?
I'm using CREATE UNIQUE INDEX INDEX_GUID ON TABLE PERSONS for creation. But if index already exists I get an error:

{
    code: 5, // SYNTAX_ERR - from docs
    message: "could not prepare statement (1 index INDEX_GUID already exists)"
}

The best solution for me would be to list all indexes of a table.
Comment: Using `IF NOT EXISTS` doesn't help in my case. I need to know if index exists.
Answer: I am using this but it's a workaround. I hope that error messages are allways in english.
db.transaction(function (tx) {
    tx.executeSql(
        "CREATE UNIQUE INDEX INDEX_GUID ON TABLE PERSONS",
        [],
        function (tx, rs) {
            // index created
        },
        function (tx, e) {
            if (e.message.indexOf("already exists") == -1) {
                // index not created - already exists
            }
        });
    );
});

Answer: if (e.message.indexOf("already exists") == -1) {
should be a !=
i.e.
    db.transaction(function (tx) {
        tx.executeSql(
            "CREATE UNIQUE INDEX INDEX_GUID ON TABLE PERSONS",
            [],
            function (tx, rs) {
                // index created
            },
            function (tx, e) {
                if (e.message.indexOf("already exists") != -1) {
                    // index not created - already exists
                }
            });
        );
     });

Check if index exists in WebSQL


Proof of summation of Stirling's Numbers of the first kind

Question: "Stirling's number of the first kind $s(n,k)$ is the number of permutations of ${1,2,...,n}$ with $k$-cycles. Prove that $n! =  \sum s(n,k)$ (from k = 1 to $\infty$) "
After checking a the first few 'n' I have managed to convince myself this is the case. As I didn't know where else to try, I attempted induction, showing true for n = 2 (I thought starting at 1 may be a little too general.) Then assumed true for n = t. Trying to work through n = t + 1 I am beginning to feel that  induction in this method won't work, unless I can figure a method, in terms of n and k on summing up terms. Can someone let me know if I am on the right track, or if I am going about this proof in the wrong way, and thus a guide on where to go from there. Thanks in advance.
Answer: HINT: Use a combinatorial argument. How many permutations of $\{1,\ldots,n\}$ are there altogether? Does every permutation have a unique cycle structure?
Comment: There would be n! permutations. I don't know how to take into account the various ways of splitting e.g. s(4,2) could be two cycles of 2, or a cycle of 3 and a cycle of 1.?
Comment: @Duncan: There are indeed $n!$ permutations of $[n]=\{1,\ldots,n\}$. It doesn't matter that $s(n,2)$ counts both permutations with cycle structure $(2,2)$ and permutations with cycle structure $(3,1)$; the point is that it counts all permutations of $[n]$ with exactly two cycles, and each permutation of $[n]$ has a unique cycle structure, so it doesn't get counted in $s(n,k)$ for two different values of $k$.
Comment: It seems to me in this case that the proof is almost trivial then..?
Comment: @Duncan: Yes, it is, provided that you've already shown that each permutation has a unique cycle structure.
Comment: That's great thanks for your help Brian.
Comment: @Duncan: You're welcome.


views generated pager url

Question: How can I get the url generated by the pager in views.
drupal/project11?page=1
drupal/project11?page=2
I would like to add a link on my image to the 2nd page on my first image, to the 3th page on my 2nd image without using the pager.
Answer: I think you're asking for a link to a View like drupal/project11/1 or drupal/project11/2. You can do this with Clean Pagination module.

Clean Pagination is a very simple module that allows you to enable
  clean URL pagination for specified pages. The way Drupal typically
  works, if you had a view with the URL 'my-view', subsequent pages
  would normally use a query to pass the page number, as in
  'my-view?page=2'. When Clean Pagination is being used for a page, it
  will create a url like 'my-view/2'.
Currently, the module has just two settings: 1) Set the pages where
  you want clean pagination enabled, and 2) Enable
  search-engine-friendly pagination hyperlinks.
The search-engine-friendly pagination hyperlinks is an experimental
  feature you can optionally turn on that will add the page URL to
  pagination links, and then remove them via jQuery. To a user, it will
  look like a single number, but to a screen readers and search engines
  it will have the url in the hyperlink text, which is usually a good
  thing.

views generated pager url


Trouble with package glmulti

Question: I try to install and use the glmulti function from the glmulti package
install.packages('glmulti')
library(glmulti)

But I am seeing no function called glmulti. Could anyone else please test and let me know if I am missing something obvious? Currently when I call the function I get the following error (note reduced specs to reduce clutter):
Error in glmulti(...  :
  could not find function "glmulti"

Comment: Just googled the separate issue that is getting rJava to work. I'm on it and will post my fix shortly. Thanks for the help.
Comment: Oh sorry, I just removed the specs to reduce clutter. Should have specified.
Comment: It appears to be properly installed. Are you saying I need to install rJava independently? Why is it a pain to install?
Comment: ok it works for me.. i just installed and run the function. Are you sure it is installed? when you do library(glmulti), it doesn't throw an error? Mine shows this ```library(glmulti)
Loading required package: rJava ```
Comment: Ugh. Narrow console means I only saw the version error messages...

```Loading required package: rJava
Error: package or namespace load failed for 'rJava':
 .onLoad failed in loadNamespace() for 'rJava', details:
  call: fun(libname, pkgname)
  error: JAVA_HOME cannot be determined from the Registry
Error: package 'rJava' could not be loaded```

Any thoughts on why it is failing? If I manually install rJava on its own, I still get an error.
Answer: Thanks to StupidWolf for pointing out solution in the comments.
I required 64-bit Java available from this link (current 27/04/2020).
Restart R and reload packages and voila!

Trouble with package glmulti


Naive bayes computation of denominator

Question: I'm wondering about the denominator in this computation :
P(Banana|Long, Sweet and Yellow)
      P(Long|Banana) * P(Sweet|Banana) * P(Yellow|Banana) * P(banana)
    = _______________________________________________________________
                      P(Long) * P(Sweet) * P(Yellow)

Which is from this post
I don't know that it is valid to convert
P(long, sweet, yellow)

to
P(long)P(sweet)P(yellow)

The reason that I'm confused is that we have conditional independence, rather than complete independence.
Or is this valid here?
edit - text example
Answer: It isn't correct exactly for the reason you realized. The evidence calculation should be:
$$P(L,S,Y)=\sum_{B'\in \{Banana,Orange,Other\}} P(L|B')P(S|B')P(Y|B')P(B')$$
However, the classification is correct because the evidence is not important in Naive Bayes classifier since it is common for all classes.
Comment: Thank you, perhaps the other post should be edited as it seems to be quite popular? ( I found it via google search ). I'm not sure how that works between stacks  and whether this suggestion is appropriate
Comment: I can post a comment there, but don't know it'd be effective or not; it's probably been upvoted by many with elementary probability knowledge.

Naive bayes computation of denominator


Why doesn't my date get rendered?

Question: In Drupal 8, I have a Flag entity with a date field attached.
My code looks like this:
function MYMODULE_flagging_presave(FlaggingInterface $flagging) {
    if ($score == 0 || $score == 1) {
      $flagging->field_date_review = date("Y-m-d", strtotime('today'));
    }
    else {
      $date = date("Y-m-d", strtotime("+$interval days"));
      $flagging->field_date_review = $date;
    }

I checked and the dates get stored in the database like 2020-07-02.
I have a custom view that shows these flaggings, and I added a filter for nodes with a date field value of less than +1 days; this behaves as expected, so the Views module seems to understand the dates as I stored them.
But, when I try to add the date field, I get an empty display in Views.
Further debugging
When I render the flagging entity, the date field doesn't show a value, either.
Other fields set in ``hook_flagging_presave()` are displayed correctly; it's only the date field that doesn't have a value.
Configuration
On the flagging entity's Manage display screen, I have set my date field to use the Plain format with no timezone offset. I also tried the Default format and several others, but nothing let me display the value.
There are no errors in the recent log messages.
To sum up: the date field has data in the database, which Views can see and use for filters.  But, this date field cannot be displayed in Views or on the rendered flagging entity.
What do I need to do to get the date to be displayed?
Comment: Does this answer your question? [Set date field in D8](https://drupal.stackexchange.com/questions/214164/set-date-field-in-d8)
Comment: Please add a screenshot of the Views config. Also, does the date show up on the regular view node page?
Comment: @beltouche Thanks, the problem doesn't seem to be Views.  Updated.
Comment: Have you tried setting the date using what is a more standard construct: `$flagging->set('field_date_review', $date)`?
Comment: @beltouche I tried that construct, same result; it is saved to DB but not displayed.
Comment: @4k4 Thanks, that's an informative question.  But my question stemmed from a confusion between date and datetime, which is not directly addressed in the linked question.
Comment: The linked question stemmed from the same confusion and then @mpdonadio addressed it in the comments and answer. See also the second answer how to use [DateTimeItemInterface](https://api.drupal.org/api/drupal/core%21modules%21datetime%21src%21Plugin%21Field%21FieldType%21DateTimeItemInterface.php/interface/DateTimeItemInterface/9.0.x) when handling this field type.
Comment: @PatrickKenny - What does the date look like in the DB if you set the value from the UI instead of via code?
Answer: I found it-- the Date field can store dates or datetimes, and you have to change your code for each case.
When you add a Date field to an entity, you can choose Date (date) or Date and time (datetime) as the Date type.
More information in this blog post, but the basic idea is:
$node->set('field_date', date('Y-m-d', time()));
$node->set('field_datetime', date('Y-m-d\TH:i:s', time()));

Why doesn't my date get rendered?