Linking Qt app with CMake and Visual Studio

Question: I'm trying to build a simple test Qt app using CMake and Visual Studio 2019.
I'm basing my tests on this example: https://github.com/jasondegraw/Qt-CMake-HelloWorld
I opened the CMakeLists.txt file with Visual Studio. During build i get:
<code>[7/7] cmd.exe /C "cd . && "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -E vs_link_exe --intdir=CMakeFiles\helloworld.dir --rc=C:\PROGRA~2\WI3CF2~1\10\bin\100183~1.0\x86\rc.exe --mt=C:\PROGRA~2\WI3CF2~1\10\bin\100183~1.0\x86\mt.exe --manifests  -- C:\PROGRA~2\MICROS~2\2019\COMMUN~1\VC\Tools\MSVC\1422~1.279\bin\Hostx86\x64\link.exe /nologo CMakeFiles\helloworld.dir\helloworld_autogen\mocs_compilation.cpp.obj CMakeFiles\helloworld.dir\main.cpp.obj CMakeFiles\helloworld.dir\mainwindow.cpp.obj CMakeFiles\helloworld.dir\helloworld_autogen\EWIEGA46WW\qrc_resources.cpp.obj  /out:helloworld.exe /implib:helloworld.lib /pdb:helloworld.pdb /version:0.0  /machine:x64 /debug /INCREMENTAL /subsystem:windows  D:\Program\Qt\5.13.1\mingw73_64\lib\libQt5Widgetsd.a D:\Program\Qt\5.13.1\mingw73_64\lib\libQt5Guid.a D:\Program\Qt\5.13.1\mingw73_64\lib\libQt5Cored.a D:\Program\Qt\5.13.1\mingw73_64\lib\libqtmaind.a kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib advapi32.lib && cd ."
  FAILED: helloworld.exe
  cmd.exe /C "cd . && "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -E vs_link_exe --intdir=CMakeFiles\helloworld.dir --rc=C:\PROGRA~2\WI3CF2~1\10\bin\100183~1.0\x86\rc.exe --mt=C:\PROGRA~2\WI3CF2~1\10\bin\100183~1.0\x86\mt.exe --manifests  -- C:\PROGRA~2\MICROS~2\2019\COMMUN~1\VC\Tools\MSVC\1422~1.279\bin\Hostx86\x64\link.exe /nologo CMakeFiles\helloworld.dir\helloworld_autogen\mocs_compilation.cpp.obj CMakeFiles\helloworld.dir\main.cpp.obj CMakeFiles\helloworld.dir\mainwindow.cpp.obj CMakeFiles\helloworld.dir\helloworld_autogen\EWIEGA46WW\qrc_resources.cpp.obj  /out:helloworld.exe /implib:helloworld.lib /pdb:helloworld.pdb /version:0.0  /machine:x64 /debug /INCREMENTAL /subsystem:windows  D:\Program\Qt\5.13.1\mingw73_64\lib\libQt5Widgetsd.a D:\Program\Qt\5.13.1\mingw73_64\lib\libQt5Guid.a D:\Program\Qt\5.13.1\mingw73_64\lib\libQt5Cored.a D:\Program\Qt\5.13.1\mingw73_64\lib\libqtmaind.a kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib advapi32.lib && cd ."
  LINK Pass 1: command "C:\PROGRA~2\MICROS~2\2019\COMMUN~1\VC\Tools\MSVC\1422~1.279\bin\Hostx86\x64\link.exe /nologo CMakeFiles\helloworld.dir\helloworld_autogen\mocs_compilation.cpp.obj CMakeFiles\helloworld.dir\main.cpp.obj CMakeFiles\helloworld.dir\mainwindow.cpp.obj CMakeFiles\helloworld.dir\helloworld_autogen\EWIEGA46WW\qrc_resources.cpp.obj /out:helloworld.exe /implib:helloworld.lib /pdb:helloworld.pdb /version:0.0 /machine:x64 /debug /INCREMENTAL /subsystem:windows D:\Program\Qt\5.13.1\mingw73_64\lib\libQt5Widgetsd.a D:\Program\Qt\5.13.1\mingw73_64\lib\libQt5Guid.a D:\Program\Qt\5.13.1\mingw73_64\lib\libQt5Cored.a D:\Program\Qt\5.13.1\mingw73_64\lib\libqtmaind.a kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib advapi32.lib /MANIFEST /MANIFESTFILE:CMakeFiles\helloworld.dir/intermediate.manifest CMakeFiles\helloworld.dir/manifest.res" failed (exit code 1120) with the following output:
