Can (Dal) Segno and (Dal) Segno Segno appear on the same bar?

Question: This is a follow-up question to my previous question.
I have made a transcription using Guitar Pro 8 of a song with the following structure:
Intro, A, B, A, B, A, Coda
Guitar Pro 8 outputs and plays audio according to what is written on the sheet. After creating the score on my previous question for this transcription -- which did not output the intended structure in the output audio playback -- I created the following one, which did output the intended audio playback (the content of the bars was replaced by whole notes for simplicity):

My idea here was that at the end of the first iteration of the loop, it would pick up the Dal Segno and go back to section A for the second iteration. Then on the end of the second iteration it would pick up the D.S.S al Coda and go back to section A for the third iteration. Then it would reach the Da Coda at the end of section A and jump directly to the Coda.
This solution worked as desired when playing the output audio, but this seems very ambiguous notation to me and it honestly seems yet another case of crazy Guitar Pro behavior.

Is it allowed to put combinations of Segno, Segno Segno, Coda and Double Coda) on the same bar (like in bar 3)?
Is it allowed to put combinations of D.S. (al Coda/Fine/Double Coda) and D.S.S. (al Coda/Fine/Double Coda) on the same bar (like in bar 15)?
Assuming that the answer to the two previous questions is yes, then how is it decided which navigation symbol on bar 3 to jump to first in this example? Is it always the one that does not have al Coda appended to the correspoding Da Segno / Da Segno Segno / Da Capo on bar 15?
Is the score that I presented above valid for this case?

I found some very informative posts about nested repeats and their mixed usage with Segno/Coda navigation marks, but none of them refer to this specific case. The posts I read are:

Dal Segno al Coda and repeats in Guitar Pro. This last one really confirms what I already suspected, which is that Guitar Pro makes its own assumptions when navigation marks such as Da Segno/Da Coda are mixed with repeat signs and sometimes the playback of the audio is unexpected when compared to the sheet.
Are there established good practices for how to use musical navigation markers correctly?
Comment: Are measures 4 and 5 the same?
Comment: @phoog No, they have different content. Why do you ask?
Answer: The double D.S. is confusing. The first thing the player sees at M.15 is "D.S.S. al coda". They take that and go to the coda, so they never reach the second D.S.
See my answer to your previous question for a better way to do this.
Comment: @PiedPier I also thought the same. Unfortunately Guitar Pro 8 forces the _D.S.S._ marker to always be on top of the _D.S._ marker. I did manage however to move the _al Coda_ from the _D.S.S._ marker to the _D.S._ marker. So now, bar 15 shows _Dal Segno Segno_ on top and _D.S. al Coda_ below it. Would you say this is this clear and unambiguous?
Comment: Although it makes sense to me, Guitar Pro 8 only plays Intro, A, B, A, Coda after the edit I mentioned in my previous comment
Comment: I am marking this answer as the accepted one because it shows that mixing navigation markers in the same bar can get confusing for some people and also links to the accepted answer with a solution in my [previous question](https://music.stackexchange.com/questions/132527/how-to-notate-two-nested-repeat-loops-and-that-finish-on-the-same-repe), which is also an answer/solution to this one.
Answer: Are you stuck with using Guitar Pro as your notation program?   What you showed us is impossible to sightread.  It could be acceptable as a 'reference guide' to a song where the player has previously had time to work out the geography.
Comment: For the time being I am stuck with Guitar Pro, unfortunately. I also have the Cubase score editor available, but learning it will involve time and a learning curve, as I haven't started using it yet. It might be time to spend some time on that :) Do you recommend any score editor program? I heard a lot about Sibelius and Finale for example.
Comment: Also, indeed this sheet is not meant for sight reading. Instead, it is one of a collection of 15 to 20 transcriptions for one classical guitar of short VGM pieces (around 20 measures each, none longer than 90 s). I was aiming at 1 transcription per page (of 2 sides). Given that these tracks are VGM MIDI sequences that loop infinitely, I don't want to write a sheet as `Intro ||: A B :|| A Coda` because the final A and Coda are artificial (as in they are not in the actual piece, which just loops infinitely). I mostly want to capture the notes + fingerings for guitar in a compact way.
Comment: Why not notate them as looping infinitely then?
Comment: That's actually a good idea, and it'd be more faithful to the original thing
Comment: The 'big boy' notation programs are currently Sibelius, Finale and Dorico.   But they're expensive.  Investigate MuseScore.  It's free, and a big step up from Guitar Pro for general notation (maybe not for strictly guitar-specific stuff?)  Don't be conned by the easily confused MuseScore subscription library.  You just need the free MuseScore notation program.
Answer: This should be fine, especially once explained. Bar 15 should have a thin double barline for clarity.
Comment: Notation that requires additional explanation always causes problems.
Comment: The missing double barline on bar 15 was a typo, my bad. I didn't realize that the picture did not have it when I posted this question.


Openlayers 4 getting wrong pixel on mouse click

Question: I am using ImageStatic with open layers.I am passing the below extent to the projection
this.extent = [0, 0, 2800, 1280];

Also i am using the below code get the pixel on map click
this.map.on('click', function (evt) {
        console.log(evt);
    });

But the x and y co ordinates value when I click on the map is not correct compared to the original x,y position
Am i missing anything?
fiddlelink
Comment: Coordinates seems ok to me... why you say that they are incorrect?
Answer: After debugging the code i found a that default coordinates of projection starts from BOTTOM LEFT corner (Y is UPWARD)
I fixed this with axisOrientation property of openlayers
Comment: Hey, I had the same issue, whitch axis orientation you put to fix this?


Cuda-gdb not stopping at breakpoints inside kernel

Question: Cuda-gdb was obeying all the breakpoints I would set, before adding '-arch sm_20' flag while compiling. I had to add this to avoid error being thrown : 'atomicAdd is undefined' (as pointed here). Here is my current statement to compile the code:
nvcc -g -G --maxrregcount=32 Main.cu -o SW_exe (..including header files...) -arch sm_20

and when I set a breakpoint inside kernel, cuda-gdb stops once at the last line of the kernel, and then the program continues.
(cuda-gdb) b SW_kernel_1.cu:49
Breakpoint 1 at 0x4114a0: file ./SW_kernel_1.cu, line 49.
...
[Launch of CUDA Kernel 5 (diagonalComputation<<<(1024,1,1),(128,1,1)>>>) on Device 0]

Breakpoint 1, diagonalComputation (__cuda_0=15386, __cuda_1=128, __cuda_2=0xf00400000, __cuda_3=0xf00200000,
__cuda_4=100, __cuda_5=0xf03fa0000, __cuda_6=0xf04004000, __cuda_7=0xf040a0000, __cuda_8=0xf00200200,
__cuda_9=15258, __cuda_10=5, __cuda_11=-3, __cuda_12=8, __cuda_13=1) at ./SW_kernel_1.cu:183
183     }
(cuda-gdb) c
Continuing.

