Dynamic markings and relative sound levels of instuments

Question: In an orchestra, various instruments have different "perceived output volume" capabilities and these change across registers. For example, flutes get louder in their higher register, bassoons are louder in their lowest register, while french horns are softer somewhere in the middle of their sound range.
Of course, it is a good practice to write playable pieces :-)
However, assuming the piece is playable (together with an appropriate instrument doubling, tripling, etc. if more volume is needed), how should dynamics be marked and understood?
There are (at least) three people involved here:

a musician, who is an expert in their instrument,
a conductor, who hears the balance of this particular orchestra,
a composer, who had an idea for what balance would sound good or achieve a particular effect.

In one extreme dynamic markings could be absolute, as in "how it should sound like from audience perspective". In another extreme I can imagine making the markings being very detailed including changes when the instrument enters its quiet register, as in "how it should be played".
How should dynamics be marked and understood?
Comment: Is this really an `orchestration` question, rather than a `composition` question? Or may it's both? Or even a bit of `interpretation` thrown in as well?
Answer: Since dynamic markings do not have an absolute meaning (historically) it's hard to give a simple answer to your question.
Your use of the term absolute is "relative"!  Relative to the audience which is not an absolute measure but an opinion (group consensus?).  Different people in the audience may perceive the music too loud while other too soft.
Having worked in orchestras I can say that the conductor would often go into the audience seats and come back to adjust our volumes.  When an entire section of horns would all play mezzo-piano (in their own mind) the sum of the sound would produce a mezzo-forte or mezzo at the conductor's seat and we would be instructed to play piano or softer to create mp.  So, clearly the intent is to produce the effect for an audience.  In that type of setting the audience is the most important participant.  I would guess that composers are creating form a listener's perspective (i.e. "I want the audience to hear it like this...").  When playing solo the situation is different from a personal physical perspective but the intent is likely the same (to produce a certain sound for the listener).
When I say that dynamics are not absolute what I mean is that piano is simply softer than mezzo and forte, but that does not translate to a fixed decibel level from the point of view of scientific measurement.  So if the loudest section of a piece is forte a player may play as loud as possible, but if the loudest section is ff they would need to play the f sections softer than their personal max volume.  It is all relative which gives the performer some leeway in interpretation.  Again, in an orchestra setting you might hear the conductor say "don't push too hard on the forte section, we have fff forzando at the end".
I think the intent is to produce a sound that is interpreted by the audience.  To this end we are trained to try our best to control the instruments so that we can create a constant volume across frequency ranges.  So if volume increases with frequency one might be instructed to soften up in the upper register of the instrument and not "overdrive" it.  The contra bass is a particular issue as in the lowest register of the instrument it gets quite quiet.
So, your two examples actually feed the same goal, i.e. to produce a consistent volume at the listener's ear.
Comment: 'Piano is softer than mezzo and forte' is a little confusing!
Comment: I'm using softer as a synonym for quieter.  piano is quieter than mezzo, and quieter than forte, louder than pp, and ppp.
Comment: You are spot-on :  it doesn't matter how loud you *think* you are or are supposed to be,  the conductor will **tell** you to adjust until he is happy with the ensemble sound.
Answer: Of course it's about what the audience hears.  But the composer doesn't have to micro-manage.  Tell the player what result you want, leave it to him to work out how to deliver it. (And make sure you've written something he CAN deliver.)
Some say that 'ff' in the strings should be matched with 'f' in the brass.  I disagree.  To me, 'f' means 'solid', 'ff' means 'exciting'.  They aren't decibel levels.  The players have ears, and there's a conductor.
For the 95% of 'orchestral' music written today that will never be performed by anything but a computer different rules apply.  You may NEED to micro-manage - hairpins every time a phrase rises, carefully graded dynamics between sections etc.   Or your software may attempt to do this for you (e.g. the 'expressive' features of NotePerformer).  The only rule is to know your tools and use your ears.
Then there's the situation where live performers combine with technology.  Henry Mancini would match a group of bass flutes with a 'big band' rhythm section.  Impossible without amplification, but perfectly valid with it.  And it isn't 'wrong' to score a song with the assumption that the vocalist will have a mic and 'right' to score like an opera.


Generating correlation matrices using Wishart distribution

Question: I have problem on generating correlation matrices using Wishart distribution. I read some articles about Wishart distribution, and it turns out that Wishart distribution is commonly used to generate covariance matrices. Is it possible to generate correlation matrices using Wishart distribution? Any information about useful sources about it?
Comment: @jbowman: Of course, if you drop the $i \neq j$ requirement in the first part of your remark, the second part becomes superfluous since the resulting diagonal entries will be one. :)
Comment: so, if we use wishart to generate covariance, what will be used as the degree of freedom? is it number of observation from which we use the Sigma matrix minus one or other thing? Sorry to ask, but I am kind a confuse too with Wishart
Comment: Do you know the relationship between a correlation matrix and a covariance matrix?  If so, you can generate a covariance matrix using the Wishart distribution, then convert it to a correlation matrix.  Just divide each $(i,j)^{th}$ entry ($i \ne j$) by the square root of the product of the $(i,i)^{th}$ and $(j,j)^{th}$ entries, and, afterwards, set all the diagonal entries equal to 1.
Comment: Thank you for guide. I will try it. Do you know any article that ever use Wishart distribution to generate correlation matrices?
Comment: @cardinal - but then you have to pay attention to the order of operations in whatever loop(s) you set up!
Comment: @jbowman: Loops? ;)
Comment: @cardinal - the invisible, implicit ones - something like: for (i in 1:N) for (j in 1:N) s[i,j] <- s[i,j] / sqrt(s[i,i]*s[j,j]) - that don't appear in any known comment of mine!
Answer: Let $S$ be from Wishart$(\Sigma,r)$ and let $D$ be the diagonal matrix such that $D_{ii} = \sqrt{S_{ii}}$. Then $R=D^{-1}SD^{-1}$  will be a random correlation matrix. Actually one can easily check that if any $S$ at all is a covariance matrix then $R=D^{-1}SD^{-1}$ is a correlation matrix, because the matrix operation always divides each elements of S by the correct standard deviations.
Furthermore, because $S$'s diagonal elements are all positive with probability one, and the matrix $D$ is invertible if and only if the diagonal elements of $S$ are all positive, the matrix $D$ must be invertible with probability one.


Adicionar valores em DIV

Question: Olá
Eu tenho 3 inputs, eu gostaria que ao digitar algo no input 1, seja inserido o conteudo em uma div chamada resultado, e ao digitar no input 2 seja inserido na div resultado e assim por diante, sem substituir o valor anterior em javascript.
Exemplo:
Input 1 - Valor: 10
Input 2 - Valor: 5
Input 3 - Valor: 12
Resultado na DIV: 10, 5, 12
Obrigado
Comment: Você está usando algum framework JS ou é javascript puro?
Comment: Javascript puro
Answer: Passos:

Percorra cada input e adicione seu value em um array, caso ele não esteja vazio

Junte cada item do array com um ", ";

Escreva o resultado na div

Coloque tudo em uma função e a execute com o evento de keyup nos inputs

var inputs = document.querySelectorAll('.concatenate');
var div = document.querySelector('div');

function fillDiv() {
  var result = [];
  [].forEach.call(inputs, function(input, i) { // percorrendo inputs
    if (input.value != "") { // verificando se está vazio
      result.push(input.value); // adicionando ao input
    };
  });
  div.innerHTML = result.join(', ') // juntando com o ", " e escrevendo o resultado na div
};

[].forEach.call(inputs, function(input, i) { // adicionando a função ao evento key de cada input
  input.addEventListener('keyup', fillDiv);
});
<input type="text" class="concatenate">

<input type="text" class="concatenate">

<input type="text" class="concatenate">

<input type="text" class="concatenate">

<input type="text" class="concatenate">

Resultado:

Comment: Obrigado, mas é quase isso que eu preciso, eu preciso que ao clicar no input pega o valor e joga na div;
Comment: @abduzeedo, acho que pelo que está escrito na pergunta, isso está servindo.
Comment: ok, Como ficaria para pegar o valor ao clicar ?
Comment: @abduzeedo, coloque ao invés de "keyup", "click"

Adicionar valores em DIV


Replace numbers with array

Question: how to put integer values, taken by another array, instead of 1,2,3 like this?
<code>$arr_id = array(1,2,3); //this arr_id go to line 2 instead of 1,2,3
'id' => array('$in' => array(1,2,3))
</code>

well, putting $arr_id instead of "1,2,3"... something like this
<code>'id' => array('$in' => array($arr_id))
</code>

