Where is the error? Application of FTC

Question: Please, I need a help to see the error on this argument:$$\int_0^tf(a)g(t-a)da=\int_0^tf(t-a)g(a)da\implies$$
$$\dfrac{d}{dt}\int_0^tf(a)g(t-a)da=\dfrac{d}{dt}\int_0^tf(t-a)g(a)da\implies$$
$$f(t)g(0)=f(0)g(t)$$
If $f(0)=g(0)=k\neq 0$, então
$$f(t)=g(t)\forall t\in\Bbb R.$$
It is obviously incorrect, but I could not find the error.
Many thanks!
Answer: You can't apply FTC here -- you have to use the Leibniz integral rule. This is because not only are the bounds changing, but the inside of the integral itself is changing as well. Contrast this with $$\frac{d}{dx}\int_0^xxt\;dt=\frac{t^2}2,$$ not $xt$ as a naive application of FTC would entail.
Comment: Actually $\frac{d}{dx}\int_0^xtdt=\frac{d}{dx}\frac{x^3}{2}=\frac{3x^2}{2}$, while any naïve FTC use would still try to claim the result is a function of $x$ alone.
Comment: Thank you so much!
Comment: 23 answers in 2 hours. This is impressive.

Where is the error? Application of FTC


Determine a positive integer $e$ that satisfies $M^{17e}\equiv_{77}M$, when $(M,77)=1$.

Question: We're doing public key cryptography this week and I just can't seem to get a grasp on it.
I really don't know how to solve this problem. Can anyone point me in the right direction? I'd really appreciate it.
Answer: $\renewcommand{\phi}{\varphi}$You are done if you find $e$ such that $17 e \equiv 1 \pmod{\phi(77)}$. Here $\phi(77) = \phi(7) \phi(11) = 6 \cdot 10 = 60$ is Euler's $\phi$ function.
So run Euclid's algorithm to find
$$
17 \cdot (-7) + 60 \cdot 2 = 1,
$$
so you can take $e = -7$, or if you prefer $e = -7 + \phi(77) = 53$.
Comment: Ah! This makes sense! Actually I read up to the 77 = 7*11 part and it immediately made sense. Thank you!


How to prove that eigenvalues of a symmetric matrix with respect to a metric are real, and that there always exists an eigenbasis?

Question: $$\lambda_i M\mathbf{v}_i=K\mathbf{v}_i$$
$K$ is a real symmetric matrix and $M$ is real and diagonal.
I need to prove that the eigenvalues of $K$ with respect to the metric $M$ are real, that eigenvectors for different eigenvalues are orthogonal with respect to the metric (i.e $\mathbf{v}^T_iM\mathbf{v}_j=0$ if $i\ne j$) and that there exists an orthonormal eigenbasis.
I've managed to prove the orthogonality of eigenvectors with different eigenvalues, but am struggling with the other two proofs.
Hints would be appreciated.
EDIT: Metric is the termonology used in the text I'm reading. To clear up any confusion, let me make it clear that $M$ is a diagonal, real matrix.
Comment: I'm not sure what you mean when you say $M$ is a metric.  Do you mean $M$ is a *matrix*?
Comment: $M^{-1}K$ might not be symmetric, but $M^{-1/2} K M^{-1/2}$ should be.
Comment: $M^{-1}K$ is real symmetric and therefore diagonalizable as required, isn't it?
Answer: Let $C=M^{-1/2}$ (the diagonal matrix whose diagonal entries are the reciprocals of the square roots of the diagonal entries of $M$). Then $C=C^*$ and $C^*MC=E$ (the identity matrix), and if we seek the eigenvectors in the form $v_i=Cu_i$, then the problem for the $u_i$ becomes $C^*KCu_i=\lambda_i u_i$. The matrix $C^*KC$ is real and symmetric, and so its eigenvalues are real and there exists an orthonormal eigenbasis $\{u_i\}$ (with respect to the standard inner product on $R^n$). The vectors $v_i=Cu_i$ are then orthogonal in the metric defined by $M$.


How can I create a "clear queue" command in discord py

Question: I've been programming a discord bot using DiscordUtils and discord.py for a time now, and I want to create a command to wipe the current queue. I can't seem to figure out how to do this, so any help would be appreciated.
@commands.command(help="Shows all the songs in the current queue")
async def queue(ctx, arg=None):
myconnectedtrue = ctx.guild.me.voice
player = music.get_player(guild_id=ctx.guild.id)
if arg == "clear":
    songs = f"{f', '.join([song.name for song in player.current_queue()])}"
    list_of_songs = songs.split(",")
    no_o_songs = len(list_of_songs)
    for i in list_of_songs:
        await player.remove_from_queue(i)
    return

This is an extremely crude attempt of trying to do this, it doesn't work for probably obvious reasons. This was the best I could do though. What I am wondering is if there is a better way to do this that I'm missing out on. Thanks for the help!
Answer: There is a Python method called .clear(). I'm assuming you're using a list to store the queue data (I would recommend learning some JSON or SQLite due to them being more reliable). Instead of seeing how long the list is and running a for loop, you can do list_of_songs.clear().


Observe only one WorkRequest in a chained Work Continuation

Question: I have a set of chained work requests, and I want to observe only the first one of them.
I get the LiveData using a unique tag assigned to only the first request. Inside the filter, I again filter the List<WorkInfo> for the worker tag.
Despite all the filtering, I get three success notifications, one for each successful work request in the chain, even though the tag was added only to the first request.
I'm not sure if this is a bug or is it the expected behaviour (tag is assigned to all work requests in a chain).
Is there a way to observe only one of the work requests in a chain?
My code so far:

val workerTag = "a randomly generated long string"

val syncRequest = OneTimeWorkRequestBuilder<SyncWorker>()
    .setConstraints(syncConstraints)
    .addTag(workerTag)
    .build()

val followOnRequest = OneTimeWorkRequestBuilder<FollowOnWorker>()
    .build()

val finalRequest = OneTimeWorkRequestBuilder<FinalWorker>()
    .build()

WorkManager.getInstance(applicationContext)
    .beginUniqueWork(WORK_ONE_TIME_SYNC, ExistingWorkPolicy.REPLACE, syncRequest)
    .then(followOnRequest)
    .then(finalRequest)
    .enqueue()

WorkManager.getInstance(applicationContext)
    .getWorkInfosByTagLiveData(workerTag)
    .observe(this, Observer { workInfoList ->

        val workInfo = workInfoList.find { it.tags.contains(workerTag) }
            ?: return@Observer

        // THIS OBSERVER IS CALLED FOR ALL THE REQUESTS IN THE CHAIN ABOVE WITH ALL THE TAGS
        if (workInfo.state.isFinished) {
            Timber.i(workInfo.tags.joinToString(", "))
        }
    })

Answer: This is working as intended.  If you need to get the WorkInfo for only one WorkRequest, you can do so by its id or this way:
val continuation = WorkManager.getInstance(applicationContext)
    .beginUniqueWork(WORK_ONE_TIME_SYNC, ExistingWorkPolicy.REPLACE, syncRequest)
continuation.then(followOnRequest)
    .then(finalRequest)
    .enqueue()

continuation.getWorkInfosLiveData()
    .observe(this, Observer { ... })

Comment: Thanks for the idea. I'll test it out.
Comment: Nope. Still the same. The observer is still triggered multiple times—once for each workRequest in the chain.
Answer: If you only want to observe the first request, rather then use continuation.getWorkInfosLiveData() you can just use https://developer.android.com/reference/androidx/work/WorkManager.html#getWorkInfoByIdLiveData(java.util.UUID) and thus your code changes to:
WorkManager.getInstance(context)
    .getWorkInfosByIdLiveData(syncRequest.id)
    .observe(...)

Comment: Thanks Rahul. I'll give it a try. Cheers!
Comment: Thanks for the suggestion, Rahul. Sadly, this doesn't work either. The observer is still called for all the following requests in the chain.


How obtain a (accurate) function from this graph with these points?

Question: I need obtain the function from 0 to 20 from this graph:

I have the even numbers in the {x, f(x)} format:
{0, 0}, {2, 1.8}, {4, 2}, {6, 4}, {8,4}, {10,6}, {12,4}, {14,3.6},{16,3.4}, {18,2.8}, {20,0}
I tried using interpolation from Wolfram Alpha but It got the Runge's phenomenon as you can see in this link http://www.wolframalpha.com/input/?i=interpolating+polynomial+{0%2C+0}%2C+{2%2C+1.8}%2C+{4%2C+2}%2C+{6%2C+4}%2C+{8%2C4}%2C+{10%2C6}%2C+{12%2C4}%2C+{14%2C3.6}%2C{16%2C3.4}%2C+{18%2C2.8}%2C+{20%2C0}
So, if anyone could give me a relatively accurate approximation I would be very grateful.
Thank you for reading this!
Comment: Can you give more information? What is this supposed to model? There must be additional requirements if you are sure the exact polynomial fit is no good...
Answer: A cubic spline does the job:

There are infinitely many programs for spline interpolation. I rolled my own, however (in Scilab). It computes cubic spline by considering it as a "correction" to piecewise linear interpolation.
a = 0
b = 20
y = [0 1.8 2 4 4 6 4 3.6 3.4 2.8 0]
n = length(y)-1
h = (b-a)/n
jumps = diff(y,2)/h
A = (h/6)*(diag(4*ones(1,n-1))+diag(ones(1,n-2),1)+diag(ones(1,n-2),-1))
z = [0,-jumps/A,0]
allx = []
spl = []
for i=1:n
   xL = a+h*(i-1)
   xR = a+h*i
   x = linspace(xL,xR,100)
   linear = y(i)*(xR-x)/h + y(i+1)*(x-xL)/h
   correction = ((z(i+1)+2*z(i))*(xR-x)+(2*z(i+1)+z(i))*(x-xL)).*(xR-x).*(x-xL)/(6*h)
   allx = [allx, x]
   spl = [spl, linear+correction]
end
plot(allx, spl)
plot(a:h:b, y, 'r*')