But as I said, if I remove the 'atomicAdd()' call and the flag '-arch sm_20' which though makes my code incorrect, but now the cuda-gdb stops at the breakpoint I specify. Please tell me the reasons of this behaviour.
I am using CUDA 5.5 on Tesla M2070 (Compute Capability = 2.0).
Thanks!
Comment: Breakpoints are not necessarily hit in kernel functions since the CUDA compiler can perform some code optimizations and so the disassembled code could not correspond to the CUDA instructions. The optimizations can be different when changing compute capability. Try taking a look at the disassembled codes: `cuobjdump xxx.cubin --dump-sass`.
Comment: Are you checking all your CUDA calls and the kernel launch for errors? http://stackoverflow.com/q/14038589/442006
Comment: Try running your program with cuda-memcheck. `AtomicAdd()` for 32-bit int has been available since compute capability 1.1, so you can compile for that architecture if you're using ints. `AtomicAdd()` for 32-bit float is available only on CC >= 2.0.
Comment: Yes, there is no error being reported. Is there any other way to compile the code with 'Atomicadd()' call and not including '-arch sm_20' flag? because that way, cuda-gdb would work fine.
Comment: @JackOLantern, do you know if that can happen also in debug builds?
Comment: @RogerDahl I can answer with your own answer to a question of mine, see [NVIDIA Visual Profiler, Debug and Release modes in Visual Studio 2010](http://stackoverflow.com/questions/14245892/nvidia-visual-profiler-debug-and-release-modes-in-visual-studio-2010). [Here](http://stackoverflow.com/questions/18333124/cuda-debugging-with-vs-cant-examine-restrict-pointers-operation-is-not-v), Robert Crovella suggests to use `printf`'s of the variables to avoid compiler optimizations, even with the `-G` debug switch.
Comment: @JackOLantern, heh, that's funny :) I guess I hadn't thought of the optimizations also breaking debugging. Seems it's time that NVIDIA fixes this.
Comment: @RogerDahl Indeed :) Anyway, to quit self-referencing, let me say that, from the CUDA DEBUGGER User Manual, Section 3.3.1, it is written that _The `-g -G` option pair must be passed to NVCC when an application is compiled in order to debug with CUDA-GDB;_ [...] _Using this line to compile the CUDA application forces `-O0` compilation, with the exception of very limited dead-code eliminations and register-spilling optimizations._ So, I would conclude that, in principle, there is no one-to-one mapping between CUDA and disassembled codes and that it may be that the debugger skips the breakpoints.
Comment: @JackOLantern, thanks, good find. So the "aggressive optimization" in debug mode that I mentioned in that answer a year ago is not correct. Hopefully it was correct at the time :)
Comment: Thanks guys, atomicAdd for integers in shared memory works for CC>= 1.2 and compiling code for sm_12 worked for me :) .I had failed to make sense out of the disassembled code, so I experimented by compiling for different architecture.
Comment: One effect of the `-G` switch is to inhibit most device code  compiler optimizations, one intent being to make it easy to set a breakpoint at any valid line of device source code.  I don't think "aggressive optimization" when `-G` is specified is a sensible characterization.  However, as already indicated, there may still be some compiler effects remaining that make setting a particular breakpoint difficult.   Since no actual reproducible example is given in this question, one can only speculate.  If a short, complete example can be provided, then perhaps something more definitive can be said.
Comment: Would somebody like to provide an answer to this question?  The OP has been given a few options (e.g. compile with different arch, printf, etc.), and seems to have chosen one of them.
Comment: @RobertCrovella I have provided an answer to this question.
Comment: Higher register pressure on sm_2x and beyond as compared to sm_1x can be the reason of behaviour I am seeing. [This](https://devtalk.nvidia.com/default/topic/498288/cuda-programming-and-performance/too-many-registers-issue-with-memory-writes-and-registers/) discussion talks about the certain optimizations that were possible on sm_1x, but are no longer possible on sm_2x and beyond. PS: My code runs 40% faster with sm_12 than with sm_20
Answer: From the CUDA DEBUGGER User Manual, Section 3.3.1:

NVCC, the NVIDIA CUDA compiler driver, provides a mechanism for generating the
  debugging information necessary for CUDA-GDB to work properly. The -g -G option
  pair must be passed to NVCC when an application is compiled in order to debug with
  CUDA-GDB; for example,

nvcc -g -G foo.cu -o foo

Using this line to compile the CUDA application foo.cu

forces -O0 compilation, with the exception of very limited dead-code eliminations
  and register-spilling optimizations.
makes the compiler include debug information in the executable

This means that, in principle, breakpoints could not be hit in kernel functions even when the code is compiled in debug mode since the CUDA compiler can perform some code optimizations and so the disassembled code could not correspond to the CUDA instructions.
When breakpoints are not hit, a workaround is to put a printf statement immediately after the variable one wants to check, as suggested by Robert Crovella at
CUDA debugging with VS - can't examine restrict pointers (Operation is not valid)
The OP has chosen here a different workaround, i.e., to compile for a different architecture. Indeed, the optimization the compiler does can change from architecture to architecture.


What does D:2 mean as the drive in a Windows path?

Question: A Windows 2012 server is showing paths starting with D: and with D:2 in Resource Monitor, e.g.:
<code>System        4      D:2\$LogFile
sqlservr.exe  1808   D:2\SQL\LOG\Sp2013_Config_log.ldf
</code>
Screen capture from the Disk pane of Resource Monitor showing file paths starting with "D:2\"
What does it mean when a path begins with "D:2\" rather than "D:\"? Is this particular to Resource Monitor?
I found this similar question, What does "C:0" mean in file path?, but I don't think we are using mounted volumes as in that question and it hasn't been answered anyway.
Assuming it is related to mounted volumes, I found this thread on TechNet that supports the suggestion that it is related to both mounted volumes and Resource Monitor but doesn't give any explanation:
https://social.technet.microsoft.com/Forums/en-US/c9e88df7-cc05-41ae-8e5c-dee9a9654ea5/what-does-c0-in-the-path-mean?forum=winserverfiles
Here is the view from Disk Management as requested:
Screenshot of Disk Management showing the D: drive
Answer: You are almost certainly using a mounted volume. Post a screenshot of diskmgmt.msc if you'd like confirmation.
Comment: I assume that this output from `mountvol D: /L` confirms that the server has mounted volumes: `\\?\Volume{48ff3e96-756e-4f22-838b-113a62c10886}`, but I still can't find any documentation explaining the `D:2` in the path in displayed in Resource Monitor.
Comment: Yes, please - posted.
Comment: Can you show *all* disks? There seem to be a bunch that aren't on the screenshot you sent.
Comment: Sure - I'd hoped just the D: drive would suffice, but I've updated the screenshot to show all drives.
Comment: Does my updated screenshot confirm the presence of mounted volumes? If you could explain what I should be looking for or link to some documentation I can accept your answer. Thanks!


Rehosted Workflow Designer default imported namespaces

Question: I'm trying to rehost the WF4 Workflow Designer. In the "Imports" tab, I'd like to have some namespaces imported by default. It looks like this:
Imported namespaces http://imageshack.us/m/850/5383/imports.png
After a lot of research, I figured out that if you look at
workflowDesigner.Context.Items.GetValue<ImportedNamespaceContextItem>().ImportedNamespaces

you'll get to see things that are already imported. However, adding a namespace manually to this collection does not seem to have any effect. My question, therefore, is: How do I add imported namespaces to this list the right way? Or, how do I get the context to refresh using my manually added namespace imports?

Additional information to the solution below:
In order to solve this, I created my desired "clean slate" activity XAML file, added it to my project, set its Build Action to Embedded Resource and its Custom Tool to empty string.
Then, in the code that initializes my WorkflowDesigner, I do the following:
_Wd = new WorkflowDesigner();

_Wd.Load(
    XamlServices.Load(
        ActivityXamlServices.CreateBuilderReader(
            new XamlXmlReader(
                Assembly.GetEntryAssembly().GetManifestResourceStream( "WpfApplication1.New.xaml" )
            )
        )
    ) as ActivityBuilder
);

Now my work flow has all the desirable namespaces imported.
Answer: The way I do this is by not starting with a completely empty workflow but creating an empty template with the required imports. Add something like:
 xmlns:si="clr-namespace:System.IO;assembly=mscorlib"

to the root activity in the XAML file to import System.IO
Comment: Yeah, I ended up doing this before you posted your solution. Still, I'll give you the "accepted answer checkmark" because your solution is correct.
Answer: Your solution solves a different problem with rehosting stream based activities as well and there is no proposed solution that I could find, so I post this here.
The Symptom is that you get a modal dialog in your designer host, that states a null reference exception in System.Activities.Presentation.View.ImportDesigner.OnContextChanged(),
if you loaded an activity with
ActivityXamlServices.Load(aStream)  // wrong way!

Cause: In
OnContextChanged() // of class ImportDesigner

in https://referencesource.microsoft.com/#System.Activities.Presentation/System.Activities.Presentation/System/Activities/Presentation/View/ImportDesigner.xaml.cs,1d24713ba95e69c5 accessing the .Collection of the "Imports" property raises the null pointer exception. Probably because no information on imported namespaces got loaded.
Solution: Use the Activity
ab.Implementation // of the ActivityBuilder ab

from Alex' post and .Load() it into the WorkflowDesigner instance.
Full code snippet:
public static Activity LoadActivityFrom(FileInfo xaml)
{
  using (var rd = xaml.OpenRead())
  using (var xr = new System.Xaml.XamlXmlReader(rd))
  using (var br = System.Activities.XamlIntegration.ActivityXamlServices.CreateBuilderReader(xr))
  {
    var ab = System.Xaml.XamlServices.Load(br) as System.Activities.ActivityBuilder;
    return ab.Implementation;
  }
}


Simplify expression with matrices and inverses

Question: I have two square invertible positive definite symmetric matrices, $A_1$ and $A_2$, and there is a third square invertible positive definite symmetric matrix which I do not know the value of, $B$. All matrices are of equal size.
I know my matrices satisfy the below equation;
$(A_1+B)^{-1}+(A_2+B)^{-1}=\alpha B$
For some scalar $\alpha$ I know the value of. Is there any way I can solve this expression for $B$? Preferably I'd like to solve this theoretically but if anyone knows of a computational way I am open to suggestions too.
Answer: Not a solution, but an approach. Multiplying the equation (from the left side) with either $(A_1+B)$ and $(A_2+B)$ yields
$$(A_2+B)+(A_1+B) = \alpha B^3 + \alpha (A_1+A_2)B^2 + \alpha A_1A_2 B\, ,
$$
which is a polynomial in $B$ of degree $3$. Since this solution would need to satisfy the case of $1\times 1$ matrices, we firstly try to solve the associtated scalar polynomial equation for $B$. These solutions then would be a candidate for the matrix equation, if you can make sense out of roots of matrices.


How to update the minimum & maximum number of running tasks in ECS

Question: I want to update the min and max number of tasks for a service in ECS in a lambda function (python with boto3). It looks like the closest thing is the desired count: desiredCount, but I don't think that is what I am after as my auto-scaling policy will change this anyway.
A bit more about my use case.
I have some containers on ECS of which poll a queue for jobs, and I to have some number of these always running during working hours, but then none running out of working hours. When load comes into the system my auto-scaling policy will scale out containers but a user would have to wait longer for this to happen when there are no containers, hence I want some always on during working hours.
I am also using AWS Fargate.
Answer: I guess you'll have to do it in 2 steps, using application auto-scaling boto3 client:

Create your ECS service as Application auto-scaling target with register_scalable_target() with for example MinCapacity=3 and MaxCapacity=100. This call will return the scalable targer ARN.
Every evening call register_scalable_target() again with MinCapacity=0 and every business day morning again with MinCapacity=3.

See the register_scalable_target() documentation where it explicitly says:

After you have registered a scalable target, you can use this operation to update the minimum and maximum values for its scalable dimension.

Your auto-scaling policy will then set DesiredCapacity within the Min/MaxCapacity boundaries where the MinCapacity will change from 0 to 3 during business hours and back to 0 after hours.
Hope that helps :)


limit with Taylor expansion

Question: I have a limit:
$$\ \lim_{x \to 0} = \frac{2\arcsin(1-\cos(x))-\tan^2x}{\ln(1+x^2)-\sin^2(x)}$$
I have substituted all the functions with Taylor series and divided by $\ x^6 $
$$\ \frac{2(\frac{1}{2x^3}+\frac{o(x^2)}{x^2}*\frac{1}{x^3}+\frac{(\frac{1}{2}+\frac{o(x^2)}{x^2})^3}{6}+\frac{o(x^3)}{x^3}*\frac{1}{x^2})-(\frac{1}{x}+\frac{1}{3}+\frac{o(x^3)}{x^3})^2}{\frac{1}{x^3}+\frac{o(x^2)}{x^2}*\frac{1}{x^3}-(\frac{1}{x^2}-\frac{1}{6}+\frac{o(x^3)}{x^3})^2} $$
Is it correct? Additionally, I am not sure, how can I calculate the limit for $\ x\to 0.$ For $\ \infty$ it seems to be not to scary.
EDIT
I use:
$$\ \ln(1+x^2)=x^2+o(x^2)\\ \sin(x)=x-\frac{x^3}{6}+o(x^3) \\ \cos(x)=1-\frac{x^2}{2!}+o(x^2) \\ \arcsin(x)=x+\frac{x^3}{6}+o(x^3) \\ \tan(x)=x+\frac{x^3}{3}+o(x^3) $$
Answer: Not quite. Since the Taylor series of the numerator begins with$$-\frac{3 x^4}{4}-\frac{x^6}{3}+\cdots$$and the Taylor series of the denominator begins with$$-\frac{x^4}{6}+\frac{13 x^6}{45}+\cdots,$$you should divide the numerator and the denominator by $x^4$, not $x^6$. You will get that the limit is$$\frac{-3/4}{-1/6}=\frac92.$$
Answer: You received the good answer from @José Carlos Santos.
If I may suggest, when you have to compose Taylor series, work one piece at the time.
For example
$$\cos(x)=1-\frac{x^2}{2}+\frac{x^4}{24}-\frac{x^6}{720}+O\left(x^8\right)$$
$$\arcsin(1-\cos(x))=\frac{x^2}{2}-\frac{x^4}{24}+\frac{x^6}{45}+O\left(x^8\right)$$
$$\tan(x)=x+\frac{x^3}{3}+\frac{2 x^5}{15}+\frac{17 x^7}{315}+O\left(x^9\right)$$
$$\tan^2(x)=x^2+\frac{2 x^4}{3}+\frac{17 x^6}{45}+\frac{62 x^8}{315}+O\left(x^{10}\right)$$
$$2\arcsin(1-\cos(x))-\tan^2(x)=-\frac{3 x^4}{4}-\frac{x^6}{3}+O\left(x^8\right)$$
$$\log(1+x^2)=x^2-\frac{x^4}{2}+\frac{x^6}{3}-\frac{x^8}{4}+O\left(x^{10}\right)$$
$$\sin(x)=x-\frac{x^3}{6}+\frac{x^5}{120}-\frac{x^7}{5040}+O\left(x^9\right)$$
$$\sin^2(x)=x^2-\frac{x^4}{3}+\frac{2 x^6}{45}-\frac{x^8}{315}+O\left(x^{10}\right)$$
$$\log(1+x^2)-\sin^2(x)=-\frac{x^4}{6}+\frac{13 x^6}{45}-\frac{311 x^8}{1260}+O\left(x^9\right)$$
$$\frac{2\arcsin(1-\cos(x))-\tan^2x}{\ln(1+x^2)-\sin^2(x)}=\frac{-\frac{3 x^4}{4}-\frac{x^6}{3}+O\left(x^8\right)} {-\frac{x^4}{6}+\frac{13 x^6}{45}-\frac{311 x^8}{1260}+O\left(x^9\right) }$$ Divide top an bottom by $x ^4$ and continue with long division to get
$$\frac{2\arcsin(1-\cos(x))-\tan^2x}{\ln(1+x^2)-\sin^2(x)}=\frac{9}{2}+\frac{49 }{5}x^2+O\left(x^4\right)$$ which, for sure, shows the limit but moreover how it is approached.
Comment: Thank you for such a step-by-step answer, I'm impressed! However, am I correct to use the expansion approximation as shown in the edited post?

limit with Taylor expansion


Only xamrin live player