the problem is that 1,2,3 are number, but in my $arr_id i've strings. If i try to convert string to int i've a problem with "," too
here
<code>array($arr_id))
</code>
i need to have integers (not string) taken by $arr_id, separated by ","...
Comment: It looks like they're already integers. Are you saying that `$arr_id` is actually equal to the string "1,2,3"? Can you clarify with code examples exactly what you're starting with and what you want to end up with?
Comment: Or is it already an array of ints and you're trying to _turn it into_ "1,2,3"?
Comment: @Don'tPanic i'm tryin' to put it inside 1,2,3 in the line 'id' => array('$in' => array(1,2,3)). It starts with a string (verified by echo gettype($arr_id);) . Please read below in the first answer and relative comments... there's a progression :)
Comment: if i wrote
'id' => array('$in' => array($array_replaced[1])) or
'id' => array('$in' => array($array_replaced[2]))

the code works fine. But i can't write [integers. Very strange problem....
Comment: I'd really like to help. But I don't really understand from your description what you're starting with or what you want to end up with. Can you edit your question to add a code example that shows that?
Comment: @Don'tPanic tnx. Ok. **1)** start with a string `$arr_id = "1,2,3"` **2)** string changed in an array `$new_array = explode("," , $arr_id);` **3)** used a function wrote below `$array_replaced = array_map('intval',$new_array);` **4)** replace 1,2,3 in `id' => array('$in' => array($array_replaced))` doensn't work **5)** if i write `id' => array('$in' => array($array_replaced[1]))` the code works (all variables and arrays are ok)
Comment: i need to pass to the $in function (MongoDB) a list of array[]... but in every database the id field is an integer (in mysql and others too... there's the same function $in). So i need to pass this group of IDs as a numeric parameter (a list of integers). I think it's impossible to write this with array[] 'cause you MUST to write the array index for the query. By shell it's very easy... by php should be "impossible"...
Answer: You can convert a string array to an int array in PHP using:
<code>$arr_id_str = array("1","2","3");
var_dump(array_map('intval',$arr_id_str));
</code>
Comment: ok... your code is correct but... there's a problem: if i put $array_replaced

$array_replaced = array_map('intval',$arr_id_str);

inside

'id' => array('$in' => array($array_replaced))

the code doesn't work

Warning: array_values() expects parameter 1 to be array, null given

i can't write $array_replaced[1] or 2 or 3... 'cause is the same to write 1,2,3. This fields is dynamic.....

Replace numbers with array


Mudança dinâmica da tag meta viewport

Question: É possível alterar o viewport de uma página e ter imediato efeito sem ter que atualizá-la?
Supondo que tenho o seguinte viewport na página para exibição em dispositivos móveis (smartphones e tablets):
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

Então, eu tenho um botão no final da página, do tipo Versão completa que, ao ser clicado, chama uma função JavaScript (ou jQuery) que altera o width do viewport para 1024 pixels de largura. Essa alteração na propriedade do <meta>, via script, já altera a visualização da página de imediato ou precisa fazer um reload?
Outra coisa: o viewport com largura definida em pixels, deve conter px ou apenas o número (ex., width=1024, ou width=1024px,)?
Answer: Esta resposta aplica-se à dispositivos móveis.
Percebi que ao mudar dinamicamente o viewport para uma largura fixa, a resolução da tela muda, porém o conteúdo não se adapta à largura.
Imagem com viewport="device-width...":

Resultado após clicar no botão Versão completa:

No entanto, o contrário funciona perfeitamente, ou seja, alterar o viewport de valor fixo (width=1024) para modo de dispositivos móveis (width=device-width...).
Conclusão:
É necessário atualizar a página para que o conteúdo da página se ajuste ao viewport. Neste caso, seria necessário guardar o novo valor do viewport em uma variável (ex., SESSION, localStorage...) e atualizar a página e renderizar com o novo viewport.
Exemplo usando SESSION com PHP:
<?php
if( $_SESSION['viewport'] == "desktop"){
?>
<meta name="viewport" content="width=1024...
<?php
}else{
?>
<meta name="viewport" content="device-width...
<?php
}
?>

Exemplo usando localStorage do JavaScript:

Ao definir um valor width no viewport, não se deve usar px
  (conforme exemplos acima).

Mudança dinâmica da tag meta viewport


In Angular JS how to disable column sort feature for selected columns

Question: In jquery data table I can disable specific column sort by
"aoColumnDefs": [{
                'bSortable': false,
                'aTargets': [0, 7]
            }]

Anyone know how to do this in angular JS?

myApp.controller("ListCtr", ['DTOptionsBuilder', function(DTOptionsBuilder) {
  $scope.dtOptions = DTOptionsBuilder.newOptions().withDOM('C<"clear">lfrtip')
}])

this code hiding my search bar but not able to hide sort feature of my first and fourth column?
Comment: You want your tr elements to be not clickable? Can you post the tr code as well? It would be helpful if you paste the full table code.
Comment: One of the ways is you can use ng-click = "$event.stopPropogation();" for that div/tr element and manipulate it in js.... would give you a more specific answer if you give more details on how you implemented the table
Comment: can you provide a fiddle or plunker or post your code for table
Answer: The angular-datatables equivalence to
aoColumnDefs: [{ bSortable: false, aTargets: [0, 4] }]

is
$scope.dtColumnDefs = [
   DTColumnDefBuilder.newColumnDef(0).notSortable(),
   DTColumnDefBuilder.newColumnDef(4).notSortable()
];

...

You must include DTColumnDefBuilder in the controller :
myApp.controller("ListCtr", ['DTOptionsBuilder', 'DTColumnDefBuilder',
    function(DTOptionsBuilder, DTColumnDefBuilder) {
       $scope.dtOptions = DTOptionsBuilder.newOptions().withDOM('C<"clear">lfrtip');
       $scope.dtColumnDefs = [
          DTColumnDefBuilder.newColumnDef(0).notSortable(),
          DTColumnDefBuilder.newColumnDef(4).notSortable()
       ];
    }
])

see http://l-lin.github.io/angular-datatables/archives/#!/api.
Comment: @vinothini, great you got it to work (apparently?) - regarding `aLengthMenu` there is no "translated" name / method, but then you should use `.withOption('aLengthMenu', [[5, 10, 15, 20, -1],[5, 10, 15, 20, "All"]])` in your case `$scope.dtOptions = DTOptionsBuilder.newOptions().withDOM('C<"clear">lfrtip').withOption('aLengthMenu', [[5, 10, 15, 20, -1],[5, 10, 15, 20, "All"]]);` ....`withOption()` simply add `this[key] = value` to the options literal.
Comment: do you know how to set "aLengthMenu": [[5, 10, 15, 20, -1],[5, 10, 15, 20, "All"]] in angular data table
Comment: @davidkonrad i am exacty suffering with the same issue.can you provide any help ?here is the link to my question   https://stackoverflow.com/questions/44501820/disabling-angularjs-datatable-sorting-for-specified-columns
Answer: I have tried every possible solution to disable sorting but the only thing that worked for me was : order: false . Use this for reference
My dtOptions were as below
vm.dtOptions = {
        dom: '<"top"f>rt<"bottom"<"left"<"length"l>><"right"<"info"i><"pagination"p>>>',
        pagingType: 'simple',
        autoWidth: false,
        responsive: true,
        order: false, // This fixed the issue
        columnDefs : [{
            targets: [0, 1, 2, 3, 4, 5, 6, 7], // column or columns numbers
            orderable: false,  // This was not working
            filterable: false,
            sortable  : false
            },
            {
                // Target the actions column
                targets           : 8,
                responsivePriority: 1,
                filterable        : false,
                sortable          : false,
                orderable: false
            }
        ]
    }


Maintain affinity in Pull notifications using EWS managed API

Question: I need to notify on events in thousands of mailboxes to another system, I've created a pull notification subscription and it works great, I've created several of them but I need to GetEvents() from each one separately, then I read this article How to: Maintain affinity between a group of subscriptions and the Mailbox server in Exchange in the MSDN, it says I need to add headers to the subscriptions then I'll be able to getEvents() for all of them in one request, using the EWS managed API it should look like this:
service.HttpHeaders.Add("X-AnchorMailbox", Mailbox.SMTPAddress);
service.HttpHeaders.Add("X-PreferServerAffinity", "true");

Then I should get back a cookie in the response:

X-BackEndOverrideCookie

I don't see the cookie in the response and I did not find anything in the article regarding how to obtain and use it in the EWS managed API (except those two lines above all the rest of the article is based on XML requests which I don't really like). besides that as far as the request it should include all the subscriptions id's (as seen in the XML) and for this I did not find a solution in the EWS managed API too.
I've made this with the streaming notification solution but I would like to work with Pull notifications.
If anyone has any experience with this I would love to hear.
Thanks in advance for the time you took in reading this and for your answers in case you've answered.
Comment: Is this for Office 365 or Exchange on-premises?  If Exchange on-premises, which version of Exchange?
Comment: This is for Office365.
Comment: Thanks, I just posted an answer that might work for you for Office 365.
Answer: For Office 365, have you looked at Webhooks through our Office 365 Mail, Calendar and Contacts REST API endpoint?  See "Connect to the Outlook Service" on http://dev.outlook.com for more info.  To access multiple mailboxes within an organization, you will need to use client credential flow.
As long as the system receiving the notifications has an always available endpoint to receive push notifications, that model works much better to monitor notifications from thousands of mailboxes.  My recommendation would be to look at using Webhooks API.  It is currently in Beta, but we are working actively to take it to GA.  At that point, you can use Webhooks in production.
Comment: Thanks for your answer, it sounds great though I would not be able to use any beta product/solution in this project (client limitations).
Answer: I know this question was asked nearly three years ago, but I happen to be working on this today and hope this will help someone else.
I'm using streaming notifications, but I'm guessing it'll work similarly for pull notifications:
// You MUST send a subscription request first! Otherwise there won't be
// any cookies to examine.
exchangeService.SubscribeToStreamingNotifications(foldersToSubscribeTo, EventsToSubscribeTo);