D:\Download\mocs_compilation.cpp.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: struct QMetaObject * __cdecl QObjectData::dynamicMetaObject(void)const " (__imp_?dynamicMetaObject@QObjectData@@QEBAPEAUQMetaObject@@XZ) referenced in function "public: virtual struct QMetaObject const * __cdecl MainWindow::metaObject(void)const " (?metaObject@MainWindow@@UEBAPEBUQMetaObject@@XZ)
</code>
and a load more LNK2019 errors after. The only thing that is different is that I commented out the "-Wall" line in the CMakeLists.txt.
As far as I can tell, this example has all the required elements to be working.
The only thing I noted is that I installed Qt 5.13.1 msvc2017 and I'm running msvc2019 but a thread on the Qt forum pointed out that those two versions are binary compatible.
Any thoughts on this problem?
Update: as @Tsyvarev pointed out, when Visual Studio runs CMake, it uses the MinGW kit that is installed along the msvc one. Where can I tell Visual Studio which Qt kit is the correct one?
Comment: "The only thing I noted is that I installed Qt 5.13.1 **msvc2017**" - Eh? The link path `D:\Program\Qt\5.13.1\mingw73_64\lib\libQt5Widgetsd.a` suggests that you have QT built with **MinGW**, not with Visual Studio (aside `mingw` subdurectory there is a suffix `.a` of the library, but Visual Studio uses native Windows library's suffix, `.dll`). Actually, I find this funny (=strange) that CMake chooses `.a` library even if it works under Visual Studio. Probably, you have passed some additional options for CMake?
Comment: I have both the mingw and msvc kits installed. I naively assumed that Visual Studio would pick the msvc one :/ Where would I specify which Qt install to use? (Edit: I'm using right click "generate cmake cache" so I don't specify anything as far as I know)
Comment: Hm, if you have `QT_DIR` variable in the CMake cache, which is set to `D:\Program\Qt\5.13.1\mingw73_64`, then change this variable accordingly.
Comment: The entry is now called Qt5_DIR, I also edited entries looking like Qt5Widgets_DIR and others for the other modules. It now runs. But having to edit the cache for every new module and having to do it again when the cache gets cleared doesn't seem right. I'll update the question.
Comment: Instead of `*_DIR` variables you may set `CMAKE_PREFIX_PATH` variable to proper path. But that should be done with **clean cache** (that is, before the first "Configure"). See more about that variable in [my answer](https://stackoverflow.com/questions/34795816/hinting-findname-cmake-files-with-a-custom-directory/34797156#34797156) to the other question.
Comment: Thank you, I managed to set this variable in Visual Studio.
Answer: Thanks to @Tsyvarev for pointing out the problem and fix.
To sum up what happened:

When Visual Studio runs CMake it doesn't hint that it should use MSVC
CMake ended up finding the MinGW kit installed on the system

To fix it in a (as far as I can tell) durable way:

Right the CMakeList file and clear the CMake cache
Right click the CMakeList file and select "CMake Settings"
Then click on "Edit JSON" in the top right
You can add CMake variables in the JSON

<code>{
  "configurations": [
    {
      "name": "x64-Debug",
      "generator": "Ninja",
      "configurationType": "Debug",
      "inheritEnvironments": [ "msvc_x64_x64" ],
      "buildRoot": "${projectDir}\\out\\build\\${name}",
      "installRoot": "${projectDir}\\out\\install\\${name}",
      "cmakeCommandArgs": "",
      "buildCommandArgs": "-v",
      "ctestCommandArgs": "",
      "variables": [
        {
          "name": "CMAKE_PREFIX_PATH",
          "value": "D:\\Program\\Qt\\5.13.1\\msvc2017_64",
          "type": "STRING"
        }
      ]
    }
  ]
}
</code>
Note that this is the part that defines the variable:
<code>    "variables": [
        {
          "name": "CMAKE_PREFIX_PATH",
          "value": "D:\\Program\\Qt\\5.13.1\\msvc2017_64",
          "type": "STRING"
        }
      ]
</code>
You should update the value accordingly. The rest of the file is generated by Visual Studio.

Generating the CMake cache should now use the correct kit

Thanks again to @Tsyvarev.


Drawing an HTML table via D3 doesn't update existing data

Question: I'm using D3 to draw an HTML table, and things work great on enter.  When I add a new item to my data collection, it adds the new item to the table correctly.
The problem is whenever I update an existing object (an object in the backgroundJobs collection below) within the collection.  When I re-run the D3 code to sync up the table, it does not work.  Nothing happens.
Here's the code:
var visibleColumns = ['Name', 'Start', 'End', 'Status', 'Metadata', 'Errors'];

var table = d3.select('#jobs').append('table');
var thead = table.append('thead');
var tbody = table.append('tbody');

thead.append("tr")
    .selectAll("th")
    .data(visibleColumns)
    .enter()
    .append("th")
    .text(function (column) { return column; });

function tick() {
    var rows = tbody.selectAll("tr")
        .data(backgroundJobs, function(d) {
            return d.name;
        })
        .enter()
        .append("tr");

    var cells = rows.selectAll("td")
        .data(function(row) {
            return [{column: 'Name', value: row.name},
                    {column: 'Start', value: row.startedTimestamp},
                    {column: 'End', value: row.endedTimestamp},
                    {column: 'Status', value: row.isRunning},
                    {column: 'Metadata', value: ''},
                    {column: 'Errors', value: row.errorMsg}];
        })
       .enter()
        .append("td")
        .text(function(d) { return d.value; });
}

setInterval(tick, 500);

Answer: Please refer to the cool explanation of the data joins.
When you call
tbody.selectAll("tr").data(some-new-data);

You actually get 3 selections: 'enter' (whith the new elements not present in the DOM yet), 'exit' (those present in DOM but not longer present in the data) and 'update' which contains nodes that are already in DOM and still have the data assigned to them via the .data call above.
In general, for 'enter' selection you create new nodes, for 'exit' you need to remove the old ones, and for 'update' you just change attributes - may be with some nice transition effect.
See the updated 'tick' function code.
function tick() {
    var rows = tbody.selectAll("tr")
    .data(backgroundJobs, function(d) {
        return d.name;
    });

    rows.enter()
        .append("tr");

    rows.order();

    var cells = rows.selectAll("td")
        .data(function(row) {
            return [{column: 'Name', value: row.name},
                {column: 'Start', value: row.startedTimestamp},
                {column: 'End', value: row.endedTimestamp},
                {column: 'Status', value: row.isRunning},
                {column: 'Metadata', value: ''},
                {column: 'Errors', value: row.errorMsg}];
        });

    cells.enter()
        .append("td");

    cells.text(function(d) { return d.value;});

    cells.exit().remove();

    rows.exit().remove();
}

See the Demo (backgroundJobs is switched on timer between the two hard-coded datasets).
Comment: why include the call 'rows.order();'?
Comment: So that the table rows order matches the order of jobs in the backgroundJobs array.
Without explicit sorting all new jobs ('new' in terms of data join - those that form the 'enter' selection) are appended to the end of the table.
Answer: The rows variable will be a selection that will only contains nodes if enter() is not empty. The second time around, if you haven't added any new rows into backgroundJobs, the data bind will update the existing nodes and enter() won't contain any nodes (meaning rows won't contain any nodes).
You can get around this by holding a reference to the update selection taking advantage of the fact that nodes appended to the enter selection get added to the update selection behind the scenes:
var rows = tbody.selectAll("tr")
    .data(backgroundJobs, function(d) {
        return d.name;
    });

rows.enter()
    .append("tr");

Now rows will refer to a selection that contains all previously existing and newly added nodes.
Answer: In order to be able to add and delete rows dynamically, this strategy works for me:
// ROW MANAGEMENT

// select all tr elements
var tr = this.table.select("tbody").selectAll("tr").data(cur_data);

// exit rows
tr.exit().remove();

// enter rows
var trEnter = tr.enter().append("tr");

// CELL MANAGEMENT

trEnter.selectAll("td").data(function(d) { return d3.values(d); }).enter().append("td").text(function(d) { return d; });

// select all td elements
var td = tr.selectAll("td").data(function(d) { return d3.values(d); });

// exit cells
td.exit().remove();

// enter and update/add data to cells
td.enter().append("td");
td.text(function(d) { return d; });


how to disable the particular step in step header in angular mat stepper

Question: I have  a scenario when it is edit-mode ,I need to disable the second-step in step header of mat-horizontal stepper, I have tried to use the pointer events , but it is disabling the entire step header. I have also tried other ways but haven't found any solution.
 <mat-horizontal-stepper linear #stepper>
    <mat-step [stepControl]="receiptInfoData" errorMessage="Receipt Info is required.">
      <ng-template class="label" matStepLabel> Receipt Info</ng-template>
      <app-receipt-info (receiptInfoData)="completeReceiptInfoEvent($event,stepper)" [receiptData]="receiptInfoData"></app-receipt-info>
    </mat-step>

    <mat-step  errorMessage="Case Info is required.">
      <ng-template  matStepLabel>Case Info</ng-template>
      <app-case-info  *ngIf="receiptInfoData.purchaseOrder" (caseData)="completeCasesInfoEvent($event, stepper)" [receiptWithCaseInfoData]="receiptInfoData"></app-case-info>
    </mat-step>
    <mat-step  errorMessage="Report Damage Container is required.">
      <ng-template class="label" matStepLabel>Report Damage Container </ng-template>
      <app-damage-info  *ngIf="receiptInfoData.purchaseOrder" (damageInfoData)="showReceiptSummary($event,stepper)" [receiptWithDamageInfoData]="damageInfo"></app-damage-info>
    </mat-step>
    <mat-step errorMessage="Summary is required.">
      <ng-template matStepLabel>Done</ng-template>
      <app-receipt-summary *ngIf="receiptInfoData.purchaseOrder" [receiptSummary]="receiptInfoData"></app-receipt-summary>

 <button mat-button matStepperNext size="sm" style="margin: 15px;" (click)="resetStepper(stepper)" class="mat-red" >Reset</button>

    </mat-step>
  </mat-horizontal-stepper>

Comment: So you want to disable only second step of the stepper but not all of them? I think more clarification is needed
Comment: yes i just want to disable the second step in step  header
Answer: Use a linear stepper with completed=false steps. When the user presses the button, it completes the step and move to the next one.
<mat-horizontal-stepper linear #stepper>
  <mat-step completed="false">
    <ng-template matStepLabel>Step 1</ng-template>
    <app-some-child (nextClicked)="nextClicked($event)" ></app-some-child>
  </mat-step>
  <mat-step>
    <ng-template matStepLabel>Step 2</ng-template>
    <app-some-other-child></app-some-other-child>
  </mat-step>
</mat-horizontal-stepper>

export class AppComponent implements OnInit {

  @ViewChild('stepper') stepper: MatStepper;

  nextClicked(event) {
    // complete the current step
    this.stepper.selected.completed = true;
    // move to next step
    this.stepper.next();
  }
}


Bidirectional OneToMany/ManyToOne mapping in OpenJPA JPQL problem

Question: I have two classes with a bidrectional relationship:
@Entity
@Access(AccessType.FIELD)
@Table(name="ROOM")
public class Room {
    @Id
    @GeneratedValue
    @Column(name="ROOM_ID_PK", updatable=false, nullable=false)
    private int id;
    @Column(name="NAME", nullable=false, unique=true)
    private String name;
    @OneToMany(mappedBy="room", cascade={CascadeType.ALL})
    private final Set<Wall> walls;
    ...
}

@Entity
@Access(AccessType.FIELD)
@Table(name="WALLS")
public class Wall {
    @Id
    @GeneratedValue
    @Column(name="WALL_ID_PK", updatable=false, nullable=false)
    private int id;
    @Column(name="NAME", nullable=false, unique=true)
    private String name;
    @ManyToOne
    @JoinColumn(name="ROOM_ID_FK", referencedColumnName="ROOM_ID_PK")
    private Room room;
    ...
}

I'm running mysql -- what looks like a sane set of tables is generated:
ROOMS: INT ROOM_ID_PK, VARCHAR NAME
WALLS: INT WALL_ID_PK, VARCHAR NAME, INT ROOM_ID_FK

However when I execute a JPQL query
SELECT w FROM Wall w, Room r WHERE w MEMBER OF r.walls AND r = :room

I get an error:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException:
Property 'wall' threw exception; nested exception is <openjpa-2.0.1-r422266:989424
nonfatal user error> org.apache.openjpa.persistence.ArgumentException:An error occurred
while parsing the query filter "SELECT w FROM Wall w, Room r WHERE w MEMBER OF r.walls
AND r = :room". Error message: No field named "walls" in "Room". Did you mean "name"?
Expected one of the available field names in "mypackage.Room": "[id, name]".

For some reason 'walls' is not being seen as a field of the Room class. This code works in hibernate -- I'm attempting to migrate to OpenJPA but came across this error. I've confirmed that both classes are defined in my persistence.xml.
Answer: I am not 100% sure if it is the cause, but making the walls variable final looks strange for me.
So remove the final marker, and try it again.


Help proving $\sum_{n\le x}{\ln{n}}=x\ln{x}-x+O(\ln{x})$

Question: Just learning a bit about big O notation and have come across this exercise.
The notation used is  $$\sum_{n\le x}{\ln{n}}=x\ln{x}-x+O(\ln{x})$$
and I am assuming that is equivalent to
$$\sum_{n=1}^{x}{\ln{n}}=x\ln{x}-x+O(\ln{x}).$$
I know that
$$\int_1^x{\ln{t}}\operatorname{dt}=x\ln{x}-x+1$$
so I feel like I am almost there, just not entirely sure how to make the connection, in particular exactly how the big O comes into this.
Edit: I should make it clear, I can see (I have done a quick sketch) that the summation is an 'overshoot' of the integral, and that the difference between the summation and the integral is bounded by something, but I'm not sure how to get that it is precisely $\ln{x}$.
Also I have no idea what tags to use, feel free to change them.
Answer: Hint: Estimate the integral from above and below with step functions of step size 1, then subtract the integrals of the two step functions.
Edit: Here are more details, in response to questions in the comments. The estimate you get is (for an integer $x$): $$\sum_{n=1}^{x-1}\ln n<\int_1^x\ln t\,dt<\sum_{n=2}^x\ln x.$$
You can start the latter sum at $n=1$, since the first term is zero anyhow, and evaluating the integral in the middle you can rewrite all this as
$$\Bigl(\sum_{n=1}^x\ln n\Bigr)-\ln x<x\ln x-x+1<\sum_{n=1}^x\ln x.$$
It may be best to rewrite the left inequality and move it to the right:
$$x\ln x-x+1<\sum_{n=1}^x\ln x<x\ln x-x+1+\ln x,$$
and noting that $1+\ln x=O(\ln x)$ as $x\to\infty$. The extra $1$ makes no difference since it is negligible compared to $\ln x$ anyhow. For this, you only need the ridiculously week estimate $1+\ln x<2\ln x$, which holds for $x>e$.
Comment: Just to verify, are these appropriate estimations?
Above: $\sum_{n=1}^{x}{\ln{n}}$. Below: $\sum_{n=1}^{x-1}{\ln{n}}$.
In which case the difference is $\ln{x}$
Comment: Correct, almost. Actually, you should start the "above" sum at $n=2$, but it doesn't matter in this case since $\ln 1=0$.
Comment: Yeah ok that makes sense. I'm unsure how to use this though... Does this show that the error in the 'above' sum (which is less than the difference between 'above' and 'below' sums) is always less than $\ln{x}$? How can I make this precise, and what happens to the '$+1$' from the integral?
Comment: I added the necessary details (I hope!) to the answer. I did not want to do so at first, as you would need to do the main part of the work yourself. But now that you have shown some effort, it's a different matter.


How to set the base URI for the grunt server

Question: I've used a yeoman webapp generator to build my app.
During the development, I simply used grunt serve to preview the app.
Now that I'm ready to deploy my app, I've found out that the production environment has a different root context than the development one. In other words, instead of:
http://base:port/

I'm forced to use
http://base:port/subdir_name/

This, of course, breaks some stuff.
Is there any way to configure the connect server that grunt uses, to take this new root context as it's base URI?
Answer: I'm not sure if you've found a solution already, but I managed to work around this by using grunt-connect-proxy capability of rewriting it's redirects. This is what my config looks like:
connect: {
  options: {
    port: 8001,
    // Change this to '0.0.0.0' to access the server from outside.
    hostname: '0.0.0.0',
    livereload: 35729
  },
  proxies: [
    {
        context: '/subdir_name/',
        host: 'localhost',
        port: 8001,
        https: false,
        xforward: false,
        rewrite: {
          '^/subdir_name': ''
        },
        headers: {
            'x-forwarded-server': 'Grunt Localhost development'
        }
    }
  ],
  livereload: {
    options: {
      open: true,
      middleware: function (connect, options) {
        if (!Array.isArray(options.base)) {
            options.base = [options.base];
        }

        // Setup the proxy
        var middlewares = [];

        middlewares.push(connect.static('.tmp'));
        middlewares.push(connect().use(
            '/bower_components',
            connect.static('./bower_components')
          ));
        middlewares.push(connect().use(
            '/app/styles',
            connect.static('./app/styles')
          ));
        middlewares.push(connect.static(appConfig.app));
        middlewares.push(require('grunt-connect-proxy/lib/utils').proxyRequest);
        // Serve static files.
        options.base.forEach(function(base) {
            middlewares.push(connect.static(base));
        });

        // Make directory browse-able.
        var directory = options.directory || options.base[options.base.length - 1];
        middlewares.push(connect.directory(directory));
        return middlewares;
      }
    }
  },

Comment: Seems interesting. I went the brute-force route of converting all the absolute paths in my app into relative ones. In retrospective, this is how I should have done it in the first place. Still, it's nice to know that this is actually possible. Thank you :)


Homeomorphism between pairs of letters

Question: How can I check if the pairs of letters T and K , E and W are homeomorphic or not?
Answer: Look at the cut points.
They'll cut those letters into two or three pieces.
Determine the number of three piece cut points in each letter.

Homeomorphism between pairs of letters


IFFT of a Gaussian power spectrum - Python

Question: I want to calculate the Inverse Fourier Transform of a Gaussian power spectrum, thus obtaining a Gaussian again. I want to use this fact to check that the IFFT of my Gaussian power spectrum is sensible, in the sense that it produces an array of data effectively distributed in Gaussian way.
Now, it turns out that the IFFT must be multiplied by a factor 2*pi*N, where N is the dimension of the array, in order to recover the analytic correlation function (which is the Inverse Fourier Transform of the power spectrum). Can someone explain why?
Here is the piece of code that first fills an array with the Gaussian power spectrum and then does the IFFT of the power spectrum.
power_spectrum_k = np.zeros(n, float)
for k in range(1, int(n/2+1)):
    power_spectrum_k[k] = math.exp(-(2*math.pi*k*sigma/n)*(2*math.pi*k*sigma/n))

for k in range(int(n/2+1), n):
    power_spectrum_k[k] = power_spectrum_k[int(k - n/2)]

inverse_transform2 = np.zeros(n, float)
inverse_transform2 = np.fft.ifft(power_spectrum_k)

where the symmetry of the power spectrum comes from the need to get a real correlation function, at the same time following the rules for the use of numpy.ifft (quoting from the documentation:
"The input should be ordered in the same way as is returned by fft, i.e., a[0] should contain the zero frequency term, a[1:n/2+1] should contain the positive-frequency terms, and a[n/2+1:] should contain the negative-frequency terms, in order of decreasingly negative frequency".)
Comment: If your analytical result is the one obtained by integration, you need to remember that ifft is a discrete fourier transform, not the continuous one. Your question is probably answerable just by looking at the definition of the discrete transforms: https://en.wikipedia.org/wiki/Discrete_Fourier_transform
Answer: The reason is the Plancherel theorem, which states that the Fourier transform conserves the signal's energy, i.e., the integral over |x(t)|² equals the integral over |X(f)|². If you have more samples (e.g., caused by higher sampling rate or a longer interval), you have more energy. For that reason your IFFT result is scaled by a factor of N. Your factor depends on hand on the convention of Fourier Integral used, as @pv already noted. On the other hand, on the length of your interval, since integral over the power of the sampled and the continuous interval need to be the same.
Answer: I'd recommend using an existing library for an fft. Not as its particularly difficult but there are some well optimised solutions.
Try scipy http://docs.scipy.org/doc/scipy/reference/fftpack.html or my favourite fftw https://hgomersall.github.io/pyFFTW/


Analysis of a few bars in Bach's BWV 895

Question: The overall key of this piece in A minor (it is Bach's prelude from Prelude and Fugue in A minor BWV 895). Here is what I understood :
At the end of bar 6, there seems to be a change of key: this might be conceivable because of the very last G natural and the 2nd inversion of the dominant seventh chord without its root (D, F, B) which belongs to C major. That being said, the fact that C is not part of bar 7's second chord creates a kind of ambiguity: it could thus conceal an E minor triad which, followed by a D natural, could lead very well to the following chord: a nice A major triad. However, neither the chord progression C major-A major nor E minor 7-A major sound very baroque to me.
For the next part, I am convinced that this A major triad goes on a D minor modulation (with the leading tone of the scale be that C♯). The next chords belongs entirely to D minor (1st inversion of its triad, then A major [dominant triad] as bar 8's second chord). And so on until the first chord in bar 9, G major triad followed by a F (to form the dominant seventh of C major) which naturally leads to a nice C major triad, whose dominant is immediately substitued with an A. Finally, this takes us back to our first key (A minor), as the G♯ reappears on the last beat of bar 9 – back home!
I have to say that I find myself a bit confused about the whole thing and I would like to read a more precise and accurate analysis of these 4 measures.
Comment: The second inversion of the dominant seventh chord without a root is usually analyzed as the first inversion of the viiº chord, or, in minor keys, of iiº.  The diminished trial is most commonly seen in first inversion.
Comment: So this chord is not really a reason to think that we have modulated towards C major?
Comment: Possibly not -- I am analyzing it in my head so it's slow going.  I'll post an answer when I have something more concrete.
Answer: In brief

m6 = a minor
m7, m8 = d minor
m9 = a minor.

My more complete analysis goes like this (measure-beat):

                     incidental
                    |-----------|
m6-1  -2      -3.0  -3.5     -4.0  4.5
Bm    E7/B    A     Dm/A     A     Am
ii    V[6/4]  I     iv[6/4]  I     i

          transition toward D minor
         |--------------...
m7-1     -2                   -3         -4
Bm7b5/A  Em7                  A7         Dm/F
ii[4/2]  v[6/5] = ii[6/5]/iv  V[4/2]/iv  iv[6]

    Cadence in Dm
|------------------
m8-1    -2     -3
Em7     A7b9   Dm
ii7/iv  V7/iv  iv

 Brief tonicization of C major    Transition back to A minor
|-----------------------------   |--------------------------
m9-1                      -2      -3                -4
G7                        C       B-7b5             E7/B
IV[6/5]/iv = V[6/5]/bIII  bIII    vii7/III = ii7/i  V[4/3]
Comment: Thank you! However, I don't understand why you have written "III" under the C major triad (m9-2) : if we are in C major, shouldn't it be "I"?
Comment: @Lava We're never really "in" C major; the visit there is too brief to be considered a modulation. However, I should have labeled it bIII rather than III. I was thinking in terms of A minor when I wrote "III" Ultimately it's the same reasoning I used in labeled D minor as iv rather than i — to maintain the perspective of A as the home key. Since any analysis is interpretive, another person might label things differently, treating the D minor or C major passages as modulations.
Comment: Understood, thank you.
Answer: I agree with Aaron's broad analysis that measures 7 and 8 are in D minor, but I disagree on the detail.  Essentially this is built from sequences of 7-6 suspensions, a very common way to deal with a descending scale.
Starting with measure 5, we have Dm, Dm7, E7/D, Am/C.  In figured bass terms, E7/D, a seventh chord in third inversion, is figured 4/2 (with the sixth implicit), and Am/C, a triad in first inversion, is figured with a 6.  In Roman numeral analysis, therefore, this is V(4/2) to i6.
In measure 6, we start with an ornamented 7-♯6 suspension over B, namely A-G♯.  You could analyze this as Bø7 or Bm7 going to E7 in the second inversion or as G♯º (viiº) in first inversion with a suspension of the root, or just as an inverted E7 with a 4-3 suspension (in lead sheet terms, Esus4add7/B to E7/B), depending on how much weight you want to give to which of the sixteenth notes.  For Bach it's just a 7-6 suspension; he was not fond of Rameau's theory that led eventually to Roman numeral analysis.
The third beat is difficult to describe with Roman numeral analysis, but it's not so complicated with figures.  The soprano has ♯3-4-♮3 while the tenor has ♮6-5.  With a raised third at the end of the measure, this would be a standard cadence to D minor, but the lowered third sends us somewhere else.  If we look at it in chordal terms, it's Am7, setting us up for the third-inversion Bø7 on the downbeat of measure 7.
Continuing with measure 7 in figures, we have (4/2) followed by either 6 or (6/4), then (4/2) and 6.  Three things suggest that the second beat is a 6 chord (Em/G) instead of a (6/4) chord (C/G).  First, second-inversion triads are very rare.  Second, it reflects the repeating nature of the harmonic and contrapuntal sequence, and, third, it gives us a nice circle-of-fifths progression of Bø7-Em-A7-Dm (where the seventh chords are both in third inversion and the triads are both in first inversion).  It is also noteworthy that this is a sequence of inverted 7-6 suspensions — that is, the suspended voice is the bass.
In measure 8, we have Em7, A (or A7 or A7♭9, again depending on how much weight you want to give to the 16th notes) and Dm, a firm cadence on the minor subdominant, where we stay for two beats.
Measure 9 is also hard to describe in functional terms.  I make it out roughly as (with the second and third chords as eighth notes) G/B - C/B - Am - Bø7 - G♯º/B, which gives figures of 6 - (4/2) - (nothing) - 7 - ♯6.
You could call the first half of the measure ♭VII (or V/III) to III7 to i, but again the C/B is more of a suspension in the bass than a structural harmony.  Reducing it to quarter notes, I'd call the second beat i, giving us a fairly standard i-viiº6-i progression liberally embellished with suspensions.
Comment: Precise and very enlightning – thank you!


Is it possible to have "Perfect Tempo"

Question: Perfect pitch is an acknowledged musical skill - the ability to hear a note and name it.
Is there a corresponding skill that applies to tempo, to be able to hear music playing and say precisely what the bpm is?
For people claiming this skill, what level of accuracy is possible?
Comment: Some people are demonstrably good at counting seconds, based on knowing their resting pulse, so this should be do-able, but I don't think it is equivalent to Perfect Pitch.
Comment: Knowing differences less than 5 BPM would require an immense amount of practice or some innate skill I've never heard of. However, when I was younger and a snare drummer in a DCI group, I could pretty consistently tell what a tempo was +/- 5 BPM. Most people here are talking about lengths over time, but ideally you'd be able to tell after just hearing 2 beats, and that's pretty difficult (but can be done).
Comment: In the professional circles I'm in this phenomenon  (which seems real) is referred to as "Perfect Tick."
Comment: I just counted out six seconds while listening to Taylor Swift's *Blank Space* and noted it was about two measures, so eight beats in six seconds means about 80 bpm. The actual tempo is 96 bpm, so that's one way anyone can get a sense of the tempo of a song without having any skills, but clearly it's not super accurate. If I had counted ten seconds and multiplied by six it might have helped. Counting seconds and beats at the same time is **not** easy, though.
Comment: @DrMayhem I can actually count seconds with 99% accuracy just from a sense of time (and occasionally testing my self against a watch as a bored child...), no heart rate needed :)
Comment: I doubt this is possible unless you know the length of the notes (e.g. A semibreve in 120BPM would last the same amount of time as a minim in 60BPM). Btw "semibreve" is a "whole note" and "minim" is a "half note" in case you're not familiar with the UK system.
Comment: EDIT: although you could figure out the time signature and then the tempo from that I suppose.
Comment: Same experiment with *Shake It Off* gives me an estimate of 120 - 130 bpm and the actual tempo is.... 160 bpm. Clearly I count seconds way too fast. Still, one could practice counting seconds (maybe I need to say "one Mississippi" instead of "one one thousand") more accurately and do all right, I expect.
Comment: https://youtu.be/Cj4y0EUlU-Y?t=49s Feynmann has some interesting insights; he did it by how many do I count in one minute (e.g. I count to 48 in one minute) instead of trying to count out one minutes' worth of time.
Comment: @DrMayhem Would this not be equivalent to Relative Pitch, listening to a rhythm prior and then associating to that.
Comment: I'm not sure if this is entirely related, but I knew a guy who could tell you the time of day to within about a minute, without looking at clock or watch. I think it shows that some people do have a more inate sense of time than others.
Answer: I know a professional conductor who can pretty much nail it right on.
It's just like perfect pitch, in that it's something you learn to do by being exposed to a ton of music and having reference points ingrained in your memory through sheer repetition.  They're not magical skills that you're born with and either have or don't have.
You can probably find 120 pretty accurately, since it's march tempo.  Just sing Stars and Stripes Forever or Washington Post.  You can probably sing your favorite songs extremely close to their original tempo, so now it's just a matter of looking up what that tempo is to develop another reference point.  Then you just keep going.
Comment: I think pitch is more complicated than repetition and practice. Wiki: "There are no reported cases of an adult obtaining absolute pitch ability through musical training" - that is "adult", of course - there's loads of things in there about key points in auditory development etc. -  well worth reading. https://en.wikipedia.org/wiki/Absolute_pitch
Comment: I agree there are folks like the conductor you mentioned, that have pretty close to perfect tempo recognition.  And I am sure that practice would improve your ability to get close to determining a tempo of a piece just by listening.  But the degree of accuracy would be the real question.
Answer: I've worked with quite a few dance band drummers who hit the correct tempo for particular dances - and believe me, serious dancers can tell if it's not right! It's sort of the opposite of what the OP is asking, but could very easily work the other way round. Basically, it's experience, the more you do it, the more consistently right it gets. Having said that, most people seem to be capable of singing/playing well-known songs at the recorded tempo, so if one knew a song at, say, 100b.p.m., it should be possible to judge another tempo from this reference point. More like relative pitch.
Comment: @BramVanroy - never, ever saw a metronome used. Just wasn't part of the kit. If the bands I worked in had a drummer that needed to rely on one, he wouldn't have lasted even a gig. And no click track either. Everything was live, no pre-recorded stuff, so nothing to follow but charts and dots.
Comment: What do you mean 'he wouldn't have lasted a gig'? Having played in many different types of bands, I'm not ashamed to say that sometimes a metronome was required externally (e.g. by a choreographer who insists on minuscule perfect time), and sometimes I myself used one for the sake of perfect rhythm when recording different instruments independently. There's no shame at all in ever using a metronome to perfect your timing, though that doesn't mean your rhythm is bad. I've heard guys humbly play with metronomes, even though they managed perfectly without one, but they did for the sake of ease.
Comment: PS: not trying to attack you here at all. Just trying to figure out if you're looking down on people who use a metronome or not. When everything needs to be perfect (e.g. For a choreography) I'd rather play with a metronome, just to be safe (a drummer can be as perfectly in time as he can, when his band members aren't, he won't be either no matter how hard he tries). However, playing with a 'regular' band, live, I'd never use a metronome.
Comment: @BramVanroy - discussions are frowned upon here. However - there are times when playing with a click track/ metronome are fairly essential - and it's a skill in itself to be able to keep that sort of time. In 'regular' bands, often the music does (and probably should) move off the beat slightly, and as such, metronomes just get in the way. It's a pleasure to play with drummers who can do both. (But not at the same time!)
Comment: Won't these drummers simply use a metronome? I don't think that on events where performance and choreography are of so much importance, they'd let drummers (or bassists) play without a metronome. I've been part of such bands in the past and even though the level was quite amateuristic, I - the drummer - played with a metronome. Obviously, there are better drummers out there than me, but to make things perfect a metronome seems an easy and almost required add.
Comment: Good points.  But there is a difference between "correct" and "perfect".  In the real word - very few things are perfect.  But close works quite well for most musical applications.
Answer: By coincidence, in last week's Boston Symphony program book (for Thursday November 12 through Saturday November 14) it says of Bela Bartok that "He was equipped with an uncannily accurate inner clock and he could tell when music marked to be played at metronome 112 was in fact going at 111 or 113."
I don't know if that is true or not.  His piano pieces have a metronome marking at the top and a timing in minutes and seconds at the end and they never match up.
Comment: Do you have an electric alarm clock?  Most likely it beeps at 60 beeps per minute.  Can you think of the sound right now?
Comment: To be fair, there are almost no pieces meant to be played exactly at a single tempo with absolutely no deviations, even going back to baroque/classical music. An uncannily accurate beat is a distinguishing characteristic of music played on Synthesia (look up Youtube videos of it), giving it a highly unnatural feeling.
Comment: There are plenty of pieces meant to be played exactly at a single tempo.  Every parade march, for example.  Judging from historic recordings I would say most dances, jazz pieces, ragtime, boogie-woogie and rock-and-roll.
Comment: I guess by "piece" I meant "solo piano piece."
Comment: "Solo piano piece" ... that sounds right.  Compare a solo piano piece to an orchestrated version of the same piece, or an orchestral piece to a piano transcription of it, and the performance of the piano version is almost always much more flexible in tempo.
Answer: I don't think anybody is a "born natural" at this, but one well-established way to become better at it, already partly mentioned by MattPutnam, is to find a set of reference points.
Matt's example of famous march music as a reference for 120 is a good one because those marches are always played at the same tempo, and to experienced ears sound "wrong" if played faster or slower. That's the catch - if you don't hear famous marches all the time so that you can reproduce them in your mind and nail the tempo, they won't work for you. The trick is finding strongly-rhythmic pieces of music, some fast, some slow, some medium, that are already "burned into your brain", and using them. For example, if you were watching TV in the 1970s and the Hawaii Five-O theme is stuck in your head, then listen to the beat of the bass drum and you have 88. If you don't know Sousa's marches but you know "Thriller" by Michael Jackson, well, that too is at 120. It doesn't matter what kind of music you use - what matters is that you know it really well and it never changes.
Don't use, for example, a national anthem or a children's song, because different people sing those at different tempi and they all sound OK. It needs to be music that "just sounds wrong" if the tempo isn't perfect.
To check the tempo of a song you find, get a free metronome app for your phone, borrow a friend's metronome, or whatever. Many of the phone apps have a "tap" function that will tell you how fast you're tapping the screen.
Answer: Here is an interesting combination, and coincidently I started both interests in the same year (age 35 in 1995). I'd played percussion in grade and high school, 17 year break and took up tenor and bass in local bagpipe band. The bass is THE metronome, and works closely with the Pipe Major. Most of our marches were 86 BPM, and I eventually could hold that as the day is long. Now, move to other interest = CLOCKS! And, I can tell if they are in beat perfectly. Best example - guy says I just have to get a machine to put regulator grandfather clocks 'in beat' = there is exactly one second between the 'tick' and the 'tock'. This is harder to do because of the 'long' time of silence between each beat, but I got it within 1% according to the guy's reading metronome. I was bummed that I missed it, be he said the instrument write up said that reading variability could be as much as 3% 'off' and still spot on due to environmental factors, age of the antique clock, etc. So I really didn't need that $500 machine.
Own a clockshop now, and am constantly trying to explain to owners putting their clock 'in beat' when they get it home. I remind them of their early music lessons, and 8'ths are 1 and 2 and 3... and 16'ths are 1 e and ah 2 e and ah.... and just fit it into their clock's beats to make sure are exact. Have discovered that some people have the beat equivalent of a 'Tin Ear' = hugely and painfully off from true, and they don't hear any difference.
Answer: The answer to your question depends on your definition of "perfect".
I believe the only way to even achieve perfect tempo, much less possess the ability to listen to a piece of music and accurately determine the exact tempo, is with a computerized click track or quantized drum track.  Even a metronome might be off a millisecond from perfect due to it's mechanical limitations.
Having said that, I am sure some folks have a unique ability to get pretty close by listening to the music.  But even recorded music is not always in a "perfect" tempo.
To illustrate my point - as a songwriter I often use software and hardware to create demos of my original compositions.  I know that if I use a live drummer, no matter how good he is and even if he is playing to a click track, the drum track will sound more realistic and organic than if I use a quantized drum sample that plays in perfect time.  Somehow the listener is able to perceive perfect tempo in a drum track (but won't be able to tell exactly what the bbm is) and it sounds artificial compared to the imperfect timing of the best real drummer.
In real life, since music is often played slightly out of perfect tempo (unless a click track or metronome is employed) or at an imperfect tempo at best, I don't know how valuable it would be for someone to be able to say "Stop the music - we are supposed to be playing this song at 160 bbm and you people are playing at 161 bbm - we need to slow it down a bit"!  Just sayin .....
If perfect means within a few bbm, then yes there are a few folks who can get pretty close.

Is it possible to have "Perfect Tempo"


Proving uniform continuity and uniform discontinuity

Question: Could someone please explain to me how to show uniform continuity and not uniformly continuous for the following:

$f(x) = \frac{1}{x^2}$ for $A = [1, \infty)$ show uniform continuity
$f(x) = \frac{1}{x^2}$ for $B = [0, \infty)$ show that $f$ is not uniformly continuous
Comment: Just FYI, the opposite of "uniformly continuous" is "not uniformly continuous," rather than "uniformly discontinuous."
Comment: oh thanks, now could you please tell me how to prove uniform continuity. I have been able to prove the "not uniform continuity" part but I am still stuck at the uniform continuity part
Comment: never mind I got the answer, thanks for the correction though
Comment: @BilalJunaidy If you got the answer, you can consider self answering your question. (You will get a hat as a reward!)
Answer: Here we see that $$f'(x)=-\frac{2}{x^3}$$
In $A$, $-2\leq f'(x)<0$, that is bounded but in $B$, $f'(x)$ is not bounded. Therefore $f(x)$ is uniformly continuous in $A$ but not in $B$.
Answer:
$|\frac{1}{x^2}-\frac{1}{y^2}|\leq |\frac{y^2-x^2}{x^2y^2}|=|\frac{(y-x)(y+x)}{x^2y^2}|\leq |\frac{x+y}{x^2y^2}||y-x|\leq (|\frac{1}{xy^2}|+|\frac{1}{yx^2}|)|x-y|\leq 2|x-y|$

2.$\frac{1}{x^2}$ is not uniformly continuous. $|\frac{1}{x^2}-\frac{1}{y^2}|\leq |\frac{y^2-x^2}{x^2y^2}|$ Near $0$ quantity is very large.


Multiple Midi Controllers on the Same Channel (different octaves)

Question: Background
I have no experience with midi (other than what I've read online) and I don't yet have any midi equipment to play with (but I have several devices working their way through the mail system).
Question
Is it possible to have multiple midi keyboard controllers set to the same midi channel, but transposed to different octaves, controlling the same sound generator?  Perhaps a better way to ask that is what problems am I likely to encounter having multiple keyboard controllers daisy-chained together that are set to the same channel?
Details
I'm getting a Memotron M2D sound generator - it only listens on one channel, but it has three voices that can be split across different key ranges of the 128 midi notes (C0 to C10 or whichever numbering you prefer).  Eventually, I plan to midify an old organ pedal board and combine this with two (small) midi keyboard controllers so that I have a different voice for each manual.  From all my reading, it seems like I should be able to set all these to the same channel, daisy chain them into the M2D and as long as I have the octave ranges set so they don't overlap and match the mapping in the M2D this should work.  However, I can't find any discussion of merging multiple controllers into a single device (lots of discussions of chaining multiple controllers to multiple devices or one controller to multiple devices).  From what I've read, the biggest potential problem seems to be that a controller may not merge the data it's receiving on the "in" port with the data it's sending out - i.e., it may simply drop all the incoming midi data and only send out it's own data.  However, for dumb controllers (i.e., that have no sound generating ability, like the Arturia Keylab) I can't imagine why the data coming into the "in" port wouldn't be passed along to the "out" port, so something like the example below should work (in my mind).
<code>keyboard 1 (chan 1) -> Arturia keyboard 2 (chan 1) -> M2D (listening on chan 1)
</code>
But, I have zero experience with midi at this point.
Answer: Yes this should work as long as you are MIDI merging or not stripping the incoming MIDI on any but the first controller. Most controllers allow MIDI merge and usually have it configurable, or they have a dedicated MIDI Thru port, which is what you should use if a controller has it. If you don't mind playing the same note twice, you don't even have to make sure the octave ranges don't overlap. For example, I have connected two keyboards with the same channel number to one tone generator and then played one with the left hand and one with the right and played the same sound in different octaves. I also have a foot controller and have done the same thing. If you are sending note on messages for different notes on the same channel, I can't see any tone generator caring (or even knowing) that those messages are from different controllers.
If you don't mind putting a computer into the mix, you could instead route the different controllers into a laptop separately and then merge the MIDI in software before sending it out to the tone generator. This solves the MIDI merge problem and gives you some other options as well, but does involve having a computer around and any necessary MIDI interfaces, but does let you easily use any USB MIDI controllers.
What a tone generator does with two different overlapping note on messages for the same note at the same time I expect would vary from tone generator to tone generator. The back of my mind seems to be trying to tell me that a multi-voice generator that I have will actually play the same note in more than one voice, while a mono synth that I have will merely re-trigger the gate while maintaining the same pitch CV output. I can experiment if you really want. Again, it will be specific to the synth/tone generator. Also, it doesn't seem like you are trying to send multiple note on messages for the same note, so it's really more of an academic question of mild interest.
Comment: If you only have one device that won't merge and has no thru port, just make that the first device in the chain. Most controllers/synths do have manuals online so you should be able to verify whether they have a merge function before you buy or even if you can't find the manual.
Comment: I tried this tonight with two keyboards and a four-voice analog synth module just to be sure. It worked - no problem. The question of the same key going to the same voice was answered by this module with the second note overriding the first. If I play C4 on keyboard one, then play C4 on keyboard two, and then release C4 on keyboard two while still holding C4 on keyboard one, the note stops. Keyboard one's C4 is overridden by keyboard two and keyboard one loses its control of the note. Again, I expect this would vary from module to module. A multi-layer piano module probably would not do this.
Comment: From what I can see on the specs, I won't have a thru port - and I definitely want the signals merged as my tone generator only has a single midi in port.  I'm trying to avoid using a computer (for now) just to keep life simple.   It's comforting to hear of real experience with this working =)
Answer: If I understand your description correctly, I think there might be problems with some midi messages applying to all 3 controllers. In addition to the number of the note being played,  there is also control information.  Some control info applies to the note, such as a velocity values, note on/off, etc. Some control data applies to the whole channel. You might wind up with one keyboard sending midi info that would affect the other notes on the same channel, even though each keyboard was sending different note on/off messages. But the next question would be why have multiple controllers? You can "record" the midi notes separately and edit them so playback is from a single, clean source.
Comment: Pitch bend would certainly apply to the whole channel, but that seems like it would be desirable to me. Also, aftertouch could be implemented as a channel value or as an individual note value, but again, channel aftertouch is not usually a problem.
Comment: I'm sure there are situations where my intended setup could run into problems: however, the motivation for this setup is that my existing keyboard is a cheap yamaha with no controls at all (no pitch bend, no knobs or buttons, etc. just 61 keys) - I purchased the small arturia keylab to get pitch bend, mod wheel, programmable knobs/sliders, etc.  My plan is to shift the octave of the keylab so it won't overlap with the notes on the yamaha at all (if I ever get around to converting an old organ pedal board, I'll shift that down to the lowest two octaves to avoid any collisions)
Comment: As for recording and playback - I don't have any DAW software at the moment, and I probably won't move that direction for some time.  Once the memotron shows up, I just want to be able to be play it "live" without needing to fight with any software playing middle-man.


Affine transformation read order

Question: I would like to ask a question about affine matrix transformations, specifically a mathematical explanation about why these two ways to interpret them are equivalent.
Suppose I have a translation matrix T (for simplicity 2D) and a rotation matrix R as follows:
$$
 T= \begin{bmatrix}
        1 & 0 & tx \\
        0 & 1 & ty \\
        0 & 0 & 1 \\
        \end{bmatrix}
 R= \begin{bmatrix}
        \cos \theta & -\sin \theta & 0 \\
        \sin \theta & \cos \theta & 0 \\
        0 & 0 & 1 \\
        \end{bmatrix}
$$
Suppose:
$$
tx = 0 , ty = 2, \theta = 45^{ \circ }
$$
Now if I transform a quad applying translation and rotation to every vertex in this order: R * T * Vertex (Column vector), I obtain this:

Since both translation and rotation transforms are done around the origin, considering T first and R after. However this is equivalent to considering R first and T after modifying the quad relative to itself and not the origin:

The result is the same. Why is this equivalent?
Answer: It depends on the agreement. Usually it is preferred to read $(f*g)(x)$ as $f(g(x))$ when we talk about functions, operators and etc., but You can put it as You like, generally, with remark about your own agreement.

Affine transformation read order


TOMCAT8.5 Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/spring]]

Question: I'm working on a Spring-MVC project on eclipse and I Have a Tomcat8.5 issue, the server fails to start and I'm getting the exception below:
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/spring]]
    at java.util.concurrent.FutureTask.report(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:939)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:872)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1419)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/spring]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    ... 6 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [org.apache.catalina.webresources.StandardRoot@6160e000]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4842)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:4974)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more