Question: I have a problem with Xamarin, i would like to run my program on the simulator like that:
image_from_turorial
to test my program on computer, without android device
but i only see:
onli_live_player
When i create project i choose this:
cross_platform
I do not want to use Xamarin live player, someone know what i should do to see such simulation? :
that_i_want
Comment: Hi, have you solved your problem?
Comment: Thanks for help, but today i can not check this.
Answer: You need to install visual studio Android emulator if not already installed and get emulator devices with it
Answer: Tools->Android->Android Device Manager->New

Choose the Base Device,Processor,OS based upon your Android SDK Manager.

Only xamrin live player


Tkinter Wait for Key to Be Pressed

Question: I am using Python 3 and Tkinter, and I have a wait() function, waiting until the right arrow key or left arrow key is pressed, however, it just freezes everything, and I have to force stop the program.
from tkinter import *

right = left = False

def setLeft(event):
    global left
    left = True
    print('Left!')
def setRight(event):
    global right
    right = True
    print('Right!')

def wait():
    global right, left
    left = right = 0
    while not (left or right):
        pass
    print(right) #0 for left, 1 for right
    left = right = 0

root = Tk()
root.bind('<Left>', setLeft)
root.bind('<Right>', setRight)

Is there a way for the wait() function to work like it is supposed to, or do I need to find a different way?
Comment: Why do you need to wait? A GUI is constantly in a waiting state by default. Just put code you want to run in `setLeft` and `setRight`
Comment: @BryanOakley I want to wait for either key to be pressed, then find out which one it was, so that I can setup a tree of sorts.
Comment: But you know which one was clicked: if `setLeft` is called, the left arrow was pressed.
Comment: @BryanOakley I want to navigate through a tree, which would be much harder if I had to store the state instead of just having a bunch of nested ifs and elses.
Comment: what kind of tree? Is it a tree-like widget? A document (ie: xml)? I don't understand why you think you need to add an additional wait on top of the waiting that the GUI is already doing. Please show a slightly larger example that shows how you plan to actually use this wait function.
Answer: Yes, you need a different way, because of event-driven nature of Tkinter GUI programming. When some event lead you to your wait() function there it is: you're stuck in infinite loop, and you can't get outside with events anymore!
As @Bryan Oakley pointed - GUI is constantly in a waiting state by default, since you reached a mainloop(). And I think, that you trying just suppress all other events (or just navigate keys) when user navigating through a tree , except this two (Left and Right clicks).
So here is a small example:
import tkinter as tk

# Main - application
class App(tk.Tk):
    # init of our application
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.minsize(width=450, height=100)
        self.wm_title('Just another example from SO')
        self.wait_state = False
        self.init_events()

    # switch state
    def switch_wait_state(self, event):
        self.wait_state = not self.wait_state
        print('Wait state switched to: %s ' % self.wait_state)

    # init events
    def init_events(self):
        self.bind('<Key>', self.wait)
        self.bind('<Control-s>', self.switch_wait_state)

    # waiter(listener) for keypress
    def wait(self, event):
        if self.wait_state and any(key == event.keysym for key in ['Left', 'Right']):
            print('I have successfully waited until %s keypress!' % event.keysym)
            self.do_smth(event.keysym)
        else:
            print('Wait state: %s , KeyPress: %s' % (self.wait_state, event.keysym))
            self.do_nhth()

    @staticmethod
    def do_smth(side):
        print("Don't be rude with me, Im trying my best on a %s side!" % side)

    @staticmethod
    def do_nhth():
        pass

app = App()
app.mainloop()

Tkinter Wait for Key to Be Pressed


Why can this question be treated as a question with geometric random variable without any modifications?

Question:
In an infinite sequence of flipping a fair coin - $0.5$ probability to get heads/tails. (every flip is independent from the others).
What is the expected value of number of flips until we get Heads then Tails?

My Attempt:
I tried to think about the event HT as my R.V success. So let $X$ be the number of flips until we get HT.
The probability to get HT in a row is $\frac{1}{4}$, as we need the coin to land on H and then immediately on T.
But I thought to myself that a geometric RV doesn't really count those two as two flips, so I thought that for example:
TTTHHHT -> My random variable $X$ would be $6$.
So I set $Y=X+1$ and my answer was $E(X+1)=4+1=5$.

But turns out the real answer is $4$. Why my method is wrong? where does my logic/understanding fall?
Is it that $X$ is just the answer for this problem? but I can't see how that's right, or maybe I have issues in my geometric random variable understanding.
Would appreciate any help, Thanks in advance!
Comment: I did not understand how you counted $5$
Comment: OK I see now but the random variable will count $HT$ as $2$.
Comment: But $E(X)$ for two heads in a row is $6$
Comment: "real answer" from where?
Comment: @herbsteinberg The writer of the question, the final answer provided with it..
Comment: @MathLover I thought that making the success for $X$ being HT, as two flips, shifts the random variable back by one, lets say I got $TTHT$, then I got 1 fail 1 fail, 1 success, so my random variable (in my eyes) would give me $3$, and that's why I added another $1$, and got to $5$, as $E(X)=4$.
Comment: @MathLover Could you explain why me merging two flips probabilities to define success for my random variable doesn't really change it's behaviour? Why does it count it as $2$ and not $1$?
Comment: But I do not understand your method. How are you calculating it without applying the law of total expectation? For example, if we had to get $HH$ in a row, what would $E(X)$ be by your method?
Comment: $E(X)$ is $4$ always, I defined it as a geometric random variable that counts the number of flips until we see an $HT$, and I calculated that the probability to see $HT$ is $\frac{1}{2}*\frac{1}{2}=\frac{1}{4}$, so $X\sim Geo(\frac{1}{4})$.
Answer: Let $\xi_i$ be the result of the i-th coin toss, and let $X = \min_{n} \{n >0: \xi_n = T, \xi_{n-1}-H\}$
You can use the law of total probability, then you have
$$\mathbb E(X) = \mathbb E(X|\xi_1=H) \mathbb P(\xi_1=H) + \mathbb E(X|\xi_1=T) \mathbb P(\xi_1=T) $$
We can calculate the conditional expectations.
$$X|\xi_1=H \sim 1+Geo(1/2) \implies \mathbb E(X|\xi_1=H) = 1+2=3$$
$$E(X|\xi_1=T) = 1 + E(X)$$
If we substitute the results in the above equation, we get:
$$\mathbb E(X) = 3 \frac 12 + \mathbb (E(X)+1) \frac 12 $$
$$\mathbb E(X) = 4$$
Answer: Here is how I would do it. Say $X$ is the event of getting $H, T$ in a row. Based on the first flip, we have two cases -
$i$) The first flip is $H$ - Then we are seeking the next flip to be a $T$. If we get $T$, we are done but if we get $H$, we are again looking for a $T$ and so on.
$ii$) The first flip is $T$ - We spent a flip and we are again back to where we started, that is seeking $H, T$.
So, $E(X) = 1 + \frac{1}{2} E(X) + \frac{1}{2} E(T)$
Now we know $E(T) = 2$
So, $E(X) = 4$


Inequality question about average and exponent

Question: Saw this being taken for granted in another post:
We know $$\frac{\sum_{1\le r\le n}a_r^m}n> \text{ or } <\left(\frac{\sum_{1\le r\le n}a_r}n\right)^m$$ according as $m$ lies  or does not lie in $(0,1)$.
How do we know this? Thanks!
Comment: Jensen's inequality.
Answer: I think that it is the
power-mean inequality,
which states that,
if the
$a_k > 0$,
then
$$M_p(a)
=\left(\frac1{n}\sum_{k=1}^n a_k^p\right)^{1/p}
$$
is an increasing function
of $p$.
So,
since
$M_1(a)
=\frac1{n}\sum_{k=1}^n a_k
$,
if $p < 1$,
$\left(\frac1{n}\sum_{k=1}^n a_k^p\right)^{1/p}
< \frac1{n}\sum_{k=1}^n a_k
$,
or
$\frac1{n}\sum_{k=1}^n a_k^p
< \left(\frac1{n}\sum_{k=1}^n a_k\right)^p
$.
The reverse inequality holds for
$p > 1$.


If a neural network performs very well on training data, does that mean it is overfitting?

