Querystring in Views ajax_view.js

Question: I'm using Views 7.x-3.11 with Better Exposed Filters and Ajax auto-submit in a panels page, and running into some issues that seem to be stemming from code in Views/js/ajax_view.js. I want to make the exposed filters bookmarkable, and I also need to deep link to certain result sets. Because of this, I added some custom js to add the selected form parameters to the URL as the user selects them.
I also have a section that lists all the currently active terms, where a user can click to remove them. In order to update the results from here, I'm calling $('.view-my-view').trigger('RefreshView');.
By default, from here I can see that the ajax_path for submitting the form has been set to the URL with the query string, which doesn't work. From what I can tell, the native ajax behavior is trying to submit the serialized form data to an already-parameterized URL. To change this behavior, at line 38 of ajax_view.js I've changed var queryString = window.location.search || ''; to var queryString = '';
It's pretty apparent that this is going to cause issues with some sort of intended functionality, but I can't determine what that is. I'm afraid I'm losing sight of something bigger-picture here, or not aware of something about how Views handles ajax submission typically.
Can anyone provide an example of a situation where you'd need the original code? Or what the intended purposed of it is?
Edit: Follow-up question that's a little more practical - is there a way I can make an equivalent change in my custom js that would override the default code in ajax_view.js, so that I don't need to alter the module?
Answer: I had a similar problem where I wanted to link to filtered versions of an ajaxified view, but the aforementioned line of code in ajax_views.js prevented the view from displaying all results when all filters where cleared. In my use case, I wanted all views filter identifiers removed, but in yours, as I understood it, you need the clicked filter value removed, so you could modify the code accordingly.
The first step is identifying all valid filter identifiers. We want to do that, so we don't parse out all of the query string's parameters, since some of them might serve another functionality. If you don't care about creating a dependency to the better_exposed_filters module you can find the views identifiers from Drupal.settings.better_exposed_filters.views.[view_name].[view_display].filters.
Otherwise, you could expose them in your own Drupal setting through a views hook:
function hook_views_pre_render(&$view) {
  if ($view->display_handler->has_exposed) {
    $valid_identifiers = array();

    foreach ($view->filter as $name => $filter) {
      if (!$filter->options['exposed']) {
        continue;
      }

      $valid_identifiers[] = $filter->options['expose']['identifier'];
    }

    drupal_add_js(array('validViewsIdentifiers' => $valid_identifiers), 'setting');
  }
}

So, now we have the identifiers and in our custom js file we can change the related properties of the views instance(s). The code for my use case is the following, but you can change accordingly:
Drupal.behaviors.fixAjaxQueryString = {
  attach: function(context, settings) {
    if (!Drupal.views || !Drupal.views.instances) {
      return;
    }

    for (var i in Drupal.views.instances) {
      var instance = Drupal.views.instances[i],
          url = instance.element_settings.url;

      // Check for any valid views filter identifiers and remove them
      var validViewsIdentifiers = Drupal.settings.validViewsIdentifiers || '';
      if (validViewsIdentifiers) {
        url = decodeURIComponent(url);

        for (var j = 0; j < validViewsIdentifiers.length; j++) {
          var regExpr = '\\&?' + validViewsIdentifiers[j] + '(\\[\\])?=[^&]*';
          var regExprObj = new RegExp(regExpr, 'g');

          url = url.replace(regExprObj, "");
        }
      }

      // Only the .options.url part is needed for the desired functionality
      // The rest is modified for consistency
      instance.element_settings.url = url;

      if (instance.exposedFormAjax) {
        instance.exposedFormAjax.options.url = url;
        instance.exposedFormAjax.element_settings = instance.element_settings;
        instance.exposedFormAjax.url = url;
      }

      if (instance.pagerAjax) {
        instance.pagerAjax.options.url = url;
        instance.pagerAjax.element_settings = instance.element_settings;
        instance.pagerAjax.url = url;
      }

      if (instance.refreshViewAjax) {
        instance.refreshViewAjax.options.url = url;
        instance.refreshViewAjax.element_settings = instance.element_settings;
        instance.refreshViewAjax.url = url;
      }
    }
  }
};

Answer: This module will allow you to make exposed filters bookmarkable:
Views Ajax History Module
It utilizes the History.js library

Querystring in Views ajax_view.js


Prove that $\lim_{\Delta x\to 0} \frac{\Delta ^{n}f(x)}{\Delta x^{n}} = f^{(n)}(x).$

