Uniqueness of Extended Euclidean Algorithm

Question: I'm doing a bit of extra reading on the Extended Euclidean Algorithm and had a side-thought that I couldn't find an answer to in the book.
I understand that the Extended Euclidean Algorithm can express the GCD of two numbers as a linear combination of those two numbers.
My question is, is the linear combination acquired unique? (My gut is telling me that it not, but I'd like some verification as I cannot produce a proof of uniqueness).
If the answer is 'No', then my follow-up question is "What is so special about the specific linear combination acquired by the EEC?"
Answer: Given two integers $a$ and $b$, the Extended Euclidean algorithm calculates the $\gcd$ and the coefficients $x$ and $y$ of Bézout's identity: $ax+by=\gcd(a,b)$. These coefficients are not unique (see linked article).
The specific coefficients created by the algorithm satisfy these conditions: $$|x|<|\frac{b}{\gcd(a,b)}|$$
$$|y|<|\frac{a}{\gcd(a,b)}|$$
Answer: The Extended Euclidean Algorithm finds the solution closest to the origin.
Comment: See for instance https://www.jstor.org/stable/10.4169/amer.math.monthly.120.06.562
Answer: If there is one solution $(x,y)$ of the linear diophantine equation $ax+by=c$ then  there are infinitely many, given by $(x-\dfrac b{\rm{gcd}(a,b)}t,y+\dfrac a{\rm{gcd}(a,b)}t)$ for any integer $t$.
There will be a solution at all if and only if $c$ is a multiple of the $\text{gcd}$.


AWS: Why do we have to specify 2 BGP ASN when configuring a DX Gateway?

Question: When creating a DX Gateway, we specify a BGP ASN. Another BGP ASN is required when specifying a VIF. Could someone explain why 2 BGP ASNs are required, and what purpose it solves?
Thanks.
Answer: As you already know that BGP session is established between 2 peers, therefore BGP ASN is required for both the peers.
While creating the Direct Connect Gateway (DXGW), you mentions Amazon side BGP ASN, however while you are creating a VIF, you mentions on-premise (customer N/W) BGP ASN.

While creating DXGW, it asks for Amazon side ASN
(The Autonomous System Number for the new Direct Connect gateway.)

While creating VIF, it asks for BGP ASN
(The Border Gateway Protocol Autonomous System Number of your on-premises router for the new virtual interface.)

Hoping that this clears out your query.


how do I return a count of items returned from an entityfieldquery

Question: Is it possible to return a count of the number of items returned in an entityfieldquery query?
Comment: do you want to get the result as well as the count? if you just want the count then you could set the query to count. something like $count = $query->count()->execute();
Comment: I think that should do it. Do you want to add that as an answer?
Comment: I have added as an answer :-)
Answer: if you just want the count then you could set the query to count.
something like
<code>$count = $query->count()->execute()
</code>
See here for more detail
Comment: For Drupal 8: `$query = \Drupal::entityQuery('node')->condition('type', "article");
echo $query->count()->execute() . "\n";`
Answer: If required you might as well try Field Count Formatter
It will display the number of item in a multifield


Determine the storage order of an Eigen3 matrix at compile time

Question: The title basically says everything. Is there some member of Eigen::Matrix that exposes the storage order (column major or row major) at compile time? I know that the Options template parameter is used for specifying the storage order but I have not found a way to extract it afterwards. The usage scenario would be something like
template<class Mat>
class C {
  static_assert(/* Mat has column major format */, "column major required");
  // ...
};

Answer: You can use Mat::IsRowMajor:
static_assert(!Mat::IsRowMajor, "column major required");

This will work for any Eigen's matrix-like type for Mat, like Matrix, Block, Map, Ref, etc.


Requisição Ajax em Formularios

Question: Fiz uma requisição ajax para enviar os dados de um formulário para o servidor, os dados são enviados e armazenados perfeitamente. Porém ao tratar o success
criando a condição, caso o retorno do result fosse o padrão 200 ou "OK" iria emitir uma mensagem de sucesso e se não, a de erro. Porém, ao fazer isso percebi que o result não estava retornando pois já caia direto no else. E mesmo caindo ELSE, ele armazena os dados no servidor, porém lança a mensagem de erro.
function showMessageError(message)
    {
      document.getElementById("errorMsg").innerHTML = message;
      $("#divError").fadeIn(200).delay(2500).fadeOut(200);
    }

>
function sendForm()
{

  $("#divSucesso").hide();
  $("#divError").hide();

  document.getElementById("btnEnviarForm").disabled = true;
  var formAgenda = document.getElementById("form");
  var formData = new FormData (formAgenda);

  $.ajax({
  url: 'insert.php',
  method: "POST",
  data: formData,
  cache: false,
  processData: false,
  contentType: false,

  success: function (result) {

      if (result.statusText == "OK")
      {
        document.getElementById("sucessoMsg").innerHTML = "Dados salvos com sucesso: " + result;
        $("#divSucesso").stop().fadeIn(200).delay(2500).fadeOut(200);
        document.getElementById("btnEnviarForm").disabled = false;
        document.getElementById("form").reset();
      }
      else
        showMessageError(result);
    },
    error: function (xhr, status, error) {
      var errorMsg = xhr.responseText;
      document.getElementById("errorMsg").innerHTML = errorMsg;
      $("#divError").fadeIn(200).delay(2500).fadeOut(300);
      document.getElementById("btnEnviarForm").disabled = false;
    }

  })
}

Comment: Gabriel, poderia passar o erro que está acontecendo? Assim tenho um parâmetro pra investigar.
Comment: @MateusSaggin ai que está cara. Ele não está indicando qual é o erro, estou sem entender.
Comment: @MateusSaggin, meio que ele não está entrando no IF, por isso nao da
Comment: tem algum link rodando esse script?
Comment: @MateusSaggin, reestruturei minha pergunta, talvez fique mais claro um pouco. E te respondendo, estou testando no WAMP localmente.
Comment: Poderia postar o código do insert.php?
Answer: Fala @Gabriel,
Agora entendi a sua pergunta, eu alteraria o código pra tratar o 200 e não o OK. Segue exemplo:
function sendForm() {

    $("#divSucesso").hide();
    $("#divError").hide();

    document.getElementById("btnEnviarForm").disabled = true;
    var formAgenda = document.getElementById("form");
    var formData = new FormData(formAgenda);

    $.ajax({
        url: 'insert.php',
        method: "POST",
        data: formData,
        cache: false,
        processData: false,
        contentType: false,

        success: function(xml, textStatus, xhr) {

            if (xhr.status === '200') {
                document.getElementById("sucessoMsg").innerHTML = "Dados salvos com sucesso: " + textStatus;
                $("#divSucesso").stop().fadeIn(200).delay(2500).fadeOut(200);
                document.getElementById("btnEnviarForm").disabled = false;
                document.getElementById("form").reset();
            } else {
                showMessageError(textStatus);
            }

        },
        error: function(xhr, status, error) {
            var errorMsg = xhr.responseText;
            document.getElementById("errorMsg").innerHTML = errorMsg;
            $("#divError").fadeIn(200).delay(2500).fadeOut(300);
            document.getElementById("btnEnviarForm").disabled = false;
        }

    })
}

Mas caso queira tratar o retorno do seu servidor, é possível também. É só dar um console.log(result), utilizando o código que enviou e verificar se realmente está sendo retornado OK no atributo result.statusText

Requisição Ajax em Formularios


Entity Reference widget selctor in view referring same reference

Question: I searched for a solution but I didn't get it right.
Given my setup:

A content type Service, referring a content type Agency
A content type Agency
A content type Person, referring a content type Agency

Now I need to add an entity reference in Service referring some of the Persons. The list of persons needs to be limited to the persons in the same Agency (of the service).
I'm using an entity reference view to generate the list of the widget.
I tried fetching the list of the person, using contextual filter(nid) and relationship but i didn't manage to make it right.
Therefore I'm asking for help. How should I setup the view?
Thank you all
Comment: I also tried to use the token argument from the entity reference widget, but i wasn't able to filter using the token. How should I add the argument in the views?
Comment: [node:field_reference_name] returns the title, i tried different option but none of them returns the id
Comment: Is this new ER field supposed to work at the time when you're creating the Service node? Before the Service node is saved, you have only chosen the Agency in the node creation form, but it has not been saved anywhere, so it can't be used to filter out the Person CT that only belong to the Agency selected in Service.
Comment: Thanks @prkos, but I'm aware of that. The service nodes are already existing and rarely newly created. The contacts though needs to be updated often.
Comment: OTOMH it doesn't seem you need a Relationship. You only need to create Person Views, with Contextual Filter of ER field (not NID). I haven't tested this case yet, is your Service->Agency field the same field as the one on Person->Agency? Was it created as a new field, or did you "Add existing field"? I think that might matter when configuring the Views. You basically need to create Person Views with a Contextual filter for Agency that when placed on nodes where Agency is in ER, that filter will reduce the list to only those People. If you have that, you can easily create Entity ref Display.
Comment: I was kinda right, right in concept but not in execution, you do need Relationships to create the context, and two of them! I added the Answer explaining the steps for both cases.
Answer: I couldn't test all the way with Entityref Views, I seem to have a bug in choosing Views on my Field settings. But I was able to create the Views and it works as expected in Views preview.
The goal is to create Views of sibling nodes. In your case we need to list Person nodes that are sibling nodes to the Service node you're currently viewing. They are sibling through the Agency Entity reference field (they both refer to the same Agency node).
When both References to Agency are the same field
This is the case when the references to Agency from both Service and Person are the same field, reused (this happens when you create one ref field on one content type, then on the other content type you choose from the second drop-down "Re-use an existing field").

Create Content Views showing Person. You don't need Page nor Block, add Entity reference Display.
Show Fields Title and Agency (to test filtering works as expected, you can remove Agency later)
Under "Entity Reference inline fields" set Separator to from (with spaces on each side) so you get meaningful output Person: Name1 from Agency: Agency1
Add a Relationship Content referenced from field_agency, you can require it. This is the Agency a Person listed in Views is referring to.
Add another Relationship Content using field_agency, set it to use the Relationship from the previous step, you can require it. This is the reverse direction, pointing to all content that is pointing to this Agency.
Add a Contextual Filter ID from Content Category and set it to use the second relationship (field_agency) and configure:
When the filter value is NOT available
Provide default value
Content ID from URL
When the filter value IS available or a default is provided
Specify validation criteria
Service
Configure Entity ref field settings to use this View, and choose the widget on "Manage form display".