Caused by: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.JarResourceSet@2abd09d0]
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:112)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:140)
    at org.apache.catalina.webresources.StandardRoot.startInternal(StandardRoot.java:708)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 9 more
Caused by: java.lang.IllegalArgumentException: java.util.zip.ZipException: invalid LOC header (bad signature)
    at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.initInternal(AbstractSingleArchiveResourceSet.java:113)
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:107)
    ... 12 more
Caused by: java.util.zip.ZipException: invalid LOC header (bad signature)
    at java.util.zip.ZipFile.read(Native Method)
    at java.util.zip.ZipFile.access$1400(Unknown Source)
    at java.util.zip.ZipFile$ZipFileInputStream.read(Unknown Source)
    at java.util.zip.ZipFile$ZipFileInflaterInputStream.fill(Unknown Source)
    at java.util.zip.InflaterInputStream.read(Unknown Source)
    at sun.misc.IOUtils.readFully(Unknown Source)
    at java.util.jar.JarFile.getBytes(Unknown Source)
    at java.util.jar.JarFile.getManifestFromReference(Unknown Source)
    at java.util.jar.JarFile.getManifest(Unknown Source)
    at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.initInternal(AbstractSingleArchiveResourceSet.java:111)
    ... 13 more

févr. 24, 2017 9:53:30 PM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at java.util.concurrent.FutureTask.report(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:939)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:793)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:655)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:355)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:495)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1419)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:947)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:872)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more