Question: In a (including convolutional) neural network, suppose I get a fair accuracy (say, $\approx 80\%-90\%$) on my validation/test data, but extremely good accuracy ($\approx 100\%$) if I run it back on my training data.
Does this necessarily mean that my network is overfitting, and I should apply some techniques (get more data, regularize, etc.) to handle it? In other words, can I conclude that my network is overfitting, or very highly likely overfitting? Are there other reasons why this can happen?
Answer: The training error is always going to be somewhat smaller than the validation error (because you're actively trying to minimize the training error) - that in itself is not a sign of overfitting. Overfitting means you decreased the training error at the expense of a higher validation ($\approx$ generalization) error. For iterative optimization procedures, you can diagnose this by plotting the training and validation error/performance over time (i.e. over successive iterations of the optimization algorithm). If, at some point, the validation error stops decreasing or even starts increasing while the training error still decreases, that is a pretty sure sign of overfitting.
For learning problems with analytical solutions (e.g. regression), you can see whether the validation performance improves when you apply regularization. If so, then the non-regularized solution was probably overfitting the training data.
Answer: I'd say very highly likely. A training accuracy of 100% is acceptable only if the data isn't noisy (which is definitely not the case for image recognition). If not, you probably are learning unnecessary noise, which is not going to allow the net to generalize well, since it "belongs" only to that particular training set instance.


Coefficient stability between two different models

Question: I have applied two different models. One OLS model with independent variables X1, X2, X3 and one ridge model with independent variables X1, X2, X3, X4 and X5 through glmnet package in R. So let's say for OLS model we receive the following Y = a1 + b1*X1 + c1*X2 + d1*X3 and from ridge model for different lambda we receive Y = a2 + b2*X1 + c2*X2 + d2*X3 + e*X4 + f*X5. Is there any way to test the null hypothesis that H0:a1=a2, b1=b2, c1=c2? More specifically I want to apply this test for all different models of all lambda with OLS.
I tried to apply a chow test but I do not think that this test works for this issue.
Comment: Isn't it easier to test that e, f=0 in the second case? Also, if X1, X2, X3 are not linearly independent there may be more than one way to combine them linearly to get the same prediction for Y
Answer: Looking at basic description of ridge regression it seems this is about finding coefficients $\boldsymbol{\beta}$ for the linear model:
$$
y=\mathbf{x}^T.\boldsymbol{\beta}+\epsilon
$$
Where $y$ is the dependent variable $\mathbf{x}$ is a vector of independent variables and $\epsilon$ is noise. We don't need to know the distribution of noise for regression, but for things like standard errors we will need it. In Chow test the residuals are assumed to be normally distributed, so we might as well assume it here: $\epsilon\sim \mathcal{N}(0,\,\sigma^2)$.
Given measured vector of dependent variable $\mathbf{Y}$ and design matrix with independent variable measurements $\mathbf{X}$, the estimator for the ridge regression is:
$$
\boldsymbol{\hat{\beta}}=\left(\mathbf{X}^T.\mathbf{X}+\lambda\mathbf{I}\right)^{-1}.\mathbf{X}^T\mathbf{Y}=\mathbf{A}.\mathbf{Y}
$$
Where $\lambda\ge0$ is your regularization constant (known). Treating $\mathbf{Y}$, and the estimator as a random variables, given $\mathbf{X}$, their distributions are:
$$
\begin{align}
\mathbf{Y}\,\big|\,\mathbf{X},\lambda&\sim\mathcal{N}\left(\mathbf{X}\boldsymbol{\beta},\,\sigma^2\mathbf{I}\right)\\
\boldsymbol{\hat{\beta}}\,\big|\,\mathbf{X},\lambda&\sim\mathcal{N}\left(\mathbf{A}\mathbf{X}\boldsymbol{\beta},\,\sigma^2\mathbf{A}\mathbf{A}^T\right)
\end{align}
$$
Both OLS and ridge regression can be treated under this framework, the former with $\lambda=0$. So then your question becomes a question about comparing coefficients from two $\boldsymbol{\hat{\beta}}$. The two could have different variances and different means.
I guess you want to test that some means of the coefficients from two $\boldsymbol{\hat{\beta}}$ are different. This boils down to comparing means from two different multivariate distributions. If you assume equality of variance, you will end up with some version of a t-Test. Uni-variate or multi-variate depending on how you choose your null hypothesis. I am sure there is plenty of literature on this, starting from wiki.
More generally, you may end up with some version of Welch's test. I would probably go with something Bayesian instead, i.e. estimate the probability distribution for $\boldsymbol{\beta}$ given what you have observed, and then estimate the probability that the two beta-s are equal within some margin.


Heatmap based on gene expression trend

Question: Can anybody guide me on the R code for the following problem?
My data contains expression values of Genes A, B, C, D, E, F, G, H, and I in a time course study for two time steps, 48 and 72 hours, with and without a treatment.
The dummy data looks like this:
Gene Names      Fold change 48h              Fold change 72h
A               1.2                          4.6
B               1.2                          1.2
C               2.3                          1.4
...             ...                          ...

Expression values of Genes A,B and C show continually increasing trend.
Expression values of Genes D,E and F remained approximately same for the two time points. Genes G, H and I had higher expression in 48h but decreased in 72 hour time point.
How can I cluster these "three" groups of genes based on the criteria described above?
I can create a heatmap using hclust etc.
Comment: Is does not seem right. You already know your clusters and would like to see code implementing a method that returns the groups you want? It should be the other way round: Given your data, what are the groups that a clustering algorithm can identify?
Comment: Questions asking for code help are generally off topic here.
Answer: Reproducible data structure...
something like this?
df <- data_frame(
  Gene = rep(letters[1:8], times = 2),
  Timestep = c(rep('48h', times = 8), rep('72h', times = 8)),
  Expression = rnorm(n = 16)
)

what about the treatment vs no treatment group?

Here is something to start with:
library(tidyverse)
set.seed(12345)
gene_data <- spread(df, key = Timestep, value = Expression)

# Get cluster membership for each row (gene)
clusters <- kmeans(gene_data[,2:3], 3, nstart = 20)

# Combine cluster membership with gene_data
gene_clusters <- cbind(gene_data, cluster = clusters$cluster)

# Plot clusters
gene_clusters %>%
  ggplot(aes(x = `48h`, y = `72h`, col = cluster)) +
  geom_point() +
  theme_bw()

Heatmap based on gene expression trend


Are eigenvalues of sum of two matrices equal to sum of other two matrices with identical eigenvalues?

Question: Consider I want the eigenvalues of $C=AA^T+BB^T$. How can I prove that the non-zero eigenvalues of $C$ is equal to matrix $D$ in which $D=A^TA+B^TB$?
If not possible in general, $A$ and $B$ are i.i.d Gaussain matrices.
I know this claim is true as I simulated it in Matlab.
EDIT: I also Assume that C has no Zero eigenvalues
Comment: "I know this claim is true as I simulated it in matlab": first of all, experiments don't qualify as proofs.  Second, are you trying to prove that it's true for all matrices, or that it occurs with $100\%$ probability?
Comment: @Omnomnomnom I understand that simulations are not reliable, but in my case they work. I just want to show using one is equal to use the other one to proceed. The general case is not important if it is hard, just the Gaussian case.
Answer: This isn't true. E.g.
$$
A=\pmatrix{0&1\\ 0&0},\ B=\pmatrix{1&0\\ 0&0},
$$
$$
C=AA^T+BB^T=\pmatrix{2&0\\ 0&0},\ D=A^TA+B^TB=\pmatrix{1&0\\ 0&1}.
$$
The only nonzero eigenvalue of $C$ is $2$ and it is not an eigenvalues of $D$.
It is true, however, that when all entries of $A$ and $B$ are i.i.d. $N(\mu,\sigma^2)$, we have
$$
\mathbb E(C)=\mathbb E(D)=2n(\sigma^2I_n+\mu^2E)
$$
where $E$ is the all-one matrix.
Comment: @MasoudArash Whether $C$ has a zero eigenvalue is unimportant. If you perturb the $A$ and $B$ in my answer by a small $\epsilon I$, you will still get a counterexample, but $C$ and $D$ are positive definite in this case.
Comment: I want to work with the trace of inverse of their sum, i.e. $D^{-1}$. The point is that in my case, D is not a Wishart Matrix, but C is.
Comment: I also Assume that C has no Zero eigenvalues. Sorry that I didn't mention that in the Question. It is edited now.


How to set a list of integers while preparing SQL queries in Java

Question: I have a query like this - select * from tbl where ... and colname in (2,3,4)
When I prepare the query (... ' colname in (?)' ) using a PreparedStatement in Java, what setter method should I call to set these integers ? The integers are available in an int array and the size varies. If it matters, the database is MySQL and the column in question is of int type.
Comment: wondering why this is not the highest rated question on SO! ;)
Answer: you can use another syntax
<code>WHERE colname = ANY (?)
</code>
and call PreparedStatement.setArray(). You have to provide an instance of java.sql.Array as parameter.One advantage of ANY instead of IN is, that you can pass an empty array without causing a SQL syntax error.
Comment: How to create an instance of java.sql.Array ? I am not getting anywhere in finding that out.
Answer: As an addendum to Learning's explanation:
Creating an Array can be tricky.
There's a creator method in Connection in JDK 1.6 and later.
http://download.java.net/jdk7/docs/api/java/sql/Connection.html#createArrayOf(java.lang.String,%20java.lang.Object[])
Since JDK1.6 is the latest stable release, your JDBC drivers may not support it.
You can try and create your own Array implementation, but that may not work with all JDBC connector implementations.


Libgdx : how to draw line using shape renderer?

Question: I am trying to make a matching game using Libgdx.
I am working on stage and want to draw a line e.g. if I touch "A" alphabet which will be the initial point then the line starts on that point from where I touch on "A" image and drag it to the "Apple" image and the line ends on  "Apple"  image and so on to match the rest of the alphabets and that line can also rotate 360 degrees. I have tried to draw it using Shape Renderer. can anybody help me to achieve that? here is my game screen...
Comment: Does this answer your question? [how to connect 2 images through line in Libgdx](https://stackoverflow.com/questions/73202367/how-to-connect-2-images-through-line-in-libgdx)
Answer: When the mouse is just pressed on one of the left images, create a temporary variable to store the mouse position and then once the mouse is just let go of on another image, draw a line using ShapeRenderer like this:
sr.line(tempMousePosOnClick, tempMousePosOnLetGo);

Both variables in the function are Vector2s btw.
Also, there is no default function for checking to see if the mouse was let go of but using InputProcessor, you can code it yourself (I already have done it for one of my projects so here it is:
package com.physicsSimApplicationEisa.physicsSimulator2d;

/**
 * InputProcessor to process more complicated input than Gdx.input.XXX can
 */
public class InputProcessor implements com.badlogic.gdx.InputProcessor {
    private static final boolean[] justPressedButtons = new boolean[5];
    private static final boolean[] justLetGoButtons = new boolean[5];
    private static final boolean[] justPressedKeys = new boolean[255];
    private static final boolean[] justLetGoKeys = new boolean[255];

    private static String keyValue;

    private static Integer keycodeOfKeyDown;
    private static Integer keycodeOfKeyUp = -1;

    private static boolean isKeyUp = false;
    private static boolean isKeyDown = false;

    private static Integer keycodeOfButtonDown;
    private static Integer keycodeOfButtonUp = -1;

    private static boolean isButtonUp = false;
    private static boolean isButtonDown = false;

    private static boolean isKeyJustDown = false;
    private static boolean justTouched;
    private static boolean justLetGo;
    private static boolean justPressed;
    private static boolean justUp;

    /**
     * @return String: the value which was typed i.e. for the key Input.Keys.A, it would be 'a'
     */
    public static String getKeyTyped() {
        return keyValue;
    }

    /**
     * @return int: the keycode for the key that was pressed.
     */
    public static int getKeyPressed() {
        return keycodeOfKeyDown;
    }

    /**
     * @return int: the keycode for the key that was most recently pressed but is not anymore.
     */
    public static int getKeyLetGo() {
        return keycodeOfKeyUp;
    }

    /**
     * @return int: the keycode for the button that was pressed.
     */
    public static int getButtonPressed() {
        return keycodeOfButtonDown;
    }

    /**
     * @return int: the keycode for the button that was most recently pressed but is not anymore.
     */
    public static int getButtonLetGo() {
        return keycodeOfButtonUp;
    }

    /**
     * @return boolean: whether any key is pressed.
     */
    public static boolean isKeyDown() {
        return isKeyDown;
    }

    /**
     * @return boolean: whether any button is pressed.
     */
    public static boolean isButtonDown() {
        return isButtonDown;
    }

    /**
     * @return boolean: whether any key is not up (must have been pressed to be able to be up)
     */
    public static boolean isKeyUp() {
        return isKeyUp;
    }

    /**
     * @return boolean: whether any button is not up (must have been pressed to be able to be up)
     */
    public static boolean isButtonUp() {
        return isButtonUp;
    }

    /**
     * @return boolean: whether a specific key is pressed.
     */
    public static boolean isKeyDown(int keycode) {
        return isKeyDown && getKeyPressed() == keycode;
    }

    /**
     * @return boolean: whether a specific button is pressed.
     */
    public static boolean isButtonDown(int button) {
        return isButtonDown && getButtonPressed() == button;
    }

    /**
     * @return boolean: whether a specific key is not up (must have been pressed to be able to be up)
     */
    public static boolean isKeyUp(int keycode) {
        return isKeyUp && getKeyLetGo() == keycode;
    }

    /**
     * @return boolean: whether a specific button is not up (must have been pressed to be able to be up)
     */
    public static boolean isButtonUp(int button) {
        return isButtonUp && getButtonLetGo() == button;
    }

    /**
     * @return boolean: whether any key is just pressed.
     */
    public static boolean isKeyJustDown() {
        for(boolean b : justPressedKeys) {
            if(b) {
                return true;
            }
        }
        return false;
    }

    /**
     * @return boolean: whether any button is just pressed.
     */
    public static boolean isButtonJustDown() {
        for(boolean b : justPressedButtons) {
            if(b) {
                return true;
            }
        }
        return false;
    }

    /**
     * @return boolean: whether any key is just up (must have been pressed to be able to be up)
     */
    public static boolean isKeyJustUp() {
        for(boolean b : justLetGoKeys) {
            if(b) {
                return true;
            }
        }
        return false;
    }

    /**
     * @return boolean: whether any button is just up (must have been pressed to be able to be up)
     */
    public static boolean isButtonJustUp() {
        for(boolean b : justLetGoButtons) {
            if(b) {
                return true;
            }
        }
        return false;
    }

    /**
     * @return boolean: whether a specific key is just pressed.
     */
    public static boolean isKeyJustDown(int keycode) {
        return justPressedKeys[keycode];
    }

    /**
     * @return boolean: whether a specific button is just pressed.
     */
    public static boolean isButtonJustDown(int button) {
        return justPressedButtons[button];
    }

    /**
     * @return boolean: whether a specific key is just up (must have been pressed to be able to be up)
     */
    public static boolean isKeyJustUp(int keycode) {
        return justLetGoKeys[keycode];
    }

    /**
     * @return boolean: whether a specific button is just up (must have been pressed to be able to be up)
     */
    public static boolean isButtonJustUp(int button) {
        return justLetGoButtons[button];
    }

    public static void update() {
        if(justTouched) {
            justTouched = false;
            for(int i = 0; i < justPressedButtons.length; i++) {
                justPressedButtons[i] = false;
            }
        }

        if(justLetGo) {
            justLetGo = false;
            for(int i = 0; i < justLetGoButtons.length; i++) {
                justLetGoButtons[i] = false;
            }
        }

        if(justPressed) {
            justPressed = false;
            for(int i = 0; i < justPressedKeys.length; i++) {
                justPressedKeys[i] = false;
            }
        }

        if(justUp) {
            justUp = false;
            for(int i = 0; i < justLetGoKeys.length; i++) {
                justLetGoKeys[i] = false;
            }
        }
    }

    /**
     * Used to get the keycode of the key pressed without knowing which key it was.
     *
     * @param keycode int: the keycode of the key that was pressed.
     */
    @Override
    public boolean keyDown(int keycode) {
        isKeyDown = true;
        isKeyUp = false;

        justPressedKeys[keycode] = true;
        justLetGoKeys[keycode] = false;
        justPressed = true;
        justUp = false;

        keycodeOfKeyDown = keycode;
        keycodeOfKeyUp = null;
        return false;
    }

    /**
     * Used to get the keycode of the key let go without knowing which key it was.
     * Also sets the key value to "" to avoid the key value being the same as a key that was pressed
     * but is not anymore.
     *
     * @param keycode int: the keycode of the key that was let go
     */
    @Override
    public boolean keyUp(int keycode) {
        isKeyUp = true;
        isKeyDown = false;
        keyValue = "";

        justPressedKeys[keycode] = false;
        justLetGoKeys[keycode] = true;
        justPressed = false;
        justUp = true;

        keycodeOfKeyUp = keycode;
        keycodeOfKeyDown = null;
        return false;
    }

    /**
     * Sets the keyValue to the key that was typed without knowing which key it was.
     *
     * @param character char: the key that was typed
     */
    @Override
    public boolean keyTyped(char character) {
        isKeyDown = true;
        if(!isKeyJustDown) {
            isKeyJustDown = true;
        }
        isKeyUp = false;
        keyValue = "" + character;
        return false;
    }

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        isButtonDown = true;
        isButtonUp = false;

        justPressedButtons[button] = true;
        justLetGoButtons[button] = false;
        justTouched = true;
        justLetGo = false;

        keycodeOfButtonDown = button;
        keycodeOfButtonUp = null;
        return false;
    }

    @Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        isButtonUp = true;
        isButtonDown = false;

        justPressedButtons[button] = false;
        justLetGoButtons[button] = true;
        justTouched = false;
        justLetGo = true;

        keycodeOfButtonUp = button;
        keycodeOfButtonDown = null;
        return false;
    }

    @Override
    public boolean touchDragged(int screenX, int screenY, int pointer) {
        return false;
    }

    @Override
    public boolean mouseMoved(int screenX, int screenY) {
        return false;
    }

    @Override
    public boolean scrolled(float amountX, float amountY) {
        return false;
    }

}