That's it! You can test Views through Preview by entering one of the Service NIDs. Don't forget to add some "No results" text.
The Views will list only Person that are in Agency that this Service is referring to.
When References to Agency are NOT the same field
This case is when you created two different Entity reference fields on Service and Person (they have different machine names). Configuration is a bit different even though they refer to the same Agency.
You create Views the same as above only with these differences:

The first Relationship needs to be of the Entity reference to Agency that is on the Person CT.
The second Relationship needs to be of the Entity reference to Agency that is on the Service CT.
Again this second Relationship must use the Relationship from the previous step. This is where the magic happens, where Service and Person Agency fields are compared.

The Contextual ID Filter needs to be using the second Relationship, as in the first case. This Contextual is only passing on the Service ID of the page you're on to Views.
Answer: After lot of tries, I gave up and use custom code, which took me 15 mins. That's how I did it:
function custom_dataset_views_pre_view ( &$view, &$display_id, &$args) {
  if ($display_id === 'entityreference_1') {
    // Get the node
    $url = arg();
    if ($url[1]) {
      $node = node_load($url[1]);
      $agency_id = $node->field_theme_working_group['und'][0]['target_id'];
      // Get the views filter
      $filters = $view->display_handler->get_option('filters');
      if ($filters['field_agency_target_id']) {
        // Change the filter
        $filters['field_agency_target_id']['value']['value'] = $agency_id;
        // Push the filter back
        $view->display_handler->override_option('filters', $filters);
      }
    }
  }
}

Less elegant, but finally working. Despite that, I still would like to know how to achieve this in plain views, or using tokens.


Too many recursions at a time

Question: I want to create a program that determines whether or not it is possible to construct a particular
total using a specific number of coins using recursion.
For example, it is possible to have a total of $1.00 using four coins if they are all quarters. However, there is no way to have a
total of $1.00 using 5 coins. Yet it is possible to have $1.00 using 6 coins by using
3 quarters, 2 dimes and a nickel. Similarly, a total of $1.25 can be formed using 5
coins or 8 coins, but a total of $1.25 can not be formed using 4, 6 or 7 coins. It should display a clear message indicating whether or not the entered dollar
amount can be formed using the number of coins indicated
def possiblechange(total, coins):
    penny = .01
    nickel = .05
    dime = .1
    quarter = .25
    if coins * penny == total:
        return True
    elif nickel * coins == total:
        return True
    elif dime * coins == total:
        return True
    elif quarter * coins == total:
        return True
    else:
        return (
            penny*possiblechange(total, coins) or
            nickel*possiblechange(total, coins) or
            dime*possiblechange(total, coins) or
            quarter*possiblechange(total, coins)
        )
print(possiblechange(1.0, 3))

I get a traceback on this.
Comment: It still multiplies numbers and booleans. What is `penny * possiblechange(...)` supposed to mean? And the function is called recursively with the same arguments again, this leads to infinite recursion.
Comment: I don't understand why the function returns a boolean in the base cases but a number in the recursive case.
Comment: I just fixed it
Answer: You've got a few issues.
The big one is that your code recurses with the exact same arguments every time. That means that if the initial call is not handled by one of your base cases, you'll recurse forever. You need to be modifying the arguments to the recursive calls, so they're doing something different than you're doing in the current call.
Actually, your recursive case don't make any sense at all. Your function is supposed to return True or False, but you're doing math on a bunch of dollar values instead there.
I think you want something like this for your recursive case:
return (
    possiblechange(total-penny, coins-1) or
    possiblechange(total-nickel, coins-1) or
    possiblechange(total-dime, coins-1) or
    possiblechange(total-quarter, coins-1)
)

The next issue is that you don't have any base case to handle failure. If you can't find a working set of change, you need to return False. I'd suggest:
if total < 0 or coins == 0:
    return False

The final issue is a subtle one. You're doing your mathematics with floating point numbers, which may not work exactly. You should probably work in cents, instead of fractions of a dollar, so that every denomination can be exactly represented.
Answer: You have to subtract the total and coins from each recursive call. Also what is the point in multiplying the value of the coin by the boolean result? For example, instead of quarter*possiblechange(total, coins) do  possiblechange(total - querter, coins - 1) .
Answer: The python recursion limit is set to 1000. However, if your computer has enough resources, you can increase this limit by putting this code in the very first line:
import sys
sys.setrecursionlimit([NUMBER OF RECURSIONS])

Replace [NUMBER OF RECURSIONS] with the number of recursions you need.
IMPORTANT: Your function does return booleans AND numbers. Please mind that Python treats booleans as numbers in operations: True means 1 and False 0. This might be the problem directing your function in way more recursions than needed.
Comment: Increasing the recursion limit doesn't help when the code recurses infinitely.

Too many recursions at a time


How to change the e-mail output of a Entity type field in a webform

Question: I have a content type Agenda. In this content type I can create paragaphs of the type Date. This paragraph has a field date and a field location.
Now people can attend to agenda items by submitting a webform (using the webform module).
In this webform use a Entity type field together with views to make a reference to date paragraphs. This reference works perfectly and creates a select with options showing the name of the name together with date and location. But in the e-mail confirmation I don't see the paragraph fields. Only the name of the node. I want to be able to manage how the output looks in the email confirmations.
At the moment I use [webform_submission:values:agenda] to get the value from the submission.
The way it looks now is:
Node:title > Content type [NID]  But I want to be able to see something like:
Node:title | Paragraph:Date | Paragraph Location
How or where can I change this output?
Answer: Because I was in quite a hurry, I ended up creating hidden fields in my form for date and location. Using javascript I fetch the information from the Select field and add them to these hidden field. This way this information is send with the submission.
Not the prettiest way to do it but it works.


could not instantiate RegionFactory [org.hibernate.cache.ehcache.EhCacheRegionFactory]

Question: My Domain Class is as below. Primary key Id is combination of 2 fields serviceProviderId and sportsId (which are present in another table serviceProvider and Sports respectively). When I start my grails app, i get the below exception
org.hibernate.MappingException: Repeated column in mapping for entity: com.zonalde.FieldsDetails column: service_provider_id (should be mapped with insert="false" update="false")
What am I probably missing here. I already had tables in place and generated domain classes using Database Reverse Engineering Plugin
Please help
class FieldsDetails implements Serializable {

    Integer serviceProviderId
    Integer sportsId
    String isPaynPlay
    Boolean isActive
    Sports sports
    ServiceProvider serviceProvider

    int hashCode() {
        def builder = new HashCodeBuilder()
        builder.append serviceProviderId
        builder.append sportsId
        builder.toHashCode()
    }

    boolean equals(other) {
        if (other == null) return false
        def builder = new EqualsBuilder()
        builder.append serviceProviderId, other.serviceProviderId
        builder.append sportsId, other.sportsId
        builder.isEquals()
    }

    static belongsTo = [ServiceProvider, Sports]

    static mapping = {
        id composite: ["serviceProviderId", "sportsId"]
        version false

    }

    static constraints = {

        isPaynPlay nullable: true, maxSize: 1
        isActive nullable: true

    }
}

Answer: You need to update your mappings as :
static mapping = {
        id composite: ["serviceProviderId", "sportsId"]
        version false
        serviceProvider column: '`service_provider_id`', insertable: false, updateable: false
        sports column: '`sports_id`', insertable: false, updateable: false
    }

You can refer grails doc for more details here
Comment: Thanks @Rahul, but after your change i got the below error will starting the grails app
Comment: @SandeepPoonia i have the updated the code and error in the question description. Now it fails with a different error
Comment: Difficult to determine the exact issue from one liner. Can you add more description i.e Exception logs
Comment: @VinodJayachandran What's the new error that you are getting?


Can a countable dense subset be split into two disjoint dense subsets?

Question: Suppose $X$ is a compact connected Hausdorff space and $D \subset X$ countable and dense. Can we always write $D=D_1 \cup D_2$ as a disjoint union of countable dense subsets? More generally if $U \subset X$ is open and $D \subset U$ is countable and dense does there exist a decomposition $D=D_1 \cup D_2$ with each $D_1 \cap U$ and $D_2 \cap U$ dense in $U$?
The result is easy to show if $X$ has a countable basis $U_1,U_2,\ldots$.
We just use how each $U_n \cap D$ is infinite to assign distinct elements of each $U_n$ to each of $D_1$ and $D_2$ and proceed by induction.
$X$ being connected, or at least perfect, cannot be dropped. For if $x \in D$ is isolated any dense set includes it, and $x$ must be an element of exactly one of $D_1,D_2$. So I wouldn't be surprised if the result fails for $U$ but holds for $X$.
Comment: If $D$ is dense in $X$ and $U$ is open in $X$ then $\overline U=\overline {U\cap D}$ so $U\cap D$ is dense in $U$. So if $D=D_1\cup D_2$ where $D_1$ and $D_2$ are dense in $X$ then  $U\cap D_1$ and $U\cap D_2$ are dense in $U.$
Comment: If it is true then it holds for any separable connected locally-compact  Tychonoff space $U$ because  if $U$ is not already compact then $U$ has a 1-point compactification $X=U\cup \{p\}.$  I still don't have an answer.
Comment: This has been asked answered and accepted at https://mathoverflow.net/questions/298069/can-every-dense-subset-be-partitioned-into-two-dense-subsets/298110#298110
Answer: Below is Ashutosh's answer from MathOverflow:

