Spark `LiveListenerBus` Exception is freaking me out

Question: I'm using AWS EMR clusters, and the spark version is
spark-submit --version
Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /___/ .__/\_,_/_/ /_/\_\   version 2.0.1
      /_/

Branch HEAD
Compiled by user ec2-user on 2016-10-11T00:04:18Z
Revision 8182b3893b6ce47724d35a32fbea3605a0d9cb98
Url firstname.lastname@example.com:/pkg/Aws157BigTop

I run some Spark GraphX jobs on the cluster and the data is in json format (gzipped, stored on aws s3). I found that, if the data is small (like around 1000 lines), the submitted jobs will run ok without any error or exception, but if I increase the data size (like around 1m lines), then the LiveListenerBus exception coming down like diarrhea, which really freaks me out :-(
I tried to tune parameters likes --num-executors,--executor-memory, doesn't help at all.
Jobs submitted like this,
spark-submit --class "MyJob" --master yarn mypkg.jar   // if do --master local, no exception
Exception like this,
17/06/11 11:18:58 ERROR LiveListenerBus: Listener EventLoggingListener threw an exception
java.util.ConcurrentModificationException
        at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
        at java.util.ArrayList$Itr.next(ArrayList.java:851)
        at scala.collection.convert.Wrappers$JIteratorWrapper.next(Wrappers.scala:43)
        at scala.collection.Iterator$class.foreach(Iterator.scala:893)
        at scala.collection.AbstractIterator.foreach(Iterator.scala:1336)
        at scala.collection.IterableLike$class.foreach(IterableLike.scala:72)
        at scala.collection.AbstractIterable.foreach(Iterable.scala:54)
        at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:59)
        at scala.collection.mutable.ListBuffer.$plus$plus$eq(ListBuffer.scala:183)
        at scala.collection.mutable.ListBuffer.$plus$plus$eq(ListBuffer.scala:45)
        at scala.collection.TraversableLike$class.to(TraversableLike.scala:590)
        at scala.collection.AbstractTraversable.to(Traversable.scala:104)
        at scala.collection.TraversableOnce$class.toList(TraversableOnce.scala:294)
        at scala.collection.AbstractTraversable.toList(Traversable.scala:104)
        at org.apache.spark.util.JsonProtocol$.accumValueToJson(JsonProtocol.scala:314)
        at org.apache.spark.util.JsonProtocol$$anonfun$accumulableInfoToJson$5.apply(JsonProtocol.scala:291)
        at org.apache.spark.util.JsonProtocol$$anonfun$accumulableInfoToJson$5.apply(JsonProtocol.scala:291)
        at scala.Option.map(Option.scala:146)
        at org.apache.spark.util.JsonProtocol$.accumulableInfoToJson(JsonProtocol.scala:291)
        at org.apache.spark.util.JsonProtocol$$anonfun$taskInfoToJson$12.apply(JsonProtocol.scala:283)
        at org.apache.spark.util.JsonProtocol$$anonfun$taskInfoToJson$12.apply(JsonProtocol.scala:283)
        at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
        at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
        at scala.collection.immutable.List.foreach(List.scala:381)
        at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:35)
        at scala.collection.mutable.ListBuffer.foreach(ListBuffer.scala:45)
        at scala.collection.TraversableLike$class.map(TraversableLike.scala:234)
        at scala.collection.AbstractTraversable.map(Traversable.scala:104)
        at org.apache.spark.util.JsonProtocol$.taskInfoToJson(JsonProtocol.scala:283)
        at org.apache.spark.util.JsonProtocol$.taskEndToJson(JsonProtocol.scala:145)
        at org.apache.spark.util.JsonProtocol$.sparkEventToJson(JsonProtocol.scala:76)
        at org.apache.spark.scheduler.EventLoggingListener.logEvent(EventLoggingListener.scala:137)
        at org.apache.spark.scheduler.EventLoggingListener.onTaskEnd(EventLoggingListener.scala:157)
        at org.apache.spark.scheduler.SparkListenerBus$class.doPostEvent(SparkListenerBus.scala:45)
        at org.apache.spark.scheduler.LiveListenerBus.doPostEvent(LiveListenerBus.scala:36)
        at org.apache.spark.scheduler.LiveListenerBus.doPostEvent(LiveListenerBus.scala:36)
        at org.apache.spark.util.ListenerBus$class.postToAll(ListenerBus.scala:63)
        at org.apache.spark.scheduler.LiveListenerBus.postToAll(LiveListenerBus.scala:36)
        at org.apache.spark.scheduler.LiveListenerBus$$anon$1$$anonfun$run$1$$anonfun$apply$mcV$sp$1.apply$mcV$sp(LiveListenerBus.scala:94)
        at org.apache.spark.scheduler.LiveListenerBus$$anon$1$$anonfun$run$1$$anonfun$apply$mcV$sp$1.apply(LiveListenerBus.scala:79)
        at org.apache.spark.scheduler.LiveListenerBus$$anon$1$$anonfun$run$1$$anonfun$apply$mcV$sp$1.apply(LiveListenerBus.scala:79)
        at scala.util.DynamicVariable.withValue(DynamicVariable.scala:58)
        at org.apache.spark.scheduler.LiveListenerBus$$anon$1$$anonfun$run$1.apply$mcV$sp(LiveListenerBus.scala:78)
        at org.apache.spark.util.Utils$.tryOrStopSparkContext(Utils.scala:1249)
        at org.apache.spark.scheduler.LiveListenerBus$$anon$1.run(LiveListenerBus.scala:77)

OK, I searched SO and people say this is a known issue, which could be fixed by upgrading Spark to newer version. HOWEVER, looks like I am the only one of the team experiencing this issue (maybe because other guys are not doing GraphX jobs?)
My question,
1) Could this exception relate to the GraphX package of Spark?
2) How to fix it? Do I have to upgrade the Spark? And how to upgrade on AWS?
Answer: java.util.ConcurrentModificationException occured because when the iterator is doing iterator.hasNext() the iterator object changed such as update,remove and son on.
Comment: So you mean, this exception could be a bug in my code?
Comment: yeah,you should check your code especially for the iterator.


How Do I Disable CiviCRM locally if I don't need it?

Question: I'm working on a Drupal 7 site build and I have a local development environment.  The site has CiviCRM working with it, but I'm not doing any work related to CiviCRM so I'd like to just have it disabled in my local environment.
Can I somehow set my civicrm.settings.php or other file to just have CiviCRM disabled (or pointing to a dummy civi install) when working locally?
I could disable the module, obviously, but this throws a bunch of errors on various places, so I guess ideally I want to 'fake out' CiviCRM with fake database or other information in settings.php, making everything just fail silently.
Answer: In a clean Drupal and CiviCRM install, the CiviCRM module can be disabled without generating any errors.
Getting CiviCRM working in a local development environment that doesn't mirror the configuration of the actual site can be a pain and CiviCRM adds a lot of overhead to page loads and increases the memory required for many tasks, but the steps for resetting the paths and deleting temp files are well documented at http://wiki.civicrm.org/confluence/display/CRMDOC/Moving+an+Existing+Installation+to+a+New+Server+or+Location
CiviCRM includes handful of Drupal modules that give Drupal access to the CiviCRM data in modules like Views and Rules as well modules that do things like add or remove users from roles based on having paid their membership, but CiviCRM is much more than just those modules.  CiviCRM is a large PHP project (much larger than Drupal core) that runs within Drupal, WordPress, or Joomla's menu and authentication and includes APIs and hooks that allow custom development to tap into CiviCRM at many levels with any of those CMSes.
You could probably get away with a "dummy" CiviCRM install if the site hasn't done much customization to CiviCRM or written any custom code that leverages it, but if disabling CiviCRM "throws a bunch of errors on various places" my guess is you are working with an instance of CiviCRM that has already been customized and integrated.  You'd have to share the specific errors for anyone to confirm that.  As soon as anyone added a custom field to one of the CiviCRM data types (profiles, contributions, events, etc), that fields could be used in a View.  If a custom field is already used in a View, you have to get the client's copy of CiviCRM running or risk deleting a CiviCRM reference when updating a View.
While CiviCRM isn't Drupal, it isn't rocket science either.  If you aren't sure what customizations and integration have been done, it is much safer to get CiviCRM working than trying to disable it.
Answer: I use a "fake" database and a local civicrm.settings.php.  you can encrypt the data if necessary.  That way any references are maintained.  Another approach is to use a multisite configuration and share some of the tables.
If you disable the civicrm module, and you are getting errors, then it will depend on the nature of the errors (ie. view references to civicrm entities?)  If you go that route, refer to this or this
Comment: Thanks, simple response that confirmed what I found which is it's best to just have a fake civi db setup to avoid errors.


PowerShell script not completing what it should do when scheduled with Windows Task Scheduler

Question: I found a script that can delete files over X days old and changed it a bit so that I will scan different network folders to see if there are files that are older than X days. Now when I run the script with PowerShell ISE the script is working fine and doing what it should do. It is taking about one hour.
Now when I try to schedule the script with Windows Task Scheduler, the task starts and completes 10 seconds later, but the script didn't run. So were no files deleted?

Scheduled Task setting:
General

Run task with account that has logon as batch priviledges
Run whether user is logged on or not
Run with highest priviledges

Trigger

Daily run

Action

Program/script: Run a program C:\windows\system32\windowspowershell\v1.0\powershell.exe
Argument: -File "C:\scripts\deletefiles.ps1"

What am I doing wrong? Or why is it not running the script?
The script can be found here.
Answer: You need to Set-ExecutionPolicy so that the account running the scheduled task is allowed to execute PowerShell scripts:
Set-ExecutionPolicy -Scope LocalMachine Unrestricted

As per the help file for Set-ExecutionPolicy, a scope of LocalMachine sets the policy for all users of that computer. As opposed to if you just Set-ExecutionPolicy Unrestricted from your own user account, it only sets that policy for your own user account.  Furthermore, there are also separate policies for 32-bit and 64-bit versions of PowerShell.
And if Set-ExecutionPolicy -Scope LocalMachine Unrestricted is too much of a security compromise to you, you could set it just for that one user by logging in as that user and doing it, or executing a process under that user's security context and setting the policy for that user.
Oh, and well, this probably doesn't need to be said, but we can't know if the user you've assigned to this scheduled task has the permissions necessary to delete stuff from those UNC paths.


What is the proper chord interpretation for the intro to Stairway to Heaven?