SUMARRY
Basically here is the code you would need to write using the InputProcessor class (of course this code isn't fully valid, you'll have to implement it into your application yourself):
(Eventually you might have to .unproject() the mouse position to get it to be correctly but assuming you're not using a moving camera etc. that won't be a hassle yet)

private Vector2 temp, temp2;
private boolean isHoveredOnLetterImage, isHoveredOnResultImage; // need to be updated by checking if the image contain the mouse position vector

@Override
public void render(float delta) {
    if(InputProcessor.isButtonJustDown(Input.Buttons.RIGHT) && isHoveredOnLetterImage) { // only if it was just pressed and it was hovering on the image
        temp = new Vector2(Gdx.input.getX(), Gdx.input.getY());
    }
    if(InputProcessor.isButtonJustUp(Input.Buttons.RIGHT) && isHoveredOnResultImage) {
        temp2 = new Vector2(Gdx.input.getX(), Gdx.input.getY());
    }
    sr.line(temp, temp2);
}


In a managed environment, should user PCs have local external HD backups?

Question: Our environment manages thousands of user PCs, provides high-end secure file servers.  Users (from new staff to executive-level) are urged to store data to the file servers and generally do so.  PCs are acquired with a standard HD image (currently Win XP) and configuration, but users have different needs and accumulate different installed software, configuration for individual apps, and at any given time have some files on their desktops.
Catastrophic PC failures are unusual but they do occur.  IT staff:user ratio is about 1:150.  Restoring PC function/configuration can be labor-intensive (local HD data recovery is not offered).
Virtual desktop delivery from centralized servers would be a great, but is not yet a reality due to constraints on resources (server purchase, bandwidth, etc) and the technology is still a moving target.
Some users have purchased local external HD backups, but there is no coherent guidance on device selection or configuration, partly because leadership has not settled on whether these devices are "a good thing".
A standardized approach to local HDs would simplify purchase and recovery procedures, but would increase acquisition cost per PC and might encourage laxity in data storage practices.
Are there best practices for local HD backup in a managed environment?
Comment: I hope you meant IT staff:user ratio is 1:150, otherwise that's really weird :)
Comment: @Kamil: actually that earlier ratio was right - we back up the servers using 1.44 MB floppies (to save money, we buy the 720K floppies and burn the hole in the corner with a hot paper clip).
Answer: You mention 'secure file servers' in your question. I would see external backups as a potential risk - what if some steals one of these? In terms of data protection, unless the data is backed up properly by users you are likely to be in trouble. It is difficult to make sure this happens if the environment is hetereogenous as you state. You could:

Have a mandatory training session around data protection for end users, or identify power users at a local level who can help embed best practices.
Install disk imaging software like Acronis so that the external hard drives have images rather than file backups. Use permissions to control who can write to the hard disks to prevent them being used for file backups.

