Erro ao rodar app direto no device IOS

Question: Tenho um app que roda perfeitamente no simulador, o mesmo já está assinado com minha conta de dev. Porém quando tento fazer o build para rodar em um device "físico" alguns erros acontecem, já tentei reinstalar as bibliotecas utilizadas pelo Pods e tbm tentei apagar a pasta DerivedData mas sem sucesso. O que poderia estar ocasionando esse erro?
Segue stack do erro:

PhaseScriptExecution [CP]\ Embed\ Pods\ Frameworks
  /Users/diego/Library/Developer/Xcode/DerivedData/my-project-hcjzjblytpxfyucbgwmphvetikwt/Build/Intermediates.noindex/my-project.build/Debug-iphoneos/my-project.build/Script-615B2B9C4AAE04ED75B72A96.sh
      cd /Users/diego/Desenvolvimento/project/my-project
      /bin/sh -c /Users/diego/Library/Developer/Xcode/DerivedData/my-project-hcjzjblytpxfyucbgwmphvetikwt/Build/Intermediates.noindex/my-project.build/Debug-iphoneos/my-project.build/Script-615B2B9C4AAE04ED75B72A96.sh
mkdir -p
  /Users/diego/Library/Developer/Xcode/DerivedData/my-project-hcjzjblytpxfyucbgwmphvetikwt/Build/Products/Debug-iphoneos/my-project.app/Frameworks
  rsync --delete -av --filter P .*.?????? --filter "- CVS/" --filter "-
  .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers"
  --filter "- PrivateHeaders" --filter "- Modules" "/Users/diego/Library/Developer/Xcode/DerivedData/my-project-hcjzjblytpxfyucbgwmphvetikwt/Build/Products/Debug-iphoneos/Alamofire/Alamofire.framework"
  "/Users/diego/Library/Developer/Xcode/DerivedData/my-project-hcjzjblytpxfyucbgwmphvetikwt/Build/Products/Debug-iphoneos/my-project.app/Frameworks"
  building file list ... done Alamofire.framework/
  Alamofire.framework/Alamofire Alamofire.framework/Info.plist
sent 1624660 bytes  received 70 bytes  3249460.00 bytes/sec total size
  is 1624230  speedup is 1.00 Code Signing
  /Users/diego/Library/Developer/Xcode/DerivedData/my-project-hcjzjblytpxfyucbgwmphvetikwt/Build/Products/Debug-iphoneos/my-project.app/Frameworks/Alamofire.framework
  with Identity iPhone Developer: Diego Augusto (4L5839GH78)
  /usr/bin/codesign --force --sign
  720B129FDEA6BFFF9AF1810B80DB6BC0A7DED204
  --preserve-metadata=identifier,entitlements '/Users/diego/Library/Developer/Xcode/DerivedData/my-project-hcjzjblytpxfyucbgwmphvetikwt/Build/Products/Debug-iphoneos/my-project.app/Frameworks/Alamofire.framework'
  /Users/diego/Library/Developer/Xcode/DerivedData/my-project-hcjzjblytpxfyucbgwmphvetikwt/Build/Products/Debug-iphoneos/my-project.app/Frameworks/Alamofire.framework:
errSecInternalComponent Command /bin/sh failed with exit code 1
Answer: Problema resolvido, tive que apagar o conteúdo da pasta Keychains
rm -rf ~/Library/Keychains

Em seguida baixei os certificados e chaves novamente.

Erro ao rodar app direto no device IOS


Does bar numbering restart for each act of an opera?

Question: Perhaps a slightly odd question...
I'm preparing the vocal score for a two act opera and was wondering whether it is standard for numbering to continue throughout the whole opera or to start numbering at 1 again for each act?
Answer: Yes, the numbering restarts at the beginning of each act. This is standard across all subgenres of opera.
But intra-act numbering conventions vary depending on the style. If it's a number opera, the measure numbering restarts at the beginning of each number. But if we're looking at a continuous single act (like those in Wagner, for example), then the numbering will continue for the entire act.
Comment: I'm not convinced. Plenty of my opera scores (admittedly some aged editions) have no bar numbers at all. In number operas (where ouverture, each recitative and aria receives its own ordinal) there is also the convention to restart the bar number at any number, which  has advantages in case of cutting whole arias.


Co-occurrence matrix of numbers in the same group

Question:
Each row in the dataframe (which I can convert into arrays) indicates groups. I want to create a 'n x n' matrix (n is the greatest number shown in the data). This matrix will tell me how many groups two numbers appeared together.
For example, in the first group (first row), 5 and 9, 5 and 23, 5 and 32, 5 and 33, 9 and 23, 9 and 32, 9 and 33 ..... so on appeared together.
So on the output matrix this will look something like this:

(This matrix is just an example, it is not according to the data above). Like I said, each number indicates how many groups the two numbers appeared together.
I've been researching this, to no avail. What code could I try, using either Python or R?
Comment: Please share example input and output data as reproducible code, not as two entirely unrelated ***images*** of data.
Comment: I m confused. Not clear to me.
Comment: Sorry guys, i will edit this post with more clear explanation and reprodicible data.
Comment: Since this question has images of data, and not data in text format, it can be put on hold as needing a [mcve].
Answer: I am not sure if I fully understood your desired output. In the following, a solution that counts the binary occurrences of items per row and then sums up the (binary) co-occurrences of items over all rows. Is this what you were looking for?
The code might probably be written more elegantly and accelerated (e.g. by using data.table all the way through), but it's a start at least.
mat <- rbind(c(1,1,2,2), c(2,2,3,3), c(2,1,1,4))
#       [,1] [,2] [,3] [,4]
# [1,]    1    1    2    2
# [2,]    2    2    3    3
# [3,]    2    1    1    4

mat_tab_row <- apply(mat, 1, function(x) {

           items <- unique(x)
           data.frame(matrix(t(rep(1, length(items)))
                             , nrow = 1
                             , dimnames = list(1, items)))
})

# [[1]]
#    X1 X2
# 1  1  1
#
# [[2]]
#    X2 X3
# 1  1  1
#
# [[3]]
#    X2 X1 X4
# 1  1  1  1

library(data.table)
mat_tab <- as.matrix(rbindlist(mat_tab_row, fill = T))
mat_tab[ is.na(mat_tab)] <- 0
#      X1 X2 X3 X4
# [1,]  1  1  0  0
# [2,]  0  1  1  0
# [3,]  1  1  0  1

t(mat_tab) %*% mat_tab
#     X1 X2 X3 X4
# X1  2  2  0  1
# X2  2  3  1  1
# X3  0  1  1  0
# X4  1  1  0  1

Answer: In R, maybe try
n <- 5
set.seed(1)
(m <- matrix(sample(seq_len(n*2), n*n, T), ncol = n))
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    3    9    3    5   10
# [2,]    4   10    2    8    3
# [3,]    6    7    7   10    7
# [4,]   10    7    4    4    2
# [5,]    3    1    8    8    3
co <- tcrossprod(apply(m, 1, `%in%`, x=seq(1L, max(m))))
diag(co) <- 0L
co
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,]    0    0    1    0    0    0    0    1    0     0
# [2,]    0    0    1    2    0    0    1    1    0     2
# [3,]    1    1    0    1    1    0    0    2    1     2
# [4,]    0    2    1    0    0    0    1    1    0     2
# [5,]    0    0    1    0    0    0    0    0    1     1
# [6,]    0    0    0    0    0    0    1    0    0     1
# [7,]    0    1    0    1    0    1    0    0    0     2
# [8,]    1    1    2    1    0    0    0    0    0     1
# [9,]    0    0    1    0    1    0    0    0    0     1
#[10,]    0    2    2    2    1    1    2    1    1     0


General SLA Expectations and Maintenance for Standard Services

Question: What would generally be your expectation for SLA uptimes across the following services in a given month for a 'normal' scenario?
I'm including my expectations... the purpose of this question is to find out what the standard baseline should be in 2009 for setting SLA goals in an IT infrastructure. (Again, in a normal scenario - we're not talking Amazon or Google, but then again we're not talking Billy Bob's Web Site hosted on home DSL either.)

Power (100%)
Network / Core Routing / Switching (99.999%)
Static Files Hosting (99.99%)
Application Hosting [Single Server / DB] (99.95%)
E-Mail Hosting (99.95%)
Complex Application Hosting / Platform [Multiple Servers / DBs / Services] (99.9%)

(For reference... SLA Calculator)
And finally... How much maintenance time is acceptable within a month?
Answer: This will depend on a number of things:

Your business requirements?  Do you serve only your local area/timezone or are you truly global?
The cost of downtime?  What does an hour's downtime cost in terms of non-productive staff, lost web-site sales, reputation?
Your budget to achieve this?  As your requirements go up, so does the cost: from on-call & pager allowances and overtime to full time night shift staff, high-availability and/or redundant servers and software and backup sites.

As to acceptable maintenance, are we talking scheduled maintenance, or unscheduled downtime?
Which side of the agreement are you on?  If you're providing the service then it's in your interests to make it as easily achievable as possible while still meeting business requirements.


How do you pass a value to a custom envelop field using the the JS SDK?

Question: I am trying to figure out how to pass a value to the custom envelope field I have created. I am currently using the new JS SDK. I am able to pass a value to a custom field for my document but am unsure how to do this for an envelope custom field.
<code>data-powerform-fields="email@example.com&signer_acknowledgement=Read
and accepted." src="//developers.docusign.com/js/docusign.js"></script>

</code>
Answer: The Docusign engineering team has confirmed the issue. However, we don't anticipate that we can implement a solution immediately. Most likely we'll have a solution later in the beta for Docusign.js.
Answer: SDK is simply an API helper. Whatever is available in the API is converted to JS SDK
and for the moment JS SDK seems to be available only in beta: https://www.docusign.com/blog/developers/introducing-our-javascript-sdk-docusignjs


Cygwin: color coding and branch info for git?

Question: I just recently changed my client from Git Bash to Cygwin but I am missing color coding when I do git status for example and also the bash prompt doesn't include the current branch / rebase etc.
Does anyone know how to make Cygwin look like Git Bash?
Answer: It sounds like you just need to set up your .gitconfig for your cygwin shell to enable coloured output. Here is what I have in my ~/.gitconfig file (with which I get coloured markup in the output):
[color]
        diff = auto
        status = auto
        branch = auto
        interactive = auto
        ui = true
        pager = true

I think the most important line here is ui = true, which you can turn on straight from the command line if you wish:
git config --global color.ui true

Comment: great! that was it :-) but are you aware of how to change the prompt to include everything that is include in gitbash i.e. when you checkout a branch it shows the branch, also when rebasing etc?
Comment: Strange. I've loaded up Git Bash on my computer and its output is not in colour! The only thing I can recommend is to load up your original Git Bash (with colour) and type `cat ~/.gitconfig` to see what settings you are currently using. And then copy those to your cygwin's `.gitconfig`.
Answer: Answer by @lee-netherton is correct.
For those using Windows Git-126.96.36.199-preview20130201 - I had to create a ~/.bashrc to enable color output from git status.
[~/.bashrc]
TERM=cygwin
export TERM

Answer: Here is an example ~/.bashrc prompt that includes git branch:
get_git_branch() {
    git branch --show-current 2> /dev/null
}

PS1='\[\e[96m\]\w\[\e[0m\] \[\e[33m\]($(get_git_branch)) \[\e[0m\]\$ '