Question: The opening sequence in Stairway to Heaven is an A minor chord followed by something strange followed by C/G, D/F#, and Fmaj7. I've seen the second chord notated as Am/G#, G#aug, and even Am/maj7/add2. None of these seem satisfactory.
The notes are G# C E and B. I'm interested in understanding how this chord works from a music theory perspective.
Comment: Here's an interesting discussion of this: https://youtu.be/eXqNyWehVEQ
Comment: Here's some analysis on Noteflite: https://www.noteflight.com/scores/view/54844f1f3a6bb099a4c04e640559ac3d8d13f7ae
Comment: Based on the answers, my favorite is E/G#(add ♭13).
Answer: The second chord is a chromatic passing chord: the bass line is descending (A -> G#) whereas the top line is ascending (A -> B). It doesn't really have a name which describes it properly (CaugMaj7 is a possibility as is Eaug). The third chord is a true C with G in the bass, so again the bass descends (G# -> G) and the top ascends (B -> C).
So, viewing the first three chords, the bass descends in semitones: A G# G, the top ascends A B C, and the inner voices (C and E) stay constant. Viewed as a sequence from Am to C, the middle chord could be seen as a variety of E (E aug) which is the dominant seventh of Am.
Extra material: I am reminded of musicologist Alan Pollack's comment about a similar chord sequence which is the bridge of "All my loving": In "theoretical" terms, such an augmented chord [the second chord in the sequence] is said to not have a root at all, but is rather the incidental byproduct of melodic motion by an inner voice of the harmonic texture; in this case, from C# -» C-natural -» B; what my jazz-trained friend calls a "line cliche." The fact that it is sustained for a full measure, essentially just as long as any other chord in the song, is what particularly draws your attention to it.... In this case, the sequence is C#m ? E, but it's the same idea. The 'genius' of Page (leaving aside the court case) is to add the ascending line on top which mirrors the descending line in the bass.
Comment: +1 for the notion of it being just a chromatic passing chord. It's clearly just an outgrowth of the lament bass concept, though here with some linear motion above it, as well. Trying to slap some chord root and quality to it misses the point, I think.
Comment: I've seen it argued that a 6th on a dominant chord is always a 13th and I've heard that it's the presence of the 7th that makes a 6th a 13th. These are usually coincident, but not in this case, so the question.
Comment: I like the E aug interpretation. Since they retain the B in the melody, and there's no 7th, would it be most correct to call this a flattened 6 (vs 13th or sharpened 5th)? Isn't the altered note generally the highest note in the melody?
Comment: @PaulJackson: I prefer to think of it as a CaugM7/G# (2nd inversion) since it better explains the role of the B.  In a M7 chord, the 7th "wants" to resolve up, and in augmented chord the fifth wants to resolve chromatically.  It may seem odd to have a form of C chord resolve to another form of C chord, but both of those things happen here.
Comment: The function of the second chord can pretty reasonably be analyzed as dominant, as we'd have i - V - III, making it a sort of small deceptive cadence. In this case, the C is just a flat 13 of the E dominant, and these kind of extensions aren't exactly strange. This would make a lot more sense than a C aug in the context of the progression, so the actual name would be something like an E b13 or add b6. If you play the same passage with a D natural in place of the C, the color of the chord changes a bit, but not the function. You could also make an argument for it being a sort of suspension, sin


How to convert annualized Standard Deviation of innovation of AR1 process to monthly?

Question: I want to calculate the standard deviation of innovation of AR1 process from its annual value to its corresponding monthly value. Say, I have
$x_t=\rho x_{t-1} +\epsilon_t$ where $\epsilon \sim N(0,\sigma^2)$
 and that  x is annual data. Now to compute the monthly counterpart of this process, I need to know the monthly values for $\rho$ and $\sigma$ to approximate the process. I know how to get $\rho$, but I am not sure how to get the other one, i.e $\sigma$. I searched quickly online, finance people scale the number by root 12, but I am not sure if that is correct.
Any help on this is much appreciated.
Answer: Let $y_i$ be the monthly process, where $i = 1, 2, ...$ are the months. Let $n=12$ to convert months to years, so that $y_{n t} = x_t$.
Suppose ${y_i}$ is AR(1), with $y_i = \alpha y_{i-1} + \eta_i$, where $\eta \sim N(0,\gamma^2)$. Then,
$$ y_{i} = \alpha^n y_{i-n} + \sum_{j=0}^{n-1} \alpha^{j} \eta_{i-j} $$
Then we can express $\epsilon_t$ as,
$$\epsilon_t = \sum_{j=0}^{n-1} \alpha^{j} \eta_{nt-j}$$
${\eta_i}$ are iid $N(0,\gamma^2)$, so $\epsilon_t$ is normally distributed with mean zero and variance,
$$ Var(\epsilon_t) = \sum_{j=0}^{n-1} \alpha^{2j} \gamma^2 $$
Since $Var(\epsilon_t) = \sigma^2$, then we have that the variance of the monthly innovations is,
$$\gamma^2 = \frac{\sigma^2}{\sum_{j=0}^{n-1} \alpha^{2j}}$$
Update:
Assuming you estimate $\hat\rho$ and $\hat\sigma^2$ from the annual AR(1), you can get $\hat\alpha = \hat\rho^{1/n}$, and then compute the estimate of the monthly innovation variance as,
$$\hat\gamma^2 = \frac{\hat\sigma^2}{\sum_{j=0}^{n-1}\hat\alpha^{2j}}$$.
Note that if we have a random walk for the annual process, $x_t = x_{t-1} + \epsilon_t$, then we also have a random walk for the monthly process, and so $\hat \alpha = 1$, and $\hat\gamma^2 = \hat\sigma^2 / n$. So the monthly vol becomes the annual vol scaled by square root of 12.
Comment: Welcome to our site!  Could you please explain what question you are answering? This one appears to ask for advice about *how to estimate $\sigma$*.  Alternative interpretations seem possible--even likely--so it's important to tell us what you think the question is asking.


Como usar o "float: left" de maneira correta?

Question: Tenho usado bastante o float: léft; ultimamente, mas há vezes que ele não funciona como eu espero. Exemplo:

(imagem 1) Reparem que aparece uma margin que não deveria estar aqui.

(imagem 2) A margin some, mas como não tem float a outra div fica na linha de baixo.
O objetivo do código é fazer um menu superior parecido com esse:

Ele não deveria apenas jogar as divs uma ao lado da outra? Como fixo isso? Por que ele faz isso?

@import url(https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300,700);
@import url(https://fonts.googleapis.com/css?family=Open+Sans:400,300,700,600);

*{margin: 0; padding: 0;}

body{
    background: #ecf0f1;
    color: #2c3e50;
    font-family: 'Open Sans', sans-serif;
}

.top-menu{
    width: 100%;
    height: 50px;
    background: #c0392b;
    border-bottom: 4px solid #96271C;
    color: #f2f2f2;
    position: fixed;
}

.top-menu .content{
    width: 900px;
    margin: 0 auto;
}

.burger-menu{
     background: #96271C;
     height: 100%;
     width: 100px;
     float: left;
     position: relative
}

.burger > div{
    width: 21px;
    height: 4px;
    border-radius: 2px;
    display: block;
    background: #fff;
    margin-bottom: 4px;
}

.burger{
    float: left;
    margin: 15px 10px;
}

.burger-menu{
    font-size: 18px;
    text-transform: uppercase;
    line-height: 50px;
}

.title-section{
    width: 300px;
    margin: 0 auto;
    float: left;
    display: block;
    position: relative;
}

.title-section .title{
    text-align: center;
    text-transform: uppercase;
    font-size: 32px;
    line-height: 50px;
    font-weight: 300;
}

.search-section{
    width: 160px;
    height: 30px;
    margin-top: 10px;
}

.search-section input, input:focus{
    width: 160px;
    height: 30px;
    background: #96271C;
    border-radius: 3px;
    border: 1px #ecf0f1 solid;
    padding:5px;
    color: #f2f2f2;
    outline: none;
}

::-webkit-input-placeholder {color: #f2f2f2;}
:-moz-placeholder {color: #f2f2f2;}
::-moz-placeholder {color: #f2f2f2;}
:-ms-input-placeholder {color: #f2f2f2;}
<!DOCTYPE HTML5>

        <meta charset="utf-8">
        <title>Menu G1</title>
        <link rel="stylesheet" type="text/css" href="css/style.css">

menu

Política

                    <input type="text" placeholder="Pesquisar" name="pesquisa-menu">

Comment: Eu acho que seria importante você [edit] a postagem e deixar bem claro o resultado que quer obter, em vez de querer usar o `float:left` em qualquer ocasião. Pode acontecer de no seu caso o `float:left` não ser adequado pra isso. Ou se quer só aprender sobre o `float`, aí a pergunta já é outra, e as imagens pra cima não são mais relevantes. Lembre-se que quanto mais objetiva a pergunta, maior a chance de uma boa resposta, pois boas respostas dependem da comunidade entender o problema de fato, e não só os desdobramentos que o problema causa.
Answer: A real utilidade do float é fazer um bloco flutuar em cima de bloco de texto, como por exemplo aquelas colunas de jornal.
Ele não serve para fazer layout, utilizam ele como gambiarra já que não existia um padrão pra fazer esse tipo de coisa, você até consegue fazer layout com Float mas é uma dor de cabeça horrivel que só quem já fez e teve que dar manutenção no código sabe.
Dá uma olhada em Flexbox, ele resolve parte do problema de fazer layout, tem uns frameworks que implementam ele pra você usar com Sass e Stylus, já tem um bom suporte dos navegadores e é uma coisa linda trabalhar com ele <3
Comment: Um adendo, o flex css não tem suporte a todos os navegadores. Os malditos IE6~9 não suportam o comando e mesmo a versão mais atual do IE ainda apresenta alguns bugs. Versoes mais antigas do navegador padrao do android também não suportam, porém não é um problema pra se alarmar, o suporte do Flex atinge cerca de 90% dos usuários, só será um problema se você precisar dar suporte pros IE antigos
Comment: Realmente, refiz o Layout usando flexbox e é muito mais fácil de mandar! Valeu.
Comment: Brother, embora vc teve o aceite na resposta e 2 positivos, acredito que deveria rever seu conceito sobre float... Ele permite que os elementos flutuem a sua direita ou a esquerda, ou float:none, que nega a flutuação ao seu redor.. Elementos posicionados absolutamente ignoram a propriedade float.
Comment: se liga na dica: https://www.youtube.com/watch?v=qBxGXb4iTQw&feature=youtu.be
Answer: FEIJAO COM ARROZ DO FLOAT:
Pra exemplificar vamos então criar uma div wrap, ela será o elemento pai que servirá de referencia pra conter os elementos flutuantes.
Dentro desse elemento pai teremos duas caixa A e B, vamos usar elas pra brincar com o float. Esse será a nossa estrutura:

A

B

.wrap{
  width:400px;
  border:1px solid green;
}
.A{
   display:block;
   background:red;
   padding:50px 0;
   width:120px;
}
.B{
   display:block;
   background:blue;
   padding:50px 0;
   width:120px;
   text-align:center;
}

Dê uma olha no link pra você entender melhor: https://jsfiddle.net/ow6ds5bk/
Primeiramente vamos flutuar as duas caixas pra esquerda, então vamos colocar o float NOS DOIS ELEMENTOS que queremos flutar
.A{float:left}
.B{float:left}

Se você olhar no nosso código https://jsfiddle.net/ow6ds5bk/3/ verá que flutuou os elementos como o pretendido, porém algo está errado. O elemento pai se desmanchou, e o restante da página continuou sendo flutuado. Vamos corrigir isso.
Vamos criar uma classe clear, ela servirá pra resetar a flutuação após as nossa caixas, assim não afetará o resto da página e tambem vai consertar o nosso elemento pai:
.clear{
  clear:both;
}

Agora o nosso html ficará assim:

A

B

Float é fácil

.wrap{
  width:400px;
  border:1px solid green;
}
.A{
  display:block;
  background:red;
  padding:50px 0;
  width:120px;
  text-align:center;
  float:left;
}
.B{
  display:block;
  background:blue;
  padding:50px 0;
  width:120px;
  text-align:center;
  float:left;
}
.clear{
  clear:both;
}

Se você olhar para a nossa pagina verá que alcançamos a estrutura desejada: https://jsfiddle.net/ow6ds5bk/4/
Você precisa ficar atento também para o tamanho dos elementos, se a soma do width de todos os elementos superarem o width do elemento pai, algumas coisas podem ser empurradas pra baixo, veja: https://jsfiddle.net/ow6ds5bk/5/
Toda propriedade que mexe com a dimensão do elemento também deve ser considerada pra conta: margin, padding, border, width, etc.
Agora Vamos ousar mais, queremos um elemento à direita e o outro à esquerda. Não é difícil basta usar a mesma lógica:

A

B

Float é fácil

.wrap{
  width:400px;
  border:1px solid green;
}
.A{
  display:block;
  background:red;
  padding:50px 0;
  width:120px;
  text-align:center;
  float:left;
}
.B{
  display:block;
  background:blue;
  padding:50px 0;
  width:120px;
  text-align:center;
  float:right;
}
.clear{
  clear:both;
}

Mamão com açúcar né? Veja como ficou o nosso exemplo: https://jsfiddle.net/ow6ds5bk/7/
Legal, agora vamos colocar os dois elementos pra direita, basta usar a mesma lógica anterior certo? ERRADO: https://jsfiddle.net/ow6ds5bk/8/
Veja que as caixas ficaram invertidas, isso acontece por que a caixa A é o primeiro elemento a ser exibido, então ele será o primeiro flutuado pra direita.
Pra resolver isso vamos criar um elemento que flutuará pra direita, ele vai abrigar as nossas 2 caixas. As caixas flutuarão pra esquerda fazendo o efeito que nós procuramos:

A

B

.wrap{
  width:400px;
  border:1px solid green;
}
.A{
  display:block;
  background:red;
  padding:50px 0;
  width:120px;
  text-align:center;
  float:left;
}
.B{
  display:block;
  background:blue;
  padding:50px 0;
  width:120px;
  text-align:center;
  float:left;
}
.right-container{
  float:right;
}
.clear{
  clear:both;
}

Veja como ficou agora o nosso exemplo https://jsfiddle.net/ow6ds5bk/6/ coisa linda!
Acho que isso é básico pra trabalhar com float sem ter sustos. Mas usar float pra montar o layout do site não é legal, existem muitas outras alternativas que você pode e deve usar: grids, frameworks html, flex. A menos é claro se você não se preocupa em se desesperar sempre que a sua página é exibida numa resolução diferente.
Apesar de não ser recomendado, é bom saber. Vai que um dia você precisa dar manutenção num site montado com float?

ATUALIZAÇÃO:
Se você der uma olhada no código, verá que eu fiz uma marcação no código pra definir onde deve ocorrer a limpeza das flutuações. Mas essa é uma técnica muito antiga, antes do CSS2, quanto não tínhamos os seletores :before e :after .
Podemos utilizar uma técnica mais moderna pra realizar a mesma função:
Basta criar a classe clearfix:
.clearfix:before,
.clearfix:after {
   content: " ";
   display: table;
}

.clearfix:after {
   clear: both;
}

.clearfix {
   *zoom: 1;
}

Basta adicionar a classe clear fix no elemento pai referente aos elementos que receberão a flutuação.

A

B

Float é fácil

Assim você terá um código mais limpo. Veja como o nosso exemplo ficou: http://codepen.io/anon/pen/ezZGOw


Spring 4 autowire to Filter

Question: I build app with Spring 4.1.6, I have all config in java class. My AppConfig:
    @Configuration
    @EnableWebMvc
    @ComponentScan(basePackages = "pl.wrweb.springrest")
    public class AppConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean(name = "messageSource")
    public ReloadableResourceBundleMessageSource getMessageSource() {
        ReloadableResourceBundleMessageSource resource = new ReloadableResourceBundleMessageSource();
        resource.setBasename("classpath:messages");
        resource.setDefaultEncoding("UTF-8");
        return resource;
    }

}

AppInitializer:
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    public void onStartup(ServletContext container) throws ServletException {

        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(AppConfig.class);
        ctx.setServletContext(container);
        ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));
        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");

        container.addFilter("customFilter",  new DelegatingFilterProxy(new CustomFilter())).addMappingForUrlPatterns(null, true, "/*");

    }

    @Override
    protected String[] getServletMappings() {
        return new String[0];
    }

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[0];
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[0];
    }
}

and my CustomFilter:
@Configuration
@EnableWebSecurity
public class CustomFilter implements  Filter {

    @Autowired
    UserService userService;

    public void init(FilterConfig fc) throws ServletException {

    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc) throws IOException, ServletException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        if (httpServletRequest.getRequestURI().contains("/employee/")) {
            String token = httpServletRequest.getHeader("x-token");
            System.out.println("token " + token);
            Long userId = TokenUtils.getUserNameFromToken(token);
            System.out.println("ObjectStore.token " + ObjectStore.token);

            if (token!=null) {
                if (token.equals(String.valueOf(ObjectStore.token))) {
                    int index = ObjectStore.token++;
                    ObjectStore.token = index+1;
                    System.out.println("index " +ObjectStore.token + "token " + token);
                    response.setHeader("x-token", String.valueOf(ObjectStore.token));
                    fc.doFilter(req, response);
                } else {
                    response.sendError(HttpStatus.FORBIDDEN.value());
                    fc.doFilter(req, response);
                    return;
                }
            } else {
                response.sendError(HttpStatus.FORBIDDEN.value());
                fc.doFilter(req, response);
                return;
            }
        } else {
            fc.doFilter(req, res);
        }
    }

    public void destroy() {

    }

}