Question: If $\Delta f(x)=f(x+\Delta x)-f(x)$, $(a)$ prove that $$\Delta\{\Delta f(x)\}=\Delta^2f(x)=f(x+2\Delta x)-2f(x+\Delta x)+f(x);$$ $(b)$ derive an expression for $\Delta^n f(x)$ where $n$ is any positive integer; and $(c)$ show that $$\lim\limits_{\Delta x\to0}\dfrac{\Delta^n f(x)}{(\Delta x)^n}=f^{(n)}(x)$$ if this limit exists.
I was able to prove $(a)$, and this is the expression I derived for $(b)$
$$\Delta ^{n}f(x)=\sum_{i=0}^{n}(-1)^{n-i}\binom{n}{i}f(x+i\Delta x)$$
I an fairly sure that the above is correct.
However, I am not sure how to prove,
$$\lim_{\Delta x\rightarrow 0} \frac{\Delta ^{n}f(x)}{\Delta x^{n}} = \lim_{\Delta x\rightarrow 0} \frac{\sum_{i=0}^{n}(-1)^{n-i}\binom{n}{i}f(x+i\Delta x)}{\Delta x^{n}} = f^{(n)}(x)$$
Comment: Try using Taylor's theorem for the limit.
Comment: induction on $n$
Comment: I do not fully understand notation: $\Delta f$ is the function which, evaluated at $x$, gives $(\Delta f)(x)=f(x+\Delta x)-f(x)$. Then $\Delta(\Delta f)$ evaluated at $x$ is equal to $(\Delta(\Delta f))(x)=(\Delta f)(x+\Delta x)-(\Delta f)(x),$ where the first term on the r.h.s. is  $(\Delta f)(x+\Delta x)=f(x+\Delta x+ \Delta( x+\Delta x))-f(x+\Delta x)$. What did I misunderstand?
Comment: I think there is some minor issue. A repeated derivative can't be defined in terms of original function. The question needs to be worded as "If $f^{(n)}(x)$ exists then prove that $\lim_{\Delta x \to 0}\Delta^{n}f(x)/\Delta x^{n} = f^{(n)}(x)$". It may happen that the limit exists but $f^{(n)}(x)$ does not. It can be proved quickly using L'Hospital's rule. Please also have a look at almost similar question http://math.stackexchange.com/questions/529923/show-that-if-fx-is-an-n-times-differentiable-function-defined-on-an-interval-i/530005#530005
Comment: By the way, your formula for $\Delta^{n}f(x)$ is correct and that means full score for part (b)!
Answer: To elaborate on the my comment, I am posting an answer. Let's us take the case of $n = 2$ then we know that $$\Delta^{2} f(x) = f(x + 2\Delta x) - 2f(x + \Delta x) + f(x)$$ and hence
$\displaystyle \begin{aligned}\lim_{\Delta x \to 0}\frac{\Delta^{2}f(x)}{\Delta x^{2}} &= \lim_{\Delta x \to 0}\frac{f(x + 2\Delta x) - 2f(x + \Delta x) + f(x)}{\Delta x^{2}}\\
&\text{(apply L'Hospital Rule, differentiation wrt } \Delta x, x \text{ is constant)}\\
&= \lim_{\Delta x \to 0}\frac{2f'(x + 2\Delta x) - 2f'(x + \Delta x)}{2\Delta x}\\
&= \lim_{\Delta x \to 0}\frac{f'(x + 2\Delta x) - f'(x + \Delta x)}{\Delta x}\end{aligned}$
Now we need the assumption of existence of $f^{(n)}(x) = f''(x)$ here. We have
$$ f''(x) = \lim_{\Delta x \to 0}\frac{f'(x + \Delta x) - f'(x)}{\Delta x}$$ hence we can see that $f'(x + \Delta x) = f'(x) + \Delta x\{f''(x) + \rho\}$ where $\rho$ denotes an expression which tends to $0$ with $\Delta x$. Replacing $\Delta x$ by $2\Delta x$ we see that $f'(x + 2\Delta x) = f'(x) + 2\Delta x\{f''(x) + \rho'\}$ where $\rho'$ is another expression which tends to $0$ with $\Delta x$. It now follows that $$f'(x + 2\Delta x) - f'(x + \Delta x) = \Delta x\{f''(x) + 2\rho' - \rho\}$$ and therefore $$\frac{f'(x + 2\Delta x) - f'(x + \Delta x)}{\Delta x} = f''(x) + 2\rho' - \rho$$ Taking limits when $\Delta x \to 0$ we get $$\lim_{\Delta x \to 0}\frac{f'(x + 2\Delta x) - f'(x + \Delta x)}{\Delta x} = f''(x)$$ and therefore we can see that $$\lim_{\Delta x \to 0}\frac{\Delta^{2}f(x)}{\Delta x^{2}} = f''(x)$$ The above proof can be carried in the same manner for any value of $n$ by repeated application of L'Hospital's rule, but at the last step when the denonominator $\Delta x^{n}$ reduces to $\Delta x$ we must make use of the existence of $f^{(n)}(x)$ the way explained above. In this connection please observe that we can't use L'Hospital rule at the last step to change $\Delta x $ in denominator to $1$ because L'Hospital Rule assumes that both numerator and denominator are differentiable in a neighborhood of the point under consideration (except possibly at that point). Hence we have to make use of the existence of $f^{(n)}(x)$ at a single point $x$ in the manner I have indicated above.
Note: The above solution would look better and more understandable if we replace $x$ by $a$ and $\Delta x$ by $h$, but I have tried to keep the notation aligned with that of OP.
Comment: Hi, how do you formally use $\lim_{h\rightarrow 0}h^{-1}[f'(x+h)-f'(x)]$ to find $\rho(h)$ and $\rho'(h)$?
Comment: For $\varepsilon>0$, we have a $\delta>0$ such that $|h^{-1}[f'(x+h)-f'(x)]-f''(x)|<\varepsilon$, for all $|h|<\delta$ such that $x+h\in\text{dom}(f')$. How do you use this find $\rho(h)$?


How to get the name of a field?

Question: I'm on hook_form_alter for the config edit form. The code runs for all fields, but it's critical that the code figures out the name of the field it is on.
When I load the formobject, I can see the field_name perfectly when I print_r the array. But I can't figure out how to pull it out. Something like $name=$field['field_name']
The field name is 'field_plan_purpose' I need to get that in a variable in the code.
My code minus all of things I've tried:
$field = $form_state->getFormObject()->getEntity();
print '
';
print_r($field);
print '
';

Here is the top part of the array that gets printed:
Drupal\field\Entity\FieldConfig Object
(
    [deleted:protected] =>
    [fieldStorage:protected] => Drupal\field\Entity\FieldStorageConfig Object
        (
            [id:protected] => node.field_plan_purpose
            [field_name:protected] => field_plan_purpose <--- HOW DO I GET THIS
            [entity_type:protected] => node
            [type:protected] => text_long
            [module:protected] => text
            [settings:protected] => Array
                (
                )

            [cardinality:protected] => 1
            [translatable:protected] => 1
            [locked:protected] =>
            [persist_with_no_fields:protected] =>
            [custom_storage] =>
            [indexes:protected] => Array
                (
                )

            [deleted:protected] =>
            [schema:protected] =>
            [propertyDefinitions:protected] => Array
                (...

As you can see, 'field_name' is in there. Does anyone know how I can pull that out and reference it directly?
A few things I've tried:
    // print_r($field->getEntityKey('#field_name'));
    // getEntityType()->getKey('field_name')
    // $field['field_name']  $field['field_name:protected']
    // $field['id']
    // $field->getKey('field_name')
    // $field->definition['field_name'];
    // print_r($field->definition);

EDITED ******* SOLUTION
/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

   $field = $form_state->getFormObject()->getEntity();
   $field_name = $field->getName();
   print $field_name;

}

Comment: From all the things you tried (at the bottom): you didn't include the leading "//", did you? If so, no surprise none of them returned what you were looking for ... Please edit your question to correct that .. if indeed you did not include those leading chars ...
Answer: FieldConfigBase has a method named getName(). That will retrieve the field name:
public function getName() {
  return $this->field_name;
}

Comment: Awesome thanks man, this works. I can't believe I couldn't figure that out lol. Final solution for getting entity field_name from hook_form_alter in Drupal 8 is edited in the original post up top.

How to get the name of a field?


Realm db change directory - React Native

Question: I have a problem finding the .realm file directory on Android 5.1. On a phone with a higher Android, I can easily find the file in Android Studio. I need some way to change the .realm file directory or make a copy to the download folder for example.
Answer: When opening the realm with Realm.open, you can override the path where the realm file should be stored: docs.
Realm.open({
  schema: [...],
  path: "path/to/my.realm",
})
  .then(...)

Comment: Thank you very much !, I had not paying much attention to this step when I read the documentation


Integrate $\int\frac{\left(1+x\right)\sin x}{\left(x^{2}+2x\right)\cos^{2}x-\left(1+x\right)\sin2x}dx$

Question: (Q) $\displaystyle \int\frac{\left(1+x\right)\sin x}{\left(x^{2}+2x\right)\cos^{2}x-\left(1+x\right)\sin2x}dx$
Tried a lot to expand denominator and reduce it to bring its derivative on top , but all in vain .
Answer: Let $$\displaystyle I = \int\frac{(1+x)\sin x}{(x^2+2x)\cos^2 x-(1+x)\sin 2x}dx$$
$$\displaystyle I = \int\frac{(1+x)\sin x}{(x^2+2x+1)\cos^2 x-(1+x)\sin 2x-\cos^2 x}dx$$
$$\displaystyle I = \int\frac{(1+x)\sin x}{\left[(x+1)\cos x\right]^2-2(x+2)\sin x\cdot \cos x-(1-\sin^2 x)}dx$$
So $$\displaystyle I = \int\frac{(1+x)\sin x}{\left[(x+1)\cos x\right]^2-2(x+1)\sin x\cdot \cos x+\sin^2 x-1}dx$$
$$\displaystyle I = \int\frac{(1+x)\sin x}{\left[(x+1)\cos x-\sin x\right]^2-1^2}dx$$
Now Let $(x+1)\cos x-\sin x = t\;,$ Then $(x+1)\sin xdx = -dt$
So Integral $$\displaystyle I = -\int\frac{1}{t^2-1}dt = -\frac{1}{2}\int\left[\frac{1}{t-1}-\frac{1}{t+1}\right]dt$$
So we get $$\displaystyle I = \frac{1}{2}\left[\ln|t+1|-\ln|t-1|\right]+\mathcal{C} = \frac{1}{2}\ln\left|\frac{t+1}{t-1}\right|+\mathcal{C}$$
So we get $$\displaystyle I = \frac{1}{2}\ln \left|\frac{(x+1)\cos x-\sin x+1}{(x+1)\cos x-\sin x-1}\right|+\mathcal{C}$$
Comment: Haha lol i had done the same way but the third didn't click in my mind . Anyway thanks soo much for writing all the steps , #respect
Comment: When I saw the substitution, then I realized and for sure that the poster is @juantheron..! (y)


CUDA C++ Linking error undefined reference threadIdx.x and blockDim.x

Question: I am trying to compile my code using CUDA for OpenGL application.
here is my code.
#include <cuda_runtime.h>
#include <cuda_gl_interop.h>
#include <device_launch_parameters.h>

float t = 0.0f;   //timer
float3* device;   //pointer to memory on the device (GPU VRAM)
GLuint buffer;   //buffer

__global__ void demo(int * d_a)
{
    int a=blockDim.x * blockIdx.x + threadIdx.x;
}

I got an error
/usr/bin/ld: CMakeFiles/MatchSlide.dir/main.cpp.o: in function `demo(void*)':
main.cpp:33: undefined reference to `blockDim'
/usr/bin/ld: main.cpp:33: undefined reference to `blockIdx'
/usr/bin/ld: main.cpp:33: undefined reference to `threadIdx'

also in CMakeFile, I defined
# Look for Truetype && libpng
find_package(Freetype REQUIRED)
include_directories(${FREETYPE_INCLUDE_DIRS})

pkg_check_modules(PNG REQUIRED libpng)
include_directories(${PNG_INCLUDE_DIRS})
find_package(CUDA  REQUIRED)
include_directories("${CUDA_INCLUDE_DIRS}")

set(CMAKE_CXX_FLAGS "-std=c++14 -Wall -lcurand -lglfw -lGLEW -lGLU -lGL -lglut -lfreetype -lpng -lpthread -lX11  -L/usr/local/cuda/lib64 -lcudart  -lcuda")

/**
 * User:Demo
 * Date: 30/4/20.
 * Sample Project
 */

// Headers

#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include "Event.h"
#include "ResourceManager.h"
#include <cstdio>
#include <cstring>
#include <cuda_runtime.h>
#include <cuda_gl_interop.h>
#include <device_launch_parameters.h>

float t = 0.0f;   //timer
float3* device;   //pointer to memory on the device (GPU VRAM)
GLuint buffer;   //buffer

__global__ void rendering(float3 *output,float k)
{
    int a=blockDim.x * blockIdx.x + threadIdx.x;
}

as you can see in my code, I am trying to define just a simple thread function to run my code. But it is generating errors that help me out where am I making mistakes in defining Cuda in my application.
Comment: That clearly isn't the code -- the error is occurring on line 33 of main.cpp, and you have posted 12 lines of code.
Comment: Please paste your cmake file as well.
Comment: Change your file's name from `main.cpp` to `main.cu` and see if it solves the issue.
Comment: @RealReza the project is in c++ so it can be possible to run Cuda in simple CPP file project.
Comment: @Bruce: No. If you put CUDA code in a .cpp file, the composition will fail. The file must have a .cu extension
Answer: Please read here on the supported file extensions by nvcc. If your source file includes both host code and device functions, it is no longer a mere C++ source file. Three solutions I can think of:
1- Change main.cpp to main.cu. But if you really don't want to change main.cpp to main.cu (not sure why), then consider these two options:
2- Include your kernel demo in a secondary file with extension cu,
3- Compile your .cpp file as is with option x cu, like:
nvcc main.cpp -x cu

by which you are forcing the compiler to treat your main.cpp file as a CUDA source file even though the extension is cpp.
Comment: Make senes to me. I think i found my answer. thanks for the tips


In scala or scalajs Diode, do any of the existing types line up with the use case of "updating a model that doesn't yet exist"?

Question: Here's a common situation: you have a form and you're interested in the submissions of that form. You may add a wrinkle to the situation by adding a server-side validator, or even a client-side validator, but the validators are only provided as a means of ensuring the input you submit is valid at that instance; any state collected between 0 and submission is thrown away and incidental.
Here's a less-common situation: your form has a password/confirm field that you need to wire to work in the obvious manner and wire to display an indication of password strength (and validity). In the past I've seen a lot of "write a jQuery callback for the event handler on change, and call it a day." This is just a more extreme case of needing the state in between to get to a destination, not as an end in itself.
Now a very uncommon situation: you need to track the input of this form because it is a form used by the US government to communicate with our guys in nuclear bunkers in Wyoming. It is certainly important that form input is valid on submission, but we need to additionally know as much as we can about the way it got there. Let's say it is a login form for instance. If we track the sequence of events from 0 to submission and compare it to the past we can detect anomalies in user behavior, for instance. We can determine whether we might be having login servers problems before we hear about them. So this is not always throwaway info.
I want to map the event onChange to some Diode concept, but I'm having trouble figuring out what I ought to do. Here are the options:

I could define a new case class for each field-type and for each object-type permuted, and stick all of them in the root model (seems like a stupid way to do it)
I could define a genericized data structure representing an "un-submitted change in input value" that would also indicate the model and field changing. Seems optimal but maybe unnecessary and a lot of work and hard to do well.
I could use an existing data structure, like one of the Pots, to stand in place for my Scratch data structure. Probably the best idea but not sure which to use.

That's where I am at... any thoughtful advice is appreciated.
Answer: This may be something where using a chat would work better, but here are some thoughts on the matter.
There are three places you could store such an event log:

In the state of the view component. Just add the timestamped events to a list stored in the view state. On submission, send this list alongside with the rest of the data.
In the Diode model. Again, store a list of events in the model and submit with the form data.
In the server. Send each event separately to the server and let it worry about what they mean. No need to store on client side at all.

For such transient data, I wouldn't route it through Diode at all, but instead use options 1 or 3 to transmit it.
Comment: I'll join you in there! Thank you


if a is not an element in a list how to print?

Question: So i created a list like this:
my_list = [1, 3, 5]
number = input("Choose a number from 1 to 5: ")

Now I want to say:
if the number is inside the list: print("ERROR"),
if the number is not inside the list: print(number)
So if I type 2 it will print me the 2, if I type 1 it will print me ERROR
How am I doing that?
Comment: What exactly is the problem? Is it how to determine if the number is in the list?
Answer: I think your looking something like the below example
my_list = [1, 3, 5]
number = input("Choose a number from 1 to 5: ")
if int(number) in my_list:
    print("error. . . . ")
else:
    print(int(number))

And when you run it this is how it works

Choose a number from 1 to 5: 2
2
Choose a number from 1 to 5: 1
error. . . .
Answer: First you need to take user input as int and then check if the number entered by user is present in my_list or not.
my_list = [1, 3, 5]
number = int(input("Choose a number from 1 to 5: "))

if number in my_list:
  print('Error')
else:
  print(number)


How to indicate flutter technique in a score?

Question: And so the question:
I would like to indicate a certain bar in a trombone score using the flutter technique. How can I label and remove it correctly?
I mean labels like for strings pizz and arco
By flutter technique I mean this:
Comment: This is a great question, and the answer applies to multiple instruments. I've taken the liberty of generalizing the title, but of course please roll back if you feel the change is inappropriate.
Answer: The notation shown in the video — the standard tremolo notation — is the correct way to indicate a flutter. In can (should) be supplemented with "f.t" (flutter tongue) for clarity.
As long as a note has no tremolo, it will be played normally.
For an extended passage, you can write "flutter" at the beginning and either use a dotted line (as in an 8va indication) or "end flutter" (or similar) to denote the passage.
Answer: One of the pieces my Wind Ensemble is playing has this exact thing, simply notated with a tremolo marking and the word "Flutter" written over top.
ps. the piece is Clash


What is stopping my theme from using a file that uses a suggested file name?

Question: I needed to modify a module's .tpl file and so copied it, renamed it to something suggested by Theme Debug's file suggestions.
Eg when I run drush theme_debug I see:

So I rename my new file image-resp-item--f6.tpl.php and place it in my site's theme.
I clear cache and rebuild the theme registry but to no affect - the site still uses the original .tpl.
To experiment, I change my new .tpl's name to match the old one (remove --f6). This works - I see my new code appear on the site.
Why is my site (or theme?) not wanting to use the suggested file name?
Answer: Your can either use hook_preprocess_page or if you don't want to code use something like context module. You can add a new context to select theme template based on your requirement.
Comment: So I would have to write a code to include each modified .tpl file? I thought  that was the point of theme suggestions - to automate this?


What is "leading note" and what does it mean to "raise a note"?

Question: I try to learn rules of how basic melody ("Cantus Firmus") should be built. At the moment I read this document. The second rule there is:

The penultimate note should go to the final in a stepwise manner i.e.
  from one note above or below the final. If approaching from below the
  leading note should be raised (except in the phrygian mode)

What is "leading note" and what does it mean to "raise a note"?
I did check Wikipedia and it says:

a leading-note is a note or pitch which resolves or "leads" to a note
  one semitone higher or lower

This statement is also not clear to me. What does it mean "leads to" and "resolves"? Are these two different things or just two different names for the same thing? Does "leads to" mean just "precedes"?
Comment: this question is related to my question of some days ago which is not yet fully answered: https://music.stackexchange.com/questions/82936/when-did-the-aeolian-mode-change-to-the-harmonic-minor. Mind that these rules for cantus firmus by Lindsay Davidson cited by Fux' Gradus ad Parnassum are a mix of several centuries and for a style of strict counterpoint that never has been written by composers - except in exercices of students.
Answer: Basically these are synonymous terms: "leads to" and "resolves."
A very important concept in tonal harmony is the strong sense of movement in the half steps of the diatonic scales. In solfege these are the tone pairs TI to DO and FA to MI.
Things can get confusing if we discuss the leading tone and resolution_and_ jump between different musical styles. You mentioned cantus firmus which suggests 16th century counterpoint, modal scales, and the species counterpoint teaching of Fux. In the 18th century homophonic style the leading tone and harmony have a different treatment with parts rooted in the older style. Let's look at the two separately. Just remember: two different styles, two different approaches.
16th century
The quote "...penultimate note should go to the final in a stepwise manner..." is describing the clausula vera, the final cadence in 16th century style. The idea is the final tone - the tonic - should be approached by two voices in contrary motion one voice moving by a whole step and the other moving by a half step. When the final is approached from below by a half step that penultimate tone is the leading tone. The exact handling depends on the mode so let's just run through each mode.
In Ionian and Lydian modes the tones above and below the final are a whole step and a half step. Let's use C as a final. The whole step above is D and the half step below is B. When B and D move to C to end this is the clausula vera. The B a half step below the C is the leading tone.
In Dorian, Aeolian, and Mixolydian modes the tones above and below the final are both whole steps. Let's use D as the final. The two whole steps are the E above and the C below. If we use those diatonic pitches and move C and E to D to end it is not a clausula vera! One voice needs to be altered to make a movement by half step. The convention is to raise the tone below the final by a half step. This will make our C become a C#. This gives us the correct movement for a clausula vera and the C# has become a leading tone (because it is one half step under the final.) Note: The unaltered tone a whole step below the final can be called the subtonic.
In Phrygian mode we have a unique situation. The tones above and below are a half step and a whole step. Instead of the half step being located under the final, it is located above the final. Technically we fulfill the definition of a clausula vera, because when the voices move to the final one moves by whole step and the other by half step. But we don't really have a proper leading tone below the tonic. The tone above is sort of like a leading tone. This half step approach from above give a unique flavor to the Phrygian mode the other modes don't have. To illustrate, let's use E as the final. The half step above is F and the whole step below is D. When D and F move to E we have a clausula vera without altering any tones with accidentals, but technically there is not a leading tone.
18th century
Briefly, let's consider 18th century harmony. During that time period the modes were no longer used. Instead harmony used the major/minor system. In that system we can shift the tonic around temporarily using tonicizations and modulations. Without going into too much detail, any diatonic major or minor chord in a given key can temporarily become the tonic. The root of such chords will become the temporary tonic, and the half step below that tone will be the temporary leading tone. For example, in C major the chords D minor, E minor, F major, G major, and A minor can all become temporary tonics. The tones a half step below each of those roots will be temporary leading tones - C# to  D, D# to E, E to F, F# to G, and G# to A.
You can link the 18th century style back to the 16th century style by constructing a clausula vera to lead to any of those tonics. But in modern terminology we don't call it a clausula vera. Instead it is called a secondary or applied dominant and label them with Roman numeral analysis symbols. For example, the temporary leading tone move to D in the key C major would be labelled like: V6/ii to ii.
I packed a lot of theory into a very short description. Take time to digest it and continue to read up on these topics.

the leading tone is a half step below a final/tonic
half step movements in the diatonic scale have a strong sense of pull or movement
resolution and important harmonic movements often involve half step movements
Comment: **the strong sense of movement in the half steps** or energy and tension, yes!
Comment: @Michael Curtis. I understood that the penultimate note should be one semitone from the final note. And I see why the Phrygian mode is special (because it is the only mode where the 2nd tone is one semi-tone away from the 1st tone). What is not clear to me, is why "if approaching from below the leading note should be raised (except in the phrygian mode)". In Phrygian mode approaching the 1st note from bellow would be one tone and therefore the penultimate tone should be raised. The exceptions are Ionian and Lydian modes, where going to the 1st note from bellow is already semi-tone.
Comment: "In Phrygian mode approaching the 1st note from bellow would be one tone and therefore the penultimate tone should be raised." I think this may be the source of confusion. Let's used letters to be clearer. In `E` Phrygian, the lower tone movement `D` to `E` _does not need to be raised._ You don't raise it because the single half step movement needed for the clausula vera is fulfilled by the other voice moving `F` to `E`. Basically in Phrygian the voice leading intervals of the clausula vera are inverted.
Comment: Also, you should be careful with the exact wording "...the leading note should be raised..." we don't raise a leading tone. We raise a _subtonic_ by half step to make it a _leading tone._
Comment: You could ask why the 2nd scale degree - the supertonic - is not _lowered_ in Dorian and Aeolian to make a clausula vera. It would fulfill the basic definition. The only answer I can give to that is: historically it was not the convention.
Answer: Leading note (or tone) refers to the 7th note in the major scale. It's always one semitone below the root, which gives its name to the key. So, in key C, that note's B. Resolution is 'coming home comfortably'. Try playing some notes in key C, and stop on a B. It feels like you're nearly home, but need one more step. That's usually to C.And that's resolution, where tension gives way to a calmer feeling. Then it all feels at rest. That's why we call the B here the leading note, as it literally leads to the C.
The same idea works when we stop on D, the note above C. That needs to be resolved, which it does in a downward motion, D>C. As noted in your text. It's common in jazz to flatten that D to D&fat, giving it a smaller route home to C.
It's also the reason why the harmonic and melodic minors use a different 7th note in their scales from the natural minor - they both use a sharpened leading note, so it works just as it does in major keys.
Comment: thanks for the answer. Do I get it right, "raised" means "to be played"? So, approaching final from below means that leading tone is played before the final. And do you also know why it is not the case for the "phrygian" mode?
Comment: No. 'Raised' means before, the note was a semitone lower than it is when raised. In key A minor, the 7th note is sometimes G (always in natural minr), but it often sounds like it's more effective when it's raised. To G#.
Answer: leading tone in melodies:
The leading tone effect is a pychological phenomen that you can hear and observe (detect) in a melody (melodic representation)
many tunes are ending so so la ti do, or do do do ti do and do re ti do. whereby the halfstep ti_do is the function of the 7_1 leading tone to the tonic. As Michael explains this "rule" has been developed in the modes of church chant and later by the Renaissance composers  in the 16th century. In addition to Tim I want to emphasize that in that time it was not used to notate the alteration of the 7th step, it was up to the performers whether they would raise it to a leading tone in the dorian, aeolian and mixo lydian modes. I didn't live at that time but I was occupied by this questions the last days When did the aeolian mode change to the harmonic minor?.)
leading tone in harmony: harmonic representation
The function of a leading tone can't be explained without the psychological phenomens and terms of
energy and tension:
In all intervals there is a certain degree of dissonance and consonance. (Ernst Kurt)
e.g.:
a major 7th sounds sharply dissonant and has the tension to resolve into a perfect octave. This energy to resolve in a perfect interval is the tension of the leading tone to the final (tonic).
Another example is the suspended 4th of  a major triad 1-3-5 as 4_3 resolving into a consonant third (Fa_Mi) notice: the final "Amen" or the clause fa-mi-re-mi.
The tritone Fa-Ti is also considered as dissonant (so far that it was the devils tone and forbidden - also in your exercises! ;)
in this interval of an augmented 4th is a maximum of tension: Ti leading to Do and Fa leading to Mi.
Initially, the leading-tone effect originates from the last step of the fundamental scale (e.g., B–C in the C major scale), whereby the sense of the critical approach to the goal, of direction, is bound with the seventh scale degree (B), and the sense of dissolution, resolution, is bound with the attainment of the fundamental tone, C, once more. The problem, initially in general terms, focuses on the entrance of an energetic moment that is given in a sounding [moment]. The transference from the sensation of drive to that of nearness is the psychologically basic function that has evolved in dynamic hearing. But with it, the essential is not exhausted; for it is available in two ways: in the drive in the leading tone, but also in its resolution, the leading tone step.
Ernst Kurth
in:
Ernst Kurth at the Boundary of Music Theory and Psychology
by
Daphne Tan
https://books.google.ch/books/about/Ernst_Kurth_at_the_Boundary_of_Music_The.html?id=9y00nQEACAAJ&redir_esc=y
also available as Pdf:
Ernst Kurth at the Boundary of Music Theory and ... - UR Research
https://urresearch.rochester.edu/fileDownloadForInstitutionalItem.action?itemId..


Convert time in hours from numeric to HMS format

Question: How to convert numbers that represent time in hours from numeric to HMS format.
for example:
8.0 -> 08:00:00
0.5 -> 00:30:00
0.25 -> 00:15:00

Comment: Does this answer your question? [How to convert decimal time to time format](https://stackoverflow.com/questions/46167536/how-to-convert-decimal-time-to-time-format)
Comment: Can you please specify the `class` of the desired output - is it `character` or a dedicated time class? If the latter, you have `data.table::as.ITime(x*3600)`.
Comment: ...or `chron::times(x/24)`.
Comment: [Convert decimal hours to HH:MM:SS](https://stackoverflow.com/questions/19721145/convert-decimal-hours-to-hhmmss)
Answer: Another base R option :
x <- c(8, 0.5, 0.25)
format(as.POSIXct(x * 3600, origin = '1970-01-01', tz = 'UTC'), '%T')
#[1] "08:00:00" "00:30:00" "00:15:00"

Comment: Elegant solution.
Answer: Convert to seconds, make use of seconds_to_periods from lubridate and change it to hms
hms::hms(lubridate::seconds_to_period(floor(v1 * 60 *60)))
#08:00:00
#00:30:00
#00:15:00

data
v1 <- c(8, 0.5, 0.25)

Answer: Here is a base R option
h <- x%/%1
m <- floor(x%%1 * 60)
s <- round((x%%1 * 60)%%1*60)
sprintf("%02d:%02d:%02d",h,m,s)

such that
> sprintf("%02d:%02d:%02d",h,m,s)
[1] "08:00:00" "00:30:00" "00:15:00" "03:45:22"

Data
x <- c(8.0,0.5,0.25,3.756)


Change Directory Browsing Page in IIS 7.5

Question: NOTE: This post is tagged ASP.NET but really that's just one of the language (families) in which I could write it.  I really need assistance with configuring IIS (7.5).
I have found many scripts and ideas to effect this but I require that it's not a "drop-in" replacement, as in it must work globally for any possibly directory from one codebase.  The one I'm working with: http://mvolo.com/get-nice-looking-directory-listings-for-your-iis-website-with-directorylistingmodule.
Here is what my server pumps out when I try to go anywhere (after putting web.config
in the main directory):

I've tried registering all the DLLs, etc. to no avail.  I didn't build anything and it's all stored in C:\server\www\etc\aspdirlist\.  Here is a snapshot of my application pool: http://img444.imageshack.us/img444/8196/screenoa.png
Here is the web.config file just for reference:
<configuration>

  <configSections>

  </configSections>

  <system.webServer>
    <modules>
      <remove name="DirectoryListingModule" />
      <add name="DirectoryListingModule" type="Mvolo.DirectoryListing.DirectoryListingModule" />
    </modules>

    <handlers>
      <remove name="StaticFile" />
      <add name="StaticFile" path="*" verb="*" modules="StaticFileModule,DefaultDocumentModule" resourceType="Either" requireAccess="Read" />
      <add name="iconhandler" path="geticon.axd" verb="GET" type="Mvolo.ShellIcons.Web.ShellIconHandler" />
    </handlers>

    <validation validateIntegratedModeConfiguration="false" />
  </system.webServer>

  <system.web>
    <httpHandlers>
      <add path="geticon.axd" verb="GET" type="Mvolo.ShellIcons.Web.ShellIconHandler" />
    </httpHandlers>
    <httpModules>
      <add name="DirectoryListingModule" type="Mvolo.DirectoryListing.DirectoryListingModule" />
    </httpModules>
  </system.web>

  <directoryListing enabled="true" templatePage="~/dirlisting.aspx" />

  <iconHandler enabled="true"
               alwaysUseExtension="true"
               enableClientCaching="true"
               enableServerCaching="true" />

</configuration>

I do not have any security of which I know configured.  Thanks.
Comment: It might be a good idea to edit this post to ask for help with the first link you provided.  If that's what you want... why doesn't it work?
Comment: Can you walk through the exact steps you took to install this module (did you build it from source?), where you put it on the file-system and also tell us how you've configured your site security and application pool? Without this we're going to be pulling at straws.
Comment: @Kev See my update
Answer: It is a .NET assembly, not a COM DLL so you don't need to register it.
What you've got is a pretty generic "I can't load the DLL" error. It could fail to load for a number of reasons. Most likely place to start is the web process can't access where you've stored the DLL. I'd double check that first. I'd also take a gander at the event log, that might have a key detail or two.
If that doesn't help, you can turn on FREB which will probably help you pinpoint the issue.
Comment: I appreciate your input and will look into the issue per your advice.


How can one show that the topology of convergence in measure is separable?

Question: Let $X$ be a polish space equiped with the borel sigma-algebra and a probability measure $\mu$. How can one show that the set of all borel measurable functions $f:X\rightarrow R $  ($R$ being the real numbers), where two a.e. equal functions are identified, equiped with the topology of convegence in measure is separable?
Comment: I've given you *many* references in [my last answer](http://math.stackexchange.com/questions/58018/radon-nikodym-derivative-as-a-measurable-function-in-a-product-space) to you. Fisher-Witte Morris-Whyte (rem 2.4) give a detailed reference to Wheeden-Zygmund, and it is contained in at least three of the other references I've given to you. Please look around a bit before you ask. You can also see Proposition 7 [here](http://dx.doi.org/10.1090/S0002-9947-1976-0414775-X) for a more precise and general result (there polonais = Polish).
Comment: Thank you Theo, you have helped me greatly. I did look around, but didn't find it. I will look in some of your references... BTW I haven't found it in  Wheeden-Zygmund
Comment: Hmmm. Not having one of my most charitable days, I guess... In fact, in the books I mentioned it's in the exercises (e.g. Kechris) and at times not even explicitly mentioned (e.g. in Wheeden-Zygmund), you're right. It's one of those results that people like to leave as an exercise... Sorry about that. Moore's proof of proposition 7 mentioned above suffers a bit from its generality. BTW: I flagged your account for merging with the other one. You could consider registering your account, then it is easier for the software to recognize you.
Comment: @Arnold: I have merged your other account, A_0, into your current account. If you have trouble logging in, or if you accidentally create duplicate accounts, simply flag one of your own questions for moderator attention, and we will help out.
Comment: Thanks (at least 15 characters...)
Answer: Here's an outline of an argument, and it should be easy to fill in the details:

Note that $L_0(X)$ is a metric space e.g. with respect to the metric $\displaystyle d(f,g) = \int \frac{|f-g|}{1+|f-g|}$.
Choose a countable base $\{A_n\}_{n \in \mathbb{N}}$ for the topology on $X$.

Every open set is equal to the union of elements in $\{A_n\}$.
For every measurable set $E$ there is a $G_\delta$-set $G$ such that $\mu(E \triangle G) = 0$, that is $[E] = [G]$ in $L_{0}(X)$.

Show that a non-negative measurable function $f$ is a pointwise monotone limit of simple functions.Hint: Put $B_{k,n} = \{x\in X : 2^{-n} k \leq f(x) \lt 2^{-n}(k+1)\}$ and consider $f_n = 2^{-n} \sum\limits_{k=0}^{2^{2n}}k \cdot[B_{k,n}]$.
Split a general measurable function into positive and negative parts.

Use these observations to build a countable dense set of $L_{0}(X)$.
For completeness and further properties of $L_0(X)$, I recommend Driver's notes on probability Section 12, especially Theorem 12.8 on page 179. (Thanks to Nate Eldredge from whom I learned about these notes).
Edit: In view of Byron's answer, note that Driver's notes contain various forms of the functional monotone class theorem in Part II, Section 8 on pages 111ff. Of course, the main point in both our answers is that there is a countable generating and separating set for the $\sigma$-algebra. The assumption that $X$ be Polish ensures that.
Comment: @Didier: Yes, the formula is a bit nicer this way; but doesn't it obscure the idea somewhat?
Comment: Sorry, mainly I meant to add the *x in X* in the definition of your set B. The other modification is a (possibly not so nice after all) nicety. Theo, really, proceed at your convenience, this is *your* post...
Answer: An alternative is to use the Functional Monotone Class Theorem.
Let $\cal A$ be a countable collection of sets that generates ${\cal B}(X)$,
and put $${\cal K}=\{1_A: A\mbox{ is a finite intersection of }{\cal A}\mbox{ sets }\}.$$
Let ${\cal K}^\prime$ be the (countable!) $\mathbb{Q}$-vector space generated by $\cal K$, and
set $${\cal M}=\{h: k^\prime_n\to h \mbox{ in probability for some }k^\prime_n\in{\cal K}^\prime\}.$$
Then $\cal K$ and $\cal M$ satisfy the conditions of the FMCT, and hence
 $\cal M$ includes all bounded ${\cal B}(X)$-measurable functions. A truncation argument now shows that any ${\cal B}(X)$-measurable function can be
approximated in probability by a sequence in ${\cal K}^\prime$.
Comment: I just wanted to point out that various useful variants of the FMCT are contained in Driver's notes I linked to, see the edit to my post. The dense set $\mathcal{K}'$ is of course the one I had in mind in my answer.


get input value from props

Question: In react they say you can't change props directly (or at least you shouldn't).
But I wonder what should I do if I have an input in component and I have a value that comes as props?
I just wanted to know whether it's okay and what is the better way of doing this?
<code>// product.amount comes from props
<input type="number" value={product.amount} onChange={(e) => onChangeProductAmount(e)}/>
</code>
so it seems like I want to change product.amount when input changes, but it is in props, so I shouldn't do it.
What should I do then?
Answer: Since the props are from the redux, you can change them in redux way only: calling an action creator that will fire an action.
There are packages that do that. I am not familiar with redux-form, but as far as I remember, it is one package that is maintaining the form state in redux. You can implement a similar thing yourself.
I do things differently: I use local state for controlling the input. When the user clicks 'submit', and if the values are valid, I call the action creator which fires the action that changes whatever needs to be changed in the redux store. However, these changes are not reflected directly in the form, as you want to do.
Some time ago I implemented a small app that handles forms this way. You may find it helpful: https://github.com/rahamin1/reactstrap-form
Comment: Yrs they are from parent component. But no, parent component receives these values from redux as props too. Parent component has no state too
Comment: Got it. I just thought that it would be strange to use redux form just for one input I have(
Comment: I didn't like redux form. I prefer to use local state, as I have done in my package. But both approaches are valid, I guess... A matter of taste.

get input value from props


Use YaST through a SOCKS5 proxy

Question: I am ssh'ing into a server (SLES 10 sp2) that does not have access to the internet.
I need to run updates and install new software on this server, preferably using Yast.
So my idea was:

Create a proxy using ssh to a box that has access to the outside.
Setup Yast to use this proxy.

The ssh command I run on the isolated server looks as follows:
ssh -D 9999 username@ip-of-box-with-internet-access

In Yast I go to Network Service > Proxy and enter the following as the HTTP Proxy URL:
http://localhost:9999

When I go to Test proxy settings it fails.
I suspect that Yast does not know it is a SOCKS5 proxy.
Could anyone tell me how I can setup Yast to use a proxy created with ssh?
Any help would be appreciated!
Answer: Ok, so you have a machine on the network that does not have it's traffic routed through a gateway to the internet, but it is on a network with other machines that DO have their traffic routed through a gateway to the internet.
1.) Why is the box isolated? Is it a security risk or is it paranoia? Firewall rules should be sufficient to keep the box isolated from the network while still allowing outbound connections and respondents to those connections.
2.) The easier way may be to use a VPN software as opposed to a proxy. YAST uses a variety of protocols and subtools (i.e. curl) to fetch patches, most of which ignore other systemwide settings.
3.) Instead of a proxy, you may consider using a VPN solution or setting up a local mirror using Novell's patch mirroring application (called 'SMT') and your mirror credentials (both available from the Novell customer center.)
Comment: Thanks for your help. The box is isolated because we're using the infrastructure supplied by our office park and they haven't patched through our external ip-address yet. I'll have a look at VPNs to see if I can use it as a quick temp solution. Thanks again!
Answer: An "HTTP Proxy" and a "SOCKS5 Proxy" aren't the same thing.  That's why YAST doesn't get it :)
A quick fix would be to install Squid or some other HTTP proxy on ip-of-box-with-internet-access , and then do something like ssh -L 12345:localhost:8080 user@ip-of-box-with-internet-access from the server.  I do this all the time.
An example of a quick HTTP proxy would be micro proxy, but I haven't used that and thus can't give a recommendation.  Squid isn't too bad to set up.
Comment: Thanks for your answer. This would explain why my attempted solution did not work. Could you quickly explanation the differences between the two proxies? Thanks!
Comment: They speak a different protocol, is all.  HTTP proxies are made to do HTTP(S) connections only. SOCKS5 is for arbitrary IP connections.  Most HTTP proxies allow you to do a direct connection (CONNECT foo.com:443), but that's somewhat of a hack.

See http://en.wikipedia.org/wiki/SOCKS#Comparison_between_SOCKS_and_HTTP_proxies for more details.

Use YaST through a SOCKS5 proxy


Cramer's rule row reducing?

Question: An example would be:
Let this bas the $Ax = 0$ matrix
$$A=
 \begin{bmatrix}
    3 & 2 & -1   \\
    1 & -4 & 1 \\
    5 & 2 & 0
  \end{bmatrix}
$$
If the b values ares
$$
 b=\begin{bmatrix}
    1    \\
    -2  \\
    1
  \end{bmatrix}
$$
Find the unknowns $Ax = b$.
The determinant of A i got from reducing is:
$$A=
 \begin{bmatrix}
    3 & 2 & -1   \\
    1 & -4 & 1 \\
    5 & 2 & 0
  \end{bmatrix} \leftrightarrow  \begin{bmatrix}
    4 & -2 & 0   \\
    1 & -4 & 1 \\
    5 & 2 & 0
  \end{bmatrix} = -18 \text{ Let the reduced matrix be H}
$$
My question is If I were to use H with cramers rule will I get the right answer?
Like the determinant of this matrix is $-4$. The answer in my textbook is zero.
$$H=
 \begin{bmatrix}
    1 & -2 & 0   \\
    -2 & -4 & 1 \\
    1 & 2 & 0
  \end{bmatrix} = -4
$$
For several examples this worked so I'm wondering if you shouldn't ever take the reduced matrix when using cramers rule or did I make a mistake?
Answer: Just row reducing $A$ in isolation will lead to incorrect solutions. For example, if we keep carrying out row reductions on $A$ we eventually get to
 $$A \leadsto I.$$
Clearly, solutions to $A \bf{x} = \bf{b}$ will be different than solutions solutions to $I\bf{x} = \bf{b}$, no matter what sort of Cramer's Rule trickery we employ.
If you want to make computation easier, you can do row reduction on the augmented matrix $[A ~|~\bf{b}] \leadsto [H ~|~ \bf{\tilde{b}} ]$. The key is that we have to do the same row operations to $\bf{b}$ as well! This is effectively the point of row operations. If we get from $[A ~|~\bf{b}] \leadsto [H ~|~ \bf{\tilde{b}} ]$ by doing row operations, then $A \bf{x} = \bf{b}$ has the some solution vector $\bf{x}$ as $H \bf{x} = \bf{\tilde b}$. We can solve this new system however we like, whether it be Cramer's Rule, row reduction, or even guess and check.

Cramer's rule row reducing?


When to use the term transposed instead of modulation?

Question: I was playing 'In the Hall of the Mountain King' and noticed it modulates from B minor to a fifth above, F-sharp major.

I looked on wikipedia and found it says:

"After being stated, the main theme is then very slightly modified
  with a few different ascending notes, but transposed up a perfect
  fifth (to the key of F-sharp major, the dominant key, but with
  flattened sixth) and played on different instruments."

So it got me wondering when one should say modulate versus the word transpose? I thought transposition implied all notes are shifted by the same pitch. But in Hall of Mountain King they're not the same melody, they're also different in that one is minor and one is major.
Comment: Thank you for at last asking a question about something you've observed in a real piece of music!
Comment: Based on the answers, I'm starting to get the hunch that transposition can result in a mere tonicization instead of a full-blown modulation.
Comment: Maybe not even that.  Does the 'Mountain King' tune repeat starting ON the dominant, or IN the dominant key?   (But don't expect a definitive answer :-)
Comment: The proper musical terminology for a modulation from B Major to F# Major would be that the passage has modulated to the dominant.
Answer: It's almost like the square and rectangle issue.
When music modulates, it just moves into a new key. Music can modulate using prior melodic material, or it can modulate with material that is completely new.
But transposition implies a copying and pasting of earlier material from one key into another key.
In other words, music that is transposed from one key to another also results in a modulation from the first key to the second. However, not every modulation is a transposition, because the music could have modulated without the use of any prior material.
(In other words, a square is a rectangle, but a rectangle isn't always a square.)
There's one added wrinkle in this distinction, but I'm saving it until the end because not all musicians agree: to me, a modulation implies a cadence in the new key. So it's possible that a transposition is not a modulation if the original music being transposed itself never reaches a cadence in the new key. As such, there's no cadence in the new key, and thus not a modulation.
Comment: @foreyez I wonder if that comment is for Michael's answer? But to me, transposition is usually literal, although there can be some slight adjustments (often between what we call "real" and "diatonic" transposition).
Comment: @Richard Umm....  I think a square is always a rectangle actually.  You've got that bit the wrong way round haven't you?
Comment: I thought a transposition meant 100% similar, where all the notes are shifted by the same pitch. but as long as they are similar (even 80% similar for example) you're saying it's considered a transposition.
Comment: "music that is transposed from one key to another also results in a modulation from the first key to the second": not necessarily; "transposition" also refers to just taking some material and moving it to another key without modulation.  The least controversial example of this is probably playing an entire piece in a different key, for example because it is being played by an instrument with a different range.
Answer: Modulate means a change of key. Something needs to make clear the music is in a new key. Traditionally a cadence in a new key does the job. Importantly to the comparison of terms a modulation can be achieved with all new thematic material.
In transposition some musical material is repeated, but at a different position pitch-wise. There is both chromatic and diatonic transposing so the pitch shifting isn't necessarily by the exact same interval for each note. Either way the important thing is that some thematic material is repeated. Note the difference with modulation where repeating material isn't part of the definition.
Given that transposition can be diatonic, it won't necessarily result in a key change. (You may notice that a diatonic transposition is the same as a diatonic melodic sequence.)
If a thematic passage was chromatically transposed, it could result in a key change, but I suppose it really depends on how the passage moves, and also the length of the passage. Some might end up resulting in a sequence. This <code>[V6/5 of IV|IV]|[V6/5 of V|V]</code> is both a transposition of the material in brackets and a harmonic sequence. On the other hand in a simple sonata form the "second theme group" (the part of the exposition in the dominant key) can often be simply transposed down a fifth to the tonic during the recapitulation. (If that sonata stuff isn't familiar, try reading some reviews of sonata form and then look at L. Mozart's Nannerl Notebook which as many examples in small scale pieces.) Transposition in the recapitulation is a nice example where it has formal, structural meaning and a modulation, a key change, is the result.
So, there is some overlap in the meanings, but modulation doesn't really say anything about the handling of thematic material while transposition does tell specifically we are modifying thematic material.
Answer: 'Modulation' is the process of getting to a different key. When we get there, we've 'modulated'.
A particular musical element, repeated literally at a different pitch, is 'transposed'.
It's not stretching the definition of 'transposed' too much to let it cover an ALMOST literal copy, and a different mode as well as a different pitch.
Comment: The modulation of the meaning of modulation is interesting in itself. Originally, "modulation" was used to describe the B and Bb usage in chant (600AD or so); this seems in agreement with the words as used in radio. In tonal music, a short secondary dominant was called a modulation (like in radio) but that left a key change without a name. Now the key change is a "modulation" while a secondary dominant is a "tonicization."
Comment: @ttw B flat wasn't invented until 1000 AD or so.
Answer: The word "modulation" isn't so much the problem (see my comment to another answer) as that there are degrees of tonal change. A simple II7-V7-I probably didn't really modulate to the dominant key. Tovey discusses the difference between cadencing "in" a key and cadencing "on" a note. A chord pattern like I-IV-I-I7-iv-II7-V followed by  I-IV-V-I-V-I doesn't really modulate; it cadences "on" the V. A bigger change would be I-IV-I-I7-iv-II7-V followed by V-VI7-II7-V does seem a bit like a modulation "in" the dominant. Schoenberg suggests that one must "neutralize" the original key to be considered a modulation. "Neutralization" means (according to Schoenberg) emphasizing notes in the new key that differ from those in the old key. Modulating from C to G means emphasizing F# (especially where F would be used without modulation.)
Answer: Transposing is moving whole passages up a certain interval. The singer cannot sing the passage in E Major so you transpose it a diminished fifth up to the key of Bb. Transcribing is related to Transposing. Here you find a violin piece written in the treble clef, but you want to play it on your Viola, but you don't auctually want to change the pitches. So you see ah this crotchet is the E above middle C, you find the E above middle C on the alt clef and you write the note there. The music does not really change, you just transcribe it so that it makes sense on the viola.
Modulation is a harmonic device where there is movement between keys. You can modulate just about to any key imaginable but some are harder to make convincing than others, although I don't think any are impossible.
You start in C Major, you move to a minor you end on C Major again. Music is all about movement, the moving between keys (modulation) is one of the ways you make music interesting.


labeling leaf nodes in tree (XSLT 1.0)

Question: I've got an xml, that I want to process, and simply label in turn each leaf node, flip or flip in turn, unless some condition is met.
take for example this xml
<root>
   <tx>
      <alloc>
         <event>a</event>
         <event>b</event>
      </alloc>
      <alloc>
         <event>c</event>
         <event>d</event>
         <event>d1</event>
      </alloc>
   </tx>
   <tx>
      <alloc>
         <event>e</event>
         <event>f</event>
         <event>g</event>
      </alloc>
   </tx>
</root>

and lets say we want to label each event node, flip then flip then flip, etc UNLESS the event is "e"
note the labelling of the events is independent of the hierachy.
so...
<root>
   <tx>
      <alloc>
         <event flip="true">a</event>
         <event flip="false">b</event>
      </alloc>
      <alloc>
         <event flip="true">c</event>
         <event flip="false">d</event>
         <event flip="true">d1</event>
      </alloc>
   </tx>
   <tx>
      <alloc>
         <event flip="true">e</event>
         <event flip="false">f</event>
         <event flip="true">g</event>
      </alloc>
   </tx>
</root>

so node "d1" is "true" AND "e" stays "true" before carrying on, because of our rule.
now...I CAN see a way to do it, but it doesnt feel as if it fits XSLT very nicely.
If I were to do this in some functional language I would recursive process the tree, basically cloning it, passing the value of flip/flop through each recursive function so something like...
so for example the tx processing template would look something like this (this is made up)
   <xsl:template match="tx" mode="label">
      <xsl:param name="flip_flip"/>
      <xsl:variable name="allocations">
         <xsl:apply-templates select="alloc" mode="label">
            <xsl:with-param name="flip_flip" select="$flip_flop"/>
         </xsl:apply-templates>
      </xsl:variable>
      <xsl:copy-of select="$allocations"/>
      <xsl:variable name="new_flip_flip" select="alloc/event/@flip[last()]"
      <xsl:apply-templates select="following-sibling::tx[1]" mode="label">
         <xsl:with-param name="flip_flip" select="$new_flip_flip + 1"/>
      </xsl:apply-templates>
   </xsl:template>

i.e. process each element in turn, pull out the last calculated flip flop value, and then process the next one.
feels ugly in xslt.
another option would be to count the number of preceding events, take off the number of exceptions and then work out mod 2 if flip is true or false.
again, feels clunky, and computationally expensive.
Comment: achch sorry...you, of course have to have 1 hand tied behdin your back...i.e. XSLT 1.0
Answer: Would something like this work for you:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="event">
    <xsl:variable name="i">
        <xsl:number count="event[not(.='e')]" level="any" />
    </xsl:variable>
    <event flip="{boolean($i mod 2)}">
        <xsl:apply-templates/>
    </event>
</xsl:template>

</xsl:stylesheet>

Comment: I've not used number/count/any...let me look that up
Comment: ok, this works for my example, but it would have to count preceding event nodes, not all.
Comment: Please explain exactly what you mean by "preceding".
Comment: we label in turn, in document order, in your example if there are two e then wouldnt it simply go false/true/false/true?
Comment: ah...I think your solution does work...I just don't understand it!...let me look closer
Comment: ah no this isnt right...let me try to explain
Comment: this is "counting" in the context of a parent node....it needs to count in the context of the document.
Comment: I believe you are mistaken. Please provide an example of input where this fails. (Not in a comment, of course.)
Comment: P.S. You can use `` to see the actual count.
Comment: yeah I've done the $i thing...let me just check the updated example fails
Comment: I've updated the exampe..."d1" is true....the subsequent "e" is false...it should be true too
Comment: and the {$i} shows a count in the context of its parent element
Comment: I am getting a different result: https://xsltfiddle.liberty-development.net/nbiE1a5
Comment: its because I'm an idiot!!!!...did you just add an "any"?
Comment: I had it in my original answer. I have mistakenly removed it in an edit and restored it 5 minutes later. You must have fallen in the crack.
Comment: how would i do it if the rule was, if the NEXT event was an "e"?
Comment: I guess (!) you could count `event[not(following::event[1]='e')]`? If not, post a new question with a proper example.
Comment: actually ignore me...the original answer works for me, thanks v much

labeling leaf nodes in tree (XSLT 1.0)


Interpretation of non-statistically significant Tests

Question: I ran an A/B test on a website. I get a p-value of 0.45: not statistically significant. There is a 4.5% difference in variation A vs. the control (B). Assume the confidence interval is -8%

So, here is the conclusion that I'm making, though I know it's flawed: "Well, the result was not statistically significant. BUT, if I'm tasked with making a decision between variation A and control, why wouldn't I go with the control at 55% significance and 4.5% lift?"
What is inherently flawed with this interpretation? What would be the proper way to assess this kind of result?
Comment: The classic, frequentist interpretation of your results is that if there were no difference between A and B, you'd be highly likely to see a result like this. To talk about the probability of effect A being higher than effect B, you need to adopt [Bayesian](https://en.wikipedia.org/wiki/Bayesian_inference) viewpoint and add prior beliefs over effect A and effect B.
Comment: The experiment lacks the statistical power to clearly ascertain whether A or B is better. What to do? Following Bayesian decision theory, your choice of A or B would also incorporate (i) prior beliefs about A or B and (ii) your preferences over risk.
Comment: Thanks Matthew. So I think that makes sense. So, basically, here is what we can conclude: There is little evidence that the perceived results are due to the experiment. Instead, the perceived difference is due to chance. So, if we see a 4.5% lift, we're running the risk (albeit, seemingly, a lower risk because we see a p value of .55, compared to a p value of say, .9), but a risk that the page we roll out is in fact NOT a winner, and is in fact a loser as seen in the confidence intervals. Am i right in that interpretation?
Comment: Sal, thanks for the response. Can I answer your rhetorical questions? There are no practical costs to switching between A/B. Theoretically, it would be bad practice to switch, so we'd only keep one of the variations. 4.5% lift is material if significant, but it didn't go significant, so the lift isn't accurate. An extended test CAN be run - perhaps that's something else I can use to staple the point.
Comment: Sorry, let me clarify: let's say the P value was .45, and the outcome is conversion rate for the website (purchased a product). Does that help?
Comment: Not yet. Can you answer the rest of my questions?
Comment: I thought I did. Sorry about that. So, also, assume the 4.5% lift is for the variation A OVER the control. So, because the p value is >.5, we see a 4.5% lift in the experiment (to conversion rates), and we have to decide between the control and the experiment in terms of pushing a variation which drives higher conversion rates
Comment: In your experiment, which did you estimate was higher? A or the control B? Do you measure one more precisely than the other?
Comment: No, same measurements were used across both. I guess, I don't want to get into any kind of practice of declaring a winner without hitting that p value < .05. But, I have some pressure other individual to push variations even at p<.5 if the lift is there, and i'm trying to educate on the risks of doing so, and how it's flawed, but I can't figure out the best way to communicate this
Comment: Rhetorical questions:  Are there practical costs to switching between A and B, in terms of time or money?  Would it be a bad practice to flip-flop between A and B repeatedly?  Is a 4.5% difference enough to matter?  Can an extended test be conducted?
Comment: So I guess to answer your question, the actual risk is low (no lives at danger, just some dollars lost due to online conversion rate). Any difference observed to this particular metric is huge - even if the lift was .5%, because the numbers we're talking about for revenue is huge. Assume the change is low level of effort, too
Answer: Imagine B is the current system with a clickthrough rate of 3%. You test A on 1 person and observe 100% clickthrough. Should you change the whole website to A?
Why might we choose B even if A performs better in the data:

We have prior beliefs that B is better (and our experimental results aren't strong enough to overturn those prior beliefs).

Example: Let A be yellow, blinking text. I have strong priors that blinking text is worse in 999/1000 cases; it will take powerful evidence to convince me blinking text is better (rather than a spurious result). Similarly, if a disease is more rare than a test is accurate, most positive test results will be false positives.

We are risk averse and measure B more precisely than A.

Example: B is the extensively tested drug ibuprofen and A is a new, seemingly effective but potentially deadly painkiller. Even if we estimate A as better, we wouldn't deploy it widely until we're confident A is consistently safe.

Applying Bayesian decision theory, point (1) treats the parameter as a random variable and brings prior beliefs into the analysis. Point (2) is that we may be risk averse (which can be formalized using expected utility).
Additional complications:

Adjustment costs (eg. implementation costs or user learning costs) would raise the bar for making a change. For example if the change is irreversible, the hurdle to change may be especially high.
In a multi-period setting, making the the change has an additional payoff in that we get to learn more about the change (which may have value).
Comment: "Thus the decision of A or B should be mostly based on factors other than the data" - I think this statement in your comment is of incredible importance as sort of a lay explanation of what it means to make Bayesian decisions in the face of indecisive data - might be worth incorporating explicitly into your answer.
Comment: This is solid reasoning. I think you're ultimately saying that there IS no inherit problem with making that decision if you're aware of the risks and adjust for those using bayesian interference.
Comment: @optimizer I think that's right. The big concern is that people people misinterpret a 51% probability that A is better as a 100% probability that A is better. (eg. when candidate B narrowly wins even though candidate A had a statistically tiny lead in the polls, people often say, "The polls were wrong!" even though the polls were actually right in that the election was close.)
Comment: @optimizer Basically, you learned from your experiment that effect sizes are probably small relative to your measurement error: your data doesn't tell whether A or B is better. Thus the decision of A or B should be mostly based on factors other than the data.
Comment: This is exactly what I thought. So essentially, the data is saying there isn't enough evidence one way or the other to prove one is better than the other. There is inherently a risk in "picking" one versus the other. But, the data is simply saying "inconclusive" - you should pick a variation based on OTHER factors
Answer: You are misinterpreting the meaning of a p-value.  While I preferentially would advocate for a Bayesian method if money is involved, if a behavior is involved then I may take the Frequentist approach.  If your p-value is $p<.45$ where $\mu_A=\mu_B$, this tells you that if the null is true, then there is less than a 45% chance of seeing a result as extreme or more extreme than what you saw.  That means you have roughly a coin toss chance of seeing this data.
Under the three main interpretations of probability your inference would be as follows.

Fisherian likelihoodist-- nothing was learned, it is time to go onto finding a different choice because there is no real evidence against the null
Frequentist inference--the null is in the acceptance region so it makes no sense to treat option A or option B as different
Bayesian inference--without more specific information no calculations can be performed, but knowing that the p-value is less than 45% tells me that there is a slight amount of evidence of one hypothesis over the other.

Your decisions though may be different.

Frequentist decision theory--You accept the null and behave as if the null is true.  This would imply, if you have a default such as B, then you should do B.  However, in the absence of additional costs, you shouldn't care if you did A or B.
Bayesian decision theory--you should base your acceptance or rejection criterion and the combination of the probabilities and the costs or utility of the choices.  Since one option is slightly more probable than the other, if you control for costs, you should choose the one with greater probability of being true.  If that choice is costly, you should factor in the cost of a false positive and a false negative.  That relative cost should constitute your odds criterion for acceptance.  If that criterion is passed, then you do the more costly choice.
Answer: Without going Bayesian and bringing priors into the equation, a null result suggests that population parameters you infer about may be equal. Depending on the distribution, they may even be directionally reversed (ie, even if your sample statistic A > B, in the population B may be > A). If we were allowed to make decisions based only on the raw directionality of the sample statistics, there'd be no reason for a statistical test.


Unreal engine 5 crash when opening new project

Question: So whenever I create a new project (in my case the thirdperson template) and the shaders start compiling, it crashes after few seconds:
(Updated with the debbuging symbols)
<code>Unhandled Exception: EXCEPTION_ACCESS_VIOLATION reading address 0x0000021ad00205d0

nvwgf2umx
nvwgf2umx
nvwgf2umx
nvwgf2umx
nvwgf2umx
nvwgf2umx
nvwgf2umx
nvwgf2umx
nvwgf2umx
nvwgf2umx
nvwgf2umx
nvwgf2umx
D3D12Core
D3D12Core
dxgi
dxgi
dxgi
dxgi
dxgi
dxgi
dxgi
RTSSHooks64
UnrealEditor_D3D12RHI!FD3D12Viewport::PresentChecked() [D:\build\++UE5\Sync\Engine\Source\Runtime\D3D12RHI\Private\D3D12Viewport.cpp:639]
UnrealEditor_D3D12RHI!FD3D12Viewport::Present() [D:\build\++UE5\Sync\Engine\Source\Runtime\D3D12RHI\Private\D3D12Viewport.cpp:739]
UnrealEditor_D3D12RHI!FD3D12CommandContextBase::RHIEndDrawingViewport() [D:\build\++UE5\Sync\Engine\Source\Runtime\D3D12RHI\Private\D3D12Viewport.cpp:939]
UnrealEditor_RHI!FRHICommand<FRHICommandEndDrawingViewport,FRHICommandEndDrawingViewportString2035>::ExecuteAndDestruct() [D:\build\++UE5\Sync\Engine\Source\Runtime\RHI\Public\RHICommandList.h:855]
UnrealEditor_RHI!FRHICommandListBase::Execute() [D:\build\++UE5\Sync\Engine\Source\Runtime\RHI\Private\RHICommandList.cpp:438]
UnrealEditor_RHI!<lambda_d9c5c35f8ce97cb91cdbe1d4918d55a5>::operator()() [D:\build\++UE5\Sync\Engine\Source\Runtime\RHI\Private\RHICommandList.cpp:744]
UnrealEditor_RHI!TGraphTask<TFunctionGraphTaskImpl<void __cdecl(void),0> >::ExecuteTask() [D:\build\++UE5\Sync\Engine\Source\Runtime\Core\Public\Async\TaskGraphInterfaces.h:1348]
UnrealEditor_Core!FNamedTaskThread::ProcessTasksNamedThread() [D:\build\++UE5\Sync\Engine\Source\Runtime\Core\Private\Async\TaskGraph.cpp:760]
UnrealEditor_Core!FNamedTaskThread::ProcessTasksUntilQuit() [D:\build\++UE5\Sync\Engine\Source\Runtime\Core\Private\Async\TaskGraph.cpp:649]
UnrealEditor_RenderCore!FRHIThread::Run() [D:\build\++UE5\Sync\Engine\Source\Runtime\RenderCore\Private\RenderingThread.cpp:332]
UnrealEditor_Core!FRunnableThreadWin::Run() [D:\build\++UE5\Sync\Engine\Source\Runtime\Core\Private\Windows\WindowsRunnableThread.cpp:149]
</code>
This happens on both 5.1 and 5.0 versions. I need to fix this since otherwise I can't use the engine.
Thanks a lot for any answers.
Comment: Can you install the debugging symbols with the engine (there is an option for it in the launcher)? This way, we can actually see what crashes.
Comment: @MaxPlay Sure, will do this.
Comment: @MaxPlayUpdated the log with the debugging symbols.
Comment: Looks to me like your solution works well in this case. If it's really a shader compiling or rendering issue, you usually have two options: Revert your graphics driver or change the API. You could also try the latter and use DirectX11 if you have the option. Sometimes it is an issue that comes from epic, sometimes from your machine. That's probably the best advice I can give you.
Answer: I found a solution. It's not ideal and I didn't find the root source of the problem but it works.
So it was caused by the latest nvidia graphics driver https://www.nvidia.com/download/driverResults.aspx/198401/en-us/.
I reverted back to this version and works well now:
https://www.nvidia.com/download/driverResults.aspx/197461/en-us/


Minimum size of .ts file

Question: I'm writing a script to test some .ts files. At this point, I want to judge if each .ts file has any content. So I need to know the minimum size of a 360p quality .ts file (let's say it's just 0.00001s). So can anyone tell me the minimum size of a .ts file in 360p quality? Or is it just 0Byte?
Answer: 0 bytes is "valid" in that it is a TS file that exists, but does not contain content. The minimum size of a 'parseable' TS file will be 188 bytes. TS is broken into 188 bytes packets and padded if smaller. But a 188 byte TS file will not be playable. You at least need a PAT and PMT. But it still does not contain any video (or audio) The smallest video frame I have ever created was 603 bytes (64x64 pix) here. Plus we need at minimum TS header(4) + AF/PCR(8) + PS Header w/ PTS(13). 603 + 4 + 8 + 13 = 628 / 188 =~ 3.34. Rounded up to 4 packets plus PAT and PMT. 188 * 6 = 1128 bytes. A single audio packet will not likely take more that one packet, so add another 188 for that.
Comment: Exactly what I need. Thank you.

Minimum size of .ts file


Find if an array can produce a sum n with k number of elements

Question: Given an int array that may contain duplicates. I need to find out whether the array can produce a sum with k elements?
I'm trying to use recursion for now but I'm not getting anywhere at the moment. I have a problem with getting the base-case right.
    static boolean groupSum(int[] nums, int k, int sum) {

            if (sum == 0)
                return true;

            if (k > nums.length || sum != 0)
                return false;
            if (groupSum(nums, k, sum - nums[k - k] - nums[k - k + 1] - nums[k - k + 2]))
                return true;
            if (groupSum(nums, k, sum - nums[k - k + 1] - nums[k - k + 2] - nums[k - k + 3]))
                return true;

            else
                return false;

        }

Answer: The base case of your recursive method is incorrect: sum == 0 isn't a sufficient condition you also have to check whether k == 0. If the sum is 0 but you still have to use a few more elements then the result true is incorrect.
The recursive part of the method has some mistakes in it as well. The number of elements summed up k never gets decremented.
Also, you have to track a position in the array. I mean you need to iterate over the array. And while iterating for each element there are only two options: apply it (decrement the k and subtract current value from the sum) or discard it. In both cases, you have to increment the position that you are passing as an argument.
That is how it could be fixed:
    public static boolean groupSum(int[] nums, int k, int pos, int sum) {
        if (sum == 0 && k == 0) {
            return true;
        }
        if (sum < 0) {
            return false;
        }

        boolean result = false;
        for (int i = pos; i < nums.length; i++) {
            boolean takeElement = groupSum(nums, k - 1, pos + 1, sum - nums[i]);
            boolean discardElement = groupSum(nums, k, pos + 1, sum);
            result = takeElement || discardElement;
            if (result) { // a combination that yield the target sum was found
                break;
            }
        }
        return result;
    }

There's another option how to implement this method. But caution: it will be slower and significantly increases memory consumption.
This approach requires creating a copy of the given array with a length decremented by 1 at each recursive method call and pass it as an argument. In this version, an element at position 0 is always used when the method is called, therefore it doesn't require to track the position in the array. The main logic remains the same: a new element can be used either to contribute the sum or can be discarded.
    public static boolean groupSum(int[] nums, int k, int sum) {
        if (sum == 0 && k == 0) {
            return true;
        }
        if (sum < 0 || nums.length == 0) {
            return false;
        }

        boolean takeElement = groupSum(Arrays.copyOfRange(nums, 1, nums.length), k - 1, sum - nums[0]);
        boolean discardElement = groupSum(Arrays.copyOfRange(nums, 1, nums.length), k, sum);

        return takeElement || discardElement;
    }

    public static void main(String[] args) {
        // sum of 1, 2, 3, 4, 5 yields 15 - expected true
        System.out.println(groupSum(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}, 5, 0, 15));
        // it's impossible with only one element - expected false
        System.out.println(groupSum(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}, 1, 0, 10));
        // sum of 4, 5, 6 yields 15 - expected true
        System.out.println(groupSum(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}, 3, 0, 15));
    }

output
true
false
true

Comment: Can it be done without tracking pos?
Comment: @Ernest In order to examine the array contents you have to iterate over the array.  There's no way around it.
Comment: @Ernest As an alternative, at each method call you can pass the copy of the array with a length decremented by 1. But it will be slower and will increase memory consumption.


Playing one hand loudly and the other quietly

Question: I'm currently learning to play Comptine d'un autre été from Yann Tiersen (Sheet music(pdf) - youtube video) and when I play starting from the 13th bar I barely hear the notes my right hand plays.
Obviously I should play my left hand less loud but this seems a hard thing to do for my brain as it seems to play both hands in the same volume, and when in some occasions it works to play some of them quietly, the timing is off between the notes.
What are some good techniques to learn to play one hand less loud than the other whilst the timing stays correct?
Comment: The sheet music you link has some notation problem. Look at the bars 17-24: there are 15 semiquavers to a bar, grouped 4-4-4-3. Is it really 15, or is there a missing semiquaver, or should the last semiquaver be a quaver ?
Comment: I've used that music; it's pretty awful.  There's the missing semiquaver, but the notes and rhythms in the melody aren't all correct.  In particular, in the 3rd system, the rhythm should be Dotted-quarter, eighth-tied-to-a-half....
Answer: In general, I feel that practicing with scales is a good way to learn technique like this, be it crescendoing through a passage, playing at different dynamics, playing with different rhythms, etc.
For instance, play an octave of a scale with your right hand loudly.  Then play an octave of the scale with your left hand, but softly.  Then practice playing both hands together at a slow tempo.  As you are able to do this without thinking so hard about it, increase the tempo.  It is important to learn to be able to do this without concentrating on the dynamic with which you play each and every finger.
Once you can do this, extract the method out to the passage you are playing with. Theoretically, it will become easier for you to move directly towards practicing with both hands together at a slow tempo and increasing.
This is also the method I use for learning to play different rhythms with each hand.
Answer: First of all, you should become comfortable with both hands separately and together.  Then play really, really slowly.  Stare at the hand that should be louder and focus all of your mental attention on it.  Play it as loudly as possible, while playing the other hand as softly as possible.  If you have little to no experience in this, just get the feel of it by playing one note/chord at a time.  When you can play one note in each hand at opposite extremes of the dynamic spectrum, you'll be on your way!  This is difficult for everyone, but if you practice diligently, it will become second nature after a while.
Comment: It is seldom a good idea to stare at your hands but a good thing to have a mental representation or where they are.
Answer: I suggest slowing it way down, so that you have enough time to focus on what your hands are doing.  Practice playing the piece (it's simple enough that you probably don't need another exercise), with grossly exaggerated dynamic differences (try fortissimo right hand, and pianissimo left hand).  As you get the hang of it, bring the right hand down to a more musical volume (that is, only slightly louder than the left hand).
Good luck!
Answer: I found that the easiest way to gain independence of the hands in terms of dynamics is to do this:
assuming that you know the notes, play only on top of the keys, without pressing the key with the hand that needs to play softly (like the accompaniement) and play regularly with the other hand. If you can't do it together just play separate first. I call this "faking" with the hand that needs to play softer. After you practice like this for a bit, then let the hands play normally and you'll see how it will come naturally.
Answer: I had a complete inability to play different dynamics with each hand. Whatever one hand tried to do, the other followed. I had to take it down to the very basics to learn this.
What I did was play one note on each hand in harmony (e.g. C and G). I just kept repeating these two notes, while varying the dynamics. Then I would keep my left hand playing softly while trying to vary the loudness in my right hand. Then bring my right hand back to playing softly and start varying with the left hand while keeping the right hand on soft. Practicing this I started to get a feel for controlling dynamics in the hands separately.
When I started this exercise, I had a tendency to lift my finger and bang it on the piano when trying to play loudly. With a little practice I was able to control dynamics by pushing hard or soft, without the finger leaving the key.
Practicing this for just ~30 minutes I had enough control that I could start practicing with songs (e.g. play cords softly with my left hand, while playing melody loudly with my right hand).
Hopefully this exercise can help others.
Answer: To the many excellent suggestions already given, I'll add something with a bit of a different slant.  It's very important to work from both sides of the problem.  If you can imagine exactly how you want the music to sound, you can make it sound that way.  The connection between your ideas and your hands is very intimate, and I went to no end of trouble trying to "get the notes" without focusing on the music.  As I have said many times before (and this for me is a very hard-won lesson), the notes come from the music, the music doesn't come from the notes.
So, work very hard to avoid an idea such as "I will learn to play the right hand louder than the left hand, and then I will learn to play my piece."  (This does not mean avoid exercises; I'll get to that in a minute.)  Visualize what you want in the piece, put your hands on the piano, and start to play, with the idea of making your vision a reality. When something happens that is inconsistent with your vision, stop and do it over again.  If it doesn't happen after a few tries, come back to it later with a fresh mind.  If it still isn't happening, it's time to look at purely technical reasons and focus more on exercises for a bit.  Again, while doing exercises, visualize exactly what you want to hear, and focus on making that vision a reality.  Always do that.
Answer: You could try playing something that's easy enough that you don't have to think about the notes (like an easy piece you learned when you were starting), play it slowly or with a metronome if necessary, and concentrate on making one hand louder than the other. Once you start getting the idea, you can work on transferring it to the piece that you are learning.
Answer: There are several difficulties in this piece, but let's concentrate on what I consider the main one for the purpose of your question.

The left hand has alternatively one and two keys to press. The first challenge is to produce an even volume on the left hand. Fortunately, the isolated note is situated almost always inside the interval of the two notes of the chord.
A first exercice would be, for each combination (2-notes chord, succeeding note), to first play the chord, keep the keys pressed, then repeatedly, gently and regularly press the inside note. Change the attack of the note you repeat, making it louder or softer at will, staccato or as plain as possible, say, twenty times in a row.  While doing this, visualize mentally your hand (do not watch it directly) and how you are using the strength and muscles of the fingers playing the chord to control, balance, and soften the attack of the isolated middle note. Then switch: press the isolated note and repeatedly strike the next chord, with the same ideas (variations of strength and speed of the fingers, use of the pressed finger's muscles and joints to control and soften the attack of the chord). Begin these two exercices very slowly, but not too lightly, try to have your upper body relaxed, your elbow and your wrists not too high, your fingers not too curved and do not forget to make small pauses to rest, not to overwork your fingers and wrist.

Now combine this exercice on the left hand with a slow regular semiquaver routine on the right hand (two notes on the right hand for one note on the left). Then add variations of strength, speed of finger descent and height inspired by the piece.
The next day, study a passage of the piece. Practice for a few bars the left hand alone in a cycle and then add the little passages from the right. Try to lift the fingers of the right hand a little higher, depress them a little faster, and keep them on the keys a little longer, as if you insisted on the note.
Answer: Generally, the hands are held at the same height as each other. If you lower the palm of one hand, only slightly, that hand should not play as loudly, even if your fingers are already resting on the keys before you play them, you can still lower your palm a small amount.
To play notes louder, as others have already suggested, try lifting your fingers off the keys, so your fingers are not touching them at all.
You will not need any concious techniques given enough practice.


I'm using the formula below and want to find the length of γ

Question: I want to find the length of the smooth curve $γ(t)$ from $t = 0$ to $t = \pi/4$
I'm using the formula for γ:
$$l(γ) = \int_a^b|\gamma'(t)|\,dt$$
apologies I can't work out how to format that correctly.
I have $ \gamma'(t) $
I am now aware this is incorrect but am struggling to amend it myself
I'm not sure how to apply this into the formula without it just integrating back into its original form?
Any help or identification of areas where I've made a mistake would be really useful.
Comment: Your computation of the derivative is not correct.
Comment: Please look up Mathjax, to format your equations
Comment: Thanks for responding, whereabouts have I made the error?
Comment: How do you get $\sin(it+1)$? Or $\cos(t-i)$?
Comment: I used the derivative of γ(t)
Comment: What's mean $\sin\color{red}{t}(t)$? This seems to be a typo.
Answer: Note that if $$\gamma(t)=e^{it}+t(\sin(t)-i\cos(t))=e^{it}+t\sin(t)-it\cos(t)$$
so, you have that $$\gamma'(t)=\color{blue}{ie^{it}}+\sin(t)+t\cos(t) +it\sin(t)-i\cos(t). \quad [1]$$
Now, since that for all $t\in \mathbb{R}$, we have that $$e^{it}=\cos(t)+i\sin(t)$$
The, you can re-write $[1]$ as $$\gamma'(t)=\sin(t)+t\cos(t)\color{blue}{-\sin(t)}+it\sin(t)-i\cos(t)\color{blue}{+i\cos(t)}.$$
Using that for all $z\in \mathbb{C}$ we have that $$|z|=\sqrt{\operatorname{Re}(z)^{2}+\operatorname{Im}(z)^{2}}$$
So, you have that \begin{eqnarray*}
|\gamma'(t)|&=&\sqrt{(\sin(t)+t\cos(t)-\sin(t))^{2}+(t\sin(t)-\cos(t)+\cos(t))^{2}}\\
&=&\sqrt{t^{2}\cos^{2}(t)+t^{2}\sin^{2}(t)}\\
&=&\sqrt{t^{2}(\cos^{2}(t)+\sin^{2}(t))}\\
&=&\sqrt{t^{2}}, \quad \text{since that} \quad \forall x\in \mathbb{R}: \quad \cos^{2}(x)+\sin^{2}(x)=1.
\end{eqnarray*}
Finally, you need calculate $$\ell(\gamma(t))=\int_{0}^{\frac{\pi}{2}}|\gamma'(t)|dt.$$
Comment: Thank you so much for that response it's really helpful, if possible could you explain the final calculation? That's the part I was initially struggling with?
Comment: Note that you have $\sin t-\sin t=0$ and similar for $\cos$. Also use $\sin^2t+\cos^2t=1$ and you will get a very simple expression for $\gamma'$
Comment: @IKSmith I added more details on what you requested.
Comment: That's brilliant thank you so much for your help!
Comment: You're welcome.


Erro no index e ListBox

Question: Este é meu código:
 public static ListBox listBox1 = new ListBox();
 Form2.Globals.listBox1.Items.Add(Form2.Globals.din);
 Form2.Globals.listBox1.Items.Add(Form2.Globals.dequi);
 Form2.Globals.listBox1.Items.Add(Form2.Globals.demer);
 Form2.Globals.listBox1.Items.Add(Form2.Globals.debai);
 Form2.Globals.listBox1.Items.Add(Form2.Globals.deval);
 Form2.Globals.listBox1.Items.Add(Form2.Globals.denin);
 Form2.Globals.listBox1.Items.Add(Form2.Globals.degoo);
 Form2.Globals.listBox1.Items.Add(Form2.Globals.dehub);
 Form2.Globals.listBox1.Items.Add(Form2.Globals.debqui);
 Form2.Globals.listBox1.Items.Add(Form2.Globals.debmer);
 Form2.Globals.listBox1.Items.Add(Form2.Globals.debbai);
 Form2.Globals.listBox1.Items.Add(Form2.Globals.debval);
 Form2.Globals.listBox1.Items.Add(Form2.Globals.debnin);
 Form2.Globals.listBox1.Items.Add(Form2.Globals.debgoo);
 Form2.Globals.listBox1.Items.Add(Form2.Globals.debhub);

 StreamWriter save = new StreamWriter(savegame);
 {
      for (int i = 0; i < Form2.Globals.listBox1.Items.Count; i++)
      {
            save.WriteLine(Form2.Globals.listBox1.Items[i].ToString());
      }
      save.Dispose();
      save.Close();
 }

 var din2 = Globals.listBox1.Items[0]; // <- line error
 Globals.din = Convert.ToDouble(din2);

Erro:
An unhandled exception of type 'System.ArgumentOutOfRangeException'
  occurred in System.Windows.Forms.dll
Additional information: InvalidArgument=Value '0' não é um valor
  válido para 'index'.

Printscreen/Screenshot.
Comment: Esse código é bem complicado e faz coisas que não deveriam, mas o problema é que deve faltar o `Form2` antes de `Globals.listBox1.Items` na linha do erro. É só o que vejo de diferente que poderia causar o erro.
Answer: Note que em todo o código está usando uma lista chamada Form2.Globals.listBox1, portanto essa variável listBox1 está em Form2.Globals. Mas no momento que vai acessar a variável, o nome não está completo e aparentemente existe uma variável com mesmo nome principal existe em outro local, e aí esta variável não tem elementos nela. Na linha do erro está acessando Globals.listBox1. É diferente.
O código tem vários outros problemas que parece funcionar, mas está errado.

Erro no index e ListBox


How do you calculate the vertical angle from a 3d rotation matrix or a quaternion?

Question: I've got the rotation matrix and quaternion of a mobile device. I'm trying to calculate the vertical angle from it. What I'm trying to get is for example 0° if the device is held in portrait mode and 90° in landscape mode.
Any help would be appreciated. I'm sorry if this was asked before, I don't have any experience with this and didn't really know what to search for.
Comment: Try starting [here](https://en.wikipedia.org/wiki/Euler_angles).
Answer: There are many sign conventions associated with rotation matrices, quaternions, and Euler angles. It can get confusing.
But hopefully you just want the angle $\theta$ between the space-fixed $z$-axis and the body-fixed $z'$-axis, and presumably your $3\times3$ rotation matrix $\mathbf{A}$ is defined such that $\mathbf{r}'=\mathbf{A}\cdot\mathbf{r}$ (or the same equation, but with the transpose of $\mathbf{A}$). In that case $\cos\theta=A_{33}$ because it is just the scalar product between the original, and rotated, $(0,0,1)$ vectors. So take the arccos of the $3,3$ element of the rotation matrix.
I advise you to double check that this makes sense for your definitions and coordinate systems!


What is the file type for the final java application?

Question: I finished a small program. What is the standard file type for the final application written with Java, so it can be run on any computer, easily and without any computer knowledge?
I've been told it's JAR, but Eclipse for example is an .exe file.
What's the standard file type for big, normal applications in Java?
Are most applications distributed in JAR, or rather in .exe or something else?
Comment: The concept of a _file type_ is system dependent. Not all operating systems have typed files.
Answer: Serious desktop applications are packaged with platform-specific launchers, which are not written in Java. The launcher must first find out how to run the JVM installed on the system, and then pass it either the path to the executable JAR to run, or the complete classpath along with the name of the main class.
In other words, "it's complicated".
Answer: Most desktop applications are distributed using .jar files. A .exe is windows-specific, and non-portable across different operating systems. It's easy to find installers (or "launchers") that will simplify the distribution of a Java program in other platforms, but anyway you'll find that .jar files are the usual packaging mechanism.
If you have a small, simple Java program the easiest approach to distribute it would be to pack it in a .jar, making sure to make it executable. And remember, the computer where your code is expected to run must have installed some version of Java, be it JRE or JDK.
Answer: Desktop java applications are usually distributed as jar files.
JRE can launch a runnable jar file using -jar param.
Answer: You have one of several options:
1 - Create an executable jar file.  By providing information in a manifest within the jar file users can simply execute the jar file by however system-dependent means exist for their OS.
2 - Write a batch file or shell script to invoke the JRE against your jar file (and specify command line parameters for, eg: the main class, the classpath, JVM options, etc.)
3 - Use a tool like jexepack or jsmooth to wrap your Java code within a native executable.  I've only ever used these to create Windows binaries - there may be other options for other platforms but shell scripts are typically easier to work with here.