The less I practice, the better I am...?

Question: Over the years I've noticed something very strange about myself.
I've noticed that if I practice, let's say scales, for little time maybe 5 minutes. If I were to keep going, I tend to just mess up more as I keep going opposed to when I started.
Then if I were to take a break and start again. I knock out the scales on the first try then start to decline again as I keep going just like before.
Everyone says practice makes perfect but with me it seems to be the complete opposite. Is there some kind of explanation to this phenomena? Because it really confuses me till this day and I noticed it years ago.
I play guitar.
Comment: Related: https://music.stackexchange.com/questions/4426/does-one-play-a-song-better-after-sleeping-on-it
Comment: Jeff Beck, apparently, never practices. The only time he plays a guitar is when he's performing or recording. Other than that, he never plays. So I would say you're sort of right in your idea.
Comment: "Everyone says practice makes perfect" - I believed this for a long time until someone pointed out that "practice makes permanent". It made me look at how I was practicing and helped me hugely.
Answer: I have 2 conflicting theories - either could be correct, with perhaps no way to know for certain.

You get bored & stop paying attention properly.
You're over-thinking & getting performance anxiety.

Without ever knowing which theory is correct, try instead playing along to something you like. Best test would be if you can find the live 20-minute version, rather than playing round & round the same 3-minute track.
See if you can improvise or play relevant scales for that entire 20 minutes, without getting worse. Chances are, the excitement in the track itself may keep your attention in the right zone.
Comment: @xR34P3Rx - _a different way to practice_ you should work hard to nail your scales. BUT - give yourself a reward when you're done: Play some songs that you enjoy, or just hang loose and play what you feel like. Practice your scales first and don't let yourself loose until you accomplish what you need to with your scales and other technical points and exercises: **Give yourself an incentive to do the grunt work - something to help you stay focused.** This works - at least for me.
Comment: Would sound like it proves to some extent that one of them may be on the right lines... though as I said, we may never know which ;)
Comment: Guess I should find a different way to practice then
Comment: I thought #2 would be a possibility too but when I play along with songs, I do get better. Which I guess would be because I'm playing something I like.
Comment: Another option, especially if the asker doesn't play much, is fatigue. In which case more practice is required to build endurance at which point this phenomenon will disappear over time.
Answer: Each of us has a most productive way of learning things - some see and do, others need to understand every nuance, others... and it's the same with practising to get those skills honed. No-one is born knowing these things, or how to do them effectively.
So, we have to experiment using loads of different strategies till we find one that suits us best. A great teacher will discuss options and possibilities, so cutting down on wasted time. Sounds like for you, short sharp bursts work better. Other players might need to sit for a whole hour, and go over and over a certain thing until they're happy with it. I may play something a hundred times, until I can't get it wrong, but that's me, and obviously isn't a good practice regime for you. Short bursts work, and maybe you could fit in 4 or 5 each day. Probably easier than trying to shoehorn an hours practice into a busy day, all at one sitting.
Practice may make perfect, but unless that practice itself is effective, it probably won't. And who says we all need to do 30 mins/ 1 hr./ 2hrs practice a day? Having said that, concert players might practise for 8hrs a day, and you'd think at that level, they'd be o.k. hardly doing any! Quite the opposite!
Answer: Tetsujin has already given a fine answer with two potential causes. A third possible cause might be muscle fatigue/cramping. When one plays with too much tension, the muscles fail to relax regularly, and they instead remain contracted for longer periods of time. This causes cramping/fatigue, which inhibits finger and arm movement. Taking a short break relieves that tension and allows the muscles to relax again, making one's playing more fluid and more effortless. This fits the description in your question: you've said it's easier to play immediately after taking a short break. But as you practice longer, the difficulty returns.
There are a lot of things that can cause one to play with too much tension: holding the pick incorrectly, leaning over too much, etc. (For more guidance on pitfalls to avoid, check out this video.) In general, the fingers are slightly curved when relaxed. There are a few different muscles that contract when the fingers straighten. Like Tetsujin said, without more information it'll be hard to know exactly what's happening in your case, but this could be another possible explanation.
Comment: I think I'm pretty good with my positions when it comes to holding the guitar and pick. Only thing is that normally people say that you should place your fingers in the fretboard at an angle so you have more control over them. 1) I used to play piano before this so my fingers can extend pretty wide as it is. 2) my hands are big to begin with so this "proper position" actually affects me. So depending on what I'm playing, my fingers are perpendicular to the fretboard. But I also keep them at an angle when I can.
Comment: @Stinkfoot, he says it's easier to play immediately after taking a break. But then it gets harder to play as he gets deeper into his practicing. This is characteristic of playing with too much tension. The muscles cramp up while playing and fail to relax. Short breaks relieve that tension and allow the muscles to relax again, which makes the playing easier and more fluid. That's all I meant by "muscle fatigue" (something short term). Feel free to suggest a different word.
Comment: @xR34P3Rx, that makes sense. This may not be the cause, but something to pay attention to is whether your fingers feel relaxed on the fretboard. As a test, perhaps place your hand on the fretboard in the most relaxed position possible, and then check to see if that's how you hold your fingers when playing. The fingers, when relaxed, have some curvature to them. Straightening the fingers requires a few different muscles to contract.
Comment: Muscle fatigue is generally noticeable - you feel it - but the question doesn't seem to reflect that.
Answer: If you're practicing scales primarily to advance to a higher degree of technical skill (speed, precision, note definition), perhaps to augment mastery of specific pieces or genres, I don't have any special advice (given all the advanced players out there).
If you're practicing scales as part of a larger goal of advancing your musicality, I suggest that as soon as you notice yourself getting sloppy, try to transition to a more of a composer/improviser mental state, and try to make up little melodies in the scale, making generous use of mixing long and short duration notes and pauses. So, less emphasis on muscle control, and more on "story-telling"; you may find you are internalizing the scales in ways that are surprising and satisfying.
Comment: Thanks! I actually was trying this earlier today while practicing
Comment: On http://www.banjohangout.org there's a group where we talk about practice techniques.  I've quoted part of this answer [there](https://www.banjohangout.org/group/thepracticegroup/blog/10541)
Answer: I have noticed the same kind of thing for me when I practice my scales, but I figure I should keep working towards being able to play through the scale as many times as I could, each time trying to achieve a higher number of accurate repetitions, in hopes of increasing my muscle memory and having my fingers land on the intended note every time without mistakes. However, extended periods of working on tedious things like scales can be counter productive, so I limit myself to about a 20 minute session and then take a break, or switch study topics to any thing more interesting.
Also I count my repetitions and I've noticed that things start to improve for me around the 25 mark, I just figure my brain is getting the message around this point, but that's just my thing.


Vocal range of songs

Question: I'm not aware that it's normal to include vocal ranges in songs' sheet music. The key and tempo are usually included, but, judging by the amount of 'what am I, tenor, baritone, etc' question on this site, I feel an included range of notes (or tessitura) would be invaluable.
Would it be a useful addition to songs for many (any) singers? It might help singers who know their  range, to be able to leave a song as is, or know where to modulate it to.
Comment: I guess what I don't understand is why "trawl through an entire song" isn't the first thing everyone does when they first look at a piece of music. Personally it takes me seconds to determine the range of a part that is 4 or fewer pages, as most songs seem to be.
Comment: I'm confused. "I'm not aware that it's normal to include vocal ranges in songs' sheet music." The range of every part, vocal or otherwise, **is** included in the sheet music for the part.
Comment: @ToddWilcoxthanks for the immediate dv! I meant that the range for the main vocal in a song could be included, without having to trawl through the entire song to find the highest/lowest notes. As in C3>F4. See Laurence's answer. Not difficult to understand.
Comment: @ToddWilcox  it's just not what I expect most people to do. Maybe, like you do, they do, but I've never noticed it. Sing through, and then decide it's out of range, yes.
Comment: Tim - please don't add an additional question into an already closed one. It would make it less suitable for reopening, as it would have multiple questions in one post.
Comment: @DoktorMayhem - I was asked to edit this question to be re-opened. I thought that's what I did, to elucidate on the original, which wasn't well understood. No point at all in adding any extra questions, as it seemed necessary to clarify the original better.
Comment: Any chance you can try and reword the question that already existed - it looked like the additional paragraph you added was a new question, so maybe just needs to be a bit clearer.
Answer: Well, as a classic 'opinion' question, I don't suppose this one will survive long!   But, yes, I think it could be useful.
It sometimes is/was done.  Particularly when a song was offered in a choice of keys for different voice types.  And it's common to give the range of each character in Music Theatre scores.
Comment: +1, and accepted. I do seem to remember, in the dim and distant past, songs having that note at the top of the song, but haven't seen it for decades. Just felt it might be a good idea again.

Vocal range of songs


Is the Serre spectral sequence a special case of the Leray spectral sequence?