Everything works fine but I can't inject userService and it's null, I need this to check token in request.
Comment: I try it, but I want do ii in java config.
Comment: Might be of some help : http://stackoverflow.com/questions/9690754/spring-and-autowired-on-a-delegatingfilterproxy
Comment: @Johny0987, I'm also facing the same issue. Did you figure our the solution in spring-boot for this?
Answer: You should use Code as this!
private UserService userService;

and then add this code
public void init(FilterConfig fc) throws ServletException {
  ApplicationContext app =  WebApplicationContextUtils.getRequiredWebApplicationContext(fc.getServletContext());
     userService= app.getBean(UserService.class);
}

Spring 4 autowire to Filter


Why are notes named the way they are?

Question: In 12 tone equal temperament, why are the notes named:

C, C#, D, D#, E, F, F#, G, G#, A, A#, B

instead of, for example,

A, A#, B, B#, C, C#, D, D#, E, E#, F, F#

or any other thing?
Comment: @junil, could you please clarify your question?  Otherwise it's in danger of being closed.
Comment: Just to clarify, you mean to ask why there're no unified descriptors for enharmonic equivalents like D#/Eb?
Comment: Nope, but why we specifically selected those notes symbols at this specific order for 12 tone equal temperament (7 letter symbols with extra 5 symbols, one after c, another after d, another after f, other after g and another after a). It would be possible to include thing where all symbols are letters or that the extra 5 notes without letters are after B.
Comment: @junil I attempted to make your question a bit easier to read. If you feel I changed the meaning of something, feel free to revert it.
Comment: Aren't you aware of the "do re mi fa sol la si" system? It's used in most countries I know. That'll make things a lot clearer
Comment: See here:  http://music.stackexchange.com/a/317/16938
Comment: It looks like the question is: Why does a scale starts from C rather than from A? Similar to [Why is C the base note of standard notation and keys?](https://music.stackexchange.com/q/893/75884)
Answer: I feel like I've already at least partly answered this question here. But I'll endeavor to add more here.
First of all, you aren't quite right in your description of the note-naming system. There are seven letters, and every one of these can be sharped or flatted:

A♭, A, A♯
B♭, B, B♯
C♭, C, C♯
D♭, D, D♯
E♭, E, E♯
F♭, F, F♯
G♭, G, G♯

It's just that many of these end up being multiple names for the same pitch (at least in 12TET), thus they are called 'enharmonic'. There are also double sharps and double flats, but let's not go there...
The key point is that Western music, both classical and pop styles, is almost entirely tonal (or modal), and these systems are actually based on a 7-note (diatonic) scale, not a 12-note scale. The system of using  letters to identify pitches dates at least to the 6th century (Boethius). Repeating the same 7 letters each octave came a few centuries later (by the 11th c., and Guido of Arezzo). Sharps and flats were added latter to introduce alterations to these notes, but these shouldn't be seen as new notes, so much as replacements for existing notes, still leaving you with a 7-note scale. All of this long predates 12TET, which, initially, was developed as a system of tuning keyboard instruments. (One alternative possibility that never caught on: a keyboard with 36 notes per octave).
The first note that people tried adjusting was B, which formed a dissonant interval of a 'tritone' with F. There came to be two forms of the letter b, written in different styles -- a rounded, or 'soft' b that meant to use the lower form of the note, and a square-ish, or 'hard' b that meant to use the higher form of the note. As these symbols became more widely used, the rounded b eventually evolved into a flat symbol, and the square b eventually evolved into both the natural symbol and the sharp symbol.
Because of the shape of the diatonic scale (consisting of whole steps and half steps: WWHWWWH), many of these altered notes ended up being the same as (or close enough to) other notes, so that you got multiple names referring to the same pitches, in different contexts.
BTW, with the advent of atonal music, some music theorists decided they didn't like this naming system based on the 7-note diatonic scale, and decided to invent a new system, called Pitch Class, in which each pitch in an octave, starting from C, is given a unique number, from 0 to 11.
Comment: When the notes were named, majors, minors and keys had not been invented yet, 3rds were dissonant, and everything was in modes. A was named 'A' because it was the lowest note expected to be sung. Later, the G below it was added, but was called Γ (gamma), since G already referred to an octave higher. The most common modes during this time were actually those ending on D, E, F, and G (not A or C). See also: http://music.stackexchange.com/questions/893/why-is-c-the-base-note-of-standard-notation-and-keys
Comment: To elaborate, Guido's note-naming system covered three octaves plus a note: The G on the bottom of the bass staff was Γ, the first full octave was A-G, the second octave (spanning middle c) was a-g, and the third octave was aa-gg. (gg being the top of the treble staff). This was the entire 'gammut' of singable notes ('gammut' = 'gamma' + 'ut'; 'ut' was a solfege syllable similar to 'do').
Comment: I wish more music books/classes would explain this
Comment: Interesting answer, but any idea why the first note of the "all-ivory scale" is named 'C' and not 'A'?   (I've always suspected that (s)he-who-made-up-the-names liked minors.)
Comment: This is incredibly interesting. German note naming has B for Bb, and H for natural B, I suppose it has to do with "The first note that people tried adjusting was B, which formed a dissonant interval of a 'tritone' with F. " I would love a source for this!
Comment: @Gauthier http://music.stackexchange.com/questions/10195/why-note-b-is-marked-with-h-in-scandinavia-and-germany?rq=1
Comment: @Caleb Hines, my understanding is that Guido set up 3 hexachords in his solmisation system running from ut to la on C (the natural hexachord), on G (the hard hexachord) and on F (the soft hexachord), transposed by octaves to fill the available vocal range (as you say, about 3 octaves at the time). When practising in a given mode, the singers would pivot their solfège syllables on a note common to two of the hexachords to arrange that the sensitive mi-fa interval fell in the right place for the mode. This might explain C's subsequent privileged position even _before_ the Ionian mode took off.
Comment: @user16935 well maybe, but while the hexachords started on F, C, and G in that they were the lowest note of each hexachord, the _tonic_ note is typically the second -- _re_ -- with the lowest note most frequently playing the role of the lower neighbor to the tonic (because most music was "minor" to modern ears, or actually Dorian).  This of course puts A back into the running for the "default home" pitch, though even by Guido's day it had begun to be eclipsed by D.  That explains why, as the preference for major tonality grew, C became the default home pitch.
Answer: The "base names", i.e. the letters, are much older than 12-edo. Music used to be played in just one diatonic scale (derived e.g. from Pythagorean/Ptolemaean tuning), and only when switching to another key you'd adjust some of the scale steps by way of an accidental. The order of accidentals you need to introduce is dictated by the circle of fifths.
This by itself does in no way imply there should be 12 steps – it just so happens that the third of the ♭-tones (a♭) comes out with almost the same frequency as the third of the ♯-tones (g♯); if you pretend they are the same and extend the system accordingly this gives you the number 12.
Answer: Why are the notes named what they are "instead of something else?"
All note-naming schemes are ultimately arbitrary. There are, in fact, many other systems for naming notes. For example, a good portion of Europeans use H for B and B for B♭ whereas, in other parts of Europe, the notes are named Do Re Me Fa Sol La and Ti (or Si). Sa Re Ga Ma Pa Dha and Ni are the note names in Indian music. All these systems evolved over centuries.
Any new and potentially more logical system of notation would be equally arbitrary. For example, MIDI, which was developed in the early 1980s, uses 128 different note "names", which are really bit strings and can be represented by numbers. Middle C, for example, equates to binary 111100 or decimal 60.
You asserted, "it would be possible to include [systems] where all symbols are letters or that the extra 5 notes without letters are after B." That's true. You could devise a system where the notes would be:

A (same as C)
B (same as C♯ / D♭)
C (same as D)
D (same as D♯ / E♭)
E (same as E)
F (same as F)
G (same as F♯ / G♭)
H (same as G)
I (same as G♯ / A♭)
J (same as A)
K (same as A♯ / B♭)
L (same as B)

This may have some advantages (and a new set of disadvantages), but you can't expect it to replace the existing systems any time soon.
Comment: In Vietnam it's called Do Re Mi Fa Sol La Si too, in Korean: to, re, mi, pa, so, ra, shi, and in Japan it's called i, ro, ha, ni, ho, he, to
http://music.stackexchange.com/questions/4957/what-is-the-relationship-between-do-re-mi-and-note-letter-names http://en.wikipedia.org/wiki/Iroha#Usage
Comment: These syllables (originally Ut, Re, Mi, Fa, Sol, La) are ultimately derived from the initial syllables of successive phrases in a Gregorian chant, "Ut Queant Laxis". Since each phrase of this chant started one pitch higher than the previous, Guido (whom I mentioned in my answer) used them as a mnemonic device for memorizing the scale. Si/Ti was a later addition. http://en.wikipedia.org/wiki/Ut_queant_laxis
Comment: @CalebHines it seems that Guido's treatise must be the oldest source for that hymn, or at least I assume so because I've seen in more than one place the suggestion that he may have composed it for the purpose of demonstrating his system.
Answer: The simple answer is that the notes were named using a minor, not major, tonality. The relative minor of C Major is A minor, ABCDEFG.
Comment: I would upvote this if there were a reference to any source. It would also be better if this answer were not included in Caleb's answer. As it is, this answer adds no new information.
Comment: There is no relative scale involved when defining note A. Boethius invented a scale with pitches A to O (2 octaves) c. 500, based on Greeks work who had a letter scale too, with alpha assigned to the highest pitch. Later an octave was added, notes were grouped by octave and renamed giving A..G, a..g, aa..gg. Later when a note below the first A was necessary (a lower G), it was named Γ (gamma) for the similarity with G. Major and minor modes appeared much later than note names. [More](https://www.peterfrazer.co.uk/music/tunings/medieval.html).
Comment: @mins but interestingly gamma is the third, not the seventh, letter of the Greek alphabet.  I wonder whether anyone ever called the low F below gamma "beta" and the low E "alpha" -- now _that_ would be confusing.
Comment: @phoog, actually 3 Latin letters, C, G and Ɣ, were derived from Greek gamma (Γ) ([more](https://en.wikipedia.org/wiki/G)), it was used here in replacement of G. Later the playable range Γ-ut, was named [gamut](https://en.wiktionary.org/wiki/gamut#Etymology), which now means a colorimetric scale in English, but derivatives still mean a musical scale in Latin languages, e.g. in French *gamme*.

Why are notes named the way they are?


How can I get the taxonomy tree by the vocabulary ID?

Question: I want load all the taxonomy terms by their vocabulary ID in Drupal 8. In Drupal 7, I would use the following code.
<code>$terms = taxonomy_get_tree($vid);
</code>
What code should I use in Drupal 8?
Answer: You can load terms using the entity query,
<code>$terms =\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid);
foreach ($terms as $term) {
     $term_data[] = array(
      "id" => $term->tid,
      "name" => $term->name
     );
    }
</code>
Comment: Thanks for quick reply.I used that and when I dpm($terms) result show like this.
Comment: Array
(
    [0] => stdClass Object
        (
            [__CLASS__] => stdClass
        )

    [1] => stdClass Object
        (
            [__CLASS__] => stdClass
        )

    [2] => stdClass Object
        (
            [__CLASS__] => stdClass
        )

)
Comment: You can loop through the array to get term id and name. Updated the answer.
Answer: This code snippet might help you.
<code>$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid,0,NULL,TRUE);
print_r($terms);
</code>


Was the widespread use of PRS in the 90s because 90s Gibson guitars were low quality?

Question: Was the 90s widespread adoption of PRS guitars really to do with the low quality Gibson guitars of the era?
I have heard that the 90s were not Gibson's best decade and was wondering if that led to more PRS adoption?
It could be that PRS simply had a sound that was popular during the 90s but I was under the impression that competitors dropping the ball also had something to do with it.
Comment: A guitar is a tool, but it is also wardrobe, and playing new designs and builders distinguishes you from older artists and styles. Could be quality, but "we're something new and look it" is an important factor.
Comment: I would even question the claim of "widespread adoption". They barely made a dent in EU. The 90s was a period of my life when I was at all the important trade shows & I recall no particular buzz about them in the industry. Sure, they managed to make a marketing dent in the US by grabbing some famous names on sponsorship/endorsee deals… but that's how the industry works. There were other equal or better makers at the time who didn't manage to grab the 'right' names. It was a good time to be in the 'boutique' market, so long as you had the right endorsees.
Comment: I think the most likely answers to this question are "no" and "we can't ever be certain". Too many changes happened related to PRS and the guitar market in general in the 90s for it to be mainly about one thing. PRS didn't even have a CnC machine until 1990. I'm not even sure if we can agree that PRS use was "widespread" in the 90s. The company might have grown a lot in the 90s, but I don't remember more than a few big acts playing PRS during that time. And PRS has never had anywhere near the market share of Gibson or Fender.
Comment: Not sure if we can definitively answer this. I have a 95 Les Paul Studio that is great. We know the types of metal that became big in the 90s were often played with PRS + Dual Recto. Also PRS was only founded in 85, so for them to take off in the 90s could just be that's when people first started to hear about them. And the 90s was a decade of guitar - everyone sold a lot of guitars. I think it's a lot more complicated than what Gibson was doing or not doing.
Comment: As far as I know PRS guitars were quite a bit more expansive that the typical Gibson models. So they do not really compete. I'd think that especially professional musicians would rather go for the more expensive guitar because they need an instrument that plays really well.
Comment: I just saw a video from Five Watt World with David Grissom, who is a great roots-rock sideman and session player, and he goes in a lot about how he developed the DGT with PRS. I'm guessing that artist relations work had a lot to do with the PRS rise, no matter the quality of Gibsons.
Comment: @ToddWilcox Agreed, but I don't know that it has to be *definitively* answered, just "documentedly." It would be a fascinating bit of organological history either way, and surely there's some bit of support other than "Well seems to me that ___ makes sense"... Also Neil, any chance you could start the train rolling towards documentation by nailing down where "you heard" the idea?
Comment: Lazy has a good point. When I bought my Gibson USA LP studio for $700 in 95, the most affordable PRS model was the CE Bolt-On at over $1000.
Answer: PRS started to become popular when Fender and Gibson were by far the dominant brands, and everyone else was either a distant wannabe, or a super-expensive product for a small niche.
In that scenario, PRS managed to carve a portion of the market for itself by combining high quality, a distinct personality, and a high, but not ridiculously so, price.
Even then, PRS never came close to challenging the domination of Gibson and Fender, something that perhaps Ibanez can claim to some extent.
In any case, answering the original question about things having to do with the quality of Gibson, no, I don't think that at all.


Dúvida: Percorrer um array multidimensional Laravel PHP

Question: Como otimizar percorrer dados do array multidimensional Laravel no Controller e o resultado ser refletido na View.
Exemplo:

[{"item":"0","item_descricao_id":5,"sim_nao":null,"dt_validade":null,"pagina_documento":null,"observacao":null},
{"item":"1","item_descricao_id":6,"sim_nao":null,"dt_validade":null,"pagina_documento":null,"observacao":null},
{"item":"2","item_descricao_id":7,"sim_nao":null,"dt_validade":null,"pagina_documento":null,"observacao":null},
{"item":"3","item_descricao_id":8,"sim_nao":null,"dt_validade":null,"pagina_documento":null,"observacao":null},
{"item":"4","item_descricao_id":9,"sim_nao":null,"dt_validade":null,"pagina_documento":null,"observacao":null}]

Utilizando a função For no Controller o resultado de impressão é uma linha de array:
Código:

      for ($i = 0; $i < sizeof($item); $i++){
           $dataInsert = array(
                       'item' => $item[$i],
                       'item_descricao_id' => $item_descricao_id[$i],
                       'sim_nao' => $sim_nao[$i],
                       'dt_validade'=> $dt_validade[$i],
                       'pagina_documento' =>$pagina_documento[$i],
                       'observacao' =>$observacao[$i]);
                     }

Resultado dessa função:

{"item":"0","item_descricao_id":"5","sim_nao":null,"dt_validade":null,"pagina_documento":null,"observacao":null}

Neste caso existe alguma biblioteca do PHP que percorra as linhas dos array de arrays?
Comment: Parece que você quer trabalhar com collections, dê uma lida em [Collections: Available Methods](https://laravel.com/docs/5.8/collections#available-methods)
Comment: @ErlonCharles Vou ler a documentação indicada.
Answer: Solução aplicada foi criar uma variável ($cont) para contar linha de cada array dentro do loop de repetição que será refletido na View.
Referência:
Salvar itens de um formulário checklist no banco - Laravel
Segue código:

 $cont = 0; //contador de linhas para os arrays

   for ($i = 0; $i < count($item); $i++){
   $dataInsert = array(
                 'item' => $item[$cont],
                 'item_descricao_id' => $item_descricao_id[$cont],
                 'sim_nao' => $sim_nao[$cont],
                 'dt_validade'=> $dt_validade[$cont],
                 'pagina_documento' =>$pagina_documento[$cont],
                 'observacao' =>$observacao[$cont]);
            $cont++;
         }
Comment: Nesse caso não poderia usar o sizeof($item) ou até mesmo o $i ?
Comment: @Darlei Fernando Zillmer Nessa situação foi erro na edição do código para a resposta. Utilizei o count neste caso. E como era necessário percorrer os outros array em um único formulário fez necessário mais uma variável para percorrer o array.


Mostrar código em textarea

Question: O que eu pretendo e mostrar no meu web site dentro de um textarea codigo php html e etc mas sempre que tento fazer ele corre o codigo e eu quero que ele mostre dentro de um text area ou e outro sistema qualquer exatamento como aqui no stack overflow

Teste PHP

      <?php
          echo"Olá, Mundo!";
          echo("
Olá, Mundo
");
          ?>

        Código feito:
        <textarea class="form-control" rows="15" id="codigo">Conteudo a apresentar</textarea>

Comment: Tem como adicionar o código que tentou fazer na pergunta?
Comment: Sim!! Erro meu 1s
Comment: O Conteudo a apresentar é o sitio onde eu quero por o conteudo a mostrar o site
Comment: Nao necessita de ser em um text area mas se possível mehor
Answer: Você precisa encodar todos os html entities. A maioria das linguagens já tem alguma maneira automática de fazer o escape do código.
Em Java, utilizando JSTL no JSP, você pode fazer assim:
<c:out value="${valorAqui}" escapeXml="true"/>

Em PHP, há a função htmlentities que você usa:
<?php echo htmlentities($texto); ?>

Não cheguei a está, mas acredito que de forma simples você também poderia imprimir o código php da seguinte forma dentro do HTML:
<?php echo '<?php //aqui você insere seu código... ?>' ?>

Veja:

Teste PHP

      <?php
          echo"Olá, Mundo!";
          echo("
Olá, Mundo
");
          ?>

        Código feito:
        <textarea class="form-control" rows="15" id="codigo"><?php echo htmlentities($conteudoParaApresentar); ?></textarea>

Comment: E eu posso colocar isso dentro do text area??
Comment: Obrigado Salvou-me a vida Ahah
Comment: pode sim, postei um exemplo utilizando seu código. No caso, bastaria substituir a variável $texto pela variável que contem o código html.
Comment: então e no caso de eu não querer a variável mas eu mesmo escrever o código tenho de igualar a essa mesma variável antes? ?
Comment: Neste caso, se não deseja utilizar variável basta fazer assim: ```aqui vem todo o código!Tudo funciona!'); ?>```
Comment: Obrigado por tudo!!  ajudou imenso!! e desculpe qualquer coisa
Comment: Testei sem o `htmlentities` e funcionou de mesmo jeito.
Comment: Também funciona, mas htmlentitles faz uma codificação, conforme documentação oficial: http://php.net/manual/pt_BR/function.htmlentities.php, já ao omitir essa função você não está escapando nada, somente imprimindo, em alguns casos pode não funcionar.

Mostrar código em textarea


What is the "polar coordinate function"?

Question: I'm reading Tapp's Differential Geometry of Curves and Surfaces, I have this problem:

$\quad\color{green}{\text{Exercise 1.10.}}$ Prove that the arc length, $L$, of the graph of the polar coordinate function $r(\theta)$, $\theta \in [a, b]$, is

What is the "polar coordinate function"? I tried a few guesses but nothing I thought seemed to make sense nor would give me the arclength function above. Using the definition of arclength, I tried to "reverse engineer" it and I got:
$$\left(\int_{a}^{\theta} r(x)\, dx,\, r(\theta) \right)$$
This seems to be the only function that would make sense here but I have no idea what $r(\theta)$ would be. This is — perhaps — the least worst thing I could think of.
Comment: I think it just means a curved parameterized using polar coordinates instead of rectangular.
Comment: So, with that in mind, hint: start with the usual arc length formula, and change variables from $(x, y)$ to $(r, \theta)$.
Comment: @SeanRoberson Suppose we have a curve (x(t),y(t)), using polar coordinates we get $(x,y)=(r \sin \theta, r \cos \theta)$. I'm not sure what to do from here.
Answer: It means that in polar coordinates $(r,\theta)$, your curve is parametrized by $$[a,b]\ni \theta \mapsto (r(\theta),\theta) \in  [0,\infty)\times [0,2\pi).\tag{1}$$Relative to cartesian coordinates $(x,y)$, it means that the parametrization is $$[a,b] \ni \theta \mapsto (r(\theta)\cos\theta, r(\theta)\sin\theta) \in \Bbb R^2.\tag{2}$$Surely you can compute the arclength of $(2)$.
Answer: Arc length for a curve $C$ in the plane looks like
$$
L = \int_C \mathrm{d}s,
$$
which you're probably more familiar with when the curve is parametrized, i.e.  the cartesian coordinates $(x, y)$ are expressed as functions of a parameter $t \in [a, b]$:
$$
L = \int_a^b \sqrt{x'(t)^2 + y'(t)^2} \, \mathrm{d}t.
$$
This formula comes from the chain rule
$$
\mathrm{d}x = x'(t) \, \mathrm{d}t
\quad\text{and}\quad
\mathrm{d}y = y'(t) \, \mathrm{d}t,
$$
together with what is essentially the Pythagorean theorem for differentials,
\begin{align}
\mathrm{d}s^2 &= \mathrm{d}x^2 + \mathrm{d}y^2 \\
&= \bigl( x'(t) \, \mathrm{d}t \bigr)^2
+ \bigl( y'(t) \, \mathrm{d}t \bigr)^2 \\
&= \bigl( x'(t)^2 + y'(t)^2 \bigr) \, \mathrm{d}t^2.
\end{align}
By the way, in the special case that $y = f(x)$, where the parameter $t$ is extraneous since we can take $t=x$, this reduces to the familiar
$$
\mathrm{d}s^2 = \bigl( 1 + f'(x)^2 \bigr) \, \mathrm{d}x^2.
$$

Now, let's use polar coordinates, related by
$$
\left\{\begin{aligned}
x &= r \cos\theta \\
y &= r \sin\theta
\end{aligned}\right.
$$
First of all,
\begin{align}
\mathrm{d}x &= \mathrm{d} \bigl( r \cos\theta \bigr) \\
&= \frac{\partial}{\partial r} \bigl( r \cos\theta \bigr)
\, \mathrm{d}r
+  \frac{\partial}{\partial \theta} \bigl( r \cos\theta \bigr)
\, \mathrm{d}\theta \\[2pt]
&= \cos\theta \, \mathrm{d}r - r \sin\theta \, \mathrm{d}\theta
\end{align}
Similarly, we can calculate $\mathrm{d}y$ (try it yourself before revealing the spoiler)

\begin{align} \mathrm{d}y &= \mathrm{d} \bigl( r \sin\theta \bigr) \\ &= \frac{\partial}{\partial r} \bigl( r \sin\theta \bigr) \, \mathrm{d}r +  \frac{\partial}{\partial \theta} \bigl( r \sin\theta \bigr) \, \mathrm{d}\theta \\[2pt] &= \sin\theta \, \mathrm{d}r + r \cos\theta \, \mathrm{d}\theta \end{align}

Putting these together to find $\mathrm{d}s^2$ and simplifying with a bit of algebra (again, try it yourself),

\begin{align} \mathrm{d}s^2 &= \mathrm{d}x^2 + \mathrm{d}y^2 \\ &= \bigl( \cos\theta \, \mathrm{d}r - r \sin\theta \, \mathrm{d}\theta \bigr)^2 + \bigl( \sin\theta \, \mathrm{d}r + r \cos\theta \, \mathrm{d}\theta \bigr)^2 \\ &= \bigl( \cos^2\theta \, \mathrm{d}r^2 + r^2 \sin^2\theta \, \mathrm{d}\theta^2 - 2r\sin\theta\cos\theta \, \mathrm{d}r \, \mathrm{d}\theta \bigr) \\ &\qquad{} + \bigl( \sin^2\theta \, \mathrm{d}r^2 + r^2 \cos^2\theta \, \mathrm{d}\theta^2 + 2r\sin\theta\cos\theta \, \mathrm{d}r \, \mathrm{d}\theta \bigr) \\ &= \mathrm{d}r^2 + r^2 \, \mathrm{d}\theta^2 \end{align}

Now, if the radial coordinate is a function of the argument, i.e. $r = f(\theta)$, then $\mathrm{d}r = f'(\theta) \, \mathrm{d}\theta$ and

 \begin{align} \mathrm{d}s^2 &= \bigl( f'(\theta) \, \mathrm{d}\theta \bigr)^2 + f(\theta)^2  \, \mathrm{d}\theta^2 \\ &= \bigl( f'(\theta)^2 + f(\theta)^2 \bigr) \, \mathrm{d}\theta^2, \end{align}

which gives the arc length formula
$$
L = \int_a^b \sqrt{f'(\theta)^2 + f(\theta)^2} \, \mathrm{d}\theta
\tag{$^\dagger$}
$$
for $\theta \in [a, b]$.
$^\dagger$This is the same as the formula you're looking for, but with the functional relationship made more explicit by using the symbol $f$. It can be confusing when $r$ is the name of the function and the output values at the same time, where you write things like $r = r(\theta)$. Tomayto. Tomahto. It's up to you how you write it.
Comment: I'm trying to show you a brief way to do these calculations using the language of [differential forms](https://www.wikiwand.com/en/Differential_form). These techniques are rigorous, even if I'm not explaining in this limited space the language of vector bundles and other tools of differential geometry that support them.
Comment: At the core, though, a calculation like
$$
\mathrm{d}(\sin\theta)
= \frac{\partial}{\partial \theta} \sin\theta \, \mathrm{d}\theta
= \cos\theta \, \mathrm{d}\theta
$$
shows the mechanics of a *substitution* like you learn in an integral calculus class, e.g. $\mathrm{d}u = u'(\theta) \, \mathrm{d}\theta$ so that
$$
\int f(\sin\theta) \cos\theta \, \mathrm{d}\theta
= \int f(u) \, \mathrm{d}u.
$$
Comment: Where did you learn the usage of notation such as $dx = d(r \cos \theta) = \frac{\partial}{ \partial r} (r \cos \theta) d r + \frac{\partial}{\partial \theta}(r \cos \theta) d \theta$? In my calculus education, I basically learned to differentiate and integrate but often I see people using really weird identities I never saw before. I asked about other of these identities [here](https://math.stackexchange.com/q/4479831/25805).
Comment: I don't know "what's happening" because I went into my undergraduate course with almost no mastery of basic mathematics. But it seems to me that using such identities is something akin to "calculus with infinitesimals" which were regarded as "non rigorous" or something? Perhaps everything I'm saying is nonsense but: I don't know if they did cover this in my courses but I couldn't pay attention because I was struggling, I don't know if I was hit by some educational trend about "infinitesimals and rigor" and they did omit this?
Comment: Anyway, the books where I mostly see this notation are always more "vintage". I'd really like to learn to use this kind of notation and also be able to derive and understand such identities myself. Can you recommend me something?


IIS web server slows down when FTP transfers are in progress

Question: A client is running an ASP.NET web site on an IIS Server (on Windows Server 2008 R2). It's a dedicated physical server, at an external host, and, for the most part, the site runs fine.
The client has noticed, however, that the web site sometimes becomes unresponsive when we are transferring files to it via FTP. We are using the built-in Windows FTP server on this box. We generally copy files up using Beyond Compare, or a simple FTP client, like WinSCP. In these cases, we are copying up .aspx pages and .pdf files, not DLLs or config file changes, so IIS should not be restarting the asp.net worker process or anything like that.
Looking at Resource Monitor while the transfer is happening shows the network utilization getting up to about 25%. CPU, memory, and disk usage are all reasonable.
Could the FTP transfer be soaking up all the bandwidth available to the server? If so, is there a way for me to limit the bandwidth that the Microsoft FTP server uses? I've looked around for information on that, and it seems like that might not be possible. I know that it can be done with, for instance, Serv-U, so I've been thinking of switching to that.
I'm not sure yet how much bandwidth the host is providing, by the way, but I'm looking into that.
Answer:
We are using the built-in Windows FTP server on this box

Sorry, WHICH One? There is the old one and the new one - unless the throw the old out out with R2, not sure ;)

Looking at Resource Monitor while the transfer is happening shows the network utilization getting up to about 25%.
  CPU, memory, and disk usage are all reasonable

That is quite a lot, espeically when this is one transfer stream. What do you mean with "disc usage are reasonable" - seconds per IO is in which range? THat is about the only counter relevant.

Could the FTP transfer be soaking up all the bandwidth available to the server?

Yes. Given that FTP is trivial processing wise that is even quite normal.

I'm not sure yet how much bandwidth the host is providing, by the way, but I'm looking into that.

I think this is likely the main point here. Note that you dont even say what link you have - 25% network ultilization mean differnet things on a 100mbit or 1000mbit physical link to start with.
I would somehow say you use 25 mbit and likely are on a shared link?
Try putting in a QOS profile and prioritize FTP lower ;)
Comment: We are using the FTP service that is manageable thru IIS Manager. The path to it that I see in the service properties is "C:\Windows\system32\svchost.exe -k ftpsvc". Not sure if that's the old or new one. Good point about the network link -- it's 100 Mbps. I'll have to do another test and look at the secs/IO #. I didn't really look at that this morning.
Comment: Secs/IO is the ONLY metric that is relevant - when that goes up, you are overloaded. All others (queue length etc.) require a LOT of interpretation - that one tells you straight how fast the IO is on the hardware, which is the only thing that really matters.


Picture changing in vb6

Question: I was trying this script from a pdf file.I got stuck where the target image should change to exploding image if clicked but the target image does not change from the standing image.Please Help!
Option Explicit

Dim fiPlayersScore As Integer
Dim fiNumberofMisses As Integer
Dim fbTargetHit As Boolean
Private Sub Form_Load()
Randomize
imgTarget.Enabled = False
imgTarget.Visible = False
cmdStop.Enabled = False
lblGameOver.Visible = False
lblGameOver.Enabled = False
End Sub
Private Sub cmdStart_Click()
Dim lsUserResponse As String
Dim lbResponse As Boolean

lsUserResponse = InputBox("Enter a level from 1 to 3." & _
(Chr(13)) & "" & (Chr(13)) & "1 being  the Easiest and 3 being the " & _
"Hardest.", "Level Select", "1")
lbResponse = False
If lsUserResponse = "1" Then
Timer1.Interval = 1500
lbResponse = True
ElseIf lsUserResponse = "2" Then
Timer1.Interval = 1000
lbResponse = True
ElseIf lsUserResponse = "3" Then
Timer1.Interval = 750
lbResponse = True
Else
MsgBox ("Game Not Started.")
lbResponse = False
End If
If lbResponse = True Then
cmdStart.Enabled = False
imgTarget.Picture = imgStanding.Picture

frmMain.MousePointer = 5
fbTargetHit = False
Load_Sounds
cmdStop.Enabled = True
fiPlayersScore = 0
fiNumberofMisses = 0
lblScore.Caption = fiPlayersScore
lblMisses.Caption = fiNumberofMisses
Timer1.Enabled = True
lblGameOver.Visible = False
lblGameOver.Enabled = False
End If
End Sub

Private Sub cmdStop_Click()
Unload_Sounds
frmMain.MousePointer = vbNormal
Timer1.Enabled = False
imgTarget.Enabled = False
imgTarget.Visible = False
cmdStart.Enabled = True
cmdStop.Enabled = False
cmdStart.SetFocus
lblGameOver.Visible = True
lblGameOver.Enabled = True
End Sub

Private Sub Form_Click()
MMControl1.Command = "Play"
MMControl1.Command = "Prev"
fiNumberofMisses = fiNumberofMisses + 1
lblMisses.Caption = fiNumberofMisses
If CheckForLoose = True Then
cmdStop_Click
lblMisses.Caption = fiNumberofMisses
Exit Sub
End If
End Sub

Private Sub imgTarget_Click()
MMControl2.Command = "Play"
MMControl2.Command = "Prev"
Timer1.Enabled = False
imgTarget.Picture = imgExplode.Picture '**I AM STUCK HERE**
pauseProgram

fiPlayersScore = fiPlayersScore + 1
Timer1.Enabled = True
If CheckForWin = True Then
cmdStop_Click
lblScore.Caption = fiPlayersScore
Exit Sub
End If
lblScore.Caption = fiPlayersScore
fbTargetHit = True
imgStanding.Enabled = False
imgTarget.Visible = False
imgTarget.Enabled = False
Timer1.Enabled = True
End Sub
Public Sub Load_Sounds()
'Set initial property values for blaster sound
MMControl1.Notify = False
MMControl1.Wait = True
MMControl1.Shareable = False
MMControl1.DeviceType = "WaveAudio"
MMControl1.FileName = _
"C:\Temp\Sounds\Blaster_1.wav"
'Open the media device
 MMControl1.Command = "Open"

 Private Sub Timer1_Timer()
 Dim liRandomLeft As Integer
 Dim liRandomTop As Integer
 imgTarget.Visible = True
 If fbTargetHit = True Then
 fbTargetHit = False
 imgTarget.Picture = imgStanding.Picture
 End If
 liRandomLeft = (6120 * Rnd)
 liRandomTop = (4680 * Rnd)
 imgTarget.Left = liRandomLeft
 imgTarget.Top = liRandomTop
 imgTarget.Enabled = True
 imgTarget.Visible = True
 End Sub

 Public Function CheckForWin() As Boolean
 CheckForWin = False
 If fiPlayersScore = 5 Then
 CheckForWin = True
 lblGameOver.Caption = "You Win.Game Over"
 End If
 End Function
 Public Function CheckForLoose() As Boolean
 CheckForLoose = False
 If fiNumberofMisses = 5 Then
 CheckForLoose = True
 lblGameOver.Caption = "You Loose.Game Over"
 End If
 End Function

Private Sub Form_QueryUnload(Cancel As Integer, _
UnloadMode As Integer)
Unload_Sounds
End Sub
Public Sub Unload_Sounds()
MMControl1.Command = "Close"
MMControl2.Command = "Close"
End Sub
Public Sub pauseProgram()
Dim currentTime
Dim newTime
currentTime = Second(Time)
newTime = Second(Time)
Do Until Abs(newTime - currentTime) >= 1
newTime = Second(Time)
Loop
End Sub

Answer: EDIT:
imgTarget.Picture = imgExplode.Picture
imgTarget.Refresh

Comment: that is for multiple images and auto loading with timer
Comment: Why not just load a new image from the image list on your click event.
Comment: I can not find the image list control
Comment: To add the ImageList control to your VB project,
click Project|Components,
and check the box next to Microsoft Windows Common Controls
Comment: thanks after search on google I got how to add the imagelist control.on running the script error message is m_index variable not defined.So I added in the start
       Private m_Index As Integer
       Private m_NumImages As Integer
and in the  Private Sub imgTarget_Click()
       m_Index = ((m_Index + 1) Mod m_NumImages) + 1
       imgTarget.Picture = ImageList1.ListImages(m_Index).Picture
but the result is the same as before
Comment: Thanks RenicK.It worked.Actually imagelist was not required.Just adding imgTarget.refresh immediately after imgTarget.Picture=imgExplode.Picture did the job.Unfortunately I cannot add a tick mark to your valuable help as you have answered in comment.Please post in answer question so I can tick your answer.
Answer: Note:
Set imgTarget.Picture = imgExplode.Picture
imgTarget.Refresh

will be faster than
imgTarget.Picture = imgExplode.Picture
imgTarget.Refresh

if imgExplode is going to be around during the lifetime of imgTarget (the first command copies the image, the Set command references the image).
Comment: Sorry Kris, slightly late in answering the question

Picture changing in vb6


Intermediate step solving Hartshorne Ex II-3.12 a)

Question: In this exercise we have a surjective graded ring homomorphism $\varphi:S\to T$. This induces a morphism $f:$Proj$(T)\to $Proj$(S)$ by contraction of ideals. I'm asked to show that $f$ is a closed immersion.
In orther to show that $f^\sharp:\mathcal{O}_{Proj(S)}\to f_*\mathcal{O}_{Proj(T)}$ is surjective, I restric it to an open subset of the form $D_+(g)=\{p\in$ Proj$(S)\mid g\notin p\}$. Surjectivity in these sets would imply surjectivity on the fibers so I'd be done.
I would like to show that $f_*\mathcal{O}_{Proj(T)}(D_+(g))=\mathcal{O}_{Proj(T)}(D_+(\varphi(g)))$ to apply proposition 2.5 of Hartshorne and get a natural homomorphism $S_{(g)}\to T_{(\varphi(g))}$, which is clearly surjective.
To show this, it is enough to show $f^{-1}(D_+(g))=D_+(\varphi(g))$. Explicitily, the firs set, using that $f^{-1}$ is given by ideal extension and that $\varphi$ is surjective, is $\{\varphi(p)\in$Proj$(T)\mid \varphi(g)\notin\varphi(p)\}$. So what I need to show is that if $g\notin p$, then $\varphi(g)\notin \varphi(p)$. This is obviously false for a general surjective ring homomorphism, but I guess this is true for the graded case.
How can I show this final implication (if it is true)? If it is not true, how can I solve the exercise?
Answer: I think it is better to use the adjunction relation from exercise 1.8, which tells us that it is equivalent to prove surjectivity of the homomorphism $\mathcal{O}_{Proj(S),\varphi^{-1}(p)}\to\mathcal{O}_{Proj(T),p}$ (using that $f^{-1}G_x=G_{f(x)}$ for a sheaf $G$). Then it is possible to apply proposition 2.5a), which gives us the homomorphism $S_{(\varphi^{-1}(p))}\to T_{(p)}$.


$x\cdot 0 \neq 0$ infinitely many zeroes on a finite interval

Question: I was playing around with polynomials by looking how they behave when I move around their zero points.
I decided to make a function which is zero on a finite interval, but since its a polynomial, it should retain all those nice properties of being differentiable and so on. Using
$$f(x,a,b,N) = \prod_{k=1}^{N} x- \left(a+\frac{b-a}{N}k\right)$$
to put $N$ zeroes between $a$ and $b$ the resulting function, as expected, somewhat resembles $x^N$.

Now I want to take the limit $N\rightarrow \infty$, first i turn the product into a sum
$$f(x,a,b,N) = \exp \left(\sum_{k=1}^{N} \ln \left(x- \left(a+\frac{b-a}{N}k\right)\right)\right)$$
and then replace the sum by an integral
$$g(x,a,b) = \exp \left(\int_{0}^{1} \ln (x- (a+(b-a)k)) dk\right)$$

Suddenly all the zero points are gone and its mostly linear outside of $[a,b]$
with
$$h(x,a,b) = \exp \left(\int_{a}^{b} \ln (x- k) dk\right) = g(x,a,b)^{b-a}\\
= \exp( (x-a)\ln(x-a) -(b-a)-(x-b)\ln(x-b))$$
The graph resembles $f$ more, but is still nonzero everywhere.

How comes that taking the limit makes such a big difference?
Comment: can exponential function take zero value?
Comment: To compare the graphs of $f$ and $g$ is odd since, even if one chooses to be sloppy with the problems of sign, one sees that $g(x,a,b)$ is related to the limit of $f(x,a,b,N)^{1/N}$ when $N\to\infty$, not of $f(x,a,b,N)$.
Comment: @GA316 At $-\infty = \ln(0)$ it can, but somehow those values disappear when turn the sum into an integral
Answer: Your very first step,
\begin{align*}
f(x, a, b, N)
  &= \prod_{k=1}^{N} \left(x - \Bigl(a + \frac{b - a}{N}k\Bigr)\right) \\
  &= \exp\left(\sum_{k=1}^{N} \log\left(x - \Bigl(a + \frac{b - a}{N}k\Bigr)\right)\right),
\end{align*}
is seriously problematic, since the product is not non-negative in $[a, b]$.
Comment: Well, then I get some complex intermediate results, but it doesnt seem like a big problem to me to write $\exp(\ln(x-1)+\ln(x+1))$ instead of $(x-1)(x+1)$


Check for text value in xml

Question: I am having an xml as
<numbers>
<number>1</number>
<number>2</number>
<number>abc</number>
</numbers>

During serialization how can i identify that the element <number> is having text as abc. I need to allow only integers not text.
Answer: Assuming what you're stuck with is exactly what you're asking (and that the XML handling isn't an issue), you could use int.TryParse which will allow you to input a string and output the resulting number, if it is a number - the return value will indicate whether the parse was successful or not, and hence determining whether the original value was in fact a number.
Answer: Depending on what you understand on "to allow only intergers" the default behavior of the .net xml serialization could be enough for you. If the number member in your class is defined as int there will be an exception on deserialization your provided XML fragment:
[XmlRoot("numbers")]
public class Numbers
{
  [XmlElement("number")]
  public int[] Numbers;
}

If you want to have more control over the serialization process you can implement the IXmlSerializable interface.

Check for text value in xml


What is the limit of series when n tends to infinity?

Question:
Calculate the limit $$ \lim_{n \to \infty}  \frac{1+\frac{1}{2}+\ldots +\frac{1}{n}}{\left(\pi^n+e^n \right)^{\frac{1}{n}} \ln{n}} $$

I tried solving the question with L hospital rule but didn't get to the answer instead the question become more complex.
Please solve the question or at least provide some hints.
Thanks in advance
Comment: Let $H_n = 1 + \frac{1}{2} + \cdots + \frac{1}{n}$ (this is the $n$-th [harmonic number](https://en.wikipedia.org/wiki/Harmonic_number)). Do you know some bounds for $H_n$ involving the natural logarithm function (if not, try and come come up with some by considering integrals of the decreasing function $1/x$ over intervals like $[1,n]$. Or see https://math.stackexchange.com/questions/2832848/bounds-for-the-harmonic-k-th-partial-sum)? Also, try and show that $\lim\limits _{n\to\infty}\left(a^n + A^n\right)^{1/n} = A$, for any real numbers $0\le a \le A$.
Answer: Hint: show that $\frac {1+\frac 1 2+...+\frac 1 n} {\log_e\,n }\to 1$ and $(\pi^{n}+e^{n})^{1/n})^{-1} \to \frac 1 {\pi}$ so the answer is $\frac 1 {\pi}$.
Answer: You have, when $n$ tends to $+\infty$,
$$\frac{\sum_{k=1}^n \frac{1}{k}}{(\pi^n + e^n)^{1/n} \ln(n)} \sim \frac{\ln(n)}{(\pi^n + e^n)^{1/n} \ln(n)} = \frac{1}{(\pi^n + e^n)^{1/n} } = \frac{1}{\pi \left(1 + \left(\frac{e}{\pi}\right)^n\right)^{1/n} }$$
and
$$\left(1 + \left(\frac{e}{\pi}\right)^n\right)^{1/n} = \exp \left(\frac{1}{n} \ln \left(1 + \left(\frac{e}{\pi}\right)^n \right) \right) \rightarrow 1$$
So the limit is
$$\frac{1}{\pi}$$
Comment: Thanks to all for such quick help


Is there a term for a chord progression that chromatically ascends or descends an octave?

Question: I've noticed a pattern in music that is very interesting where a progression will start with one chord and chromatically ascend or descend until the starting chord is reached again.
For example: a descending progression that has this pattern would look something like this:

C   G7/B   Bb   F/A   Ab   G   D/F#  F  C/E Cm/Eb  D  Eb7/Db  C

The bass chromatically moves by half step down 12 times until reaching the first chord. Does this type of progression have a name?
Comment: I'm not sure it has a name, but it's really a bunch of deceptive progressions: root moves up a fifth, "resolves" to the flat mediant; up a fifth, etc....
Comment: @Patrx2 I know there are similar progressions out there and this one was just one I've been playing with for a while. I'm pretty sure there is one like this in somewhere in Mozart's Requiem (Lacrimosa if I remember correctly).
Comment: I'll have to check. I've seen similar in the literature myself (parallel first inversion chords, maybe?), but they rarely go full circle (or they go _past_ full circle). The practical problem with a full circle sequence of any sort is that it can give the impression of treading water.
Comment: If I'm not mistaken, it is called an omnibus progression.
Answer: This type of progression is called an Omnibus Progression.  It is a variation on the lament bass which is a figure where bass moves by a 4th connecting all chromatic notes in between.  The Omnibus Progression most notably features a chromatically-descending bassline that traverses an octave.  Additionally, the progression may also support a chromatically ascending S, A, or T line that ascends an octave simultaneously.
Here is a link to read more:
http://en.wikipedia.org/wiki/Omnibus_progression
Comment: @Kevin, reread the last full sentence of my answer. :)
Comment: old question, but for who looks this up, this is often called a "line cliché" in jazz
Comment: Can an omnibus progression also ascend the chromatic scale, or is there another term for that?
Answer: One could also call this a descending bassline type of progression. Descending basslines are a powerful device that can unify a seemingly atonal chord sequence.


Highchart range selector doesn't show up

Question: For the last few hours I am struggling with rangeSelector in Highcharts. I have enabled: input and allButtons, but that didn't help. Also I've put min and max for x axis and also min range for x axis, still no luck. Here is my initialization of graph:
P.S. dataPreparedForGraph is series of element containing javascript Date, and some value.
Highcharts.setOptions({
      global: {
          useUTC: false
      }
  });

  Highcharts.chart('graph', {
    chart: {
        type: 'scatter',
        zoomType: 'x',
        panning: true,
        panKey: 'shift'
    },
    title: {
        text: tableName
    },
    xAxis: {
        type: 'datetime',
        dateTimeLabelFormats: {
            month: '%e. %b',
            year: '%b'
        },
        title: {
            text: 'Date'
        },
        min: timestamp_label[0].getTime(),
        max: timestamp_label[timestamp_label.length - 1].getTime(),
        minRange: 3600
    },
    yAxis: {
        title: {
            text: 'Sensor value'
        }
    },
    tooltip: {
        headerFormat: '{series.name}
',
        pointFormat: '{point.x:%e. %b}: {point.y:.2f} m'
    },
    plotOptions: {
      columnrange: {
        grouping: false
      },
      series: {
        marker: {
          enabled: true
        },
      }
    },
    rangeSelector: {
      enabled: true,
      inputEnabled: true,
      allButtonsEnabled: true,
      buttons: [
        {
          type: 'minute',
          count: 1,
          text: 'minute'
        },{
          type: 'hour',
          count: 1,
          text: 'hour'
      },{
          type: 'day',
          count: 1,
          text: 'day'
      }, {
          type: 'week',
          count: 1,
          text: 'week'
      }],
      buttonTheme: {
          width: 60
      },
      selected: 2
    },
    series: dataPreparedForGraph
  });

Answer: Range selector is available only for Highstock.
To use it, you need to change source code:

and use stockChart constructor:
Highcharts.stockChart('graph', {...});

Live demo: http://jsfiddle.net/BlackLabel/mtkcg6aj/
Docs: https://www.highcharts.com/docs/stock/understanding-highstock
Comment: Thanks! Do you know why series labels don't show up now?


Slurm job array pulling parameter set from .txt file and using parameters as objects in Rscript

Question: I am currently trying to run a stochastic simulation in R using changing parameters by submitting a slurm array job to HPC. I have stored the parameters in a .txt file where each line contains the parameter iteration to be set as individual objects in R before running simulation (e.g. Line1: a=5,b=10,c=0.75,d="SL",e=1; Line2:a=5,b=10,c=0.5,d="TL",e=5; etc...). Therefore, for $SLURM_ARRAY_TASK_ID in R, object 'a' must be 5, object 'b' must be 10, etc. I am looking for some assistance on:
How to assign each parameter set corresponding to the $SLURM_ARRAY_TASK_ID and setting those parameter sets as objects in R before running script.
Then I am looking to export/save a .csv of each array task doing something like write.csv(out, paste0("out",$SLURM_ARRAY_TASK_ID,".csv")).
I hope this is enough information. Thank you in advance!
Answer: You can read in the lines of the parameters.txt file into an array and use `` to index this array and pass the data as an argument to the R script.
The basic bash script to call the sbatch run:
#!/bin/bash
#
#SBATCH --array=0-1 #adjust to your number of lines in parameters.txt

while IFS= read -r; do
  parameters+=("$REPLY")
done < "parameters.txt"

srun Rscript "calculation.R" "${parameters[SLURM_ARRAY_TASK_ID]}"

The parameters.txt:
a=5,b=10,c=0.75,d="SL",e=1
a=5,b=10,c=0.5,d="TL",e=5

The basic calculation.R script (here, most work is to parse the arguments):
# read in arguments
args = commandArgs(trailingOnly=TRUE)

# split into different variables
all_vars <- read.table(text = args[1], sep = ",")
colnames(all_vars) <- unlist(lapply(seq_len(ncol(all_vars)), function(i) {
  regmatches(all_vars[, i], regexpr(".*(?==)", all_vars[, i], perl = TRUE))
}))

for (i in seq_len(ncol(all_vars))) {
  all_vars[, i] <- regmatches(all_vars[, i], regexpr("(?<==).*", all_vars[, i], perl = TRUE))
}

all_vars$a <- as.numeric(all_vars$a)
all_vars$b <- as.numeric(all_vars$b)
all_vars$c <- as.numeric(all_vars$c)
all_vars$e <- as.numeric(all_vars$e)

# do calculation

# save
slurm_array_id <- Sys.getenv("SLURM_ARRAY_TASK_ID")
write.csv(out, paste0("out", slurm_array_id, ".csv"))

It would be probably easier to store the parameters in a csv file with headers, so you have to do less parsing.


Equivalent term of integration

Question: Let $f:[0,3]\to\mathbb R$ given, such that $\int_0^3 f(x)\,dx $ exists.

Give a function g and a constant C such that $\int_0^3 f(x)dx=C\int_a^b g(x)dx$ while $g$ is only depending on $f$ and $C$ is only depending on $a$ and $b$ .

How does one handle this problem? This task was an old exam question.
Answer: One way to do this is to switch the $a\to b$ integral to one on $0\to 3$. So let's try
$$\int_a^bg(x)~dx=\int_0^3 g(u)~du$$
Now we need to find the substitution for $u$. When $x=a$ in the first integral we need $u=0$, and when $x=b$ we need $u=3$. So try $u=\frac{3}{b-a}(x-a)$. So we can reverse this to obtain $g$ in terms of $f$. Then the constant $C$ will be to take care of the change of variables, since $du=\frac{3}{b-a}~dx$. I leave it to you to put everything together.
Answer: Take $g(x) = \int_0^3f(t)dt$ (yeap, a constant function) and $C = \frac{1}{b-a}$.
Comment: On "how does one handle this": well, your first desire is to say something like $g = f$ but you quickly understand it is wrong, moreover, you understand that almost any reasonable connection to $f$ will fail, cause $g$ should be integrable on any interval, though we have nothing on $f$ outside interval $[0,3]$. So here comes the idea to make $g$ constant. The rest follows.

Equivalent term of integration


Proof involving Lagrange Theorem and subgroups help

Question: My Question reads:
If $G$ is a group of order $n$, and $G$ has $2^{n-1}$ subgroups, prove that $G=< e>$ or $G$ is isomorphic to $\Bbb Z_2$.
I now understand this question a bit more. I received the suggestion to use Lagrange's theorem but I am not too sure how. I was testing out different $n$ values so say for $n=1$ which would be the case for $G= < e >$, then $2^{1-1}$ is $1$, so there is one subgroup. For the second case $n$ would be two so $2^{2-1}$ is two which makes sense because order of $\Bbb Z_2$ is two. I think something with contradiction could work here but I am unsure of how to approach the proof.
Comment: Why have you deleted your earlier post? I already answered your question there in a comment.
Comment: @DerekHolt Because I wanted to include that I now know more information. I talked a bit through it with my professor and I see how plugging in different n values relates to the subgroup amount. Essentially, it has something to do with arguing this amount of subgroups is too large is what I think he was aiming to say.
Comment: @DerekHolt yes, but I needed further explanation for the problem. I am only just learning this so I am unsure how to proceed with saying that these subgroups have order m. I think then you need to use the theorem to state m divides n?
Comment: I still don't understand why you deleted the earlier question.
Comment: I wanted to just restart the question because I have a new understanding of the question and what I had down before made no sense.
Answer: Here is another approach: there is an injection $f$ between the set of subgroups of $G$ and $P(G-e)$ the set of subsets of $G-\{e\}$ such that $f(H)=H-\{e\}$. Since the cardinal of $P(G-e)$ is $2{n-1}$, the hypothesis implies that $f$ is bijective.   Suppose $x\in G$, $\{x,e\}$ is a subgroup implies implies $x^{-1}=x$ or $x=e$. If every element verifies $x=e$,done. Suppose you have $x,y,x^2=y^2=e, x,y\neq e$, $\{x,y,e\}$ is a subgroup so $x=y^{-1}$.
If  you want to use Lagrange theorem, suppose that $n\neq 1$, you have a non empty subset $H$ of $G$ of order $n-1$. The lines above     implies $H$ is  a subgroup. Lagrange impliess that $n-1$ divides $n$, this true only if $n=2$.
Comment: I see, but I am only just learning Lagrange's Theorem so I am supposed to use this. I appreciate seeing another way to approach the problem nonetheless.
Comment: This is simpler than Lagrange theorem. I use only basic set theory.
Comment: Yes, but I have to use Lagrange Theorem because that is what we are currently learning.
Answer: Let $G$ be a group of order $n$.

Let $S$ be the set of subsets of $G$ which are subgroups of $G$, and let $m = |S|$.

It's easy to verify that if $n = 1$ or $n = 2$, then $m = 2^{n-1}$.

Claim: If $m = 2^{n-1}$ then $n = 1$ or $n = 2$.

Suppose $n > 2$ and $m = 2^{n-1}$. Our goal is to derive a contradiction.

Let $e$ be the identity element of $G$. Define $W,E,F$ by
\begin{align*}
W &= \text{ the set of nonempty subsets of }G\\[6pt]
E &= \{X \in W \mid  e \in X\}\\[6pt]
F &= W\setminus E
\end{align*}
Then
\begin{align*}
|W| &= 2^n-1\\[6pt]
|E| &= 2^{n-1}\\[6pt]
|F| &= 2^{n-1}-1
\end{align*}
Then $H \in S \implies e \in H \implies H \in E$, hence $S \subseteq E$.

Since $|S| = |E|$, $S \subseteq E \implies S = E$.

Let $g \in G$, $g \ne e$, and let $H = G\setminus \{g\}$. Then $|H| = n - 1$.

Then
\begin{align*}
e \in H &\implies H \in E\\[6pt]
&\implies H \in S\\[6pt]
&\implies |H| \text{ divides } |G|\;\;\text{[by Lagrange's Theorem]}\\[6pt]
&\implies (n-1)|n
\end{align*}
which is impossible since $n-1$ is relatively prime to $n$, and $n > 2$.

Thus, we have a contradiction, and hence, the claim is proved.
Comment: then subsets are the same as subgroups for where you define S?
Comment: @Sam: The set $S$ is the set of those subsets of $G$ which are subgroups of $G$.
Comment: How do you know there are 2^n-1 subsets? is this because each subgroup has the identity?
Comment: @Sam: Given _any_ set with n elements, there are $2^n$ subsets, hence there are $2^n - 1$ nonempty subsets. That explains why the cardinality of $W$ is $2^n - 1$.
Comment: Oh is this sort of like the power series? where we have 2^n subsets and since one is the empty set we have (2^n)-1 non empty subsets
Comment: @Sam: Yes, but you surely meant "power set", nor "power series".
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/53662/discussion-between-sam-and-quasi).


Designated initializer missing a super call to designated initializer of the super class

Question: my code is here:
<code>(instancetype)initWithFrame:(CGRect)frame
{
self = [[[NSBundle mainBundle] loadNibNamed:@"LSCouponADView" owner:Nil options:nil] objectAtIndex:0];
if (self) {

}

    return self;
}
</code>
Then xcode has warning

Designated initializer missing a super call to designated initializer
  of the super class

when I building it.
Comment: What is the parent class of this class?
Answer: You need to add this line in this method.
<code>self = [super initWithFrame:frame];
if(self) {

}
return self;
</code>
From Apple Doc.
The Designated Initializer

The initializer of a class that takes the full complement of initialization parameters is usually the designated initializer. The designated initializer of a subclass must invoke the designated initializer of its superclass by sending a message to super. The convenience (or secondary) initializers—which can include init—do not call super. Instead they call (through a message to self) the initializer in the series with the next most parameters, supplying a default value for the parameter not passed into it. The final initializer in this series is the designated initializer.
Answer: you should make your class some thing like this:
Run tIme init:>
<code>-(instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
        if(!self){
            return nil;
        }

        NSBundle *mainBundle = [NSBundle mainBundle];
        NSArray *views = [mainBundle loadNibNamed:@"LSCouponADView"
                                            owner:nil
                                          options:nil];
//above nib name should not be hard coded, it should be like this:
//NSArray *views = [mainBundle loadNibNamed:NSStringFromClass([self class])
                                                owner:nil
                                              options:nil];
        [self addSubview:views[0]];

    return self;
    }
</code>
You should also override for xib initialization:
<code>-(id)initWithCoder:(NSCoder *)aDecoder
    {
        self = [super initWithCoder:aDecoder];
        if(!self){
            return nil;
        }

        NSBundle *mainBundle = [NSBundle mainBundle];
        NSArray *views = [mainBundle loadNibNamed:@"LSCouponADView"
                                                owner:nil
                                              options:nil];
        [self addSubview:views[0]];

    return self;
    }
</code>
over all you can make a common method for loading from nib.
Comment: I do it with your idea like this      -(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        UIView *view = [[[NSBundle mainBundle] loadNibNamed:@"LSCouponADView" owner:Nil options:nil] objectAtIndex:0];
        view.frame = CGRectMake(0, 0, CGRectGetWidth(frame), CGRectGetHeight(frame));;
        [self addSubview:view];

    }

    return self;
}
Comment: @waterKnight upvote/acceptance will be motivating :)


ReactJs how to dynamically render a page based on user selection?

Question: I'm trying to build an E-commerce shop and using the rule "Don't repeat yourself", I have a data.Js file that contains an array of objects - each object is a corresponding watch (has name, ID, price, description and other details). I have all the watches displayed on the homepage, like this:

What i want is:
When a user clicks on a specific watch, to then be taken to the product page that corresponds to the specific watch (I.E. get populated with data matching the correct object, with {item.id} and {item.title} and {item.price} and etc.
How can I do this so that React knows which watch the user clicks and how to populate the product page with the correct data?
Thank you very much in advance!
Comment: Can you provide the code snippet of this?
Comment: Read about react router https://reactrouter.com/docs/en/v6/getting-started/tutorial
Answer: Map through the array of object using a list tag making each list unique with the id property of each object. You can embed the list within a react-router Link which can be used to navigate to the page to display the details.
//Assume your array of object is watchData
return (

      {watchData?.map((data) => (
        <Link to"watch-details">

            {watchData.image}

        </Link>
      ))}

  );


Should I use ivars in Objective-C?

Question: I have an application that I'm writing that uses solely @properties. I have not one ivar declared at all in any of my class files. As I understand it ivars are no longer needed with the introduction of @property. Am I coding according to best practice? Will this end up biting me in the proverbial butt in the long term? I have been reading mixed reviews on what is "right" and "wrong"...
Comment: Note that if you have both an ivar declaration and a property declaration for the same ivar, your code isn't DRY (don't repeat yourself).
Comment: The answer to this question depends, among other things, on when you asked the question.  The "ideal" approach here has been a moving target.
Answer: It's not so much that instance variables aren't needed. It's just that instance variable declarations aren't needed. Given a property and a @synthesize statement, the compiler will take care of creating the instance variable along with appropriate accessor methods.
There's nothing wrong with using properties exclusively. They simplify memory management. There's also nothing wrong with using iVars without properties, if that's what you want. If you want to use properties but don't want to advertise the accessors to the rest of the world (i.e. maintain encapsulation), consider declaring your non-public properties in a class extension (basically an anonymous category in your implementation file).
Answer: I generally don't declare ivars, either.   I will often use @synthesize foo = foo_; though to prevent direct access when I meant through-method or vice-versa. And I always let the compiler automatically synthesize the ivar with the _ prefix (which prevents accidental direct access, as per the struck phrase).
And, as Caleb said, there are still ivars floating about, you just don't explicitly declare 'em unless you really want to (which, really, you don't as exposed ivars in the headers are not useful to clients of the class, if your API is designed appropriately).
I also find that the hype over "only use direct access in init/dealloc, use setter/getter everywhere else" to be largely overblown and, thus, just use the setter/getter everywhere.   The reality is that if you have observers during initialization/deallocation, you are already hosed;   the state of the object is, by definition, undefined during construction/destruction and, thus, an observer can't possibly reason correctly about the state.

As Caleb points out, another reason to use direct ivar access in init/dealloc is to avoid subclasses that implement custom setter/getter logic that may barf due to the undefined state of the object during init/dealloc.
While this may be true, I consider it a nasty architectural flaw to implement setters/getters with custom behavior.   Doing so is fragile and makes it significantly more difficult to refactor the code over time.  As well, such custom behavior will often have dependency on other state within the object and that dependency then leads to order dependencies on state changes that are not at all reflected by the seeming simple @property declaration.
I.e. if your setters and getters are written such that foo.bar = bad; cannot be executed at any time on foo, then your code is busted.
Comment: I find that if I don't explicitly declare ivars, I can't inspect their values in the debugger. So I've taken the habit of explicitly declaring ivars for value types.
Comment: circling back on my question after a few months... I use `@property` for everything now, with `@synthesize foo = foo_;`, no iVars anywhere. I also don't like using the dot-notation anymore, I use the setter for everything... Thanks all for your comments!
Comment: @bbum do you now use autosynthesis, which infers `@synthesize foo = _foo`, instead of `@synthesize foo = foo_`?
Comment: @ohhorob Where do they state that? It's not that I disagree -- I've always thought that was the case. But I've searched for a statement to that effect in the docs a few times recently and came up empty. If you happen to know where it is, please share!
Comment: @Emile - Ahhh! That is great to know. I've always wondered why in some applications I can see values in the debugger and sometimes not. Perhaps this IS tied to whether or not an ivar is declared. I must investigate this immediately! =)
Comment: @bbum - I think you have it backwards. I believe ohhorob is promoting the use of trailing and not the use of leading... (or perhaps you have a typo, or he has it backwards). PS -- Thanks all for your very informative answers!
Comment: @bbum I thought the concern about init/dealloc was mostly due the possibility that a subclass might override an accessor and add side effects that could cause problems in those methods. More often than not I'm creating the subclass, not the thing to be subclassed, so it's not a big issue, but I'd appreciate your opinion.
Comment: Nope;  given that my day job is an Apple engineer, I use `_foo`. :)  @Caleb that is also correct... let me expand my answer.
Comment: @bbum Nice update. Setters *seem* like attractive override points (even if they're really not): "I want to do X every time `foo` changes, so I'll override `setFoo:`." Maybe KVO is a better way to do that.
Comment: @caleb KVO is a decoupling improvement, but still leaves order dependency issues.  Think of an object with "firstName" and "lastName";  observing both will lead to situations where you'll end processing a change where the `firstName` and `lastName` might not be in a coherent, matching, state. (I.e. if I change my name from "William Bumgarner" to "Bill Bumblaster" [from when Fake SJ was funny], it takes two transactions and processing after the first would be incorrect... but what if I only change my first name?)
Comment: @Caleb my answer to a previous question summarises it (http://stackoverflow.com/questions/4580684/common-programming-mistakes-for-objective-c-developers-to-avoid/4588709#4588709). And it provides a link to the relevant section of the Apple Developer Library Coding Conventions document.
Comment: One reason for preferring ivar_ over _ivar is that KVC gives direct access to the latter, however 'private'. Not very likely to bite often, admittedly.
Comment: @bbum: one motivation for not using accessors in -init might be to be really clear about the semantics of an immutable object; ie. declare properties readonly (in a class extension), and assign using ivars in init (and only init).
Comment: @Cris both good points;  though I would claim that any use of `valueForKey:` and `setValue:forKey:` in code is generally a sign of a Design Gone Wrong.   As for readonly properties, I often redeclare them as read write in a class extension at the top of my .m for internal use by my class.  Especially when not using ARC, this guarantees all memory management is handled automatically through the setter/getter.
Comment: @bbum: have you written more about not using KVC accessors anywhere? Curious, but don't want to derail comments here (and design-related questions don't tend to go down well with the SO cops).
Comment: I haven't, but -- in short -- use of `valueForKey:` bypasses any compiler checks.  Given that you have to write the code, you should just write the call. Certainly, you may be computing a key on the fly, but -- even then -- it is best to avoid or, at the least, isolate the calls behind a sensible API that does a bunch of validation internally.
Comment: @bbum: right, I can see the sense in that. I have a specific case in mind for which KVC's ability to return a mutable proxy collection is a godsend; but I'm making those calls only on a class written specifically for that purpose.
Comment: To be clear; using `foo.bar = 42` vs. `[foo setBar:42]` is entirely a personal choice of style.  There is no difference in the generated code.   To each his own (I use `.` pretty much all the time with `@property` declared stuff and pretty much never -- sometimes `anArray.count` or `aString.length` -- otherwise).
Comment: @MattDiPasquale Thanks!  Updated!  Yup -- I always use automatic synthesis.   Fewer lines of code, the better.
Answer: Using iVars certainly isn't wrong, however best practises now do push for using @property instead.
Answer: One place where you may want to use an ivar is when you want to declare a protected property. You declare the property in the .m file for a class, and declare its corresponding ivar in the .h with the @protected directive. This will then let you have a protected access in the subclass. There's no alternative for protected access to members.

Should I use ivars in Objective-C?