A spline is a piecewise defined function; instead of a single complicated formula you have a bunch of simple formulas. Let $(x_1,y_1),\dots, (x_{11},y_{11})$ be the  points in your post. The code calculates numbers $z_1,\dots,z_{11}$ which you can get by simply typing z after running the program. The formula for the spline is as follows:
when $x_i\le x\le x_{i+1}$, $$\begin{split}
y &= y_i\frac{x_{i+1} -x}{h}  + y_{i+1}\frac{x-x_i}{h} \\
&+ \frac{(x-x_i)(x_{i+1}-x)}{6h}((z_{i+1}+2 z_i) (x_{i+1} -x)+ (2 z_{i+1}+z_i) (x-x_i))
\end{split}$$
where $h=2$ (space between $x$-coordinates of the points). The first line is   the piecewise linear interpolant. The second line is the cubic correction term. It must vanish  at the nodes of interpolation, hence the factor $(x-x_i)(x_{i+1}-x)$. This leaves only a linear factor of correction term to figure out,  which is done by using the condition that the first derivative of the correction term must jump at the interpolation node to negate the jump of the slope of the piecewise linear interpolant.
The numbers $z_i$ are actually $y''(x_i)$, as you can check by taking the derivative of $y$ above. This is a natural cubic spline, for which $y''$ vanishes at the endpoints.
Comment: Thank you, it is very accurate! But, how can I make Scilab give me the resulted function? I understand your code uses vectors and variables to make the curves and the "spl" from the line "plot(allx, spl) " should be the function in form of various points (or at least was what I think). So, how can I see the points in the form of a function? Ex: 23x²-3x-43.453; cos²x+23x; Sorry if it is a stupid question, I never used an math software before.
Comment: @user3676848 This is the sort of task that calls for math software. Scilab is a free download. See the explanation I added to   the answer.
Comment: @user3676848 A more detailed explanation of the above code [is here](http://calculus7.org/2014/02/14/connecting-dots-naturally/).


Prove that permutation group is automorphism group of some structure

Question: Let $G$ be a permutation group on $X= \{ x_1,x_2,...,x_n\}$
Prove that  $Aut(X,G)=G$

I have no ideas how to prove it.
Besides, there is a question that the problem asks to prove $Aut(X,G) = G $ , i.e. prove automorphism group with the structure (permutation group G) is the permutation group.
But, in context the textbook says that we indeed prove every permutation group  is the automorphism group of some object .
What's the connected?

Here are some definitions from textbook
Answer: By definition $\operatorname{Aut}(X,G)$ is a subset of $S(X)$, the group of all permutations of $X$. By definition a permutation $\sigma\in S(X)$ is an automorphism of $(X,G)$ if and only if $G\sigma=G$. In particular this implies that $e\sigma=\sigma\in G$, which shows that $\operatorname{Aut}(X,G)\subset G$. On the other hand, for all $g\in G$ you have $Gg=G$ and hence $g\in\operatorname{Aut}(X,G)$, which shows that $G\subset\operatorname{Aut}(X,G)$. Hence $\operatorname{Aut}(X,G)=G$.
This shows that $G$ is the automorphism group of $(X,G)$. As $G$ was an arbitrary permutation group to begin with, this proves that every permutation group is an automorphism group.
Comment: Thanks! I have realized almost things but the $e\sigma=\sigma\in G$. The $\sigma$ is permutation like $(g_1) \sigma = g_2$. How can I derive it?
Comment: Well $g_1,g_2\in G$ and $G$ is a group, so $g_1^{-1}g_2\in G$.
Comment: Or $\sigma$ is not a permutation function ($S(X)$)? how to say a function is a element in $G$
Comment: By definition $G$ is a subset of $S(X)$.


Function returning undefined when callback is not used, on using callback, JS says function not defined

Question: Please take into consideration that similar questions have been asked on SO and I went through most of them.
I am making a RESTful service that needs querying the DB to get the data. I wrote the code that queries the database correctly but does returns undefined all the time. The code is here:
function returnAll(){
    ModuleDBService.find({},function(err,data){
        if(err){
            console.log('Error occured while retrieving the documents!');
        }
        return data;
    });
}

I was exporting the module using:
module.exports = {
    getAll:returnAll
};

After digging SO a lot, I discovered that I will need to use callback to get the data. I went through many examples and tried to apply a similar technique to my code, the modified code looked like this:
function getAllFromDatabase(callback){
    ModuleDBService.find({},function(err,data){
        if(err){
            console.log('Error occured while retrieving the documents!');
        }
        callback(returnAll(data));
    });
}

function returnAll(data){ return data;}

and then returning it in the similar fashion as above.
But now I am getting error that ModuleDAO.getAll is not a function (I am using var ModuleDAO = require('path to the database service').
I tried many variations of the code, went through a couple of videos on YouTube, all of them either lead to returning undefined, or return to the above stated error. If anyone could fix the code and throw light on this whole callback thing (Or could provide solid documentation to understand it), it'll be a great help.
Thanks.
EDIT: After all the extremely helpful answers, here is a summary:
Callbacks cannot return data, pass the function (the callback function) that you want your program to call with the data. In my case, it was my router returning the data.
Here is the corrected code:
function returnAll(callback) {
    ModuleDBService.find({}, function (err, data) {
        if (err) {
            console.log("Error while retrieving the document!")
            callback(null);
        }
        callback(data);
    });
}

I used this code in my router as:
mainAPIRouter.post('/api/module', function (req, res) {
    try {
        moduleDAO.getAll(function(data){
            res.status(200);
            res.json(data);
        });
    } catch (error) {
        res.status(500);
        return res.send("Invalid request");
    }
});

Thanks to all those who helped! :)
Comment: To me this seems like an X/Y that's actually just another duplicate of : https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call
Comment: @KevinBHi! I understand that similar questions are around and I went through most of them, it's just I am not able to figure out why similar solutions lead to undefined and errors in my case.
Comment: What is undefined?
Comment: For example, returnAll doesn't return anything, and the reason is covered in the duplicate i linked. If that's what was undefined, then yeah, this is definitely a dupe.
Comment: It is in fact a duplicate of that bug @KevinB.
Answer: You are close. You don't need the returnAll() function, and you need to export getAllFromDatabase and pass a callback to it:
function getAllFromDatabase(callback){
    ModuleDBService.find({},function(err,data){
        if(err) {
            console.log('Error occured while retrieving the documents!');
        }
        callback(data);
    });
}

module.exports = {
    getAllFromDatabase: getAllFromDatabase
};

Then, when you want to use it, you need a callback function:
dataModule.getAllFromDatabase(callbackHandler);

function callbackHandler(dataFromDatabase) {
    // this function will be executed when ModuleDBService executes the callback
    console.log(dataFromDatabase);
}

A small detail: if err is Truthy, you should not execute the callback:
if(err) {
    console.log('Error occured while retrieving the documents!');
} else {
    callback(data);
}

Comment: good answer. one suggestion, it can help make the code more robust if you check to make sure callback is a function before trying to invoke it. `if(typeof callback==='function') callback(data);`
Answer: You want to simply call the callback() with the data you need as an argument. You are  making things much more complicated by passing another function into the callback. Try something like:

function returnAll(callback) {
  ModuleDBService.find({}, function(err, data) {
    if (err) return callback(err)
    callback(null, data);
  });
}

returnAll(function(err, data)) {
// it's customary for callbacks to take an error as their first argument
  if (err) {
    console.log('Error occured while retrieving the documents!');
  } else {
    // use data here!!
  }
}
Comment: @metamemelord You can't really ever *return* data when you're dealing with async functions. Your callback is being called by the `returnAll()` function. If you return from your callback you are returning data to the function that just called it. You need to *use* the data in your callback or pass it to another function.
Comment: Thanks a lot. I will try. It seems to me that I just have to return the data in the else section now and export the module as getAll, is that right?
Comment: Okay. Thanks a lot. I will then call my router and export the data directly into json. All this is happening because of having multiple layers of logic. Thanks a lot for all the help.
Answer: As previous answers mentioned, you can use a callback. You can also use a promise if you prefer:
function returnAll(){
    return new Promise(function(resolve, reject) {
    ModuleDBService.find({},function(err,data){
        if(err){
            console.log('Error occured while retrieving the documents!');
                reject(err);
        }
          resolve(data);
    });
     });
}

You would then use something like this to access it:
returnAll()
  .then(data=> {console.log(data); })
  .catch(err=> { console.log(err); });

*Edit: since you want to use a callback, thought I'd add my $0.02 there as well. The most streamlined approach would be to just use the callback you're passing in with the ModuleDBService.find, without the ad-hoc function. But it's good to verify that callback actually is a function, and if not to make it one...makes your code more fault-tolerant.
function returnAll(cb){
    if(typeof cb!=='function') cb = function() {};
    ModuleDBService.find({},cb);
}

Comment: @metamemelord you're welcome, happy coding! Also just a suggestion, but you might think about upvoting raul.vila's answer in addition to marking it as the solution. Upvote gives him an additional 10 rep points.
Comment: Thanks for the help. I am right now struggling with callbacks. I would definitely learn promise as well, but after I learn callbacks. Thanks a lot though!
Comment: @metamemelord no worries...I added some code to show how you might do a callback in a little more streamlined manner. Just one thing to be aware of, callbacks can sometimes make code very difficult to read if you have several callback functions running in sequence. You can end up with a callback inside of a callback inside of a callback...often called "callback hell." It's why promises were invented; just something to be aware of.
Comment: I have upvoted all the three answers. When I was upvoting, I observed that someone had downvoted all three; I am not sure why is that so.
Comment: Ah, sorry, good on ya, it's hard to tell when a downvote has cancelled an upvote, or if no vote has been applied.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/169280/discussion-between-metamemelord-and-david784).


Importance of using all fingers while playing guitar

Question: I have been playing guitar for about 8 months now. I would say I'm progressing decently well, but my guitar teacher has one complaint against me: I don't use all my fingers of my fretting hand.
The fact is that I have REALLY long fingers. So for maneuvers a normal fingered person would have to use all fingers, I can manage equally well with just my index and middle finger. Only sometimes do I have to use my ring finger, and almost never my pinky.
My guitar teacher says that thought it's ok that i can play well with mainly two fingers, but not learning how to use all fingers will negatively affect me in the long run.
My question is: is my habit acceptable? Or will it really pull me back in the long run? Because I have to force myself to use my other two fingers which means playing becomes REALLY uncomfortable, though some other websites and sources say that "play how you feel comfortable".
All recommendations will be appreciated by me.

EDIT:Sorry, my internet connection was down so I couldn't view or reply any answers and comments.
I think I need to get a little more specific. In chords SURELY I can't play with just two fingers, but say, while playing solos. I'm not too good in soloing, but am practicing to solo. In such cases I find it more comfortable to use two fingers rather than all 4.
In response to Graham, one of the answerers, I might have only 8 months experience, but I'm a faster than average learner, so I feel OK in trying to do basic solos.
Thanks to all those who have answered and helped.
Comment: Ask your teacher to teach you things that require three or more fretting fingers to play. There are many.
Comment: The advice in http://music.stackexchange.com/questions/51974/how-do-i-stop-muting-nearby-strings-or-will-my-fingers-reshape-after-some-practi?noredirect=1&lq=1 is about practicing the thing which is hard, instead of looking for a way to avoid the hard thing. Every guitar player has something they have to work through before it becomes easy enough to not avoid.
Comment: How would you propose playing the "Hendrix chord" with two fingers? e.g. strings 1-6 fretted 0,8,7,6,7,0.  No matter how much you can do with two fingers, there are plenty of things e.g. Sweep picking that would be much harder (or more limited) if you haven't got good individual articulation of all of your fingers.  Best to practice now and make it easier for yourself later.
Comment: How would you play 4 different fret positions with only 2 fingers?  What about a position with a barre and then multiple other frets on 2 (or 3 or 4) different strings at the same time?  You are dramatically limited as to what level of music you can play if you only use 2 fingers, regardless of how long they are.  As a starting point, just try to play your current practice pieces faster.  You'll quickly see that it's quite difficult to move just those 2 fingers fast and accurately enough to keep up with the metronome.
Comment: You should investigate paul gilberts playing to see how good long fingers can be.
Answer: There are so many things that I play all the time that I can't figure out how to play with two fingers at all that I wonder if you are mainly playing very specific music.
You will want to be able to use all of your fingers, and you will want them all to be strong but not too strong, and flexible but not too flexible, and you will want them all to have muscle memory.
The majority of (non-open) chord shapes require all four fingers, and trying to play single notes with fewer than four fingers is very limiting.
I learned guitar for several years while hardly ever using my pinky (fourth finger). Then I decided I really had to take advantage of all the fingers I was born with and forced myself to learn scales, etc. with my pinky. I wish I'd started on that sooner. Don't be like me - get all the fingers into the game.
Comment: I'm not a guitar player but I started learning guitar first and anything I tried included all four fingers. All scales are based on four finger movements.
Answer: Well, one could always bring up Django Reinhardt, who used to play incredible stuff with only two fingers. So, you most definitely don't need to use all fingers to be a good guitarist, especially when you're mostly into pure melody stuff.
But I would fully agree with your teacher: it's just stupid to not use all fingers that you have available. Four fingers are necessary for full chords, and with a bit of practice, melodies are also much easier (especially WRT tempo, but also for expressive bending and proper muting) if you use all four fingers.
Answer: Once you get past the very early stages of learning, the technical business of practicing guitar is largely about minimising tension and effort, and finding the most efficient movements which accomplish the sounds you want to make.
Deciding to ignore half of your available fingers seems to me like a fairly drastic step in the opposite direction from where you need to be.
It might seem like hard work using your ring and pinky fingers, but that's not just you - everybody finds them harder to tame. The sooner you put in the effort, the sooner you'll reap the benefits, which will include but not be limited to:

playing a lot more chords and voicings, including barres that require more than one spare finger
choosing the appropriate fingers to play a chord based on the context, eg the next or previous chords in the progression, and any passing notes
playing accompaniment and melody at the same time
greater stamina, particularly in long/fast passages, due to the overall left hand effort being distributed across twice as many fingers

Django Reinhardt has inevitably been mentioned already. His lesson is not that you only need two fingers to play guitar, it's that good guitarists make the best of whatever fingers they have.
Answer: "Play how you feel comfortable" is good advice for ergonomics.  It's really, really bad advice for technique though.
For example, almost all guitar players start with their wrist bent backwards and the palm of the left hand supporting the neck.  It feels natural - and it's the single worst thing you can do for enabling your fingers to reach round the fretboard.
If you're used to playing with only two fingers, then playing with all four fingers will inevitably feel awkward or unnatural.  There's a big difference between "comfort" that just feels awkward, and "comfort" which relates to muscle pain.  And don't forget that if you're not used to using those fingers, they are inevitably going to be weaker.  However good your technique is, there's a certain minimum level of strength/endurance required, and unless you have a heavy manual job or do rock-climbing or something, it's very likely that those two fingers aren't up to that level yet.
I do have to question what your teacher is teaching you though, if you claim to be able to do everything with two fingers.  The vast majority of chords need more than two fingers.  Interesting string-crossing picking patterns such as the backing for "Every breath you take" need several strings held at once.  Many scales require three notes fretted per string using a standard fingering method, for the examination boards I'm aware of.  And there are vanishing few classical pieces which don't require more than two notes held at once.  The only thing you can reliably do with two fingers is soloing, and if you're only 8 months into learning the instrument then I seriously doubt you're in a position to know the instrument well enough for much of that.  This sounds suspect to me.
Comment: I'd rather say, "play how you feel comfortable _right now_" is bad advice. After sufficient practising, the correct technique _will_ feel comfortable.
Comment: "Play how you feel comfortable" is also bad advice for ergonomics. You generally feel comfortable doing things whatever way you've become used to doing them. I wonder how many people reading this are sitting up straight with their screens raised to eye level, and how many are comfortably hunched over their desks or comfortably sprawled over their sofas?
Comment: @leftaroundabout Certainly it should.  OTOH there are known problems with some techniques (e.g. Segovia's right hand position) which current knowledge of biomechanics should help us avoid, but not all teachers have taken the time to find out about them.  If you've got tingling in your hands/arms/shoulders, you're doing something very wrong.  If it's just sore muscles then suck it up buttercup. :)
Answer: To all of the above answers, I would just add this.  If your fingers are long, as mine also are, it might well be that you can comfortably reach intervals, especially in the lower positions, with fewer fingers than other people.  That might mean, for particular passages, that you can play them using fewer fingers.  But as the others say here, there are many passages where you need as many fingers as you have to play fluently.
Thus, though your most comfortable fingering for a given passage might use fewer fingers than many other players, most of the time you will need all your fingers to play as well as you can.
Answer: I'm guessing that you're talking about your left hand fingering, as finger length rarely, if ever, plays a part in the right hand.
Good guitar fingerings of difficult passages are figured out by experience (using something that worked in the past and applying it to the current passage) and trial and error (when the default doesn't work). A good sign that a fingering doesn't work for a given passage is that you constantly mess up at that point. A good fingering should feel fluid and sound good.
The index and middle fingers are certainly the most acrobatic fingers and it can seem that they will replace all the other fingers. This is why it's important to record yourself practicing and evaluate your playing with intense scrutiny. When you come across a passage that doesn't sound good or you mess up all the time, it's time to look at the fingering and figure out if another finger other than the two that you are using will do a better job.
Answer: I side with your music teacher, there is a whole different side to practice that it seems you may not have been exposed to yet. When you begin to learn different mode shapes and chords you will have to retrain yourself to begin incorporating your other fingers. This will cause you "double" work as you will be unlearning a bad habit so you can learn proper fretting. Also, these newly incorporated fingers will have less dexterity and strength that your dominant fingers. I highly suggest finding a major scale pattern and playing low on the fretboard (more comfortable spacing for longer fingers) and begin working out use of all four fingers across the strings. Comfort will come...
Answer: Find something that is ridiculously impractical to play using only two fingers, learn it (using proper finger positions), and then play it incessantly.  Do this with a few songs you like and before you know it your ring and pinky fingers will be nearly as strong as your index and middle.
You don't want to skip out on your weak fingers, or else they will always be your weak fingers.  The sooner you start strengthening them, the sooner they will become strong fingers.  If you think you can play well with just two fingers, it would stand to reason that you would be twice as good with twice as many fingers.  Okay, maybe not exactly like that, but you see what I'm saying.
Answer: You will limit yourself by using less fingers.
You may be perfectly comfortable playing with fewer fingers, but you will be limiting your future potential and setting a wall where there doesn't need to be one. If you really have a large reach then you can do so much more than learn simple melodies and repeat songs.
Outside of what you can currently do, and what other answers mention about practicing and making things easier, that is a big reason to learn to use all of your fingers. You don't want to be 10 years down the road wondering "what if".
Answer: You should practice using all of your fingers ON BOTH HANDS.
You should practice with and without a plectrum (pick).
You should practice all conceivable ways to use your fingers to make a particular chord.
You should practice the same chord in as many fretboard LOCATIONS as your guitar allows.
You should practice reading music, reading tablature, and playing by ear.
You should practice the things you are bad at MORE than the things you are good at.
You should practice, practice, practice, practice, practice, practice, practice, practice, practice, practice, practice, practice, practice, practice, practice, practice, practice, practice.
Comment: I think you mean _plectrum_.
Comment: And once you've finished doing all that... ***practice.***


Are Drupal .php files associated with a module cached?

Question: I am wondering if they are, as that would explain why a simple change to one of my variables in my config.php file is not showing up in the DOM.
Here is what is making me suspect this.
In my fls_price_calculator_2012 module in my includes directory I have a file called config.php.
I am trying to change my $START_DATES_OPTIONS_COMBINATIONS['Specialty Tours'] variable to look like the following:
$START_DATES_OPTIONS_COMBINATIONS['Specialty Tours']['Surf Camp - Saddleback College'] = array('June 29, 2014', 'July 6, 2014', 'July 13, 2014', 'July 20, 2014', 'June 28, 2015');

Simply adding June 28, 2015 as a last option to the array.
The php file is included in my .module file for the module, following this line:
include_once('includes/config.php')

in my fls_price_calculator_2012.module file.
The variable itself is added into a hidden <input> variable in the DOM in the same .module file like so:
$tour_start_dates = '<input type="hidden" id="tour_start_dates" etc...>'
foreach ($START_DATES_COMBINATIONS['Specialty Tours'] as $key => $value){
  //populates the above created input with the keys and values
}

once it is all loaded in the DOM, I search via the Javascript console for the #tour_start_dates element but I get the only the old value for Surf Camp - Saddleback College and I don't understand how that is happening.
Comment: No, Drupal won't cache the results of your custom code unless you explicitly tell it to, or the output is contained within something that Drupal is already responsible for caching (e.g. block content)
Comment: @Clive so do you have any idea why this simple change to my `config.php` file is not being picked up in production?
Comment: are you using a php optimizer with a cache lifetime that hasn't cleared yet?
Comment: i am not sure, this is a legacy Drupal site. Would it be listed as a recognizable php optimizer module?
Comment: @tenken the only optimizer I use that caches anything is ImageCache. I don't see any php optimizers on my Module page.
Comment: I mean something like APC or the newer php Opcache http://php.net/manual/en/book.opcache.php
Comment: Are you sure you aren't looking at a cached output of the whole page? If you clear page cache do the changes show up?
Answer: To answer it literally - probably, yes, on many levels:

Filesystem cache
Opcode cache
Possible other caches, depends on your configuration

Above caches should not create the effect you are seeing, but outout of the whole page is also cached, in your browser. Inspect headers to make sure it was not the case, and if so, clear caches and try again. If you have any proxy or reverse proxy, make sure they are not interfering, too.
If you are sure pages are not cached at output, and you didn't make Drupal to cache your variable, it shouldn't be cached. So there are two options:

Problems with include path:

Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include will finally check in the calling script's own directory and the current working directory before failing.

Maybe there is another instance of this file somewhere, one that gets higher priority in including? That's one of the reasons to use module_load_include instead.
Problems with uploading. You know what you sent to your server. But have you inspected (from console, for example) what really is there? Maybe you are looking for something that isn't even there.


How to model volatility spillovers between some financial time series?

Question: I am doing research to study volatility spillover effects between  several financial time series $\{x_{1,t}\}, \dots, \{x_{k,t}\}$ (in my case, $k=4$). What would be the best model to study the spillover effect of other series on $x_{1,t}$?
I was thinking of using VAR-GARCH or BEKK-GARCH Model in R. Any suggestion would be highly appreciated.
Comment: This is an edited copy of a thread that has been deleted. I repeatedly encounter similar questions, and the answer I gave in the deleted thread is relevant for many users. Therefore, I have copied the thread to preserve the answer.
Answer: VAR
VAR is a conditional mean model and as such has nothing to do with volatility spillovers – unless you apply it on realized variances instead of raw data. In that case it is a model that directly allows for volatility spillovers; see Diebold & Yilmaz "Better to give than to receive: Predictive directional measurement of volatility spillovers" (2012).
BEKK-GARCH
Unfortunately, full BEKK-GARCH appears to be a nonsense model; see McAleer "What They Did Not Tell You about Algebraic (Non-) Existence, Mathematical (IR-)Regularity and (Non-) Asymptotic Properties of the Full BEKK Dynamic Conditional Covariance Model" (2019). Diagonal BEKK-GARCH is fine, though (ibid.), but it does not seem to allow for volatility spillovers; see e.g. equations (6), (9) and (11) on p. 5 of Erten et al. "Volatility Spillovers in Emerging Markets During the Global Financial Crisis: Diagonal BEKK Approach" (2012) – even though people use it for the purpose (e.g. Zolfaghari et al. "Volatility spillovers for energy prices: A diagonal BEKK approach" (2020)).
DCC-GARCH
Some people use DCC-GARCH for the purpose, but that model does not allow for volatility spillovers by design (just like the diagonal BEKK-GARCH), as I have explained elsewhere. Moreover, it is also full of problems: McAleer "What They Did Not Tell You about Algebraic (Non-) Existence, Mathematical (IR-)Regularity, and (Non-) Asymptotic Properties of the Dynamic Conditional Correlation (DCC) Model" (2019).
Other models (e.g. GO-GARCH)
There are other multivariate GARCH models out there, as reviewed in Bauwens et al. "Multivariate GARCH models: a survey" (2006) and Silvennoinen & Teräsvirta "Multivariate GARCH models" (2009). Perhaps some of them might work. E.g. consider GO-GARCH; there are at least a couple of packages for estimating the model in R, namely, gogarch and rmgarch. I am just afraid McAleer comes out soon and explains how GO-GARCH is full of problems, too :)
RIP Michael John McAleer. The world of econometrics has lost a great man.


backbone.js model not firing events

Question: I have a view which doesn't seem to want to render as the model's change event is not firing.
here's my model:
var LanguagePanelModel = Backbone.Model.extend({
    name:       "langpanel",
    url:        "/setlocale",
    initialize: function(){
        console.log("langselect initing")
    }
})

here's my view:
var LanguagePanelView = Backbone.View.extend({
    tagName:        "div",
    className:      "langselect",
    render:         function(){
        this.el.innerHTML = this.model.get("content");
        console.log("render",this.model.get(0))
        return this;
    },
    initialize : function(options) {
        console.log("initializing",this.model)
        _.bindAll(this, "render");
        this.model.bind('change', this.render);
        this.model.fetch(this.model.url);
  }
});

here's how I instantiate them:
if(some stuff here)
{
   lsm = new LanguagePanelModel();
   lsv = new LanguagePanelView({model:lsm});
}

I get logs for the init but not for the render of the view?
Any ideas?
Comment: worth noting that the setlocale url is showing nicely too with correct JSON content in chrome dev tools
Answer: I guess it's about setting the attributes of the model - name is not a standard attribute and the way you've defined it, it seems to be accessible directly by using model.name and backbone doesn't allow that AFAIK. Here are the changes that work :) You can see the associated fiddle with it too :)
$(document).ready(function(){
var LanguagePanelModel = Backbone.Model.extend({
    //adding custom attributes to defaults (with default values)
    defaults: {
        name:       "langpanel",
        content: "Some test content"  //just 'cause there wasn't anything to fetch from the server
    },

    url:        "/setlocale",

    initialize: function(){
        console.log("langselect initing"); //does get logged
    }
});

var LanguagePanelView = Backbone.View.extend({
    el: $('#somediv'), //added here directly so that content can be seen in the actual div

    initialize : function(options) {
        console.log("initializing",this.model);
        _.bindAll(this, "render");
        this.render(); //calling directly since 'change' won't be triggered
        this.model.bind('change', this.render);
        //this.model.fetch(this.model.url);
    },

    render: function(){
        var c = this.model.get("content");
        alert(c);
        $(this.el).html(c); //for UI visibility
        console.log("render",this.model.get(0)); //does get logged :)
        return this;
    }
});

var lpm = new LanguagePanelModel();
var lpv = new LanguagePanelView({model:lpm});

}); //end ready

UPDATE:
You don't need to manually trigger the change event - think of it as bad practice. Here's what the backbone documentation says (note: fetch also triggers change!)
Fetch

model.fetch([options])
  Resets the model's state from the server.
  Useful if the model has never been populated with data, or if you'd
  like to ensure that you have the latest server state. A "change" event
  will be triggered if the server's state differs from the current
  attributes. Accepts success and error callbacks in the options hash,
  which are passed (model, response) as arguments.

So, if the value fetched from the server is different from the defaults the change event will be fired so you needn't do it yourself. If you really wish to have such an event then you can use the trigger approach but custom name it since it's specific to your application. You are basically trying to overload the event so to speak. Totally fine, but just a thought.
Change

model.change()
  Manually trigger the "change" event. If you've been
  passing {silent: true} to the set function in order to aggregate rapid
  changes to a model, you'll want to call model.change() when you're all
  finished.

The change event is to be manually triggered only if you've been suppressing the event by passing silent:true as an argument to the set method of the model.
You may also want to look at 'has changed' and other events from the backbone doc.
EDIT Forgot to add the updated fiddle for the above example - you can see that the alert box pops up twice when the model is changed by explicitly calling set - the same would happen on fetching too. And hence the comment on the fact that you "may not" need to trigger 'change' manually as you are doing :)
Comment: Thanks for this. I was after the this.trigger("change") but massive thanks for the heads up on the defaults :-)
Comment: I've just tried what you said removing the trigger and the fetch. No request is made to the server at all? Which is really annoying.
Comment: Try changing the defaults to some garbage value and check - maybe the data is the same. Are the models even getting populated with data to begin with?
Answer: The issue was resolved my adding
var LanguagePanelModel = Backbone.Model.extend({
    //adding custom attributes to defaults (with default values)
    defaults: {
        name:       "langpanel",
        content:    "no content",
        rawdata:    "no data"
    },
    events:{
        //"refresh" : "parse"
    },
    url:        "/setlocale",
    initialize: function(){
        log("langselect initing");
        //this.fetch()
    },
    parse: function(response) {

        this.rawdata = response;
                // ... do some stuff
        this.trigger('change',this) //<-- this is what was necessary
    }
})