// Get a string of all the cookies
var allCookies = exchangeService.CookieContainer.GetCookieHeader(exchangeService.Url);
Console.WriteLine(allCookies);

// Or get a specific cookie
var cookies = exchangeService.CookieContainer.GetCookies(exchangeService.Url);
var xBackEndOverrideCookie = cookies["X-BackEndOverrideCookie"];
Console.WriteLine(XBackEndOverrideCookie);

I think for new subscription requests where you were using a new exchange service, you would set the cookies like this:
exchangeService.CookieContainer.SetCookies(url, cookieHeader)

...but I could be wrong since I haven't had to actually set any cookies yet in my application.
Comment: Why not test it before posting an answer?
Comment: Hi @StephenRauch! I don't know if you've worked with the EWS Managed API before, but I've found a lack of information concerning key portions of interacting with Exchange. I've appreciated people posting anything related to the EWS Managed API; even if it's incomplete, indirectly related to my application, or untested, the hints can be enough to get me down the right track. I'm not able to test the exact solution the original asker is looking for while I'm at work, so I posted the above hoping that what I've learned in researching this subject will help someone else get on the right track.
Answer: @broAhmed, your way of accessing the X-BackendOverrideCookie works like a charm! But as far as setting the X-BackendOverrideCookie in the HttpHeaders of new EWS requests, here is what works for me:
// this is how to get the cookie
string xBackendOverrideCookie = exchangeService.CookieContainer
    .GetCookies(exchangeService.Url)["X-BackendOverrideCookie"].Value;

// this is how to set the cookie for future requests
exchangeService.HttpHeaders.Add("X-BackendOverrideCookie", xBackendOverrideCookie);


How to prove $\frac{nx^3}{1 + n^2 x^2}$ converges uniformly on $[1, \infty)$

Question: I know this sequence of functions converges to $0$ pointwise, so I have to show that for all $\epsilon > 0$, there exists an $N$ such that for all $n > N$, $d(\frac{nx^3}{1 + n^2 x^2}) < \epsilon$. I can see that $d(\frac{nx^3}{1 + n^2 x^2}) < d(\frac{nx^3}{n^2 x^2}) = d(\frac{x}{n})$, so I can't take this approach since $\frac{x}{n}$ is not uniformly convergent (I think I have to show something like $d(\frac{nx^3}{1 + n^2 x^2}) < \epsilon < d(\frac{nx^3}{n^2 x^2}) = d(\frac{x}{n})$.)
I thought it might not converge uniformly so I tried taking the derivative and setting it equal to $0$, but the result is that $x = 0$ so that doesn't work since the sequence does converge pointwise to $0$.
What other approaches can I take?
Answer: The sequence does not converge uniformly to $0$ on $[1,\infty)$. Consider what happens when $x=n$.


xmlstarlet select value

Question: This is the xml-data:
<DATA VERSION="1.0">
  <TABLES>
    <ITEM>
      <identifyer V="1234"></identifyer>
      <property1 V="abcde"></property1>
      <Property2 V="qwerty"></property2>
    </ITEM>
    <ITEM>
      <identifyer V="5678"></identifyer>
      <Property1 V="zyxwv"></property1>
      <Property2 V="dvorak"></property2>
    </ITEM>
  </TABLES>
</DATA>

I am trying to find property2 of the item where identifyer has value 1234. I can select the data:
$ xmlstarlet sel -t -c "/DATA/TABLES/ITEM/identifyer [@V=1234]" test.xml
<identifyer V="1234"/>

Two types of output would be desirable:
$ xmlstarlet <some magic>
<identifyer V="1234"></identifyer>
<property1 V="abcde"></property1>
<Property2 V="qwerty"></property2>

And:
$ xmlstarlet <some magic>
qwerty

Answer: The key is to start from the ITEM node, not the identifyer:
$ xmlstarlet sel -t -c "/DATA/TABLES/ITEM[identifyer/@V=1234]" test.xml
<ITEM>
  <identifyer V="1234"/>
  <property1 V="abcde"/>
  <Property2 V="qwerty"/>
</ITEM>

Then you can pick out the bits you want:
$ xmlstarlet sel -t -c "/DATA/TABLES/ITEM[identifyer/@V=1234]/*" test.xml
<identifyer V="1234"/><property1 V="abcde"/><Property2 V="qwerty"/>

$ xmlstarlet sel -t -v "/DATA/TABLES/ITEM[identifyer/@V=1234]/Property2/@V" test.xml
qwerty

Comment: Great, that works :) Good to see the syntax in an example, I can get forward with this. Thanks!

xmlstarlet select value


economics.stackexchange.com is not properly moderated

Question: Can a small reward control big money exchange rates?

Closed. This question needs details or clarity. It is not currently accepting answers.
Add details and clarify the problem you're solving. This will help others answer the question. You can edit the question or post a new one.

I've accomplished the moderator's requirements, but the question isn't unclosed. Why?
Comment: I recommend changing the title of this meta post to: "The decentralized review process of economics.stackexchange.com is oppressing my crypto question, please help me central authority."
Answer: First, the requirements are not moderator requirements they part of site rules and the site is moderated by all high rep members not just moderators. It is not necessarily moderator job to review your contribution, if other users do not reverse their closing vote.
Furthermore, moderators on stack exchange sites are volunteers and we do not guarantee speedy moderation. Consequently, just because your question is not opened immediately after it is edited does not mean the site is not properly moderated.
In addition, I find that the question still lacks details and clarity you just included some extra information about your project that does not even seem relevant.
In your question you ask if "small reward" can control "big money exchange rates", what is here "small reward"? What are "big money exchange rates"? This is not economic terminology so you need to explain what you even mean by that. How do you define small reward in economic terms? Is it some monetary reward if so what is small \$100 \$10,000 or \$100,000?
Next, in the body of a question you state:

Let we have a prediction market. Suppose the prices of some conditionals became high because it bubbled so much that people started to use the conditionals as means of payment.

I want to control this big market of conditionals using only a small (e.g. 1-5% of the big market) amount of some collateral (e.g. dollars or bitcoin) to pay to conditional owners at the end of the prediction period.

Again you need to add details of clarity, what are the conditionals you are talking about here? Also what do you mean by controlling the "big market of conditionals"?
Next you ask:

Is this possible? At first it would seem impossible, but in Russia the CB was able to control the dollar-rouble rate by publishing recommended exchange rate. Considering existing practical economical knowledge of similar situations, will our small collateral donations likely control the big market? Is this control stable? How much part of the value of the big market we need to control well?

What are your references for the first statement? Next again how you define small collateral donation and control over a market?
Lastly, the last two new paragraphs you included do not seem to add any clarification at all of your question so you should either consider removing them or explaining how they relate,


AR(1) Finding $\gamma_l$

Question: I have $\gamma_l = Cov(r_t, r_{t-l})$ as a definition in my notes and now I need to find $gamma_l$ for a series $r_t- m = p(r_{t-1} - m) + a_t$ where $r_t$ is a linear time series with expected value $m$ and $a_t$ is a white noise.
Here is my attempt:
$Cov(r_t - m, r_{t-l} - m) = E[(r_t - m)(r_{t-l} -m )] = E[p^2(r_{t-1} - m)(r_{t-l-1} -m ) + pa_t(r_{t-l-1} -m ) + pa_{t-l}(r_{t-1} - m) + a_ta_{t-l}] = p^2E[(r_{t-1} - m)(r_{t-l-1} -m )] + 0 + pE[a_{t-l}(r_{t-1} - m)] + E[a_t]E[a_{t-l}]$
Now if $l=0, =  p^2E[(r_{t-1} - m)(r_{t-l-1} -m )] + pE[a_{t-l}(r_{t-1} - m)] + s_a^2 $
Otherwise, $=  p^2E[(r_{t-1} - m)(r_{t-l-1} -m )] + pE[a_{t-l}(r_{t-1} - m)]$.
In either case, I'm stuck here.  I am supposed to get everything in terms of $\gamma_{l-1}$ (or $\gamma_1$ in the case of 0, but I am not sure how to proceed.
Comment: you might consider adding the self-study tag after reading this: https://stats.stackexchange.com/tags/self-study/info
Answer: Let $v_t=r_t-m$, then $v_t=pv_{t-1}+a_t$. Covariance is invariant under de-meaning: $\gamma_l=cov(v_t,v_{t-l})$. Let's first solve $\gamma_0$:
$$\gamma_0=cov(pv_{t-1}+a_t, pv_{t-1}+a_t)=p^2\gamma_0+\sigma_a^2 \rightarrow \gamma_0=\frac{\sigma_a^2}{1-p^2}$$
Note that $cov(v_{t-1},a_t)=0$ because previous output is irrelevant of the current white noise.
For $l=1$:
$$cov(v_t,v_{t-1})=cov(pv_{t-1}+a_t,v_{t-1})=pcov(v_{t-1},v_{t-1})=p\gamma_0$$
For $l=2$:
$$cov(v_t,v_{t-2})=cov(pv_{t-1}+a_t,v_{t-2})=pcov(v_{t-1},v_{t-2})=p\gamma_1=p^2\gamma_0$$
If you go on like this, you'll have $\gamma_l=p^l\gamma_0$. Since $\gamma_l=\gamma_{-l}$, by definiton, this formula generalizes into the following:
$$\gamma_l=p^{|l|}\frac{\sigma_a^2}{1-p^2}$$