Here are some details following [1].
Claim: There is a countable dense $X \subseteq [0, 1]^{\mathfrak{c}}$ which does not have a dense co-dense subset.
Proof: Follows from (1) + (2) below.
(1) Every countable dense subspace of $2^{\mathfrak{c}}$ is homeomorphic to a countable dense subspace of $[0, 1]^{\mathfrak{c}}$.
Proof of (1): Use the fact that for every countable dense $D \subseteq 2^{\omega}$, $2^{\omega} \setminus D$ is homeomorphic to the Baire space $([0, 1] \setminus \mathbb{Q})^{\omega}$.
(2) $2^{\mathfrak{c}}$ has a countable dense subspace $X$ which has no dense codense subset.
Proof of (2): (Alas et al. [1]) Let $\{A_i : i < \mathfrak{c}\}$ list all infinite coinfinite subsets of $\omega$. Inductively, try to construct $X_i = \{x_{i, n}: n < \omega\} \subseteq 2^{\mathfrak{c} +i}$ for $i < \mathfrak{c}$ such that the following hold.
(a) $X_i$ is dense in $2^{\mathfrak{c}+i}$.
(b) If $i < j$, then $x_{j, n} \upharpoonright (\mathfrak{c} + i) = x_{i, n}$.
(c) If $\{x_{i, n}: n \in A_i\}$ is dense codense in $X_i$, then $\{x_{i+1, n}: n \in A_i\}$ is open in $X_{i+1}$.
There is no problem at stages $i = 0$, limit.
At stage $i + 1$: If $X_i$ has no dense codense subset, we terminate the construction and put $X = X_i$ - So $X \subseteq 2^{\mathfrak{c} + i} \cong 2^{\mathfrak{c}}$ and we are done. Otherwise, choose an infinite cofinite $A \subseteq \omega$ such that
(i) $\{x_{i, n}: n \in A\}$ is dense codense in $X_i$ and
(ii) if $\{x_{i, n}: n \in A_i\}$ is dense codense in $X_i$, then $A = A_i$
and define $x_{i+1, n} = x_{i, n} \cup \{(i, 1)\}$ if $n \in A$ and $x_{i+1, n} = x_{i, n} \cup \{(i, 0)\}$ if $n \notin A$. As noted above we can assume that the construction can be carried out at every $i < \mathfrak{c}$ and we set $X = \{\bigcup_{i < \mathfrak{c}} x_{i, n} : n < \omega\}$. It is easily checked that $X$ is dense in $2^{\mathfrak{c} + \mathfrak{c}} \cong 2^{\mathfrak{c}}$ and has no dense codense subset.
[1]: Alas et al., Irresolvable and submaximal spaces: Homogeneity versus σ-discreteness and new ZFC examples, Topology and its Applications, Volume 107, Issue 3, 4 November 2000, Pages 259-273
Comment: I think you should accept this answer to move this question off the "unanswered" list.


Debug with release(my own) keystore

Question: I am using titanium.
Normally, I compile like this and check the debug log in console.

ti build --T device --P android

It doesn't require any keystore (maybe titanium default keystore for debugging is used??)
However, I would like to use my own keystore file because google map requires original keystore file to show the map.
How can I debug with release keystore???
Answer: You can run
<code>ti build --help
</code>
and see the options.   Use -K or --keystore to specify the keystore.
That being said, you can run keytool against the default developer keystore and register it will Google api and list it in you tiapp.xml.
Comment: Thank you very much , it works perfectly. I tried only ti --help, I should have tried ti build --help.

Debug with release(my own) keystore


What is an effective way to tune a guitar for an unpracticed ear?

Question: I played viola for 6-7 years and always had this problem to a degree where plucking or playing a string made me feel the pitch was wobbling in a range. I assumed I just don't have a precise ear, but was just fine tuning using 5ths, i.e. playing two strings and listening for them to match against each other.
For guitar, sometimes I tune string by string, but then the relative pitches don't sound right sometimes. Sometimes I tune relative by playing the 5th (or 4th) fret of the lower string to match, but then I wonder if the precision drifts as I go from low E to high E. Sometimes I outright use a tuner with the gauge, but as much as the device reads correctly, I swear sometimes they just don't feel precise. (It's been a while since I tried the tuner so maybe I imagined it.)
For an unpracticed, or maybe just off-pitch, ear like mine, is it better to tune string by string against each pitch (play E, tune E, then play A, tune A, then play D etc), or better to tune one string then match relatively by playing the 4th or 5th fret of the lower string, or use a tuner? I've been tuning relatively simply because I prefer the strings sound good against each other than trying to tune each to a perfect pitch.
Comment: @MichaelMcGriff: Yes, tuning apps are great, some like pitch lab or so have various good visual representations that can help a lot, but you need t be aware of that your phone can be a very bad frequency counter. E.g. my sgs3 shows 440HZ as 439.2Hz. So before using such an app I would recommend to check it against a known well tuned instrument.
Comment: I use a tuning app on my phone, works pretty well.  Another easy way for me to check is tune via the octaves across different strings.
Answer: Since you are a beginner, I would strongly suggest you start with an electronic tuner. Take one and tune you guitar and then see how it's supposed to sound when it's tuned correctly. Play the natural harmonics over the 5th and the 7th frets and listen to the correct sound. Or, you can try playing the 5th fret and the open string below (these are supposed to be the same note); or, you can try playing the 7th fret and the open string above (these are supposed to be the same note, an octave apart).
Then, when it's out of tune, play one of the ways mentioned above again and try to see if you can match the correct ones. If not, use a tuner again and do the same process again.
When you tune just by ear, still use a tuner afterwards to check if the tuning is correct. This way you'll know for sure if you have it correct or not.
But, I remember when I was a beginner, I couldn't tune the guitar just by ear. I needed some help. Use the technology. You can even find tuners online.
Comment: When I was a beginner, I forced myself to tune by ear (using a tuning fork!) because I thought using a tuner would be not as accurate nor as educational. When I started getting into bands and getting paying gigs, I learned that have an accurate, automatic, chromatic tuner is key to tuning quickly and accurately, especially in noisy environments. I still think tuning by ear is educational, but my first lesson with any student always included how to use an electronic tuner.
Comment: @Tetsujin correct. I added two more ways that could work
Comment: I wholeheartedly agree with Shevliaskovic. Definitely tune with a tuner. Surely it's great to be able to tune your instrument by ear, but a tuner will certainly make your life a lot easier, and should make your tuning a lot more accurate.
Comment: @ToddWilcox tuning by ear is really useful, I agree;  but I think starting off with a tuner is much easier
Comment: I agree with everything except the harmonics. That's bound to fail, especially with a beginner, as they won't know to compensate for the drift. Maths - http://www.schrof.net/guitar/articles/harmonics.html
Comment: For a beginner, it's possible (I've seen it happen) for a string to be inadvertently tuned an octave out. If the tuner says it's right...
Answer: It can depend on a couple of factors; amongst them, how good your ear is & how accurately the guitar is set up.
The method that removes the most drift would be to tune each string to a played note on a piano or against a tuner. That way any inaccuracy would not be exacerbated as you move down the strings.
If you tune by fretting one string & comparing it to the next open string, there is the chance that
1) the guitar is inaccurate enough or
2) your precision in making each comparison is sufficient
 that by the time you reach the last string, even the octave Es no longer match up.