By allowing these drives you are in some ways delaying your ability to put better measures in place at an enterprise level because the execs say why do we need to pay for this when users already have a 'backup' in place (assuming they can't understand the issues).
Answer: This is a tough question that we've been asked to address on a few different occasions. We've experimented with a few different solutions, none of which have worked well. Right now we have a policy of "use the file servers or lose the data" for all users except some executive types and a few users with exceptional requirements.
The unmanaged external backup route wouldn't be acceptable to us, because regulation & policy requires encryption for all data at rest on portable devices. Doing that in a controllable way will be expensive until Windows 7.
I've heard that some GE divisions are using an Enterprise version of Mozy to backup laptops -- that might be a solution that works for you. It also might be possible to leverage a de-duplicating backup solution like PureDisk or Avamar to backup workstations centrally -- at a cost.
Answer: The last time I worked with a very small IT group with a support ratio like yours, their users were used to having a D partition that would survive reimaging.  Were I backing up that partition on an enterprise scale, I would definitely have something server-based, and NOT relying on something the users could kick, detach, lose, etc.
Answer: I have a very hard-liner type of mentality. Data goes on the server computers (replicated using "Offline Files" on portable comptuers as necessary) and permissions are ratcheted down to prevent saving data local hard disk drives or USB-attached mass storage devices. (Per-machine and per-user temporary directories are cleaned up on a per-boot and per-logon basis, respectively.) Ideally, corporate security / IT policy documents back this up, too.
I've been told by friends who worked in "big" enterprises that this strategy is wholly unrealistic for "large" environments. I disagree, but I will offer the caveat that the largest environment that I get to enforce this kind of strategy in only has roughly 1,000 PCs. (I'm sure that I'm just a starry-eyed optimistic kid when it comes to this...)
My guiding thoughts are:

PCs are easy to steal. External hard disk drives, doubly so. I want confidential data to remain confidential. (Portable computers use full-disk encryption.)
PCs should be stateless, easily replaceable, and basically interchangable. (It sounds like you're not up to the level of automatically deploying software so this probably isn't an option for you. It's a godsend, if you can get it.)
Users should be able to access their data (though not necessarily have all their application software) from any client computer in the network.
IT does IT's job, and users do the user jobs. That means IT handles backups / restores / etc. "Self service" solutions like "Previous Versions" are one thing, but putting users in out-and-out control of their backups is another. It's not that they can't handle it, but rather that they shouldn't have to. (Having everyone responsible for their own backups would be, to me, like having everyone responsible for their own payroll withholding calculations...)

Like I said, I've been told in the past that this is unrealistic. (I fail to see, with proper "back billing" to departments for their employees' usage of file server and backup resources, how this can't be realistic... but-- hey-- not fighting BS corporate politics battles is one of the reasons I'm a 'hired gun' contractor for project work and not a day-in day-out corporate IT admin...)
There's an implicit trust level in this strategy that IT is doing IT's job. If I was in an executive position and found out that my IT group wasn't fulfilling the basic functions of reliable backups (and all the things that make backup truly a backup) my response would be severe and swift.
This strategy also implies management buy-in. If you don't have that, don't bother. (I'd be looking for another job... >sigh<)
Edit:
I'd love to have a detailed conversation with someone who can tell me why it's unrealistic to expect users to save all their data onto server computers. I'm not personally offended by the position counter to mine, but I simply can't wrap my mind around the idea that the products of the work of potentially highly-paid employees should be treated with such a lack of care.
No offense is intended to the commenters here when I say this, but I just can't understand the logic. I've been told so many times that what I think is unrealistic, but the "throw some numbers in a spreadsheet" calculations that I've run make me thing that the "hard costs" of centralized storage and backup aren't too much more than a decentralized solution. When you throw in the "soft costs" (and the assumption that the IT department will follow through on such a basic duty as stewardship of user / departmental data), it seems like a "no brainer" that it would be cheaper and more efficient to have all data stored and managed centrally.
This is one of those "truisms" of large-scale IT management that I just don't buy, and I've love to see some data one way or the other to back it up. I have yet to see any data from anyone that substantiates the position of it being wholly cost-ineffective to store and manage data centrally. I generally get some hand waving and vague statements about backup and enterprise storage being expensive, but that's typically where it ends. In organizations that are larger than those for whom I am personally responsible where I've had contracts I've seen baroque "solutions" such as storing disk images of tens or hundreds of "critical computers", time-consuming and performance-sapping logon scripts that XCOPY the contents of "My Documents" to server computers, and out-and-out disclaimers of any responsibility by IT departments to be responsible for data storage.
I accept that there are attitudes in users and management, primarially caused by past dysfunctional IT experiences that these people have had, that drive the decision to have decentralized storage. I also think that these attitudes don't take into consideration (or radically underestimate) the expense to the business in the event of data loss, or in breaches of security. In fact, I'd go so far as to say that the way that businesses treat the data created by their "knowledge workers" generally fails to take into account the value that this data could have to other parts of the business in decision support or saving duplicated labor (as is evident to me in the environments where I've seen out-of-control "home directories" and such).
This whole issue strikes me as a management problem associated with businesses not being able (or willing) to ascribe value to data. Because no value is ascribed, it seems to be that businesses are assuming that no value (or very little value) is present.
Comment: Your "hard-line", security-focused approach works where the workloads are very static (ie. call center, retail POC, etc), or you are purposefully limiting capability (ie. computer lab, kiosk). But most knowledge workers end up running into enough exceptions that the cost of managing those exceptions exceeds the cost of other mitigating measures (Encryption, DLP, policy, etc).
Comment: I agree with the spirit of your comments, and the perspective of those who've told you it won't work in some environments, like mine.
Comment: Not unrealistic at all, I worked in a very large place where this was the case.
Answer: In my last job, we took the approach of making sure computers were purchased with the smallest sized drives we could get away with.  Combined with that, we would install Symantec Backup Exec System Recovery Desktop Edition on the PCs that were the most critical to keep running.
The problem comes up as to where to put the backup data.  For laptop users, it makes sense to use an external drive.  For desktop users, adding another internal drive is the cheapest solution if you can make sure the user doesn't use that drive to store data themselves.
You don't have to store that data for long since this is not for archiving data but for use in recovering the PC to a state before it died.  Make sure the user knows this!  Don't even hint that you could recover data they deleted since the last snapshot or YOU WILL REGRET IT!
Answer: If the information is critical and needs to be backup in real-time, use network drives as you are doing.
If the information is not critical (ie: you can accept to roll back one day), you need to add a NAS/SAS backup solution to your WinXP image. Setup a storage area, and have the backup client run daily (you might want to load balance that if you have a very large PC base).
This way it's not backuping in real-time (you can't have all your network sync'ing in real time... well you could but it would cause a fortune in network equipment to properly manage that), but all your PC base is better protected than the average, and you don't run the security risk of having people free to plug USB drives on their computer (and, therefore, into your network). And also, you are in charge of the backup policy, so you have one policy, not one for each user with his own tricks to arguably backup their data properly.


How to list subdirectory in the same order of date of creation with Python 2.7 under Linux?

Question: I have subdirectory 'f' under base_path.
My python Skript is creating 5 Directory after each other under "base_path". example like this ('a','b','c','d','e').  So now I have under base_path one old Directory ('f') and 5 new Directory ('a','b','c','d','e').
I listed the new with:
os.chdir(base_path)

for i in range (5):
    dirs = [os.path.join(os.getcwd(),d) for d in os.listdir(os.getcwd()) if ((os.path.isdir(d)) and 'f' not in d)]

    print dirs

I have a list like
['e', 'a', 'b', 'c', 'd']

but i want a function that append every new created Directory to have:
[ 'a', 'b', 'c', 'd', 'e']

In the same order of their date of creation.
Note: it worked with 4 Directory but with 5 Directory no.
Comment: Try replacing `os.listdir(os.getcwd())` with `sorted(os.listdir(os.getcwd()), key=lambda x: os.path.getmtime(os.path.join(os.getcwd(), x)))`
Comment: Thank you :) it worked!!
Answer: You need to sort the files returned by os.listdir() into modified time order. This can be done by sorting on the value returned by os.path.getmtime() for each file as follows:
os.chdir(base_path)

for i in range (5):
    dirs = [os.path.join(os.getcwd(),d) for d in sorted(os.listdir(os.getcwd()), key=lambda x: os.path.getmtime(os.path.join(os.getcwd(), x))) if ((os.path.isdir(d)) and 'f' not in d)]

    print dirs


how to prevent the json data output being alphabetically sorted and stored in mysql work?

Question: Hi I'm trying to insert complex json data in mysql workbench but my json data being inserted alphabetically sorted. How do I get json data with same order which I passed in insert query?
Create table:
CREATE TABLE payload ( `id` INT NOT NULL,
      `json` JSON NOT NULL,
      PRIMARY KEY (`id`));

Insert Json
INSERT INTO payload ( id, json)
VALUES  (2, '{
    "request": "release",
    "type": [
        {
            "type" : 1
        }
    ],
    "start": [
        {
            "type": "sample",
            "id": "01",
            "content": [
                {
                    "name": "jon",
                    "email": "email@example.com"
                }
            ]
        }
    ]
}');

stored json in database after select * table name:
'3', '{\"type\": [{\"type\": 1}], \"start\": [{\"id\": \"01\", \"type\": \"sample\", \"content\": [{\"name\": \"jon\", \"email\": \"email@example.com\"}]}], \"request\": \"release\"}'

Actually I want to have store my json same as my inserted json in database.
Is there a way to prevent the json data being alphabetically sorted?
Thanks.
Comment: @nancy The order of properties should not matter in json data type. If you want to preserve the order, then store it as a string. Retrieve it and convert it into json. But you will not be able to leverage the advantages of making it a json data type.
Comment: Why does the order of properties matter?
Comment: yes. I will read that json as input
Answer: Mysql will automatically sort the keys of a JSON object before it's stored.
I had the same problem!
The solution is to change the column type to 'text' and then the order of keys will not be changed!
Answer: Use serialize before storing. The conversion will make the array unrecognizable to MySQL so when retrieved and restored with unserialize it will be in the exact same order as before storage.
The drawback is the native MySQL json functions and methods can't be used to search and manipulate the array. Serializing is good only for storing and retrieving.
The only other way is to add a key with a value representing the array's sort order. That drawback is that the array must be sorted to restore it to its original state.


Read multiple csv files within a function

Question: I'm trying to read multiple .csv files using a function and have found lots of similar questions/answers but none seem to address my specific issue.
The following code works fine
id=3:5

selected_files=list.files()[id]

for(i in 1:length(id)){
assign(selected_files[i], read.csv(selected_files[i]))
}

However, when putting this code inside a function the code runs but no files are read in
readfiles=function(id){
selected_files=list.files()[id]
for(i in 1:length(id)){
assign(selected_files[i], read.csv(selected_files[i]))
 }
}

Any help?
Comment: Use `lapply(selected_files, read.csv)`
Answer: All of your dataframes are being set within the the function environment, not the global environment. Change your assign() to
assign(selected_files[i], read.csv(selected_files[i]), envir = .GlobalEnv)


Explanation of an example of the Bayes Estimator

Question: In section 4.4 of 'Introduction for Machine Learning' by Ethem Alpaydin the following example of estimating a prior density us given:

For example let us say that we are told that [the random variable] $\theta$ is approximately normal and with 90 percent confidence, $\theta$ lies between 5 and 9, symmetrically around 7. Then we can write $p(\theta)$ [(the prior density)] to be normal with mean 7 and because:
  \begin{align}
P\{-1.64 < \frac{\theta - \mu}{\sigma} < 1.64\} &= 0.9\\
P\{\mu  -1.64\sigma < \theta < \mu + 1.64\sigma\} &= 0.9
\end{align}
  we take $1.64\sigma = 2$ and use $\sigma = 2/1.64$. We can thus assume $p(\theta) = \mathcal{N}(7, (\frac{2}{1.64})^2)$.

Based on the information given I think that $p(\theta)$ looks like this:

However I do not fully understand the equalities form the example. Since the confidence interval is 90% the standard error of the mean is 1.64. But how do you go from that knowledge to the equalities in the example. Why is the z-score used in the first equality? And why do they take 1.64$\sigma = 2$, I assume that that has something to do with the fact that $9 - 7 = 7 -5 = 2$.
Please note that I know that I can find the standard deviation by solving the following equation:
\begin{equation}
 \int_5^9 \frac{1}{\sqrt{2\pi}\sigma} \exp{\left(\frac{-x-7}{2x\sigma^2}\right)}dx = 0.9
\end{equation}
But the method used in the example seems a lot simpler than solving the equation ($\sigma = 1.21951 \approx \frac{2}{1.64}$) above.
Answer: This is simply the formula for the z-score:
$z=\frac{x-\mu}{\sigma}$
90% of the area under the curve lies between z=-1.64 and z=+1.64. So on your diagram, that corresponds to 5 and 9.


Usar nome da planilha extraído de uma célula

Question: Estou criando uma pasta de trabalho no excel que servirá de modelo para muitas outras que serão geradas através dela.
Esta pasta de trabalho modelo possui 5 planilhas, e uma dela poderá ser replicada diversas vezes com vários nomes diferentes como: Financeiro, Faturamento, Fiscal, etc, dependendo da necessidade de cada projeto.
Uma das minhas planilhas contém uma referência a dados que aparecem nestas planilhas novas através de uma fórmula. Abaixo vou dar o exemplo de como está a minha planilha:
<code>Títulos:
Nome 001
Nome 002
Nome 003

Tabela:
Financeiro
Faturamento
Tecnologia

Pontos:
115
168
985
</code>
A coluna de pontos hoje possui uma fórmula onde eu insiro, manualmente, o nome da planilha que ele precisa buscar, por exemplo: Financeiro!A1:C50. O que eu gostaria é poder buscar na planilha que leva o mesmo nome da coluna, assim ficaria dinâmico.
OBS: O número de linhas para cada projeto nesta planilha de resumo também é variável, por isso preciso deixar a fórmula pegando na coluna de Tabela para poder calcular.
Abaixo o código da coluna pontos seguindo:
<code>=SE(ÉERROS(ÍNDICE(Modelo!$D$3:$BA$3;1;CORRESP($C5;Modelo!$D$3:$BA$3;0) + 2));"";ÍNDICE(Modelo!$D$3:$BA$3;1;CORRESP($C5;Modelo!$D$3:$BA$3;0) + 2))
</code>
Comment: `[sobre a suspensão da pergunta]` Fórmulas de Excel está com pontuação de +8/-3 em [Quais assuntos devem fazer parte do nosso foco (on-topic)?](http://meta.pt.stackoverflow.com/a/1436/201)
Comment: Afinal [o Excel pode ser considerado uma linguagem de programação](http://pt.stackoverflow.com/questions/35547/html-%c3%a9-uma-linguagem-de-programa%c3%a7%c3%a3o#comment71719_35548) :)
Answer: Finalmente achei a solução graças a um amigo que me apontou um link que o ajudou a solucionar o mesmo problema dele. Vou colar o texto da referência aqui apenas adaptando a minha pergunta para contextualizar:

Use a seguinte função:
1) INDIRETO(texto_ref; [a1]) - A função indireto, pega textos que
  representam um endereço de célula, retornando o valor desta célula.
[a1]: não se preocupe com esse parâmetro, não é necessário.
Então se você escrever em uma célula qualquer:
=INDIRETO(B1)
Supondo que em B1 estivesse escrito Financeiro!A2, na verdade
  retornaria o valor da célula A2 da planilha 'Financeiro'. Já, se você
  escrever:
=INDIRETO("B1")
A função reconhece B1 como um texto que retorna uma célula, retornando
  o valor de célula B1. Isso é ótimo para o que você quer, em vez de por
  B1 a gente vai escrever algo que soluciona o seu problema.
Sabendo que escrever o símbolo & junta dois textos a gente pode agora
  juntar B1, onde está escrito Financeiro, com um texto escrito !A2,
  dessa forma escrevendo em uma célula qualquer:
  =B1&"!A2". Isso vai retornar o texto Financeiro!A2. Escrevendo dentro da função INDIRETO() vai retornar o que você quer, basta escrever:
  =INDIRETO(B1&"!A2").

No meu caso a minha fórmula fica:
<code>=SE(ÉERROS(ÍNDICE(INDIRETO(D5&"!$D$3:$BA$3");1;CORRESP($C5;INDIRETO(D5&"!$D$3:$BA$3");0) + 2));"";ÍNDICE(INDIRETO(D5&"!$D$3:$BA$3");1;CORRESP($C5;INDIRETO(D5&"!$D$3:$BA$3");0) + 2))
</code>


Gregorian modes in Renaissance music (with Cabezón's 'Tiento del Cuarto Tono' as an example)

Question: I'd like to ask a question on how Gregorian modes were transformed during Renaissance using a piece of Antonio de Cabezón as an example. His 'Tiento del Cuarto Tono' is written in mode 4, which is, as far as I can tell, the "Hypophrygian" one (https://en.wikipedia.org/wiki/Gregorian_mode). It does not seem that this mode assumed the use of any accidentals. However, Cabezón used a lot of them:

In this fragment one could even use a 'key signature' of C# and G#. Why is this so? Is it really a piece in the Hypophrygian mode?
My guess is that in Renaissance music there was already a tendency to consider major chords as 'stable points' in music flow. For the Hypophrygian mode, the 'main' notes are E (final) and A (tenor), thus the 'main chords' are E major and A major (which implies sharpening of G and C). In this tiento, the fragments where this 'key signature' can be applied sound close to modern A harmonic minor or major. My understanding that this is an example of how 'old' Gregorian modes were gradually transformed to major/minor keys familiar to us.
I would appreciate your feedback as to what extent my guesses are right.
Thank you so much!
PS. Full score of the tiento can be found in IMSLP: Keyboard Music (Cabezón, Antonio de), Intermedios and Tientos, p. 72 (63).
Comment: There is an f# in the second line, 4th bar, final note of the alto part. But saying that this piece is modulating between D minor and A minor is a tonal perspective that would probably not have been shared by the composer.
Comment: That's my understanding based what is said in https://en.wikipedia.org/wiki/Gregorian_mode: mode 4 ('cuatro tono') is Hypophrygian. Naturally, I may be mistaken. However, this piece indeed makes an emphasis on A and E, and ends on an E major chord. (To clarify, the example in my question is just the beginning of the piece.)
Comment: It's starting in A minor, and the first C# is to take it to D minor. The G# is then to get back to A minor. While the G# is common in A minor pieces, the C# isn't. Unless it's modulated to D minor... No F# in sight, so 'having a key sig. of 3#' doesn't seem a possibility. Did I just spot one in the 2nd line? More like A melodic minor, then.
Comment: Yes the way in which the c#resolves to the d definitely gives the impression of d minor
Comment: I am curious, though, on what basis the OP thinks this is Hypophrygian.
Comment: Ah, sorry... I missed the whole "Cuarto Tono" = "Fourth Mode" in the title.
Answer: Pedrell's edition is here.
Yes, you can call this the 4th tone. Note the points of imitation on B and E; notice that the dux and comes of the opening point emphasise C & F respectively before falling back to the final. Subsequent points (such as at the start of page 2) have similar incipits.
Note also that IV (A major) does not appear in cadences, only in the middle of phrases, and it normally leads to ♭vii. (That's to say that, in the context of this piece, A major is not stable.) Cadences using A tend to take the form of I-iv (occasionally iii°-iv, as in ms 13-14) and iv-I (notably the final cadence, but also at the start of the third system on the first page of Pedrell's edition, for instance). Cadential A is always minor.
The third system, immediately after your example, is where the sense of A as tonic starts to be seriously undercut. In addition to the plagal cadence at the start of the system, notice that the middle of the system prolongs A minor in a purely diatonic setting, and notice the cadential approach to iv is via a 6-5 appoggiatura (i.e., ♭iii6-♭II6-iv). This is a bit of an exceptional situation, but it does not make for a stable landing at all.
The third and fourth bars of the fourth system introduce a cadence that is going to show up at critical points during the piece: ♭vii6-I. iv follows I at the start of the subject entry, but in 2nd inversion, i.e., not at all stable and leading back to I. You can see here the shape of the Phrygian cadence as it came to be used in functional harmony, that is, as iv6-V-i, but the placement of the cadence relative to the phrasing and the undercutting of the mode's iv (A minor) by inversion leave the Phrygian cadence in its modal form here.
The Phrygian cadence shows up again, for example, in the middle of the third and fourth systems and the start of the fifth system on the second page of Pedrell's edition, and it doesn't always move to A (the instance in the fourth system moves to an augmented chord on F, for example).
So to summarise:

Points of imitation start on B and E, and tend to emphasise C and F as descending leading tones.
Important cadences take the form of I-iv, iv-I and ♭vii6-I.
IV is used only in passing, generally en route to ♭vii.
5 as a root is unstable and generally avoided, hence 4 as the tenor, but, as important as 4 is, it is usually undercut by not being given a tierce de Picardie in cadential contexts.
1, when used as a root, is generally given a tierce de Picardie, and generally functions either as V/iv or I. It is further reinforced as a final by having two types of cadence: a mode-specific "perfect" cadence (♭vii6-I) and a plagal cadence (iv-I).

Cabezón's career overlapped the careers of the Elizabethan composers, and he died during Monteverdi's childhood, so his work is right on the cusp of the Baroque, and some of the strains that led to the Church tones being relegated to the periphery are starting to show: the sense of modal polyphony that saw octave-and-fifth chords as perfect and used them to define cadences was already in the past; the use of functional relations in a triad-based vocabulary was starting to peek through. Cabezón establishes his mode by reliance on constraints and formulae, both cadential and melodic (including how musica ficta is used, hence the avoidance of C♯ at cadences).
Modal music never entirely went away. You can see Hypophrygian mode incorporating a wider tonal range, but using very similar conventions and constraints to establish the mode, in Bach's 6-voice prelude on Aus tiefer Not schrei' ich zu dir from the Clavier-Übung.
Answer: This is a typical example of a modal keyboard piece from the late 16th or early 17th century. Mode in polyphonic music (as distinguished from mode in plainchant) is a complicated topic that is being actively researched by musicologists and is still the subject of scholarly debate.
It is a different way of thinking about music that just can't be compared with functional tonality. I won't go into all the complexities, but there is a difference between mode, (psalm) tone, and what were known as church keys, none of which were equivalent to tonality. (See Gregory Barnett's article in the Cambridge History of Western Music Theory.)
In general, according to Zarlino, Cerone, and other contemporary theorists, the mode of a polyphonic piece was determined by the ambitus or range of the Tenor voice and the final note in the lowest voice. If the piece ends with E in the bass (regardless of whether the final chord has a G or G# in it), and if the range of the tenor goes from B3 to B4 (or down an octave), then the piece is in mode IV, the plagal of the "phrygian" mode. ("hypophrygian"). If the tenor's range was from E3 to E4, the piece would be authentic plagal, mode III.
Some theorists also specified that the mode indicated a pattern of cadential points in the middle of the piece (IIRC, mode I/Dorian had internal cadences on F and A).
About accidentals, contrary to some popular belief, it was common to use accidentals in modal music, particularly at cadences or cadence-like passages. This is connected to practices of musica ficta in which singers improvised unnotated accidentals  according to certain patterns, such as leading tones at cadences. In this period, some of these accidentals are written out, and some were added by the singers. This is why you often see what appear to be "dominant" chords with raised "leading tones", or "tonic" chords at cadences with raised major thirds. These chromatic alterations were not understood to alter the mode, in fact, they were an expected part of the composition.
In this specific case, this is a genre of keyboard piece that was most commonly performed as a verset, in between verses of choral psalms, sung either in Gregorian chant with the traditional psalm tones, or in polyphonic settings based on the same psalm tones. In this practice, called alternatim, the choir would sing verse 1, the organ would "sing" verse 2, then the choir would singe verse 3, ec. Part of the organ's function was to cue the choir for the correct psalm tone, partly by the pattern of cadences and especially by the final cadence. The psalm tones (explained in Willi Apel's Gregorian Chant and at the beginning of the Liber Usualis) were paired with the modes, but were not the same thing.
Tientos were also played during the Elevation of the Eucharistic host, and like Italian elevation toccatas (e.g., Frescobaldi) these pieces are often highly chromatic (tientos de falsas).
Answer: These all just look like a minor which modulates to the sub dominant key (d minor ). This is further emphasised in the manner in which the c# and g# resolve to the d and a respectively. Also this seems to me to be a baroque transcription of a piece that very well may have had its existence rooted in the renaissance.
There seems to be a distinct minor tonality to this piece that would not have been possible in the pre baroque era.
Comment: This is incorrect. The piece really is in the fourth "tono" and not in any major or minor key. The original piece does have these accidentals, as do most modal polyphonic pieces from the period.
Comment: Thank you! It is indeed possible that the transcription that I have differs from what Cabezón conceived. However, I found the original 16th century score for this piece (also in IMSLP) in a kind-of SATB notation with notes numbered from 1 for F to 7 for E. In that score, sharps appear to be in the same places as they are in the more modern rendition.


Equality in Minkowski's inequality proof(no integrals)

Question: So what I'm looking for is a proof for when does the equality hold in Minkowski's inequality?
I'm talking about this form of inequality:
$$\left( \sum_{K=1}^n |x_k + y_k|^p \right)^{\frac{1}{p}} \leq \left( \sum_{k=1}^n |x_k|^p\right)^{\frac{1}{p}} + \left( \sum_{k=1}^n |y_k|^p\right)^{\frac{1}{p}}$$
Not the one using integrals.
I know when does the equality hold, I just can't figure out how to prove it. It holds when (X1, ..., Xn) = c*(Y1, ..., Yn), where c is a real constant (this is similar to Holder's inequality which I used to prove Minkowski's inequality). So can I just point out that it similarly holds in Minkowski's case, as I suppose it does? Thanks.
EDIT:
I proved that if (X1, ..., Xn) = c*(Y1, ..., Yn) , then the equality holds. Now, how to do in reverse - if equality holds, then (X1, ..., Xn) = c*(Y1, ..., Yn) ? Because these are equivalent.
Comment: Hi. You will probably get a much better response if you give some idea of what you have already tried - people will be happy to help you understand, but not to just do your homework for you. Also, do you just want to know when there is an equality, or a proof of this. Do you have any idea at to when it might hold?
Comment: I don't think I will be able to solve this in general quickly, but some brief points: Firstly, if $p=1$ then the equality holds if and only if $x_i$ and $y_i$ are positive for all $i$. Secondly, I don't see what the equality necessarily holds if $(x_1, \ldots, x_n) = c(y_1, \ldots, y_n)$. For example, what if $c=-1$. Then the left hand side is zero, but the right hand side is not...
Answer: The case where $p=1$, the Minkowski's Inequality is nothing but a bunch of triangle inequalities of real numbers,
that is
$$\left( \sum_{K=1}^n |x_k + y_k|^p \right)^{\frac{1}{p}}
\le \left( \sum_{k=1}^n |x_k|^p\right)^{\frac{1}{p}} + \left( \sum_{k=1}^n |y_k|^p\right)^{\frac{1}{p}},
$$
when $p=1$, is
$$
 \sum_{K=1}^n |x_k + y_k|
\le  \sum_{k=1}^n |x_k| + \sum_{k=1}^n |y_k|.
$$
Equality holds when $x_ky_k\ge0$, for each k, that is $x_k$ and $y_k$ are either both non-negative or non-positive. So, that gives $x_k=c_ky_k$, for some positive $c_k$, for eack $k$.
For the case $p>1$ I assume you used
\begin{align*}
\left( \sum_{k=1}^n |x_k + y_k|^p \right)
& =\left( \sum_{k=1}^n |x_k + y_k|^{p-1}|x_k + y_k| \right) \\
& \le \sum_{k=1}^n |x_k + y_k|^{p-1}|x_k|+\sum_{k=1}^n |x_k + y_k|^{p-1}|y_k|,
\end{align*}
that is a triangle inequality, followed by Hölder's inequality:
$$
\sum_{k=1}^n |x_k + y_k|^{p-1}|x_k|
\le \left(\sum_{k=1}^n|x_k|^{p}\right)^{\frac{1}{p}}\left(\sum_{k=1}^n|x_k+y_k|^{(p-1)q}\right)^{\frac{1}{q}},
\quad \text{where } \frac{1}{p}+\frac{1}{q}=1.
$$
and similarly,
$$
\sum_{K=1}^n |x_k + y_k|^{p-1}|y_k|
\le \left(\sum_{k=1}^n|y_k|^{p}\right)^{\frac{1}{p}}\left(\sum_{k=1}^n|x_k+y_k|^{(p-1)q}\right)^{\frac{1}{q}}.
$$
and added the expressions to get the desired result.
So, to have equality in Minkowski's inequality we must have equality in both applications of Hölder's inequality and the triangle inequality, i.e., $\, \exists \, \lambda_1, \lambda_2 \ge 0$ s.t.,
\begin{align*}
|x_k|^p
=\lambda_1|x_k+y_k|^{(p-1)q}, \qquad
|y_k|^p
=\lambda_2|x_k+y_k|^{(p-1)q} \tag{1}
\end{align*}
and
\begin{align*}
|x_k+y_k|
=|x_k|+|y_k|, \tag{2}
\end{align*}
for $k = 1,2, \cdots, n$.
WLOG we may assume $\lambda_1,\lambda_2 > 0$. Therefore, from $(1)$ we have $|x_k|^p = \left(\frac{\lambda_1}{\lambda_2}\right)|y_k|^p$. Again for equality to hold in $(2)$ $x_k$ and $y_k$ must have same sign. So, that gives us the equality condition to be $x_k = cy_k$, for $k = 1,2, \cdots, n$ with $c = \left(\frac{\lambda_1}{\lambda_2}\right)^{1/p}$.
Comment: Thanks for the clarification. Here's one thing I still don't understand: Why can we conclude that if the sums in the Hölder inequality must be equal, all summands must be equal? I.e. we could have $1 + 4 = 2 + 3$ but obviously $1 \neq 2$ und $4 \neq 3$. Surely, one direction is true $x_k = y_k$ for all $k$ $\implies \sum_{k } x_k = \sum_{k} y_k$ but I'm not sure about the "only if" part.
Comment: Also pertaining the paragraph mentioned in the comment above: why do you need the triangle inequality to be an equality, too? $|x_k|^p = \frac{\lambda_1}{\lambda_2} | y_k|^p$ follows from the two "Hölder equalities", right?
Comment: @ViktorGlombik You are right. I didn't use the equality of triangle inequality $(2)$ the first time.
Comment: +1 for explaining why $x_k$ and $y_k$ must have same signs!
Comment: @Ramanujan  I think it goes as follows : You know $a\leq a'$ and $b\leq b'$. Then the equality $a+b=a'+b'$ implies the separate equalities $a=a'$ and $b=b'$.


O Angular 2 substitui jQuery e AJAX?

Question: Com a utilização do Angular 2, ainda é necessário ainda a utilização do jQuery e AJAX ou o Angular faz a substituição 100% dessas 2 tecnologias?
Answer: O Angular faz substituição a 100%. É possível misturar se estiveres dependente de código antigo. Mas a ideia é deixar o jQuery para trás...
Se nunca soubesses que jQuery existia era quase melhor para começar uma app em Angular, Vue ou React :)
O conceito desta nova geração de aplicações reactivas é não mexer no DOM como antigamente. A aplicação toma conta do DOM e o paradigma de programação deve ser mais funcional/reactivo. Quando algo no estado (state) da aplicação mudar isso deve refletir-se no DOM. E não como antigamente: usar jQuery para implementar no DOM o que está no state. Ou ainda pior, ir ler no DOM dados para processamento da aplicação.
Há obviamente coisas em que o jQuery ainda pode ser útil. Ajax é uma delas. Mas é preferível nesse caso usar bibliotecas mais especializadas para funcionalidades que são necessárias. O Angular tem o <code>$http</code>, o React e o Vue.js são agnósticos, ou seja podes usar o que quiseres. Caso necessário, o Axios é uma boa alternativa.
Comment: Boa resposta, só acho que deveria citar o "Ajax" que o AP fala.
Comment: @Sergio, muito obrigado pelos esclarecimentos amigo..
Comment: @Maniero o MooTools é bem mais poderoso que jQuery, por isso consegue fazer o que o Angular faz ou o Vue com mais qualidade. Mas é de outra geração e na prática abandonado, infelizmente.
Comment: @LINQ bem visto, juntei. Obrigado.
Comment: No caso esse React substitui o Angular? ou eles andam em conjunto?
Comment: @NicolaBogar React, Vue e Angular são as 3 bibliotecas mais populares nesta nova geração de bibliotecas "reactivas".
Comment: Entendi, então eu deveria apenas me atentar a aprender 1 tecnologia, não teria necessidade de aprender todas, certo ?
Comment: @NicolaBogar exato. Todas são JavaScript, por isso saber JavaScript é o mais importante, e podes fazer isso em paralelo com uma dessas bibliotecas claro.
Comment: Perfeito @Sergio, você sabe onde posso achar alguma documentação do angular com o ASP.NET MVC, procurei pela internet e vi que é bem escasso esse tópico, só consegui achar com ASP.NET CORE
Comment: @NicolaBogar na verdade não. O mundo ASP.NET é-me completamente alheio :) Eu estou mais em casa com Node.js e PHP... Mas se tiveres alguma duvida específica há boa gente aqui que quer ajudar.
Comment: @NicolaBogar de nada!
Comment: E o MooTools? :)

O Angular 2 substitui jQuery e AJAX?


MySQL Schemas not showing on Work Bench

Question: My schemas in the MySQL Workbench is not showing up. I tried with multiple users and granted all privileges to all users, yet nothing shows up.
Answer: I had previously created two connections for two different databases. One was for a university project which I didn't want touched.

The wrong MySQL instance was running, which meant I couldn't see the schemas. So I had to start the correct service from the bottom right icon.

MySQL Schemas not showing on Work Bench


Frescobaldi does not create files

Question: I am using LilyPond with Frescobaldi editor. It sometimes happens that Frescobaldi stops working, that is: If I change something in the .ly file (e.g. some string) and hit the Lilypond button (or press CTRL+M), nothing happens. The preview does not update, and no files are generated/updated.
I use:

Linux Mint 20.2 Cinnamon, Version 5.0.5, Linux Kernel 5.4.0-80-generic.
GNU LilyPond 2.20.0.
Frescobaldi Version 3.0.0.

Until now I managed to get rid of this problem by closing and reopening Frescobaldi, but it does not help any more. I even removed and reinstalled Frescobaldi, restarted my computer, removed the config file... but nothing helps. Frescobaldi just does not work anymore.
Any ideas what I can do to make it work again?
If not, I'd already be happy if someone can give a clue to what is going on here. Currently, this is just (evil) magic to me...

Here is a simple example LilyPond file newFile.ly:
\version "2.20.0"

title = "title"
music = { \relative { c' d e f g } }

\bookpart {
  \header {
    title = \title
  }
  \score {
    \music
    \layout { }
  }
}

If I run lilypond newFile.ly in the console, I get the following output in the console:
GNU LilyPond 2.20.0
Processing `newFile.ly'
Parsing...
Interpreting music...
Preprocessing graphical objects...
Finding the ideal number of pages...
Fitting music on 1 page...
Drawing systems...
Layout output to `/tmp/lilypond-NKnbRf'...
Converting to `newFile.pdf'...
Deleting `/tmp/lilypond-NKnbRf'...
Success: compilation successfully completed

A pdf is generated (or overwritten if already present).
If I open newFile.ly in Frescobaldi, change the string value of title to "title2", save and then press  CTRL+M, I get this:

No preview window is opened, no pdf is generated, and the Lilypond log inside Frescobaldi is suspiciously short: it contains only three entries (Processing, Parsing, Success), unlike the Lilypond log in the console after a direct lilypond call.
Before Frescobaldi stopped working, I always got a long log just like when using lilypond in the console.
I wonder: If Frescobaldi merely calls lilypond under the hood, why are all the other steps (Interpreting, Preprocessing, ...) omitted? And why were they not omitted before (when Frescobaldi still worked)?
Answer: I found the answer for the current "broken-ness":
If there is a file init.ly inside the folder of the main file (main file = the one to be compiled), console lilypond doesn't mind but Frescobaldi can't cope with it and will behave as described in the question. Even if that init.ly file isn't even \included anywhere!
I guess this is worth a Frescobaldi bug report. Anyone who wants to do that - go ahead!

How did that happen?
I use \include, and I named one of the included files (which consists solely of variable assignments) init.ly. Didn't know that was a bad name choice. I went on working on my main file, and after I added the \include "init.ly" statement and compiled with console lilypond, the error message there

/usr/share/lilypond/2.20.0/ly/init.ly:43:1: error: \maininput not
allowed outside init files

made me suspicious, so I renamed my init.ly file and voila, Frescobaldi was back to normal.
Answer: I don't think this is a Frescobaldi problem but a misunderstanding about LilyPond include files and Frescobaldi's include paths (Edit -> Preferences -> LilyPond Preferences tab at the bottom).
There already is a file called init.ly in LilyPond.  Depending on how your include paths are setup, you may get this file or the file you created.  If you get LilyPond's init.ly file, then things go haywire.
Notice your error message:

/usr/share/lilypond/2.20.0/ly/init.ly:43:1: error: \maininput not allowed outside init files

See that you are including LilyPond's init.ly file, not yours.  If you include the full path of the file, the problem goes away:
include "/full/path/to/your/init.ly"

Comment: If I have a file of a certain name `X` in the same folder as the file that I'm compiling (and I'm NOT including `X` in the main file!), and I use `lilypond` compiler, there is no problem at all. It just does not matter that `X` is there. That is, in my opinion, the correct behaviour. Frescobaldi on the other hand DOES care about the presence of `X`: It simply does not compile. How can this not be a Frescobaldi issue?
Comment: Well, the comments of StackExchange are too small for me you post examples.  The long and the short of it is, I don't get the behavior you're seeing with my test files.  Why don't we pickup the conversation on the [Frescobaldi discussion group](http://groups.google.com/group/frescobaldi)?
Comment: I created a post in the Frescobaldi discussion group [here](https://groups.google.com/g/frescobaldi/c/UrCZZEGR0Yk) that explains what I did.  You may be asked to formal join the group -- it's been so long since I first posted there I forget.
Comment: Don't want to join google groups, sorry. But you didn't do what I did. Here's what you should check: Create `foo.ly` file without any includes. It should be compilable (i.e. have no errors). Create `init.ly` file in the same folder. It can contain anything you want, or stay empty. Then compile `foo.ly` with command line `lilypond`. There shouldn't be any issues. Now open `foo.ly` in Frescobaldi and compile from there. Does it compile and generate pdf? Or do you only get the short log of just three entries (`Processing`, `Parsing`, `Success`)? If the latter, then you have reproduced my issue.
Comment: Following your instructions, I get no errors with LilyPond at the command line nor with Frescobaldi.

Frescobaldi does not create files


Unable to get Goatcounter to work on Github pages website

Question: I deployed my personal website (React Typescript) through Github pages here and I wanted to add Goatcounter to me website.
I added this line of code to my index.html to enable Goatcounter.

But I'm unable to access the Goatcounter domain, the Goatcounter site does not exist.

Am I missing something? Would appreciate the help. Thanks!
Comment: [You **absolutely** need to specify a `integrity=""` attribute](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity) on all externally-loaded `
Comment: _"I'm unable to access the Goatcounter domain."_ - what do you mean by that?
Comment: Edited with more details. Thank you.
Comment: [The documentation says](https://www.goatcounter.com/help/start) you should have `<script data-goatcounter="https://MYCODE.goatcounter.com/count"` - is `astronights` your actual value for `MYCODE`? If so, then [you should contact them and file a bug](https://www.goatcounter.com/contact).
Answer: I see that astronights.goatcounter.com is a sub domain specific to your site astronights.com, Although attached error SS points out that goatcounter.com doesn't exposes this sub domain yet.
As per first paragraph of goatcounter Readme, you need to either host the app your self OR you need to sign up and register your Code (astronights) like shown in attached SS, If not done already. Make sure https://astronights.goatcounter.com is accessible before loading it in your index.html
Comment: Thank you, that worked. Once I signed up on goatcounter.