AR(1) Finding $\gamma_l$


Is it legal to substitute the limit variable in a question like this?

Question: The question: Find the derivative of $f(x) = x^{-1}$
You can write down the derivative (Using limits) as
$\lim_{h\to 0} \frac{f(x+h)-f(x)}{h}$
$\lim_{h\to 0} \frac{(x+h)^{-1}-x^{-1}}{h}$
$\lim_{(x+h)\to x} \frac{(x+h)^{-1}-x^{-1}}{(x+h) - (x)}$
As you can see, i switch the variable in the limit above. Is that legal? What is the formula behind the switch? What are the formal requirements for it to be legal?
Comment: No! You'll get prosecuted!
Comment: @YoTengoUnLCD Goddamn, i don't even have a lawyer! Although in all seriousness i was wondering about whether or not the substitution is valid/invalid.
Comment: As far as I can tell, it seems valid.
Comment: It also gives the correct answer in many scenarios i tried. But there's got to be some kind of a derivation/rule that allows you to confirm whether or not the above is valid, and under what circumstances such a switch on the limit for the same function is valid or not.
Answer: You have the right idea, but the notation is not very good. What you can do it something that looks like substitution in integral computation: let $y = y(h) = x+h \iff h = y - x$, and now your expression becomes:
$$\lim_{h \to 0} \frac{f(x+h)-f(x)}{h} = \lim_{y \to x} \frac{f(y)-f(x)}{y-x},$$
and this is true.
Formally, how does that works? You're computing the limit of some function $g_1(h) = \frac{f(x+h)-f(x)}{h}$ with $h \to 0$. Let $\phi : \mathbb{R} \to \mathbb{R}$ be defined by $\phi(h) = x+h$. Then you can let $g_2(y) = \frac{f(y) - f(x)}{y - x}$, so that:
$$g_1(h) = g_2(\phi(h)).$$
It's obvious that $\lim_{h \to 0} \phi(h) = x$. So now, if $\lim_{y \to x} g_2(y) = l$ exists, then the theorem about limits and composition of functions* implies that:
$$\lim_{h \to 0} g_1(h) = \lim_{h \to 0} g_2(\phi(h)) = \lim_{y \to \lim_{h \to 0} \phi(h)} g_2(y) = \lim_{y \to x} g_2(y) = l.$$
Note that I used a theorem here, it's not something completely obvious. It's usually not very hard, but you need to check that all the hypotheses of the theorem are satisfied.

* The one that says that if $\lim_{x \to a} f(x) = b$ and $\lim_{y \to b} g(y) = c$, then $\lim_{x \to a} g(f(x)) = c$.
Comment: Can you please name the theorem about limits and composition of functions?
Comment: @AayushAgrawal I don't know what name you give it, it's the one that says that if $\lim_{x \to a} f(x) = b$ and $\lim_{y \to b} g(y) = c$, then $\lim_{x \to a} g(f(x)) = c$.
Answer: In that limit, the number $x$ is fixed, the number $h$ is variable. So it's somewhat strange to write ${(x+h)\to x} $ but it makes sense and even it's equivalent to ${h \to 0} $ in your case (since the number $x$ is fixed here). I mean this: since $x$ is fixed, obviously ${(x+h)\to x} $ if and only if ${h \to 0}$.
Answer: Yes, you can do that since the two statements are equivalent if $x$ is continuous. Consider a discontinuous function i.e.
$x = {1, \hspace{0.25cm} if \hspace{0.1cm} x \leq x^*}$
$\hspace{0.4cm} = {0, \hspace{0.25cm} if \hspace{0.1cm} x>x^*}$
In a case like this, such a substitution would be incorrect.
Please share if you have something different to say. :)
Answer: First question to ask is whether the writing $\lim_{x+h\to x}$ even makes sense according to the definition of limits. In this case it does. The second is if it's a valid transformation. Which it also does in this case.
You have to recall the definition of limits:

We say $\lim_{\xi\to a} \phi = L$ if for each $\epsilon > 0$ there's an $\delta > 0$ such that whenever $|\xi-a|<\delta$ we have $|\phi-L|<\epsilon$.

I intentionally left out the argument of $f$ as we shall see what happens if $x$ is not the argument of $f$. The thing here is that in the first cases we have $\xi$ being $h$, and $a$ being $0$ and in the last $\xi$ being $x+h$ and $a$ being $x$. In the definition that affects $|\xi-a|$ which would be $|h-0|=|h|$ in the first case and $|x+h-x|=|h|$ in the second. So it's seem to make sense and be correct.
Now for the problem of substitution in general. You simply have to make sure that the substitution behaves well enough. You first of course have to make sure that the substitution is bijective - otherwise you could miss out parts of the neighborhood of the target, but you also have to make sure it's continuous in both directions.


Criar uma Query no Wordpress utilizando campos relacionais do ACF

Question: boa noite.
Estou desenvolvendo um site de cadastro de filmes para um primo aficionado por cinema e preciso de uma ajuda para colocar uma query que liste o nome dos filmes cujo personalidade da página participou ou atuou.
Estou desenvolvendo (tendo em vista meu pouco conhecimento em programação) utilizando WordPress + Elementor + Custom Post Types UI + ACF.
Criei os seguintes CPTs: Filmes e Personalidades
No Post Type Filmes, existem campos como diretores, atores, roteiristas, músicos e fotógrafos que são preenchidos de forma relacional com o Post Type Personalidades, que possuem suas áreas de atuação distinguidas pela taxonomia (diretor, ator, atriz, roteirista, músico e fotografia).
Até aí tudo está funcionando perfeitamente. Agora gostaria que fosse exibido na single da personalidade, quais filmes ele atuou.
Pesquisando no Google, e dando muita cabeçada na parede e murro em ponta de faca, cheguei no seguinte código, que se possível fosse inserido na single via shortcode.
Entretanto mesmo depois de muita pesquisa, hoje completam quase 30 dias, esta função ainda não funciona. Até agora consegui chegar no seguinte código:
add_shortcode ('filmografia', 'filmografia_ator' );

function filmografia() {
ob_start();

<?php
    $post_data = get_post( get_the_ID(),ARRAY_A );
    $post_data = $post_data['post_name'];

        if($post_data){
        $args = array(
                  'post_type'   => 'filmes',
              'meta_query'  => array(
                array(
                      'key'     => 'atores',
                      'value'   => $post_data,
                      'compare' => '=',
                     ),
                        ),
                      'posts_per_page'=> -1
                );
        $query = new WP_Query( $args );

        // Loop da Listagem
        if ( $query->have_posts() ) { ?>

Filmografia

        <?php while ( $query->have_posts() ) {
        $query->the_post(); ?>

        <a href="<?php the_permalink(); ?>"><?php the_title(); ?> de <?php the_field('ano_lancamento'); ?>

        <?php } ?>

        <?php }
        wp_reset_postdata();
        }
        ?>
return ob_get_clean();
}

Quando rascunhei este código foquei somente num tipo de atuação e se desse certo, partiria para o segundo desafio que era fazer uma busca por atuação.
Acredito que o seguinte fluxo deve ser observado:
- Pegar o ID do post (para identificar qual personalidade é)
- Pegar taxonomia do post (para identificar qual tipo de atuação – diretor, ator, roteirista, etc.)
- Dependendo do tipo de atuação, buscar informação no campo correspondente do post type filmes;
- Caso exista post filmes cuja atuação foi definida:
- Gerar um loop em uma lista ordenadas com o nome do filme e ano.
Será que alguém poderia me dar um norte? Desde já agradeço a todos que tiraram um tempinho para ler e me ajudar nesta peleja.
Answer: Opa, boa tarde!
Cara, vendo o teu shortcode será usada apenas na single do cpt? Caso seja, não ha necessidade de tu passar um query porque a função vai pegar o ID do post atual. Por exemplo, tu poderia fazer algo assim:
<?php
function vv_filmes_by_actor()
{
   $filmes = get_posts([
      'post_type'   => 'filmes',
      'meta_query'  => array(
         'key'     => 'atores',
         'value'   => get_the_ID(),
         'compare' => 'IN',
      ),
      'posts_per_page'=> -1
   ]);

   if( ! $filmes ) return "Nenhum filme encontrado";

   $html = '';

   foreach($filmes as $filme){
      $html .= '
'.$filme->post_title.'
';
   };

   return $html;
}
add_shorcode("vv_filmes_by_actor", "vv_filmes_by_actor");