Sometimes you can correct for that using a second pass, but not necessarily.
For some reason, people find the B - G hardest to do that way. If you've drifted by the time you reach the bottom, correct the bottom E to the top E, then work your way back up the strings. See if you went out at the G on the way down.
Whatever you do, don't fall for the 'trick' of comparing harmonics at 5th & 7th frets - mathematically, that can never work.
I've found over the years that a good way in the long-term of being able to do it is simply playing each string one at a time, from top E to bottom E.
Do it before & after it's in tune & feel the difference.
Eventually you can actually tune it just by doing that, string at a time from top to bottom, as a 'set' - you learn how those specific pitches sound compared to a 'normal' which lives inside your head. You don't need perfect pitch to do that either.
Mechanically, check the intonation is good at least to the 12th fret, and that the action is not so high you're pushing the strings out of tune by merely fretting on the lower part of the neck. Once the guitar is actually in tune, all simple open chords ought to sound good, not just some.
Remember the guitar is a pseudo-even-tempered instrument. It has idiosyncrasies you won't find on either piano or unfretted stringed instruments.
Oh… one more thing…
Dirty old strings will never be in tune up the fretboard.
Comment: 5-7 works wonderfully. And it's very quick. But I'm with you re stage tuning - electronics are fast and can work in a loud environment
Comment: It wasn't me!! However, I've used 5/7 harmonics for 35+yrs, on gtr and bass, and it's by far the best way for me. On well intonated instruments.
Comment: Then you must have got used to how to compensate for the drift, because mathematically it doesn't work & any beginner would be listening for the beating between the 2 notes & naturally tuning til that stopped. tbh, I have been happiest since I just learned what all 6 strings ought to sound like… can't do it on stage, I need a tuner, but if it's reasonably quiet
Comment: It was also used by Segovia - that's the first time I saw it, in the '60s. Wondered what he was doing ! But, yes, on stage an electronic tuner is the best way to go - especially to check in the middle of a song!
Answer: I always use the reference string method if I don't have any other tuning reference to hand.
Using the 4th/D string as your reference string you can make the following comparisons:
6th/E string 10th fret = D string open
5th/A string 5th fret = D string open
3rd/G string = D string 5th fret
2nd/B string = D string 9th fret
1st/E string = D string 2nd fret + 1 octave = 6th/E string + 2 octaves
The advantage of this method is that it avoids the cumulative error that can occur when tuning each string against the previous one.
Answer: If you're used to tuning a viola, you'll be used to the sound of bowed strings, a sound with perfectly pitched overtones (i.e. if you play a note with basic pitch 440Hz, you'll hear 440, 880, 1320, 1760, 2200...). Plucked strings, like a guitar or piano (or pizzicato violin playing) create overtones which are not precise multiples of the base frequency, the imperfections being the result of string thickness and stiffness. This makes it more difficult to tune a plucked string instrument by ear, and has led to things like "stretch tuning" for piano's. See e.g. https://en.wikipedia.org/wiki/Stretched_tuning
Comment: Thanks for that interesting observation - that **bowed** violins don't have inharmonicity.  I learned something new today.
Answer: the question: "For an unpracticed, or maybe just off-pitch, ear like mine, is it better to tune string by string against each pitch (play E, tune E, then play A, tune A, then play D etc), or better to tune one string then match relatively by playing the 4th or 5th fret of the lower string, or use a tuner?... (I've been tuning relatively simply because I prefer the strings sound good against each other than trying to tune each to a perfect pitch)."
answer: In 12-tone Equal Temperament (which is what a fretted-guitar uses), only the octave and unison intervals are truly perfect.  Trying to tune using any other interval would not likely be a good idea.  If the intonation set-up of the guitar is good (it can never be perfect, partly due to 12-TET https://en.wikipedia.org/wiki/Equal_temperament), using one string's pitch as reference, tune each of the other strings, by fretting appropriately to produce a unison or octave interval to that reference string's pitch (octave harmonics may be used).
What I've done, for standard tuning, is use an A tuning fork to tune the A (5th) string (the fork I have is an octave higher A at 220hz). I tune the other strings relative to that open A string, variously fretting those strings to produce an A note.
"Sometimes I outright use a tuner with the gauge, but as much as the device reads correctly, I swear sometimes they just don't feel precise."
That statement is unclear (what is not 'feeling precise', the tuner or the resultant tuning of the guitar using the tuner?).
I'm wondering if what you are sensing (hearing) is the imperfection of some intervals due to 12-TET ?   Because you mention viola (which is fretless, and can be played in Just Intonation) and state: "...but was just fine tuning using 5ths, i.e. playing two strings and listening for them to match against each other...", it seems that you might have been tuning the adjacent pairs of strings in sequence, and not relative to a single reference.
Answer: Your first step in tuning a string to a reference by ear is to determine where the strings are in relation to each other. Do you need to tune it up or down?
You have to train your ear to recognize which tone is higher and which is lower. That's fairly easy - it might take you a few weeks or months if you practice a few hours a day. Just remember that you aren't a prisoner to the tuning keys. Try bending the reference string up and seeing if the resulting interval sounds more "in tune". Or try playing the reference string a fret (or two) below or above and seeing if that sounds more "in tune". If you play the E string on the 7th fret and it sounds perfectly in tune with your A string, then your A string is (possibly... but possibly not) tuned a whole note too high.
One issue is that sounding "in tune" doesn't necessarily mean "same note." An octave will sound very good. So will a 5th and a 4th. Even a 3rd might fool you. But unison will sound best. And if you mistakenly tune your 5th string to something other than an A (a C or an F, for example), then you'll know when you try to play a 5th between them. Play the open E string and B on the 5th string (2nd fret) and you should have a perfect 5th, which should sound very consonant ("in tune"). But if you tuned the A string to a C you'll have E-D (minor 7th), which is dissonant and "bluesy." It also would match the 4th string exactly, if that string was still tuned correctly.
Once you finally get the two notes close, then you have to break out your auditory microscope. Eventually, you might be able to hear the difference between two very close notes. But first, you'll probably just hear the "wobbliness" between them. When two notes are exactly the same, they sound like a single string when you play them together. If they're slightly off, you'll here an overtone (actually an interference pattern between the two notes) that sounds like a wavering note, rising and falling gradually or quickly. At this point, you make very slight adjustments to the tuning key. You might even just grip it, without even noticeably moving it, and cause a change in that interference pattern. You tweak it until the interference pattern disappears, or until you decide you've had enough and this is close enough.
Again, here you can definitely try a slight bend on the reference string to see how that affects the interference pattern.
Continue the process for all strings.
To hear the interference pattern more clearly, you can try harmonics. I'm sure there are youtube videos on how to get them out of your guitar. You play them right over the frets, not between frets, by lightly touching the string, not pressing down, when you pluck it. The 12th fret is easiest to get a harmonic out of. 7th isn't too hard either. 5th is a bit harder. You can compare most strings using 5th fret harmonic on the lower string, 7th on the higher.
Finally, try comparing you low E's 12th fret harmonic with your high E, to close the loop.


SSH issue with GCE VM Instance

Question: I've been trying to solve this for a few days without luck and similar questions/answers on this site don't solve the problem.
I have 3 different VM Instances on GCE and everything works fine on two of them.
With the third I have lost all access to SSH in through both the terminal built into console and also directly via Terminal on Mac.
I have created new key pairs and added the public key to the meta and ssh key section after clicking edit on the VM instance.
I keep getting the "Permission denied (publickey)" error. Port 22 is fine, IP is whitelisted, and I've generated multiple replacement SSH key pairs to try and fix this. Nothing works. I cannot SSH in and my SFTP client doesn't connect with the new keys (even though I have absolutely no problem with other instances to ssh or sftp).
There are multiple ssh keys in the .ssh folder but I don't think that's the issue because the other keys continue to work with different VM instances. It seems like something on the server that is watching for the keys is corrupt or the cache is stuck and it needs flushing. If this is the case any help knowing which file and what to do would really help. Also how do I even edit these files if I cannot get in there with ssh?
Below is the result of -v:
<code>Bobcomp:.ssh Bob$ sudo ssh -v [SERVER USER]@[SERVER IP]
OpenSSH_7.9p1, LibreSSL 2.7.3
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 48: Applying options for *
debug1: Connecting to [SERVER IP] [[SERVER IP]] port 22.
debug1: Connection established.
debug1: identity file /var/root/.ssh/id_rsa type -1
debug1: identity file /var/root/.ssh/id_rsa-cert type -1
debug1: identity file /var/root/.ssh/id_dsa type -1
debug1: identity file /var/root/.ssh/id_dsa-cert type -1
debug1: identity file /var/root/.ssh/id_ecdsa type -1
debug1: identity file /var/root/.ssh/id_ecdsa-cert type -1
debug1: identity file /var/root/.ssh/id_ed25519 type -1
debug1: identity file /var/root/.ssh/id_ed25519-cert type -1
debug1: identity file /var/root/.ssh/id_xmss type -1
debug1: identity file /var/root/.ssh/id_xmss-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.9
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.4p1 Debian-10+deb9u6
debug1: match: OpenSSH_7.4p1 Debian-10+deb9u6 pat OpenSSH_7.0*,OpenSSH_7.1*,OpenSSH_7.2*,OpenSSH_7.3*,OpenSSH_7.4*,OpenSSH_7.5*,OpenSSH_7.6*,OpenSSH_7.7* compat 0x04000002
debug1: Authenticating to [SERVER IP]:22 as '[SERVER USER]'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: firstname.lastname@example.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: email@example.com MAC: <implicit> compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:LOMx9T+sBw/LBUQvhsbaou5H4AwAMbUcnSWYzP0yKv0
debug1: Host '[SERVER IP]' is known and matches the ECDSA host key.
debug1: Found key in /var/root/.ssh/known_hosts:1
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: rekey after 134217728 blocks
debug1: Will attempt key: /var/root/.ssh/id_rsa
debug1: Will attempt key: /var/root/.ssh/id_dsa
debug1: Will attempt key: /var/root/.ssh/id_ecdsa
debug1: Will attempt key: /var/root/.ssh/id_ed25519
debug1: Will attempt key: /var/root/.ssh/id_xmss
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<ssh-ed25519,ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521>
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Trying private key: /var/root/.ssh/id_rsa
debug1: Trying private key: /var/root/.ssh/id_dsa
debug1: Trying private key: /var/root/.ssh/id_ecdsa
debug1: Trying private key: /var/root/.ssh/id_ed25519
debug1: Trying private key: /var/root/.ssh/id_xmss
debug1: No more authentication methods to try.
[SERVER USER]@[SERVER IP]: Permission denied (publickey).
</code>
Any help appreciated.
Answer: You need to specify the path of the private key when you run the SSH command:
ssh -i [PATH_TO_PRIVATE_KEY] [USERNAME]@[EXTERNAL_IP_ADDRESS]
Here is how to locate the key [1].
For more information on how to troubleshoot this kind of issues [2].
__
[1] https://cloud.google.com/compute/docs/instances/adding-removing-ssh-keys#locatesshkeys
[2] https://cloud.google.com/compute/docs/instances/connecting-advanced
Comment: Hi Alan, Thanks for the reply. I do reference the the path to private key as you stated when I usually connect but still get the "permission denied (public key)" error. I'm on with second level tech at Google trying to solve this. It seems as though the user I'm using is somehow corrupt or the wrong settings for the user are cached somewhere.
Comment: If the problem is the user , you can enable OS Login in order to access to the instance [1]
___

[1] https://cloud.google.com/compute/docs/instances/managing-instance-access

SSH issue with GCE VM Instance


Does a Gaussian mixture model always imply a within-class multivariate normal probability distribution?

Question: If I use a latent profile analysis (Gaussian Mixture Model) to model my observed multivariate probability distribution as a mixture (K-classes) of conditionally-independent normal pdfs, does this model imply that each within-class multivariate pdf is multivariate normal?
Can you show my why, or why not, this is true?
If it is true, can tests for multivariate normallity be used to help evaluate the model?
Answer: Except in degenerate cases, it won't be multivariate Normal. The easiest way to see that is in the $\mathbb R^2$ case. The probability density function of a GMM is a sum over Normal densities $p(x) = \sum_i \pi_i \cdot \mathcal N(x|\mu_i,\Sigma_i)$. Since a multivariate Normal distribution is unimodal with its only a single maximum at the mean, the mixture should also be unimodal. However, if $\mu_i\not=\mu_j$ and $\pi_i\not=0$, you get several "bumps" since there is a Gaussian sitting on each mean $\mu_i$. Therefore, the distribution you can't be multivariate Normal.
Comment: Hmm, I try to guess what you mean. The sampling model for a mixture of Normals would be: randomly draw a normal distribution from the $K$ you got according to $\pi_1, ...,\pi_K$. Then draw a sample from that Normal distribution. This means that conditioned on the component your data point is multivariate Normal.
Comment: You are right, but I don't think I've put my question well. What about the within class pdf when each estimated normal describes a different random variable? Will this imply a mvnorm?
Comment: @DLDahly It's not clear what you're asking, but in any case, could you clarify in your actual question?


Invalid Cursor when Passing RefCursor to a function

Question: I am trying to execute a function that receives a REFCURSOR and performs some data manipulation.
To test my function I have this SQL/PLUS code:
var some_cursor REFCURSOR;

exec :some_cursor := SCHEMA.test_getcursor;

print some_cursor;

variable res varchar2;

exec :res := SCHEMA.second_function(:some_cursor, 'Other_parameter');

print res;

Now, the first test_getcursor function is a simple function that OPENS the cursor, performs a select query and returns the cursor. It works just fine and it prints some_cursor just fine too.
The problem happens when I call the second_function and pass the refcursor to it.
Function has the following code:
type cursor_row
IS RECORD
(field_1 some_field1%type,
 field_2 some_field2%type,
 field_3 some_field3%type);

 new_row cursor_row;

BEGIN
LOOP
fetch PASSED_IN_REFCURSOR INTO new_row --this is where the function fails
...data manipulation...
EXIT WHEN PASSED_IN_REFCURSOR%NOTFOUND;
END LOOP;
CLOSE PASSED_IN_REFCURSOR;
END;

The error I am getting is Invalid Cursor.
I am sure that the type I created has the same number of rows and the same data types as the ref cursor.
What am I doing wrong in this case? I am using Oracle 10g, PL/SQL 10.2
Answer: this is your problem:
print some_cursor;

remove it. by printing the cursor, you've fetched all the records and closed it. so the second function can not read it anymore.
eg;
SQL> create procedure two(p_rc sys_refcursor)
  2  is
  3    v_col varchar2(1);
  4  begin
  5    loop
  6      fetch p_rc into v_col;
  7      exit when p_rc%notfound;
  8      dbms_output.put_line(v_col);
  9    end loop;
 10  end;
 11  /

Procedure created.

SQL> set serverout on
SQL> var rc refcursor;
SQL> exec :rc := one;

PL/SQL procedure successfully completed.

SQL> exec two(:rc);
X

PL/SQL procedure successfully completed.

vs
SQL> var rc refcursor;
SQL> exec :rc := one;

PL/SQL procedure successfully completed.

SQL> print rc

D
-
X

SQL> exec two(:rc);
BEGIN two(:rc); END;

*
ERROR at line 1:
ORA-01001: invalid cursor
ORA-06512: at "TEST.TWO", line 6
ORA-06512: at line 1

which bombs out on the fetch as the cursor wasn't open. You should check %isopen first and raise a defined error if you wanted to give a more useful error back.
Comment: is there any difference between using a function and a stored procedure? It looks like when I use a function and do the same, it comes back saying `Error report: Cursor is closed`


IF Generator Expression with Option as parameter

Question: I have a script (CMake 3.12) which looks a bit like this (superfluous stuff removed):
option(XXH_D_FNF "" OFF)
...
target_compile_definitions(xxh PRIVATE $<IF:XXH_D_FNF, XXH_FORCE_NATIVE_FORMAT, > XXH_FORCE_MEMORY_ACCESS=${XXH_D_FMA})

with the intention being that the preprocessor definition XXH_FORCE_NATIVE_FORMAT be added to the target_compile_defintions iff the associated option is set to ON, otherwise remained undefined. However, this gives me the error:
First parameter to $<IF> must resolve to exactly one '0' or '1' value.

Which isn't fixed by wrapping XXH_D_FNF in a ${}. How do I use this option's value as the condition in this expression?
Comment: Anything wrong with `if (XXH_D_FNF) target_compile_definitions(xxh PRIVATE XXH_FORCE_NATIVE_FORMAT)` which is more readable, maintanable, etc? why would you use generator expression for this?
Comment: So anything wrong with `target_compile_definitions(xxh PRIVATE XXH_FORCE_MEMORY_ACCESS=${XXH_D_FMA})` `if (XXH_D_FNF)` `target_compile_definitions(xxh PRIVATE XXH_FORCE_NATIVE_FORMAT)`?
Comment: I have a few more definitions, some of which require values setting, I'll update the OP
Comment: Ah I didn't realise calls to `target_compile_definitions` were cumulative, that should do
Answer: The documentation for conditional generator expressions (which includes those using IF) says:
$<IF:condition,true_string,false_string>

Evaluates to true_string if condition is 1. Otherwise evaluates to false_string.
  Typically, the condition is a boolean generator expression.

So, your condition itself must be a boolean generator expression. So if we wrap XXH_D_FNF in a boolean generator expression, we would use $<BOOL:${XXH_D_FNF}>. This would evaluate to false when the option is OFF, otherwise it would be true.
Hence, your full call to target_compile_definitions would look something like this:
target_compile_definitions(xxh PRIVATE $<IF:$<BOOL:${XXH_D_FNF}>, XXH_FORCE_NATIVE_FORMAT, > XXH_FORCE_MEMORY_ACCESS=${XXH_D_FMA})

Answer: There is no reason to use generator expressions here. target_compile_definitions and all similar interfaces are cumulative. Just:
target_compile_definitions(xxh PRIVATE XXH_FORCE_MEMORY_ACCESS=${XXH_D_FMA})
if (XXH_D_FNF)
   target_compile_definitions(xxh PRIVATE XXH_FORCE_NATIVE_FORMAT)
endif()


Powershell validation of read-host data entry in while loop with nonewline

Question: I have a function which inserts a Y or N menu when called within my Powershell scripts. It uses a while loop to validate that either a Y or N value is entered. Everything works fine, however a new line is created each time an error is made. I could use cls and redisplay everything, but this is not the most ideal solution. Instead, I would like to find a way to redisplay the read-host prompt on the same line while clearing any previously entered answer. Here is my existing code:
# Begin function to display yes or no menu
function ynmenu {
    $global:ans = $null
    Write-Host -ForegroundColor Cyan "`n Y. [Yes]"
    Write-Host -ForegroundColor Cyan "N. [No]`n"
    While ($ans -ne "y" -and $ans -ne "n"){
        $global:ans = Read-Host "Please select Y or N"
    }
}
# End function ynmenu

I have a few other dynamically populated menus which leverage this methodology. Finding a solution to this would resolve the issue with those as well.
Comment: Ok thanks. I know I can do it via clearing the screen, but I was trying to avoid that. Doing so is not the end of the world though.
Comment: To be clear, when the user provides input (a carriage return, or enter), if not "Y" or "N," you want to remain on the line above, instead.  Having no visible entry prior?
Comment: If anything is entered other than a "y" or an "n" including enter or no entry, I would like the prompt to redisplay on the same line. It would also need to clear the previous entry. For example, if someone typed yes or no or anything else it would not be valid. So that text would need to be cleared as well.
Comment: You aren't going to be able to "move" the cursor, or clear an individual line like that (not easily, at least - it's possible, but rather involved).  The most practical method of achieving, purely visually, what you're asking for is to clear-screen, and rewrite the prompts and read-host.  See [this question](http://stackoverflow.com/questions/25846889/powershell-overwriting-line-written-with-write-host) for a similar request.  Otherwise, you're overcomplicating what sounds like a series of similar implementations for prompt-only requests.
Answer: I don't think there's any simple way to do that.
But for a yes/no response, you can use $PSCmdlet.ShouldContinue($Query, $Caption) instead, as long as the scope you're in (function, script, etc.) defined the attribute [CmdletBinding(SupportsShouldProcess=$true)]. This shows an appropriate yes/no prompt in ISE and in the console host and avoids manual processing.


Subscription - "This subscription will not be automatically renew" Text shown while launching billing flow

Question: Subscription launch billing flow bottom sheet shows text that "This subscription will not automatically renew"
Answer: Plz skim this article
After trying whole day I got this to my eyes.
As per latest update from Goggle auto-renew, redeems, intro prices, grace periods are paused in India due to some dealing with RBI.
https://www.google.co.in/amp/s/www.xda-developers.com/google-play-suspend-free-trials-auto-renewing-subscriptions/amp/


How to alter a form depending how it was accessed

Question: I would like to alter the login form depending how it was accessed. As an example, if the form was access from a particular link, it would display the standard login form. If it was accessed from a different link, then the login form would be modified (ie maybe display a different title and exhibit different behaviour (redirects based on role)).
I figure I need to use hook_form_alter() but I am not sure how to tell which link was clicked. Any ideas how one would go about accomplishing this? I am working with Drupal 6 by the way.
Thanks
Answer: Inside your form_alter() hook, you can always check what page a form is on by looking at $_GET['q'], eg:
if ($form_id=='user_login' && $_GET['q']=='different/link') {
  // do form alters here
}

so if you are at www.yourhost.com/different/link, it will do whatever you tell it to do.
Comment: I am pretty sure I tried this and it didn't work. I will look at my implementation again and see if I did something wrong.
Comment: let me know, the approach above does work, but the login form is also pretty unique in a lot of ways, especially with redirection, so, it could be something else that is masking the behavior.
Comment: Sorry for not getting back to this sooner but I had a bunch of other stuff on my plate to deal with. I looked at my code more closely and saw that I didn't have it quite set up like you suggested. I changed it to match and it worked. The only thing I had to change was to get the clean url instead the internal url. Otherwise worked great!


Dividing Note Value

Question:
I'm accompanying a vocalist in the song "Selve Amiche." In this piece, there is an instruction at the bottom of the first page that says to "divide the note value equally between the two vowels." When listening to recorded version of this song, though the notes are written on the same beat, the accompanist plays the left hand note first and then the right hand, both as eighth notes, instead of together as quarter notes as written. This starts in measure 8 (see the picture I've attached), where the singer begins. Is that what you're supposed to do here? I'd never seen this instruction before, so I wasn't sure.
Answer: Look at the piano part in this edition. (Different key, but same song).  I expect that's what you're hearing.
http://artsongcentral.com/wp-content/uploads/1ais057.pdf