Comment: You MAY NOT need to manually trigger 'change' - see my update
Answer: You don't need attributes to be predefined unlike PhD suggested. You need to pass the context to 'bind' - this.model.bind('change', this.render, this);
See working fiddle at http://jsfiddle.net/7LzTt/ or code below:
$(document).ready(function(){
    var LanguagePanelModel = Backbone.Model.extend({

        url:        "/setlocale",
        initialize: function(){
            console.log("langselect initing");
        }
    });

    var LanguagePanelView = Backbone.View.extend({
        el: $('#somediv'),

        initialize : function(options) {
            console.log("initializing",this.model);
            // _.bindAll(this, "render");
            //this.render();
            this.model.bind('change', this.render, this);
            //this.model.fetch(this.model.url);
        },

        render: function(){
            var c = this.model.get("content");
            alert(c);
            $(this.el).html(c);
            console.log("render",this.model.get(0));
            return this;
        }
    });

    var lpm = new LanguagePanelModel();
    var lpv = new LanguagePanelView({model:lpm});

    lpm.set({content:"hello"});

}); //end ready

backbone.js model not firing events


Como por um JScrollPane em um JTextArea?

Question: Estou tentando criar um projeto onde imprimo diversas frases em um JTextArea, mas para isso, preciso incluir um JScrollPane. Olhei alguns exemplos na internet mas nenhum está funcionando.
public class Projeto extends JFrame {