Are there rules of thumb that let me quickly determine a possible playing position from the key?

Question: I am playing some pieces in various keys; for example this one (from William Leavitt - Melodic Rhythms For Guitar):

I want to play it in a certain position (not using open strings), such that each finger is assigned to a fret. It turns out that this example can be played at position 3:
<code>---------------------------------------...
-4-3---4-----3-------------------------...
-----5---------3---------5-----------3-...
---------------------5-----6-----3-----...
-----------------------6-----------5---...
---------------------------------------...
</code>
However, if I try playing it at position 4, I'll soon discover that I need an uncomfortable stretch:
<code>-----------------
-4-----4---------
---7-5-------7---
---------------8- < problem!
-----------------
-----------------
</code>
Are there rules of thumb that let me quickly determine a possible playing position from the key?
Like (for example)

Key E♭? Play at position 3
Key Am? Play at position 5
Answer:
Are there rules of thumb that let me quickly determine a possible playing position from the key?

Really depends on the song/exercise you're trying to play. I don't there is a rule of thumb for things like this. You might find two songs that are in the same key, but for some reason or another, they aren't easy to play in the same position.
What I do and what I believe really helps is to try to figure it out by yourself. Try it on a couple of different positions and see what position fits for every song. This might not work on the next song that is in the same, but it will help you to learn your instrument and you'll be able to play in most of the positions, because you'll have had practice in them.
Also, this way you'll be able to play part of the exercise in many different positions. This will help you improvise (if you are interested in it).
Of course there are some stuff you should take into consideration. Like for instance, if your exercise/song is in Eb, and you are using standard tuning on your guitar, you (most likely) wouldn't start from the low E string, because it is a semitone higher than the desired tonic. You can start from F, the second of the scale, if you are going for something like that, but most likely, you are going to start from a higher position.
Answer: Each melody will differ, as the range will be different. So, no rule of thumb, except check the highest and lowest notes, and check through each note as it comes.And bear in mind that any accidentals may throw you out by a fret up or down.
Using a four fret encompass works for, for instance, a full two octave (plus 3 or 4 extra notes). Take A major,(4-7) starting at 5th fret bottom string. Assuming you're not going to find F on 4th string, it all works. Take A natural minor, though,(5-8) and to do the same involves moving down to B on the third string, so you're out of span. Make it A harmonic and the same occurs on top string for G#. So, almost all melodies will present a move out of the 4 fret span, if this is what you seek.
What most players end up doing is sharing a melody with two adjacent shapes, sliding between them as ans when. Obviously you'll find some melodies that fit your mould, but I don't think there's a formula that applies to give the answer. Play in several, and find those with least movement - or play up the dusty end of the neck, where a 5 fret stretch is less problematic.


Understanding the significance of @ProcessApplication

Question: I see the following way to create Camunda Process applications :
<code>@ProcessApplication
public class SpringServletProcessApplication extends ServletProcessApplication {
  ...
}
</code>
I what scenarios, do we use the above method ? When the project is not a springboot project ?
But when working with spring boot application, we don't need the annotation @ProcessApplication, why so ? Does SpringBoot Application contains own process application ?
<code>@SpringBootApplication
public class WebappExampleProcessApplication {
    public static void main(String... args) {
        SpringApplication.run(WebappExampleProcessApplication.class, args);
    }
</code>
Thanks
Answer: You can see what the annotation does here:
https://github.com/camunda/camunda-bpm-spring-boot-starter/blob/master/starter/src/main/java/org/camunda/bpm/spring/boot/starter/annotation/EnableProcessApplication.java

Annotation that disables the {@link SpringProcessEngineConfiguration}  * auto-deploy feature and instead
uses the required META-INF/processes.xml
as an indicator for
resource scanning. This also allows all processes.xml
configuration features described here:
 href="https://docs.camunda.org/manual/latest/user-guide/process-applications/the-processes-xml-deployment-descriptor/">The
processes.xml Deployment Descriptor

So you don't need the annotation if you are happy with the standard auto-deployment for process and decision models and have no need to override the default location of the process.xml file.
You may also find this class (or the other code in the project) interesting, in case you want to understand all the tings the Camunda Spring Boot Starter does: https://github.com/camunda/camunda-bpm-spring-boot-starter/blob/master/starter/src/main/java/org/camunda/bpm/spring/boot/starter/SpringBootProcessApplication.java#L99


ffmpeg-php won't start after upgrading php from 5.1.6 to 5.2.13

Question: CentOS 5, installed ffmpeg and compiled the ffmpeg.so. Everything works fine.
Then upgrade the php to 5.2.13 (using an external repository)
recompiled ffmpeg.so but now when trying to load php:
PHP Warning:  PHP Startup: ffmpeg: Unable to initialize module
Module compiled with module API=20050922, debug=0, thread-safety=0
PHP    compiled with module API=20060613, debug=0, thread-safety=0
These options need to match
 in Unknown on line 0
Any ideas how to resolve this issue ?
Thanks.
Comment: I suggest you to rollback, as there is no real php-5.2.13 rpm provided by rhel/centos
Answer: Got a solution,
phpize -clean,
rm the so file.
then reinstalling.


How do you check to see what your drupal site looks like as different types of users?

Question: I hope to find a way to stay logged in as admin but see what it looks like to an unauthenticated user and other types of users too, if possible.
I ask firstly because right now I am trying to make certain changes to the css file which means I need to check what the change looks like to an unauthenticated user. Sometimes it is easy to see more or less what I want in the admin pages but I do find I can get tripped up by this sometimes and also find I need to clean the cache of my browser before I can actually see how it looks. This is something that I do not really want to be taking much time over as I want to be able to correct it quickly if I made something look terrible.
Aside from that I do also have a few different kinds of users with various permission rights and when I change something I want to check that a change is doing what I want and all the users are still seeing the right things. Again, it is not an ideal situation for me to have to log out and in as each type of user for this type of thing as it can expose parts of the site if a mistake has been made or there is some bug rearing its head etc.
Aside from the aforementioned issues I have with needing to log in and out after every little change I make to the site, it makes the whole process pretty laborious. It suddenly dawned on me that someone else might have thought this too and that there is some way to work around it without compromising anything. Can anyone advise on this?
Answer: For the anonymous user you will require a second browser (not logged in) or you will have to log out to view the changes. For other roles, check out the Masquerade module. It permits you to rapidly switch user roles by masquerading as a user with that role.
Comment: Thanks, I just installed and actually I think writing "Anonymous" inMenu Quick Switch user  will allow to include non members to the list but I have not figured out how I use the switcher once I named the members to switch between yet! If you want I will edit your answer and add a screen shot to show how to include it.
Comment: Add away! Happy to help.


wordpress Hash method + login with wordpress database

Question: I use some external php I wrote and I want it to be used by wp_users.
So, I check user and password - if it matches I echo 'logged in'.
In Wordpress documentation it says the Wordpress hash method is MD5!
But when I md5 this (123321), I get this:
c8837b23ff8aaa8a2dde915473ce0991

But the password in my database is saved like this :
$P$BKaMz3dTLI9GIspy4Qmk2jPPQ4zv9f1

Is there any way to get a hash method in an external php to check if the user is logged in or not?
This is my code:
$userName = isset($_POST["name"]) ? $_POST["name"] : null;
$userPass = isset($_POST["pass"]) ? $_POST["pass"] : null;
$userPass = md5($userPass);
if ($userName && $userPass ){
    //print_r('SELECT * FROM wp_users WHERE user_login = "'.$userName.'"');
    $sql = "SELECT * FROM wp_users WHERE user_login = '$userName' limit 1";
    $result = $con->query($sql);
    if (!$result) {
        die('Invalid query: ' . mysql_error());
    }
    if ($result->num_rows > 0) {
      $row = $result->fetch_assoc();

      // CHECK PASS
     if($row['password'] == $userPass){
         echo "yeah you logged in";
     }

    }
}

Answer: Wordpress no longer uses MD5. See this. You can use is_user_logged_in () to check to see if the user is logged in, or go through the trouble to re-implement the Portable PHP password hashing framework. It is probably best to use the first option and pass the result to your external framework from your Wordpress app.
Comment: dear  i want use code for my mobile application , so i dont think so work with is_user_logged_in () . if you have idea please explain more . thank you
Comment: How is your mobile app *currently* handling authentication? Your best bet is to create an endpoint on your wordpress site that returns the information you need, which is guarded by running `is_user_logged_in`. It sounds like you're trying to insecurely check the password - which defeats the purpose.
Comment: yeah because i dont know how can i create plugin or API in wordpress.
do you have any sample ? thanks


How can I create logo for each user

Question: I want each user to create their own site-logo. This is not multi-site, this is a single site only. How can I do it?
Comment: if this is not for multisite, then why would you need that?
Comment: I just want each user to have their own logos :)
Answer: Add a field to the user profile and use this as a replacement for the logo. Use the page_preprocessor to add the user logo to the page template. Replace the logo by the one the user provided or show a default one.
Read more about this:

