Como manter um valor fixo dentro de uma função recursiva?

Question: Eu gostaria de criar uma variável com o primeiro valor passado como parâmetro em uma função, mas toda vez que é feita uma chamada recursiva a variável recebe o valor do novo parâmetro passado. Por exemplo:
def fatorial(n)
    print(n)
    if n <= 1:
        return 1
    else:
        return n * fatorial(n - 1)

No caso acima eu gostaria de imprimir apenas o valor passado como parâmetro na primeira vez. Tem como eu armazenar e imprimir apenas o primeiro valor passado? Se sim, como eu poderia implementar isso?
Answer: Não é necessário armazenar o valor passado pela primeira vez. Ao invés disso, utilize uma variável de controle para decidir se você deve ou não imprimir o primeiro valor.
def fatorial(n, imprima=False):
    if imprima:
      print(n)
    if n <= 1:
        return 1
    else:
        return n * fatorial(n - 1)

print(fatorial(5, True))

Exemplo online aqui.
Comment: Funcionou, mas tem alguma outra forma de armazenar em uma variável?
Comment: @RafaelLima você poderia armazenar o valor do parâmetro dentro da condição `if imprima`.
Comment: Como você quer somente o primeiro valor impresso, não vejo porque isso deve ser feito dentro da função.
Comment: Ao tentar armazenar e usar a variavel depois ainda está dando erro, mas a impressão do valor já resolve o meu problema.
Comment: Na verdade, o mais comum - e o que eu gosto - é deixar valor default do valor opcional ajustado para quem chama a função "de fora" - a função recursiva "sabe mais sobre si mesma" - (isso é, voce está pensndo no código dela quando escreve as chamadas a ela mesma), e é melhor que essas chamadas internas passem os parametros opcionais a mais.
Em resumo, mude o cabçalho para `def fatorial(n, imprima=True):` e a chamada interna para `fatorial(n - 1, imprima=False)` assim quem chama de fora não precisa se preocupar com o "imprima".
Comment: Dito tudo isso - é uma péssima ideia que uma função dessas 0- que é puramente numérica, imprima alguma coisa - a melhor prática mesmo é a função recursiva só retornar um valor - quem fizer a chamada de fora que imprima.
Comment: Se for um código real (em contraste com esse exemplo que é só didático)  em que o que vai se fazer com o valor final retornado é mais complicado que um simples `print` - ainda vale a pena manter a função recursiva sem um "special case` para quando é chamada de fora -e em vez disso criar uma outra função pequena, que só cuida de chamar a função recursiva, e imprimir ou gravar seus resultados.


Document base [path]\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\[project] does not exist or is not a readable directory

Question: I am trying to run a project on a Tomcat server 7.0 from within eclipse, and I am getting the error: Server Tomcat v7.0 Server at localhost failed to start
I am using spring framework for the first time so I guess I have something misconfigured.
Here is my stacktrace:
<code>    Nov 05, 2014 10:41:26 AM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre7\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\Python34\;C:\Python34\Scripts;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\Java\jdk1.7.0\bin;C:\Program Files (x86)\MySQL\MySQL Fabric 1.5.2 & MySQL Utilities 1.5.2 1.5\;C:\Program Files (x86)\MySQL\MySQL Fabric 1.5.2 & MySQL Utilities 1.5.2 1.5\Doctrine extensions for PHP\;.
Nov 05, 2014 10:41:26 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:test' did not find a matching property.
Nov 05, 2014 10:41:26 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:GestionEtudiant' did not find a matching property.
Nov 05, 2014 10:41:26 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:SiteInfo' did not find a matching property.
Nov 05, 2014 10:41:26 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Sites' did not find a matching property.
Nov 05, 2014 10:41:26 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:CouchePresentation' did not find a matching property.
Nov 05, 2014 10:41:27 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Nov 05, 2014 10:41:27 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Nov 05, 2014 10:41:27 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 924 ms
Nov 05, 2014 10:41:27 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Nov 05, 2014 10:41:27 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.55
Nov 05, 2014 10:41:28 AM org.apache.catalina.core.StandardContext resourcesStart
SEVERE: Error starting static Resources
java.lang.IllegalArgumentException: Document base C:\Documents and Settings\Administrator\workspace EE\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\GestionEtudiant does not exist or is not a readable directory
    at org.apache.naming.resources.FileDirContext.setDocBase(FileDirContext.java:136)
    at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:5108)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5292)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

Nov 05, 2014 10:41:28 AM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/GestionEtudiant]]
    at java.util.concurrent.FutureTask$Sync.innerGet(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:816)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/GestionEtudiant]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    ... 7 more
Caused by: org.apache.catalina.LifecycleException: Error in resourceStart()
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5293)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 7 more

Nov 05, 2014 10:41:32 AM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/Sites]]
    at java.util.concurrent.FutureTask$Sync.innerGet(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:816)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/Sites]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    ... 7 more
Caused by: java.lang.NoClassDefFoundError: Lorg/apache/commons/logging/Log;
    at java.lang.Class.getDeclaredFields0(Native Method)
    at java.lang.Class.privateGetDeclaredFields(Unknown Source)
    at java.lang.Class.getDeclaredFields(Unknown Source)
    at org.apache.catalina.util.Introspection.getDeclaredFields(Introspection.java:106)
    at org.apache.catalina.startup.WebAnnotationSet.loadFieldsAnnotation(WebAnnotationSet.java:270)
    at org.apache.catalina.startup.WebAnnotationSet.loadApplicationServletAnnotations(WebAnnotationSet.java:139)
    at org.apache.catalina.startup.WebAnnotationSet.loadApplicationAnnotations(WebAnnotationSet.java:65)
    at org.apache.catalina.startup.ContextConfig.applicationAnnotationsConfig(ContextConfig.java:403)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:879)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:374)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5378)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 7 more
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.Log
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
    ... 21 more

Nov 05, 2014 10:41:32 AM org.apache.catalina.core.StandardContext resourcesStart
SEVERE: Error starting static Resources
java.lang.IllegalArgumentException: Document base C:\Documents and Settings\Administrator\workspace EE\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\CouchePresentation does not exist or is not a readable directory
    at org.apache.naming.resources.FileDirContext.setDocBase(FileDirContext.java:136)
    at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:5108)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5292)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

Nov 05, 2014 10:41:32 AM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/CouchePresentation]]
    at java.util.concurrent.FutureTask$Sync.innerGet(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:816)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/CouchePresentation]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    ... 7 more
Caused by: org.apache.catalina.LifecycleException: Error in resourceStart()
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5293)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 7 more

Nov 05, 2014 10:41:32 AM org.apache.catalina.core.StandardContext resourcesStart
SEVERE: Error starting static Resources
java.lang.IllegalArgumentException: Document base C:\Documents and Settings\Administrator\workspace EE\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\test does not exist or is not a readable directory
    at org.apache.naming.resources.FileDirContext.setDocBase(FileDirContext.java:136)
    at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:5108)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5292)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

Nov 05, 2014 10:41:32 AM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/test]]
    at java.util.concurrent.FutureTask$Sync.innerGet(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:816)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/test]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    ... 7 more
Caused by: org.apache.catalina.LifecycleException: Error in resourceStart()
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5293)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 7 more

Nov 05, 2014 10:41:32 AM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at java.util.concurrent.FutureTask$Sync.innerGet(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:300)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:739)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:689)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:321)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:455)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:816)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 7 more

Nov 05, 2014 10:41:32 AM org.apache.catalina.startup.Catalina start
SEVERE: The required Server component failed to start so Tomcat is unable to start.
org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:689)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:321)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:455)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:739)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 7 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 9 more
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:300)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 11 more

Nov 05, 2014 10:41:32 AM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["http-bio-8080"]
Nov 05, 2014 10:41:32 AM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["ajp-bio-8009"]
Nov 05, 2014 10:41:32 AM org.apache.catalina.core.StandardService stopInternal
INFO: Stopping service Catalina
Nov 05, 2014 10:41:32 AM org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["http-bio-8080"]
Nov 05, 2014 10:41:32 AM org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["ajp-bio-8009"]
</code>
Comment: Change  your workspace from `C` to other directory and try.
Comment: My other projects are working correctly, so I don't think that the problem is the directory
Comment: This post has multiple solutions to solve this problem. Hopefully one of these helps:

http://stackoverflow.com/questions/8492454/eclipse-tomcat-error-document-base-does-not-exist-or-is-not-a-readable-director
Comment: this question is "blatantly off-topic" and has nothing to do with programming, you are asking on the wrong forum.
Answer:
Remove the projects which are not already in use from the Tomcat Server(Servers console).

delete the .snap file. from the following directory
WORKSPACE-DIRECTORY\.metadata.plugins\org.eclipse.core.resources
Answer: Simple Solution
please check your web.xml file Syntax,
when I use this code I got same error,

        attr2
        com.abc.logindemo.code.AttributeExample2

        attr2
        callAttribute2

when I use

        attr2
        com.abc.logindemo.code.AttributeExample2

        attr2
        /callAttribute2