You appear to have a transposed version, done on a modern computer score program.  The piano part has been simplified.

Dividing Note Value


How would I do a definition for a name validation

Question: What I want to do:
I am trying to make a definition that takes an input (name as string) and checks if the name is in a set list.
If it is, the program will continue.
If it isn't, it will give the user 2 more chances to enter their name correctly.
Requirements:
I need to use the name variable after the definition.
I need the system to exit if the name is wrong 3 times.
Problems:
If the name is correct it works properly
However, if the name is wrong, it doesn't allow another name input, printing "You have 2 more tries" and "You have 1 more try" then ends the loop and exits.
Code:
names_allowed_to_play = ["MUM","DAD"]

def val_1 (name_1):

    print("Player 1, you have 3 tries to enter the correct name")
    print("")
    a = 0

    while a < 3:

        name_1 = name_1.upper()

        if name_1 in names_allowed_to_play:
            print(name_1 + ", you are authorised to play, have fun!")
            print("")
            a = a + 4
            names_allowed_to_play.remove(name_1)

        elif name_1 not in names_allowed_to_play:

            a = a + 1

            if name_1 not in names_allowed_to_play and a ==1:
                print("You have 2 more tries")
                print("")
                print("")
            elif name_1 not in names_allowed_to_play and a ==2:
                print("You have 1 more try")
                print("")
                print("")

    if a == 3:
        print("")
        print("Sorry Player 2, " + name_1 + " ruined it! " + name_1 + ", you are NOT AUTHORISED!")
        sys.exit()