template_preprocess_page
Setting up variables to use in a template
Answer: If you want each user to have their own logo, then in the account settings of admin section you can create a logo field of type image. Then in edit section of account page you can upload the image.
Then with this custom code you can able to assign logo based on each user logged in :
So in the page.tpl.php of your theme folder you can make this modifications:
<?php if ($logo): ?>
        <?php global $user; ?>
    <?php if($user->uid == 1 || $user->uid == 0)?>
       <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" id="logo">
       <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>">

    <?php else :?>
    <?php
         $uid = $user->uid;
         $userDetails = user_load($uid);
         $filename = $userDetails->field_site_logo['und'][0]['uri'];?>
         <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" id="logo">
           <img src="<?php print image_style_url('sitelogo',$filename);?>" />

    <?php endif; ?>
<?php endif; ?>

Hope this helps you and saves time:)
Comment: Thanks for the reply. Can i know what is that sitelogo?
Comment: I came to know about image_style_url in drupal.org.thanks. let me try all these :)

How can I create logo for each user


Visual Studio 2012 "Apply Code Changes" menu-item is missing for native C++ debugging (probably due to managed-code projects in solution)

Question: I suspect that this relates to having managed-code DLL projects in the solution, since in VS2010 the menu-item was also missing unless I manually unloaded all managed-code projects from the solution.
In VS2012 though, I now have many more managed DLLs in the solution (not by personal choice), so I am hoping that there might be a way to enable "Apply Code Changes" even with managed DLLs in the solution.
I have set my local debugging mode to "Native Only" and also edited the "Edit and Continue" options under Debug - Options and Settings... to enable native "Edit and Continue", but still I get no "Apply Code Changes" icon under the Debug menu.
If I manually add the 'Apply Code Changes' button to a toolbar, it remains continually disabled.
Please can anyone offer any hints and tips as to how I might get this to work, or do I simply have to unload all managed-code projects from the solution?
Supposing that I do have to unload the managed-code projects, is there a straightforward way to maintain two different sets of solution options so that I can quickly decide whether I wish to mount all projects or native-only?
Answer: Although I do not have a definitive solution to your problem (I am an a similar position myself) I suspect that a good thorough reading of this MSDN document would be productive for us both:
Edit and Continue (Visual C++)
Comment: Thanks @James - I gave up in the end, having discovered that with edit and continue enabled, the custom visualizers didn't work for debugging.  I'm just having to get used to the kill, rebuild and try again cycle.  At this point I'm fed up of VS2012!


Como forçar um entry numeric no android funcionar com virgula ao invés de ponto para números decimais?

Question: Já tentei utilizar Culture mas também não funcionou e não queria fazer a gambiarra de colocar um replace antes de mandar para a base. Nem com o XLab eu consegui colocar o teclado para funcionar me ptbr e deixar colocar virgula ao invés de ponto. Alguém tem alguma solução mais luxuosa ?
Comment: A entrada é via `prompt dialog`? Utiliza XAML ou código para UI?
Comment: é direto pelo entry por código e não XAML.
Answer: Encontrei uma solução no fórum da Xamarin (código fonte está no final da resposta)
Você deve criar um layout de teclado personalizado (resource XML). Este código abaixo já está personalizado para sua necessidade:
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:keyWidth="33%p" android:horizontalGap="0px"
    android:verticalGap="0px" android:keyHeight="54dip">

    <Row>
        <Key android:codes="8" android:keyLabel="1" android:keyEdgeFlags="left" />
        <Key android:codes="9" android:keyLabel="2" />
        <Key android:codes="10" android:keyLabel="3" android:keyEdgeFlags="right" />
    </Row>

    <Row>
        <Key android:codes="11" android:keyLabel="4" android:keyEdgeFlags="left" />
        <Key android:codes="12" android:keyLabel="5" />
        <Key android:codes="13" android:keyLabel="6" android:keyEdgeFlags="right" />
    </Row>

    <Row>
        <Key android:codes="14" android:keyLabel="7" android:keyEdgeFlags="left" />
        <Key android:codes="15" android:keyLabel="8" />
        <Key android:codes="16" android:keyLabel="9" android:keyEdgeFlags="right" />
    </Row>

    <Row>
        <Key android:codes="67" android:keyIcon="@drawable/sym_keyboard_delete"
            android:iconPreview="@drawable/sym_keyboard_delete"
            android:keyEdgeFlags="left" />
    <Key android:codes="55" android:keyLabel="," />
        <Key android:codes="7" android:keyLabel="0" />
        <Key android:codes="66" android:keyEdgeFlags="right"
            android:keyIcon="@drawable/sym_keyboard_feedback_return"
            android:iconPreview="@drawable/sym_keyboard_feedback_return" />
    </Row>

</Keyboard>

Utilizando o teclado personalizado:
public class Activity1 : Activity
{
    public CustomKeyboardView mKeyboardView;
    public View mTargetView;
    public Keyboard mKeyboard;
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        mKeyboard = new Keyboard(this, Resource.Xml.keyboard2);
        mTargetView = (EditText)FindViewById(Resource.Id.target);

        mKeyboardView = (CustomKeyboardView)FindViewById(Resource.Id.keyboard_view);
        mKeyboardView.Keyboard = mKeyboard;

        mTargetView.Touch += (sender, e) => {
            Log.Info("onTouch", "true");
            ShowKeyboardWithAnimation();
            e.Handled = true;
        };

        mKeyboardView.Key += (sender, e) => {
            long eventTime = JavaSystem.CurrentTimeMillis();
            KeyEvent ev = new KeyEvent(eventTime, eventTime, KeyEventActions.Down, e.PrimaryCode, 0, 0, 0, 0, KeyEventFlags.SoftKeyboard | KeyEventFlags.KeepTouchMode);

            this.DispatchKeyEvent(ev);
        };
    }

    public void ShowKeyboardWithAnimation()
    {
        Log.Info("keyboardState", mKeyboardView.Visibility.ToString());
        if (mKeyboardView.Visibility == ViewStates.Gone)
        {
            Animation animation = AnimationUtils.LoadAnimation(
                this,
                Resource.Animation.slide_in_bottom
            );
            mKeyboardView.ShowWithAnimation(animation);
        }
    }
}

Utilize esta tabela de códigos android para personalização: KeyEvent
Código fonte: CustomKeyboard.zip


Slurs and repeats in LilyPond

Question: In a piece I have a bunch of:
<code>   b( es b es b es)  b( es b es b es)
</code>
repeating stuff.
I'd like to just copy-paste whatever template and insert the notes once.
I could do:
<code>\repeat unfold 6 { c d }
</code>
or:
<code>\repeat unfold 2 { \repeat unfold 3 { c( d) } }
</code>
but the slurs will be incorrect.
So how can I add a slur to a note sequence?
Comment: What about `\repeat unfold 2 {b( \repeat unfold 2 { es b } es)}`? Is there some reason that won't work for you?
Comment: Works, but this pattern is repeating many times. I'd like to write the notes ONCE, and in the proposed solution it appears twice.
Answer: As long as you remain quite simple something like this could work for you:
<code>enslur =
#(define-music-function (n base count music)
   ((number? 1) (ly:duration? (ly:make-duration 3)) (number? 6) ly:music?)
   #{
     << \repeat unfold #n { s$base ( s$base * $(- count 2) s$base) } #music >>
   #})