Question: Let $F \to E \to B$ be a fibration with $B$ simply connected (more generally, such that $\pi_1(B)$ acts trivially on the homology of $F$). Then there is a Serre spectral sequence $H_p(B, H_q(F)) \to H_{p+q}(E)$.  One can do the same for singular cohomology. However, for reasonable spaces (specifically, locally contractible spaces, e.g. CW complexes), singular cohomology is the same as sheaf cohomology of the constant sheaf $\mathbb{Z}$.
But there is another spectral sequence for sheaf cohomology: the Leray spectral sequence. Given spaces $X, Y$ and $f: X \to Y$, and a sheaf $\mathcal{F}$ on $X$, there is a spectral sequence $H^p(Y, R^q_f(\mathcal{F})) \to H^{p+q}(X, \mathcal{F})$.
The Wikipedia article hints that the topological implications of this include in particular the Serre spectral sequence. I would be interested in this, because I like the machinery of the Grothendieck spectral sequence (from which the Leray spectral sequence easily follows), and would be curious if the Serre spectral sequence could be obtained as a corollary.
Is this possible?
Comment: @Akhil, Serre did precisely as you suspect. He looked at the Leray spectral sequence and applied it to a fibration over a CW complex, and noticed that it cleans up quite a bit in that situation.   If you read Serre's papers or Dieudonne's history you'll see this.
Comment: Tohoku is from 57, Serre's thesis from 51, and Leray's work predates that. The original arguments, Akhil, did not involve Grothendieck's s.s.
Comment: Akhil, as I said before, it follows from G's s.s. that a spectral sequence with the same initial term as Leray's exists. But a s.s. is much more than its initial term!
Comment: What happens if you try to check the hypotheses of the Grothendieck s.s. theorem in the case of the Serre s.s. for cohomology?
Comment: (By the way, note that even if using the Grothendieck s.s. you manage to get a s.s. whith $E_2$ term of the same shape as that of the Serre s.s., that is not enough (sadly!) to know that the s.s. you got is the same one as the one Serre got.)
Comment: @Ryan: Sure, I'll take a look at _Homologie des espaces fibres_ and see how it goes; thanks for the recommendation (the idea hadn't occurred to me).
Comment: @Mariano: Sure, but I just  like to think of the Leray SS as a special case of the Grothendieck SS, even if Leray's came before Grothendieck's.
Comment: *What* are you asking exactly? If Serre's ss is a corollary of Leray's, or if (both?) follow from Grothendieck's.
Comment: The former. Isn't Leray's a direct corollary of Grothendieck's? (Take the first functor to be the pushforward $f_*$ from $Sh(X) \to Sh(Y)$ and the second to be global sections. $f_*$ preserves flabbiness, so Grothendieck ss hypotheses apply.)
Comment: @Mariano: Good point. All I have ever seen used is the initial term and the existence of a product structure for the cohomology SS (which may be derivable in the Grothendieck case from cup-products).  I have so far been able to avoid thinking about the differentials (except in deducing what they are from $E_\infty$, e.g. if the fiber space is contractible), but I have not gotten very far in this subject.
Comment: I really would like to see an answer here which does not just say "it's obvious". After all, the Leray spectral sequence is *cohomological*. whereas the Serre spectral sequence has a *homological* (and a cohomological) version. How to deduce it?
Answer: Yes.  In fact, the result is basically obvious if you use Czech cohomology on the base.
Serre really had two key insights.  First, sheaf cohomology is a pain to compute, but if there is no fundamental group then for fiber bundles the Leray spectral sequence is really just using normal old-fashioned untwisted cohomology.  Second, you don't really need to work with fiber bundles -- all you need are Serre fibrations, and those are easy to construct.  In particular, you have the standard Serre fibration $\Omega X \rightarrow PX \rightarrow X$, where $\Omega X$ is the loop space of $X$ and $PX$ is the space of paths starting at the basepoint of $X$ and the map $PX \rightarrow X$ is "evaluation at the endpoint".  Clearly $PX$ is contractible!  An amazing amount of milage can be had from this silly observation!
Serre also really developed many of the key algebraic tricks one needs to work with spectral sequences.  For instance, he had the amazing idea that one can work modulo "Serre classes", and thus ignore things like torsion.  It's like pretending to localize spaces long before Sullivan and Quillen realized you could do so for real!
Comment: It is obvious if you use Czech cohomology -- I don't really think there is anything more one can say there.  Just write down the definition.  My guess is that he was confused by trying to do it using singular cohomology (or, worse, by thinking of sheaf cohomology using derived functors or some other such nonsense).  The rest of my answer is answering the the meta-question "Why does Serre get all the credit if all he did was construct a special case of something Leray had already done"?  But I'm on my 7th beer for the night, so I might be reading too much into the OP's question.
Comment: Your first paragraph answers the question by saying the answer is obvious! On the other hand, I don't see the connection of your second paragraph to the question.
Comment: @Mariano: historically the answer to the question is "tautologically yes".  Serre was interested in the Leray SS in the special case of a fibration.
Comment: @T_P: Thanks! Sorry, but I don't see why it is obvious. (For instance, I don't understand where the condition on the fundamental group pops in---there's nothing about that in the Leray SS a priori.) Also, what's wrong with looking at sheaf cohomology at a derived functor? In pathological cases (e.g. nonseparated schemes), there is no a priori reason to conclude that it will agree with Cech cohomology in dimensions >1. Though I am willing to believe that Cech cohomology is  equivalent in this case (since paracompact spaces, e.g. CW complexes, are OK).
Comment: @Akhil : What you have to prove is that your sheaf is really a constant sheaf in a strong sense.  Namely, not only does it give the same thing on all sufficiently small open sets, but it does so in a natural way.  At that point, you're just computing Czech cohomology with coefficients.  The fiber bundle condition shows that the sheaf gives the same thing on all sufficiently small open sets, and the fundamental group condition shows that there is no monodromy, so your identification of what the sheaf is is natural.
Comment: @Ryan, the history may be such (is, even!) but Akhil wants a proof not a story :)
Comment: I can't comment on the OP's question (I dont' have enough rep), so I'll comment here.  Mariano asked whether you actually get the same spectral sequence (not just the same E^2 page).  Well, here the literature is not in good shape.  There are SEVERAL different constructions of the Serre spectral sequence (via the Leray spectral sequence, via cubical cochains, via singular cochains, Dress's bisimplicial constuction, etc).  As far as I know, no one has bothered to prove that they give the same differentials, just that they have the same transgression and E^2 page. (continued)
Comment: (continued) It would be interesting to try to axiomatize the Serre spectral sequence and then prove some kind of uniqueness statement for it...
Comment: (There is a paper by Matthias Künzer where some useful comparisons are made, iirc.)
Comment: OK, here's what I do see. Cover the base $B$ by contractible nbds $U_\alpha$ and consider the preimages $p^{-1}(U_\alpha) \subset E$; these are fiber homotopy equivalent to $U_\alpha \times E$ by contractibility. So homology is the same. The Cech complex w.r.t. the cover $p^{-1}(U_\alpha)$ is *something like* the tensor product of the Cech complex of the covering $U_\alpha$ tensored with the Cech complex of $F$ (by the Kunneth formula?). So apply the SS for tensor products or something like that. I'm willing to buy this but will need to check some justifications for myself.
Comment: By the way, there is a version of the Serre spectral sequence with no fundamental group assumptions, but there you have to take twisted cohomology groups.  For these, I recommend either looking at the chapter in Hatcher or at the original paper (due to Steenrod I think -- Hatcher has a reference to it.  I remember it being very readable).
Comment: And I have no problem with computing sheaf cohomology with derived functors on weird spaces.  I have just seen too many young people learn the subject from Hartschorne and then be unable to work with easy situations like the one at hand, where Czech cohomology works nicely.
Comment: I just looked up the paper on cohomology with twisted coefficient systems.  It is indeed due to Steenrod, and it is called "Homology with local coefficients".  I also remembered that there is a (somewhat less well-written) account of this in McCleary's book on spectral sequences.
Comment: Dear @T_P: thanks! It looks like I'm going to have to learn more about algebraic topology (e.g. I don't know anything about local coefficients) before I can fully understand this answer, so I'll come back here later.
Answer: This is not intended to be an answer but rather a long comment.
First, on the question why does Serre take all the credit if his theorem is a particular case of Leray's?. Well, John McCleary says on page 139 of his book User's Guide to Spectral Sequences (2ed):

For the Cêch or Alexander-Spanier cohomology theories, the multiplicative structure is carried along transparently in the construction of the spectral sequence and so we get a spectral sequence of algebras directly with converges to $H^*(E;R)$ as an algebra.
The result for singular theory, however, is more difficult --- it is one of the technical triumphs of Serre's celebrated thesis.

And, as the same wiki page that the OP cites say:

Earlier (1948/9) the implications for fiber bundles were extracted in a form formally identical to that of the Serre spectral sequence, which makes no use of sheaves.
This treatment, however, applied to Alexander–Spanier cohomology with compact supports (....).
Jean-Pierre Serre, who needed a spectral sequence in homology that applied to path space fibrations, whose total spaces are almost never locally compact, thus was unable to use the original Leray spectral sequence (...).

On another topic, and as @T_P points out, Serre's original result does not impose any condition on the homotopy group of the base.
That assumption is added so that one can simply the $E_2$-term by getting rid of (co)homology with local coefficients.
Finally, I would like to say a few words about spectral sequences and their initial terms.
Apparently, there is a Grotehndieck's spectral sequence whose $E_2$-term is exactly as in Serre's, but the equality of both is questioned, since nothing is said about the differentials.
This is completely true.
However, there are (not a few) case where sheaf cohomology and singular cohomology provide the same result. Thus, one is found dealing with two spectral sequences which have the same initial term and the same limit.
This is still not enough to guarantee that both are the same spectral sequence in general.
However, for the particular case when one of them degenerates, so must the other; in this case both become eventually the same.
I know it is a very particular situation, but it is also one that becomes very handy sometimes.


Source code of default Android 4 Apps (Clock Alarm Timer)

Question: I can't find sources of android native apps for Android 4. I know about git hub repo but I have found only Alarm Clock app for Android 2. Please give me a link to source code of Clock app for Android 4.
I would be very grateful for any help.
Answer: I do not know what "Clock app for Android 4" means. There are two "clock" apps in the AOSP set of Git repositories, in terms of the project name having "clock" in it. DeskClock is tagged for Android 4.x, while AlarmClock is not.
Comment: Is it possible to use this Clock for user made applications. These UI elements are not available.
Comment: @Ranjith: The AOSP apps generally are not designed to be built as SDK apps. You are welcome to copy code from them subject to their license terms and attempt to modify them for your use.


Dynamically create multiple DirectShow virtual webcam devices

Question: I am trying to create a virtual webcam DirectShow filter with multiple virtual devices.
The cameras are defined as follows:
CFactoryTemplate g_Templates[] =
{
    {
        SUB_DEVICE_NAME_0,
        &CLSID_VirtualCam_0,
        CVCam::CreateInstance0,
        NULL,
        &AMSFilterVCam_0
    },
    {
        SUB_DEVICE_NAME_1,
        &CLSID_VirtualCam_1,
        CVCam::CreateInstance1,
        NULL,
        &AMSFilterVCam_1
    }
};

The initialization is done with these static methods:
CUnknown * WINAPI CVCam::CreateInstance0(LPUNKNOWN lpunk, HRESULT *phr)
{
    return new CVCam(NAME(DEVICE_NAME_0), lpunk, phr, CLSID_VirtualCam_0, 0);
}

CUnknown * WINAPI CVCam::CreateInstance1(LPUNKNOWN lpunk, HRESULT *phr)
{
    return new CVCam(NAME(DEVICE_NAME_1), lpunk, phr, CLSID_VirtualCam_1, 1);
}

Is it possible to do this more dynamically so that we do not have to hard code each camera but can pass a parameter during runtime?
Regards,
Answer: Dynamic addition and removal of the camera is possible. However it is quite different from what you though of in the body of the question. DirectShow BaseClasses offer you certain helpers to convert static declarations into registration and DirectShow sample code shows how DLL exports are connected to these helpers for registration needs.
To make it dynamic you need to expand what AMoveDllRegisterServer2 does for most of filter projects and adapt its implementation for your needs.
This part of RegisterFilters might be a good starting point, you would want to make it a loop or something. You will have to deal with additional fm->RegisterFilter(... calls respectively to additional virtual cameras you want.
Comment: Thanks for your reply. The example you linked also creates the ``CSource`` (``CVCam::CreateInstance``) as shown in my code example above.


Which Email Server Expands the Recipient List into Many Emails?

Question: When sending a message via a different SMTP outbound gateway, will a message containing multiple recipients in the BCC field be broken up into many messages by the originating server, or the server that is responsible for eventually sending the messages? For example, if I use Google but relay a 10-recipient message to another server over SMTP, does Google create 10 messages and send them via SMTP, or does the other server turn the original message into the 10 separate messages?
BACKGROUND: Using Google Apps for Work. We sometimes want to send emails to a large number of people at once, but would hit Google's sending limits.
We are considering using something like MailGun, which we can connect to via SMTP, to handle sending out mailing lists of up to 1000 recipients. Google Apps allows us to setup outbound gateways, but they also have limits.
I'm hoping that if we have an email with 1000 recipients in the BCC list, and relay it to MailGun, that Google will consider it as 1 email, and MailGun will have to do the "conversion" into 1000 actual email messages.
Comment: Why the downvote?!? L'il help?
Comment: Mouse over the down arrow; the popup says "*This question does not show any research effort; it is unclear or not useful*".  Downvotes without comment may be presumed to be for at least one of those reasons.
Answer: The RFCs generally recommend a limit of 100 recipient addresses per message.  The mail server may expand this list if a recipient is a list known to the server.  This applies to the envelope recipients, not the recipients listed on the header.
For a mailing lists, it is bad practice to list the recipients unless the message is being sent to a single user, and that is the only recipient listed.
Mail servers may list multiple recipients in the same domain when sending a message.  Some or all of these may be rejected by the receiving server.
Setting up a list on your mail server will allow you to sent to and address the list address, and have that expanded by the client.  Your client lists should not be accessible from the internet.
Comment: Find and read the RFCs. They describe the process.  Also check http://www.systemajik.com/blog/running-an-email-server/
Comment: I appreciate this input, and apologize for my ignorance in this area. I don't know what envelope vs. header recipients are. And I'm not really sure how having lists "expanded by the client" would help here. You've given me some starting insight into email, but I'm not sure how this addresses the question. Is my question just a really bad one?
Comment: Like a paper letter, there are two parts the message and the envelope.  The message has headers like Subject. From:,To:, Sender:, CC:, etc.  Delivery does not depend on these headers, although the client will use the contents of the addressing header when submitting.  These will be copied to the envelope which is used for delivery.
Comment: OK, that's a good explanation--by client do you mean the mail app on my phone or do you mean the sending server? And further to addressing, does this mean that if the message header has multiple addresses, that multiple envelopes are created? Like, before the message is sent over SMTP relay?
Comment: By client I mean the mail app on your phone, or any other program you use to compose and send email.  As the message is delivered the envelope changes.  Your mail server will have all delivery addresses on its envelope.  When it connects to another server, it will only add address for which that server is responsible.
Comment: OK, that makes sense. But if my mail server is passing the message on via SMTP relay, does it just hand over an envelope containing all of the header addresses, or does split the message up into a bunch of envelopes for each recipient and then relay these over SMTP? Btw I'm sorry if this is an idiotic question I just really don't understand when in the process each step happens.


Views: Limit amount of a node type by percentage

Question: I have a view showing nodes of two different types sorted by date.
I want to limit the maximum number of nodes shown of the one type by, say, 25% percent of the total nodes per page.
How would I go about that?
Comment: What should happen to nodes that aren't displayed on for example the first page? Should they be displayed on the second page or left out completely?
Comment: Do you have a limit on the number of items being displayed in the view?
Comment: Yes. Say the view is limited to 4 nodes, I want maximum  25%/one of them to be of a certain type.
Comment: Do the results need to be displayed in a single sorted list?
Comment: Good point @zwirbeltier it looks like the only way of doing this is a bit of a template hack, but if you are setting up a display like this you must know you can't have pagination.
Comment: I think there might be a way to achieve this directly by using a per-type counter for the nodes. But it goes far beyond what views can do on its own.
Answer: This might be a job for _views_pre_render().  In it, you can go through your views results and modify them to your module's content.  The issue here is creating a view result big enough to make your percentages work. For example, let's say you want to have that view of 4 nodes, but only 1 of which is of a certain type.  Since you are sorting by date, if the first 4 are all of that type, you grab one but need to keep looking for 3 of the other type.
In a dull ax approach, you could, though, create a view that returned 100, or however many is reasonable on your site based upon what you actually see re mix of nodes, of both types sorted by date and then do something like:
function YOURMODULE_views_pre_render(&$view) {

  if ($view->name=='NAMEOFTHEVIEW') {

    //  drupal_set_message('
' . print_r($view->result[0], true) . '
'); // just the first row
    //  drupal_set_message('
' . print_r($view->result, true) . '
');    // all of them

    $max=1;    // hardcoded for example purposes
    $total=4;  // hardcoded for example purposes

    $new_result=array();

    foreach ($view->result as $result) {

      if ($max && $result->FIELDTHATHASTHENODETYPEINIT==NODETYPEWEARELOOKINGFOR) {
        $new_result[]=$result;
        $max--; $total--;
      } elseif (--$total) {
        $new_result[]=$result;
      }

    }

    $view->result=$new_result;

  }

  // any other views_pre_render()ing here

}

which if my logic gene is in gear today will cycle through your view results and pick out at most $max nodes of one type and then fill up $new_results up to $total with the rest of the view results and then replace the results of the view with that.
The issue, again, is that if all the results are of one node type, or there aren't enough of the other node type to fill up $new_result, you will have less than $total results returned.
(One or both of the drupal_set_message()s will/might be helpful for figuring out FIELDTHATHASTHENODETYPEINIT.  If there isn't one in your view already, you can put one in and then not display/hide it if necessary.)
Comment: I love hook_views_pre_render, and at first I even thought this would be the right approach. On a second thought however, the issue with the pre render hook is that you are altering the result set after the fact - after the fact that the results have been returned from the database. The user's date sort means that you could potentially end up with 4 nodes of only one type in the result set, while there are still nodes of the other type that could potentially be returned in the result set. What then? At that point the 25% node type constraint is out of the window.
Comment: BTW, I would not guarantee a perfect response to that question. When it comes to relatively close answers (those that might require the user to alter some of his requirements), I think this answer is a good starting point, +1 for that. Also [`hook_views_query_alter`](http://api.drupal.org/api/views/views.api.php/function/hook_views_query_alter/7) might be another good starting point.
Comment: I think I addressed your first comment's point about 4 nodes of only one type by artificially inflating the number of nodes returned by the view.  Dull ax I know but allows for one view and some reasonable sorting to occur.
Comment: I agree that this dull ax provides a reasonable sorting (and 1+'d for that). That it will meet the user's hard requirements, that's a completely different subject ;)
Answer: A simple way will be to:

create a view that will show X amount of 1 type of nodes that is equivalent to the 25% of the total nodes you want to display.
Then add an attachment (not EVA) view and attach it after the first one, but overwrite the filter indicating the content type selected for the attachment view only.
Repeat the step 2 as many times as needed to show the 100% of the total nodes from 25% of different content types.

Note: if you add footer and header HTML or text to the main view when adding the attachment view they will be copy over, but you can overwrite them so they will not show.
End result width a limit of 4 node will be like:

Node title (content type A) {main view}
Node title (content type B) {attachment view 1 => attached after main view}
Node title (content type C) {attachment view 2 => attached after attachment view 1}
Node title (content type D) {attachment view 3 => attached after attachment view 2}

Thank you.
Comment: Are these views appended to one another or merged together?  Will sorting by date as a single list be an option?
Comment: At the end it is going to look like a single list I can see an issue with the day sorting. They will be sorting by day, but the sort order will not look right
Comment: This seems like it's on the right track.  I'm sure there is a way to do this with views, but you could throw all the values into an array, sort and re-display as a single list.  I didn't realize views had the attachment feature.  Way cool. :)
Comment: Just an idea after you do the view with the attachments as I recommended you might be able to sort properly by date by creating a template (tpl.php) file for the view and before printing it sort the results by the date field.
Comment: @redhatlab I would have initially done it by creating two views and merging the results at template level. I may be wrong but I would prefer to keep the logic out of the template so _views_pre_render might be better method.


Determine whether $U$ is a subspace of $\mathbb{R}^3$

Question: Determine whether $U$ is a subspace of $\mathbb{R}^3$
$$U = \{(r, s, t) \mid r, s, \text{ and }t \in \mathbb{R}, −r + 3s + 2t = 0\}.$$
I have never seen such a question how would i prove this?
Comment: When is your homework due? Do you have other subjects too?
Comment: Hint: Prove that it is a subset of $\mathbb{R}^3$ and that it's a subspace (Closed under addition and scalar multiplication)
Answer: HINT
$V \subseteq \mathbb{R}^n$ is a subspace if

$\vec{0} \in V$
$V$ is closed under addition and constant multiplication; i.e. if $\vec{v},\vec{w} \in V$ and $a,b \in \mathbb{R}$ then $a\vec{v} + b \vec{w} \in V$.

Can you prove both?
UPDATE
Let $a,b \in \mathbb{R}$ and $\vec{v}, \vec{w} \in U$. Then there exist $s,t,S,T \in \mathbb{R}$ such that
$$
\vec{v} = \begin{pmatrix} 2s+2t \\ s \\ t \end{pmatrix}\\
\vec{w} = \begin{pmatrix} 2S+2T \\ S \\ T \end{pmatrix}
$$
So let $\vec{u} = a\vec{v} + b\vec{w}$. Can you find the correct values for $s,t$ to show $\vec{u} \in U$ as well?
Comment: How exactly would you prove 2?
Comment: @Micky see update
Answer: Hint:
$$
-r+3s+2t=0
$$
is a plane, so it's a subspace of $\mathbb{R}^3$.
Answer: First, prove that (0,0,0) is an solution to the equation:
−r+3s+2t=0
-0+3.0+2.0=0
0=0 (true)
And than, prove that if (a,b,c) and (d,e,f) are solutions to the equation, m.(a,b,c) + n.(d,e,f) must to be a solution too (m and n real numbers):
(a,b,c) is a solution, so:
−r+3s+2t=0
-a+3b+2c=0 (i)
(d,e,f) is a solution, so:
−r+3s+2t=0
-d+3e+2f=0 (ii)
Well, note that if (i) and (ii) are true (and they are), (iii) and (iv) will be too:
-a+3b+2c=0 (i)
m.(-a+3b+2c)=m.0
m.(-a+3b+2c)=0 (iii)
and:
-d+3e+2f=0 (ii)
n.(-d+3e+2f)=n.0 (ii)
n.(-d+3e+2f)=0(iv)
Finally, (iii)+(iv) is true too:
m.(-a+3b+2c)=0 (iii)
+
n.(-d+3e+2f)=0(iv)
=
m.(-a+3b+2c) + n.(-d+3e+2f)=0+0 (iii)+(iv)
m.(-a+3b+2c) + n.(-d+3e+2f)=0 (iii)+(iv)
So, m.(a,b,c) + n.(d,e,f) is a solution too!
Comment: Welcome to the site. We generally try not to solve the homework problems for people completely without them doing something to complete it...
Comment: Sorry, i didn't know it. Tks
Comment: No problem, I upvoted your answer. It will do you good to typeset your answers in MathJax, they are much easier to read then. You can learn to do this here: http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference


str_replace is replacing all but 1 section of my string correctly.

Question: My original string looks like this

value='' tabindex='500'

I would like to replace the string with this

value='Email:' tabindex='500' onclick=\"if (this.value=='Email:') {this.value='';}

So I use this str_replace function
$userForm = str_replace("value='' tabindex='500'", "value='Email:' tabindex='500' onclick=\"if (this.value=='Email:') {this.value='';}\"",$userForm);

My output ends up being this
value="" tabindex="500" onfocus=" if (this.value == '') { this.value = ''; }"

If you notice, everything except for the parts that include 'value="Email:" are replaced correctly...
I was hoping someone might have an idea on why this is happening? Any help would be greatly appreciated. Thank you in advance!
Comment: You can use the `placeholder` attribute in html and it does basically the same thing you're trying to do with javascript (i.e. show 'Email:' on input field and automatically erase as user begins to type). I haven't seen someone try to do what you're doing here in javascript in over 6 years.
Answer: You may be looking for something like:
$userForm = preg_replace('/value=\'\' tabindex=\'(.*?)\'/i', 'value=\'Email:\' tabindex=\'$1\' onclick="if (this.value==\'Email:\') {this.value=\'\';}', $userForm);

Result:
value='Email:' tabindex='500' onclick="if (this.value=='Email:') {this.value='';}

preg_replace
Comment: I'm not saying your answer is wrong, on the contrary. But OP question was *I was hoping someone might have an idea on why this is happening?* and I legitimately am curious about its reasons. Do you know anything about it?
Answer: You can use below codes:
$val = "value='' tabindex='500'";

$result = str_replace( "value='' tabindex='500'", "value='Email:' tabindex='500' onclick=" . '\"if' . " (this.value=='Email:') {this.value='';}", $val );

echo $result;

Comment: ... which is essentially the **exact same code** OP used and claimed to be failing, except that you didn't escaped the last double quote (actually you deleted it)
Comment: but I got this result after running: `value='Email:' tabindex='500' onclick="if (this.value=='Email:') {this.value='';}`
Comment: Without the trailing double quote.
Comment: There is ***still*** no difference. Can you explain exactly *what* did you fix in OP code?
Answer: Something is missing here, copying your code right off:
<?php

$userForm = "value='' tabindex='500'";

var_dump($userForm);

echo '

';

$userForm = str_replace("value='' tabindex='500'", "value='Email:' tabindex='500' onclick=\"if (this.value=='Email:') {this.value='';}\"",$userForm);

var_dump($userForm);

I end up with the following result:
value='Email:' tabindex='500' onclick="if (this.value=='Email:') {this.value='';}"

which seems to be the results you are looking for. Do you alter the variable anywhere else?


How to apply Cochran-Armitage trend test in R

Question: I'm working on a publication examining rising authorship of minorities for certain articles. There is a clear increasing trend, but I wanted to apply some statistical rigor. My data frame is simple: Years, and % minority authorship. However, Cochran-Armitage input dataframe doesn't make sense in my context. Am I using the right test?
I have perfected the dataframe and prepared it by producing the number of years on the x-axis, and the % minority authorship on the y-axis. essentially 1 row, and 10 columns (each column representing one year). However, cochran-armitage cannot accept 1 row dataframes
my dataframe exists as so
year 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
race 11.1 12.1 14.2 15.2 19.2 20.5 21.8 27.9 30.1 31.1
Comment: According to wikipedia, Cochrane Armitage is for association between a variable with 2 categories and an ordinal variable with K categories. I would say wrong test. What about simple linear regression? (take the % as the Y axis value...)
Comment: You are analyzing percentages as the outcome, so it's by definition not going to be normally distributed. Beta regression is more likely to meet the distribution of percentages because beta distributions have bounds of 0 and 1.
Comment: I can create an additional category that is essentially the compliment of what I have there. Interprested as non-minority (i.e. a 1 - value). This is a similar paper that used it https://www.thespinejournalonline.com/article/S1529-9430(17)30315-7/fulltext. Can I use a linear regression to imply an increasing trend? Is a simple linear regression appropriate in this situation?
Comment: I would say yes, the trend is pretty strong. You don't have a lot of points, but it seems to be significant. I'll put this into an answer...
Comment: With regards the paper you linked - the Cochrane Armitage is more appropriate there as they have 2 categories (female/male) and an ordinal with k variables (first, middle, last). That's why they can apply the test in their situation, in yours you have 2 categories, but no ordinal variables.
Comment: Why would first middle and last be the ordinal? If we want to argue a trend in successive fashion, wouldnt we use year?
Comment: see section on ordinal variables [here](https://stats.idre.ucla.edu/other/mult-pkg/whatstat/what-is-the-difference-between-categorical-ordinal-and-interval-variables/).  Year could be considered ordinal too, though I would consider it continuous variable rather than ordinal normally.
Answer: The Cochrane Armitage is likely to be the wrong test, it is for association between a variable with 2 categories and an ordinal variable with K categories. You have two variables each with one category.
I think a simple linear regression would work. In fact, when you run one on the data you provided (you are missing the % for 2018, so I removed that row), this is what you get:
> summary(y_p)

Call:
lm(formula = year ~ percent, data = y_p)

Residuals:
 Min       1Q   Median       3Q      Max
-0.77079 -0.38560 -0.03582  0.35535  0.90139

Coefficients:
         Estimate Std. Error t value Pr(>|t|)
(Intercept) 2.004e+03  5.428e-01 3692.52  < 2e-16 ***
percent     4.045e-01  2.526e-02   16.01 2.32e-07 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.5586 on 8 degrees of freedom
Multiple R-squared:  0.9697,    Adjusted R-squared:  0.966
F-statistic: 256.4 on 1 and 8 DF,  p-value: 2.319e-07

This looks fairly significant to me, but you would need to check the residuals etc to be sure.
Comment: Just because you don't get an error does not provide assurance that your statistical analysis is correct.
Comment: I am aware of that, but I'm not statistician by any means. Your comment regarding B-regression looks like the best solution to OP's problem


Disaster Recovery: PXE boot Windows Server 2019 from ISO

Question: I have a dedicated physical Windows Server 2019 on the Ionos cloud platform. I need to implement a disaster recovery plan. I also have added a shared storage block on another Ionos server and mapped the shared storage segment as a network drive on the dedicated server. I created a bootable media ISO file and a bare metal backup file, and saved both of these to a folder on the shared storage segment. The shared storage segment is assignable to multiple servers, so in case of disaster I would have access to the ISO file and bare metal backup from the new server. Ionos will not provide the service of inserting a USB drive in a new server in order to boot from it, and the server does not permit iLO nor iDRAC IPMI access. I am looking for a way to remotely boot from the ISO boot media and then have access to the ISO-booted server in order to do the next step of restoring the bare metal backup file to the new server. Is there any way to do this?
Answer: If the iso contains a Windows pe environment, then you can start that using iPXE and Wimboot.
To access the rest of the iso contents you need to do a separate mount when inside winpe.
Another alternative is to make the iso available over iSCSI and again use iPXE to boot that iSCSI device. This requires that the OS on the ISO is iSCSI + BFT aware, and that it has drivers for the NIC.
Even if you could load the iso into memory during PXE stage, access to that data becomes unavailable unless the OS itself knows how to access that data.
Comment: What's the best way to create an ISO boot disk that meets either your first sentence's requirements or your second?
Comment: What OS should be on the disk? Or rather what OS is needed to do the recovery? Best is to not use ISO at all.
Comment: I don't know - I'm a newbie to BMR. I'd like to engage the services of an expert in this area, for a fee.


NumPy or SciPy to calculate weighted median

Question: I'm trying to automate a process that JMP does (Analyze->Distribution, entering column A as the "Y value", using subsequent columns as the "weight" value).  In JMP you have to do this one column at a time - I'd like to use Python to loop through all of the columns and create an array showing, say, the median of each column.
For example, if the mass array is [0, 10, 20, 30], and the weight array for column 1 is [30, 191, 9, 0], the weighted median of the mass array should be 10.  However, I'm not sure how to arrive at this answer.
So far I've

imported the csv showing the weights as an array, masking values of 0, and
created an array of the "Y value" the same shape and size as the weights array (113x32).  I'm not entirely sure I need to do this, but thought it would be easier than a for loop for the purpose of weighting.

I'm not sure exactly where to go from here.  Basically the "Y value" is a range of masses, and all of the columns in the array represent the number of data points found for each mass.  I need to find the median mass, based on the frequency with which they were reported.
I'm not an expert in Python or statistics, so if I've omitted any details that would be useful let me know!
Update:  here's some code for what I've done so far:
#Boilerplate & Import files
import csv
import scipy as sp
from scipy import stats
from scipy.stats import norm
import numpy as np
from numpy import genfromtxt
import pandas as pd
import matplotlib.pyplot as plt

inputFile = '/Users/cl/prov.csv'
origArray = genfromtxt(inputFile, delimiter = ",")
nArray = np.array(origArray)
dimensions = nArray.shape
shape = np.asarray(dimensions)

#Mask values ==0
maTest = np.ma.masked_equal(nArray,0)

#Create array of masses the same shape as the weights (nArray)
fieldLength = shape[0]
rowLength = shape[1]

for i in range (rowLength):
    createArr = np.arange(0, fieldLength*10, 10)
    nCreateArr = np.array(createArr)
    massArr.append(nCreateArr)
    nCreateArr = np.array(massArr)
nmassArr = nCreateArr.transpose()

Comment: Some example input\output data would be helpful, also try to show the code for how far you've come so far.
Answer: Since this is the top hit on Google for weighted median in NumPy, I will add my minimal function to select the weighted median from two arrays without changing their contents, and with no assumptions about the order of the values (on the off-chance that anyone else comes here looking for a quick recipe for the same exact pre-conditions).
def weighted_median(values, weights):
    i = np.argsort(values)
    c = np.cumsum(weights[i])
    return values[i[np.searchsorted(c, 0.5 * c[-1])]]

Using argsort lets us maintain the alignment between the two arrays without changing or copying their content. It should be straight-forward to extend it to an arbitrary number of arbitrary quantiles.
Update
Since it may not be fully obvious at first blush exactly how easy it is to extend to arbitrary quantiles, here is the code:
def weighted_quantiles(values, weights, quantiles=0.5):
    i = np.argsort(values)
    c = np.cumsum(weights[i])
    return values[i[np.searchsorted(c, np.array(quantiles) * c[-1])]]

This defaults to median, but you can pass in any quantile, or a list of quantiles. The return type is equivalent to what you pass in as quantiles, with lists promoted to NumPy arrays. With enough uniformly distributed values, you can indeed approximate the input poorly:
>>> weighted_quantiles(np.random.rand(10000), np.random.rand(10000), [0.01, 0.05, 0.25, 0.50, 0.75, 0.95, 0.99])
array([0.01235101, 0.05341077, 0.25355715, 0.50678338, 0.75697424,0.94962936, 0.98980785])
>>> weighted_quantiles(np.random.rand(10000), np.random.rand(10000), 0.5)
0.5036283072043176
>>> weighted_quantiles(np.random.rand(10000), np.random.rand(10000), [0.5])
array([0.49851076])

Update 2
In small data sets where the median/quantile is not actually observed, it may be important to be able to interpolate a point between two observations. This can be fairly easily added by calculating the mid point between two values in the case where the weight mass is equally (or quantile/1-quantile) divided between them. Due to the need for a conditional, this function always returns a NumPy array, even when quantiles is a single scalar. The inputs also need to be NumPy arrays now (except quantiles that may still be a single number).
def weighted_quantiles_interpolate(values, weights, quantiles=0.5):
    i = np.argsort(values)
    c = np.cumsum(weights[i])
    q = np.searchsorted(c, quantiles * c[-1])
    return np.where(c[q]/c[-1] == quantiles, 0.5 * (values[i[q]] + values[i[q+1]]), values[i[q]])

This function will fail with arrays smaller than 2 (the original would handle non-empty arrays).
>>> weighted_quantiles_interpolate(np.array([2, 1]), np.array([1, 1]), 0.5)
array(1.5)

Note that this extension is fairly unlikely to be needed when working with actual data sets where we typically have (a) large data sets, and (b) real-valued weights that make the odds of ending up exactly at a quantile edge very long, and probably due to rounding errors when it does happen. Including it for completeness nonetheless.
Comment: @Mahé It is actually a fairly small update, so enjoy the minor extension :-)
Comment: @Mahé Awesome, the more the merrier! :-) running timeit with larger datasets (10k random numbers) and more quantiles gives a slight advantage to my implementation (on my computer), which just goes to show how important it is to profile your own specific use case!
Comment: It is probably OK for large samples, but not quite accurate for small samples. `weighted_median([1, 2, 3, 4], [1, 1, 1, 1]) == 2`  instead of the correct value `2.5`.
Looking at the wquantiles module provided above, to have centered value you need to:
1) use `np.interp` instead of `np.searchsorted`
2) retrieve half a weight to the cumulative weight
Comment: But to be fair, as I was trying to reproduce the results of [this paper](https://agupubs.onlinelibrary.wiley.com/doi/full/10.1029/2021JB022355), your function worked like a charm (suggesting that correct or not -- and probably correctly, the authors of that scientific paper used a similar formulation as yours)
Comment: PS: they cited http://mitpress.mit.edu/9780262046305/introduction-to-algorithms/ as reference
Comment: @Mahé That is correct, there is no interpolation in the case where the median is not observed. I'll have a think about whether it would still be a minimal solution with eg. linear interpolation, or if that's the point where you're better off adding in a dependency on a third-party library. I'll update the answer to make this precondition explicit though, thanks!
Comment: Sounds good. I also posted my own, for completeness, as a synthesis between your original approach and @muzzle's wquantlies function. I find it more convenient to have one function, but that is a matter of preference. I recommend the use of np.interp, which is clearer and faster (I assume np.where consumes up the time).
Answer: What we can do, if i understood your problem correctly. Is to sum up the observations, dividing by 2 would give us the observation number corresponding to the median. From there we need to figure out what observation this number was.
One trick here, is to calculate the observation sums with np.cumsum. Which gives us a running cumulative sum.
Example:
np.cumsum([1,2,3,4]) ->  [ 1,  3,  6, 10]
Each element is the sum of all previously elements and itself. We have 10 observations here. so the mean would be the 5th observation. (We get 5 by dividing the last element by 2).
Now looking at the cumsum result, we can easily see that that must be the observation between the second and third elements (observation 3 and 6).
So all we need to do, is figure out the index of where the median (5) will fit.
np.searchsorted does exactly what we need. It will find the index to insert an elements into an array, so that it stays sorted.
The code to do it like so:
import numpy as np
#my test data
freq_count = np.array([[30, 191, 9, 0], [10, 20, 300, 10], [10,20,30,40], [100,10,10,10], [1,1,1,100]])

c = np.cumsum(freq_count, axis=1)
indices = [np.searchsorted(row, row[-1]/2.0) for row in c]
masses = [i * 10 for i in indices] #Correct if the masses are indeed 0, 10, 20,...

#This is just for explanation.
print "median masses is:",  masses
print freq_count
print np.hstack((c, c[:, -1, np.newaxis]/2.0))

Output will be:
median masses is: [10 20 20  0 30]
[[ 30 191   9   0]  <- The test data
 [ 10  20 300  10]
 [ 10  20  30  40]
 [100  10  10  10]
 [  1   1   1 100]]
[[  30.   221.   230.   230.   115. ]  <- cumsum results with median added to the end.
 [  10.    30.   330.   340.   170. ]     you can see from this where they fit in.
 [  10.    30.    60.   100.    50. ]
 [ 100.   110.   120.   130.    65. ]
 [   1.     2.     3.   103.    51.5]]

Comment: Thanks so much for your explanation!  I'm getting close but am not quite there yet.  I don't think I articulated my problem quite right - basically, the median should always be a number within the range of masses - the frequencies of [30, 191, 9, 0] correspond with masses [0, 10, 20, 30], respectively (i.e. mass in range 0-10 showed up 30 times, mass of 10-20 showed up 191 times, etc.).  With your answer above it looks like I'm getting the median of the frequency count instead, right?
Comment: Yes, it finds the median of the frequency count, and then relates that to the masses. Using that the ranges of masses are directly related to the elements of the frequency count. Do you need it to figure out the true median or the range that contains the median? This will find the range containing the median.
Comment: Could you try to either give more example of inputs, outputs. Or check the "test data" i used and say what the output should be for them.
Comment: Ideally I'd find the true median, but the range would also be fine.  using your test data, I found medians of [20, 25, 25, 25, 25], respectively.  Here's some actual data [30, 191, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 99, 256, 254, 82, 5, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 65, 205, 189, 249, 120, 72, 40, 2, 0, 0, 0], [0, 0, 0, 0, 0, 1, 59, 192, 324, 204, 188, 127, 104, 29].  These correspond with masses from 0-130, counting by 10s.  The medians using JMP:  [10, 30, 65, 90].
Comment: The medians using your edits are [125.5, 348, 471, and 614].  This looks like it's getting there - they're getting consecutively larger, which follows the same pattern as JMP.  I'll tinker around with it to see if there's a small tweak that will get it the rest of the way, but would appreciate any more input you've got!  At a glance it may be something with the indices formula - instead of 0-130 by 10's, I'm getting 0, 10, 50, 80 as the output (after modifying it to (i-1)*10 to start at 0).
Answer: wquantiles is a small python package that will do exactly what you need. It just uses np.cumsum() and np.interp() under the hood.
Comment: I've had a proper implementation of weighted introselect on my back burner for a couple of years now :(
Answer: I ended up writing that function based on @muzzle and @maesers replies:
def weighted_quantiles(values, weights, quantiles=0.5, interpolate=False):

    i = values.argsort()
    sorted_weights = weights[i]
    sorted_values = values[i]
    Sn = sorted_weights.cumsum()

    if interpolate:
        Pn = (Sn - sorted_weights/2 ) / Sn[-1]
        return np.interp(quantiles, Pn, sorted_values)
    else:
        return sorted_values[np.searchsorted(Sn, quantiles * Sn[-1])]

The difference between interpolate True and False is as follows:
weighted_quantiles(np.array([1, 2, 3, 4]), np.ones(4))
> 2
weighted_quantiles(np.array([1, 2, 3, 4]), np.ones(4), interpolate=True)
> 2.5

(there is no difference for uneven arrays such as [1, 2, 3, 4, 5])
Speed tests show it is just as performant as @maesers' function in the uninterpolated case, and it is twice as performant in the interpolated case.
Answer: Sharing some code that I got a hand with.  This allows you to run stats on each column of an excel spreadsheet.
import xlrd
import sys
import csv
import numpy as np
import itertools
from itertools import chain

book = xlrd.open_workbook('/filepath/workbook.xlsx')
sh = book.sheet_by_name("Sheet1")
ofile = '/outputfilepath/workbook.csv'

masses = sh.col_values(0, start_rowx=1)  # first column has mass
age = sh.row_values(0, start_colx=1)   # first row has age ranges

count = 1
mass = []
for a in ages:
    age.append(sh.col_values(count, start_rowx=1))
    count += 1

stats = []
count = 0
for a in ages:
    expanded = []
    # create a tuple with the mass vector

    age_mass = zip(masses, age[count])
    count += 1
    # replicate element[0] for element[1] times
    expanded = list(list(itertools.repeat(am[0], int(am[1]))) for am in age_mass)

    #  separate into one big list
    medianlist = [x for t in expanded for x in t]

    # convert to array and mask out zeroes
    npa = np.array(medianlist)
    npa = np.ma.masked_equal(npa,0)

    median = np.median(npa)
    meanMass = np.average(npa)
    maxMass = np.max(npa)
    minMass = np.min(npa)
    stdev = np.std(npa)

    stats1 = [median, meanMass, maxMass, minMass, stdev]
    print stats1

    stats.append(stats1)

np.savetxt(ofile, (stats), fmt="%d")


Scrolling through Netbeans code assistance list without mouse or keyboard arrows

Question: This is basically the same question as this except for Netbeans 8.0.2 (running under jMonkeyEngine SDK 3.1-alpha1) instead of Visual Studio.
Honestly, the aforemetnioned link says it better than I can, but basically I'm a vim key binding user, and have the netbeans jVi plugin installed and want to map, for example, alt-j and alt-k to scroll through the code completion list instead of the arrow keys:

I've searched through Tools->Options->Keymap, as well as the the JVi configs at Tools->Options->jViConfig.  I don't see anything at all under jViConfig, so I think the standard NetBeans key bindings are the way to go.
I have tried modifying most of the obvious down keys e.g insertion point down, scroll down, page down etc, but they all affect the underlying text in the editor, never the completion list.

And:

Does anyone know of a way to do this?
Or maybe a plugin to provide the functionality?
It simply appears that the raw arrow key movements are not mappable by netbeans (?).
Note: this is possible to do in Visual Studio 2015, so I'm hoping it's possible in NetBeans as well.
Many Thanks.
Answer: AFAIK, there is no way to do this in NetBeans. At least there wasn't in 2010, when I filed the NetBeans bug hint completion makes assumptions about associated editor pane bindings. I maintain jVi. I filed the bug since I was having trouble with completion bindings for some special keys. In the NB source take a look at

editor.completion/src/org/netbeans/modules/editor/completion/CompletionScrollPane.java

And you'll see a bunch of hardcoded stuff.
In the jVi source

nbvi/nbvi-module/src/org/netbeans/modules/jvi/KeyBindings.java

method fixupKeypadKeys, you see what jVi does (given the fix for the bug I filed). This is part of some arcane code that depends on being friend with some NB editor package.
You could file a bug with NB. If you provided NB a patch, they might incorporate it. If you file a NB bug, cc me (err at netbeans.org)
Alternately, you could try adding some code to the jVi file to add your keybindings.


Which distribution is this

Question:
I know this will be a f distribution.But it's not f(m,n) since the square sign is outside the summation.So it will be f(1,n).But i can't seem to know how exactly.
Answer: To answer your question, you must remember that:

if $X\sim N(\mu_x, \sigma^2_x)$ and $Y \sim N(\mu_y, \sigma^2_y)$ (independent) then $X + Y \sim N(\mu_x+\mu_y, \sigma^2_x + \sigma^2_y)$
if $X \sim N(\mu, \sigma)$ then $\frac{X-\mu}{\sigma} \sim N(0, 1)$
if $X\sim N(0, 1)$ then $\sum_{i=1}^n X_i^2 \sim \chi^2_n$
if $X \sim \chi^2_a$ and $Y \sim \chi^2_b$ are independent, then
$\frac{\frac{X}{a}}{\frac{Y}{b}} \sim F_{a,b}$
Comment: Perhaps another property to remember in order to reach the answer is that if $Z\sim \mathcal{N}(0,1)$ then $X = \mu + \sigma Z \sim \mathcal{N}(\mu,\sigma^2)$
Comment: @Emil: Yes, indeed ! I had to do the exercice to figure this out ! Thank you ! I have added it (2nd bullet)
Comment: Same here! I had to solve it as well, and at first I misread the denominator having the same form as the nominator, i.e $\left(\sum_{j=1}^{n} Y_j\right)^2$, which led me to the conclusion of $W\sim F(1,1)$ as a ratio of two $\Gamma(\frac{1}{2}, mn)$ variables. Obviously, this was not the result of interest here, but I actually found this conclusion rather interesting, i.e. that $\forall m,n\in \mathbb{N}_{>0}$,
$$ W := \dfrac{n\left(\sum_{i=1}^m X_i\right)^2}{m\left(\sum_{j=1}^n Y_j\right)^2} \sim F(1,1)$$
Comment: also, I just noticed on your 2nd bullet point that you should change $\sigma$ to $\sigma^2$ in the distribution, otherwise people will be "standardizing" by the variance, not the std. deviation

Which distribution is this


Combine bass guitar and PC audio into Bluetooth headphones

Question: I want to play my bass guitar along to YouTube videos on my Windows 7 PC and hear the combined mix via my Bluetooth headphones. I have two problems. I have tried a tiny USB Bluetooth adapter, it works and connects to my Bose QC35 headphones, and I hear the PC audio fine, but for some reason it only plays the PC Audio to my headphones, and the bass guitar, which is plugged into the PC front MIC socket, still comes out the speakers.  I'm pretty PC literate but can't find a fix in the settings.  I then tried a BT adapter that is USB powered, but connects to the headphone socket for audio input.  That's getting a LOT of background noise from the headphone socket.  The next problem is a delay of around a second on the bass, with the bass plugged into the mic socket on the PC.  PC is an i7 ATX desktop with 8GB RAM so it's quite pokey, but I'm obviously going about this the wrong way.
Will a cheap USB guitar input box like the Behringer UM2 work for this?  Or a separate sound card?  I don't want to record, and as long as the sound is clear and not noisy, with no latency, I don't need to tweak it.  All I want to do is play along to YouTube videos on my PC and hear both the video audio and the bass guitar through the BT headphones only.  Without spending a fortune :). Thanks in advance.
Comment: Can't call this an answer, but I just heard about this today - [Voicemeeter Banana](https://www.vb-audio.com/Voicemeeter/banana.htm) - (bizarre name;)  I haven't tried it as I'm on Mac, but seems to be the right kind of thing & is donation ware, so you can trial it. You may not be able to reduce the bass latency without a more 'pro' i/o solution, but it looks like it may handle the routing.
Comment: I'm afraid that whatever you'll do, latency introduced by BT will be unacceptable.
Answer: Wouldn't you need an audio interface? I know when mine is plugged in and turned on all computer sound is routed through it, including any plugged in instruments. You could maybe add a headphone type Bluetooth adapter to one of the "outs". For example my focusrite scarlet has two headphone Jacks that I'm certain could do this with a simple Bluetooth adapter. I may have even tried it. Would also eliminate delay
Answer: Firstly- no approach using bluetooth is viable.  Your target latency is less than around 12ms, and bluetooth will introduce 30-40ms (or more) by itself.
The typical way to do this is with an audio interface.  You mentioned the Behringer UM2, which may work, but I have heard of driver issues regarding Behringer devices- they used to recommend 3rd party generic drivers for some of their devices because the OEM driver was so bad.  I got a Focusrite interface instead, and it does exactly what you need it to do.  You can direct monitor to hear your bass, or you can run your bass through a DAW if you want, and you can listen to audio from other programs on your PC while doing either.  The Scarlett Solo is the minimal interface to do this.
Another option would be to use a pedal, amp, headphone amp, or bass effects processor that has a headphone output and aux input.  For example, the Darkglass Alpha Omega Ultra pedal (expensive!)
One major downside to this approach is that if you ever wish to record, you will still need to buy an audio interface anyway, unless you get a device that also functions as an interface (which is rare).
Comment: My go-to is a small mixer, such as a Yamaha MX-6.  The guitar and computer audio plug into the mixer inputs, headphones plug into the output.  Of course that doesn't account for BT, but as noted in this thread, BT is pretty much a non-starter anyway.
Answer: I think the problem is that you are dealing with two different media sources. The streaming from youtube is going to be treated differently from what is driving your mic input, and latency is going to occur even if you switch to a USB input for the guitar.
It is possible there is some mixing software that will combine the streaming from your browser on youtube with the input to your sound card from the mic input, but something that specific may be hard to find.
I think your simplest solution would be to download the audio from youtube locally to your computer and use playback from software such as media player or Audacity to play along with.
Depending on what browser you use to access youtube there are add-ons, plugins or accessory programs that can capture or download the audio from youtube. I can't comment as to the legality or rights issues of using such plug-ins as I haven't looked into it, so do your research first if you want to take those issues into consideration.
Most of the tracks available on youtube would be available for purchase, or even available for free from the respective artists if you want to be sure an be legit about downloading them.
Answer: I have Audacity and besides it being a great, free DAW, I record the audio from free YouTube videos with it. I can then save as MP3 or WAV or other formats. I have no interest in sharing or selling any of this music, as I only use it to jam to or add tracks to for practice. You can record directly into the program while it's playing (I don't use that function however) and I've noticed a latency setting for it.
Comment: This doesn't address how to combine bass guitar and PC audio into Bluetooth headphones


Cabeçalho da página em detalhes de seção no Crystal Reports

Question: Bom dia à todos!
Criei um relatório de comissões com Crystal Reports no Visual Studio com filtro de datas. Todo mês é enviado aos vendedores individualmente suas comissões no período. Para abrir os detalhes do vendedor, basta clicar duas vezes em cima do seu grupo e é aberto isoladamente as vendas do mesmo. Porém, gostaria que fosse mantido o cabeçalho do relatório, onde estão informações de período, data de impressão e nome da empresa. Alguém sabe como fazer?
Obrigado!
Comment: pode configurar para que apareça um vendedor por pagina também acho que ficaria mais profissional, 1 vendedor por pagina, sairia o cabeçalho para cada e poderia adicionar o tipo de relatório Analítico e Sintético deixar por opção do usuário seria uma outra opção apenas uma dica abraço.
Answer: <code>Crystal Reports > Report > Report Options... > Mostrar todos os cabeçalhos na pesquisa detalhada
</code>
Isso resolve meu problema.
Fica a dica para quem utiliza o Crystal!


Understanding Scala Future andThen

Question: I'm trying to use andThen method to register action stages for the future. Like this:
implicit val executionContext = ExecutionContext.global

val f = Future(0)
f.andThen {
  case r => println(r.get + "1")
} andThen {
  case r => println(r.get + "2")
}

Since this method executes asynchronously and does not produce a
  return value, any non-fatal exceptions thrown will be reported to the
  ExecutionContext .

What does it mean asynchronously? It means asynchronously to the future execution itself?
Answer:
What does it mean asynchronously? It means asynchronously to the
  future execution itself?

It means that the execution of andThen will happen on a given thread provided by the ExecutionContext after the originating Future[T] completes.
If we look at the implementation:
def andThen[U](pf: PartialFunction[Try[T], U])(implicit executor: ExecutionContext): Future[T] = {
  val p = Promise[T]()
  onComplete {
    case r => try pf.applyOrElse[Try[T], Any](r, Predef.conforms[Try[T]]) finally p complete r
  }
  p.future
}

This method is a smart wrapper over Future.onComplete which is a side effecting method that returns Unit. It applies the given function, and returns the original Future[T] result. As the documentation states, it is useful when you want to guarantee the order of several onComplete callbacks registered on the future.

Understanding Scala Future andThen


Problema com Sistema de Recomendação em R

Question: Estou tentando desenvolver um sistema de recomendação utilizando a linguagem R.
Basicamente, o sistema é de recomendação musical coleta informações de um arquivo onde existe uma certa quantidade de usuários e para cada usuário, uma contagem de vezes que ele ouviu determinado artista.
library(tidyverse)
library(data.table)
library(recommenderlab)

dados <- fread("dadosTreinamento.txt", header = TRUE, sep = "\t", fill = TRUE) #Dados carregados em variável

names(dados)[2:3] <- c("IdArtist", "IdUser")

dadosGrupo <- group_by(dados, IdUser, IdArtist) #Agrupando os dados

dadosGrupo2 <- summarise(dadosGrupo, count = n()) #Gerando tabela com soma da quantidade de vezes que cada usuário ouviu determinado artista
dadosGrupo2 <- as.data.frame(dadosGrupo2) #Convertendo dadosGrupo2 para data.frame

matrizAfinidade <- as(dadosGrupo2, "realRatingMatrix") #Matriz real de dados

Rec.model<-Recommender(matrizAfinidade, method = "UBCF")

usuarios <- length(unique(dadosGrupo2$IdUser))

listaRecomendacoes <- list(length(usuarios))

for (i in 1:usuarios) {
  itemRecomendado <- predict(Rec.model, matrizAfinidade[i,], n=5)
  listaRecomendacoes[i] <- as(itemRecomendado, "list")
}

Nesse trecho o programa gera a recomendação de 5 itens para os usuários.
Entretanto, quando tento visualizar a recomendação através do comando View(listaRecomendacoes), o sistema apresenta apenas os itens recomendados e onde deveria ficar a informação do usuário para o qual o sistema recomendou, fica apenas a palavra "character", como é possível ver na figura abaixo:

O arquivo de dados dos usuários que estou usando está neste link.
Answer: Bote um colchete a mais em listaRecomendacoes para que ele receba a lista inteira e não só conteúdo. Aí os IDs dos usuários são os nomes das listas.
listaRecomendacoes <- vector('list', usuarios) #inicializa uma lista vazia do tamanho de usuarios

for (i in 1:usuarios) {
  itemRecomendado <- predict(Rec.model, matrizAfinidade[i,], n=5)
  listaRecomendacoes[[i]] <- as(itemRecomendado, "list") #passa os valores para a lista
}

names(listaRecomendacoes[[1]]) #pega o ID do usuário 1
sapply(listaRecomendacoes, names)#vetor com os IDs dos usuários

Comment: Obrigado Jorge Mendes. Na verdade, acrescentando apenas os colchetes a listaRecomendacoes já deu certo!


Converter um Double com mais de 13 casas decimais para String sem perder valores

Question: Tenho em C# o seguinte número em Double: 124.00767638369544. Quando eu, SIMPLESMENTE, coloco valor.toString(), o valor vai para: 124.007676383695, IGNORANDO os 0,00000000000044. O sistema que estou fazendo precisa dessa precisão.
Já tentei forçar região, parse, e uma infinidade de conversões diferentes e nada.
Alguém tem alguma sugestão? Acredito que siga a limitação do Excel, que... se colocar o mesmo valor em uma célula, também é desconsiderado o 0,00000000000044.
Answer: Ele está arredondando para uma precisão de 15 digitos, que é o padrão do ToString() para esse tipo, segundo o link abaixo.
Mas o ToString() permite passar parametros de formatação, como a precisão.
Como o tipo Double tem uma precisão maior, pode usar assim para ter todos os dígitos:
double num = 124.00767638369544
String numString = num.ToString("G17");

O format "G" é um número "Geral", e o 17 é a precisão
Também pode tentar o formato "R", que tenta converter para um valor que, possa ser novamente convertido para o tipo original, nesse caso Double, sem perda, mas a documentação recomenda usar o "G17": https://docs.microsoft.com/pt-br/dotnet/standard/base-types/standard-numeric-format-strings?redirectedfrom=MSDN#RFormatString
Mais sobre os formatos do ToString(): https://docs.microsoft.com/pt-BR/dotnet/standard/base-types/standard-numeric-format-strings


Pandas iterations to Pyspark Function

Question: Given a dataset I tried to create a logic where within two column I need to enforce continuity in terms of last destination (in to column) being the exact next starting point (in from column) per id. For instance this table
+----+-------+-------+
| id | from  | to    |
+----+-------+-------+
|  1 | A     | B     |
|  1 | C     | A     |
|  2 | D     | D     |
|  2 | F     | G     |
|  2 | F     | F     |
+----+-------+-------+

should ideally look like this:
+----+-------+-------+
| id | from  | to    |
+----+-------+-------+
|  1 | A     | B     |
|  1 | B     | C     |
|  1 | C     | A     |
|  2 | D     | D     |
|  2 | D     | F     |
|  2 | F     | G     |
|  2 | G     | F     |
|  2 | F     | F     |
+----+-------+-------+

Using Pandas I did this by looping row wise and checking if previous_row['to'] == current_row['from'], also a check for id that can be probably avoided using a groupby, as you may see below
for i in range(len(df)):
    if (i < (len(df)-1)):
        if (new.ix[i,"to"] != new.ix[i+1,"from"]) & (new.ix[i,"id"] == new.ix[i+1,"id"]):
            new_index = i + 0.5
            line = pd.DataFrame({"id":new.ix[i,"id"],
                             "from":new.ix[i,"to"],"to":new.ix[i+1,"from"],}, index = [new_index])
            appendings = pd.concat([appendings,line])
        else:
            pass
    else:
        pass

Is it possible to as is  "translate" this to pyspark rdds?
I am aware that looping is far from optimal in Pyspark to replicate a looping and if-else logic.
I considered grouping by and zipping from and to columns and working on a single column. Main problem with this lies in the fact that I could produce a flag on lines that are "faulty" but there is no way to insert new lines without using index-wise operations.
Comment: in spark, the order of rows are non-deterministic after shuffling(i.e. groupby, window), you need to specify at least one column to sort so the order of rows can be deterministic.
Answer: This isn't a pyspark answer but a partial answer to show you how to achieve the task without loop in pandas.
You can try:
def f(sub_df):
    return sub_df.assign(to_=np.roll(sub_df.To, 1)) \
                .apply(lambda x: [[x.From, x.To]] if x.to_ == x.From else [[x.to_, x.From], [x.From, x.To]], axis=1) \
                .explode() \
                .apply(pd.Series)

out = df.groupby('id').apply(f) \
        .reset_index(level=1, drop=True) \
        .rename(columns={0: "from", 1: "to"})

Workflow:

Group the dataframe by id using groupby
For each group:

Create a new column (here names to_) to have the previous row. np.roll performs a circular shift in order to keep the last value.
According if the current from == previous to: return current line or add a new line to make the transition.
Use explode to explode the list of list into one list per row.
Convert the column into two columns using apply(pd.Series)

Then, for the output dataframe, remove the level 1 index using reset_index
And rename the columns using rename

Full code
# Import module
import pandas as pd
import numpy as np

# create dataset
df = pd.DataFrame({"id": [1,1,2,2,2], "From": ["A", "C", "D", "F", "F"], "To": ["B", "D", "D", "G", "F"]})
# print(df)

def f(sub_df):
    return sub_df.assign(to_=np.roll(sub_df.To, 1)) \
                .apply(lambda x: [[x.From, x.To]] if x.to_ == x.From else [[x.to_, x.From], [x.From, x.To]], axis=1) \
                .explode() \
                .apply(pd.Series)

out = df.groupby('id').apply(f) \
        .reset_index(level=1, drop=True) \
        .rename(columns={0: "from", 1: "to"})
print(out)
#    from to
# id
# 1     D  A
# 1     A  B
# 1     B  C
# 1     C  D
# 2     F  D
# 2     D  D
# 2     D  F
# 2     F  G
# 2     G  F
# 2     F  F

The next step is to translate it into PySpark. Try it and feel free to open a new question with yours attempts.

Pandas iterations to Pyspark Function


Insert current timestamp using javascript in database using php

Question: I am trying to insert local time into database using javascript. Can any one help me?
could you please have a look on the file named member.class.php and please let me know where I have to put the javascript code... https://www.dropbox.com/sh/lfef67brewx7rub/wYRP72bDh7
Comment: Actually I have tried with php script but I am not that much familiar with javascript
Comment: A little bit of code could help us help you.
Answer: Its very simple man...try with this
var milliseconds = new Date().getTime();

it will give you time in milli seconds or you can use like
new Date().getTime();

if you want it in unix(linux) timestamp then use like this
var unix = Math.round(+new Date()/1000);   it will also give you in seconds

Comment: What about date and time together? and I am trying to store it in linux platform in web host...
Comment: could you please have a look on the file named member.class.php and please let me know where I have to put the javascript code... `https://www.dropbox.com/sh/lfef67brewx7rub/wYRP72bDh7`
Answer: In Javascript:
    var d = new Date();
    var date_with_time = d.getDate()+"-"
                        +d.getMonth()+1+"-"
                        +d.getFullYear()+" "
                        +d.getHours()+" "
                        +d.getMinutes()+" "
                        +d.getSeconds();

In PHP, the best way will be that you should create your time column DATETIME type and set default value CURRENT_TIMESTAMP. No need to manually insert it through Javascript.
Comment: after setting current_timestamp the value is inserting the servers current time... but I want to insert my local regions time
Comment: could you please have a look on the file named member.class.php and please let me know where I have to put the javascript code... `https://www.dropbox.com/sh/lfef67brewx7rub/wYRP72bDh7`
Answer: var currentdate = new Date();
var datetime = "Date n Tym : " + currentdate.getDate() + "/"
            + (currentdate.getMonth()+1)  + "/"
            + currentdate.getFullYear() + " @ "
            + currentdate.getHours() + ":"
            + currentdate.getMinutes() + ":"
            + currentdate.getSeconds();

Answer: 10 ways to format time and date using JavaScript
See this answer!
Answer: DB like time stamp in js:
var timestamp = "" + d.getFullYear()
                    + ("0" + (d.getMonth()+1)).slice(-2)
                    + ("0" + d.getDate()).slice(-2) + "-"
                    + ("0" + d.getHours()).slice(-2)
                    + ("0" + d.getMinutes()).slice(-2)
                    + ("0" + d.getSeconds()).slice(-2);

after this, for example, timestamp="20160408-134304"


Twig templates for nodes in different views

Question: I have a content type, blog_post, that is displayed by a number of different views.
I'm having a problem that the node template that gets used first after clearing the cache will then be used for all other views.
For example one page displays a view called "Blog Posts". If I load this page after clearing the cache, it correctly uses the template node--view--blog-posts.html.twig.
Another page uses the view "Latest Blog Posts", and this should use the template, node--view--latest-blog-posts.html.twig. However if I load this page without clearing the cache first, it uses the node--view--blog-posts.html.twig template.
If I clear the cache and reload the second page, it will then use the correct template, but if I go back to the first page, it will be using the template for the second!
I have twig debugging enabled, and it shows the wrong view name under "FILE NAME SUGGESTIONS" as follows:

I expect that lots of other sites theme nodes in multiple views, so I expect I'm done something wrong. Any suggestions how I can debug this?
Answer: Do not use node--view-* templates. They are broken.
Two views with entity view mix up rendered templates
The quick solution:

create unique view mode for your CT
display views with content
use unique view mode for your view
Comment: Thanks! So in the above example, my template would become `node--blog-post--teaser.html.twig`, and if I create a view mode called "Latest" and use it for my view, the template would become `node--blog-post--latest.html.twig`?
Comment: Yes, you can see this suggestion like in your example.
Comment: Brilliant. I will try this tonight. It would appear that this bug has been known for a year and a half, and no fix in sight.
Comment: Brilliant! That's working perfectly now. I must admit I hadn't realised how useful custom view modes are. I suspect I will be using a lot of them in the future!


Como posso somar o valor do resultado ao valor anterior?

Question: Gostaria de saber,como faço para somar na variável res o valor da sequencia e depois printa-lo? como por exemplo, entrar com o valor de N igual a 2 e conseguir na saída o valor 2.5?
#include <stdio.h>

int main (void)
{
    int N,i;
    float res;

    scanf("%d", &N);
    for( i = 1 ; i <= N; i++)
    {
        res = (float)i/((N - i) + 1);
    }
    printf("%.4f\n", res);
    return 0;
}

Answer: Para fazer isso, você pode utilizar o operador += (atribuição de adição) para acumular o resultado e inicializar a variável res. O código deve ficar assim:
#include <stdio.h>

int main (void){
    int N, i;
    float res = 0;
    puts("Digite um valor: ");
    scanf("%d", &N);

    for( i = 1; i <= N; i++){
        res += (float)i/((N - i) + 1);
    }
    printf("%.2f\n", res); // 2.50
    return 0;
}

DEMO


ComboBox e SQLReader

Question: Eu tenho um ComboBox com uma lista de items que contém nomes que são gerados a partir do meu banco de dados(eu puxo o nome da coluna cerveja que estão alocadas na tabela):
private void Form1_Load(object sender, EventArgs e)
{
   try
   {
   conexao.Open();
   SqlCommand cmdd = new SqlCommand("select Cerveja from Cervejas where Cerveja ='" + comboBox1.SelectedItem + "'", conexao);
   SqlDataReader DR;
   DR = cmdd.ExecuteReader();
   if (DR.HasRows)
   {
     while (DR.Read())
     {
        comboBox1.Items.Add(DR.GetString(0));
     }
   }
   else
   {
        MessageBox.Show("Não tem cervejas no nosso banco de dados!");
   }

A partir desse código eu consigo obter o nome da coluna "Cervejas" no combobox ao iniciar o programa. O que eu preciso fazer agora, é quando o usuário selecionar um item no combobox, o mesmo faz uma comparação com o nome do item do combobox e as cervejas no banco de dados, puxando a row da cerveja certa, eu estava tentando assim, porém não consigo:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
        try
        {
            conexao.Open();
            SqlCommand cmd = new SqlCommand("select * from Cervejas where Cerveja ='" + comboBox1.SelectedItem + "'", conexao);
            SqlDataReader DR;
            DR = cmd.ExecuteReader();
            if (DR.Read())
            {
                if (comboBox1.SelectedItem == DR.GetValue(1))
                {
                    MessageBox.Show("teste");
                }
                else MessageBox.Show("teste2");
            }
        }
        catch (Exception ex)
        {
            conexao.Close();
            MessageBox.Show("Erro de conexão Modbus: \n\n" + ex.Message);
        }

No caso, nesta parte:
if (comboBox1.SelectedItem == DR.GetValue(1))
{
   MessageBox.Show("teste");
}

Eu faço esta comparação, se o item selecionado corresponder a alguma cerveja no banco de dados deveria imprimir a palavra 'teste', porém isso não acontece.
Answer: A verificação com o if era desnecessária, uma vez que eu uso a cláusula WHERE no cmd.
Apenas editei:
SqlDataReader DR;
DR = cmd.ExecuteReader();
if (DR.Read())
{
     Messagebox.Show = DR.GetValue(0).ToString(); // teste
}

ComboBox e SQLReader


Installing python API from git

Question: I can't figure out why I can't install https://github.com/ldilley/minestat. when I do pip install git+https://github.com/ldilley/minestat, it gives a error of Command "python setup.py egg_info" failed with error code 1 in C:\Users\Chuck\AppData\Local\Temp\pip-req-build-98h731vo\
Anyone know how to fix it?
Comment: it's not a pip package, you cant install it. if you want to use it then just put the minstat.py file in you projectand import from there as shown in example.py file.
Comment: From a quick glance, seems you just need to download or clone the repositiory. Then place `minestat.py` somewhere in your python path so you can import it.
Comment: The repo build for python has no `setup.py` file. When I try your same command to install I get `IOError: [Errno 2] No such file or directory: '/private/var/folders/qz/smb2qbnj2bzft1w15htqhdmrzz6jc_/T/pip-req-build-abqhx9/setup.py'`, the `setup.py` missing for `pip`.
Answer: This may means that your setuptools are out of date.
You can fix this by doing: pip install --upgrade setuptools

Installing python API from git


How do I turn off .js for certain media queries?

Question: I have a portfolio page that uses a lightbox .js plugin and I want to be able to turn that off when I have a screen size of less that 480 because the box pop ups are too large. Is there a way to do this in css? If not how do I go about this in .js?
This is the site http://www.campusphotoservices.org/portfolio.html
Comment: As a side note, you should scale down the images on your page in a graphics program so they don't take so long to load.
Answer: You can't do it with CSS directly, but it's pretty simple to do with JavaScript.
In the spot in your code where you call lightbox, just check that the window's width is greater than 480px; otherwise do whatever else it is that you want to do.
window.innerWidth

Answer: In javascript you can match media queries just like would in CSS. There's a matchMedia() object attached to the window, https://developer.mozilla.org/en-US/docs/DOM/window.matchMedia. You use media queries just like you would in the CSS.
var mediaQuery = matchMedia("(min-width: 400px)");
if (mediaQuery.matches) {
  /* the view port is at least 400 pixels wide */
} else {
  /* the view port is less than 400 pixels wide */
}

Not all browsers support it so you'll need to use the matchMedia polyfill, https://github.com/paulirish/matchMedia.js/


ant design onSelect is not firing

Question: I'm trying to use Autocomplete from Ant Design, but the "onSelect" is not firing. Everything else is working well - when I type into the search bar, my ingredient list appears and filters as intended. If I console log "data" in onChange, the search's values appears (the "data"). When I click on an item from my filtered pop up menu, the menu disappears, the value in the input remains the same as before (i.e. it does not change to the selected item) and nothing is fired to the console. What am I doing wrong?
UPDATE: Added a sandbox.
Thanks in advance for your help.
export default function Searchbar() {
  const [value, setValue] = useState('')
  const [options, setOptions] = useState<{ value: string }[]>([]);

  const ingredients = useSelector(state => state.ingredients);

  const onSearch = (searchTerm: string) => {
    setOptions(
      !searchTerm ? [] : ingredients.filter(ferment =>
        ferment.label.toLowerCase().includes(searchTerm.toLocaleLowerCase())
      ))
    };

    const onSelect = (data: string) => {
      console.log("onSelect", data);

    };

    const onChange = (data: string) => {
      setValue(data);
      console.log(data)
    };

    return (
      <>

    <AutoComplete
        options={options}
        value={value}
        style={{ width: 200 }}
        onSelect={onSelect}
        onSearch={onSearch}
        onChange={onChange}
        placeholder="looking for"
      />

        </>
    )
}

Comment: This appears to be correct from what I can tell. Can you try reproducing this in a *running* codesandbox and link it here in your question?
Comment: Just added a sandbox. thanks!
Comment: I am unable to run your codesandbox. Can you try a simpler one that isolates your `Searchbar` component and behavior?
Answer: <AutoComplete /> expects prop options with items that must have value prop.
You pass ingredients as options to AutoComplete and ingredients don't have this property.
This is the reason why the callback onSelect is not firing.
Answer: When creating search options we need to specify value key :pair for example value: item?.title,for onSelect to understand which one was selected.

ant design onSelect is not firing


Systematic application of algebraic topology to energy minimization problems?

Question: I have come across two different occurrences of energy minimization problems which find an interpretation using notions from algebraic topology, and I was wondering whether analogous situations have been studied in a systematic way somewhere in the literature.
The first is a result by Cartan in Riemannian Geometry states that, given a compact Riemannian manifold $M$, every homotopy class of loops in the path space of $M$ contains a closed geodesic.
The second is a result in Hodge theory stating the existence of an isomorphism:
$$ H^k_\Delta(M) \xrightarrow{\sim} H^k_{deR}(M) $$
between the $k$th de Rham cohomology group of $M$ and the vector space of harmonic $k$ forms on $M$.
In both instances, objects which are defined as infimums of sorts (closed geodesics and harmonic forms) can be identified as representatives of homotopy/cohomology classes related to the underlying manifold. Is there a body of work in which the above two results are brought to a common ground?
Answer: Closed geodesics are special loops. Namely, the closed loops are exactly the loops that extremize the energy. Let $\Lambda M$ be the space of all loops in $M$. The closed geodesics are the critical points of the function(al) $E:\Lambda M\rightarrow \mathbb R$
$$
E(\gamma)=\int_{S^1}\Vert \dot\gamma(t)\Vert dt
$$
Finding all closed geodesics amounts to finding all the critical points. It is well known that critical points of a function are closely related to the topology of the domain, which can be studied with algebraic topological methods.
This paradigm is available in many geometric situations. Very often the objects of interest extremize some function defined on some space, which then can be studied with algebraic topology. Some keywords that might get you into this are calculus of variations and Morse theory.


Azure SignalR Service - swagger page

Question: When creating a new SignalR Service on MS Azure, it seems to be there a default swagger page that is wrongly configured (screenshot below). There is any way to disable it?
To reproduce the issue, on a SignalR Service instance, navigate to:
<code>https://<yourservicename>.service.signalr.net/swagger
</code>
If it cannot be disabled, seems to be a light case to put the SignalR Service prone for Information Disclosure attacks.
screenshot
Answer: Have a look at https://docs.microsoft.com/en-us/azure/azure-signalr/howto-network-access-control. You should be able to block the swagger page by Denying REST request. Let me know if that helps.
Comment: I noticed you had an open support ticket. I advise you mention this in the support ticket, but I will also bring this feedback to the product. I realize the current feature is opt-in, but you should still be able to apply that access policy.
Comment: Thanks for the suggestion Ryan! However, why am I supposed to block request for a page that is wrongly configured and it is not requested by customer itself? I do not need a public Swagger... I suggest to escalate to Product Group :)

Azure SignalR Service - swagger page


Oracle SQL query statement and conditions with timestamps and ISO dates

Question: I need a query which will select records from Oracle database on the basis of the datetime condition. Example below:
SELECT * FROM table_name WHERE [modification_date] >= '2014-01-28T12:00:00Z';

As datetime I used ISO date and this is "Must be". In Oracle XE database a [modification_date] column has type "Timestamp with time zone".
And now is my question - How to convert ISO date in query to proper searching on database ?
I tried adding to_timestamp_tz to query statement.
SELECT * FROM table_name
WHERE MODIFICATION_DATE >= to_timestamp_tz('2014-01-28T00:00:0Z', 'YYYY-MM-DD"T"HH24:MI:SS');

But get this error:

SQL Error [1830] [22008]: ORA-01830: date format picture ends before
  converting entire input string
Comment: `[modification_date]` is an invalid name for a column. Plus: `'2014-01-28T12:00:00Z'` is not a "ISO date". It's a string literal, you need to use `to_timestamp()` to create a proper timestamp value.
Comment: Probably a [duplicate of this](http://stackoverflow.com/q/26671557/266304); but is your Z fixed too?
Comment: Doesn't Oracle support `TIMESTAMP'2014-01-28T12:00:00Z'` literals?
Comment: @vanzen - yes, because of your Z at the end. If that is fixed include that in double quotes too, but you might want to replace it with UTC and use the TZR model, or include an `at time zone utc` clause?
Comment: Ok, i got it.

Query should look like:
`SELECT * FROM table_name WHERE MODIFICATION_DATE >= to_timestamp_tz('2014-01-28T13:00:0Z', 'YYYY-MM-DD"T"HH24:MI:SS"Z"');`
Comment: @jarlh - [Not with the T and Z embedded, no](http://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements003.htm#SQLRF51062).
Comment: @Alex - unfortunately the date format is dictated from above. I have to keep this convention.
Comment: @jarlh, no timestamp literal must be `TIMESTAMP '2014-01-28 12:00:00 UTC'`
Answer: Based on an earlier question, it's tempting to treat both the T and Z as character literals, and basically ignore them, using:
to_timestamp_tz('2014-01-28T12:00:0Z', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')

If you use to_timestamp_tz() without specifying a timezone then it defaults to your session time zone, as would to_timestamp(); so a time specified in Zulu/UTC loses that zone information:
alter session set time_zone = 'America/New_York';
select to_timestamp_tz('2014-01-28T12:00:0Z',
  'YYYY-MM-DD"T"HH24:MI:SS"Z"') from dual;

TO_TIMESTAMP_TZ('2014-01-28T12:00:0Z','YYYY-MM-DD"T"HH24:MI:SS"Z"')
-------------------------------------------------------------------
28-JAN-14 12.00.00.000000000 AMERICA/NEW_YORK

Your 12:00 time is shown as 12:00 in New York, not 12:00 UTC.
A safer conversion, assuming your values are always supposed to represent UTC, is to specify the time zone explicitly with the from_tz() function:
WHERE MODIFICATION_DATE >= from_tz(to_timestamp('2014-01-28T12:00:0Z',
  'YYYY-MM-DD"T"HH24:MI:SS"Z"'), 'UTC')

This gets the UTC time properly:
alter session set time_zone = 'America/New_York';
select from_tz(to_timestamp('2014-01-28T12:00:0Z',
  'YYYY-MM-DD"T"HH24:MI:SS"Z"'), 'UTC') from dual;

FROM_TZ(TO_TIMESTAMP('2014-01-28T12:00:0Z','YYYY-MM-DD"T"HH24:MI:SS"Z"'),'UTC')
-------------------------------------------------------------------------------
28-JAN-14 12.00.00.000000000 UTC

Comment: Use `'YYYY-MM-DD"T"HH24:MI:SSTZH:TZM'` and it will match both `2017-01-10T00:00:00Z`, `2017-01-10T00:00:00+0000` and `2017-01-10T00:00:00+00:00`
Comment: You can also use `to_timestamp_TZ('2014-01-28T12:00:0Z'||'UTC',
  'YYYY-MM-DD"T"HH24:MI:SS"Z"TZR')`
Answer: Look at the to_timestamp_tz function.
Assuming Z is for Zulu/UTC, you ca probably do a replace of Z with +00:00 and work with to_timestamp_tz function
SELECT * FROM table_name
WHERE modification_date >= to_timestamp_tz(replace('2014-01-28T12:00:00z','z','+00:00'),'YYYY-MM-DD"T"hh24:mi:sstzh:tzm')

Comment: You do not need to replace `z` with `+00:00`. Using the format mask `TZH:TZM` will match the `z` character and set the time zone to zulu time (`+00:00`). So you can just do `TO_TIMESTAMP_TZ( :your_isotime, 'YYYY-MM-DD"T"HH24:MI:SSTZH:TZM' )`.