Result:
/current/dir (feature/branch) $


Onkeydown not working javascript

Question: Here is my code
document.onkeydown = function (a) {
    if (a.which == 13) {
        alert("Not Anymore");

    }
}

document.onkeydown = function (b) {
    if (b.which == 65) {
        auto();
    }
}

document.onkeydown = function (c) {
    if (c.which == 83) {
        auto2();

    }
}

Only the last snippet works can someone explain why this is happening
check my website and you can see it isnt working when you press a but when you press b it is
Thanks, I appreciate the help and feedback
Comment: The event handlers are overriden by the last, so only the last works
Comment: [`document.addEventListener(`…`);`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) would be another option.
Answer: You're binding the same event on the document multiple times. So, the later event handlers override the previous event handlers just like the functions with same name does. You need to bind only one event handler and use if... else in it.
You can use this
document.onkeydown = function (e) {
    if (e.which == 13) {
        alert("Not Anymore");
    } else if (e.which == 65) {
        auto();
    } else if (e.which == 83) {
        auto2();
    }
};

Also, use addEventListener instead of onkeydown.
document.addEventListener('keydown', function (a) {
    if (a.which == 13) {}
    ...
}, false);

Comment: To expand on this, nowadays its a common best practice to use event listeners; document.addEventListener('keydown', function(e){})
Comment: @DuncanMilrad You're welcome! If your problem is solved, kindly accept the answer

Onkeydown not working javascript


What angle results in the shortest route across a river?

Question: Take a river $100m$ wide flowing at $10m/s$ ($x$-axis). Take a boat which can go at $8.0m/s$. Clearly this boat cannot go straight across the river without being dragged some distance downstream. What angle $\alpha$ ( relative to the negative $x$-axis) should the boatsperson steer in order to minimise the resultant displacement downstream, ie: maximise the angle $\beta$ (relative to the positive $x$-axis) ?
All velocities are in $ms^{-1}$.
Velocity of river: $$\vec{V}_r=10\vec{i}+0\vec{j}$$
Velocity of boat:  $$\vec{V}_b=(-8.0\cos\alpha)\vec{i}+(8.0\sin\alpha)\vec{j}$$
Relative velocity of boat: $$\vec{V}_R=(10-8.0\cos\alpha)\vec{i}+(8.0\sin\alpha)\vec{j}$$
Direction of $\vec{V}_R$: $$\tan\beta=\frac{8.0\sin\alpha}{10-8.0\cos\alpha}$$
So assuming this equation correctly relates $\alpha$ to $\beta$ for given velocities for the river and the boat, what angle of $\alpha$ gives a maximum value for $\beta$ ?
My thoughts are that one should get and expression for $\beta$ in terms of $\alpha$. Differentiate to get $\frac{d\beta}{d\alpha}$. Then solve for $\beta$ where $\frac{d\beta}{d\alpha}=0$. But I am not sure how to differentiate such an expression. Where does one go from here ?
Comment: @user247327 No, the fastest route is **not** the shortest route, and this question is clearly about the shortest route - the one which results in least downstream displacement.
Comment: By the way, you say "shortest route" when you really mean "fastest route".
Answer: It's clear that $\beta<\pi/2$ because boat cannot go "upstream" or straight across. So $0<\beta<\pi/2$. Now in this range $\tan$ incerases as $\beta$ increases, so to maximize $\beta$ it's enough to maximize $\tan \beta$. Now you can just compute $\frac{d\tan\beta}{d\alpha}$ using quotien rule or whatever you need and find the root.
Actually, resulting derivative has rather nice numerator and you probably get $\cos \alpha = 4/5$ for maximum $\beta$
Answer: To minimise the resultant downstream displacement, the velocity of the boat (relative to the fixed bank) must be perpendicular to the relative velocity, i.e. the velocity of the boat relative to the water.
Therefore you draw a right-angled triangle with the velocity of the water ($10$) as the hypotenuse. The other two sides are $8$, the speed of the boat relative to the water, and $6$ which is the actual observed speed of the boat.
The required direction of motion relative to the negative $x$ axis is therefore given by $$\cos \alpha=\frac{8}{10}=\frac 45$$
Comment: Intuitively attractive, but you need to justify why perpendicular. Also you mean the absolute velocity relative to the bank (or equivalently the river bed), not the velocity relative to the water, which is all produced by the boatman and cannot be perpendicular to itself.
Comment: @Joffan: this is a well-known result and not guess-work on my part.  The boatman steers in a direction which will be perpendicular to his resultant velocity.
Comment: I wasn't suggesting it was guesswork, I just think it needs justification, given that it is the more interesting part of your answer rather than the subsequent trig.
Comment: I also would like to understand why this angle is 90 degrees. It might explain why I am having trouble with a similar question: https://mathoverflow.net/questions/393801/how-to-calculate-distance-of-shortest-path-when-there-is-a-flow-in-the-river


All England wins for Lee Chong Wei?

Question: How many times has Lee Chong Wei won the men's singles in the All England Badminton Championships?
Answer: Lee Chong Wei just won his third championship against Chen Long:

BWF broadcast of the MSF

Reference:

List of All England Men's Singles champions

All England wins for Lee Chong Wei?


I added space to a kvm img file but the physical extents do not show up in lvm

Question: I ran qemu-img resize kick.img +12G and thought I'd see some free physical extents when running pvdisplay but nope.
When I run virt-filesystems --long --parts --blkdevs -h -a kick.img
I see the space was allocated in some sense:
Name       Type       MBR  Size  Parent
/dev/sda1  partition  83   500M  /dev/sda
/dev/sda2  partition  8e   8.5G  /dev/sda
/dev/sda   device     -    21G   -