\new Voice {
  \time 6/8
  \repeat unfold 2 { \enslur \repeat unfold 3 { c8 d } }
  \enslur 2 \repeat unfold 6 { c8 d }
  \enslur 4 4 3 \repeat unfold 6 { c4 d }
}
</code>
With more complex cases the problem is that slurs generally are started on the first note and ended on the last note, which means that if you want to add a slur you'd need to add the slur end event to the last note, which means having to determine the last note relevant to the slur.
Comment: @pihentagy https://extending-lilypond.gitlab.io/en/index.html
Comment: @pihentagy This is unrelated to `\enslur ...`. You will see the same with `\repeat unfold 3 { g!? fes }`. The reason is that `?` and `!` set the `'force-accidental` property, as you can see here: `\displayMusic { g g? g! g!? }` (`!?` does the same as `?`, as `?` does *more* than `!`). You could do something like `\repeat unfold 3 { \volta 1 g? \volta 2,3 g fes }`. If you define `altFirst = #(define-music-function (n first others) (number? ly:music? ly:music?) #{ \volta 1 #first \volta #(iota (1- n) 2) #others #})` you could also write this as `\repeat unfold 3 { \altFirst 3 g? g fes }`.
Comment: Oh, nice. I am a developer, but when engraving music, I haven't yet tried lisp. Is there a good tutorial to start with?
Comment: Well, sometimes I need to add a `\f` mark to the first note. I guess that would quickly make things very complicated.
Comment: Also adding `\f` on the first note can be done by `<>\f \repeat ...`, adding it on later notes can be done like `\after 8 \f \repeat ...`. Generally this `\enslur` could also be done like `<>( \after 8*5 ) \repeat ...`
Comment: Wait, wait! I think I can learn again from your <> syntax. Could you update your answer with this possibility?
Comment: And what about `\enslur \repeat unfold 3 { g!? fes }`, it marks all `g`s as accidentals.

Slurs and repeats in LilyPond


Bind custom object to TreeView in WPF

Question: I have a object of a class defined below
class XYZ
{
    List<XYZ> child;
    String header;
}

I want to bind this object to a tree view. Initially XYZ root will be the topmost TreeViewItem. root will have the List child as the sub TreeViewItems. This will go on recursively until List of each XYZ object is not empty. Each TreeViewItem is either a node or a leaf (if List child is empty).
I am able to do this programmatically by adding TreeViewItem as a child to parent TreeViewItem.
The number of levels is not known.
I referred this answer Bind Object to WPF TreeView but here it is mentioned for a three level hierachy.
Answer: You just need to define the Hierarchical Datatemplate for your viewmodel and that should take care of the multiple levels in your treeview.
Make sure the collection you are using implements INotificationPropertyChanged
The datatemplate will be in the lines of
<TreeView ItemsSource={Binding child}>
<TreeView.Resources>
<HierarchicalDataTemplate ItemsSource="{Binding child}" DataType="{x:Type vm:XYZ}">
<Grid>
<TextBlock Text="{Binding header}"/>
</Grid>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>

Comment: Why downvote??? The OP asked how to build a dynamic treeview and I provided a Datatemplate for that. Ofcourse he did not provide any code I had to guess his implementation and provide a guide atleast for a solution!

Bind custom object to TreeView in WPF


Finding $B_{2\times 2}$ such that $A^{51}=B$

Question: Assuming  $$ A=\left(\begin{matrix}0 & \sqrt{3}\\\sqrt{3}\ &4\end{matrix}\right)$$ how to find B such that $$A^{51}=B$$
My attempts:
if find $P,D$ that $D$ be diagonal matrix $A=P^{-1} DP$ then $$A^{51}=P^{-1} D^{51}P$$  therefore $B=P^{-1} D^{51}P$ but  how to find $D$ and $P$?
Thanks for any hints.
Comment: Compute the eigenvectors of $A$.
Comment: ...together with the eigenvalues. The eigenvalues constitutes $D$, and eigenvectors...$P$.
Comment: A has real eigen value but let A have complex eigen value then eigen vector correspond to this eigen vector has two part (imaginary and real ) how  find p now ?
Answer: You would find the eigenvalues and eigenvectors for the matrix $A$.
You should get:
$$\lambda_1 = 2 + \sqrt{7}, v_1 = \left(\left(\frac{-2 + \sqrt{7}}{\sqrt{3}}\right), ~1\right)$$
$$\lambda_2 = 2 - \sqrt{7}, v_2 = \left(-\left(\frac{2 + \sqrt{7}}{\sqrt{3}}\right), ~ 1\right)$$
This forms the Jordan Normal Form, with
$$J = P^{-1}DP$$
You have the columns of $D$ as a linear combination of the eigenvalues.
$$D = [ \lambda_1 | \lambda_2]$$
You have the columns of $P$ as a linear combination of the eigenvectors.
$$P = [ v_1 | v_2]$$
And of course, you can easily find $P^{-1}$.
That should help you move forward.
Regards
Comment: Clear proof, Amzoti.
Comment: @BabakSorouh: Thank you, I really like your responses to problems! Regards
Comment: Great work here! +1
Answer: Here's another way.  The generating function of $A^n$ is $$G(t) = \sum_{n=0}^\infty t^n A^n = (I-tA)^{-1} =
\dfrac{1}{-1+4t+3t^2}  \left( \begin {array}{cc} -1+4\,t&-t\sqrt {3}\\ -t
\sqrt {3}&-1\end {array} \right)
$$
Now using a partial fraction decomposition
$$
\eqalign{\frac{1}{-1+4t+3t^2} &={\frac {\sqrt {7}}{14(t+2/3-\sqrt {7}/3)}}-{\frac {\sqrt {7
}}{14(t+2/3+\sqrt {7}/3)}}\cr
&= -\frac{\sqrt{7}}{14} \sum_{n=0}^\infty \frac{t^n}{(-2/3 + \sqrt{7}/3)^{n+1}}
+\frac{\sqrt{7}}{14} \sum_{n=0}^\infty \frac{t^n}{(-2/3 - \sqrt{7}/3)^{n+1}}
}$$
Thus with $\alpha = -2/3 + \sqrt{7}/3$ and $\beta = -2/3 - \sqrt{7}/3$,
the coefficient of $t^{51}$ in $G(t)$ is
$$ \dfrac{\sqrt{7}}{14} \left(\frac{-1}{\alpha^{52}} + \frac{1}{\beta^{52}}\right) \pmatrix{-1 & 0\cr 0 & -1\cr} + \dfrac{\sqrt{7}}{14} \left(\frac{-1}{\alpha^{51}} + \frac{1}{\beta^{51}}\right) \pmatrix{4 & -\sqrt{3}\cr -\sqrt{3} & 0\cr}$$
Answer: What you need is called an Eigendecomposition of the matrix $A$. See for instance http://en.wikipedia.org/wiki/Eigendecomposition_%28matrix%29 or almost any textbook on linear algebra.
Answer: You may proceed as follows: Consider the characteristic polynomial $p_A$ of $A$:
$$
p_A(\lambda)=\det(A-\lambda I)=\lambda(\lambda-4)-3=\lambda^2-4\lambda-3=(\lambda-2-\sqrt{7})(\lambda-2+\sqrt{7})
$$
Next, for $n \ge 3$, we find $a_n, b_n\in \mathbb{R}$ such that
$$
\lambda^n=q(\lambda)p_A(\lambda)+a_n\lambda+b_n.
$$
We have
$$
(2+\sqrt{7})a_n+b_n=(2+\sqrt{7})^n,\ (2-\sqrt{7})a_n+b_n=(2-\sqrt{7})^n,
$$
i.e.
$$
a_n=\frac{(2+\sqrt{7})^n-(2-\sqrt{7})^n}{2\sqrt{7}},\ b_n=3\frac{(2+\sqrt{7})^{n-1}-(2-\sqrt{7})^{n-1}}{2\sqrt{7}}.
$$
Thanks to the Cayley-Hamilton theorem we have
$$
A^n=a_nA+b_nI.
$$
Now just take $n=51$.


Logistic regression in R with large amounts of data

Question: I am currently carrying out an investigation to find if certain factors such as playing home or away or position of a footballer affects overall pass completion using logistic regression. I am using R to compute my data. In my current section in which I am trying to analyse uses the data of every player to convey a general conclusion to whether or not the position of a player affects the successfulness of pass completion.
so far I have computed:
test.logit <- glm( cbind(Total.Successful.Passes.All,Total.Unsuccessful.Passes.All) ~
                   as.factor(Position.Id), data=passes.data, family = "binomial")

summary(test.logit)

and my output was:
Coefficients:
                        Estimate Std. Error z value Pr(>|z|)

(Intercept)              0.28482    0.01256   22.67   <2e-16

as.factor(Position.Id)2  0.99768    0.01438   69.38   <2e-16

as.factor(Position.Id)4  1.06679    0.01398   76.29   <2e-16

as.factor(Position.Id)6  0.68090    0.01652   41.23   <2e-16

Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 32638  on 10269  degrees of freedom
Residual deviance: 26499  on 10266  degrees of freedom

AIC: 60422

Number of Fisher Scoring iterations: 4

the intercept is goalkeepers,position.Id 2 is for a defender, 4 = midfielder and 6 = striker
Is this a good set of results to come to a conclusion? and with the large deviances?
Comment: This doesn't feel like a programming question, but rather one about how to interpret the results of a logistic regression. As such, I think this is off topic for SO. I would suggest consulting a statistics textbook, or even better a statistician.
Answer: Based on

Very small p-values (less than 2e-16)
Large effect size estimations (log-odds ratios ranging from .68 to 1.06)
Small standard errors (around .015)