most of the time we put wrong servlet-class
or url-pattern wrong,
So make sure servlet-class and servle
Answer: This error can be resolved following four cases
1.Clean project & server
Or
2.Remove .snap file from this directory
<code><workspace-directory>\.metadata\.plugins\org.eclipse.core.resources
</code>
Or
3.Remove temp file from this directory
<code><workspace-directory>\.metadata\.plugins\org.eclipse.wst.server.core
</code>
4. Remove the current tomcat object from the server tab and create new one(while creating make sure you removed tomcat old object completely from the option

configure run time environments

Hope helped you.
Happy coding!
Answer: Clean and Publish the server again and deploy the code again.


distance measure of two discrete probability histograms (distance between two vectors)

Question: I have multiple sets of  discrete probability histograms(vectors) and I want to measure the distance between each histogram. I have done some research but I am in doubt.
Literature suggest I could use the Bhattacharyya distance or the Hellinger distance (both are closely related). Which one should I use.
Some additional info. prob Histogram(vector) $A= (.18, .61, .16, .05)$ and prob Histogram (vector) $B= (.26, .55, .16, .03)$. I want to calculate the distance/difference among these two probability Histograms.
The Bhattacharyya coefficient ($BC$) =
$$
\sqrt{.18 \times .26}+\sqrt{.61 \times .55}+\sqrt{.16 \times .16}+\sqrt{.05 \times .03} \; .
$$
Consequently the Bhattacharyya distance = $-\ln(BC)$ and Hellinger distance = $2 \sqrt{1-BC}$.
Is this the right measure and is this the right calculation?
Comment: Is not the Hellinger Distance = $\sqrt {1−BC} $ ? That's what I have always used - and seems to be confirmed in a few references i have here. Not sure where the 2 factor comes into it?
Answer: Jensen-Shannon distance is the 1st thing I'd consider. If you don't insist on having a "distance function", you can directly use Jensen–Shannon divergence, from which this distance is derived.
JS divergence is widely used to measure the difference between two probability distributions. It fits your case, as the inputs are two probability vectors. JS divergence is a straightforward modification of the well-known Kullback–Leibler divergence.
Generally, KL and JS divergence require the input vectors have nonzero entries. In case of zeros in the input, many people simply choose to throw out those values. Check
https://mathoverflow.net/a/72672 for more details on this issue.
Answer: There is also the Wasserstein metric, which has become more popular in the Bayesian inference literature. In your case, the 'wasserstein1d' function from package 'transport' should do the trick:
<code>  x <- rnorm(200)
  y <- rnorm(150,2)
  wasserstein1d(x,y)
</code>


F Dm Am C (Lydian?) Progression

Question: I've been recently wrapping my head around the analysis of the following progression: F Dm Am C. Would you agree it's got an undeniable lydian vibe? I know an explicit lydian progression should feature #4 (and therefore the lydian mode would have been clearer if the progression had featured a G or Em chord) and in fact this one doesn't, but for some reason my ear can't help perceiving that F as the "home key". Maybe it's because the final C chord implies the #7 (#4 of the F lydian scale)? Or would you disagree and say the progression is just "straight" Am? To add even more ambiguity, since the fourth degree of the scale is not explicited, it could also be considered to be in F major. But this option is definitely put aside by the second section of the song, going F Am G G#dim (and thus straight harmonic minor). So wrapping it up my analysis would be: first section sounds halfway between lydian and aeolian (but with a slightly more prominent lydian vibe), second section resolves the ambiguity going straight harmonic minor. Would you agree?
The song in question is Galantis-Runaway:

QUESTION EDIT:
First things first, thank you guys for all of your answers. Each and everyone has been very useful.
I think we've come to a point, however, where it might be of some importance to clear out the reason why I came up with the question in the first place: the very ultimate purpose of my analysis is that of "mining" the relationship between melody and harmony here. My "compositional routine" would often be the following:
1 come up with an acapella vocal line entirely in my head"
2 put it into midi and see what scale/scales it fits
3 come up with a chord progression to transform the vocal melody into a full song section.
So the matter here would be not just simply "harmonizing a melody" (you can just throw tens of progressions under your melody and come up with something pretty coherent and structured) but rather "finding a chord progression that REALLY makes your melody stand out".
So there are many people out there stating that one of fhe most used tecniques in this sense is some sort of modal overlapping, meaning that the composer would often choose a key, write a chord progression in one of the seven modes in that key, and then create a melody in a mode other than that of the progression (though still in the same key), meaning, of course, that the melody would imply mainly and resolve ultimately on notes belonging to a chord which is different than the "home chord" of the progression itself. And the process would also work backwards (starting from the melody like I do).
Such a method would inevitably imply a couple of crucial points:
1 position matters. In both harmony and melody.
2 one can always tell what mode a progression is written in (by "progression", i mean the nude and simple progression).
And the two intertwine, since, even in a progression like this one (F Dm Am C), though characterized by a level of ambiguity undeniably higher than average (mostly due to to the fact that it does not contain the full tritone, as many of you pointed out), there actually is something that makes a chord prevail on the others and stand out as the "home chord", and that something is position: in absence of any other stronger elements driving the attention of the ear, the first chord prevails. The whole strenghtened by the perfect cadence at the end of the progression (C F).
This is the point where many would state that just the fact that a progression begins on a certain chord doesn't automatically imply that that chord is the home key. Which is true, but only in absence of any other "strong signs" of a different home chord (like a cadence, or the repetition/long duration of that other home chord), which is not the case here.
So this is why i wouldn't consider THE PROGRESSION itself to be in A minor. I wouldn't consider it C major either, because the only Cmajor chord falls on the fourth beat of fhe bar, which is the weakest of the four downbeats. What is more, all its chances to be heard as the home key are kind of "sucked away" by the fact thay it's involved in a perfect cadence as dominant key.
So, to wrap it up so far:
Is this progression ambiuguos in a sense that it doesn't clear out its triton? YES
Is this progression ambiguous in a sense that the listener cannot easily identify a home chord? NO.
I would call the first "formal" or "abstract" or "theorical" ambiguity, and the second "practical". So this song progression is FORMALLY ambiguous, but not PRACTICALLY.
Does the verse of this song (no need to argue with the chorus, since it's clearly in Am) really "give justice" to what would otherwise be a pretty "vanilla", boring, even childish vocal melody in Am, ultimately making it stand out and giving it a unique flavour? YES (song is a banger).
What is this due to? The fact that it mixes up a minor (or better Aeolian) melody with a progression which is INHERENTLY in F.
What is ultimately ambiguous in the progression is not its home chord, but its MODE.
The note B then appears in the following section (chorus), creating some sort of resolution to the tension previously caused by the ambiguity, clearing out that the progression is lydian. Which has even a stronger impact if we consider the fact that the song has an ABAB structure, meaning the listener will be approaching the same F Dm Am C progression in the second verse, but this time with the "psicoacoustic advantage" of still having that B from the chorus "in his head".
PS: psychoacoustics (which i find incredibly useful when it comes to explaining harmony) may also have some further implications in the matter: it is not completely true that the progression F Dm Am C has neither B nor Bb: the G note in the Cmaj chord and the E note in both the Cmaj and Am chords actually have B as their third and fifth harmonics, which, in absence of any materially played Bb in the chord, simply prevails, ultimately giving the progression a (though incredibly subtle) INHERENT lydian vibe.
Do you guys agree?
Comment: Why does it matter what you call it? It's a perfectly reasonable chord progression. It could be in a number of different keys (not to mention modes), but so what? It is what it is. Not all music can be explained by the way it follows one set of "rules".
Comment: You don't need to introduce the lydian scale to "explain" why you think it's in F. C F is a perfect cadence! None of the chords contain either Bb or B natural, so why invent a hypothetical question about which one might have been used but wasn't?
Comment: What is the song in question?  Impossible to tell with just the chords really, need the context
Comment: @alephzero because it's interesting...?  People like to know why their music sounds the way it does, and hear whether other people feel the same "implied harmony" that they do.  A fun thing to do in music is to subvert expectations, but that only works if you properly understand the what those expectations are, and why
Comment: @cloverblack a list of chords will almost never you enough about a song to tell you convincingly about its tonality: other cues in the song (harmonic rhythm, melody etc. but which all ultimately add up to a subjective sense of pitch centre and tonality) are important. Ultimately, with the chords sequence given, I could write a song that comes out in D, A, F, or even G pretty easily. If it's even possible for those chords to add up to 4 different pitch centres without context, then making a distinction between "major feel" and "lydian feel" is just not going to be possible without context :)
Comment: Your edit does not convince me that this is in the key of F at all. The chords themselves work equally well in both keys; the only way to point definitively to one key or the other is to look at the melody. The C could extend to a maj7 chord, so you can't simply say "I found a V-I so I'm done". Also, B being in the harmonic series of two of the notes is irrelevant, since you could extrapolate that for absurd results. Besides, Bb is relatively low in C's harmonic series. Finally, chord progressions generally cannot be pegged to a mode without any melodic analysis.
Comment: @Some_Guy The song is Galantis-Runaway (I've transposed the original up a semitone for simplicity's sake). May I ask you what do you mean it's impossible without the context? You wanna check the other layers in the arrangement? To me, the first section NEVER seems to feature the fourth degree of the scale, and that's what generates the ambiguity i mentioned
Comment: The chords you have listed do not specify a key.  It could be I --> vi --> iii --> V in the key of F or IV --> ii --> vi --> I in C.  Although one may be a more reasonable choice than the other.  But you pointed that out so I guess you are in the know.  The key ambiguity is a blessing as you can change the character of the song during a solo by changing modes.  Though you do not need key ambiguity to justify this, you can do what you want and theorize about it later.
Answer: While the chords alone might be ambiguous, I think the song itself is squarely in A minor. You've already explained why the second section is in Amin, so I'll focus my answer on why the first section is also in Amin.
Melody
The melody starts with three melodic phrases:

These three phrases resolve to the notes E-C-A, forming an A minor triad. In the first section, the very final note of the melody occurs at 0:29, over the Amin chord. In other words, the melody reaches its final conclusion upon reaching an Amin chord, giving that chord a little more weight.
Moreover, the entire melody is built almost exclusively from the A minor pentatonic scale (A-C-D-E-G). There is one exception at 0:19 when an F is played. However, this note is brief and is simply a passing tone.
Background parts
In the first section, the higher synth part is repeating the notes G-E-C, which is a rootless Amin7 arpeggio.
The song never switches tonics
Songs with multiple sections will often switch tonics. However, this is usually made very obvious, so that the listener clearly hears the change and notices "oh, we're in a new key." We never get that sort of obvious change when switching back and forth between the two sections. The sections bleed together as though they are in the same key, and the second section is clearly in Amin. This suggests that the first section is in Amin too.
Why you might be hearing F Lydian
In the first section, these chords repeats: ||: FMaj | Dmin | Amin | CMaj :||. When we loop from the 4th measure back to the 1st measure, we get a CMaj-FMaj progression, which might initially sound like a V-I progression. However, the C chord is really more of a CMaj7 chord than a C7. (If you try out both CMaj7 and C7, I think you'll find that the CMaj7 sounds better. This is partly because of the B♮ occurring in the melody at 0:57 and the G♯dim chord occurring at 0:43, etc.). Hence, the CMaj chord doesn't really serve as a proper dominant V7 chord, and thus FMaj isn't really the tonic.
Why the tonic isn't FMaj
In general, we can't separate the melody from the chords, because otherwise it might lead to statements that there are two tonics (one for the harmony and one for the melody). But just as this song isn't in two different keys, it similarly doesn't have two different tonics.
So for the chord progression, we have two candidates: | ♭VI | iv | i | III | in Amin, and | I | vi | iii | V | in FMaj. The second is not more inherent than the first because both progressions are perfectly logical. In fact, the first (in Amin) makes more sense and is more common than the second (in FMaj). Specifically, the second progression has a vi chord leading to the iii chord, which is atypical. The vi chord is a weak subdominant and usually lead to a stronger subdominant (e.g., vi-ii-V) or straight to a dominant (e.g., vi-V). For example, see c and d here. There is a second feature of the FMaj progression that is unusual. It's rare for the iii chord to lead straight to the V chord. In fact, the iii chord is "so weak that it almost always leads to stronger pre-dominant chords, rarely progressing directly to V." (myweb.fsu.edu/nrogers/Handouts/iii.pdf) By contrast, the first progression uses i - ♭VI, which is fairly common (for example, see a and b).
So in general, the progression in Amin (| ♭VI | iv | i | III |) tends to  make more sense than the progression in FMaj (| I | vi | iii | V |).
Comment: @cloverblack I disagree that the "progression ... is inherently in F." I would take some time to explain why, but I worry that you've already made up your mind. You've stated that, by default, the tonic is the first chord played unless this is overturned by "strong signs" of a different home chord. This is simply not true. You've stated that the C-F chord is a perfect cadence, and this is also not true (because the C chord is CMaj7 not C7). You've said "What is ultimately ambiguous in the progression is not its home chord, but its MODE," but I don't think this distinction exists.
Comment: @cloverblack, if someone asks "what key is this song in," we can't reply: the chord of F maj & the scale of A Aeolian. We must give one answer--there is only one "home." The melody & harmony can't be separated & assigned two different tonics. If we hear the melody as being in Amin, then we're making a broad statement about the *key of the song*, which applies to the chords too. The chords can't be in a different key than the melody.
Comment: @cloverback, for the chord progression, we have two candidates: `| ♭VI | iv | i | III |` in Am, and `| I | vi | iii | V |` in FM. The second is *not* more inherent than the first because both progressions are perfectly logical. In fact, the second (in FMaj) is far less logical because it has a vi chord (subdominant) leading to the iii chord (mediant). Additionally, it's extremely rare for the iii chord to lead to the V chord. The iii chord is "so weak that it almost always leads to stronger pre-dominant chords, rarely progressing directly to V." (http://myweb.fsu.edu/nrogers/Handouts/iii.pdf)
Comment: I updated the question as a comprehensive answer to you all. Mind taking a look?
Comment: Not made my mind up yet,  rather just trying to wrap things up and focus. Would be grateful if you took the time to give that explaination
Comment: @cloverblack, by contrast, the first progression uses i - ♭VI, which is fairly common (**[see a and b](http://myweb.fsu.edu/nrogers/Handouts/vi.pdf)**).
Answer: OK, so just for fun, before listening to the actual song, I made a demo as a kind of "proof of concept" to show how chords can mean different things.  I'm not saying these are masterful compositions, and the C major one especially sounds a bit shoehorned in, and the G one I had to lean on G a lot before and after the progression to make it clear where we were, but it's to make a point not sell an album ;)
https://vocaroo.com/i/s0aKBNLoWxT5
Now, since you are asking about a specific song, I just listened to it.  It's in  A minor not F.  (well B flat minor, but as you've transposed it in your question, I've used that as the example).
Your ear training is obviously going well, because you've heard that a B sounds very "in-key", you've just attributed the reason- it's because it's in A not in F!
In minor pop music the flat 6 chord can often sound quite "resolved", and it's often used to essentially "recontextualise" a melody, you often find minor pop music where the melody over the minor 1 chord is then repeated over the bVI chord, giving it a new context.  This sounds quite stable and so it's possible to mistake it for the tonic, however if you listen closely you'll realise that the actual centre is the i chord.
This song doesn't actually use this movement much , instead opting to repeat the melody over first the F (bVI) then the (bVII G) but with a tweak to the melody, avoiding the Am on the chorus altogether (well, except as a passing chord).  This helps build tension in the chorus as it never properly "lands", it simply bounces between the F and the G, avoiding the resolution to the Am.
For the purposes of argument though, you could sing the song like this:
F                (G)
I wanna run away
Am
I wanna run away

To hear how the "trick" of swapping out an Am for an F works.
Here's a demo of what I mean and some rambling analysis of how the song works.  You later clarified in your question that it was the first section not the second section which gave you trouble but I'm going to leave this here anyway because I think it still has value for you:
https://vocaroo.com/i/s1lONrpeilXE
And by the way, on the chorus you don't "need" the G#diminished chord to tell you it's A minor, you can play it as literally F->G F->G without even playing either the G#diminished or the Am and it's still clearly in A minor from the musical context.  In light of your edit to the question I recorded this just now to show you what I mean, and also explain the verse a little.
https://vocaroo.com/i/s0nptGkaAyam
Here are some other songs that rely heavily on the F-Am movement, to help you recognise it:
https://open.spotify.com/track/2sCFFlnYg6Lk75GCcfSXEz?si=Yx7JcgjnRrWZAEXZQXThTg
https://open.spotify.com/track/2aoo2jlRnM3A0NyLQqMN2f?si=oZzKuLlMSUWr7PbbH1UL4g
https://open.spotify.com/track/1KA6FrMQpvpHbMERjKNuaq?si=_PsJ6yD0Rs23paX8-QvEEA
https://open.spotify.com/track/1dfuJYDSIc41cw5RPsaCF1?si=Whh9HJJtTRyASqAFlrxApg
Comment: @Some_Guy, >you can essentially throw chunks of diminished chords around to imply a V chord.<  Very nicely put.
Comment: First of all, thanks for the amazing answer! I've actually had a tough time figuring out that chord with the # seven on the bass in the chorus. How can u tell so strongly it's an E over G#  (F over A in the original key) and not a viidim? I had thought of an F/A in the first place too, but changed my mind right after throwing a spectrum analyzer on the track and noticing a couple of pretty distinct Eb peaks (original key) and no F peaks at all. + I'd swear i can distinguish the presence of Eb even by ear (maybe I'm a little conditioned by the visual feedback of the analyser?). Can you relate?
Comment: @cloverblack sure, if you'd said G#dim in you're question I wouldn't have objected, but you just said "G#" which it most certainly isn't!  Btw a good thing to do when trying to work out chords and especially specific voicings is to slow down a recording to half speed and try and pick out individual notes in the difficult chords by singing notes with the record. This works especially well when the song has good voice leading and you can follow "submelodies" within chords (it works well for this song).  Youtube's half speed is ugly, use a program (try both with and without pitch correction too)
Comment: @jdjazz has done an excellent job of explaining why the chord progression isn't ambiguous here (and indeed why even without context the chord progression is most likely in A minor), but to make a more general point, it doesn't make sense to assign some sort of "theoretical ambiguity" to a decontextualised chord progression if that chord progression is unambiguous in context. Would it be possible to generate tonal ambiguity with that chord sequence? Yes, of course (as with many progressions), but the pertinent question is "is there any tonal ambiguity in this context", and the answer is no.
Comment: As a demonstration, listen to the 3rd audio recording I made where I played the chorus using only the chords F and G, you no longer have G#dim or Am to tell you you're in A minor, however when listening to the rendition, *practically* there is no ambiguity at all. What you seem to be arguing is that there would be some "theoretical ambiguity" of the chords outside this realisation in context. i.e. that the chorus now, while being *practically* in A minor is somehow *theoretically* in, say, G mixolydian.  There is no merit to this approach though.
Comment: The reason I say this is that, yes, tonal ambiguity is possible, and yes, it would surely be possible to use these chords to construct a passage tonally ambiguous between A minor and G mixolydian, but that *isn't what's happening here* which is the relevant level of analysis. And this is talking about F>G F>G which is far more ambiguous than F Dm Am C. Yes, tonal ambiguity and "semi-pivots" where the pitch centre is unclear are possible in music (and interesting), but they don't occur in this song, and any analysis of the chords pulled from the song without the song as context is meaningless.
Comment: (meaningless other than as an intellectual "what if" exercise, of course; obviously looking at how these chords *might* be used to create ambiguity is worthwhile in its own right, I just mean that it's meaningless as a level of analysis used to explain the phenomenology of an actual piece of music)
Comment: V and V7 perform the same function, so I was a bit lazy above, the 7th is present yeah; that actually makes the function stronger. I can't hear that easily whether the root note is actually present somewhere or omitted, but it doesn't really matter: a diminished triad is the top of a dominant 7th chord so if you have E/G# you can voice that as G#dim and it has pretty much exactly the same effect. Whether it's actually there or not, including the E or omitting it has hardly any effect on the harmony of the song, so it doesn't really matter.
Comment: I only do that when I'm desperate ahah btw that chord has always sounded
 diminished to me from the very first time. The tension it creates is pretty unusual for an edm tune
Comment: In a lot of latin American music they go one step further, the dominant chord is often voiced as the dissonant E7b9 (i.e. E G# B D **F**). That clashing F is used as a further tension that can resolve down to an E).  What this means is that you have an exploitable situation now where every diminished triad beginning on one of the notes in the G#dim7 chord (so G#dim, Bdim, Ddim,Fdim) can be used to imply the dominant.  This gives you a lot of possiblities for improvising where you can essentially throw chunks of diminished chords around to imply a V chord. https://youtu.be/GvCKSr0IRa0
Comment: You're right I completely forgot the dim. I'm a mess. Thanks again btw
Comment: The G#dim chord is part of a **[deceptive cadence](https://en.wikipedia.org/wiki/Cadence_(music)#Interrupted_(deceptive)_cadence)**. Given that it's functioning as E7 (the V chord), it sounds like it should resolve to Amin (the tonic). But instead it resolves to FMaj (the ♭VI chord). Great answer, +1!
Comment: @Some_Guy I updated the question as a comprehensive answer to you all. Mind taking a look?
Comment: @cloverblack forgot to tag you
Comment: @cloverblack oi cloverback, don't suppose you saved any of these audio recordings?  I was stupid enough to use an audio service that purges the recordings... :/
Answer: I think you are looking at this in the wrong way and that it's probably hindering your ability to properly contextualize this stuff. The real answer is that it is impossible to tell based on the chords provided what the key center is because there is more than one valid answer.
You were asked in the comments on your original question to provide the song because it is impossible to tell what the key center is based on these chords alone since they don't quite give enough information. Here is a (fairly long-winded) way to illustrate this:
F consists of F A C. Dmi of D F A. Ami of A C E. C of C E G. If you take all of these together and remove the duplicates, you get F G A C D E; you have a note of every letter except B. If we assume that we are dealing with something diatonic here, you have two potential key centers: C major (above notes plus B) or F major (above notes plus Bb). This progression therefore lends it to being interpreted in at least two completely valid ways. You could call it a I-vi-iii-V in F major; probably there'd be a Bb in the melody somewhere if you went this route. You could also call it IV-ii-vi-I in C major, which may or may not involve a B somewhere.
Things get a little bit messy once you acknowledge that you could be dealing with a mode of either C major or F major. It is also reasonable to frame this as a progression in D minor (bIII-i-v-bVII) or A minor (bVII-iv-i-bIII). You could also look at it as being an F lydian progression (as your post implies), but this would be a bit of a stretch since the progression ends on the C. The only way to resolve this uncertainty really is to look at the melody (or other accompaniment); if you can identify which B is being used that will give you your answer. If you can't (or there are no Bs being played at all), the key center may indeed just be very ambiguous and you will have to look at where the melody resolves - if, for example, there is a recurring thematic resolve to A, you are probably dealing with A minor.
There are a few key points that you can take away from this.

The only way to make a determination on what key center you're in is to present a collection of notes that is unique to one key. You will eventually come to understand that this means the only time you can definitively state what key a set of notes belongs to is if there's a tritone in it somewhere, since the "uniqueness" of each key can be summed up as its root plus its tritone - a melody containing E and Bb or its enharmonic spellings will always suggest C or F#, and it will be obvious which of the two that it is nearly all the time.
Nearly everything in my post is concerned with analyzing diatonic music. Most of the things I've said here don't apply to non-diatonic music, except for the principle that the only solid identifier of a key center is the presence of a combination of notes that is unique to that key center.
The distinction between whether something is in, for example, C major and F lydian tends to not be particularly important or helpful for harmonic analysis. There are some cases where you would really want to know - you don't want to be thinking that So What is in C major instead of D dorian - but in general this distinction is about the melody.

EDIT: As an aside, with no context whatsoever I would guess that this is probably in A minor based on the position of the A minor chord in the progression, but this is also a fairly strong progression in F with the right melody.
Comment: Hi fugu, did you downvote my answer?  I've made it a little clearer now so if you'd take another look and see whether you think it still deserves a downvote, I'd appreciate it ;)
Comment: >"The only way to make a determination on what key center you're in is to present a collection of notes that is unique to one key. You will eventually come to understand that this means the only time you can definitively state what key a set of notes belongs to is if there's a tritone in it"  I don't think I can go along with this: a lot of still perfectly "diatonic" music doesn't stick strictly to the major scale, and so you're going to get an awful lot of wrong answers using this method outside of western classical music (and even in it too http://youtu.be/0U6sWqfrnTs)
Comment: I mean, while I can get behind the idea that, in practice, the answer is rarely going to be lydian (because lydian missing the fourth and so doesn't play nice with a lot of conventional harmony), I don't think you can just say "the distinction between F lydian and C major isn't important". The presence/absence of Bb isn't really enough to tell you where you stand, it's trivially easy to write diatonic music clearly centred around A as a key centre using Bb as a flat 2nd, and a lot of pop/rock music uses the b7 more than the nat7, and so a song with no Bs & plenty of Bbs may very well be in C.
Comment: I updated the question as a comprehensive answer to you all. Mind taking a look?
Comment: @Some_Guy If it's diatonic, it will contain exactly one tritone and the combination of notes that make up the tritone will limit the analysis to two keys. Any scale with zero or more than one tritones is not diatonic because it will either contain too few or too many half step intervals. As for the distinction between F lydian and C major not being important, I meant that particularly in the context of harmonic analysis. It is *relatively* unimportant to distinguish them in that context because the principles of functional harmony don't translate well to the modes.
Comment: @Fugu but by your own definition you're excluding minor music with an F# or G# from your definition of diatonic, as well as relegating pop music with a flat 7 in a major key as "non functional harmony".  If your definition of diatonic music & functional harmony is that narrow then fine, but at that point it becomes pretty much inapplicable to not just all popular music but a lot of classical too, and so starting the analysis with "I assume we're talking about diatonic functional music" is no longer a useful assumption if as defined that excludes everything from Bach to Ed Sheeran
Comment: @Some_guy That's not my definition of diatonic, that's **the** definition of diatonic. The harmonic minor scale is not a diatonic scale. You learn how to do this type of analysis in layers: First you work with purely diatonic systems, then you learn how functional harmony interacts with non-diatonic systems to understand how to do an analysis that incorporates secondary dominants, modal interchange, modulation and whatnot. You learn how to deal with a Bb in C by learning why a Bb might find itself in a C major composition to the first place (a modulation/tonicization to F, for example).
Comment: @fugu also functional analysis of music holds up very well on non-diatonic music employing a lot of "mode-mixture" aka a good chunk modern music.  If every time a song in G includes an F natural or D minor song includes a G major chord you throw up your hands and say "well they may as well be in C now because modes aren't functional" then your system of analysis is useless for modern popular music
Comment: @Fugu the word diatonic is more ambiguous than you might think.  It can be (and often is) used more loosely to mean "major/minor music without any funny business". You might not like that use of the term, and I can see why, but if you're going to use diatonic to mean "white key music and nothing more" then it's not a useful way to analyse anything outside of a music theory 101 classroom, because the "exceptions" are innumerably more common than examples which follow "the rules".  While building analysis in "layers" can be a useful didactic approach, if you're not careful and judicious (cont.)
Comment: cont. in how you teach this analysis, you can end up with the "a little knowledge is a dangerous thing" problem because in order to understand pretty basic chord progressions you jump to extremely convoluted modulations and borrowings rather than seeing the music for what it is, i.e. rather than taking the chords as they actually relate to the pitch centre and chords around them, you shoehorn them through a simplified and ultimately arbitrary framework until you can get it to fit (even if in a meaningless way), and if you can't, simply throw up your hands and declare it "an exception".
Comment: @Some_Guy I have a degree in music and I got along just fine using (and hearing) the correct definition of diatonic, which is a scale in which each letter gets one pitch, there are two semitones and no interval between them larger than a tone. You're right in that most musical analysis will involve more than the principles of diatonic analysis, but a) I was specifically talking about when the set of notes are (or probably are) diatonic and b) basically all functional harmony analysis is based on how diatonic music is analyzed. I never once made any suggestion that anything was "an exception".

F Dm Am C (Lydian?) Progression


Qual usar no Ajax, success ou done?

Question: Às vezes eu vejo utilizarem success, às vezes eu vejo .done, para tratar a resposta obtida na requisição.

Qual eu devo usar?
Existe alguma diferença entre as duas? Qual?

A mesma coisa para .error e .fail.
Utilizo o jQuery 3.2.1.
Comment: Não são. Os métodos `done` e `fail` estão relacionados ao retorno da função `$.ajax`, que é um Promise. Os métodos `success` e `error` são *callbacks* executados dentro da própria função.
Comment: O `.done` sempre é executado, enquanto que `.success` só é chamado caso ocorra sucesso. Não sei a distinção entre `.fail` e `.error`
Comment: Deve ser a mesma coisa
Answer: Conceitualmente eles não são a mesma coisa, mas o resultado produzido é exatamente o mesmo. As funções success e error são denominadas callbacks. Por sua vez, as funções done e fail são métodos de um Promise.
Diferença entre promise e callback
O resultado é exatamente o mesmo porque o jQuery utiliza os próprios métodos done e fail para executar as funções success e error. Veja o trecho de código retirado do repositório oficial (linha 662):
// Install callbacks on deferreds
completeDeferred.add( s.complete );
jqXHR.done( s.success );
jqXHR.fail( s.error );

Neste caso, s.success faz referência ao success passado em options, assim como s.error faz referência a error.
Qual deles utilizar?
Se você possui apenas uma função success e error, não faz diferença. Use qual preferir. Utilizar o done e fail são úteis quando você precisa executar múltiplas funções em cada evento:
$.ajax("dominio.com")
    .done(fazAlgo1)
    .done(fazAlgo2)
    .fail(deuErrado1)
    .fail(deuErrado2);

Utilizando success e error você não consegue atribuir várias callbacks. Existem ainda a callback complete que é executada sempre, após a execução de success ou error. Neste caso, o método semelhante no Promise seria o always.
Para mais informações, vale ler a documentação oficial citada na outra resposta

Nota: é importante salientar que os métodos .success e .error que a documentação cita como obsoletos não são as callbacks success e error. São, na verdade, métodos presentes no Promise em versões antigas do jQuery. As funções callbacks ainda podem ser utilizadas.

Exemplo utilizando callbacks:
Utilizando a função callback success.

$(() => {

  $.ajax({
    url: "https://jsonplaceholder.typicode.com/users",
    method: "get",
    dataType: "json",
    success: users => {
      $(users).each(i => {
        console.log(users[i].name);
      });
    },
  });

});

Exemplo utilizando Promise
Utilizando o método done do objeto Promise retornado por $.ajax.

$(() => {

  const request = $.ajax({
    url: "https://jsonplaceholder.typicode.com/users",
    method: "get",
    dataType: "json"
  });

  request.done(users => {
    $(users).each(i => {
      console.log(users[i].name);
    });
  });

});

Exemplo utilizando métodos obsoletos do Promise (OBSOLETO)
Utilizando o método success do objeto Promise retornado por $.ajax.

Este método está presente apenas para referência, mas o mesmo está obsoleto desde a versão 1.8 do jQuery e foi removida completamente no jQuery 3. Não utilize-a.

$(() => {

  const request = $.ajax({
    url: "https://jsonplaceholder.typicode.com/users",
    method: "get",
    dataType: "json"
  });

  request.success(users => {
    $(users).each(i => {
      console.log(users[i].name);
    });
  });

});

Exemplo utilizando fetch
Uma alternativa está em testes no momento chamada fetch. A função é basicamente o que $.ajax faz, acredito eu, mas será nativa no navegador, não precisando importar uma biblioteca de terceiros. Uma requisição GET, por exemplo, poderia ser feita assim:

const request = new Request("https://jsonplaceholder.typicode.com/users", {"method": "GET"});

fetch(request).then(response => {
  if (response.ok) {
    return response.json().then(data => {
      data.forEach(user => {
        console.log(user.name);
      });
    });
  }
});

Ao meu ver ela será muito melhor de utilizar, não apenas por ser nativa, mas por ser semântica, trabalhando com objetos do tipo Request, Response, Headers, etc. Mas lembrando, ainda está em fase de testes.

Outras leituras
O que são promises (promessas) em javascript?
Como realmente aprender a usar promessas em javascript?
O que é callback?
Qual a diferença entre function() {} e () => {}? Por que não funciona o $http.get?
Comment: UHMMM agora eu entendi a diferença bem legal
Answer: De acordo com a documentação do jQuery, segue abaixo os status

jqXHR.done(function( data, textStatus, jqXHR ){});
  Uma alternativa para a opção de retorno de success.

jqXHR.fail(function( jqXHR, textStatus, errorThrown ){});
  Uma alternativa para o retorno de erro, o método .fail() substituiu o método .error() que hoje é obsoleto.

jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown){}); (adicionado em jQuery 1.6)
  Uma alternativa para a opção de chamada quando a requisição está completa. O método .always() substituiu o método .complete() que hoje está obsoleto.
Caso seja uma solicitação bem-sucedida, os argumentos da função são os mesmos de .done(). Para solicitações que ocorreram erros, os argumentos são iguais aos de .fail().

jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ){});
  Incorpora a funcionalidade dos métodos .done() e .fail(), permitindo (a partir de jQuery 1.8) trabalhar com Promise.

Importante: os retornos de jqXHR.success(), jqXHR.error() e jqXHR.complete() foram removidos a partir da versão 3.0 do jQuery. Você pode usar jqXHR.done(), jqXHR.fail() e jqXHR.always() como alternativa.

Qual usar no Ajax, success ou done?


Can I install Jenkins on an unpriviledged account?

Question: I'm trying to test Jenkins and see how it would work for our project. The problem is, there are a lot of policies and restrictions about services on my work computer , and Jenkins fails to start with the message:
Cannot start service from the command line or a debugger. A Windows
service must first be installed ...

Is there a possibility of running Jenkins without installing it ( maybe in a portable way )? I cannot create services, nor special user accounts for it.
Answer: Yes, this should be possible, since starting Jenkins is actually a prerequisite to installing it.
First, verify that you have JRE 1.5 or later. Then it should "just work" with
java -jar jenkins.war

Alternatively, you could launch Jenkins through Java Web Start (test drive mode) then visit http://localhost:8080/ to configure.
If your local policies allow installing a VM host system, a longer way around would be to create a guest VM that allows you to create priviledged accounts.
Finally, if you have a servlet container that supports Servlet 2.4/JSP 2.0 or later (Glassfish, Tomcat 5, JBoss, Jetty 6) you can deploy jenkins.war like a normal WAR file.


Sort an ArrayList based on an object field

Question:
Possible Duplicate:
Sorting an ArrayList of Contacts

I am storing DataNode objects in an ArrayList. The DataNode class has an integer field called degree.
I want to retrieve DataNode objects from nodeList in the increasing order of degree. How can I do it.
List<DataNode> nodeList = new ArrayList<DataNode>();

Comment: On a second tought http://stackoverflow.com/questions/1814095/sorting-an-arraylist-of-contacts may be closer to this
Comment: Possible duplicate of http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property
Comment: See also http://stackoverflow.com/questions/2535124/how-to-sort-an-arraylist-of-objects-by-a-property
Answer: Use a custom comparator:
Collections.sort(nodeList, new Comparator<DataNode>(){
     public int compare(DataNode o1, DataNode o2){
         if(o1.degree == o2.degree)
             return 0;
         return o1.degree < o2.degree ? -1 : 1;
     }
});

Comment: The proper way to do this is the way Mark coded it. Yes the simple one line of code will work 99.9 percent of the time. But you will have a problem if the result of the subtraction is a large number causing the high order bit to overflow. For example you would expect (Integer.MAX_VALUE - (-10)) to be postive, but it isn't.
Comment: Java 8 update: Collection.sort(nodeList, Comparator.comparing(DataNode::getDegree)) or Collection.sort(nodeList, Comparator.comparingDouble(DataNode::getDegree)) if degree is an double instead of an Double
Comment: how about return(o1.degree - o2.degree);?
Comment: @Kazaag your comment should be the correct answer! :) The `Comparator.comparing...` methods can also be used with the `Stream`s API as in `nodesList.stream().sorted(Comparator.comparing(DataNode::getDegree)).collect(Collector.toList())`
Comment: @camickr What about o1.degree.compare(o2.degree)?
Comment: @BenAaronson, should work fine if working with "Integer" objects, but it won't work if using "int" variables since the comparTo(...) method only works on objects not primitives.
Comment: @camickr Good point
Comment: I'd give another upvote but 128 is a nice round number :(
Answer: Modify the DataNode class so that it implements Comparable interface.
public int compareTo(DataNode o)
{
     return(degree - o.degree);
}

then just use
Collections.sort(nodeList);

Comment: [Beware of overflow!](https://stackoverflow.com/q/2728793/1553851) Much safer to `return Integer.compare(this.degree, o.degree);`
Comment: For some reason I get an error if I don't input an object
Comment: this will fail because there are no checks for null. Also you don't need the brackets
Comment: I'm getting an issue where I have to use `Object` as the type in the method call, and I can't cast that to my object type (DataNode in this example)
Comment: Your class has to implement Comparable and not just implement Comparable.
Answer: You can use the Bean Comparator to sort on any property in your custom class.


How Can I do a content type with a 1:n field inside?

Question: I'm a bit lost about how Drupal manage content.
For example, I want to create a new content type called Game. When I create a "Game" I want to introduce "Platform" and "Release date".
For example:
Title: Sonic the Hedgehog.Description: Whatever.
Released on:
Platform: Mega Drive Date: 23 june 1991
Platform: Arcade Date: 1991
Platform: Nintendo Switch Date: 2018
I want both platform and date to be keys for sorting games, so clearly platform might be a "vocabulary" in taxonomy?...I'n not really sure. How would be your take on this?
Answer: It seems Field collection/tabular data solution is what you're after.
In Drupal 7 the popular module for that was Field collection.
In Drupal 8 Paragraphs seems to be popular, although its description is pointing heavily to the current fad of designing content pages with separate sections, it is still a solution that allows for a more structured group of references. Then you reference the Paragraph you constructed for this particular purpose from within your nodes.
A more abstract solution similar to Paragraphs but more flexible is Bricks. Although its description is pointing to Layout integration you don't have to be distracted by that, it's still a great entity reference grouping mechanism you can use to construct your node structure.
I think Bricks might be better suited for your particular case since you'll always be using the same platform/date structure, but investigate both and see which fits you best.
In short, you need references from your nodes to the platform, and date, and they need to be grouped in pairs. You can do that by creating the abstract reference (brick) from your node, that in itself holds two other references (to platform and date). Platform items (entity reference) can be Taxonomy terms, Date can also be Taxonomy or Date fields, it all depends on your details, what type of data it is, how you're expected to manipulate it, etc.
Comment: Some advice - pick the best fit for your use case but don't mix them.. some do, I wouldn't. Each has its own paradigm.
Comment: Personally rec paragraphs over bricks unless you need the extra functionality bricks can provide, e.g. the layout stuff, and it doesn't sound like you do. Disclaimer: I'm not a big fan of bricks.


Problema em fazer import do models User

Question: Estou fazendo alguns testes em um projeto Django. Criei um módulo bem simples só para testes mesmo. Segue abaixo:
from django.contrib.auth.models import User

def teste():
    for i in User.objects.all():
        print i.username

if __name__ == "__main__":
    teste()

Ao executar o código, esse erro é retornado:

Traceback (most recent call last):
File "teste.py", line 6, in
from django.contrib.auth.models import User
File "/home/carlos/myworkspace/helpdesk/lib/python2.7/site-packages/django   /contrib/auth/init.py", line 6, in
from django.middleware.csrf import rotate_token
File "/home/carlos/myworkspace/helpdesk/lib/python2.7/site-packages/django  /middleware/csrf.py", line 14, in
from django.utils.cache import patch_vary_headers
File "/home/carlos/myworkspace/helpdesk/lib/python2.7/site-packages/django/utils/cache.py", line 26, in
from django.core.cache import get_cache
File "/home/carlos/myworkspace/helpdesk/lib/python2.7/site-packages/django/core/cache/init.py", line 69, in
if DEFAULT_CACHE_ALIAS not in settings.CACHES:
File "/home/carlos/myworkspace/helpdesk/lib/python2.7/site-packages/django/conf/init.py", line 54, in getattr
self._setup(name)
File "/home/carlos/myworkspace/helpdesk/lib/python2.7/site-packages/django/conf/init.py", line 47, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but   settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

OBS.: Dentro do python manage.py shell com o comando %run teste.py, o código funciona.
Answer: Esta não é a forma "comum" de executar um projeto com Django, mas se você quer apenas resolver o problema em questão, a solução está em definir a variável DJANGO_SETTINGS_MODULE.
Quando você roda o comando pelo python manage.py shell, esta variável é definida automaticamente, o que faz com que neste caso não ocorra o erro.
Para definir a variável manualmente, você pode colocar o seguinte código no começo do seu script:
import os
# estou considerando que o nome do projeto (e não o app!) seja "helpdesk"
os.environ['DJANGO_SETTINGS_MODULE'] = 'helpdesk.settings'

Outra opção é definir a variável no seu shell em vez do código. Assim:
export DJANGO_SETTINGS_MODULE=helpdesk.settings

Em todo caso, recomendo que você não faça dessa forma. É mais simples e confiável usar o manage.py, ou então fazer um código "tradicional", usando modelos, views e templates.
Comment: Ok. Certifique-se apenas de usar "helpdesk.settings" então. O correto é sempre usar o nome do site/projeto, e não do app.
Comment: Agora esta retornando : ImportError: Could not import settings 'help.settings' (Is it on sys.path? Is there an import error in the settings file?): No module named help.settings
Comment: meu path /home/carlos/myworkspace/helpdesk/help/
/home/carlos/myworkspace/helpdesk
/home/carlos/myworkspace/helpdesk/lib/python27.zip
/home/carlos/myworkspace/helpdesk/lib64/python2.7
/home/carlos/myworkspace/helpdesk/lib64/python2.7
/home/carlos/myworkspace/helpdesk/lib64/python2.7/lib-old
/home/carlos/myworkspace/helpdesk/lib64/python2.7/lib-dynload
/usr/lib64/python2.7
/usr/lib/python2.7
...
Comment: meu wsgi :
import os
import sys

sys.path.append('/home/carlos/myworkspace/helpdesk/help')

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "help.settings")

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
Comment: "help" é o nome do app ou do projeto? Já tentou com "helpdesk.settings" em vez de "help.settings"? Outra opção é você definir o DJANGO_SETTINGS_MODULE como uma variável de ambiente, assim: `export DJANGO_SETTINGS_MODULE="help.settings"`
Comment: "help" é o nome do app e "helpdesk" é do projeto. O arquivo settings esta na pasta "help". $DJANGO_SETTINGS_MODULE e $PYTHONPATH estão certos. Estou já dois dias pesquisando e testando e nada. Vou continuar e qualquer coisa posto. Obrigado Michael.
Comment: Se o app é "help", o arquivo `settings.py` não deveria estar na pasta `help` mas na pasta `helpdesk` (a pasta do projeto, junto com o `urls.py` mestre e o `wsgi.py`) (o settings é do site inteiro, não do app e assim `helpdesk.settings` funcionaria)

Problema em fazer import do models User


How can I align the BPM/Tempo with this audio track using Logic Pro X, Cubase or Ableton?

Question: I have downloaded a November Rain orchestral track on which I would like to add a click using one of the DAWs: Logic Pro X, Cubase Elements or Ableton. Below the link with the track (one is the orchestral one while the other is the same instrumental track, but with guitars, drums, etc... I would only need the orchestral one without guitars, drums, etc...):
November Rain
I would like to use the orchestral track with the click in order to practice on the piano.
I tried to use Smart Tempo on Logic Pro X, trying with KEEP and ADAPT modes, I also edited the project preferences and set the "Set imported audio files to" option to "On + Align Bars and Beats".
However, I couldn't obtain a satisfiable result and the resulting track is out of time with the metronome. Using the File Tempo Editor seems really tricky because the string parts don't have sharp transients and I cannot see them on the audio track in order to align the beats.
What else could I do? I have the Cubase or Ableton option at hand, too, but with them I do know how I can achieve this. If someone could advise me something it would be great!
Thank you for the attention.
Comment: You could manually make a click track and then practice against it.
Comment: I meant you would manually make the click track aligned with the backing track. Hit record on a midi track while playing the backing track, and play in the clicks. Edit as desired afterwards.
Comment: Yes, but it would be funnier with the backing track and maybe after I will record myself with the backing track in the background, that's why I would need it to be aligned with the tempo, do you have any advice on how I can do it?
Comment: That's a good idea! I didn't think about it. Will try it, thank you!
Comment: If the strings track is in sync with the original full band mix, you could load both into your DAW, sync them, and then have the rhythm of the full mix analyzed.
Comment: @YourUncleBob Yes, they are in sync, I tried what you suggest but the problem is that the DAW has troubles to sync the tempo even on the full mix track... Maybe I am doing something wrong? I tried to use Logic's Smart Tempo like I wrote in the question
Answer: Even though both the audios have different relative starting points

both are in sync (OP's comment) hence the tempo will also be same for both so finding the tempo of the audio with guitars, drums will do the trick.
This can be done in Logic Pro X using the BPM Counter plugin on the track with drums.

A few things to keep in mind -

LPX's BPM Counter plugin works best on tracks with more obvious transients.
Best practice is to play the whole track with the plugin enabled but if you are short of time, you can set the playhead to the point where drums are starting.

In this particular case, it is at 1:38

Once you start the playback, the BPM Counter will start blinking, which means it is analysing it.

Let this continue for some  time and you'll see numbers will start to blink on the plugin screen

After a while, it will settle on one number - That's the BPM.
The BPM of the track in question is 78ish (BPM Counter reading is 77.9) but 78 should work for Piano practice.
More on BPM Counter here.


Create a mock Form for WebTestBase?

Question: Is there a way in the testing framework to define a generic form intended only when tests run?
I have created some custom form item Element classes. I have working Unit tests with them, but I would also like to provide Simpletests for them as well.
Answer: Core provides several examples of this.  The basic pattern is to create a test module, and have that module provide the form.  In your test ::setUp(), you add the test module to $modules, and then your form should be available for use.
Look through 'core/*/tests/modules' for the test modules, and if you have an IDE that class completes, a lot of the test form are (wait for it) TestForm.
However, in your case, I would look at existing Element classes and see what their integration tests look like.   I suspect you can just emulate what they are doing w/o needing your own test module.

Create a mock Form for WebTestBase?


How do I calculate the confidence interval of an ICC?

Question: Here's the output from my the summary of lmer function which I used to calculate the ICC.
   Linear mixed model fit by REML ['lmerMod']
   Formula: CareChange ~ 1 + (1 | PROVIDER)
      Data: MEA_data_1

   REML criterion at convergence: 35.2

   Scaled residuals:
       Min      1Q  Median      3Q     Max
   -0.3093 -0.2829 -0.2711 -0.2599  3.6206

   Random effects:
    Groups            Name        Variance  Std.Dev.
    PROVIDER          (Intercept) 0.0003096 0.01759
    Residual                      0.0660667 0.25703
   Number of obs: 239, groups:  PROVIDER_CALENDAR, 14

   Fixed effects:
        Estimate Std. Error t value
        (Intercept)  0.07119    0.01742   4.086

   ICC = 0.0003096 /(0.0003096 +0.0660667 ) = 0.004664315

I did not find any literature that shows how to calculate the CI for this    ICC value. Any help on this issue is much appreciated.
Answer: A straightforward way to calculate a confidence interval would be to create a bootstrapped distribution, then obtain the relevant quantiles from that distribution.  This can be done as a parametric or nonparametric bootstrap, depending on what assumptions you're comfortable with.  Generally, if you accept a Normal distribution for the random effects, a parametric bootstrap is also appropriate.
Since you're using R, the lme4 package offers a very nice parametric bootstrap function, bootMer() to calculate a bootstrapped distribution of any statistic of interest derived from a random effects model.  The parametric method is fully implemented, which simulates the model of interest using new values of the random effects with each iteration.  New values are drawn from a Normal distribution using parameters derived from the mixed model.  See the documentation in bootMer() for some detail on control over what effects get bootstrapped.  Set your own number of iterations, but 1000+ is a good rule of thumb.
To calculate this in R, you need to fit the random effects model and pass a function to bootMer() that calculates the statistic of interest.  An example implementation is below:
Example Code using R
#Make some mocked data
library(lme4)
library(reshape2)
set.seed(2024)  #For the Bell Riots
id <- factor(seq(1, 15))
id.mu <- rnorm(15, 10, 5)
mydat <- NULL
for (a in 1:length(id)){
  score <- rnorm(2, id.mu[a], 3)
  id.fr <- data.frame(id=id[a], score1=score[1], score2=score[2])
  mydat <- rbind(mydat, id.fr)
}
mydat <- melt(mydat, id.vars='id', value.name='score')

#Create function to calculate ICC from fitted model
calc.icc <- function(y) {
  sumy <- summary(y)
  (sumy$varcor$id[1]) / (sumy$varcor$id[1] + sumy$sigma^2)
}

#Fit the random effects model and calculate the ICC
mymod <- lmer(score ~ 1 + (1|id), data=mydat)
summary(mymod)
calc.icc(mymod)

#Calculate the bootstrap distribution
boot.icc <- bootMer(mymod, calc.icc, nsim=1000)

#Draw from the bootstrap distribution the usual 95% upper and lower confidence limits
quantile(boot.icc$t, c(0.025, 0.975))

Answer: I had the same need, here's another solution that I ended up with using the irr package to bootstrap this more easily.
(And less clever too, but if it can help future users ...)
I know the package gives you a confidence interval as well as the ICC package but if you're bothered because of the distribution and need a bootstrap:
#create the matrix needed for your task
matrix <- select(dataframe, var1, var2)

#you need to define the model, type and unit according to the question you're asking, here's for the example
irr:icc(matrix, model ="twoway", type = "agreement", unit = "single")

#New fuction, [7] is to get the value we want (icc in this case)
icc.boot <- function(data,x) {irr::icc(data[x,], model ="twoway", type = "agreement", unit = "single")[[7]]}

#bootstsrap distribution with 10 000 samples in this example
boot <- boot(matrix,icc.boot, 10000)

# get the confidence interval
quantile(boot$t,c(0.025,0.975))

# If you're unsure of the number of samples to choose, you can get a look of the distribution of the bootstrap
hist(boot)

I hope it helps.


Find the limit $\lim_{t \rightarrow \infty} tx(t)$ where $x=x(t)$ is the least positive root of equation $x^2 + \frac12 = \cos(tx)$.

Question: My attempts:
First of all, if we draw graphs of left and right sides of the equation, will see that $x(t) \rightarrow 0$ as $t \rightarrow \infty$, because segment $[0, \frac{\pi}{2t}]$ shrinks with growth of $t$. It's obvious.
Of course, it is too little and we need at least to find out an infinitesimal order of $x(t)$.
I thought about expansion $\cos(tx)$ into a Taylor series:
$$\frac12 + x^2 = 1 - \frac{(tx)^2}{2!} + \frac{(tx)^4}{4!} - \dots$$
but it didn't help much.
And some special cases:
If $t = 0$, then $x = \frac{1}{\sqrt2}$.
If $t = 1$, then $\frac12 + x^2 = 1 - \frac{x^2}{2!} + O(x^4)$ and $x \approx \frac{1}{\sqrt3}$.
If $t = 2$, then $\frac12 + x^2 = 1 - \frac{4x^2}{2!} + O(x^4)$ and $x \approx \frac{1}{\sqrt6}$.
But with growth of $t$ we can't continue with this idea.
I guess, we need to check hypotheses about the order of $x(t)$ and look if there is any contradiction with Taylor series, but I got stuck there.
Answer: Denote $u(t)=tx(t)$. Then $u$ is the least positive root of
$$
F_t(u)=\frac{u^2}{t^2}+\frac12-\cos u.
$$ We can see that $F_t(0)=-\frac12$ and $F_t(\frac{\pi}3)>0$. Since $F_t'(u)=\frac{2u}{t^2}+\sin u>0$ on $[0,\frac{\pi}3]$, it follows by intermediate value theorem and Rolle's theorem, that there is a unique root $u(t)$ of $F_t$ on $(0,\frac{\pi}3)$. Also, $\partial_tF_t(u)<0$ implies that $\frac{d}{dt}u(t)=-\frac{\partial_t F_t(u)}{F_t'(u)}>0$, i.e. $u(t)$ is increasing by implicit function theorem. Thus $u^*=\lim_{t\to\infty}u(t)\in [0,\frac{\pi}3]$ exists by monotonicity and should satisfy
$$
\frac12=\cos u^*,
$$that is, $u^*=\lim_{t\to\infty}tx(t)=\frac{\pi}3$.
Comment: Using of implicit function theorem is really tricky! Thank you, great proof!


Automatically close a resolved work item after some time without any activity

Question: We have a process for handling issues where the developer moves the work item to the "Resolved" state when he thinks he has finished his work.
Then it is up to the person who reported that issue to check if the resolution meets his needs and move it to the "Closed" state.
However people often don't bother moving the work items to the "Closed" state, so a lot of work items are piling up in the "Resolved" state.
Is it possible to automatically move work items from one state to another after an inactivity timeout (like 1 week or so)?
Answer: There is no built-in feature in Azure DevOps to automatically move work items from one state to another after an inactivity timeout.
You could use below workaround:

Get the work items via rest api Wiql - Query By Wiql, which changedate before 1 week.

Update the work items state to closed via rest api Work Items - Update.

my powershell script for your reference:
# Define the variables
$organization = "orgname"
$project = "projectname"
$token = "PAT"
$baseurl = "https://dev.azure.com/$organization/$project"
#$today = Get-Date
#$weekago = $today.AddDays(-7)
#$weekagostr = $weekago.ToString("yyyy-MM-dd")

# Encode the PAT token
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$token"))

# Define the WIQL query
$wiql = @{
    query = "SELECT [System.Id], [System.AssignedTo], [System.State], [System.Title] FROM workitems WHERE [System.TeamProject] = '$project' AND [System.State] = 'Resolved' AND [System.ChangedDate] < @today-7"
} | ConvertTo-Json

# Post the WIQL query to the REST API
$wiqlurl = "$baseurl/_apis/wit/wiql?api-version=6.0"
$wiqlresponse = Invoke-RestMethod -Uri $wiqlurl -Method Post -Body $wiql -ContentType "application/json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}

echo $wiqlresponse | ConvertTo-Json

# Loop through each work item
foreach ($workitem in $wiqlresponse.workitems) {
    # Get the work item id
    $id = $workitem.id

    # Update the state to "Closed"
    $updateurl = "https://dev.azure.com/$organization/_apis/wit/workitems/$id"+"?api-version=7.0"
    $body = '[{"op": "add", "path": "/fields/System.State", "value": "Closed"}]'
    $changestate = Invoke-RestMethod -Uri $updateurl -Method Patch -Body $body -ContentType "application/json-patch+json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}
    Write-Output "Work item $id updated to Closed"
}

You can run the script on a scheduled basis, for example, use devops pipeline with schedule trigger to run every week, or other schedule trigger tool like Azure Logic Apps, it's up to you.
Edited: change to use @today-7 for System.ChangedDate value.
Comment: Does `System.ChangedDate` also change when a comment is added, or only when the work item itself changes?
Comment: @wertzui, yes, the field value will also change when a comment is added, it standards for
the date and time when a work item was modified.
Comment: @wertzui, may i know if there's any update?


Given $N$ find the number of natural numbers less than $N$ that may be written in the form $\frac{(k)(k+1)}{2}$

Question:
Given $N$, find the number of natural numbers less than $N$ that may be written in the form $$\frac{k(k+1)}{2},$$ where $k\in \Bbb N$.

I know that the answer to this problem is approximately $\sqrt {2N}$, but I have no idea how to prove this.
Comment: What do you mean by 'solution'? Also $\sqrt {N}$ doesn't return a whole number unless $N$ is square. Can you clarify the question a bit?
Comment: He probably means the number of natural numbers which can be written in that form, i.e. $n = \left\vert\left\lbrace a\in\mathbb{N}, a<N | \exists k \in \mathbb{N}: a = \frac{k(k+1)}{2}  \right\rbrace \right\vert$
Comment: Edits:the correct answer is "approximately $${\sqrt {2N}}$$ values" and not "$${\sqrt {N}}$$". Sorry i was not able to edit the problem
Comment: What do you mean by "solution"?  A single number, N, does not **have**  a solution.  I suspect you were given some formula, with, say, variable "n", equal to N, but you did not give that formula.
Comment: also k belongs to the set of Natural numbers
Answer: (NOTE: I am counting $0$ as a natural number, so $0$ is one of the solutions since $0=\frac{0(0+1)}{2}$.)
We have the following inequality:
$$\frac{k(k+1)}{2} < N$$
We need to solve for $k$ in terms of $N$. Multiply both sides by $2$ and distribute the $k$ on the left side:
$$k^2+k < 2N$$
Subtract both sides by $2N$:
$$k^2+k-2N < 0$$
Quadratics with positive coefficients are negative in between the zeroes of the polynomial, so we can use the quadratic formula to find the range of possible $k$:
$$\frac{-1-\sqrt{1^2-4\cdot 1\cdot -2N}}{2\cdot 1} < k < \frac{-1+\sqrt{1^2-4\cdot 1\cdot -2N}}{2\cdot 1}$$
First, before we simplify this, notice that $0$ satisfies the original inequality. Therefore, the minimum is less than $0$. However, we only care about natural numbers, so we know that $k > 0$. Therefore, we can get rid of the minimum:
$$k < \frac{-1+\sqrt{1^2-4\cdot 1\cdot -2N}}{2\cdot 1}$$
Now, simplify:
$$k < \frac{-1+\sqrt{1+8N}}{2}$$
$$k < -\frac 1 2+\sqrt{\frac 1 4+2N}$$
Now, depending on what $N$ is, this could be $\lfloor \sqrt{2N} \rfloor-1$ or $\lfloor \sqrt{2N} \rfloor$ solutions, but the answer is $\approx \sqrt{2N}$ solutions.


Using group_concat With a Condition: Display 0 if Values are Not Equal

Question: I just want to display column fields horizontally but also putting a condition to it. Display zero if it has not met the condition.
Example problem: Find the PAYCODE 912 and 686 and display the amount, if not available, display 0
my_table

EMPLOYEE
PAYCODE
AMOUNT

1
912
1

1
123
3

2
912
5

2
686
7

3
111
4

Output must be:

EMPLOYEE
AMOUNT

1
1,0

2
5,7

3
0,0

My code so far:
SELECT
    EMPLOYEE,
    GROUP_CONCAT(DISTINCT CONCAT(
          IF(PAYCODE = '912', AMOUNT, '0'),
          IF(PAYCODE = '686', AMOUNT, '0'))
          SEPARATOR',') as AMOUNT
FROM
    my_table

Note: There are no duplicate paycodes on a similar employee. e.g. two 912 paycodes
Comment: DO you have a table were all paycodes are stored?
Comment: @P.Salmon Yes it is from my_table as an example for now.
Answer: I'm thinking a cross join approach should work here:
SELECT e.EMPLOYEE,
       GROUP_CONCAT(COALESCE(t.AMOUNT, 0) ORDER BY e.PAYMENTTYPE DESC) AS AMOUNT
FROM (SELECT DISTINCT EMPLOYEE FROM my_table) e
CROSS JOIN (SELECT '912' AS PAYMENTTYPE UNION ALL SELECT '686') p
LEFT JOIN my_table t
    ON t.EMPLOYEE = e.EMPLOYEE AND
       t.PAYMENTTYPE = p.PAYMENTTYPE
GROUP BY e.EMPLOYEE;

The cross join between the e and p subqueries generates all employee/payment type combinations of interest (only types 912 and 686).  We then left join to your table to bring in the amounts, which if are missing we report 0 instead.
Comment: Hi tim, thank you for always answering. It took me some time to understand the answer and I think that COALESCE is not working because 0 is not showing when paycode 686 for example is not available.


On integer values which are attained by $n/\pi(n)$ only once

Question: Let $\pi (n)$ denote the prime counting function. I can prove that $\mathbb N \setminus \{1\} \subseteq \{n/ \pi(n) : n \in \mathbb N \}$ . Now for every integer $m>1$ , define $s(m) := \{ n \in \mathbb N : n>1 , n/ \pi(n)=m \}$ . Does there exist any integer $m$ such that $|s(m)|=1$ ? If there exists such integers , then are there infinitely many of them ?
Comment: Seems that $\frac{n}{\pi(n)}=11$ only holds for $n=175197$
Comment: The values $2,3,4,\cdots ,17$ except $11$ appear more than once.
Comment: $18$ and $19$ appear more than once as well.
Comment: @Peter: Note that the Rosser–Schoenfeld bound $\pi(x) < \frac x{\log x}\big( 1 + \frac{3}{2\log x} \big)$ shows that $\frac n{\pi(n)} > 11$ for $n \ge 230000$.
Comment: How did you prove that $\frac{n}{\pi(n)}=k$ has a solution for every integer $k>1$ ?
Comment: @Peter : here's a general way to see how every integer more than 1 is attained : Let $f :\mathbb N \to \mathbb N$ be a function such that the sequence $\{n/f(n)\}$ is unbounded . If $x,n $ be positive integers such that $x/f(x) \le n $ , then $y/f(y)=n$ , where either $y=x$, or if $x/f(x)\ne n $, then we can take $y=max \{w \in \mathbb N : x \le w < z , w/f(w) n$ (such positive integer $z$ exist as the sequence $\{ m/f(m) \}$ is unbounded ) . For our case, note that $2/\pi(2) \le n$ for every integer $n>1$ and $\lim_{n \to \infty} n/\pi(n)=\infty $
Comment: @Peter : in the above comment , one more property of $f$ has to be assumed which I forgot to mention , $f$ has to be non-decreasing
Comment: @Peter : Just work out the proof, if you can prove it , then it is correct ...
Comment: What does mean $|s(m)|$? Is it the cardinal of $s(m)$?
Comment: Thanks for your answer, misao. I was wrong misunderstanding your question. Regards.
Comment: @Piquito : no problem ... I am happy to see that my problem has gained attention ..
Answer: Not a complete answer, but a table showing the frequences using the primes upto $10^{10}$. The first column is the value of $\large \frac{n}{\pi(n)}$ and the second column shows how often it appeared :
<code>2   4
3   3
4   3
5   6
6   7
7   6
8   6
9   3
10   9
11   1
12   18
13   11
14   12
15   21
16   3
17   10
18   33
19   31
20   32
21   24
</code>
Apparently, the frequences do not strictly increase. Value $16$ is particular suprising. It appeared only $3$ times. In total, only $243$ times, an integer-value appears.
UPDATE : You are right, misao. I didn't understand the argument, but finally I could prove your claim. Sorry for my doubt ...
Moreover, the following can also be proven : If $k>2$ and $f(p)<k$, then there exists $N>p$ with $f(N)=k$. This implies misao's claim.
Proof : Suppose , $q>p$ is the smallest number with $f(q)\ge k$. If $f(q)=k$, we are done. Otherwise, we have $p<\pi(p)\cdot k\le \pi(q)\cdot k<q$. If there is no prime $P$ with $p<P<q$, then we can choose $N:=\pi(p)\cdot k$ and we have $\frac{N}{\pi(N)}=\frac{N}{\pi(p)}=k$. If there is at least a prime $P$ with $p<P<q$, assume $P$ is the largest of those. Now, we have either $f(P)=k$ and are done, or we have $P<\pi(P)\cdot k\le \pi(q)\cdot k<q$ and $N:=\pi(P)\cdot k$ does the job.
So, if $s$ is the smallest number with $f(s)=k$ ($k>2$), then there is another number $t$ with $f(t)=k$, if and only if for some positive integer $m$, the interval $[s,s+mk]$ contains at least $m$ primes.
Comment: Since $n/\pi(n) >11$ for $n>230000$ (as Greg Martin remarked) and you have checked upto $10^{10}>230000$ that $11$ appears only  once , so $11$ appears only once for all integer values. Thus we atleast now know that $|s(11)|=1$
Comment: With the help of Wolfram alpha, I could extend to $26$. All values from $2$ to $26$, except $11$, appear at least twice.
Comment: And finally, with the $n$-th prime page, I found out that $27$ appears at least twice.


How can I filter a view by "has translation"?

Question: Filter a view by "Current user language" creates an empty div when missing translation. This is problematic because it breaks my layout. See the below image for my criteria.
Answer: This is not tested but you could probably add the filter "Node translation: Child translation" to your view. Together with the current user language fiter this could work. Description is: "Content that is a translation of a source translation."
Answer: Well this can easily be solved by adding a "No results behavior"  to be a global: text area, global:view or anything you have to say when it's empty.
just add whatever the HTML you want to display there. this can be a workaround for the problem that you are having.


What kind of algebraic structure is this

Question: I know that a commutative ring with an additional scalar multiplication on it is called an associative algebra. If the ring also has a 1 it is called a unital algebra. What would you call a field with an additional scalar multiplication(from a different field) on it?
Comment: Consider the orbit of the unit element under scalar multiplication. That will give you a copy of the scalar field inside the field (use the fact that a field has no non-zero proper ideals). In your example, the subfield consists of scalar matrices. Conversely, whenever you have a field with a subfield, the big field is clearly an algebra under the subfield, just using multiplication in the big field.
Comment: @AlexB. Thanks, this is a nice way to think about it. Further research also seems to suggest it is an F-algebra (which just seems to be a special type of R-algebra).
Comment: Good question. As I'm sure you're well aware, take a field $K$, then the rational function field $K(x)$ is an example of what you're talking about, perhaps the canonical example.
Comment: It's just a field with a subfield.
Comment: [Just like](http://math.stackexchange.com/a/4300/242) R-algebras are rings containing a central image of R.
Comment: @AlexB. I'll have to think about that, it's not quite clear to me. One example I'm thinking about is the collection of positive definite symmetric circulant matrices. I'm not sure how this example is a field with a subfield.
Answer: An associative algebra over a commutative ring is just an associative ring $A$ which has some scalar multiplication from a commutative ring $R$ which satisfies some axioms.
If both $A$ and $R$ are fields, I'd still call $A$ an $R$-algebra. You might improve by calling it an $R$ division algebra.
Comment: I'd call $A$ a field extension of $R$.
Comment: I found a document that refers to this structure as a F-algebra. http://darkwing.uoregon.edu/~brundan/math647fall04/ch4.pdf
Comment: @mtiano It kind of looks like you're attaching special significance to the letters $R$ and $F$. If you replaced the letter $R$ above with any other commutative ring (such as a field $F$, a field $k$ or an integral domain $D$, you'd have an $F$-algebra, a $k$-algebra, or a $D$-algebra.
Comment: Dear @lhf : It's true, but I felt like this is most in the spirit of the OP's original post, relating them to $R$-algebras. Field extensions are *structures* I suppose, but they aren't really defined as more than one field containing another, so the algebra relationship (while there) is silent.
Comment: @rschwieb, you're quite right.
Answer: If $k$ is a commutative ring, then a commutative $k$-algebra $A$ is the same as a homomorphism of rings $k \to A$. If $k,A$ are fields, then $k \to A$ is injective. Therefore this is just a field extension.