    JPanel painel = new JPanel();
    public static JTextArea textarea = new JTextArea();
    public static JScrollPane sp = new JScrollPane();
    JButton cmd1;

public static void main(String[] args) {
   new Projeto();
}

public Projeto(){
    super("Árvore");
    setResizable(false);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLocationRelativeTo(null);

    painel.setPreferredSize(new Dimension(600,400));
    painel.setLayout(null);

    cmd1 = new JButton("Start!");
    cmd1.setBounds(450, 50, 100, 30);
    painel.add(cmd1);

    textarea.setBounds(50, 50, 300, 300);
    textarea.setEditable(true);
    sp.add(textarea);

    painel.add(sp);

    add(painel);
    pack();

    setVisible(true);

    event e = new event();
    cmd1.addActionListener(e);
}

public static void atualiza(String frase){
    textarea.append(frase);
}

public class event implements ActionListener{
    Pai p = new Pai();
    public void actionPerformed(ActionEvent e){

        p.start();
    }
}
}

Answer: Defina a JTextArea como portview do JScrollPane:
sp.setViewportView(textarea);

Um JScrollPane é um container flexível, que se adapta conforme um componente adicionado a ele. Mas para isso, este componente precisa ser um viewPort do painel rolável. Isso só é possível passando o componente para o painel em seu construtor ao inicia-lo, ou utilizando o método setViewportView(). O método add não funciona corretamente para este painel em especifico.

Uma dica:

Evite usar layout absoluto, a não ser que seja de extrema necessidade e que saiba as consequências disso, pois layout absoluto dificulta manutenção da tela e faz com que sua aplicação fique com aparência diferente dependendo do monitor e resolução que estiver sendo executada.
Existem vários gerenciadores de layouts para que você não tenha que se preocupar com posicionamento ou organização manual de componentes. Sem contar que o uso de layouts faz com que seu código fique mais fácil de dar manutenção do que ficar inserindo um monte de setbounds, e caso precise alterar a posição de algum componente, vai ter que posicionar todos manualmente.

No seu código mesmo, por utilizar layout absoluto, a JTextArea jamais será exibida, pois você definiu um tamanho e posição pra ele, mas para o scrollpane não há nada sobre seu tamanho e posição. Com a alteração abaixo, o componente é exibido normalmente:
sp.setBounds(50, 50, 300, 300);
textarea.setEditable(true);
sp.setViewportView(textarea);

Comment: O problema é que eu uso o painel.add(sp); mas o JScrollPane e o JTextArea não estão mais aparecendo no painel.
Comment: @GustavoCruz você alterou conforme a resposta? Isso parece ser outro problema diferente.
Comment: Alterei sim e continua com o mesmo problema.
Comment: @GustavoCruz o problema não tem a ver com isso, é que você está usando layout absoluto, o que é uma pessima pratica. Pesquise sobre layouts managers para swing, layout absoluto só causa esse tipo de problema, ainda mais se não souber exatamente o que se está fazendo com ele.
Comment: @GustavoCruz mas se quiser continuar utilizando layout absoluto, veja a edição.
Comment: O problema foi resolvido. Muito obrigado pela ajuda Articuno.


For using Micrsoft.Web.Adminsitration in a console application, is there any extra references required?

Question: I'm trying to write a console application that will run and remove/add items to the IP Granted table.
I have a web-based version of this running perfectly(standard asp.net program) and now I'd like to port some of the functionality to a console app, and I'm running into problems.
The console app reports missing references and how Microsoft.Web does not exist (but I have added the reference for Microsoft.Web.Adminsitration and set copy local and specific version to true). The Microsoft.Web.Administration dll is being reference from C:\Windows\System32\inetsrv\Microsoft.Web.Administration.dll.
I had a similiar problem with the web-based version, but after a reference to System.Web, it's fine.
However this fix is not working in the console application.
Is there an additional package I am missing/should use, or?
Answer: Are you using Visual Studio 2010 and .Net 4? If so, the following might help you:
http://blog.stevienova.com/2010/10/01/visual-studio-2010-console-app-where-is-my-system-web/
In short, it comes down to VS2010 having the default target for console projects set to the .NET Framework 4 Client Profile instead of .NET Framework 4. Changing it to the latter should enable you to reference System.Web.