All evidence indicates there is a significant effect of position on the probability of a successful pass.
Note that the size of the deviance isn't immediately interpretable as "large" or "small" (deviance is affected by the sample size, so there is no such thing as a "large deviance" without context).
Comment: `Position.Id` here is a categorical variable. Therefore, doesn't the estimate and p-values show significance only with relation to the `reference` (which is not shown in the post) (what I mean is that if the factors were re-levelled, you might get different p-values)? Also, how important is the ratio of `residual df` to `residual deviance` in a `logistic regression`? Could you please comment on it? Thank you!
Comment: @Arun: Yes, they do show significance relative only to the reference level. Note that `2` and `4` are therefore very close together (though probably still far apart enough, given those standard deviations, to be statistically significant). The OP should try releveling the factors to check that. The residual deviance and null deviance mostly play into the question of how much of the variance this regressor explains (while there is no equivalent to R^2 in logistic regression, there are some "pseudo-R^2"'s that use these deviances.
Comment: thank you very much for your help, it is much appreciated


Tanh property: mapping outlier values toward the mean : What do we mean by this?

Question: I was reading Jurafsky 3rd edition, page 4 chapter 7

How does it map outlier to a value towards the mean? (This is not clear to me)
Here is the link to the book chapter(freely available from the official author).
Comment: The highlighted comment refers to the fact that $\tanh$ decreases differences: for any numbers $x$ and $y,$ $\tanh(x)$ and $\tanh(y)$ are closer to each other than $x$ and $y$ are.
Answer: Similar to log-transfrom. If you take the log of log-normal distributed data, you will observe tail values shrink towards mean and it becomes normal distrb.. Below the behaviour of Tanh, where straight line represents original data and the other one tanh transformation. You can see edge values shrinked towards 0 which is the mean:


Create a node programmatically on installing a module

Question: I would like to have my module to create new nodes (page) when being installed and removing these pages on uninstall.
I tried the following with no success in my mymodule.install file:
<?php

function mymodule_install() {

  $node = new stdClass(); // We create a new node object
  $node->type = "page"; // Or any other content type you want
  $node->title = "Your title goes jere";
  $node->language = LANGUAGE_NONE; // Or any language code if Locale module is enabled. More on this below *
  $node->uid = 1; // Or any id you wish
  $node->path = array('alias' => 'your_node_path'); // Setting a node path
  node_object_prepare($node); // Set some default values.

  // Let's add standard body field
  $node->body[$node->language][0]['value'] = 'This is a body text';
  $node->body[$node->language][0]['summary'] = 'Here goes a summary';
  $node->body[$node->language][0]['format'] = 'filtered_html'; // If field has a format, you need to define it. Here we define a default filtered_html format for a body field

  $node = node_submit($node); // Prepare node for a submit
  node_save($node); // After this call we'll get a nid

}

This code is cut n' paste from this page.
When I disable/enable the module, the page is not created (at least it does not appear in Content and in the node table of the database).
How should I do it please?
Answer: The problem is that install/uninstall and enable/disable are two separate things in Drupal.
When you enable or disable a module, hook_enable() and hook_disable() are invoked respectively.
When you install or uninstall a module, hook_install() and hook_uninstall() are invoked respectively.
If you want to keep your code in hook_install() / hook_uninstall() you'll need to disable the module, and then uninstall it at http://mysite.com/admin/modules/uninstall. Once you re-install it (which will also enable it), your code will be run.
It might be worth having a think if this code would be better served in hook_enable() / hook_disable(), but it will depend on your particular situation.
Comment: Sorry for my misunderstanding of the API Clive. And thank you for your help, it works beautifully. I will put in hook_disable() some lines to delete the content created in the _enable() function now. Do you have any recommendation or good practice to keep track (in hook_enable()) of the node ID to be deleted (in hook_disable())?
Comment: Note: in Drupal 8 these methods have been consolidated. There is no `hook_enable` or `hook_disable` anymore, just `hook_install` and `hook_uninstall`. See details here: https://www.drupal.org/node/2193013


Is it possible to bound this sum?

Question: Maybe this question is too simple, but I have been thinking about it for several days and I can't find the solution.
Is it possible to show that the there exists a universal constant such that the  sum
$$(N-k)\sum_{n=N-k}^{N-1}\frac{log(n)}{n^2}$$
is bounded for every $k,N\in \mathbb{N}$ with $1\leq k \leq N-1$?
I know that the sum $\sum_{n=1}^{\infty}\frac{log(n)}{n^2}$ converges, so  I am trying to relate the previous question to the question of how fast this series converges but I'm not sure if this is a good idea.
EDIT: Thanks to the answer given by @Conrad it is clear that it is not possible to bound the sum. But is it true for
$$(N-k)\sum_{n=N-k}^{N-1}\frac{1}{n^2}\log\left(\frac{n(N-n)}{N}\right)?$$
Comment: I am trying to prove the existence of a universal constant. I just edited the post
Comment: For $k=N-1$ you'll get the constant $-\zeta'(2)\approx 0.937548254315843753702574$ as $N\to\infty$ but as indicated by Conrad your sum will grow without limit before going back to this value.
Answer: The sum is actually unbounded as one can easily see for $k=N/2$ when $N=2M$ even. Then $$(N-k)\sum_{n=N-k}^{N-1}\frac{log(n)}{n^2}=M\sum_{n=M}^{2M-1}\frac{log(n)}{n^2} \ge \frac{1}{4M}\sum_{n=M}^{2M-1}\log n$$ since $1/n^2 > 1/(2M)^2, n \le 2M-1$. But:
$$\frac{1}{4M}\sum_{n=M}^{2M-1}\log n \ge \frac{\log M}{4}$$ since $\log n \ge \log M, n \ge M$ and there are $M$ terms in the sum.
It actually can be shown that that is the right behavior in the sense that $(N-k)\sum_{n=N-k}^{N-1}\frac{log(n)}{n^2}=O(\log N)$
Comment: After reading your answer I am wondering if the same is true for the series that I have write in the edit. I don't see now how to bound the function as you did with $log(n)\geq log(M)$
Comment: you can do same thing but now with $N=4M$ and the sum between $2M, 3M$ (so for $k=2M$) say so $\frac{n(N-n)}{N} \ge M/2$ and that part of the sum still has $M ~ \sim N$ terms (while the rest of the terms are nonnegative except maybe a few so do not really matter); in general for sums like this look at the terms were $k \sim N$ (and $N-k \sim N$ if you have $N-k$ around)  and those will generally tell you what happens

Is it possible to bound this sum?


Datepicker (Bootstrap) funciona com libs Online mas não com Offline

Question: Desenvolvi uma aplicação que utiliza 3 bibliotecas jquery-1.11.1.min.js, bootstrap.min.js, bootstrap-datepicker.js, esta aplicação funciona usando as bibliotecas adquiridas online (src="htt://") porem quando adiciono a referencia a estas mesmas bibliotecas que possuo no pc o datepicker não funciona (já chequei os diretorios) OBS: são as mesmas versões
codigo html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <link rel="stylesheet" type="text/css" href="../CSS/StyleSheet.css"/>

    <link rel="stylesheet" type="text/css" href="../Bootstrap/css/bootstrap.css" media="screen" />

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />

Create Account

            <form class="form-horizontal">

                        Your Email (login)

                            <input type="email" class="form-control" id="input_email" placeholder="Email">

                        Password

                            <input type="password" class="form-control" id="input_password" placeholder="Password">

                        Birthdate

                            <input type="text" class="form-control" id="input_date">

                        <button type="reset" class="btn btn-danger">Reset</button>
                        <button type="submit" class="btn btn-primary">Create Account</button>

            </form>

Back to Site

Answer: Tens de colocar as bibliotecas javascript: Jquery, bootstrap e datepicker (na mesma ordem) na tag head, e mudar os endereços relativos para o endereço localhost/.../.../jquery (no meu projeto funcionou desta forma)


Check a string exists in the query response c#

Question: I am getting a response from the select query and storing them in to the string list
        string abc = "123";
        List<string> numb = new List<string>();
        string selectQuery = "SELECT Number FROM NumberList;";
        using (MySqlConnection conn = new MySqlConnection(connStr))
        using (MySqlCommand cmd = new MySqlCommand(selectQuery, conn))
        {
            conn.Open();
            var reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                numb.Add(reader.GetString(0));
            }

I am not sure how to check the string abc exists in numb. I dont want to use for loop for this because the count of records returned from query response is high. Is there any easy of checking if the 123 exists in the list or not.
Comment: But why are you doing this at all? `SELECT Number FROM NumberList WHERE Number=123` will give you one record if 123 is in the database, and zero if it's not. Why read everything and then throw it away?
Comment: `if (numb.Contains(reader.GetString(0))
{
    //yes, it contains!
}`
Comment: I need to check if numb contains string abc
Comment: if (numb.Contains(abc))
Answer: This?
if (numb.Contains(abc))
{
   // List contains the string contained in variable abc
}

Answer: while (reader.Read())
{
    var s = reader.GetString(0);
    if (!numb.Contains(s))
    {
        numb.Add(s);
    }
}