févr. 24, 2017 9:53:30 PM org.apache.catalina.startup.Catalina start
SEVERE: The required Server component failed to start so Tomcat is unable to start.
org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:655)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:355)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:495)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:793)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 7 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 9 more
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:947)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 11 more

The spring configuration file pom.xml file looks like this:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.journaldev</groupId>
    <artifactId>spring</artifactId>
    <name>SpringMVCHibernate</name>
    <packaging>war</packaging>
    <version>1.0.0-BUILD-SNAPSHOT</version>
    <properties>
        <java-version>1.8</java-version>
        <org.springframework-version>4.3.0.RELEASE</org.springframework-version>
        <org.aspectj-version>1.5.4</org.aspectj-version>
        <org.slf4j-version>1.7.21</org.slf4j-version>
        <hibernate.version>5.2.2.Final</hibernate.version>
        <mysql.connector.version>5.1.31</mysql.connector.version>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
            <exclusions>

                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                 </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>${hibernate.version}</version>
    </dependency>

    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>1.4</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql.connector.version}</version>
    </dependency>

    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>${org.aspectj-version}</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>${org.slf4j-version}</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>${org.slf4j-version}</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>${org.slf4j-version}</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
        <exclusions>
            <exclusion>
                <groupId>javax.mail</groupId>
                <artifactId>mail</artifactId>
            </exclusion>
            <exclusion>
                <groupId>javax.jms</groupId>
                <artifactId>jms</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.sun.jdmk</groupId>
                <artifactId>jmxtools</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.sun.jmx</groupId>
                <artifactId>jmxri</artifactId>
            </exclusion>
        </exclusions>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>javax.inject</groupId>
        <artifactId>javax.inject</artifactId>
        <version>1</version>
    </dependency>

    <dependency>
        <groupId>javax.transaction</groupId>
        <artifactId>jta</artifactId>
        <version>1.1</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.7</version>
        <scope>test</scope>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <artifactId>maven-eclipse-plugin</artifactId>
            <version>2.9</version>
            <configuration>
                <additionalProjectnatures>
                    <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                </additionalProjectnatures>
                <additionalBuildcommands>
                    <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                </additionalBuildcommands>
                <downloadSources>true</downloadSources>
                <downloadJavadocs>true</downloadJavadocs>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.5.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <compilerArgument>-Xlint:all</compilerArgument>
                <showWarnings>true</showWarnings>
                <showDeprecation>true</showDeprecation>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <configuration>
                <mainClass>org.test.int1.Main</mainClass>
            </configuration>
        </plugin>
    </plugins>