É possível aplicar estilo CSS em método de envio de e-mail?

Question: Tenho o seguinte método que envia um e-mail de recuperação de senha para o usuário.
Gostaria de saber se é possivel aplicar algum tipo de formatação CSS no mesmo, a fim de deixar mais atrativo o e-mail enviado.
E-mail Recebido:

Código:
public void EnviarEmailRedefinicaoSenha(int Codigo)
        {
            try
            {
                string empresa = _config.GetValue<string>("EmpresaEmail");
                Clientes objClientes = new Clientes(_config).ConsultarClientes(Codigo);
                Data = DateTime.Now.AddMinutes(10).ToString("HH:mm:ss");
                this.Assunto = "Redefinição de senha";//Assunto,
                StringBuilder BodyContent = new StringBuilder();

                Link = "<a href =http://" + Link + "/Accounts/RedefinicaoSenha?id=" +
                    PCIGlobal.Encrypt(Codigo.ToString(), _config.GetValue<string>("keyEncryption")) +
                    "&T=" + PCIGlobal.Encrypt(Data, _config.GetValue<string>("keyEncryption")) +
                    ">Clique aqui";

                BodyContent.Append("Prezado(a) " + objClientes.CliNome + ", ");
                BodyContent.Append("
");
                BodyContent.Append("
");
                BodyContent.Append("Você solicitou a redefinição da sua senha de acesso ao Escritório Virtual.");
                BodyContent.Append("
");
                BodyContent.Append("Não se preocupe, o processo é simples, basta clicar no link abaixo e seguir as instruções.");
                BodyContent.Append("
");
                BodyContent.Append(Link);
                BodyContent.Append("
");
                BodyContent.Append("
");
                BodyContent.Append("Qualquer problema entre em contato conosco.");
                BodyContent.Append("
");
                BodyContent.Append("
");
                BodyContent.Append("Atenciosamente,");
                BodyContent.Append("
");
                BodyContent.Append("Equipe " + empresa + "");

                this.Mensagem = BodyContent.ToString();
                this.EnviarEmail();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

Comment: Sim é possível usar o CSS direto na Tag. Qualquer folha de Estilo indexada vai ser ignorada pela maioria dos SMTP, algo tipo isso deve funcionar: `BodyContent.Append("Você solicitou a redefinição da sua senha de acesso ao Escritório Virtual.");`
Answer: Apenas para ficar como registro vou publicar o meu comentário como resposta. Assim vc pode finalizar a pergunta se achar que resolveu o seu problema.
Sim é possível usar o CSS direto na Tag. Qualquer folha de Estilo indexada vai ser ignorada pela maioria dos SMTP, algo tipo isso deve funcionar:
BodyContent.Append("
Você solicitou a redefinição da sua senha de acesso ao Escritório Virtual.
");
O código acima seria o mesmo que: p {font-size:16px; color:red;} no .css
Aqui tem dois links em português que pode te ajudar com boas práticas de CSS para email
https://tableless.com.br/boas-praticas-para-e-mail-marketing/ https://www.benchmarkemail.com/br/help-FAQ/answer/Usar-CSS-em-emails-HTML


Find longest common subsequence of 2 String?

Question: I'm learning about the longest common subsequence, Using these algorithm:

public class LCS {
static int[][] E;
static int[][] S;
static int D;
static int T;
static int L;
public static void LCS_cost(String X,String Y)
{
    int m = X.length();
    int n = Y.length();
    E = new int[m][n];
    S = new int[m][n];
    for(int i=0;i<m;i++){
        E[i][0] = 0;
    }
    for(int j=0;j<n;j++){
        E[0][j] = 0;
    }
    for(int i=1;i<m+1;i++){
        for(int j=1;j<n+1;j++){
            if(X.charAt(i) == Y.charAt(j)){
                E[i][j] = E[i-1][j-1]+1;
                D =  E[i-1][j-1]+1;
                S[i][j] = D;//Diagonal Direction
            }
            else if (E[i-1][j]>=E[i][j-1]){
                    E[i][j] = E[i-1][j];
                    T = E[i-1][j];
                    S[i][j] = T;//TOP
            }
            else
                    E[i][j] = E[i][j-1];
                    L = E[i][j-1];
                    S[i][j] = L;//Left
        }
    }

}

public static void Backtrack(int[][] S,String X,String Y){
int row = X.length();
int col = Y.length();

while (row > 0 || col > 0){
    if (S[row][col] == D){
        System.out.print(X.charAt(row));
        row--;
        col--;
    }
    else if (S[row][col] == T){
        row--;
    }
    else
        col--;
}
}
public static void main(String[] args) {
    new  LCS();
    LCS_cost("SCHOOL","SPOOL");
    Backtrack(S,"SCHOOL", "SPOOL");
    }
}

But the program return an ErrorCharAt(Unknow Source) and didn't do anything.
i'm trying to change
for(int i=1;i<m+1;i++){
        for(int j=1;j<n+1;j++){

to
for(int i=1;i<m;i++){
        for(int j=1;j<n;j++){

the result is this line IndexOutofBoud
if (S[row][col] == D){
    ....
    }

Also,if i change  int i and j to 0 then E below would be index -1 and error
for(int i=0;i<m;i++){
        for(int j=0;j<n;j++){
            if(X.charAt(i) == Y.charAt(j)){
                E[i][j] = E[i-1][i-1]+1;
                ......
            }

i'm so lost right now.Can anyone help me?
Answer: I would go about this using strings rather than dealing with individual characters:
String findLCS(String str1, String str2) {
    int longest = 0;
    String longestSubstring = "";

    for (int i=0; i < str1.length(); ++i) {
        for (int j=i+1; j <= str1.length(); ++j) {
            String substring = str1.substring(i, j);
            if (str2.contains(substring) && substring.length() > longest) {
                longest = substring.length();
                longestSubstring = substring;
            }
        }
    }

    return longestSubstring;
}

As you can see, using String.contains() is more powerful than it looks.
Comment: I don't think what you have there is what's typically referred to as LCS.  LCS is basically "diff".  He needs all sub-strings in common, not just the single longest segment, and "all" should be the "all" that results in the longest sequence.
Comment: Title: `Find longest common subsequence of 2 String` ... how does my answer not address that?   If he wants all subsequences in common, he can make a one line change to my answer and add each sequence to a set.
Answer: If
 int m = X.length();

then
for(int i=1;i<m+1;i++){
   ...
   if(X.charAt(i) ....

will throw an error as in Java arrays are zero based
Also if
int row = X.length();
int col = Y.length();

if (S[row][col] == D){

will throw an error
Also, use String.equals to compare Strings not ==
Answer: import java.util.Scanner;
class Main {
public static void main(String[] args)
{

Scanner sc=new Scanner(System.in);

    Sub s=new Sub();

    int t=Integer.parseInt(sc.nextLine());

    for(int i=1;i<=t;i++)
    {

    String a=sc.next();
    String b=sc.next();

    System.out.println("Case "+i+": "+s.subString(a, b));

}

}
}
class Sub
{
   public static int subString (String a,String b)
   {

       int max=0;
       int m=a.length();
       int n=b.length();

       int dp[][]=new int [m][n];

       for(int i=0;i<m;i++)
       {

           for(int j=0;j<n;j++)
           {

               if(a.charAt(i)==b.charAt(j))

               {
                   if(i==0||j==0)
                   {
                       dp[i][j]=1;
                   }
                   else
                       dp[i][j]=dp[i-1][j-1]+1;
               }

               if(max<dp[i][j])

                   max=dp[i][j];
           }

       }

       return max;

   }

}
Comment: how about inserting the output of the code as well ?
Answer: You are using a matrix approach where we,

In case [i]th char & [j]th char matches - go previous diagonally [i-1][j-1] value and  add 1 for lcs length
In case [i]th char & [j]th char don't match - then take max value of {left [i][j-1] or right [i-1][j] for lcs.

Personally I feel this approach is more scripted and essence of Dynamic Programming & Memorization shed behind it. When we are more relying on script approach rather than pure logic of DP & memo - we are more prone to error or may be lost in between...
Rather than matrix approach I have used Dynamic Programming and memoization to demonstrate LCS as -
package com.company.dynamicProgramming;

import java.util.HashMap;
import java.util.Map;

public class LongestCommonSubsequnce {

    public static void main(String ...args){

        String s1 = "SCHOOL";
        String s2 = "SPOOL";
        System.out.println(new StringBuilder(findLcs(s1, s2, new HashMap<>())).reverse());
    }

    static String findLcs(String s1, String s2, Map<String, String> memo){

        //check if lcs is already processed in memo for s1 & s2
        String lcs = memo.get(s1+"-"+s2);
        if(lcs != null){
            return lcs;
        }

        if (s1.substring(s1.length()-1).equals(s2.substring(s2.length()-1))){
            lcs = s1.substring(s1.length()-1);
            if(s1.length()>1 && s2.length()>1){
                lcs = lcs + findLcs(s1.substring(0, s1.length()-1), s2.substring(0, s2.length()-1), memo);
                memo.put(s1.substring(0, s1.length()-1)+ "-" + s2.substring(0, s2.length()-1), lcs);
            }
            else {
                memo.put(s1+"-"+s1, lcs);
            }
            return lcs;

        }else {

            String lcs1="";
            String lcs2="";

            if(s1.length()>1 && s2.length()>1){
                lcs1 = findLcs(s1.substring(0, s1.length()-1), s2, memo);
                memo.put(s1.substring(0, s1.length()-1)+"-"+s2, lcs1);
                lcs2 = findLcs(s1,s2.substring(0, s2.length()-1),memo);
                memo.put(s1 +"-"+s2.substring(0, s2.length()-1), lcs2);
            }
            else if(s1.length()>1){
                lcs1 = findLcs(s1.substring(0, s1.length()-1), s2, memo);
                memo.put(s1.substring(0, s1.length()-1)+"-"+s2, lcs1);
            }
            else if(s2.length()>1){
                lcs2 = findLcs(s1,s2.substring(0, s2.length()-1),memo);
                memo.put(s1 +"-"+s2.substring(0, s2.length()-1), lcs2);
            }else {
                memo.put(s1+"-"+s2,"");
            }

            if(lcs1.length() >= lcs2.length()){
                return lcs1;
            }else {
                return lcs2;
            }
        }
    }
}

Run this code and result is -
SOOL

Process finished with exit code 0


How do I show an Open/Save file dialog using an AJAX callback?

Question: In the form builder I have the following code.
$form['export_to_pdf'] = [
  '#type' => 'submit',
  '#value' => $this->t('Pdf Format'),
  '#attributes' => array('name'=>'print_pdf',),
  '#ajax'=> array(
    'callback' => '::exportPdf',
    'event' => 'click',
    'effect' => 'fade',
    'prevent' => 'submit',
    'progress' => array(
      'type' => 'throbber',
      'message' => t('Retrieving...'),
    ),
  ),
];

The callback function is the following one.
public function exportPdf(array &$form, FormStateInterface $form_state) {
  global $base_url;
  $url = "{$base_url}/pdf_templates/report.pdf";
  $response = new AjaxResponse();
  $response->addCommand(new RedirectCommand($url));
  return $response;
}

This works, but it doesn't pop up the Open/Save file dialog. It redirects to the PDF file. How do I make the callback show the Open/Save file dialog so that the users can either open or save according to their wish?
Answer: For Open /Save Dialog  pop up you can use following ajax commands in the ajax callback
1.OpenModalDialogCommand
2.OpenDialogCommand

Don't forget to include following namespaces
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\OpenModalDialogCommand;
use Drupal\Core\Ajax\OpenDialogCommand;

In your ajax callback function add like below:
 $content = AjaxTestController::dialogContents();
 $response = new AjaxResponse();
$title = $this->t('AJAX Dialog & contents');

Attach the library necessary for using the Open(Modal)DialogCommand and
     set the attachments for this Ajax response.
$content['#attached']['library'][] = 'core/drupal.dialog.ajax';
if you need as modal dialog you can use below statement

$response->addCommand(new OpenModalDialogCommand($title,
$content));

or only dialog type
 $selector = '#ajax-test-dialog-wrapper-1';
    $response->addCommand(new OpenDialogCommand($selector, $title, $content);

return $response;
for any reference you can check below files in the  drupal directory

core/modules/system/tests/modules/ajax_test/src/form/AjaxTestDialogForm

After completing the dialog command ,you can use  your redirect command to continue
Comment: Is there no way to use the browser in-built Open/Save file dialog because your answer will require repeating the code behind these in-built Open/Save file dialog.


How to get a custom block form in another custom block?

Question: I have a custom block
/**
 * Provides block A.
 *
 * @Block(
 *   id = "block A",
 *   admin_label = @Translation("Block A"),
 * )
 */
class Block A extends BlockBase implements ContainerFactoryPluginInterface {

  public function defaultConfiguration() {
    return [some_value]
  }

  public function blockForm($form, FormStateInterface $form_state) {
    // Configuration form
  }
}

Now I have another block
/**
     * Provides block B.
     *
     * @Block(
     *   id = "block B",
     *   admin_label = @Translation("Block B"),
     * )
     */
    class Block B extends AnotherClass {

      public function defaultConfiguration() {
        return [some_value]
      }

      public function blockForm($form, FormStateInterface $form_state) {
        $form = BlockA->buildForm()
        return $form;
      }
    }

The AnotherClass extends BlockBase.
Is it possible to display the Block A configuration form in Block B?
Like $form = BlockA->buildForm()?
The problem with @Clive comment is that Block A is from the contrib module. So I can't change its base class.
Comment: If the block classes share common functionality, they should inherit from the same base class. So yes, just move the form method into `AnotherClass`, and make sure `BlockA` and `BlockB` both inherit from it. There are several other ways to solve the problem of course, what you're asking about are just standard OO principles and how to implement them in PHP
Comment: The problem is `Block A` is from contrib module, so I don't have any control over it. @Clive
Answer: The answer is to use the plugin.manager.block service
Example:
In the Block B BlockForm method.
public function blockForm($form, FormStateInterface $form_state) {
  $block_manager = \Drupal::service('plugin.manager.block');
  $block_a = $block_manager->createInstance('block_a');
  $form = block_a->blockForm($form, $form_state)
  return $form;
}


How do I use slash chords in music composition?

Question: After studying pop music composition for a while I noticed that many composers use slash chords in their music. How do I use those in my own composition? When is it more preferable to use slash chords than traditional chords?
Answer: Here are some cases where slash chords might be used:
Pedal point
The most boring case. The bass holds (or repeats) a note while the harmonies change. Useful in everything from bagpipe drones to the codas of Bach organ fugues.
Passing tones
Sort the reverse of the above. The bass is moving around while the harmony is staying relatively static, leading to passing tones and such.
Inversions
You're probably already used to seeing these types of chords.

1st (3rd in bass) -- a slightly less stable version of the chord, with a strong desire for the bass to resolve stepwise upward to the root of the next chord. C/E wants to resolve to F.
2nd (5th in bass) -- an even less stable version of the chord, typically used as a passing chord, or in a "cadential 6 4" formula, as in classical music, where the bass stays put, and the upper voices resolve downward. C/G wants to resolve to G.
3rd (7th in bass) -- This inversion tends to slap you in the face, and has a feeling of things wanting to fall apart. The bass typically resolves downward to become the third of the next chord. C/Bb wants to resolve to F/A.

Extended chords
This is where things get interesting, and is what I think you're probably asking about.
Jazz-based styles, especially, are prone to building harmonies beyond 7th chords by stacking thirds. So you get 9th chords, 11th chords, even 13th chords. Often these chords will also omit notes. Sometimes it seems like just about any note can be thrown into a chord (sometimes even if its not in the scale) but I'm pretty sure that's not the case. A full discussion of chord extensions is outside the scope of this question, but here's how they can lead to slash chords.
First a simple case (that you wouldn't typically see): Let's say you have CM7 (C, E, G, B). This could technically be written as an E minor chord over a C (Em/C). If you play an E minor chord with your right hand, then add a C in the left hand, you can see how the CM7 chord retains some of the meloncholy "flavor" of the E minor chord, even though CM7 is technically a major. You can try this with other seventh chords as well, playing all but the bass note, then adding the bass note.
Now lets take it up a third higher. Say you have a C9 (C, E, G, Bb, D), which is an extended version of a dominant C7. One possibility is to omit the 3rd completely, giving a Gm/C. Another possibility is to make the 3rd a suspended 4th, which gives a C9sus4: (C, F, G, Bb, D), or Gm7/C. Finally, you might choose to omit the 5th (G), giving a Bb/C. This might be the same situation as your Eb/F chord that you mentioned: you have the IV chord over the 5th scale degree. This specific combination is a common enough occurrence that wikipedia calls it a "jazz sus chord". Note that, classically, a sus4 chord would be expected to resolve, but that is not the case here. Instead, the dissonance is embraced, and the sus4 is used as a substitution for the dominant. Essentially, it acts like a dominant chord, but with less urgency (since there's no leading tone), seasoned with the "sweetness" of a subdominant IV chord. Since this is a dominant chord, it should resolve to a tonic. You could try resolving to an FM7 chord, (voiced as an Am/F), so the progression looks like C9sus4 -> FM7 (or in slash chords: Bb/C -> Am/F).
Hopefully the "mixing flavors" metaphor will give you an idea of how to approach experimenting with extended chords.
Answer: The most common way to play "slash" chords (more properly known as chord inversions) is to take a major chord and play it over it's III or V. However any chord with a non-I note as its bass note would be consider an inversion.
For example, the root note for the D major chord is the note D. So playing a D major chord with a root note that is anything but the note D would considered an inversion of D major.
Common Usage
John Mayer's Free Fallin is a cool example. The chord progression F - Bb - F - C. However John is inverting the F chord and playing it over an A note. He does it the whole song. It gives a sort of "suspension" feeling because your brain expects to hear an F chord over an F note, and the playing of the A gives it a some suspense.
Oh The Blood by Gateway Worship is another awesome example as it has two slashes in a row in the chorus. D/F# - C/E - G. You'll hear it at the start of the chorus at the 47 second mark. If you want a treat then wait for the bridge when Kari goes into super-angel-voice-overdrive.
By The Way by RHCP is a cool example. Right away the first chord is strummed 8 times and then inverted by playing the root note down 1 step.
And the classic, I'll Make A Man Out Of You from Mulan. It starts with Em - D/F# - G.
Really though, the best way to add this to your own writing is to listen to a butt-ton of songs and learn them. Add them to all your songs then listen to them. Your ear will tell you when not to use them.
Comment: Do you have an example that doesn't uses the chord tones. I sometimes hear Bbm7/Ab or Eb/F, but I don't know how to use those.
Comment: In the case of Eb/F, it's *not* the same as D/F#. The later is first inversion (3rd in the bass), but the former is a non-harmonic tone (specifically a 2nd). I'd guess (without knowing the context) that the F in the bass is a passing tone, or something similar. Alternately, it might be a sort of "upper structure" thing going on. Think of it as an F11 chord (F, A, C, Eb, G, Bb), without the 3rd or 5th. I see this sometimes when what *looks* like a IV chord is placed over the 5th scale degree, and functions as a V.
Comment: Bbm7/Ab would be third inversion, since Ab is the seventh of the chord.
Answer: To add tension...
Very [very] simple example...
F, G, C or instead
F, G/F, C
Gives the 'trad' IV, V 7th, I but puts the tension in the bass.


How to associate a goal conversion with the ad campaign?

Question: I start an Ad campaign and whenever user clicks the Ad banner, he will be redirect to a URL like this:
mysite.com/?utm_source=ad3
Then in my Google Analystics, I defines a goal as:
mysite.com/goal.htm
Then how to associate the ad campaign with the goal so that I can know whether the goal is generated from the ad campaign?
Answer: When using manual campaigns utm_source, utm_medium and utm_campaign are required parameters, you should use all 3.
If you go into your traffic source reports you can select the Goal metrics to see how many goals are completed per traffic source. This is automatically done for your correctly manual tagged campaigns.


How to create custom gradle plugin for Android application

Question: How to create custom gradle plugin for Android application?
Which language is best for creating custom plugin for Android app development purposes and can be used in Gradle build file for building process?
Comment: http://blog.sqisland.com/2015/02/gce2retrofit-gradle-plugin.html
Answer: You can add your code to buildSrc module. For a Groovy plugin the directory will be buildSrc/src/main/groovy.
package com.example;

import org.gradle.api.Plugin
import org.gradle.api.Project

class MyPlugin implements Plugin<Project> {
   ...
}

and then from your build.gradle
apply plugin: 'com.android.application'
import com.example.MyPlugin

android {
    ...
}


How can I do rough vocals without hurting my voice?

Question: I recently wrote a song where the vocals are supposed to sound rough, but not quite growling/screaming. What's the best way to get that sort of sound from my voice without any long-term or short-term adverse effects?
Comment: related: http://music.stackexchange.com/questions/7674/what-are-nodules-and-how-do-you-avoid-them
Comment: Probably you are searching for "belting technique": http://www.youtube.com/results?search_query=belting+technique&sm=3 - p.s.: don't listen to the fat guy from expertvillage. He's one of the guys from classical training who ignore giants of soul, gospel and rock.
Comment: Vocal Frys - They make you want to fry in all your singing :)
Answer: [Insert obligatory 'ruining your voice for eternity' lecture here]
Now that's over with... Here is what I've found from my experiences with trying to make my voice sound rough.
Quick Background: I've been experimenting with this style for 3 or 4 years, just on a casual level while practising, not a professional or even performance basis. Also, most of the time I Don't sing this way, but I'll usually work on it a couple hours over the course of a week. Over the course of this time I haven't caused damage to my voice, and have actually improved my vocal range, control, and skill level (with this style and overall).
I'm not a vocal scientist, so I'm not even going to venture into the realm of 'What is actually going on in this throat-thing'. But here are some things I've observed that hopefully may help you:
Tips on Getting the 'Rough' Sound:

Like slim posted, it's all about tightening the throat. It's difficult to explain how to actually do this, but it's basically like trying to imitate a smoker voice. Try this just speaking at first, without singing. Just focus on feeling what muscles you need to use to get that rough sound, and once you get a feel for that, STOP.
In my experience, it's actually easier to go overboard and damage your voice doing this while speaking, than while singing.
Now try doing the same thing while singing. I've found that the higher in your range that you sing, the easier it is to get this rough sound. It's important to realize that its actually easy to get a very rough sound (which will end up damaging your voice). The trick is to get just a little roughness, so that the pitch isn't completely choked. Don't expect to be able to consistently produce the sound you want right away, as you practice you will develop more control.
For singing in your lower range (which doesn't work as well with the previous technique you might find), you can use a different trick that seems like a combination of singing and 'coughing'. [Insert more voice safety ranting here... ] Like anything, as long as you don't abuse this technique, your voice should be fine (but don't sue me). Cough a couple times and notice how there's a 'grinding' deep in your throat that produces the cough. On a smaller scale, you can reproduce this grinding while singing to give your voice a low growl. Not only that, but I've used this to clear my throat and sing at the same time!
Another trick to give your voice an 'edginess', especially if you're trying to reproduce something like Marianas Trench, is to use what's called a 'glottal stop' also referred to by some as a 'glottal attack' when done in an extreme sense. [Insert the now violent, foaming-at-the-mouth vocalist opposition here]. This technique doesn't have to do with roughness per say, but it helps to bring out the intensity of your voice. The non-scientific explanation is: you cut off the flow of air in your throat, build up pressure, and let it all out at once.
All to Myself by Marianas Trench  is a good example of this technique in action (as well as throat-tightening). Though as an aside: there are definitely some parts in this song where it sounds like Josh Ramsay is damaging his voice.
Many red flags pop up for vocalists at the mention of glottal stops, for good reason, in a sense you're playing with fire. I've successfully been able to use this technique and so far haven't had any adverse effects on my voice. I still think there's merit in the argument that you can seriously damage your voice through glottal abuse though.
Here's the best discussion I could find on what a glottal stop is and whether it can damage your voice. Don't necessarily draw conclusions from this article (to me it seems biased pro-glottal), but use it to understand the issues and what you're getting into.

Tips for Keeping your Voice Safe while using these techniques:

The major point for voice safety that I recommend, no matter what style you're singing, is: If your throat shows ANY sign of soreness, dryness, or fatigue, then STOP.
Don't use roughness to hide the fact that a note is above your range. I'm often tempted to do this, since if you choke the pitch so much that its not really even there, you can get away with singing 'higher'. I have no evidence to back up that its harmful, but all my instincts scream Don't do this!
Other things you should do are warm up properly before-hand, stay hydrated, and don't over-exert your voice.
Comment: Over the years, I've found many tips, from using mixed voice and getting the overdrive from headvoice, through using muscles you use when you bite, to focus on the overtones of the voice (rather than rushing for higher volumes).
Answer: I suppose the most obvious way to protect your voice is to sing normally and distort the signal. Run the signal through tube-style distortion and/or flange. Record it through taught shreds of wax paper ("kazoo"-it) or use a harmonica-mic. 8-bit mastering would mess-up some vocals nicely. Find some assembly code and play it back on the PC-speaker (not Audio Speakers, but the part that BEEPs!) and record that underwater. The possibilities are endless.
You can get acoustic "distortion" effects with suitably-tuned snare-drums, bottles, jugs, tile-bathroom-stalls.
Answering machines, really-old audio tape. Lo-fi lowers the nyquist limit, cutting-off upper frequencies, same as distortion cuts higher amplitudes.
Answer: I wonder why nobody brought it up yet, but The Zen of Screaming by Melissa Cross is probably THE resource on alternate vocal techniques (fry, death, heat and fire anyone?). With proper training it's not just on/off screams or singing - you can get exactly the rough tone that you want; even transitioning between clean and distorted sounds is not that hard if you know how to do it properly. I'm not a natural and it took a while to get to the point where I can adjust the grain in the singing voice consciously - but the DVDs are full of insight, not just for screaming but singing in general. I highly recommend them - they helped me a lot, I have a couple of other books on the topic but they just didn't click with me :-).
Hope that helps, happy screaming!
P.S.: as for the side effects, the way the techniques are tought take the whole topic of avoiding hurting your voice into full consideration; Melissa is very aware of the things that can happen to your voice if you're using it wrong
Answer: One trick is to summon up some phlegm/saliva in the back of your throat.
Then to approach a growl, tighten your throat enough that the airflow is affected by the phlegm, but not so tight as to cause pain.
Even with that technique, I wouldn't like to keep going for an hour-long performance. I don't know how the rock professionals do it.
Comment: The documentary said Andy Serkis used a honey/lemon concoxion to enable him to perform the Gollum voice during numerous rehearsals and takes.
Comment: When I do that, it always causes some throat pain and makes me lose my voice within a few minutes unless im well lubricated. It seems to me that rough should be easier than growling, no?


How to store my program's output into a file?

Question:     spykoni@spykoni-H81M-S2PV:~/Desktop/C_plus_plus/MIXMAX/mixmax_release_100_beta$
    spykoni@spykoni-H81M-S2PV:~/Desktop/C_plus_plus/MIXMAX/mixmax_release_100_beta$
    spykoni@spykoni-H81M-S2PV:~/Desktop/C_plus_plus/MIXMAX/mixmax_release_100_beta$
    spykoni@spykoni-H81M-S2PV:~/Desktop/C_plus_plus/MIXMAX/mixmax_release_100_beta$ cat screen.log
    Script started on Δευ 06 Απρ 2015 05:13:12 μμ EEST
    spykoni@spykoni-H81M-S2PV:~/Desktop/C_plus_plus/MIXMAX/mixmax_release_100_beta$ ./testU01
    Welcome to the MIXMAX random number generator!
    The curent matrix size is 256, with arithmetic  mod 2^61-1
special entry in the matrix is -1
    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                     Starting SmallCrush
                     Version: TestU01 1.2.3
    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

***********************************************************
    HOST = spykoni-H81M-S2PV, Linux

    float

    smarsa_BirthdaySpacings test:
-----------------------------------------------
       N =  1,  n = 5000000,  r =  0,    d = 1073741824,    t = 2,    p = 1

          Number of cells = d^t = 1152921504606846976
          Lambda = Poisson mean =      27.1051

    ----------------------------------------------------
    Total expected number = N*Lambda      :      27.11
    Total observed number                 :      23
    p-value of test                       :    0.75

    -----------------------------------------------
    CPU time used                    :  00:00:00.97

    Generator state:

I have a program in C++ , which I run in Linux , after running program it gives me a lot of information as an output, and I want to save this information in file in order to see all information later, because it's huge. I can save or let's say record all information from a screen in Linux. As I can see there are various ways to do it , but I exactly want to save information only the output of program. In this example I only want to save only since Starting SmallCrush , because my program prints information starting from there. I don't  want   """ /mixmax_release_100_beta$ cat screen.log
    Script started on Δευ 06 Απρ 2015 05:13:12 μμ EEST """      extra lines like this.
Answer: Running your program like:
$ ./testU01 | tee testU01.out

will show your program's output on stdout but also store it into file testU01.out.

Check man 1 tee for more information.
Comment: Thank you very much , it has worked, I was trying but with no result. And you just helped me in  a matter of second
Comment: @Narek : Np :) Mind to accept posts that answer your questions.
Comment: Sorry ,  I didn't understand you, as I am new in stackoverflow, can you explain what do you mean ?


How to choose between two models having similar validation score but different training score?

Question: I have trained two models, A and B. A has more parameters than B. Also A has higher training score than B. However both models have similar validation scores. Obviously model A overfits.
How do I choose between A and B?
What if A had better validation score, but the difference between training score and validation score were higher?
Comment: Are the training and validation scores cross validated? Why don't you have test dataset to have a test score?
Comment: They are not cross validated. I do have a test dataset but I am not sure if I should use the test score while selecting between two models. The test scores are similar to the validation scores.
Answer: Almost every model will have better training score than validation score. The purpose of validation score1 is to select which model performs the best on unseen data and that is probably the model which you want to use. If multiple models perform equally well on a validation set, then choosing the simplest one makes sense. To wrap it up:

How do I choose between A and B?

Use the simpler one (B).

What if A had better validation score, but the difference between training score and validation score were higher?

Use the better performing one (A).
Note aside: You should also consider performing a cross-validation; that way you obtain a mean validation score and its variance. If the model has slightly higher mean validation score but very high variance, you should perhaps choose the worse, but more stable model.

1 Sometimes the term validation score is reserved for hyperparameter tuning and early stopping in some models; then the term test score is used for model selection.


Solve differential equation $y''+y=\cos(2x)+\sin(2x)$

Question: I think my answer for this is incorrect, as "graphing" the equation in Desmos after finding $y$ does not show lines on the entire $x$ axis. Here is my approach. First, I need to solve
$$\lambda^2 + 1 = 0 \iff \lambda = \pm i \Rightarrow y_h = c_1\sin(x) + c_2\cos(x)$$
Then,
$$e^0(\cos(2x)+\sin(2x))=e^{\alpha x}(P(x)\cos(\beta x) + Q(x)\sin(\beta x)) \Rightarrow \\ \Rightarrow \alpha = 0, \beta = 2, P(x) = 1, Q(x) = 1 \Rightarrow \\ \Rightarrow y_p =A\cos(2x)+B\sin(2x) \Rightarrow y_p'' = -4A\cos(2x)-4B\sin(2x)$$
Thus,
$$y_p'' + y_p = \cos(2x)(-4A+A)+\sin(2x)(-4B+B) = \cos(2x) + \sin(2x),\ \forall x\in\mathbb{R} \Rightarrow \begin{cases}A = -\frac{1}{3} \newline B = -\frac{1}{3}\end{cases}$$
Finally, $y=c_1\cos(x)+c_2\sin(x)-\frac{1}{3}\cos(2x)-\frac{1}{3}\sin(2x)$. However, as I said, graphing this using Desmos displays distinct/discrete (not sure this is the correct term) solutions, which means the equation is not correct for all $x\in\mathbb{R}$. Where could my approach wrong?
Comment: Have you tried plugging in your proposed solution into the differential equation? This is often the easiest sanity check. Also: what exactly did you put into Desmos, and what did it produce?
Comment: @TheoBendit I have no clue why I didn't think of that! Thank you for the help, I now see that, in fact, I accidentally mistyped my equation into Desmos, which led to the wrong graph. Here's what I meant to put into Desmos and how it should look if it is correct (by which I mean that it should look strange because Desmos can't plot the whole plane): https://prnt.sc/dmmBQ9Hm_2NJ
Answer: I see that $$y^\prime(x)=-c_1 \sin(x)+c_2 \cos(x)+\frac{2}{3} \sin(2x)-\frac{2}{3} \cos(2x),\,\,x\in\mathbb{R}$$
as well as $$y^{\prime \prime}(x)=-c_1 \cos(x)-c_2 \sin(x)+\frac{4}{3}\cos(2x)+\frac{4}{3}\sin(2x),\,\,x\in\mathbb{R}.$$
Finally, $$y^{\prime \prime}(x)+y(x)=\cos(2x)+\sin(2x),\,\,x\in\mathbb{R}.$$
Nothing wrong.


Is it possible to do partial template rendering in Django?

Question: I wonder if it's possible to partial render Django template. Let me make it clear what I want, please check this out (this is in django shell python manage.py shell, not in basic python shell):
from django.template import Context, Template
t = Template('{{var1}} - {{var2}}, {% if var2 %} {{var3}} {% endif %}')
t.render(Context({'var1': 'test'}))

output:
'test - , '

But I wonder, if it's possible to render only passed variables, so my desired output is
'test - {{var2}}, {% if var2 %} {{var3}} {% endif %}'

I want to get it, because I didn't pass var2 and my main goal here is to render the template in few steps, not in one step. I know there is a string_if_invalid setting, but it's only for debug purpose.
Answer: This is is not possible out of the box. Evaluation of variables happens while rendering template nodes, so each template tag would have to support this.
For really simple templates, like {{var1}} - {{var2}}, you could create a custom Context subclass that returns {{ key }} for any missing variables. But this approach would not work as intended as soon as you use filters or use a variable in a tag, like in your example.


Can GET a method but POST doesn't work. Any ideas why the method POST isn't uses?

Question: from flask import Flask, render_template, url_for, request, redirect

app = Flask(__name__)

@app.route('/doborpompy', methods=['GET', 'POST'])
def doborpompy():

    if request.method == 'GET':
        return render_template('doborpompy.html')
    else:
        metry = 200
        if 'metry' in request.form:
            metry = request.form['metry']

        return render_template('doborpompy_wynik.html', metry=metry)

"GET /doborpompy%20method=?metry=44&metry_ogrzewane=44&ilosc_osob=44&typ_domu=pasywny&dofinansowanie=dofinansowanie&budget=standard&zrodlo=ogrzewanie_podlogowe&powietrze_woda=woda HTTP/1.1" 404 -

I can go for an option GET, but when I am trying to POST it still trying to do an GET option.
Any ideas?
Comment: The problem is with what `url_for("doborpompy")` is returning -- it's returning `/doborpomy method` instead of just `/doborpomy`
Comment: 404 means "that url was not found".  That log file shows that the requested url was `/doborpompy%20method`, not `/doborpompy`.
Comment: `method` is not passed as part of the url, as you seem to expect.
Comment: yes but why it's happend?
Answer: You are not handling the POST Action.
By default when you access the route, you are doing a GET Request, so you should handle the POST Like This:
from flask import Flask, render_template, url_for, request, redirect

app = Flask(__name__)

@app.route('/doborpompy', methods=['GET', 'POST'])
def doborpompy():

    if request.method == "POST":
        return "
This is how to handle post action in the if statement
"
        # rest of your code ...

    return render_template("doborpompy.html")

if __name__ == "__main__":
    app.run()

And you should also edit this line in your doborpompy.html file:
<form id="formularz_doboru" action="{{url_for("doborpompy")}}" method="POST">
to
<form id="formularz_doboru" action="{{url_for('doborpompy')}}" method="POST">
Comment: This seems irrelevant; `request.method` has a value; which one you check for with an explicit comparison shouldn't matter. The OP's request looks suspicious, with the endpoint containing a space.
Comment: Hey @chepner, I'm not sure about the 'endpoint containing a space'; I can't see or figure out what you're mentioning. Regarding `request.method`, what you are saying is correct. At least, I handle my routes like this myself in Flask.
Comment: I'm referring to the `/doborpompy%20method=?...`; `%20method=` appears to be on the wrong side of the `?` in the OP's question. I would expect the `method=` to be on the other side of the `?`.


Geometric Proof for the shortest path cube sides problem

Question: A spider in one edge of a cube (length of all side = $l$) wants to get to an insect on the other edge of the cube. obviously the spider cannot fly and must walk on the sides of the cube to get to the insects. Find the shortest path possible. (See the image below)

I know the differential approach to solve this question (optimization problem) and the path is drawn on the above picture. But I want a geometric proof without using derivative. Just using geometric theorems (like pythagoras) and using simple algebra.
Answer: HINT
Let consider the unfolded cube on the plane.


How to keep threads untangled when changing vector? c++

Question: This program will crash cause the threads are tangled... One could be pushing while the other is trying to erase.
How can I make this work?
#include <thread>
#include <vector>

using namespace std;

vector<int> v_test;

void push()
{
    v_test.push_back(0);
}

void erase()
{
    if (v_test.size() > 0)
    {
        v_test.erase(v_test.begin());
    }
}

int main()
{
    thread w0(push);
    thread w1(erase);

    while (true) { Sleep(1000); }
    return 0;
}

Comment: Threats don't get "tangled".   The operations they do can be unsequenced.   If you have two threads modifying a single object, then it is necessary to synchronise the operations to avoid concurrent access.   There are various ways of achieving that, such as mutexes (both threads lock the mutex before doing operations and release the mutexs when done -  if one thread has the mutex, other threads are forced to wait until the mutex is released).
Comment: `if one thread has the mutex` got it. Thank you!
Comment: The technical term for what you are calling "tangled threads" is **data race**.
Answer: You need to synchronize the threads so they coordinate their access to the vector. For example, by using a std::mutex, eg:
#include <thread>
#include <mutex>
#include <vector>
using namespace std;

vector<int> v_test;
mutex m_sync;

void push()
{
    lock_guard<mutex> lock(m_sync);
    v_test.push_back(0);
}

void erase()
{
    lock_guard<mutex> lock(m_sync);
    if (v_test.size() > 0)
    {
        v_test.erase(v_test.begin());
    }
}

int main()
{
    thread w0(push);
    thread w1(erase);

    while(true) {Sleep(1000);}
    return 0;
}

Comment: Since this is looking kind-of Producer-Consumer-y, [`std::condition_variable`](https://en.cppreference.com/w/cpp/thread/condition_variable) could be helpful as well.
Comment: I appreciate! Does this also work on detached threads?
And is `lock_guard` basically sleeping the function until it is allowed to run (in which case the other is sleeping)? Or is the lock on a flow basis, locking anything after it, and not the whole function?
Comment: @user19816087 yes, it works on detached threads, and yes, it only sleeps whichever function(s) are trying to get into the lock at that moment.


Arredondamento igual ao Excel - C# (ARREDONDAR.PARA.CIMA)

Question: Estou com o seguinte problema, no Excel, utilizando o valor 2.0001983727441233 e a função ARREDONDAR.PARA.CIMA com 2 casas decimais, esse valor passa para 2.01.
No entanto, no meu código já tentei várias formas de obter o mesmo resultado e nada.
Já tentei:

Math.Round - com várias casas decimais para testes);
Math.Round - com a propriedade MidpointRounding.AwayFromZero;
Math.Ceilling

E em nenhum dos casos eu consigo 2.01, apenas 2.00.
Alguém consegue me dizer como eu conseguiria o mesmo arredondamento do Excel? Ou se existe alguma biblioteca para tal? (Já fiz testes com algumas sem sucesso).
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: É só usar MidpointRounding.ToPositiveInfinity
Math.Round(number, 2, MidpointRounding.ToPositiveInfinity)

A documentação explica bem esse parâmetro e tem vários exemplos de quando usar cada valor de MidpointRounding
Outra opção é calcular "na mão", provavelmente não é necessário nada muito elaborado.
Console.WriteLine(Math.Ceiling(number * 100) / 100);

Veja ambos exemplos funcionando no Repl.it.
Comment: O "ToPositiveInfinity", não é nativo. No meu Round só aparece o MidpointRounding.AwayFromZero ou MidpointRounding.ToEven.
Comment: É nativo sim. Porém não existe no .NET Framework. Eu não tinha como adivinhar qual .NET está sendo usado.
Comment: Não estou usando o .NET Core... pelo que vi o "ToPositiveInfinity" só existe no CORE. Mas muito obrigada pela ajuda. De fato eu não expliquei no post.
Comment: De qualquer forma eu vou atualizar a resposta com a solução manual.
Comment: Jéf, muito obrigada. No entanto, essa opção do Math.Ceilling não funcionaria para um número diferente, por exemplo 2,0000000000001. Como o valor é resultado de uma conta... preciso procurar algo mais padronizado... semelhante o que o Excel faz com o ARREDONDAR.PARA.CIMA.
Comment: RESOLVIDO para toda a qualquer condição:

double a = valor;
string b = a.ToString(EN);
double c = Math.Round(Convert.ToDouble(b.Substring(0, b.IndexOf(".") + 3), EN) + (Convert.ToInt64(b.Substring(b.IndexOf(".") + 3)) > 0 ? 0.01 : 0), 2);

Testado e funcionando!
Comment: @LisaGuedes Tem que funcionar. Qual o resultado com `2,0000000000001`? Tratar números como string - ainda mais pra uma operação naturalmente matemática é geralmente uma má ideia.


saving programmatically without changing the author

Question: I made a script to change some node fields that is run by cron.
When it saves the nodes, the author changes and becomes "Anonymous".
Is there a way to save programmatically a node without changing its author?

Since you are asking the code, I suppose that my question is not clear.
It's not important what I change in the node. What I need is to leave the author as it is and not changing that to Anonymous.

Finally thanks to one comment I get that node_save() doesn't change the author. It should be something else. Thank you.
Comment: Post the code you're using.
Comment: It's very important to see your code. Using `node_save()` doesn't change the author so there must be something wrong with your code. Or if there isn't, there's something wrong elsewhere (which we're not going to be able to help without a lot more information about your site). But we do need to see your code. Please edit it into the question and flag for re-opening
Comment: thank you Clive, this is finally an answer. I did not know that node_save doesn't change the author...
Comment: Check that you are not calling node_submit($node) inside your script. This function could be the problem.
Answer: Saving the node using node_save() does not change the author.  Example:
$node = node_load($nid);

$node->field_xyz['und'][0]['value'] = 'your changes';
//make the changes to field
 node_save($node);

Comment: this is not an answer to my question...


solve $b^2c-a^2=d^3$ with some conditions.

Question: Solve $b^2 c-a^2=d^3$
Conditions
$b^2c>a^2$,  $b$>0, $c$>0,  $a$, $b$, $c$, $d$ are rational number.
Example Solution
$a=108$, $b=12$, $c=849$, $d=48$
Is Solving this equation impossible?
Comment: why do you want to consider such a general thing?
Comment: If it was impossible, then you wouldn't have found your example solution.
Comment: http://www.artofproblemsolving.com/community/c3046h1054060_cubes_with_squares
Answer: Note that any positive integer can be written in the form $b^2c$ - some in many ways. For example $7=1^2\times 7$; $36=1^2\times 36=2^2\times 9= 3^2\times 4=6^2\times 1$
So you can take any positive integers $a, d$ and write $a^2+d^3$ in this form. And that is without considering rational numbers (which you ought to be able to sort out by clearing denominators).
Answer: $c = \frac {d^3 + a^2}{b^2}$ solves your equation. Note that if $a, b$ and $d$ are rational, so is $c$.