So ho can I add that 12G to sda2? Do I need to convert the img to a qcow?
Thanks.
Answer: When you extend your virtual disk, you need to do couple of changes to be visible.
First, if you have done an online resize, you need to rescan the device:
for i in /sys/class/scsi_device/*; do echo 1 > $i/device/rescan ; done

Now, you will see your block device with new size.
After that, if you have partitioned your drive, you have to extend partitions. That will sometimes require you to delete existing partition, recreate it with larger boundaries and then reboot VM.
fdisk /dev/sda
Command (? for help): d
Partition number (1-4): 2
...

If you use LVM, you will need to resize PV after your kernel has recognized new size of the partition/block device. This step is pretty easy to do (and is done online):
pvresize /dev/sda2

Now, you need to resize your LV (also online) :)
lvresize -l +100%FREE /dev/VolGroup00/LogVol00

And final step to be able to use the free space is to resize the filesystem. Depending on the FS, you will either use xfs_grow or resize2fs. This step can also be done online.
resize2fs /dev/VolGroup00/LogVol00

Answer: The rescan would probably have helped but to be honest, I cheated. I booted the VM to gparted-live-0.22.0-1-amd64.iso and expanded the partition.
But I also needed to understand xfs_growfs.
I went, xfs_growfs -d / and that was it.
(I should have mentioned the file system type in the original post.)


Facebook API: allow my own website to access my profile, semi-permanently

Question: Essentially I want to have my blog grab wall photos, status updates, etc. from my facebook profile. I know how the Javascript sdk works: the user clicks on a special facebook button which then gives my website permissions, for some short duration. I'm using it to grab the display picture of people who post on my website to show next to their comments.
However, this is a somewhat different use case: I'll be the only one person giving permission to my website, and it will be for the long term (weeksish?). I can easily hack together a client-side authentication flow for myself to go and click on and accept, I was wondering if there was a better way to manage this sort of thing? Some backdoor where I, as a facebook user, can manually "give permission" to my website to do stuff.
EDIT: I looked through the app permissions management page on my facebook, and although I can remove app permissions and see what permissions they have and have been using, there is no way to add more permissions manually
Answer:
Create an app at https://developers.facebook.com/apps
Choose that app in the dropdown at the top right of the Graph API Explorer and get an access token from that app.
CLick 'Get access token' and give it whatever permissions you think you'll nee to access the data you want.
Accept the permissions
Copy/paste the generated access token into your code and you're done

If the token ever expires (e.g. you change password or your account is locked for security reasons) just generate a new token using the same steps
Comment: Yes, my answer was posted over two years ago; there have been many changes to the API since then - you'll now need to extend the access token to a long-lived token using the App ID and App Secret via this method: https://developers.facebook.com/docs/facebook-login/access-tokens/#refreshtokens

In general, starting with the documentation and looking at other resources only when you can't find the answer in the docs is probably a good idea
Comment: This is not currently a correct answer to the question. Following these steps to the letter results in an access token that expires in an hour.
Answer: https://developers.facebook.com/docs/reference/oldjavascript/FB.Connect.showPermissionDialog/
this shows how to use the showPermissionDialog method on FB Connect. I believe the permission you are looking for is offline_access.
Comment: I think I know how to do that. I was just wondering if there was any way to give my own site offline access with myself and manage it, rather than having to go through the normal workflow and make a special button for myself to click =D


Dúvida sobre o IF

Question: A função IF só funciona com Inteiros ou também funciona com String? Eu estava tentando criar um programa que perguntaria se você tem certeza que deseja criar a senha. Você pode verificar o código abaixo:
package com.programas.Verificacao2;
import java.util.Scanner;

public class VoceTemCertezaVerifi {
    public static void main(String[] args) {

     int campo1 = 0, campo2 = 0;
     int sim = 0, não = 0;

     String s = "sim";

    Scanner in = new Scanner(System.in);

      System.out.println("Digite Sua Senha:");
      campo1 = in.nextInt();

      System.out.println("Digite novamente sua senha:");
      campo2 = in.nextInt();

      System.out.println("Você tem certeza?");
      s = in.nextLine();

      if(s == sim) {System.out.println("Senha Criada.");}else{
          if(s == não) {System.out.println("Ação Cancelada");
      }

    }
}
}

Comment: Acho que responde => http://pt.stackoverflow.com/q/34562/91
Answer: Para comparar string, use equals:
String opcao = "sim";

  if(opcao.equals("sim")){
   System.out.println("Senha Criada.");
  else{
    System.out.println("Ação Cancelada");
  }

Pelo código postado, você pode alterar a validação para que receba uma String, depois basta comparar usando o exemplo acima:
public static void main (String[] args) {

     int campo1 = 0, campo2 = 0;
     String confirmacao;
     Scanner in = new Scanner(System.in);

      System.out.println("Digite Sua Senha:");
      campo1 = in.nextInt();

      System.out.println("Digite novamente sua senha:");
      campo2 = in.nextInt();

      System.out.println("Você tem certeza?(Digite sim ou nao)");
      confirmacao = in.next();

  if(confirmacao.equals("sim")) {
    System.out.println("Senha Criada.");
    }else{
          System.out.println("Ação Cancelada");
      }
    }

Outra alternativa é usar switch, assim se a pessoa não digitar nada e der enter, é possível exibir uma mensagem diferente:
public static void main(String[] args) {

        int campo1 = 0, campo2 = 0;
        String confirmacao;
        Scanner in = new Scanner(System.in);

        System.out.println("Digite Sua Senha:");
        campo1 = in.nextInt();

        System.out.println("Digite novamente sua senha:");
        campo2 = in.nextInt();

        System.out.println("Você tem certeza?(Digite sim ou nao)");
        confirmacao = in.next();

        switch (confirmacao) {
            case "sim":
                System.out.println("Senha Criada.");
                break;
            case "nao":
                System.out.println("Ação Cancelada");
                break;
            default:
                System.out.println("Opção digitada inválida");
        }

Comment: Eu devo ter clicado sem querer no -1, eu já retirei, a sua respsta foi completa
Comment: Acho que faltou coisa sim na resposta, e você pode complementa-la Diego: o principal problema do código na questão não é a comparação com `==`  (que é uma comparação válida de string em quase todas as linguagens de alto-nível populares) - mas sim, o fato de o "sim" e o "nao"  do código na pergunta estarem sem aspas. Com isso eles são tratados como nomes de variáveis, não como texto. (eu sei que você sabe disso - só estou pedindo para colocar na resposta)
Comment: :-)  agora está legal.
Comment: obrigado pela resposta rapida.
Comment: @DanielT Disponha :D Caso a resposta tenha ajudado a esclarecer sua dúvida, não esqueça de marcar como aceita, clicando no `v` logo abaixo do contador a esquerda.
Comment: Gostaria de saber porque o -1. Se faltou algo na resposta, sem saber o que foi, não vou conseguir melhorar.
Comment: @DanielT sem problemas :)
Comment: @jsbueno pior que ele tratou como int, e nem havia percebido, para mim, eram variaveis de string sim e nao. Mas é válida a sugestão. vou editar a resposta com base no código dele.
Comment: @jsbueno ficou boa agora?
Comment: Já resolvi meu problema,

Dúvida sobre o IF


Why jQuery .submit is not working?

Question: I tried for almost an hour to figure out how to perform some validation before submitting the form. My form is like this:
<!doctype html>

<title>sample</title>

  <form id="myform">
   <input id="foo" value="Change me and press enter"/>
   <input type="submit" />
  </form>

It is not working in IE, Chrome FF :-(
I must be doing something terribly wrong, but what?
EDIT
Working sample:
<!doctype html>

<title>sample</title>

<form id="myform">
    <input id="foo" value="Change me and press enter"/>
    <input type="submit" />
</form>

Comment: Your alert text is wrong. When it tells you "it is not working", it actually means "it is working".
Comment: We need to find a head question for these too-localised "trying to use a DOM element before it exists" questions.
Comment: @TomalakGeret'kal HA B-)
Comment: Define "it is not working."  (Which seems to be a poor choice for the alert text, since if the text displays then that means the JavaScript _is_ firing.)
Comment: @TomalakGeret'kal ahh but which one?
Comment: Ohh, right.. he's missing the dom ready wrapper
Answer: Wrap it in the ready function:
$(function(){
   $("#myform").submit(function() {
      alert("THIS IS WORKING!!!!!!");
      return false;
   });
});

You need to wrap it in the ready function because where your function is now, the DOM element #myForm does not exist, so you are attaching the handler to a non existent element.
The ready function waits for the DOM to load and then runs everything inside of the ready fintion.
Comment: @TomalakGeret'kal added an explanation :-P
Comment: @Neal: Bah, and now my wit is moot!
Comment: @TomalakGeret'kal its still there ^_^ just in a little lesser of a form :-D

Why jQuery .submit is not working?


Solving a recursion (probability related)

Question: I want to solve the following: $$
\begin{align*}
    G_{T_t}(s) &= s\cdot G_X(G_{T_{t-1}}(s)) \\
 G_{T_{t-1}}(s) &= s\cdot G_X(G_{T_{t-2}}(s)) \\
 &\vdots \\
 G_{T_0}(s) &= s \\
 \implies G_{T_t}(s) &= s\cdot G_X(s\cdot G_X(\cdots s\cdot G_X(s)))
\end{align*}$$
$G_X(s) = \mathbb{P}(X = 0) + s^2\cdot\mathbb{P}(X = 2) = 1-p + ps^2$.
My goal is to find the result of the above recursion if we iterate it infinitely, i.e. $t\to\infty$ and the result should be the following: $$
G_T(s) = \frac{1 - \sqrt{1 - 4p(1-p)s^{2}}}{2ps}.$$
Maybe someone already realised that $X$ is a Bernoulli kindish random variable, but it takes value $2$ with probability $p$. And $G_X(s)$ is a probability generating function of $X$.
I appreciate your help in advance.
Answer: I'll slightly simplify the notation and forget what the expressions come from:
$$g(s) = 1 - p + ps^2$$
and $f_0(s) = s$,
$$f_{n + 1}(s) = sg(f_n(s)).$$
A bit informally (requiring further justification), we can look for a function $f = \lim_{n\to\infty}f_n$ as the solution to
$$f(s) = sg(f(s)).$$
Intuitively, the sequence tends to stabilization. Writing this out, we get
$$f(s) = s(1 - p + pf(s)^2) = spf(s)^2 - ps + s.$$
This is a quadratic equation in $f(s)$, whose solution (one of whose solutions) is the expression in the coefficients that you are looking for.


Connect to Database from Apigee

Question: Can anyone let me know if it is possible to connect to a Microsoft database from Apigee oncloud? We have a requirement to perform get and post operations from the database.
I tried to search it on internet, but did not get any information.
Thanks in advance
Answer: It depends on your license, since you might be able to use Java for this, but this requires a Developer license:
http://apigee.com/docs/developer-vs-edge
My best bet would be to add a thin API layer on top of your database for the CRUD operations. Probably a good idea as well to decrease the latency as much as possible or perform an async operation (if possible) towards the database API. From an architectural point of view the MSSQL database should be 'close' to your backend systems, while your API should be pointing 'outside'. Ensure to secure the connection between your Apigee layer and your Database API layer (firewall, SSL).
Hope this helps.

Connect to Database from Apigee


question about tree

Question: i have question for example i   want to implement   binary tree with array    i want understand what will  indexes for left child and rigth child  ?my array is 0 based  i want implement   searching in tree using array  can anybody help me?
Answer: left child = parent * 2 + 1
right child = parent * 2 + 2
I imagine this is homework so I will let you figure out the searching algorithm.
Answer: To implement a binary tree as an array you put the left child for node i at 2*i+1 and the right child at 2*i+2.
So for instance, having 6 nodes here's the indices of the corresponding array
          0
          |
      ---------
      |       |
   ---1--   --2--
   |     |  |    |
   3     4  5    6

Answer: I think you are looking for a heap. Or at least, you use a tree when an array structure is not enough for your needs so you can try to implement a tree inside an array but it wouldn't make much sense since every node contains references to its children without any need of indices.
But an heap is an array that can also be seen as a binary tree, look it out here. It's a tree in the sense that it organizes data as a tree but without having direct references to the children, they can be inferred from the position.
Comment: Why would it be extremely inefficient?
Comment: I think you're confused. A heap is a tree where the value of each child is less than (for a max-heap) or more than (for a min-heap) the value of its parent. This has nothing to do with whether a tree is implemented using an array or linked nodes.
Comment: Of course it is so. I didn't say that a heap didn't have any kind of additional constraint. The fact is that usually you don't use an array to store a binary tree unless it's a specific type of binary tree (that is why I mentioned the heap). How useful would be to use an array to store a generic binary tree? Operations would be extremely unefficient compared to an implementation that used references..
Comment: Because a rearrangment in the tree (think about a rotation: http://en.wikipedia.org/wiki/Tree_rotation) will imply moving many items instead that just changing some references..

question about tree


Archived app crashes only on iOS 5.1 not on 5.0

Question: I have archived my app and given for testing.
when i run this app , I dont find any crash on ios5 Version.( i dont have 5.1 device)
But my client has 5.1 version, when he tried he got crash when tapping on some button inside the app.
So i have asked him the crash report which look as below
Date/Time:       2012-04-23 12:54:10.320 +1000
OS Version:      iPhone OS 5.1 (9B179)
Report Version:  104

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x00000000, 0x00000000
Crashed Thread:  0

Last Exception Backtrace:
(0x3788488f 0x35d8a259 0x37884789 0x378847ab 0x38037a1b 0x9451 0x2493b 0x33f69e33 0x33f76391 0x33f76201 0x33f760e7 0x33f75969 0x33f756ab 0x33f69ca7 0x33f6997d 0xb397 0xc21f 0x3408f3cb 0x377de3fd 0x33f4bfaf 0x33f4bf6b 0x33f4bf49 0x33f4bcb9 0x33f4c5f1 0x33f4aad3 0x33f4a4c1 0x33f3083d 0x33f300e3 0x326e822b 0x37858523 0x378584c5 0x37857313 0x377da4a5 0x377da36d 0x326e7439 0x33f5ee7d 0x25f7 0x25b0)

    Thread 0 name:  Dispatch queue: com.apple.main-thread
    Thread 0 Crashed:
    0   libsystem_kernel.dylib          0x35d0332c 0x35cf2000 + 70444
    1   libsystem_c.dylib               0x31e51208 0x31e04000 + 315912
    2   libsystem_c.dylib               0x31e4a298 0x31e04000 + 287384
    3   libc++abi.dylib                 0x35456f64 0x35450000 + 28516
    4   libc++abi.dylib                 0x35454346 0x35450000 + 17222
    5   libobjc.A.dylib                 0x35d8a350 0x35d81000 + 37712
    6   libc++abi.dylib                 0x354543be 0x35450000 + 17342
    7   libc++abi.dylib                 0x3545444a 0x35450000 + 17482
    8   libc++abi.dylib                 0x3545581e 0x35450000 + 22558
    9   libobjc.A.dylib                 0x35d8a2a2 0x35d81000 + 37538
    10  CoreFoundation                  0x377da506 0x377cb000 + 62726
    11  CoreFoundation                  0x377da366 0x377cb000 + 62310
    12  GraphicsServices                0x326e7432 0x326e3000 + 17458
    13  UIKit                           0x33f5ee76 0x33f2d000 + 204406
    14  MyApp                           0x000025f0 0x1000 + 5616
    15  MyApp                           0x000025a8 0x1000 + 5544

When i do debug the crash report in terminal,

armv7 0x000025f0 main (in MyApp) (main.m:14)
armv7 0x000025a8 start (in MyApp) + 32

But i am not sure what it describes , please let me know that what it explains
Thanks a lot for your help.
Comment: The only solution is to execute it on a 5.1 simulator or device and look how it works, I noticed that every time Apple release a new version of iOS I have to change something in my code (not much) in order to use it.
Answer: SIGABRT is the most generic type of crash. If you are running say an iPhone 3gs and your client is using a newer iPhone 4/4s for example you could be compiling for different architectures (Armv6/7) make sure its set to Armv6 in that case and it also looks like one of the methods you are using may be deprecated. Look for code in main.m. There are a lot of instances where you have to use iOS version difference code (but most of it is for iOS4/iOS5)
Comment: Thank you for the reply. can you please tell me what i need to do now.
Answer: I had the same problem, I was using core data in my app, so if you are using core data, maybe this answer will help you, I fixed mine by changing the persistentStoreCoordinator store code.
    ....
    - (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

        if (persistentStoreCoordinator != nil) {
            return persistentStoreCoordinator;
        }

        NSURL *storeUrl = [NSURL fileURLWithPath:[[self applicationDocumentsDirectory] stringByAppendingFormat:@"yourdb.sqlite"]] ;
    ....

Check this line
NSURL *storeUrl = [NSURL fileURLWithPath:[[self applicationDocumentsDirectory] stringByAppendingFormat:@"yourdb.sqlite"]] ;

Changed the above line to
NSURL *storeUrl = [NSURL fileURLWithPath:[[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"yourdb.sqlite"]] ;

This just solved my problem.


Only bulleted list shown when using 'simplexml_load_file()' in PHP to read RSS Feeds

Question: I only see bulleted list on a page when loading this script to read RSS feeds. What am I not doing right?

<title>RSS Feed Test</title>

<?php
    function fetchFeeds($url){
    $feed = simplexml_load_file($url);
    echo "
";
    foreach($feed->channel->item as $itementry){
    echo "
link' title='$itementry->title'.$itementry->title"."
";
    }
    echo "
";
    }
    echo fetchFeeds("http://rss.cnn.com/rss/cnn_topstories.rss");
    ?>

Comment: http://www.cnn.com/services/rss/ page is not `XML`, it's `HTML`. Try `RSS Readers` in http://www.cnn.com/services/rss/ page like `Top Stories` linked `http://rss.cnn.com/rss/edition.rss`
Comment: just like bora has said, its the homepage of all rss feeds, you need to pick/choose which rss you want in the table
Comment: When I do that, I only see bullet points on my page and no feeds fetched. I have corrected the link pointing to RSS feed page for top stories on CNN. Test that and see what it displays
Comment: @Bora, I have edited the code and the description of the problem, please check back and advise.
Answer: First off, you are not calling the proper rss url. That is just the homepage of the RSS feeds. You need to select one first. In this example, Top Stories is selected. Consider this example:
<?php

// top stories RSS
$rss_url = 'http://rss.cnn.com/rss/edition.rss';
$xml = simplexml_load_file($rss_url);
$title = (string) $xml->channel->title; // typecast the title
$items = array();
for($i = 0, $size = count($xml->channel->item); $i < $size; $i++) {
    // also one way to extract is to convert it to this
    // each item will become an array
    $items[] = json_decode(json_encode($xml->channel->item[$i]), true);
}

?>

<?php echo $title; ?>

<?php foreach($items as $key => $value): ?>

<?php echo $value['title']; ?>

<a href="<?php echo $value['link']; ?>"><?php echo $value['link']; ?>

<?php echo $value['description']; ?>

<?php echo $value['pubDate']; ?>

<?php endforeach; ?>

Sample Output


Multiple comparisons in the process of finding the best-fit curve

Question: I've often seen the following approach to how people report parameters of best-fit curves: a correlation between X and Y is weak and/or non-significant, so because the data points seem to be placed on what appears to be a parabola, try a 2nd-order polynomial fit, and report those params if the fit is good enough.
I just wonder if it is correct for the curve type to be eye-balled and its parameters then computed. Isn't there a problem of multiple comparisons also apparent? Is there a systematic way to find the curve of best fit, one that eliminates the subjective "hunch" element, or is that element actually desirable?
Answer: There are a lot of issues here. The first two, and certainly not the least, are that higher-order polynomials will always fit at least as well as lower-order polynomials, and that data that lies perfectly on a parabola can still be significantly linearly correlated. These are some of many reasons that model fit alone is not a good model-selection criterion, and nor is correlation. Better methods of model selection include AIC, cross-validated prediction error, and Bayes factors. Which to use depends in part on what you want the model to do, because different purposes call for different models.
Comment: "So even if one did a good job at eye-balling what the best-fit line would be from the first attempt (e.g, a 3rd-order polynomial)" — A 3rd-order polynomial will always fit better than a parabola, and a parabola will always fit better than a line. That's what I meant by "higher-order polynomials will always fit at least as well as lower-order polynomials". So, if you use model fit as your criterion to decide whether a model is good, you'll always think that higher-order polynomials are better.
Comment: Because a straight line is also a parabola: the models are nested. For a set of perfectly collinear points, the parabola will fit equally as well as a line rather than strictly better, but of course, real data is never perfectly collinear.
Comment: Just to make I understand your proposed answer. So even if one did a good job at eye-balling what the best-fit line would be from the first attempt (e.g, a 3rd-order polynomial), and finds that curve to fit well, this is still not the best to do it? Is it because doing the fit is itself one way of doing model selection, and model selection should instead be done with those other methods you mention?
Comment: Is that really true that N-poly always beats (N-1)-poly? If you have data points almost perfectly alligned on a line, how could a parabolic shape fit better than the straight line that connects these dots?


How to apply HMM for each class separately in R?

Question: I am using depmixs4 package in R to apply HMM for a classification problem. My response variable is binary. I should train HMM for each class separately. I split the data set into two data sets one for each class.
y is a binary variable, and in the first split dataset, its value is  1.
I run the code below but it gives error
msp <- depmix(y~1,nstates=2,data=test)
set.seed(1)
fmsp <- fit(msp)
Error in em.depmix(object = object, maxit = emcontrol$maxit, tol = emcontrol$tol,  :
  likelihood decreased on iteration 1

I would appreciate if anybody can tell me how to resolve this issue.
Answer: Without the data, it is difficult to see what is the problem. You could try running the estimation with different random seeds. Do you always have this problem? depmixS4 uses the EM algorithm by default, but you could also try to use a numerical optimizer:
fmsp <- fit(msp, method="rsolnp")

to see whether this works. But that the likelihood went down on the first iteration of EM makes me think that there could be issues in the data or model specification.


kubernetes ingress on GKE timeout and 502 during deployment

Question: I'm having a hard time figure out why ingress on GKE returns 502 errors and timeout during a deployment on a project.
To better understand the issue, I have setup a basic hello application which takes the same workflow.
Here is the complete manifest:
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: helloapp
  labels:
    app: helloapp
spec:
  replicas: 3
  template:
    metadata:
      labels:
        app: helloapp
    spec:
      containers:
      - name: helloapp
        image: gcr.io/${GCLOUD_PROJECT_ID}/helloapp:${HELLOAPP_VERSION}
        imagePullPolicy: Always
        ports:
        - name: http-server
          containerPort: 8080

        readinessProbe:
          httpGet:
            path: /sys/health
            port: 8080

        livenessProbe:
          httpGet:
            path: /sys/health
            port: 8080

---

apiVersion: v1
kind: Service
metadata:
  name: helloapp
  labels:
    app: helloapp
spec:
  type: NodePort
  externalTrafficPolicy: Local
  ports:
    - port: 80
      targetPort: http-server
  selector:
    app: helloapp

---

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: helloapp-http
spec:
  backend:
    serviceName: helloapp
    servicePort: 80

which contains an ingress, a service and customized probe for the pods.
The application is dead simple hello world application written in Go.
During a deployment, if I siege the ingress healthcheck of my application and I notice:
HTTP/1.1 502     9.02 secs:     332 bytes ==> GET  /sys/health
HTTP/1.1 502     9.10 secs:     332 bytes ==> GET  /sys/health
HTTP/1.1 200     4.70 secs:     473 bytes ==> GET  /sys/health
HTTP/1.1 200     4.56 secs:     475 bytes ==> GET  /sys/health
HTTP/1.1 200     0.01 secs:     475 bytes ==> GET  /sys/health
HTTP/1.1 200     0.01 secs:     476 bytes ==> GET  /sys/health
HTTP/1.1 200     0.03 secs:     475 bytes ==> GET  /sys/health
HTTP/1.1 200     0.01 secs:     474 bytes ==> GET  /sys/health
HTTP/1.1 200     4.58 secs:     475 bytes ==> GET  /sys/health
HTTP/1.1 200     4.51 secs:     474 bytes ==> GET  /sys/health
HTTP/1.1 200     0.01 secs:     475 bytes ==> GET  /sys/health
HTTP/1.1 200     0.01 secs:     475 bytes ==> GET  /sys/health
HTTP/1.1 200     4.83 secs:     474 bytes ==> GET  /sys/health
HTTP/1.1 502     9.07 secs:     332 bytes ==> GET  /sys/health
HTTP/1.1 200     0.02 secs:     475 bytes ==> GET  /sys/health

After a few minutes (generally 5-10), it stops and forwards the requests correctly.
Cluster information:

Kubernetes version: 1.8.8
Google cloud platform
g1-small
Answer: All is fine with your configs.  Looks like you have a problem during  your go-app starting: round-robing on your service is sending some requests to the non-started app in the pod, and that causes error with code 502.
How long does your app start  in the pod? You may add  initialDelaySeconds  to fix your error.
spec:
  replicas: 3
  template:
    metadata:
      labels:
        app: helloapp
    spec:
      containers:
      - name: helloapp
        image: gcr.io/${GCLOUD_PROJECT_ID}/helloapp:${HELLOAPP_VERSION}
        imagePullPolicy: Always
        ports:
        - name: http-server
          containerPort: 8080

        readinessProbe:
          httpGet:
            path: /sys/health
            port: 8080
            initialDelaySeconds: 60

        livenessProbe:
          httpGet:
            path: /sys/health
            port: 8080
            initialDelaySeconds: 120

Comment: Thank you for you answer, I will try the `initialDelaySeconds`. The application is starting really fast (since it's just an hello world written in Go). One another thing I have noticed if I exposed directly the service as `LoadBalancer` I do not have the `502` errors during a deployment it seems really related to an issue in the ingress.
Comment: If you want to use Ingress try to use type `Cluster IP` for you service. When you use `NodePort`  some request cant be proceed because firewall issue.
Comment: still can't get this to work, even the service doesn't do its job with a `type: LoadBalancer`, I have updated the [manifest](https://github.com/ulule/helloapp/blob/master/scripts/kubernetes/manifests.yml) with a `rollingUpdate` strategy.
Comment: Could you check the firewall between nodes may one of your nodes can not response to request?
Comment: how do you check the firewall?


Problem with calculating $R^2$

Question: I believe I have rather simple question but I would like to make it right.
I have already asked question, however I am not sure whether I did everything correct or there is a mistake in the answer (probably the first one, but still I cannot find it).
To make it short:
I would like to check how well my model predicts outcome of a game between two players - and that is why I am trying to calculate R^2. What I have done is based on  this answer.
Firstly, I calculate ESS:
ess = 0
for each game in my database:
   ess += (predictedOutcome - realOutcome)^2

The real outcome is either 1 (if win), 0.5 (if draw) or 0 (if lose). To calculate what was the average real outcome, I do:
 averageRealOutcome = (wins + 1/2*draws)/(wins + draws + loses)

The result is always about 0.5
And then for each game I do a loop
tss = 0;
for each win
   tss += (1 - averageRealOutcome)^2
for each draw
   tss += (0.5 - averageRealOutcome)^2
for each lose
   tss += (averageRealOutcome)^2

Then, once more according to the previous answer, I try to calculate R^2:
R^2 = ESS/TSS

Unfortunately the value that I get is above 1, while I believe it should be between 0 (very bad) to 1 (cool). Adjusting R^2 does not do the trick and i can see no difference at all.

Does it in general make sense what I try to do?
If it does, where is my mistake? Or maybe my interpretation is bad? If not, can you provide and resources where I can read what should I do?
Comment: Note that this is not an $R^2$ because your "TSS" is not the (usual) total sum of squares, nor is it even a reduced sum of squares.
Comment: sorry, I was confused myself about your notation, so I removed my answer. I don't like R2 anyway :-)
Comment: @Nick apologizes if I do not follow standards, thanks for spending your time and writing it though!
Comment: anyone? should I rephrase the question?
Comment: We don't create new questions to address ones that are unanswered: please just edit your old one.
Comment: @whuber I am not sure how to edit it. I believe that everything is important. According to what you said, does it mean that I cannot use R2 in my case, or I do it wrong?
Comment: There will be a set of links below the question that include, at a minimum, "link edit flag".  Click on "edit".
Comment: @whuber I meant i do not know what should be edited form of the question, not that I do not know where I can find this option :) I have already edited it many times to make it as clear as possible and not sure how to make further improvements
Comment: Sorry about the misunderstanding.  The description of what you're doing is opaque.  Moreover, the code shown is not executable and, as pseudocode, is incomplete and ambiguous.  More precision in describing what you're doing, together with a representative sample of your data, might clarify things and inspire someone to offer some insight.
Answer:
See http://en.wikipedia.org/wiki/Coefficient_of_determination
Be careful about notation. Use tot, reg, err.
From your first code snippet, ess is SS_err. But in the last code snippet, ESS is SS_reg.
The actual definition of R2 is 1 - SS_err / SS_tot.
If you use this definition and get R2 < 0, that's not a problem. R2 is only guaranteed to be between 0 and 1 for linear models.
Use this definition of R2 or a generalization of R2 (also in the Wikipedia article).
Comment: It's great to see you replying to questions, Jessica.  Welcome to our site!
Answer: Since in your predictive model the design is very like in discrete choice models within the case of binary response variables (logistic regression for example would be relevant here), the problem could be approached in the same manner.
First of all you may consider the generalized $R^2$. Note the last suggestion to scale the $R^2$ by the $R^2_{max}$ that insures the modified coefficient is below $1$.
You may also consult the classical text book in econometrics (I used Greene Econometric Analysis Chapter 21.4.5, but a link from SAS help page seems also relevant) regarding the goodness-of-fit for binary response models:

McFadden's likelihood ratio index $LRI = 1 - \frac{\log L(\theta)}{\log L(0)}$ the coefficient is pointed to have no clear interpretation though, but this one is a common build-in solution in most of the statistical software
Another interesting suggestion is to look either on the average probability of correct predictions as in Ben-Akiva and Lerman: $R^2_{BL} = 1/n \sum_i (y_i \hat F_i - (1- y_i)\hat F_i)$, where $\hat F_i$ is the estimated probability (the estimated value you use to compare with the threshold $0.5$).
In unbalanced samples when the number of wins is much different from the number of losses the $R^2_{BL}$ underestimates the smaller group, so you may introduce a measure that compares average correct and incorrect cases $\lambda = (average \hat F_i | y_i = 1) - (average \hat F_i | y_i = 0)$ Cramer's $\lambda$ heavily penalizes incorrect answers.
Note that for the unbalanced datasets it is recommended to be cautious about the naive threshold value of $0.5$ since in that case a smaller group risks to be unpredicted too often.
The other suggestions for the $R^2$ augmentation are in the abovementioned SAS help page (to be frank, I have never used one thus has no clear opinion regarding them, but the Cragh-Uhler 1 is exactly the generalized coefficient of determination from the wiki page).

Problem with calculating $R^2$


New activity from a button in navigationbar

Question: I'm having trouble in starting a new activity from a button in navigation bar.
The below line is creating an error.
<code>    Intent myIntent = new Intent(NavigationDrawerFragment.this, AddIntake.class);
</code>
Answer: Try the following::
<code>@Override
public void onNavigationDrawerItemSelected(int position) {
    switch(position) {
          case 0:
              startActivity(new Intent(this, AddIntake.class));
    }
}
</code>
Answer: Thanks but I've solved this using.
Intent myIntent = new Intent(getActivity(), AddIntake.class);


Prove that there exists complex numbers $a$ and $c$ such that $f(z)=ae^{cz}$.

Question: Let $f$ be an entire function such that $|f'(z)|\leq|f(z)|$ for all $z\in \mathbb{C}$. Prove that there exist complex numbers $a$ and $c$ such that $f(z)=ae^{cz}$ for all $z\in\mathbb{C}$.
My try: take $g(z)$ such that
$$
f(z)=e^{g(z)}.
$$
Then by chain rule
$$
f'(z)=e^{g(z)}g'(z).
$$
Now we have
$$
|g'(z)||f(z)|=|g'(z)||e^{g(z)}|=|f'(z)|\leq |f(z)|
$$
which implies
$$
|g'(z)|\leq 1.
$$
Thus $g(z)=cz$, and then $f(z)=e^{cz}$. However, how to make $g(z)$ is entire function? and where is the constant $a$?
Answer: You have to justify writing $f$ as $e^{g}$. Here is a correct solution: If $f \equiv 0$ we can take $a=0$ and $c=1$. Otherwise the zeros of $f$ form a set $\{z_n\}$ with no limit points. On $\mathbb C \setminus \{z_n\}$ we have $|\frac {f'(z)} {f(z)}| \leq 1$. This implies that $\frac {f'(z)} {f(z)}$ has a removable singularity at each $z_n$. Hence it extends to a bounded entire function. By Louiville's Theorem we have $\frac {f'(z)} {f(z)}=A$ for some constant $A$. Now observe that $(e^{-Az}f(z))'=0$ so $e^{-Az}f(z)=B$ for some constant $B$. Hence $f(z)=Be^{Az}$.
Answer: Note that $f$ has no zeros. In fact, if $a$ is a zero of $f$ of order $n\in\mathbb N$, then $a$ is a zero of $f'$ of order $n-1$. But then, near $a$, the inequality $\bigl\lvert f'(z)\bigr\rvert\leqslant\bigl\lvert f(z)\bigr\rvert$ means$$\bigl\lvert na_n(z-a)^{n-1}+(n+1)a_{n+1}(z-a)^n+\cdots\bigr\rvert\leqslant\bigl\lvert a_n(z-a)^n+a_{n+1}(z-a)^{n+1}+\cdots\bigr\rvert.$$Now, dividing both sides by $\bigl\lvert(z-a)^n\bigr\rvert$, you get that$$\bigl\lvert na_n(z-a)^{-1}+(n+1)a_{n+1}+\cdots\bigr\rvert\leqslant\bigl\lvert a_n+a_{n+1}(z-a)+\cdots\bigr\rvert,$$which is impossible, because the LHS tends to $+\infty$ when $z\to a$, whereas the RHS tends to $\lvert a_n\rvert$.
So, since $f$ has no zeros and $\mathbb C$ is simply connected, there is indeed an entire function $g$ such that $f=e^g$. You proved that $g'$ is bounded. Therefore, by Liouville's therem, it is constant. So there are constants $k$ and $c$ such that $(\forall z\in\mathbb{C}):g(z)=cz+k$ and therefore$$(\forall z\in\mathbb{C}):f(z)=e^{g(z)}=e^{cz+k}=e^ke^{cz}.$$


Load a custom style before the whole page is loaded

Question: I need to load different CSS files in contains different colors like a style switcher. and I want to load the color.css before DOM is loaded. I tried the window.onload but always I see default.css is loaded before.

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="keywords" content="">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Style switcher</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

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

    <link href="css/colors/default.css" id="theme" rel="stylesheet">

                          Test

Comment: `window.onload` means on window loaded
Comment: seealso https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload#Notes
Comment: @appleapple External style sheets don't affect DOM, so DOMContentLoaded does not wait for them. I found this here https://javascript.info/onload-ondomcontentloaded .
Answer: First of all you are trying to use jQuery before it is available, so that won't work.
Instead of changing the src of the link, you could just create a link tag dynamically with the correct source. I make use of an IIFE to make the function execute directly ones it's loaded
Here is a small snippet that creates a link tag with the correct CSS source, you can change the source the whatever you need.

Comment: thanks man. This is exactly what I need. I appreciate your help.


Is there any elementary function whose antiderivative contains an exact constant?

Question: Let's say we have $F(x) = \int{f(t)}\ dt$. Now it's obvious to me why $F$ is the class of functions whose derivative yields $f(x)$. However, I was curious if it is possible for the antiderivative to be something such as $F(x) = \tan(x)+5+C$ as an example. I can see how we would merge this to become just $F(x) = \tan(x) + C$ but I'm wondering if it is possible for an elementary antiderivative to contain a constant that the entire class of antiderivatives share. My feeling is that this would never happen but I can't seem to figure out exactly why.
Answer: No function at all has an antiderivative that contains an exact constant.  This is because if you add a constant to a function, no matter what it is, the function's derivative does not change, since $(f(x)+g(x))' = f'(x) + g'(x$) and the derivative of any constant is identically zero.


In basketball, what does 'two for fifteen' mean?

Question:
He was raggedy as... Went two for 15. Seven points.
  He finished with 16 points on six of 14.

I guess it is about points, but I really don't understand what they mean.
Could someone explain what these phrases mean?
Comment: Note: The [answer posted on ELL](https://ell.stackexchange.com/a/185412) includes the phrase "1st and 10," which has been [previously addressed here](https://sports.stackexchange.com/q/15092).
Comment: Not clear.  Could be the same players started poorly and finished a bit better.
Answer:
Went two for 15. Seven points.

This specific player made two field goals (FGM - field goals made) out of 15 attempts (FGA - field goals attempted) for a total of seven points (PTS).

He finished with 16 points on six of 14.

This specific player made six field goals (FGM - field goals made) out of 14 attempts (FGA - field goals attempted) for a total of 16 points (PTS).
Total field goals made/attempts include three point field goals made/attempts. Made free throws (FTM) also contribute to the number of points. These are possible reasons for discrepancies in point totals when reading such phrases.
I was not able to find the specific quote you highlight in your question, so I am attempting to break it down based on my interpretation. It doesn't make sense for a player to go 2 for 15 for 7 points AND 6 for 14 for 16 points without additional context (one player is being talked about across two separate games OR two separate players are being talked about in one game), so I chose the latter context to answer this question.


If $a_{1}=1$ and for n>1, $a_{n}=a_{n-1}+\frac{1}{a_{n-1}}$ , then $a_{246}$ lies between two integers, what are they?

Question: I tried to use the characteristic equation technique which basically led me to (n-2) roots.
what I did was put $a_n$ as $x^n$ and same for n-1. Taking $x^{(n-2)}$ led me to a higher degree polynomial. Then I resorted to python. I wrote a script so I could obtain the first n values for all integral inputs. The source code follows:
Python version 3
depth=input("enter depth : ")
depth=int(depth)
listis=[None]*depth
listis[0]=1

def f(n,listis):
    if n == 1:
        return 1
    else:
        listis[n-1]=listis[n-2]+1/listis[n-2]
        return listis[n-2]+1/listis[n-2]

import time
for i in range(depth):
    tt=time.time()
#    print ("The value of f(",i+1,") is ",f(i+1,listis))
#    print ("computed in ", time.time()-tt ," seconds")
    print (f(i+1,listis))

#print (listis[depth-1])

You can check the following graph as well https://www.desmos.com/calculator/mtepe4pdsg
I found out that it increases always and the first decimal places showcases a pattern which is very much visible when the units digit is 9.
Pattern is as follows:
9.031846164717614
9.142565499586983
9.25194398859482
9.36002938137635
9.466866652847923
9.572498224166102
9.676964161540262
9.780302355555111
9.882548683290779
9.983737155217133

I have tried numpy polyfit as well and it doesnt seem to fit.
The coefficients for degree(1 upto degree 10 are as follows):
[0.11199654 3.9178784 ]
[-7.92924950e-04  1.92081958e-01  2.55642626e+00]
[ 1.24263633e-05 -2.67551898e-03  2.68517761e-01  1.89714183e+00]
[-2.60256961e-07  6.49982694e-05 -6.10038906e-03  3.46286630e-01
  1.48684664e+00]
[ 6.40214942e-09 -1.87679969e-06  2.10497785e-04 -1.16532133e-02
  4.28025960e-01  1.19246775e+00]
[-1.74582869e-10  5.93007587e-08 -7.96069525e-06  5.40080166e-04
 -2.00822463e-02  5.15765103e-01  9.60398854e-01]
[ 5.10638718e-12 -1.97969074e-09  3.12182211e-07 -2.57784984e-05
  1.20066428e-03 -3.23214527e-02  6.11265933e-01  7.64857997e-01]
[-1.56810140e-13  6.84576839e-11 -1.24466422e-08  1.22180547e-06
 -7.02796874e-05  2.41588122e-03 -4.95017346e-02  7.16107540e-01
  5.91920008e-01]
[ 4.98123182e-15 -2.42078000e-12  4.99472539e-10 -5.70348627e-08
  3.94084176e-06 -1.69434350e-04  4.50932324e-03 -7.29491182e-02
  8.31706919e-01  4.33414958e-01]
[-1.61948602e-16  8.67652759e-14 -2.00502065e-11  2.61608664e-09
 -2.11920169e-07  1.10445757e-05 -3.71712108e-04  7.92828968e-03
 -1.04170633e-01  9.59323448e-01  2.84241128e-01]

Here the last terms are constant terms and as we go on left, the power increases.
To summarize :
I was not able to approximate the solution without a computational aid. I would like a more intuitive way to approximate it.
#Without any computational aid
$a_{246}$=22.236857105192666
Closed form for the sequence defined by $a_0=1$ and $a_{n+1} = a_n + a_n^{-1}$
Comment: Does this answer your question? [How to find range $a_{75}$ of the term of the series $a_n=a_{n-1}+ {1 \over {a_{n-1}}} $](https://math.stackexchange.com/questions/3599155/how-to-find-range-a-75-of-the-term-of-the-series-a-n-a-n-1-1-over-a).  If you look at the answers there, you should be able to show that $$22<a_{246}<23\,.$$
Comment: Looking at the formula, it reminds me of the iteration formula to calculate the square root of a number (Newton's formula) ... That should be a hint!
Comment: @Batominovski Yes, and this as well https://math.stackexchange.com/questions/29777/closed-form-for-the-sequence-defined-by-a-0-1-and-a-n1-a-n-a-n-1/29786#29786  found it in the link you provided. Also please note, the answer provided by mark-bennet is new and useful as well. question closed i guess
Answer: $a_n$ is increasing and suppose that $k\lt a_n\lt k+1$ then $a_n+\frac 1{k+1} \lt a_{n+1} \lt a_n+\frac 1k$ so there is a fair estimate to be made that there are either $k$ or $k+1$ elements with integer part $k$. Refining this should get you pretty close to a good-enough estimate.


Find a determinant of this matrix.

Question: I've got matrix
\begin{equation*}
A=\left(
\begin{array}{ccccccc}
a & 0 & 0 & \ldots & 0 & 0 & b \\
0 & a & 0 & \ldots & 0 & b & 0 \\
0 & 0 & a & \ldots & b & 0 & 0 \\
\ldots & \ldots & \ldots & \ldots \\
0 & 0 & b & \ldots & a & 0 & 0 \\
0 & b & 0 & \ldots & 0 & a & 0 \\
b & 0 & 0 & \ldots & 0 & 0 & a \\
\end{array}
\right)
\end{equation*}
оf $2n$ size (number columns and rows). I need to find it's determinant using a traditional formula:
$$\det A = \sum_{\sigma \in S_{2n}}{\text{sgn}(\sigma)\prod_{i=0}^{2n}{A_{i\sigma(i)}}}$$
Where $\text{sgn}(\sigma)$ is $(-1)^{inv(\sigma)}$, and $inv(\sigma)$ is the number of inversions in $\sigma$.
It's easy to see that non-null terms in will be if and only if $\sigma(i) \in \{i, 2n - i + 1\}$.
So, the answer for me looks like: $\text{sgn}(\sigma_1)a^{k_1}b^{2n - k_1} + \text{sgn}(\sigma_2)a^{k_2}b^{2n - k_2}\ldots$. (where each $sgn(\sigma_i)$ is $\pm1$).
But I have no idea how to expand this and count all $\sigma$'s.
Comment: foreach $i \le n$, group rows $i,2n+1-i$ and columns $i,2n+1-i$ together, you get a block-diagonal matrix with $2\times 2$ blocks: $[\begin{smallmatrix}a & b\\ b &a\end{smallmatrix}]$.
Answer: We have to focus on permutations $\sigma \in S_{2n}$ such that $\sigma(i) \in\{i, 2n-i+1\}$ for all $i \in \{1, \ldots, 2n\}$.
To uniquely determine such a permutation, we have to pick $k$ numbers out of $1, 2, \ldots, n$ which will be fixed points of $\sigma$. If $i$ is one of the remaining $n-k$ numbers, then set $\sigma(i)=2n-i+1$.
The action of $\sigma$ on $n+1, \ldots, 2n$ is now uniquely determined like this:
$$\sigma(i) = \begin{cases} 2n-i+1, &\quad\text{if }i \in \sigma(\{1,\ldots, n\}),\\
i,  &\quad\text{otherwise}.\\\end{cases}$$
To find the sign of $\sigma$, notice that $\sigma$ is a composition of $n-k$ transpositions $(i,  2n-i+1)$ each having sign $-1$ so $\operatorname{sgn}(\sigma) = (-1)^{n-k}$.
Now if $i$ is a fixed point of $\sigma$ then $A_{i\sigma(i)} = a$ and otherwise $A_{i\sigma(i)} = b$. Since $\sigma$ as above has $2k$ fixed points and $2n-2k$ other points, it yields the product $a^{2k}b^{2n-k}$ in the determinant formula.
All in all, we get
$$\det A = \sum_{\sigma \in S_{2n}} \operatorname{sgn}(\sigma) \prod_{i=1}^{2n} A_{i\sigma(i)} = \sum_{k=0}^{n}{n\choose k}(-1)^{n-k} a^{2k}b^{2n-2k} = (a^2-b^2)^n.$$
Answer: This is simply the value $(a^2-b^2)^n$
Comment: An answer without any sort of explanation isn't particularly helpful.

Find a determinant of this matrix.


How can I speed up MSDeploy?

Question: MSDeploy is excruciatingly slow.
As in, it has taken our build /deployment process from 3.8 minutes to 15.
Is there anyway to speed this up?  The publish method we are using is WMSVC.
Comment: How large is the deployment package? What providers are you including?
Comment: @RichardSzalay: About 10MB.  Not sure what you mean by what providers I'm including.
Comment: In the output log, does it look like it's deploying the entire site even though not much has changed? If so, see if the `useCheckSum` option mentioned in my answer helps.
Answer: Without knowing more about your configuration (which MSDeploy providers/settings your using), I can only provide vague advice.
If your deployment time has increased, it's possible that the files are having their last modified timestamps updated everytime. Since this is the default mechanism MSDeploy uses to determine whether the file should be uploaded, it would cause your entire application to be deployed everytime.
If that sounds right, you can switch to checksum-based syncing by specifying the <code>-useCheckSum</code> command line argument.
Comment: It's worth noting that i've seen a lot of deployment pipelines slow down by *using* *-usechecksum* so it might not always be the ultimate speed saver :-)

How can I speed up MSDeploy?


Transform array using JavaScript

Question: I have values in my array as:
var chartData=[["web",0],["file",2],["desktop",2],["laptop",17]]

I need to convert this array into
var chartData= [["Web","file","desktop","laptop"],[0,2,2,17]]

How to write proper JavaScript function for this conversion.
So far I have used a for loop:
 for (var i = 0; i < 5; i++)

        {
            for(j=0;j<i;j++)
            {
                chartData[i][j] = chartData[j][i];
            }
        }

Comment: What did you try so far?
Comment: add your code to question not in comments
Comment: Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Comment: gerado, yes I do have outer square bracket, also I have used for loopsfor (var i = 0; i < 5; i++)
            {
                for(j=0;j<i;j++)
                {
                    chartData[i][j] = chartData[j][i];
                }
            }
Comment: @DeepshikhaSharma, have a look to my answer.
Comment: Create two new empty arrays. Loop through your original array and get each of its elements. Each element is itself an array of two elements. Push one of those elements onto one of your new arrays, and the other element onto the other new array. When done with this loop, create another new array with two elements, each element being one of the two new arrays you just created.
Answer: This would do :
var chartData=[["web",0],["file",2],["desktop",2],["laptop",17]];

var outData = [];var a1Out = [];var a2Out=[];
for(i=0;i<chartData.length;i++){
var a1 = chartData[i][0];     //first array value
var a2 = chartData[i][1];     // second array value
    //save them in seperate arrays
    a1Out.push(a1);
    a2Out.push(a2);
}

outData.push(a1Out);
outData.push(a2Out);

console.log(outData); //final array

working fiddle
Answer: Check it out

const chartData = [["web",0],["file",2],["desktop",2],["laptop",17]];

function convert(array) {
  const length = array.reduce((a, b) => a.length > b.length ? a : b).length;
  const result = [];

  for (var i = 0; i < length; i++) {
    result[i] = array.map(el => el[i]);
  }

  return result;
}

console.log(convert(chartData));

Transform array using JavaScript


Is my project about migrants rights welcome here?

Question: I am volunteering in a French association helping migrant people who want to take their studies up again get through the administrative difficulties. Many volunteers are good-willing people but not experts, often lacking knowledge when it comes to giving advice (administration and legislation are complex matters, even for native people). More generally, having precise knowledge about migrants' rights, what they can do, and how to do it, is of great importance for anyone willing to help, as they can't necessarily access this knowledge themselves.
A resource on SE would be extremely useful for this purpose as it would centralize the precise knowledge that volunteers and migrants, who can access internet, could use. Questions would include:

Can I apply to college with/without a refugee status ?
How can I get this form ?
Can I be arrested if I go to this administration ?
Where can I learn French ?

I wondered if such a project could fit into SE policy and asked so on area 51, where I was redirected to this community and Law.
I saw indeed questions about refugees here (less specific though), but also that not everybody likes that. To my mind, bringing my project here could potentially cause two issues :

If this was to work, many non-expats people would come here to talk exclusively about legislation and administrative matters for migrant people, which could lead to a kind of entryism.
At least at the beginning, this will be nearly only about France (because people I would talk into coming here would be French).

I'm getting far ahead of what is reasonable to expect here: at this point, this is only my idea and it is very possible that my folks don't like it and never use SE. However, I find it good and will try to make it happen. If I was to succeed, would such a project be welcome here or would it be off-topic?
Answer: You or anybody can certainly ask these questions. But if you are wanting specific resources set aside just to handle matters regarding your topic, or to ask questions which clearly do not meet our guidelines, I don't think we will be very receptive or very useful.
For one thing, we just don't have a large enough number of volunteers (everybody here is also a volunteer) to manage and administer such a resource. Another thing is that technically, we don't actually own this website. It is owned and operated by a Stack Exchange Inc., a for-profit corporation. It would really be up to them to designate and set aside such resources, or make it possible for us to do so.
It is true that this website has become a de facto stop for immigration questions in general (life is funny like that). There is obviously significant cross-over of the topics, and many of the moderators and active particpants happen to have a broad and diverse amount of knowledge on immigration, as well as a lot of experience on how to research such information. Many times just knowing how and where to look is more useful than knowing the information itself, especially as immigration rules and laws can change with the wind. That's probably why you're looking for a central resource. It's a dynamic topic to say the least.
We have, in general, been receptive to refugee questions of all types and will usually get around to answering them at some point. However unlesss you also plan on also pointing knowlegeable people here as well, there will be questions that will go unanswered, or not be answered for a long time after asking. Any traffic you direct here will have to include some people willing to dedicate their time and experience to this site and those topics.
Comment: Thank you ! There are also very knowledgeable people in volunteers, whom I plan to point here indeed.
Comment: "this website has become a de facto stop for immigration questions in general (life is funny like that)" -> That's probably because questions can be closed when "[it's not about an issue a local wouldn't have as well.](https://expatriates.stackexchange.com/q/1345/164)". I guess this partly explains why immigration is one of the most common topic here, since many non-immigration questions that expats would ask can be closed under that reason.
Answer: As usually stated we'd like to create an environment that is both helpful and is within the boundaries of what is usually allowed on the StackExchange network. Me personally I am okay with any question that looks a valid problem faced by expats. My usual check is to see if a "local" would have the very same problems or not, and even if it looks like it's not really expat related (e.g. a local would have the same problem) I refrain closing at least for a while - as weird local customs and regulations can actually lead to extra problems for someone not accustomed to their new place as well.
However recently because of our very low answer rate we did a check on our unanswered questions and closed the ones that did look either off-topic (based on the above criteria), or either in the too broad or opinion-based  categories, as the latter types are not not a good fit to any of the StackExchange network sites, including ours.
Looking at your questions none of them seem off-topic, so are definitely welcome here. The only question that might be a bit problematic is the "Where can I learn French?" one as that might be a bit too broad, but depending on the actual question it might still be okay. So no problems there.
Let's see your concerns:

You said that some of your experts who would come to the site (hopefully) answering questions are local, which is not a problem, if they can properly answer the questions. Having people more on the legal side is also not a problem, as a fair amount of our current questions do fit in this category.
Having questions around France is also okay. If you check our current tags you can see, that the UK has around 700 questions, while France lags behind with only around 200, so extra questions in those tags would probably be useful. Also we do lack information especially tailored for refugees, as most of our questions are from / for voluntary migrants.

As a start you could probably check our list of questions in the France tag and the list of questions in the refugee tag.


Multistep involutions

Question: I'm familiar with the concept of an involution.  For example, two simple single-variable functions are $f(x) = 1-x$ and $g(x) = 1/x$.  If we apply the function twice, we get back to the identity operation:
$$f(f(x)) = x,\quad g(g(x)) = x.$$
I'm curious if there are multi-step extensions of this, and how one might go about constructing higher-order involutions.  For example, $f(f(f(x))) = x$, where the values $x$, $f(x)$ and $f(f(x))$ are all distinct.  I guess what I'm asking for is how to find functions over a subset of the reals that give a cycle of values (so not simply permutations on a vector, which would serve as an example over a finite set).
Answer: For order three, there aren't any such functions when you look at the whole $\mathbb{R}$. This is a consequence of Sharkovskii's theorem: if you have a point of period three, ie. $x$ such that $f(f(f(x)))=x$ and $f(x)$, $f(f(x))$ are not $x$, then you have points of all periods. This is a really strong theorem, but in particular it implies existence of $y$ such that $f(f(y))=y$ and $f(y) \neq y$, which means $f(f(f(y))) \neq y$.
Actually that theorem is even stronger than I mentioned: it states that if we have a point of period $m$, then we have a point of period $n$, whenever $n$ appears after $m$ in this peculiar sequence:
$$ 3,5,7,\ldots, 6,10,14,\ldots,12,20,28,\ldots,\ldots,16,8,4,2,1. $$
This is not exactly what you asked for, but this theorem is worth mentioning whenever possible.
After we allow us to restrict ourselves to a subset of $\mathbb{R}$, the situation becomes easier. Or, alternatively, we can look at a superset of $\mathbb{R}$.
To see what I mean, let's return to your example of $g(x) = \frac{1}{x}$. Then $g(0)$ is not quite defined, but let us write $g(0) = \infty$ and $g(\infty) = 0$. Our infinity represents here neither $+ \infty$ nor $-\infty$, but somehow both of them at the same time. Now $g$ is defined everywhere in a continuous way.
We can imagine our set $\mathbb{R} \cup \{ \infty\}$ as the line, whose endpoints were glued together – in other words, a circle. This can be made precise by the notion of a stereographic projection: if you draw a line $y=0$ and the circle $C$ with diameter $(0,0)$, $(0,1)$, then we have a map from $\mathbb{R} \cup \{\infty\}$ to $C$ given by mapping $t$ to the intersection of line through $(t,0)$ and $(0,1)$ with $C$, if $t$ is finite, and $(0,1)$ if $t=\infty$. I will call this map $s$.
Now, if we look how $g$ acts on our circle, it turns out that this is the same as reflection across the vertical diameter. Looking at the circle, we have yet another involution: reflection across its center. On the real line, it corresponds to $h(x) = -\frac{1}{x}$, which actually satisfies $h(h(x)) = x \neq h(x)$ for all $x$.
To find a map of period three, we simply look at a map $r:C \to C$ given by rotation by $120$ degrees. Then $s^{-1} \circ r \circ s$ (ie. we move from line to the circle, we rotate, and then we project back to the line) is a map of period three. The trick here is that composing it three times, consecutive $s$ and $s^{-1}$ will cancel out, leaving $r \circ r \circ r$, which is identity.
It will still work if you take your favourite continuous bijection $f : \mathbb{R} \to \mathbb{R}$, and looked at $f^{-1} \circ s^{-1} \circ r \circ s \circ f$. If you start with linear functions, you should be able to conclude that all maps of form $h(x)=\frac{ax+b}{cx+d}$ with $ad-bc=1$ and $a+d=-1$ have period three.
I'm sorry for that long and winding answer, but there's definitely too much exciting mathematics involved here to keep it short.
Comment: ok.  Forgive my poor etiquette.
Comment: Wow!  That's very interesting.  I like the rotation example.
Comment: @Doug Why you do not accept the answer? Check the your other questions as well.
Comment: @Doug No problem.

Multistep involutions


Why is the integral characterization of e the same as the derivative characterization of e?

Question: Why is it the case that $$\frac{d}{dx}b^{x}=b^x \iff b = e$$ is equivalent to $$\int_1^b{\frac{1}{t}dt}=1 \iff b = e?$$
Comment: Are you allowed to use the integral definition of the natural logarithm or just this integral definition of the number $e$?
Comment: I think it is enough to show that given $e^x$ as defined above, the function $f(x) = \int_1^x\frac{1}{t}~\mathrm{d}t$ is its inverse function. See here https://math.stackexchange.com/questions/2775529/if-the-natural-logarithm-is-defined-by-the-integral-how-to-show-that-exp-is-the
Comment: What do you mean by "equivalent" or "the same"? Both statements are true.
Comment: Are you asking why both statements are true for $b = e$?
Answer: If you restrict $x > 0$, the differential equation is also true if $b = 0$. Putting that case aside and since $b^x$ is not defined for $b< 0$ and non-integer $x$, assume $b > 0$.
Let $y(x) = b^x$ and note that $y(0) = 1, y(1) = b$. So the differential equation becomes $\frac{dy}{dx} = y$, or $$\frac 1y\frac{dy}{dx} = 1$$ Also note that since $y$ is differentiable, it is continuous, and by the differential equation, $\frac{dy}{dx}$ is also continuous.
Integrate both sides:
$$\int_0^1\frac1y\frac{dy}{dx}\,dx = \int_0^1 1\,dx = 1$$
Make the substitution $t=y, dt = \frac{dy}{dx}dx, x= 0 \implies t = 1, x=1 \implies t = b$:
$$\int_1^b\frac{dt}t = 1$$
The inverse implication follows from defining $f(y) = \int_1^y\frac{dt}t$ and differentiating.


What is the "Magic Spray"?

Question: In football, you often see a player gets injured. Then the physio comes and they use a spray often called as "magic spray". Does anyone have any idea what it is?
Looking for the actual details.
Answer: It contains anesthetics. When players get hit or tackled they could be in great amount of pain, but their team still needs them to play. The physicians apply the spray and the injured body part goes numb, so players can continue playing with no pain.
Source
Comment: It might be a good idea to add some information to this answer from that link, in case the article goes away and to save people from following it. Especially the point that the "magic" is often based on the complete absence of injury or real pain, such as when the player was taking a dive.
Answer: The spray is actually a burst of very cold water/mist with ingredients to help/make it cool (I don't have one on hand to know what is inside). The term 'magic' can refer to its history and the seemingly miraculous way the player gets back on his feet.
It is cold because it can help with reducing inflammation which in turn can reduce pain on knocks / joints.
You may also get a heat spray which can help muscles.
reference
Answer: The spray is an aerosol containing menthol. Menthol cools, and the act of spraying aerosol is cooling. (Boyle/Charles/Combined Gas Laws -- when the pressure of a gas is reduced, the temperature goes down.) By drastically cooling the area, it applies temporary pain relief. Very temporary, but for minor dings it gets rid of the pain so they can play. Most (male) soccer "injuries" are really only acting for a foul anyways.
One product that is used in various sports is BioFreeze(TM), which I have seen used in my work in ER (as a Sports Medicine PA). They describe on their website that Menthol is "the active ingredient in Biofreeze Pain Reliever", and explain how cooling and menthol can relieve pain.
Comment: Hi, welcome to the site, and thanks for a good answer based on your experience. I tried to improve it a bit, and added a link. Feel free to further improve if you want, or to roll back if you think I've made it worse.

What is the "Magic Spray"?


Image style generating hook

Question: I'm using Drupal 7. Is there a hook for generating image from image style?
For example. I upload an image. When image is displayed for the first time, drupal generates image style. Can I hook to that event somehow?
Answer: The image style hooks are documented here:
http://api.drupal.org/api/drupal/modules%21image%21image.api.php/7

hook_image_default_styles:     Provide module-based image styles for reuse throughout Drupal.
hook_image_effect_info:    Define information about image effects provided by a module.
hook_image_effect_info_alter:  Alter the information provided in
hook_image_effect_info.
hook_image_styles_alter:   Modify any image styles provided by other modules or the user.
hook_image_style_delete:   Respond to image style deletion.
hook_image_style_flush:    Respond to image style flushing.
hook_image_style_save:     Respond to image style updating.

Nothing for the actual image generation process, if that's what you're looking for.
See image_style_deliver for the details on the image generation
Comment: Thanks for the image_style_deliver() function:) hook_file_load can be injected there:)
Comment: Ah yes, glad it's sorted!
Answer: You can define any number of custom image styles (presets). You can then call an image to be embedded using a specific image_style with theme_image_style
Answer: Hooking your own code into the image derivative generation, image link generation and menu routing is very difficult. In the imagecache_actions contrib module we have had a lot of questions about it. I think that comments 12, 13 and 14 of issue "Change file format :: Doesn't change the file extension" best answer what can be done and what trouble you will probably run into.

Image style generating hook


Inicialização de Enum

Question: Sempre criei enums assim:
public enum TipoTelefone
{
  Residencial,
  Celular,
  Comercial
}

Mas hoje dando manutenção em um código encontrei um assim:
public enum TipoTelefone
{
    Residencial = 0,
    Celular,
    Comercial
}

Qual a diferença de inicializar o primeiro elemento do enum?
Answer: Por padrão, o valor associado as constantes dos membros da enumeração são do tipo int. A primeira variação começa como zero e é incrementada em um para cada variante seguinte. Portanto, neste exemplo:
enum TipoTelefone {
    Residencial,
    Celular,
    Comercial
}

O valor para cada variante é: Residencial, 0; Celular, 1 e Comercial, 2. Repare que é sequencial.
Mas também é possível definir explicitamente valores para os membros. Por exemplo:
enum ErrorCode {
    Residencial = 100,
    Celular = 200,
    Comercial = 300
}

Nesse caso, os membros têm valores definidos explicitamente. Não há mais sequência implícita no exemplo acima. No exemplo acima, parece-me meio desnecessário, mas pode ser útil em algumas situações específicas.
Já em casos como mostrado no exemplo da pergunta, no qual apenas o primeiro elemento é redefinido, os demais continuam seguindo a sua ordem, de modo sequencial.
Então, no exemplo abaixo, a definição de Residencial à 0 é redundante, já que o primeiro elemento é, por padrão, zero.
enum TipoTelefone {
    Residencial = 0,
    Celular,
    Comercial
}

Mas se fizer algo como:
enum TipoTelefone {
    Residencial = 5,
    Celular,
    Comercial
}

As variantes serão definidas a partir do 5. Residencial, 5; Celular, 6 e Comercial, 7.
Answer: Esse caso muda nada. Apenas adotou o estilo mais explícito do que o compilador já faz por padrão. Quando nada é informado o primeiro valor é sempre 0 e os demais segue sendo sempre o valor do membro anterior + 1.
Faz mais sentido quando você quer valores diferentes do padrão.
E claro, se tiver um padrão muito estranho é melhor ser explícito em todos para ficar mais legível. Ou seja, opte pelo padrão implícito ou seja todo explícito.
Particularmente não gosto do meio termo que é o caso demonstrado, foi explícito em um caso e implícito nos outros.
Sempre pode haver caso para adotar uma mistura e mesmo esse caso não causou nenhum grande problema, mas eu prefiro ligeiramente mais o seu jeito. Cada caso posso agir diferente, essa é só uma tendência.
O meu conselho é evitar ao máximo adotar padrões diferentes de começar com 0 e cada membro ir adicionando 1 ou então ir em múltiplos, por exemplo cada membro ir dobrando de valor, em geral adotando o atributo [Flags]. mas se o domínio pedir, não tem problema usar outros valores. Em alguns casos quando foge muito do padrão talvez um enum não seja o mais adequado. Esse é o mecanismo que vejo algum abuso.

Inicialização de Enum


Multiple Values to Trigger #states

Question: How can I have multiple values trigger the Form API's #states?
Say for example, I wanted this field to be visible not only if the value is 5 (currently works below), but wanted to make the field visible if the the values are 3, 4 or 5.
'#states' => array(
    'visible' => array(
       ':input[name="field_star_rating"]' => array('value' => t('5')),
    ),
),

As a note, I tried the following and it does not work.  It only works if the value is '4'
'#states' => array(
    'visible' => array(
        ':input[name="field_star_rating"]' => array('value' => t('5')),
        ':input[name="field_star_rating"]' => array('value' => t('4')),
    ),
),

This also does not work, it too only works if the value is '4':
'#states' => array(
    'visible' => array(
        ':input[name="field_star_rating"]' => array('value' => t('5'), 'value' => t('4')),
    ),
),

Answer: Here's what you need:
'#states' => array(
    'visible' => array(
        ':input[name="field_star_rating"]' => array(
            array('value' => t('5')),
            array('value' => t('4'))
        ),
    ),
),

Comment: This is indeed the correct way, the current one marked as correct is wrong. See this issue for more info:
http://drupal.org/node/735528
Comment: The #states API sure has come a long way sense 2011. Marking as correct.
Comment: this is a great answer, and I came here from Google, like a dozen times... a bounty is on its way.
Comment: It is working fine for normal view. After running any 'ajax', it added again and again
Comment: In my case with hook_form_alter of an existing node form the states only changed correctly when i added [und] to the name: input[name="field_star_rating[und]"]' => array(
Answer: Only way I could figure is to use #ajax in D7.
Here are a few helpful tip's I wish I would have known before starting.

#ajax in the form API is awesome and worth learning
#states does not support OR or XOR (Without a patch? http://drupal.org/node/735528 )
dpm($form); and var_dump($form_state) on a custom submit function are priceless

Here is a modified version of one of the AJAX examples from the examples module.
function plugin_autotextfields($form, &$form_state) {

    $form['star_rating'] = array(
        '#type' => 'select',
        '#title' => t('Star Rating'),
        '#options' => array('_none' => '- select -', 5 => '5 Star', 4 => '4 Star', 3 => '3 Star', 2 => '2 Star', 1 => '1 Star'),
        '#ajax' => array(
            'callback' => 'plugin_autotextfields_callback',
            'wrapper' => 'textfields',
            'effect' => 'fade',
        ),
    );

    $form['textfields'] = array(
        '#title' => t("Fieldset Name"),
        '#prefix' => '
',
        '#suffix' => '
',
        '#type' => 'fieldset',
        '#description' => t('Where the field will be placed'),
    );

    if (!empty($form_state['values']['star_rating']) && $form_state['values']['star_rating'] == 5) {
        $form['textfields']['review'] = array(
            '#type' => 'textfield',
            '#title' => t('Message if 5 stars'),
        );
    } else if (!empty($form_state['values']['star_rating'])) {
        $form['textfields']['review'] = array(
            '#type' => 'textfield',
            '#title' => t('Message if not 5 stars'),
        );
    }

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Click Me'),
    );

    return $form;
}

function omfg_autotextfields_callback($form, $form_state) {
    return $form['textfields'];
}

I hope this helps someone that runs into the same problem :)
Comment: Wow! Very helpful answer my friend. I have been wrapping my head around an issue with #states and now have it working but #ajax would of obviously been easier now that you slapped me with a clue-stick. And that debugging tip as a bonus? Sorry I have to pay you with measly karma. ;)
Answer:  $form['student_type'] = array(
    '#type' => 'checkboxes',
    '#options' => array(
      'high_school'   => t('High School'),
      'undergraduate' => t('Undergraduate'),
      'graduate'      => t('Graduate'),
    ),
    '#title' => t('What type of student are you?')
  );

// High school information.
  $form['high_school']['tests_taken'] = array(
    '#type' => 'textfield',
    '#title' => t('What standardized tests did you take?'),
    '#states' => array(
      'visible' => array(   // action to take.
        ':input[name="student_type[high_school]"]' => array('checked' => TRUE),
        ':input[name="student_type[undergraduate]"]' => array('checked' => TRUE),
        ':input[name="student_type[graduate]"]' => array('checked' => FALSE),
      ),
    ),
  );

P.S. See the examples module for more features  "form_example/form_example_states.inc"

Multiple Values to Trigger #states


Joda ISODateTimeFormat serializing/deserializing

Question: When I run the below test, it prints out "2016-11-11". What is going on here? How can I get it print the DateTime string that I supplied as input?

import org.joda.time.DateTime;
import org.junit.Test;

public class Adapter2
    extends XmlAdapter<String, DateTime>
{

    public DateTime unmarshal(String value) {
        return (org.joda.time.format.ISODateTimeFormat.dateTimeParser().parseDateTime(value));
    }

    public String marshal(DateTime value) {
        return (org.joda.time.format.ISODateTimeFormat.dateTime().print(value));
    }

    @Test
    public void test()
    {
        System.out.println(new Adapter3().marshal(new Adapter3().unmarshal("2016-11-12T00:00:00.000+08:00")));
    }

}
Comment: The test uses Adapter3. You posted the code of Adapter2.
Comment: @JBNizet Thanks for pointing out. Changing to Adaptor2 also yields the same results. (I am unable to edit my original post to fix this)
Comment: What is the issue exactly? When I run this test, it doesn't print "2016-11-11". It prints 2016-11-11T17:00:00.000+01:00, which is the expected output, given that my timezone is Europe/Paris, which is one hour ahead of UTC. What do you **really** have as output, what do you expect instead, and why?
Comment: My bad, again. The output after the change is "2016-11-11T08:00:00.000-08:00" (in my timezone). What I am hoping to do - is preserve the timezone in the input serialized string, without timezone conversion.
Comment: And the reason I need this, is because I need to perform an action on the date portion of my DateTime input, ignoring the time or timezone. @JBNizet
Answer: Use DateTime.parse() instead of ISODateTimeFormat.dateTimeParser().parseDateTime(). Or use what DateTime.parse() uses:
ISODateTimeFormat.dateTimeParser().withOffsetParsed().parseDateTime(value)


$\ E[(X-c)^2]\geq E[(X-EX)^2]$

Question: Prove that:
$\ E[(X-c)^2]\geq E[(X-EX)^2] $ where $c$ is some constant.
I know that $\ E[(X-c)^2]=E[X]^2-2cE[X]+c^2$ and that $E[(X-EX)^2] =D[X]$.
Comment: Sure. It's at $c=a$
Comment: Can you find value $c$ that gives minimum of the  function $f(c)=a^2-2ca+c^2$?
Comment: Basically, proving the inequality is equivalent to proving that the map $c\mapsto\Bbb E[(X-c)^2]$ is minimized when $c=\mu=\Bbb E[X]$. To show this, denoting by $a=\mu=\Bbb E[X]$, your map is $c\mapsto a^2-2ca+c^2$ which has a critical point at $c=a$ with second derivative being $2 (\gt 0)$ at $c=a$, thus showing it's a minimum.
Answer: Let $Y$ have mean $0$.
Then: $$\mathbb{E}\left(Y-d\right)^{2}=\mathbb{E}Y^{2}-2d\mathbb EY+d^{2}=\mathbb{E}Y^{2}+d^{2}\geq\mathbb{E}Y^{2}$$
Now substitute $Y:=X-\mathbb{E}X$ and $d=c-\mathbb{E}X$ in order
to get:
$$\mathbb{E}\left(X-c\right)^{2}=\mathbb{E}\left(Y-d\right)^{2}\geq\mathbb{E}Y^{2}=\mathbb{E}\left(X-\mathbb{E}X\right)^{2}$$
Answer: You are almost there:
$$
\begin{align}
E\!\left[(X-c)^2\right]
&=E\!\left[X^2\right]-2cE[X]+c^2\\
&=E\!\left[X^2\right]-E[X]^2+\left(E[X]-c\right)^2\\
&=E\!\left[\left(X-E[X]\right)^2\right]+\left(E[X]-c\right)^2
\end{align}
$$
Answer: $$E[X]^2-2(E[X] + a)E[X]+(E[X] + a)^2 = E[X]^2-(E[X])^2 + a^2 > E[X]^2-(E[X])^2 = E[X]^2-2E[X]E[X]+E[X]^2$$
for any real non-zero $a$.
That makes $E[X]$ the point of global minimum of $f(c) = E[X]^2-2cE[X]+c^2$

$\ E[(X-c)^2]\geq E[(X-EX)^2]$