</build>

Thank's
Comment: Please [edit] your post and include the COMPLETE stack trace, including all "caused by" sections, plus any other messages logged.  It is impossible to help with the information you've provided so far.
Comment: It looks like another instance of tomcat is up with the same http port. either stop all running tomcat. or try changing the http port of your project's tomcat.
Comment: @JimGarrison I've just edited it
Comment: I resolved the problem by runing the project as a maven build before running into the server of my choice
Answer: I tried Right click on the server -> Clean. didn't work.
What worked is:
You just to add <absolute-ordering /> tag to your web.xml just under the <display-name> tag and it should work.


Why can linear independence of $e^{ax +by^2}$ be proven without considering $y$?

Question: Linear independence of $e^{at}$ has been answered multiple times. My favorite one is by Marc van Leeuwen in this one: Proof of linear independence of $e^{at}$. The answer uses the property that $e^{at}$ are eigenfunctions of the differentation operation. Now if we instead have an exponential function in two variables, say $e^{ax + by^2}$, it seems to me the linear independence of these functions can too be proved with the same technique, except now using the partial derivative operator:
Proof by induction as in the link except here $e^{a_1x + b_1y^2}$, $e^{a_2x + b_2y^2}$, $...$,$e^{a_{n-1}x + b_{n-1}y^2}$ are assumed linearly independent. As in Marc's proof, we then assume that $e^{a_1x + b_1y^2}$, $e^{a_2x + b_2y^2}$, $...$,$e^{a_{n}x + b_{n}y^2}$ are in turn dependent and thus have:
$e^{a_{n}x + b_{n}y^2}= c_1e^{a_1x + b_1y^2} +  c_2e^{a_2x + b_2y^2} + ... + c_{n-1}e^{a_{n-1}x + b_{n-1}y^2}$. Applying operator $\frac{\partial}{\partial x} - a_nI$ will give  $0= c_1(a_1-a_n)e^{a_1x + b_1y^2} +  c_2(a_2-a_n)e^{a_2x + b_2y^2} + ... + c_{n-1}(a_{n-1}-a_n)e^{a_{n-1}x + b_{n-1}y^2}$ which would thus require all c to be zero, which essentially completes the induction proof (other argumentation as per link).
My question is: why does $y^2$ not seem to have any effect on the linear independence. Where does this stem from?
edit: assume all $a_k$ and $b_k$ are distinct.
Comment: You have to take in consideration that the linear independence you present, is towards variable $x$, judging from the operator you are using. A 2 variable function $f(x,y)$ would need a 2-dimension operator. So what your assumption is that $e^{ax+bx^2}$ is linear towards $x$ which is true (its like considering $bx^2$ a constant)
Comment: I suspected something like this (assume you meant $by^2$). I guess $\frac{\partial }{\partial x \partial y} $is then what youd sugggest
Comment: also, despite seeing your point on intuitive level, I fail to see the logic fully since I dont see which part of my argumentation fails in my question. After all $a_1f_1 + a_2f_2 + ... + a_nf_n = 0$ implies linear independence if all a_i are 0, no matter what the f_1 are (no matter how many variables e.g. second answer here http://mathhelpforum.com/calculus/220785-linearly-independent-multivariable-function.html)
Comment: Note that your functions are *products:* $e^{a_jx} e^{b_jy^2}$. If a linear combination $\sum c_j  e^{a_jx} e^{b_jy^2}$ is zero then by fixing $y$ it follows that a linear combination of the $e^{a_jx}$ is zero.
Comment: Good point. Am I right saying that then it would suffice to prove separately for each variable i.e. using partial differentiation wrt x and y each at turn
Comment: The false in your logic is that you are using the operator ,which is used "conditionally" on the proof, to prove something completely different. This operator is used a mathematical "trick" to annihilate the final exponential function and thus leaving us only the coefficients we need to prove independency. It works only on $e^{a_{n}x}$. Your misconception stands on the fact that you used this operator, which will annihilate the final exponential function and thus leave again only the coefficients of the one variable. Proving the independency of only variable $x$.
Comment: Great, thanks!!
Comment: The error in your proof comes from claiming that

$$\tag 1 \sum_{k=1}^{n-1}c_k(a_k-a_n)e^{a_kx+b_ky^2}\equiv 0$$

implies all $c_k=0.$ It doesn't; it implies all $c_k(a_k-a_n)=0.$ Since $a_k=a_n$ is a possibility, we can't deduce $c_k=0$ for such a $k.$
Comment: that's true, but I implicitly assumed all $a_k$ are different from each other as this is what was assumed in the question I linked to. I should have stated that explicitly though. I have edited accordingly.
Answer: Your proof essentially repeats the proof that the functions $e^{a_j x}$ are linearly independent. The "$y$-terms" have "no effect" because they occur as (non-zero) factors $e^{b_j y^2}$ which are constant with respect to $x$.
What you observed is this: If $g_1, \ldots, g_n : A \to \Bbb R$ and $h_1, \ldots, h_n : B \to \Bbb R$ are functions such that

$g_1, \ldots, g_n$ are linearly independent, and
there is a $y_0 \in B$ such that $h_j(y_0) \ne 0$ for all $j$,

then the functions $f_j : A \times B \to \Bbb R$, $f_j(x, y) = g_j(x) h_j(y)$, $j=1, \ldots, n$, are linearly independent.
The proof is straight forward: If $c_1, \ldots, c_n \in \Bbb R$ with
$$
 \sum_{j=1}^n c_j g_j(x) h_j(y) = 0 \text{ for all } (x, y) \in A \times B
$$
then in particular
$$
 \sum_{j=1}^n \bigl( c_j h_j(y_0) \bigr) g_j(x) = 0 \text{ for all } x \in A
$$
Since the $g_j$ are linearly independent it follows that
$$
c_j h_j(y_0) = 0\text{ for  } j = 1, \ldots, n
\implies c_j = 0  \text{ for  } j = 1, \ldots, n \,.
$$
In your case $g_j(x) = e^{a_j x}$ and $h_j(y) = e^{b_j y^2}$.
Comment: Ah amazing! So actually my proof was then "correct" (which I thought it wasnt based on Pookaros' comments above). I suppose his/her comment would be valid if x and y had a more complex relationship?


Volum of the covering of $\bar{S} \geq S$?

Question: The proposition on GP Page 203 says:
Let $S$ be a rectangular solid and $S_1, S_2, \ldots$ a covering of its closure of $\bar{S}$ by other solids. Then $\sum$vol$(S_j) \geq$ vol($S$).
This does not quite make sense to be - why can we assert that Volum of the covering of $\bar{S} \geq S$? I think I must missed something. One thing I am not sure about is thatis defined to be the whole space?
Thank you very much for helping me clear my confusion.
Comment: I'm not sure what you're asking.  The proposition is followed by a page-long proof.                             "One thing I am not sure about is thatis defined to be the whole space?" I'm not sure what this sentence means :(
Comment: Ohhh! It's the topological closure! :)
Comment: Hi @Timkinsella, thank you for you comment. I understand $\bar{S}$ as the compliment of $S$. Hence, I am confused with what is the whole set - in other words, what is $S + \bar{S}$. Thanks.
Comment: @Timkinsella, oh no. I got it - I confused closure with compliment! Thank you so much for helping me clear this out!!
Answer: Thanks to @Timkinsella. This is trivially true, since the closure of a set certainly is greater than or equal to the set.


Set-valued maps: locally Lipschitz implies upper semicontinuity

Question: With $X$ and $Y$ metric spaces, let $F:X\rightrightarrows Y$ be a set-valued map satisfying the following

(P) For each compact set $K\subset \operatorname{dom} F$ there exists $L>0$ such that, for all $x_1,x_2\in K$, $\|F_1-F_2\|\le L\|x_1-x_2\|$ holds for all $F_1\in F(x_1)$ and $F_2\in F(x_2)$

Is it true that $F$ is upper semicontinuous?
My clumsy attempt: Pick $x\in X$ and let  $V_\epsilon:= F(x)+ B_\epsilon$ (with $B_\epsilon$ the open ball on $Y$). With $\nu>0$, pick any $x_1,x_2\in x+B_\nu$ and let $K\subset X$ be any compact subset containing $x+B_\nu$. Then from (P) we have $\sup\{ \|f_1- f_2\|\,:\, f_1\in F(x_1),\, f_2 \in F(x_2)\} \le L\|x_1-x_2\|\le L\nu$ for some $L$ depending only on $K$. Thus, if $\nu\le \epsilon/(2L)$, then $F(x+B_\nu)\subset V_\epsilon$, and the result should follow.
I am on the right way? If that's correct I guess that this can be found in many books. However I could not find it. Do you have any reference?
-------------------------- edit
As @Michelle pointed out, (P) implies that $F$ is single valued, so the guess is true. Therefore I want to modify the question with the following assumption holding anstead of (P):

(P2) For any $x\in X$ and for any compact subset $K\subset X$ containing $x$, there exists $L>0$ such that $\forall x_1,x_2\in K$, $F(x_1)\subset F(x_2) + B_{L\|x_1-x_2\|}$

Thanks.
Answer: Version 1: incorrect form of Lipschitz continuity

for all $x_1,x_2\in K$, $\|F_1-F_2\|\le L\|x_1-x_2\|$ holds for all $F_1\in F(x_1)$ and $F_2\in F(x_2)$

This implies $\|F_1-F_2\| = 0$ for all $F_1,F_2\in F(x_1)$. So the map $F$ is actually single-valued. The set-valued upper semicontinuity then becomes regular continuity of $F$.
The latter still takes a bit of effort to prove since we only have the Lipschitz property on compact subsets. It goes like this: pick any convergent sequence $x_n\to x$. The set $K=\{x_n\}\cup \{x\}$ is compact, so $f$ is Lipschitz continuous on it. Hence $f(x_n)\to f(x)$. Since we are in a metric space,  sequential continuity is equivalent to continuity.
Version 2: Lipschitz continuity with respect to Hausdorff distance

For any $x\in X$ and for any compact subset $K\subset X$ containing $x$, there exists $L>0$ such that $\forall x_1,x_2\in K$, $F(x_1)\subset F(x_2) + B_{L\|x_1-x_2\|}$

This does not imply upper semicontinuity. For example, let $F(x) = (x,x+1)\subset \mathbb R$ for $x\in \mathbb{R}$. The definition of upper semicontinuity says that for every open set $W\subset Y$, the set $\{x\in X: F(x)\subset W\}$ must be open in $X$. But this fails with $W=(0,1)$ for which the latter set is $\{0\}$.
Aside: The definition of upper semicontinuity makes more sense for maps such that $F(x)$ is compact for every $x$, or at least closed.
Version 3: Lipschitz continuity with respect to Hausdorff distance, compact-valued map
Suppose $F(x)$ is compact for every $x$, and is globally Lipschitz in the Hausdorff metric. (Not just Lipschitz on each compact set). Then upper semicontinuity holds. Indeed, take an open set $W\subset Y$ and a point $x_0$ such that $F(x_0)\subset W$. Let $\rho = \operatorname{dist}(F(x_0), Y\setminus W) $, which is a positive number. If $d(x,x_0)<\rho/L$, then the Lipschitz condition on $F$ implies $F(x)\subset W$, as required for upper semicontinuity.
Comment: thanks for pointing that out. I just modified the question
Comment: I added an answer for version 2, and also version 3 that you didn't really ask (but perhaps should have).


Proving $(f^*)^*=f$

Question: I solved it like this : $$\langle (f^*)^*(v),w \rangle=\langle v,f^*(w)\rangle=\langle f(v),w\rangle$$ My lecture notes gave a proof with some more steps. Now i'm not sure, maybe i messed something.
here $f^*$ denotes the adjoint  of the linear map $f$.
Comment: I guess the adjoint was defined as (for all $v,\,w$) $\langle v,\, f(w)\rangle = \langle f^\ast(v),\, w\rangle$ and the proof in the notes went something like $\langle (f^\ast)^\ast(v),\, w\rangle = \langle v, f^\ast(w)\rangle = \overline{\langle f^\ast(w), v\rangle} = \overline{\langle w, f(v)\rangle} = \langle f(v),w\rangle$?
Comment: Well, if you have something that you may use for the equality $\langle f(x),y\rangle = \langle x, f^\ast(y)\rangle$, it is okay. That's a trivial thing to prove of course, by hermitian symmetry, but if that is never done, your argument uses a property that hasn't been proved.
Comment: For linear maps you can attach them a matrix. You should try this proof using matrices.
Comment: yes @DanielFischer that was the proof. And the definition we gave is as you stated but it starts in the first slot. Am i missing something in my resoning?
Comment: @DanielFischer this equation is how we defined the adjoint function , so we should start from there i think.
Comment: @AmireBendjeddou Was it defined $\langle f(x),y\rangle = \langle x,f^\ast(y)\rangle$, or $\langle v, f(w)\rangle = \langle f^\ast(v), w\rangle$? The definition gives you one direction of moving the map to the other side off the inner product adding/removing a $^\ast$. Your chain of equations moves into both directions. At some point, you need to show that that is okay.
Comment: @DanielFischer I got your point now. It was defined like the first equation of your last comment. Well now it makes sense , the second equation is not given so i can't go back from the second to the first slot. So i have to stick with the proof of mu lecture notes. Thanks for clearing my doubt!
Answer: Once you have $\langle (f^*)^*(v),w \rangle=\langle f(v),w\rangle$ for all $v$ and $w$ you still need to do a little bit more to show $(f^*)^* = f$. First rewrite it as $\langle ((f^*)^* - f)(v),w \rangle=0$ which is true for all $v$ and $w$. In particular it is true for $w = ((f^*)^* - f)(v)$. So we get $\langle ((f^*)^* - f)(v),((f^*)^* - f)(v) \rangle=0 \implies ((f^*)^* - f)(v) = 0$ for all $v$. And so $(f^*)^* - f = 0 \implies (f^*)^* = f$.
Answer: From your argument, you can conclude that, for $y = (f^{\ast})^{\ast}(v) - f(v)$, one has
$$
\langle y,w \rangle = 0 \quad \forall w
$$
And you want to conclude that $y = 0$. For this you need to know that these linear functionals
$$
\varphi_w : x \mapsto \langle x,w\rangle
$$
separate points in your vector space. For this you will need the Riesz representation theorem and the Hilbert space version of the Hahn-Banach theorem. Is that what your book uses?
Comment: It's much simpler here, just plug in $w = y$ to conclude $\lVert y\rVert^2 = 0$.
Answer: I assume we are working in a finite dimensional inner product space V. What your proof is missing is the well known fact that if $f:V \to V$ and $g:V \to V$ are linear transformations with $<f(v),w>=<g(v),w>$ for all $v,w \in V$, then $f=g$.  To prove this fact, let $\{e_1, ..., e_n\}$ be an orthonormal basis of $V$ (you can construct one via the Gram-Schmidt process). Then for each $v \in V$ we have the identity $v= \sum_{i=1}^n<v,e_i>e_i$. In particular $$f(e_j) = \sum_{i=1}^n <f(e_j), e_i>e_i = \sum_{i=1}^n<g(e_j),e_i>e_i = g(e_j)$$ Thus, $f$ and $g$ agree on a basis, so they are equal.

Proving $(f^*)^*=f$


Side effects of not using row/column?

Question: I'm trying to develop a pricing section of a site, which contains 3 different prices. At the very top there should be a header and a short description, something like "Pricing", "The pricing plans:

Pricing

The pricing plans

Now, I've seen people put things that are supposed to be 1-row/1-column, directly inside the container, as above. If I followed the Boostrap "convention", then I'd do:

Pricing

Here are our pricing plans

But, isn't putting a row with single col-xs-12 reduntant? If you see the source of the Bootstrap home page, you'll notice
 tags directly inside the container. However, here, the
 and the
 tags aren't the ONLY things inside the container, there is a row following them.
So my question is, will there be any un-intended side-effect of using the first example vs. "following the rules" and using the second examples?
Answer: The Bootstrap Grid framework relies on padding and margins for proper placement.  When you omit either the .row or .col-*-* you create alignment issues.  Consider the following code:

.default {
  background: blue;
  color: white;
}

.no-column {
  background: gray;
}

.no-row {
  background: yellow;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

A paragraph within a col-12 element

A paragraph with no column wrapper.

A paragraph with no column or row wrapper.

In the first example we have a grid element that follows Bootstrap's framework; text is wrapped within a column that is wrapped within a row that is part of the .container-fluid element.
Everything aligns as expected.
In the second example we omit the column.  Immediately we lose the padding created by .col-*-* and your paragraph presses up against the extreme left margin of the container.
In the 3rd example we omit not only the column, but also the row class.  As you can see the spacing difference becomes even more extreme.

Side effects of not using row/column?


Desabilitar o autocomplete de formulários em Laravel?

Question: Olá. Pesquisei por toda a internet e não encontrei.
Simplesmente não consigo fazer com que o autocomplete de formulários Laravel seja desativado. O 'autocomplete="off"' pra isso, não funciona para os campos se email e senha.
Alguém tem uma alternativa pra eu fazer isso no site?
@extends('layouts.template')

@section('content')

Cadastrar Usuario

               {{Form::model($users, array('route' => array('user.store'),'id' => 'crud-form', 'files' => 'true'))}}

                    {{Form::label('nome', 'Nome:',['class' => 'col-lg-2 control-label'])}}
                    {{Form::text('nome',null,['class' => 'col-lg-8 form'])}}
                    @if ($errors->has('nome'))
                        {{$errors->first('nome')}}
                    @endif

                    {{Form::label('sobrenome', 'Sobrenome:',['class' => 'col-lg-2 control-label'])}}
                    {{Form::text('sobrenome',null,['class' => 'col-lg-8 form'])}}
                    @if ($errors->has('sobrenome'))
                        {{$errors->first('sobrenome')}}
                    @endif

                    {{Form::label('email', 'E-mail:',['class' => 'col-lg-2 control-label'])}}
                    {{Form::email('email',null,['class' => 'col-lg-8 form'])}}
                    @if ($errors->has('email'))
                        {{$errors->first('email')}}
                    @endif

                    {{Form::label('cpf', 'CPF:',['class' => 'col-lg-2 control-label'])}}
                    {{Form::text('cpf',null,['class' => 'col-lg-8 form'])}}
                    @if ($errors->has('cpf'))
                        {{$errors->first('cpf')}}
                    @endif

                    {{Form::label('rg', 'RG:',['class' => 'col-lg-2 control-label'])}}
                    {{Form::text('rg',null,['class' => 'col-lg-8 form'])}}
                    @if ($errors->has('rg'))
                        {{$errors->first('rg')}}
                    @endif

                    {{Form::label('telefone', 'Telefone:',['class' => 'col-lg-2 control-label'])}}
                    {{Form::text('telefone',null,['class' => 'col-lg-8 form'])}}
                    @if ($errors->has('telefone'))
                        {{$errors->first('telefone')}}
                    @endif

                    {{Form::label('celular', 'Celular:',['class' => 'col-lg-2 control-label'])}}
                    {{Form::text('celular',null,['class' => 'col-lg-8 form'])}}
                    @if ($errors->has('celular'))
                        {{$errors->first('celular')}}
                    @endif

                    {{Form::label('rua', 'Rua:',['class' => 'col-lg-2 control-label'])}}
                    {{Form::text('rua',null,['class' => 'col-lg-8 form'])}}
                    @if ($errors->has('rua'))
                        {{$errors->first('rua')}}
                    @endif

                    {{Form::label('bairro', 'Bairro:',['class' => 'col-lg-2 control-label'])}}
                    {{Form::text('bairro',null,['class' => 'col-lg-8 form'])}}
                    @if ($errors->has('bairro'))
                        {{$errors->first('bairro')}}
                    @endif

                    {{Form::label('complemento', 'Complemento:',['class' => 'col-lg-2 control-label'])}}
                    {{Form::text('complemento',null,['class' => 'col-lg-8 form'])}}

                    {{Form::label('numero', 'Numero:',['class' => 'col-lg-2 control-label'])}}
                    {{Form::text('numero',null,['class' => 'col-lg-8 form'])}}
                    @if ($errors->has('numero'))
                        {{$errors->first('numero')}}
                    @endif

                    {{Form::label('cep', 'CEP:',['class' => 'col-lg-2 control-label'])}}
                    {{Form::text('cep',null,['class' => 'col-lg-8 form'])}}
                    @if ($errors->has('cep'))
                        {{$errors->first('cep')}}
                    @endif

                    {{Form::label('datanascimento', 'Data de nascimento:',['class' => 'col-lg-2 control-label'])}}
                    {{Form::text('datanascimento',null,['class' => 'col-lg-8 form', 'id' => 'datepicker','autocomplete' => 'off','readonly'])}}
                    @if ($errors->has('dattanascimento'))
                        {{$errors->first('datanascimento')}}
                    @endif

                    {{Form::label('role', 'Função:',['class' => 'col-lg-2 control-label'])}}
                    {{Form::select('role',array('gerente' => 'Gerente', 'vendedor' => 'Vendedor'),'vendedor',array('class' => 'tipo col-lg-8'))}}

                    {{Form::label('password', 'Senha:',['class' => 'col-lg-2 control-label'])}}
                    {{Form::password('password',['class' => 'col-lg-8 form','autocomplete' => 'off'])}}
                    @if ($errors->has('password'))
                        {{$errors->first('pasawword')}}
                    @endif

                    {{Form::label('password_confirmation', 'Confirmação Senha:',['class' => 'col-lg-2 control-label'])}}
                    {{Form::password('password_confirmation',['class' => 'col-lg-8 form'])}}
                    @if ($errors->has('password_confirmation'))
                        {{$errors->first('password_confirmation')}}
                    @endif

                    {{Form::reset('Limpar', array('class' => 'btn'))}}
                    {{Form::submit('Salvar', array('class' => 'btn', 'id' => 'validar'))}}

                    Voltar

                {{Form::close()}}

@endsection

@section('script')

{!! $validator->selector('#crud-form') !!}
 @endsection

Answer: No seu e-mail você não está desativando. Use da seguinte forma:
{{Form::email('email',null,['class' => 'col-lg-8 form', 'autocomplete'=>'off'])}}

Acabei de testar e desativou normal.


Add text at the end of the score in LilyPond

Question: Is it possible to add a text at the end of the score like in this example?
Answer: Yes, it is very simple.
In your lilypond file, you can use any number of \score and \markup blocks, one after another, and Lilypond just typesets it all and puts it into one file in the same order. So here you would have
(...)
\score { (your score goes here) }
\markup {This text will appear below the score.}

Here's a lilybin for you to experiment with (Lilybin is an online app that makes it possible to share Lilypond snippets. It can also render them right in your browser, so you can see the results).


Clear description of PCA using SVD of covariance matrix

Question: After reading thousands of articles on PCA and SVD, using them in a number of programming frameworks and even implementing similar techniques (like Random Indexing) I found out that I still have doubts about some parts of PCA for dimension reduction. So let me show what I know and what I have doubts about.
Let's say we have $N$ observations of $M$-dimensional data, organized as matrix $A \in R^{N * M}$. To perform PCA we should first compute MLE estimate of covariance matrix $\Sigma \in R^{M*M}$:
$$\Sigma=\frac{1}{N}\sum_{i=1}^N(x_i - \bar x)(x_i - \bar x)^T$$
where $x_i \in R^M$ is $i$-th observation, $\bar x = \frac{1}{N}\sum_{k=1}^{N}x_k \in R^M$ is mean observation.
Then we can decompose $\Sigma$ using SVD as follows:
$$\Sigma = USV^T$$
Now here are several things I'm not sure about:

What are dimensions of $U$, $S$ and $V^T$?
In $USV^T$ what exactly is considered as eigenvalues and which of them should I use as principal components?
How can I project original observations $x_i$ onto new reduced space and vice versa?

UPD. There's a different way to compute PCA using SVD - by factorizing data matrix ($A$ here) instead of covariance matrix ($\Sigma = AA^T$). Good description for this process may be found in this answer.
Comment: I hoped you know that because covariance matrix is symmetric U=V (with columns corresponding to the PCs) and is the same eigenvectors matrix as eigen-decomposition returns, and S's diagonal are the same PCs eigenvalues as eigen-decomposition returns.
Comment: @ttnphns: the problem is that different articles use different terms and make emphasis on different parts. For example, in some articles they use terms "left eigenvalues" to refer to columns of $U$ and "right eigenvalues" to refer to rows of $V^T$, but they don't say which of them should I use for PCA. Also different notations are used for projection of original vector onto reduced space - normally it is written as $x' = Px$ (where $P$ is matrix of first $k$ eigenvectors), but I have also seen following form, that breaks down my understanding of used dimensions: $x' = \sum p_i x$
Comment: Ah, symmetry of $U$ and $V$ is just what I missed. This explains many things in articles that confused me and proves assumptions I had about my 3 questions. Thanks, you saved me from doubts :)
Comment: @ttnphns If you have time and inclination, could you please convert your comment as an answer so that the OP could accept it and close this thread?
Comment: Please excuse if it sounds rude, but... where are you stuck `after reading thousands of articles on PCA`?
Comment: So this question is caused not by little number of articles read, but by mixing ideas and notations in that articles. What I actually want is to bring some order in my thoughts. I have my own opinion on all 3 questions, but it's always worth to make sure when dealing with rigorous maths.
Comment: I know this is a very old question, but I find it very unfortunately formulated. When people talk about using SVD for PCA, they mean SVD of the data matrix itself (matrix $A$ in your question), as opposed to doing eigendecomposition of the covariance matrix. But you are asking about SVD of the covariance matrix, which is square symmetric matrix, and so its SVD is equivalent to its eigendecomposition! So the question itself is asking something very different (and much more trivial) than what the title implies.
Comment: [cont.] It would be most useful for this site and for the community to rewrite the question such that it asks about SVD of the matrix $A$, but this requires significant changes. If you don't want to do that, I can understand, but then perhaps we should edit the title to clarify what it's about.
Comment: @amoeba: changing question is not an option here, because in this case the answer below will lose any sense. So I simply linked a different question (see update) and change the title. Please, feel free to refine the post further if you see better formulation.
Answer:
What are dimensions of $U$, $S$ and $V^T$?

Since $\Sigma$ is a M by M matrix, the three matrices $U$, $S$, $V^T$ wil be all M by M matrices. Because applying SVD on a N by M matrix, you will get $U_{N{\times}N}$, $S_{N{\times}M}$, and $V^T_{M{\times}M}$. You can verify that in matlab. When you truncate the singular values $S$ you also should remove the corresponding parts in $U$ and $V^T$.

In $USV^T$ what exactly is considered as eigenvalues and which of them should I use as principal components?

PCA should be done by doing eigenvalue decomposition on the covariance matrix $\Sigma$, or done by applying SVD on $A$. The left singular vectors of $SVD(A)$ come from the eigen vectors of $AA^T$, and the right singular vectors of $SVD(A)$ are from the eigenvectors of $A^TA$. But you need to order them according to the eigenvalues from large to small, and make them orthonormal. $A^TA$ is called Gram Matrix and is related to the covariance matrix $\Sigma$. If the dimensional vectors in $A$ (M of them totally) are all centered already, Gram Matrix = N * Covariance matrix. Check Wikipedia and some tutorials of SVD and PCA.

How can I project original observations $x_i$ onto new reduced space and vice versa?

If applying SVD on $A$ for PCA, it would be $u_i*S$; if applying eigen decomposition on covariance matrix $\Sigma$, and $V$ is eigenvectors of $\Sigma$, it is $x_i*V$.
Comment: just want to add that PCA = eigen decomposition on the covariance matrix  = centering the data matrix A + SVD on the centered A. In this way you will find the singular value of the centered A and the eigenvalue of \sigma are the same.