#Run definition
name_1 = input("Player 1, please enter your name to play: ")
val_1(name_1)

Comment: You never seem to ask the user for new `input(). Also you have to return `name_1` from the function.
Answer: There are a few problems with your code:

you never ask the user for new input within the loop, instead just testing the first name again
you modify the (local) name_1 variable, but never return the value to the caller
you do not have to repeat all the conditions, and can use math to determine the number of tries remaining

You can try something like this:
def get_name(player, tries, names_allowed_to_play):
    print(f"Player {player}, you have {tries} tries to enter the correct name")
    for i in range(1, tries+1):
        name = input("Please enter your name to play: ").upper()
        if name in names_allowed_to_play:
            print("You are authorised to play, have fun!")
            names_allowed_to_play.remove(name)
            return name
        elif i < tries:
            print(f"You have {tries - i} more tries")
        else:
            print("You messed up")
            exit()

names_allowed_to_play = ["MUM","DAD"]
name1 = get_name(1, 3, names_allowed_to_play)
name2 = get_name(2, 3, names_allowed_to_play)
print(name1, name2)

Answer: Major changes:

put input() in while loop so you can get new input when the name is wrong, otherwise you only get the input once and the wrong name is checked by the if-statement 3 times
add return statement for allowed name so you can use the name later (such as print out or other functions)

You can find other minor changes in my code comment.
# change the names to lowercase so you don't need upper() for input
names_allowed_to_play = ["mum","dad"]

def player_validate():
    # \n for new line, just works like your print("")
    print("Player 1, you have 3 tries to enter the correct name\n")
    tries = 0

    while tries < 3:
        player_name = input("Player 1, please enter your name to play: ")
        if player_name in names_allowed_to_play:
            print(player_name + ", you are authorised to play, have fun!\n")
            names_allowed_to_play.remove(player_name)
            # return will stop the loop so you don't need to break it by other code
            return player_name
        else:
            tries = tries + 1
            # use calculation instead of many elif statment
            print(f"You have {3-tries} tries.")

    # I have change Player 2 to Player 1, if it is not typo, you can change it back
    print("Sorry Player 1, " + player_name + " ruined it! " + player_name + ", you are NOT AUTHORISED!")
    # use exit() instead of sys.exit() or you will need to import sys at beginning
    exit()

# Run function (I think function is a more common name then definition)
name_to_use_later = player_validate()
print(name_to_use_later)

Answer: This is working for me, I think the way you had structured it meant the logic was flawed.
import sys, time

names_allowed_to_play = ["MUM","DAD"]

def main():
    authorised = False
    attempts = 3
    while authorised == False:
        if attempts < 3:
            print("You have",attempts,"remaining.")
        if attempts > 0:
            name = input("Player 1, please enter your name to play: ")
            name = name.upper()
        elif attempts <= 0:
            print("You are locked out.")
            time.sleep(1)
            sys.exit()
        if name in names_allowed_to_play:
            print(name," you are authorised to play, have fun!")
            names_allowed_to_play.remove(name)
            authorised = True
        else:
            attempts -= 1
main()

Answer: I have fixed your code problem.
names_allowed_to_play = ["MUM", "DAD"]
def val_1():
   print("Player 1, you have 3 tries to enter the correct name")
   name_1 = input("enter your name")
   a=0
   while a < 3:
       name_1 = name_1.upper()
       if name_1 in names_allowed_to_play:
           print(name_1 + ",you are authorised to play, have fun!")
           a = a + 4
           names_allowed_to_play.remove(name_1)
       elif name_1 not in names_allowed_to_play:
           a = a + 1
           if name_1 not in names_allowed_to_play and a == 1:
               print("You have 2 more tries")
               name_1 = input("enter your name")
               print("")
           elif name_1 not in names_allowed_to_play and a == 2:
               print("You have 1 more try")
               name_1 = input("enter your name")
           elifa == 3:
               print("")
               print("Sorry Player 2, " + name_1 + " ruined it! " + name_1 + ", you are NOT AUTHORISED!")
               exit()

val_1()

Comment: Please don't add code as images - they're not searchable and they're not accessible for those who have trouble reading.
Comment: iam new so when i tried putting code i was not able to put it .
Comment: Edit it and leave it in your answer and tag me / just comment here, and I'll clean it up for you. Usually you can use the `code` button in the editor to get it tabbed in by four spaces automagically.
Comment: I finally got it. I checked some info given by stack overflow. Thanks for helping me
Comment: "Here is working code" is almost never a *useful* answer, even if the OP can copy and paste it as is.
Comment: i was not trying to create advance code  I just solve the problem he was facing.


When I try to get data from flutter firebase realtime database I got NULL

Question: When I try to get the name of the current user from the database I got NULL in the userName variable.
Future<String?> getName(String email) async {
final ref = FirebaseDatabase.instance.ref('users');
final query = ref.orderByChild('Email').equalTo(email);

final snap = await query.once();
final snapshot = snap.snapshot;

if (snapshot.value != null) {
  final data = snapshot.value as Map<dynamic, dynamic>;

  data.forEach((key, value) {
    final name = value['userType'];
    if (name is String) {
      userName = name;
    }
  });
}
}

I want the name to be saved in a global variable called userName but it's always shoing null When I try to use it on the screen in a Text() widget.
Comment: Are you sure you use right key inside forEach? `final name = value['userType'];`
Answer: If you want to show an asynchronously loaded value in the UI, you can do so with a FutureBuilder.
First, change your getName function so that it actually returns a value:
Future<String?> getName(String email) async {
  final ref = FirebaseDatabase.instance.ref('users');
  final query = ref.orderByChild('Email').equalTo(email);

  final snap = await query.once();
  final snapshot = snap.snapshot;

  if (snapshot.value != null) {
    final data = snapshot.value as Map<dynamic, dynamic>;

    data.forEach((key, value) {
      final name = value['userType'];
      if (name is String) {
        userName = name;
      }
    });
  }
  return userName; //
}

Now to display this value in the UI, wire up a FutureBuilder like this:
Widget build(BuildContext context) {
  return FutureBuilder<String>(
    future: getName,
    builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
      if (snapshot.hasError) return Text("ERROR: ${snapshot.error}");
      if (!snapshot.hasData) return CircularProgressIndicator();

      var data = snapshot.data!
      return Text("$data");
    }
  )
  ...

Also see the documentation for FutureBuilder and the codelab on async programming.


CHICKEGG chicks problem [spoj]

Question: I was solving this problem and getting TLE (time limit exceeded).
I was doing it using priorityqueue collection in java.I stored all the given egg hatching ability in priorityqueue and after that i took the first(smallest) element from priorityqueue and find its next day of laying an egg by the  given relation
i.e.
**Hen[i] lays it's first egg on D[i]th day.
Hen[i] lays it's second egg on 2*D[i]+1 th day.
Hen[i] lays it's thrid egg on 3*D[i]+3rd day.
Hen[i] lays it's fourth egg on 4*D[i]+6th day.
Hen[i] lays it's fifth egg on 5*D[i]+10th day.
and so on..**
and get it added to prirityqueue and removes that first(smallest) element.
For example suppose we are given 3 egg hatching abilities and we have to find minimum number of days to produce atleast 3(k=3) eggs....
so my solution involve k iterations each time taking smallest value and calculate its next egg laying day and again add it to priorityqueue after removing smallest element..
so let the inputs given in question be
n=3                  k=3
values of n hatching abilities=1,2,3
for k=1
we just need 1 day.
for k=2
now i have calculated next egg laying day of first hen i.e.2*(1)+1=3
and remove 1 from priority queue and add 3 to it ,so now priority queue will look like  2,3,3
ans for k=2 is 2..
for k=3
again doing the same procedure and finding the next egg laying day of first hen in priority queue i.e 2*(2)+1=5..
and again removing 2 from queue and adding 5 to it now the queue will look like..3,3,5
hence answer for k=3 is 3..
In each case after k iterations answer is the smallest element in priorityqueue.
**so basically it iterates k times and left me with TLE **
Is there any approach independent of k or how could i improve it further..
Comment: As k can become as large as $10^8$, your task as *participant* in the contest is apparently to find an algorithm that is much better than $O(k)$.
Comment: TLE stands for?
Comment: TLE-time limit exceeded..
Answer: Find an efficient way to obtain the number of eggs a single hen produces within $x$ days. Then make a binary search for the right number of days.

CHICKEGG chicks problem [spoj]


Using Proc Freq or different method

Question: I am trying to display create data set to make it show that  how consumer units participated in at least three of the four quarterly interviews.
I am not sure if its efficient to use proc freq by looking at how many times I see CU_ID come up.
but this is my code so far:
data fmli071Q1;
set hw06.fmli071;
QTR = 1;
run;

data fmli072Q2;
set hw06.fmli072;
QTR = 2;
run;

data fmli073Q3;
set hw06.fmli073;
QTR = 3;
run;

data fmli074Q4;
set hw06.fmli074;
QTR = 4;
run;

data fmli2007_bob2;
set fmli071Q1 fmli072Q2 fmli073Q3 fmli074Q4;
run;

proc contents data = fmli2007_bob2;
run;

data memi071Q1;
set hw06.memi071;
QTR = 1;
run;

data memi072Q2;
set hw06.memi072;
QTR = 2;
run;

data memi073Q3;
set hw06.memi073;
QTR = 3;
run;

data memi074Q4;
set hw06.memi074;
QTR = 4;
run;

data memi2007_bob2;
set memi071Q1 memi072Q2 memi073Q3 memi074Q4;
run;

proc sort data=fmli2007_bob2;
by CU_ID;
run;

proc sort data=memi2007_bob2;
by CU_ID;
run;

data ce2007_bob2;
merge fmli2007_bob2 memi2007_bob2
by CU_ID;
run;

Now I am at a part where I need to display how many consumer units participated in at least three of the four quarterly interviews in 2007? How should I do this by proc freq or a different method I want to create a new data step call at least_three_bob2 that will only show IDS of consumer units that participated in at least three of the four quarterly interviews in 2007. Then eventually print it out
data atleast_three_bob2;
set ce2007_bob2;
run;

Comment: Can a CU_ID occur more than once in a quarter ?
Answer: Proc SQL can perform data aggregation and frequency counts based on complex critera.
data have;
  do quarter = 1 to 4;
    do id = 1 to 100;
      if quarter > 0 and mod(id,7) = 0 then
        output;
      else
      if quarter > 1 and mod(id,13) = 0 then
        output;
      else if quarter > 2 then
        output;
    end;
  end;
run;

proc sql;
  create table want(label="ids and quarters of ids appearing in >= 3 quarters") as
  select quarter, id
  from have
  group by id
  having count(distinct quarter) >= 3
  order by id, quarter
  ;

  create table want2(label="frequency counts for number of ids having >= 3 quarters") as
  select quarter_count, count(*) as id_count
  from
  (
    select count(*) as quarter_count
    from want
    group by id
  )
  group by quarter_count
  ;

Using Proc Freq or different method


Rerun Jquery function onclick

Question: I have a simple jquery script that changes the url path of the images. The only problem is the doesn't apply after I click the load more button. So I'm trying to do a workaround where it calls the script again after clicking the button.

HTML
Load More

Comment: Your ReplaceImages is anonymous named function  inside your .ready().. move it outside the .ready,  and then do  $(document).ready(ReplaceImage)
Answer: While Keith's answer will get you what you are looking for, I really can't recommend that approach. You are much better off with something like this.

Using this html
<button class="js-replace-image">Load More</button>

By taking this approach, you do not expose any global variables onto the window object, which can be a point of issue if you work with other libraries (or developers) that don't manage their globals well.
Also, by moving to a class name and binding an event handler to the DOM node via JavaScript, you future proof yourself much more. Also allows yourself to easily add this functionality to more buttons very easily but just adding a class to it.
I updated the anchor tag to a button because of the semantics of what you need to do - it doesn't link out anywhere, it's just dynamic functionality on the page. This is what buttons are best served for.
I'd also recommend putting this in the footer of your site, because then, depending on your situation, you will already have the images updated properly without having to click the button. The only need for the button would be if you are dynamically inserting more images on the page after load, or if this script was in the head of your document (meaning jQuery couldn't know about the images yet).
I hope this helps, reach out if you have questions.
Comment: If your JavaScript is being included via an external file you can use the `defer` attribute in the `script` tag to ensure the script is not run until the DOM is fully loaded. Although you are using jQuery's `ready()` which is pretty solid about not executing until everything is loaded so you might be okay.

Rerun Jquery function onclick


Hosting advanced cron for Aegir 3

Question: There was one very useful contributed module named Hosting Advanced Cron. It allowed me to set cron interval per site, instead of set just global for all (and you can even disable cron on specific sites). hosting advanced cron
For Aegir 3, there is no such release and development seemed to be stopped. There is a fork on Github by omega8cc, but it is not functional (doesn't work, has error and notice, has debug statements left on), so does anyone have a solution or a replacement for such a useful feature for Aegir 3?
Comment: The fork from omega8cc is your best bet... it has seen some commits recently. You could open an issue to ask the original maintainer to grant omega8cc access to the project as a co-maintainer.
Comment: Thanks @HermanvanRink I did that already. They reworked module and adjusted for BOA, and it cannot be a drop in replacement for common Aegir. I also confirmed what they said by trying it myself on some instance.
Answer: After discussion with omega8cc, and a bit of testing, the answer is that advanced_cron is not any more compatible with Aegir 3. It is also merged into BOA (by omega8cc) in their core, and it is not back compatible with stand alone Aegir.
There are two options:

port it to work with standalone Aegir 3
use crontab and wget / curl to trigger cron on site

Hosting advanced cron for Aegir 3


If $f(f(x))=x^2-x+1$, what is $f(0)$?

Question:
Suppose that $f\colon\mathbb{R}\to\mathbb{R}$ without any further restriction. If $f(f(x))=x^2-x+1$, how can one find $f(0)$?

Thanks in advance.
Comment: (-1) for showing no effort and/or context in the question.
Comment: Hint: figure out $f(1)$ first.
Comment: Same question on AOPS: "[2019 Nepal National Mathematics Olympiad](https://artofproblemsolving.com/community/c6h2303094p18233602)", "[Determine f(0) if given f(f(x))](https://artofproblemsolving.com/community/c6h443695p2498519)" and "[hard functional equation](https://artofproblemsolving.com/community/c4h1115547p5104444)". It seems that the problem has originally appeared as Problem 5 of Baltic Way 2011 contest.
Answer: We have that
$$f(f(f(x)))=f(x)^2-f(x)+1.$$ Since $f(f(0))=1$ we get that $$f(1)=f(0)^2-f(0)+1.$$ That is
$$f(0)^2-f(0)+1-f(1)=0.$$ Repeating the process, since $f(f(1))=1$ we get that $$f(1)=f(1)^2-f(1)+1.$$ That is
$$(f(1)-1)^2=f(1)^2-2f(1)+1=0.$$ Thus, $f(1)=1.$ So it is $$f(0)^2=f(0),$$ from where $f(0)=0$ or $f(0)=1.$
If $f(0)=0$ then $f(f(0))=f(0)=0$ which contradicts $f(f(0))=1.$ So, it must be $f(0)=1.$
Answer: $f(f(0))=f(f(1))=1$. Apply $f$ once again: $f(f(f(0)))=f(f(f(1)))=f(1)=f(0)^2-f(0)+1=f(1)^2-f(1)+1$.
That leads to $f(1)=1$, hence $f(0)^2-f(0)=0$ and $f(0)$ can only be $0$ or $1$.
But $f(0)=0$ leads to $f(f(0))=0$, contra $f(f(0))=1$, so $\color{red}{f(0)=1}$.
Answer: If such a function $f$ exists, then $f(0) = 1$, but such a function $f$ does not exist. See the paper:

When is $f(f(x)) = az^2 +bz+c$?
R. E. Rice, B. Schweizer and A. Sklar
The American Mathematical Monthly
Vol. 87, No. 4 (Apr., 1980), pp. 252-263
(Link to PDF not behind the JSTOR paywall)

Edit: Such a function does not exist in $\mathbb{C}$! Or in any algebraically closed field of characteristic zero. But you can have such a function in the reals. See the epilogue of the paper (page 262).
Comment: Actually the result there is "heavily domain dependent" and in fact they show a quadratic that has arbitrary iterative roots over the reals.
Comment: Oh wow, you're right. I just read the introduction and assumed that if it was true in $\mathbb{C}$ then it must be true in $\mathbb{R}$.
Comment: Not true because the way the subset relation works.
Answer: I think it is more easy from what it seems. You know that
$$f(f(0))=1,$$
then
$$f(1)=f(f(f(0)))=f(0)^2-f(0)+1,\;(*)$$
but also
$$f(f(1))=1^2-1+1=1,$$
so
$$f(1)=f(f(f(1)))=f(1)^2-f(1)-1$$
and you can calculate $f(1)$ from here, and then substitute its value in $(*)$

If $f(f(x))=x^2-x+1$, what is $f(0)$?


Handling different summation limits

Question: My question is to understand the difference of summation limits based on these example distributions.
Let's say that $x = 0, 1, 2, ..., 2m$
Then we have $$\frac{\delta^x}{1+\delta^{2m+1}}$$
When taking the summation of this distribution I would do:
$$\sum_{x=0}^{2m} \frac{\delta^x}{1+\delta^{2m+1}}$$
However, let's change the variable and replace it with  z when $0 < z < 2m$, I get this distribution:
$$\frac{\delta^z}{1+\delta^{2m+1}}$$
But what happens to the limits of the summation? Surely, $0 < z < 2m$ is different to when $x = 0, 1, 2, ..., 2m$
The best I can get is:
$$\sum_{0<z<2m}\frac{\delta^z}{1+\delta^{2m+1}}$$
However, I wouldn't know how to compute this sum or get the right lower and upper limits.
Comment: This is essentially the same question you asked at. https://math.stackexchange.com/questions/4326599/how-to-sum-an-even-series . Here you have two different sums, one including $0$ and $2m$, one not. Write them with ellipses ( ... + .. +..)  instead of sigma notation. Then each can be manipulated to include a standard finite geometric series sum.
Comment: They're similar but different as I'm asking what happens to the sum limits when 0 < z < 2m. I'm not quite sure that I catch you, when I expand them out I'll follow the same logic as if x = 0, 1, 2, ..., 2m but they must be different?
Answer: You are overthinking this question, and relying too much on the formal summation expression. Write the sums out using ellipses and look at the patterns.
In each of these two sums the denominator of each term is the same, so you can just divide by it when you  sum the numerators that vary.
To evaluate the first sum you need
$$
1 + \delta + \delta^2 + \cdots + \delta^{2m-1} + \delta^{2m} .
$$
You can find it using the standard formula for the sum of a geometric series.
For the second sum the numerators add this way:
$$
 \delta + \delta^2 + \cdots + \delta^{2m-1}   .
$$
To calculate that, just factor out $\delta$ and sum the resulting ordinary geometric series that starts with exponent $0$ and ends with exponent $2m-2$.
Comment: Yes, But my general point is that the summation notation with its dummy index variable gets in the way of understanding rather than helping, so you should avoid it as much as possible. When you see it in something you are reading, unpack it. Don't write it yourself until you have to, perhaps for publication.
Comment: So this summation looks like $\sum_{z=1}^{2m-1}\delta^{z}$ and then factoring out a delta and re-arranging the summation limits $\delta \sum_{m = 0}^{2m-2}\delta^m$? where $m = z-1$?
Comment: I believe there is a flaw with my summation! I managed to correctly figure it out in the end:$
\sum_{y=1}^{2k-1}\delta^{2y} \implies \delta \sum_{y=1}^{2k-1} \delta^{2y-1}$ substituting $u=y-1$ as we can do this $\delta^{y-1}\delta^y \implies \delta^{u}\delta^{u+1}$ we get $\delta \sum_{u=0}^{2k-1} \delta^{2u+1} \implies \delta^2 \sum_{u=0}^{2k-1} \delta^{2u} = \frac{\delta^2 \cdot (1-\delta^{4k-2})}{1-\delta^2}.$ Definitely a more fluid approach, although knowing both methods in deriving the answer is great also!

Handling different summation limits


Area between two functions

Question: My question is from Apostol's Vol. 1: One-variable calculus with introduction to linear algebra textbook.

Page 94. Exercise 16. Let $f(x)=x-x^2$, $g(x)=ax$. Determine $a$ so that the region above the graph of $g$ and below the graph of $f$ has area $\frac{9}{2}.$

My attempt at a solution. I tried following: $$a(S)=\int_{x_1}^{x_2}[f(x)-g(x)]\mathrm dx=\int_{x_1}^{x_2}x\mathrm dx-\int_{x_1}^{x_2}x^2\mathrm dx-a\int_{x_1}^{x_2}x\mathrm dx=\frac{x_2^2-x_1^2-a(x_1^2-x_2^2)}{2}-\frac{x_2^3-x_1^3}{3}=9/2$$ but this approach gets me nowhere, I graphed both functions, and I realize that $a$ must be negative but without boundaries, on integral, how should I find out what $a$ is, because $a$ changes as $x_1,x_2$ change. Please explain or give some hints.
Comment: are we talking about all the regions in the first quadrant? otherwise, you are going to have infinite area in the lower half plane.
Comment: @abel now I understand that it was talking about area between points of intersection of those 2 functions. Otherwise, area would be infinite yes.
Comment: but the total area in the first quadrant is only $5/12$ very much smaller than the $9$ to halve.
Comment: @abel what do you mean total area in the first quadrant is only $5/12$? Because $a$ can be negative, so we are not restrained in first quadrant. It is asking for area between the intersections of those 2 functions.
Answer: By graphing the two functions, we can see that the region represented by the volume is:
$$f(x) - g(x) = x-x^2 - ax$$
In order to find the points of intersection, we must set the two graphs equal to one another:
$$x-x^2 = ax \Leftarrow\Rightarrow \ x^2 + x(a - 1) = 0 \Leftarrow\Rightarrow\ x(x + a - 1) =0$$
Therefore, $x = 0 , 1 - a$
Constructing our integral:
$$\int_{0}^{1-a} (x-x^2 - ax)dx = \left[\frac{x^2}{2} - \frac{x^3}{3} -\frac{ax^2}{2}\right]_{0}^{1-a} = \frac{(1-a)^2}{2} - \frac{(1-a)^3}{3} - \frac{a(1-a)^2}{2} = \frac{9}{2}$$
Simplifying we get:
$$\frac{(1-a)^3}{6} = \frac{9}{2}\Leftarrow\Rightarrow 2(1-a)^3 = 54 \Leftarrow\Rightarrow (1-a)^3 = 27$$
Therefore, $a = -2$
Comment: Thank you very much for nice solution, I didn't realize that question was talking about area between points of intersection and since otherwise, area would be infinite, I got confused.
Comment: @GeorgeApriashvili no problem. It always helps to first draw a graph to help you visually see what region you are taking the area of.

Area between two functions


What are your techniques to research music basics signs, theory and for sheet music?

Question: There are many questions about music basics, scales, keys, signs, harmony, chords etc. which could be answered by own researches if people had better strategies for searching.
This is because they don't know the terms like "music signs", "symbols", they don't only lack for theory but for music terminology. For this we have many posts like: "what does this letter or figure or that sign above that mean?"
That's why I wonder and ask: what are your best and most successful strategies to research about music information? (apart of asking in music theory and praxis)
Comment: I was asking myself something similar in the past, especially because my natural language is Italian (and, since many musical terms are inherited from my language, I usually don't need to know them in other languages) and I often struggle trying to find the correct terms when I need to do some research in English.
Comment: The first thing I had to learn that in English the  relative chords are what we call  And there are still a lot of other differences in terminology we have to learn. (But people here are very helpful when we are not correct in formulating in English, especially Tim!)
Answer: Read a good book.
I started with Learning to Read Music by Peter Nickol.
Then The AB Guide to Music Theory Part 1 and First Steps in Music Theory Grades 1 to 5 by Eric Taylor, both published by the ABRSM.  If you're planning to do the ABRSM grades, then the Eric Taylor books match the exams.  Otherwise, they aren't very reader-friendly, and can be ignored.
Answer:
If I want to look up a question about scales or keyboard or music symbols I type in google the word e.g. piano, keyboard, music clef or the song title e.g.Summertime + Gershwin and then I look up Images and scroll all the pictures through. From there I find the link to the source of this picture and a lot of new information.

It took a long time until I've found out that you can translate e.g. an English site in Wiki to German or Italian and an Italian Wiki Site to English: There are actually several ways: sometimes there exists an equal Wiki site with exactly the same information, or you can translate on site in another language, or there are quite different Wiki sites with quite different information in the different languages. (On the left of the site scroll down: languages!)

Youtube-videos often hide a lot of interesting information if we would know the frame and context of our problem. From certain youtube videos you can capture the text and download and translate it, if it is not possible to translate it in the cc.

What we often forget or ignore are the links and bibliography on the bottom of the Wiki sites! There are always good resources, of course the IMSLP links too, but also many other helpful links and titles of books. (History, Theory etc.

Here are some examples of links when looking up a certain term:
Summertime Gershwin
Piano Keyboard Signature
Chord progressions
Scales and modes
Answer: Terminology is the beginning of theory so I'd say these are the same discipline.  A good series is,
Master Theory Book by Charles S Peters and Paul V. Yoder Vol. 1 - 6
These are short, easy to read, and well written.  Vol 1 - 3 are basic theory and 4 - 6 harmony.  The harmony books do not have great exercises.  For Harmony I prefer Cheyette and Paulson.
If you are based in England, or elsewhere where their standard is used, then ARBSM might be a good choice but if you are in America that system might screw you up.  I made the mistake of buying some ARBSM books for harmony and their definitions for inversions and cadences are different from those in the US system.
Comment: I'm from Canada, and I recall that my harmony lessons, textbooks, and exercise books (for the Royal Conservatory of Music) made me aware of both cadence systems (both "Perfect Authentic Cadence" and "Perfect"/"Plagal"/"Deceptive").
Comment: I have not seen that those books but then again I have not gone through them all.  Canada i would guess, would follow British standards over us.  Just a guess.


How can I warm up my asp.net mvc webapp after an app pool recycle?

Question: I am running an ASP.NET MVC webapp in IIS 8.0. My application needs to be warmed up before taking requests. We already have a process to warm up the application automatically when we deploy new code. However, we are seeing periodic App Pool Recycle events that are resulting in the app not being warmed up.
Is there a best practice for detecting an app pool recycle event and executing a script or some code?
Answer: There are several things you can do:
1. Application Initialization
You can use Application Initialization Module which comes in-box with IIS 8.0
you can have something like this in your web.config
<applicationInitialization
     doAppInitAfterRestart="true" >
   <add initializationPage="/" />
</applicationInitialization>

This will send a request to the root of your app (initializationPage="/") every time your app starts automatically.
You can also configure the Start Mode for your application pool to Always Running which means every time IIS restarts, it will make sure to start your application pool immediately (this if from right click on your application pool then Advanced Settings

and Preload for your site itself (right click on the site then Manage Site then Advanced Settings

2. Disable Idle Time-out
Additionally you can disable idleTimeout (by default IIS will shut down the app after 20 minutes of in activity) by changing the of in Idle Time-out for your application pool to 0 (infinite)

3. Disable periodic recycling
also turn off Regular Time Interval (minutes) by default IIS would recycle your app every 29 hours.

For
Comment: Comments on drawbacks to these settings would be appreciated.  Surely there's a reason they aren't defaults.
Comment: Sure, high memory consumption if you run multiple sites on the same IIS box since all the sites stay alive all the time, which leads to very low site density. Also no protection against memory leaks in your applications. Keep in mind that IIS was around before managed languages became popular for web and many apps were running native handlers that got into memory leaks & weird state if left running for a long time. That was done to help sysadmins who had to wake up in the middle of the night to reset servers due to app issues. They are still defaults mostly for backward comparability reasons
Comment: You can get the [Application Initialization Module](http://www.iis.net/downloads/microsoft/application-initialization) for IIS 7.5 for #1 to work. #2 and #3 are applicable as-is to IIS 7.5
Comment: FYI for folks using this: the `applicationInitialization` goes into ``
Comment: Alternatives in ***IIS 7.5 - Windows Server 2008 R2*** ?
Comment: @ahmelsayed Thanks I did everything but still not calling `applicationPage` on one server, any idea?
https://superuser.com/questions/1246478/iis-applicationinitialization-doesnt-call-initializationpage-on-one-of-the-serv
Comment: Is the path for the application initialization relative to the root directory? In other words, if the application lives in a virtual directory named:
/mypath

Should the value be "/mypath" or "/"??
Answer: From my experience, AlwaysRunning and Preload enabled doesn't get much speed up. The most wait time goes on dynamic compilation (which can be fixed with aspx precompile) and loading assemblies into memory and caching.