Do rest days aid in developing strength in facial muscles used by brass players?

Question: I'm a somewhat experienced trumpet player — not sure how to quantify it since I played intensively for a few months about a year and a half ago and then didn't play so much after that until about a month ago when I dove into another intensive practice schedule.  My ability to play high notes is still developing pretty quickly — last year A5 (5th partial) was barely attainable, but since I started playing again it's become something I can hit much more reliably and I've managed to squeak out a C6 for a moment.
I'll be playing in a concert in less than a month and I'd like to be able to land high notes as cleanly and reliably as possible by that point in time.  My question is this: in order to best meet this goal, is it advisable to take days off from practicing to let my muscles recover and build strength?  Is one day the longest I should rest?  How frequently should I take rest days?  When I do practice, should I stop playing when it becomes extremely difficult to play notes that are normally within my range?
Answer: Your facial muscles are different than your other muscles in the sense that they won't get huge if worked intensely.
Typically when brass players rest, it's due to lip sensitivity. Resting more than a day will cause you to begin losing well-honed fine motor coordination.
I believe that the best way to achieve your goal has nothing to do with rest, but with preparation. I have a good answer on here somewhere about extending range. You (or somebody else) should search for it and take a look.
Each day you practice, you should begin by playing long, low, medium-soft tones in the lower-third of your instrument's register. Never play high at first. Start in the middle or most comfortable part of your range and work both directions of your range. If you want to play high, you have to learn how to play low, and vice versa. Every high exercise you play should be balanced with a low one.
You should play every day, even if you just buzz on the mouthpiece. Even after a heavy day, your lips should be fine for the next day.
In terms of actively extending range, the rule of 3 is best: give yourself 3 tries to play the target pitch. If you can't do it within three tries, you're done for the day. The worst thing you can do is get frustrated and keep trying to hammer at it until you get it. You're just damaging your instrument (your lips).
Remember that the piece of metal you hold is just an amplifier.
Comment: Further, the more you practice, the more (one hopes!) you improve your diaphragmatic breath control, which takes stress off your lips as well.   There are many facets of playing ( breath, finger coordination, interpretation, etc)  which require daily work, so unless there's true soreness or damage, best to play every day.
Comment: How long is it best to spend warming up on low- to mid-range exercises before working into the upper part of my range?
Comment: Depends on your focus. If you really want to improve tone, then you can play quiet long-tones for 30 minutes, for example. Or if it's a regular session with mixed goals, 3-5 minutes. I'd recommend doing what feels the most right / what works for you versus being a clock-watcher.
Answer: No, don't plan days with no practice.  You've had good advice about how to practice effectively.
Comment: I'd prefer one with content.
Comment: Interesting. Do you think a day with no practice is *always* a bad idea? Do you think practice away from the instrument is possible?
Comment: It's occasionally inevitable.  You invariably notice the next day!
Comment: Not really useful
Comment: You'd prefer a different answer, @CarlWitthoft?


Time complexity of string repetition (via str * int)

Question: What's the time complexity of repeating a string in python with the String * int operator?
To be clear, I'm talking about this phenomenon:
print("a"*4)

would output "aaaa"
I tried to find an answer myself, but can't find anything about this, and it's worse because I am unsure of what it's called... I'm just calling it string repetition for now.
Answer: According to this lecture, given an integer k and a list l, k*l is of complexity O(k*N).
Since strings are iterables too, I assume the answer is the same for strings.


Number of ways to divide a line of length $s$ into segments such that each segment has length $\leq n$

Question: This is a slightly modified version of this question. With a line of length $s$ and an integral length $n$, I must divide $s$ into $\left \lceil{\frac{s}{n}}\right \rceil$ segments such that union of all segments gives $s$. Constraint is that none of the segments should have length $> n$.
Is a closed form solution possible for $f(s,n)$? Since with the given constraints I'm unable to reach anywhere.
Example: for a given $s = 6$ and $n = 4$.
The possible combinations are (1-4, 5-6), (1-3, 4-6), (1-2, 3-6) => So $$f(6,4) = 3$$
Comment: Do each you need the segments to have strictly positive length, or is a segment allowed to have length $0$ (in other words, do you need to use *exactly*  $\left\lceil\frac{s}n\right\rceil$ segments or are we allowed to use less)?
Comment: Is it possible for one segment to have length $0$ without another having length $>n$?
Comment: I think you are right @ConnorHarris. My bad.
Answer: You "initialize" all segments to have length $n$ precisely. Now you have cut up a stick of length
$$
\left\lceil\frac sn \right\rceil \cdot n,
$$
which is
$$
\left\lceil\frac sn \right\rceil \cdot n - s = n-(s \% n)
$$
too long, where $s\%n$ uses the "computer science modulo operator", i.e. the remainder of $s$ after dividing by $n$. Thus, you need to shorten your segments by a total of $n-(s\%n)$. Because $0 < s\%n < n$ always, you have no further constraints: you could allocate all these "units of shortening" to one segment, or to all different ones. This is a typical stars and bars problem, and the number of ways of doing it is given by
$$
\binom{n-(s \% n) + \lceil s/n\rceil - 1}{\lceil s/n \rceil-1}.
$$
Edit: Actually, the above only works when $n$ does not precisely divide $s$. However, that special case is easy: there is only one solution. All sticks have length precisely $s/n$, which is now an integer.
Comment: won't this give 10 for $s=6$, $n$=4, rather than 3?
Comment: @IndoUbt, my bad; what I called $n$ in the final formula is supposed to be the number of segments, i.e. $\lceil s/n \rceil$. I will update it now.


Would IT ever need a user's domain password?

Question: Is there anything a Windows domain administrator might need to do while configuring a workstation for a new user that absolutely can't be done without the user's domain account password? To avoid asking users for their passwords the admin could, theoretically, change the password, log in as the user, and do whatever it is they wanted to do, but would that actually give them any additional permissions that they don't already have by virtue of being a domain administrator?
UPDATE:
The answers so far have referred to "tuning" or changing the user's profile. However, there's this article from Microsoft on modifying the default profile which gets applied to users when they log on for the first time and these instructions for changing another user's Windows registry settings at any time. What would an admin change while logged in as a user that the admin couldn't change using these or other available techniques that don't involving logging in as the user? Just "logging in as the user" isn't a reason to ask for or change the user's password. I'm looking for a practical reason for doing so.
Comment: My suspicion before asking this question was that, twisted though Windows administration may be at times, there was nothing that would be impossible for an admin that would be possible for a less-privileged end user. The motivator for asking for a user's password, or changing their password, and logging in with their account would be inexperience or convenience; either the admin doesn't know how to do something or doesn't want to fiddle with registries and editing configuration files by hand and doesn't have tools available to make the required changes.
Comment: You might want to rewrite this question as at first you ask about user passswords then you change to to logging in as the user at all.  These are 2 seperate issues
Comment: How about installing an application that requires access to the user's Outlook profile (like a CRM app that uses Outlook)?  You're at the mercy of the application developer's installer script.
Comment: @Jim Actually, I tried to head off the password reset avenue in the second sentence of my original question. If you reset a user's password, then you DO now have that user's password. You don't have their OLD password. I was getting vague answers about changing a user's profile, so I provided links showing how you could do that without impersonating the user. I also specifically called out "logging in as the user" as not being an acceptable end goal because that was mentioned in a comment as something you couldn't do without requesting/changing the user's password.
Comment: @gravyface So your answer is "to install poorly written software?" Interesting. Care to post it as an answer?
Comment: @isaac, no you have the reset password, not the one the users uses and now the fact that you reset the password has been logged, as well as, when the user logs in they are going to notice that their password (which you never had) no longer works
Comment: @IsaacTruett Your answer was moved to a comment because it was not an answer, it was a clarification of your question and a summation of points you already made in several comments. StackOverflow may handle that differently, but here on SF that was clearly "not an answer" and was being voted as such (it hadn't been flagged yet, but it was coming). Therefore, I moved it rather than obliterate the content.
Comment: @Isaac, you seem to have this strange notion that anything that doesn't work they way you think it should must of necessity be poorly written. Let me be the first to say that you are jumping to completely invalid conclusions. As admins we see a much broader range of software and installation situations than a dev ever would.
Comment: @sysadmin1138 Thank you for taking the time to explain.
Comment: @John We'll have to agree to disagree about who has the stranger notions. You obviously have a very particular bias yourself and I'm not going to argue over that with you.
Comment: I just got my password asked by IT so that "they can join the PC to the domain", isn't that done with admin's passwords and not user's passwords?
Answer: Let's be clear: if you're a Domain Admin, you can install a piece of software–a device driver comes to mind–that can literally do anything.  However, it's varying degrees of impractical, ranging from "What's the registry key for the desktop background, again?" all the way up to "And then we hook onto the file read call inside the encrypted-profile layer so as to spoof Firefox into thinking that they have disabled cookies from doubleclick.net".
You're asking for an absolute, and I think that's the wrong way to look at this, because the answer's going to be "You never need the user's password, really," which is very misleading.  The reality is that  until Microsoft delivers (or you install third-party software to allow) a capability like *NIX's su/sudo, you'll never be able to perfectly imitate a user's account for all purposes while maintaining a semblance of sanity, without requiring occasional usage–note I didn't say "disclosure!"–of their password.
Comment: +1 - This answer nicely covers the realities, as well as the theory.
Comment: A very fair point. One point I was making in my own summarily deleted answer was that there appears to be a lack of tool support in this area.
Comment: on the point of sudo as far as that goes, the windows security model precludes the use of a sudo type utility, as it means you could run applications in the context of another user without authenticating as that user first (there are ways around it but they all make effort to go around the security model).
Answer: It is neither acceptable nor necessary for an administrator to request a user's password.
Under the circumstances where it may be necessary for an administrator to log in as a user (and I don't believe that such circumstances exist), the user should log in and supervise the administrator's activities.
The reason for this is accountability. It is the responsibility of each user to ensure that their password is secure. If malicious activity were traced back to a user's credentials, that user could be held accountable. Therefore they need to ensure that their credentials remain secure.
It is also the responsibility of the organisation to ensure that this is not only adopted, but enforced. There was a legal case where somebody in an organisation sent a malicious email using somebody else's mailbox. The owner of the mailbox was ultimately dismissed. While they argued that they had given their password to someone else, the company insisted that it was their responsibility to maintain the integrity of their credentials, and they were therefore accountable, as was dictated by their company IT policy. This was then overturned by a court when this user proved that there was a culture of password sharing endemic within the organisation. The court ruled that if the company could not be seen to actively enforce their IT policy, they could not rely on it for accountability under these circumstances.
That said there is clearly a gulf between theory and practice. I've contracted for a major multi-national firm that provides, amongst other things, IT advisory services, and as part of the documented procedure for an SOE upgrade we were instructed to request the end user's password.
Personally, I take a hard line approach to this. I don't believe that requesting passwords (or re-setting them to access a user's account) is necessary. If there is a vastly increased workload to get around this, then so be it. It's no excuse to compromise security. I guess I'm just fortunate that I'm not a manager, and so don't have to take responsibility for these decisions when instructed to do so by someone higher up.
Comment: Perhaps I wasn't clear. I'm taking a scientific approach. Just because the sun has risen every day for the past five billion years does not mean I can say with absolute certainty that it will rise tomorrow. But if you ask me, "will the sun rise tomorrow?", I will say yes without feeling the need to further qualify that. So I take your question regarding "every conceivable situation on the planet" to be an equally hypothetical and abstract qualification.
Comment: Are you seriously suggesting that you know what is acceptable or necessary in every conceivable situation on the planet?
Comment: off the to of my head new user setup comes to mind - and your mind obviously is stuck here. New user = "No user has the password", so IT sets up the user, then gives the user the password (who changes immediately). They never ask the user  because - ah the user at this point does not know the password.
Comment: Of course not - if somebody can give me an example to the contrary I'll happily accept it. I'm not talking about every conceivable situation on the planet, but with that said I cannot possibly conceive of any goal which is only achievable by compromising a user's login credentials.
Comment: You say "of course not", which completely invalidates the first sentence of your answer. I suggest you edit it accordingly.
Comment: there are a whole host of reasons to log in as a user without the  users knowledge or presence (off the to of my head new user setup comes to mind).  Logging in as a user doesn not compromise security so long as the access is traceable.  Taking the hard line, your theory is flawed and conclusion invalid.
Comment: Perhaps we need an ivorytower.stackexchange.com?
Comment: If "No user has the password" , IT should provide the user a "magic link" - a one time link to a place where the user can change the password for the first time, just once. If the user sees the link doesn't allow to change the password, someone has tampered with it so a new one has to be provided. If not, the user will use a password that IT doesn't  know aobut.
Answer: Many of us have worked in environments where password disclosure was required for various reasons. I'll even go so far as to say all of us consider it a bad idea. If such needs to be done, the end user needs to consent to it, not be coerced.
Back in the day, like 1998, my IT department used to request a user's password when we were doing a PC replacement so we could get it set up exactly like they had their old one. Down to the icon locations. As we were in a Novell NetWare environment with no corresponding WinNT domain, changing their network password didn't change their local password so we needed to have that password if we wanted to deliver that level of seamless service.
That was 13 years ago. You specifically asked about Windows Domains. At the job I just left, a large University, it was up to the end user whether or not to disclose a password or be there for whatever work was being done. In other words, the end-user opted in to it rather than forced by IT. Certain very busy executive-types high up the org-chart generally had their admin assistant log in for them so it was easy for IT people to slip in (consent had already been delegated).
In Windows, the only way to hand tune a user's Profile is to log in as that user. If that profile needs hand-tuning for some reason (a bad uninstall left remains that are getting in the way of a reinstall, or other weird stuff), the IT person will need to log in as that user. This can be done by forcing an administrative password change, having the user disclose their password, or having the user log the IT person in as themselves and letting the IT person work.
Comment: @IsaacTruett **Technically** everything can be done directly through regedit or hand-editing those desktop.ini files. However, a lot of IT people are far more comfortable with UI tools. As a short-cut, ill-advised though it may be, the IT person may ask a user to do any of the three things I mentioned (login for them, go through a password reset, or give the password) and use the tools they know well, the GUI.
Comment: @KCotreau @Isaac **Technically** you could copy their registry hive to the admin's profile temporarily, use whatever's necessary to edit it, then put it back. This is *Not a Good Idea™* in 99% of cases. I know of very few circumstances where knowing the users password is necessary these days; and all of them are related to *dumb* conveniences (like the Netware example SysAdmin1138 gave).
Comment: What sort of profile tuning could you do as the user that you couldn't do by modifying the default profile as described [here](http://support.microsoft.com/kb/973289) before the user logs in?
Comment: For the most part, no, there are still things that need to be configured for that specific user. For example, before Outlook 2007/Exchange 2007, you had to configure Outlook manually for that user. Now with autodiscover, you could possibly consider letting them try it themselves, but still, most administrators would not as users just want it to start when they log in.
Comment: @KContreau Microsoft says [here](http://office.microsoft.com/en-us/outlook-help/outlook-e-mail-profiles-explained-HA001147158.aspx) that Outlook profiles are stored in the registry, which an admin can edit from their own account. Any other ideas?
Comment: Issac, while it is stored in the registry, some of the settings are specific, and impossible to edit. You must log in as the user to let the program change them as you create their profile.
Comment: @KCotreau Can you backup your claim that a registry setting can be impossible to edit with a citation?
Comment: @sysadmin1138 Could I convince you to update the last paragraph of your answer to reflect your comment above? Otherwise, great answer. +1. Thanks!
Comment: Use the login script you joker!
Answer: Some applications during installation require the ability to make changes or reference the user's profile (i.e. CRM applications that integrate with Outlook) by use of environmental variables like %userprofile%, modifying HK_CURRENT_USER, and the like.
While you could certainly "reverse engineer" an installation with tools like procmon and then manually modify the user's profile, registry, etc. after the fact, this is highly inefficient, impractical, and error prone.
Comment: +1. I could definitely seeing this being a factor. As a software engineer, I would argue that there are better ways to write installation processes than to require the end user to be logged in during installation. There are, in fact, existing software products that allow for different single-user and multi-user installation processes, such as [Google Chrome](http://www.google.com/support/chrome/bin/answer.py?answer=118663).
Comment: @Isaac, I believe you have overlooked the fundamental principle of per user configuration, which cannot be taken care of by the installer. Take for example a package that's going to be used by multiple users on a given machine, where each user needs/wants/requires a different configuration and they need to be in place before those users start using the package.
Comment: @John/Isaac: I'm assuming, John, you're speaking of completing this customization on behalf of the user?  If so, yes, another good point for why you'd want or need to login as the user, especially if the configuration is not modifiable outside of the application (stored in a binary format) and is bound to the currently logged in user.
Comment: that is correct. Resetting the user's password in such a situation merely causes problems, as well as interferes with their ability to do whatever they are currently doing on another machine.
Answer: Absolutely 100% not. Anything that needs to be done with another users account should be done by resetting the users password, logging in, and then either having the user call the helpdesk or restting the password to something uthe users is told and setting the account to force password to change on next login.  While admit I've worked in fairly large and or secure environments disclosing your password to anyone was usually grounds for termination (and that should be the case in most situations)
Comment: That's too broad a statement. There are many environments where that just won't work. I'd go for maybe 98% but certainly not 100%.
Comment: @John Can you offer a specific example of something that is impossible to do without being logged in as the end user?
Comment: @Isaac: there are many applications that, during installation, reference %userprofile% for file placement, perhaps make changes like installing toolbars in Word or Outlook, etc.  Sure, you could sit there with procmon running, diligently record every registry, profile, etc. change, but why on earth would you bother?
Comment: @Jim, where I work we frequently need to log on as others and resetting passwords simply pisses people off without good cause. We have an environment where passwords (for most users) are not secret within the company. I know that goes against the grain for anyone who works in larger companies and it was a real culture shock for me when I started here. It's a management choice, not mine, and that's that.
Comment: @john, can you give me an example of where it would be impossible to reset the users password as explained?  I'd agree that there are places where users are too complacent or admins too lazy, but I've yet to encounter a place where that simply could not work.
Comment: @john, so in your case you always know the password (as they are not secret), you could reset the password, then set it back to the users non secret password when finished.  Admittedly it seems pointless in your scenario since passwords are public knowledge, but what reason would that not work?
Comment: @Jim, there's the problem of the user being affected as they will normally be working on another machine and/or need to log in elsewhere while I'm doing my thing on the target machine. I need to stress that the users have full knowledge that I'm logging in as them (very often at their request).
Comment: @john the only issue would be a user that logs out or locks their workstation then comes back while you are working on their account on a different workstation, but I agree that your circumstances probably preclude any security concerns by admins logging in as users.  I think however your circumstances throw security out the window.
Comment: @Jim, I couldn't agree more about the lack of security but my case does illustrate that, whether we like it or not, there are exceptions to every rule. Of course perimeter security is entirely another matter and is taken seriously.
Comment: @John, I don't think this exception disproves the rule, when you have a company clearly choosing to blatently ignore security (and if this was the US open up gobs of legal liability on the HR side alone) no normal policies apply.  Ignoring the fact that 2+1<>4 still leaves you 1 shy of 4.
Answer: Most of these posts seem quite old, but hopefully some knowledgeable folks are still active on the thread, since this would seem to continue to be a current topic.
Arguments certainly can be made that you shouldn't ever have to request a password.  I'd much prefer to tell my users "don't ever share"... and yes, configuration can in most cases be handled by an administrator for a user.  But troubleshooting is another affair.
We support a one-to-one program with 2600 students and 500 employees.  We address "weird" software problems on a daily basis.  It is quite often the case that we must experience the problem as the user in order to resolve the issue (or determine with some confidence that a reload is going to be needed).  Absolutely, we try to do this with the user present - but that isn't always practical; they have a schedule to maintain.
What about smartcards?  Is there any feasibility in a 2010/2012 AD Environment that a smartcard could be associated (temporarily) with a domain account?  This would permit access to the user's account in full reality, while not exposing their password specifically.  The card could then be deactivated when the troubleshooting was complete.  Technicians could utilize the account, but the cards could be well supervised.
We've used fingerprint readers for years, but the process for setting that up for a specific tech, then clearing that print simply isn't feasible.  I'm not sure how complex the process would be to "authorize" and then "deactivate" a smart card for a particular user would be, but it seems like it could be a decent compromise.
Comment: StackExchange operates on a different model than traditional forums in that this is not a discussion thread but rather a question followed by a selection of potential answers. On the downside this is also a poor example of a question per our [FAQ].
Answer: Yes: Anything that needs to be done to their profile. When that happens, you either must know their password, or set it, as you said. Then they can change it when you are done.
If you log in as that user, you are not giving them additional permissions. You are logging in as them with their permissions.
Comment: beat me to it.  Was thinking of applications that integrate with Outlook especially.
Comment: Yes, obviously you aren't giving the user extra permissions. The question is, what could an admin do with an individual user's permissions that they, the admin, couldn't do with their own admin permissions? So, what would an admin do to a user's profile that they couldn't do from their own admin account?
Comment: The answer to your question what can't the admin do: Simply log in as that user. When that user logs in, only then can changes be made to the profile that is associated with that user. When you log in as administrator, you log in with your administrator profile.
Comment: I thought I misread the question but no you do not need the users password to do anything to the profile.


How to filter taxonomy term in views from URL

Question: I am working on a travel website, and I made taxonomy with depth continent/country/city. I also have taxonomy locations restaurants, museums, nightlife... I have content types destinations and locations. I made a view from location content (all restaurants)
I would like to have locations filtered from destination taxonomy term in URL (e.g. destination/europe/france/paris to sort only restaurants from Paris, but destination/europe/france to list all restaurants from France).
Can anybody help?
Comment: have a look at my answer [here](http://drupal.stackexchange.com/a/82157/16739) might be helpful I think.
Comment: Please use the term name with depth module. It will provide the term name with depth option in contextual filter (Raw value from URL).
https://www.drupal.org/project/views_taxonomy_term_name_depth
Answer: The best way to do this is as follows:
Assuming you have fields in your content type for continent, country, and city: Add each of these fields separately in your view's Contextual Filters. You can leave them at the default settings for now.
Then, change your path settings for the page to one like such: destinations/% (the % will be replaced with your contextual filters).
After saving the view, you should then be able to visit a path such as destination/europe/france/paris OR destination/europe/france, granted you have content within those areas.
Comment: After re-reading your question, I totally missed that your are using taxonomy for the continent/country/city. Not exactly sure if the approach I listed above will work with taxonomy, but you can give it a shot. Sorry about that.
Comment: No, unfortunately it doesn't work this way. I want to achieve that when I set manual URL destinations/europe/france/paris for content about Paris, all the restaurants from Paris appear in block view. That block should appear only when the part of URL, in this case "paris", is matched with term "paris" in restaurant content taxonomy term.
Comment: I tried to make view block listing all locations content and than to add filter with taxonomy term witch would some how find term in row url separated with slashes. But, i suppose that Drupal use internal path and for some reason it cannot recognize my term or I'm making mistake somehow.


Applying Chebyshev's Bound

Question: I'm doing an exercise in randomized algorithms which is equivalent to the following:
Suppose we have pairwise independent events $X_1,\dotsc,X_n$ so that
$$\mathbb{P}[X_i] = 1 - \frac{1}{\alpha n}$$
for each $i$, where $0 < \alpha < 1$, $\alpha n \ge 1$. Use the Chebyshev inequality to show that
$$\mathbb{P}\left(\bigcap_{1 \le i \le n} X_i\right) \le \alpha$$
The following approach seems natural but gets stuck:
Let $\chi_1,\dotsc,\chi_n$ be the indicator variables corresponding to $X_1,\dotsc,X_n$. Then the event $\bigcap_i X_i$ occurs precisely when $\sum_{1 \le i \le n} \chi_i \ge n$. We have $E\left[\sum_i \chi_i\right] = n - \frac{1}{\alpha}$, so by Chebyshev's inequality, we have \begin{align}
\mathbb{P}\left(\bigcap_i X_i\right)
&=
\mathbb{P}\left[\sum_i \chi_i \ge E\left[\sum_i \chi_i\right]+ \frac{1}{\alpha} \right] \\
&<
\frac{E\left[\sum_i \chi_i\right]}{\alpha^{-2}} \\
&= \alpha^2(n - \alpha^{-1}) = \alpha(\alpha n - 1)
\end{align}
At this point it seems that I'm stuck, since $\alpha(\alpha n - 1) \le \alpha$ only happens if $\alpha n \le 2$. I don't see a way to get anywhere by splitting into cases based on whether $\alpha n \le 2$. What's the best way to proceed from here?
Answer: Let random variable $T_i$ be the indicator for event $X_i^c$ (the complement of $X_i$).  Thus $\mathbb P\left(\bigcap_i X_i\right)
= \mathbb P\left(\sum_i T_i = 0\right)$.  Now $T_i$ has mean $\mu = 1/(\alpha n)$ and variance $ 1/(\alpha n) - 1/(\alpha n)^2$,
and since the $X_i$ are pairwise independent the covariance of $T_i$ and $T_j$ is $0$ if $i \ne j$.  Thus $S = \sum_i T_i$ has mean
$\mathbb ES = 1/\alpha$ and variance $\sigma^2 = 1/\alpha - 1/(\alpha^2 n)$.
Now
$$P(S = 0) \le P(|S - \mathbb ES| \ge 1/\alpha)$$
so Chebyshev says
$$P(S = 0) \le \dfrac{\sigma^2}{1/\alpha^2} = \dfrac{\alpha n - 1}{n} < \alpha$$
Comment: Thanks! Should that last line read $P(S = 0) \le \dotsi$?
Comment: Corrected... thanks.

Applying Chebyshev's Bound


I've got an error while i was installing a newest php

Question: I was updating the PHP version to the newest in my CentOS server, following this guide step by step.  When I finally get to install PHP, I get the following error.
sudo yum install php53 php53-cli php53-common php53-devel php53-gd
-bash: sudo: command not found

Or just
yum install php53 php53-cli php53-common php53-devel php53-gd
-bash: yum: command not found

Can anyone help me?
(sorry for my bad english)
Answer: The error tells you what is wrong: You don't have the sudo command available.
Either the package is installed, but the binary is not in your $PATH variable, or you need to install it.
If you execute commands as the root user you don't need to run the command with sudo. You can use sudo to run as another user, specified with the -u USERNAME flag.
Comment: @Joele25 `su -` to root and run `yum install sudo` again.
Comment: Thanks for the answer, now the problem is that yum is not found too....
Comment: Yum and sudo commands dont works
Comment: @Joele25 Are you root? `su -` is not the same as `sudo`.
Comment: What is the output of `echo $PATH` ?  You probably don't have these commands in your path.
Comment: [root@euve21750 ~]# echo $PATH
//sbin://bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
Comment: @jscott I'm root
Comment: @Joele25 please run `whoami` to make sure you're root. You could also try the absolute path for yum. If I remember correctly that is `/usr/bin/yum`
Comment: It said that i'm root.. and the directorty /usr/bin/yum doesnt exist
Comment: You can try `rpm -qa | grep -i yum` to see if yum is still installed or `whereis yum` and `which yum` to see if there is any path information on where the binary is installed.
Comment: [root@euve21750 ~]# rpm -qa | grep -i yum
yum-metadata-parser-1.1.2-4.el5
[root@euve21750 ~]# whereis yum
yum:
[root@euve21750 ~]# which yum
/usr/bin/which: no yum in (//sbin://bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin)

... so yum is installed but i can run it
Comment: Are you sure it is installed? It seems to me there is only the yum-metadata-parser package. The empty result of `whereis` support that suspicion. Please try to reinstall the yum package manually(download the package and then afterwards install it via rpm)
Comment: Please I'm a real dumbass of Centos can you please tell me how to do it?
Comment: Please use Google for those easy tasks the next time. There are extensive tutorials on how to do those basic tasks, like this [How to install yum on a Virtual Server](http://wiki.centos.org/TipsAndTricks/BrokenVserver)
Comment: Ok, Thank you. But the question is how it is possible that i was running the yum command before and now i cant?


SVProgressHUD with query findObjectsInBackgroundWithBlock?

Question: I would like to make a SVProgressHUD with a parse query findObjectsInBackgroundWithBlock.
When I test, the hud is leaving 1 second after the view appears.
How can I make that the hud stay to the end of the query (I know it's a background query...) :/
What am I doing wrong ?
Any idea ?
Here is my code :
-(void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeGradient];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // time-consuming task
        [self loadShop];
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
    });
}

and Method :
-(void)loadShop {
    //    Configure Shop with Parse DB
    PFQuery *presentationText = [PFQuery queryWithClassName:@"presentationText"];
    [presentationText findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            self.presentationText.text = [[objects valueForKey:@"Text" ] objectAtIndex:0];
        }}];

    PFQuery *categoryQuery = [PFQuery queryWithClassName:@"Category"];
    [categoryQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            self.categoryLabel.text = [[objects valueForKey:@"Text" ] objectAtIndex:0];
            self.categoryLabel2.text = [[objects valueForKey:@"Text" ] objectAtIndex:1];
        }}];

    PFQuery *descriptionLabel = [PFQuery queryWithClassName:@"descriptionLabel"];
    [descriptionLabel findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            self.descriptionLabel.text = [[objects valueForKey:@"Text" ] objectAtIndex:3];
            self.descriptionLabel2.text = [[objects valueForKey:@"Text" ] objectAtIndex:0];
            self.descriptionLabel3.text = [[objects valueForKey:@"Text" ] objectAtIndex:1];
            self.descriptionLabel4.text = [[objects valueForKey:@"Text" ] objectAtIndex:2];
        }}];

    PFQuery *priceLabel = [PFQuery queryWithClassName:@"priceLabel"];
    [priceLabel findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            self.priceLabel.text = [[objects valueForKey:@"Text" ] objectAtIndex:0];
            self.priceLabel2.text = [[objects valueForKey:@"Text" ] objectAtIndex:1];
            self.priceLabel3.text = [[objects valueForKey:@"Text" ] objectAtIndex:2];
            self.priceLabel4.text = [[objects valueForKey:@"Text" ] objectAtIndex:3];
        }}];

    PFQuery *urlImage = [PFQuery queryWithClassName:@"urlImage"];
    [urlImage findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            self.imageButtonURL = [[objects valueForKey:@"URL" ] objectAtIndex:0];
            self.imageButtonURL2 = [[objects valueForKey:@"URL" ] objectAtIndex:1];
            self.imageButtonURL3 = [[objects valueForKey:@"URL" ] objectAtIndex:2];
            self.imageButtonURL4 = [[objects valueForKey:@"URL" ] objectAtIndex:3];
            imageButtonData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:self.imageButtonURL]];
            self.imageButton.imageView.image = [UIImage imageWithData: imageButtonData];

            imageButtonData2 = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:self.imageButtonURL2]];
            self.imageButton2.imageView.image = [UIImage imageWithData: imageButtonData2];

            imageButtonData3 = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:self.imageButtonURL3]];
            self.imageButton3.imageView.image = [UIImage imageWithData: imageButtonData3];

            imageButtonData4 = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:self.imageButtonURL4]];
            self.imageButton4.imageView.image = [UIImage imageWithData: imageButtonData4];
        }}];
}

Comment: you are using Blocks from parse. Start your SVProgressHUD before you are fetching objects. Stop it when it's finished.
Comment: @Anton It's not what I am doing here ? I start [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeGradient]; before fetching objects : starting my method loadShop... no ?
Comment: Create separated function with your progress hud starts with all settings inside. Run it before fetch started and simply stop it when it finished
Answer: you are using Blocks from parse. Start your SVProgressHUD before you are fetching objects. Stop it when it's finished.
example:
 PFQuery *priceLabel = [PFQuery queryWithClassName:@"priceLabel"];
//SVProgressHUD starts
    [priceLabel findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            self.priceLabel.text = [[objects valueForKey:@"Text" ] objectAtIndex:0];
            self.priceLabel2.text = [[objects valueForKey:@"Text" ] objectAtIndex:1];
            self.priceLabel3.text = [[objects valueForKey:@"Text" ] objectAtIndex:2];
            self.priceLabel4.text = [[objects valueForKey:@"Text" ] objectAtIndex:3];
//SVProgressHUD stops
        }}];

So you could start it when view will appear and stop it after last request done.
Comment: and last question (if you know, and if it's easy...), how to display progress with % on SVProgressHUD ?
Comment: You should check it on official doc on GitHub: If you'd like the HUD to reflect the progress of a task, use one of these:

+ (void)showProgress:(CGFloat)progress;
+ (void)showProgress:(CGFloat)progress status:(NSString*)status;
+ (void)showProgress:(CGFloat)progress status:(NSString*)status maskType:(SVProgressHUDMaskType)maskType https://github.com/TransitApp/SVProgressHUD


output to csv in a similar manner 'print' outputs to terminal?

Question: the logic included in my ruby code is a little difficult to translate into a csv output, is there a way to append each value in a similar manner that print works when outputting to the terminal?
cop_log is a hash of thousands of records
cop_log = { 'A1' => 'val1', 'B1' => 'val2', 'C1' => 'val3', 'D1' => 'val4, 'E1' => 'val5', 'F1' => 'val6', 'G1' => 'val7', 'H1' => 'val8', 'I1' => 'val9', 'J1' => 'val10, 'K1' => 'val11', 'A2' => 'val12', 'B2' => 'val13', 'C2' => 'val14', 'D2' => 'val15, 'E2' => 'val16', 'F2' => 'val17', 'G2' => 'val18', 'H2' => 'val19', 'I2' => 'val20', 'J2' => 'val21, 'K2' => 'val22'}

cop_log.each do |key, value|
  if key.include?('K')
    print "#{value}\n"
  elsif key.include?('A')
    print "#{job_number},#{pm_lookup[job_number]},#{value},"
  elsif key.include?('B') || key.include?('C') || key.include?('D') ||
        key.include?('E') || key.include?('F') || key.include?('G') ||
        key.include?('H') || key.include?('I') || key.include?('J')
    print "#{value},"
  end
end

currently outputs in the terminal like this, i want it to print to a csv in the same way:
val1, val2, val3, val4, val5, val6, val7, val8, val9, val10, val11
val12, val13, val14, val15, val16, val17, val18, val19, val10, val21, val22

reading the documentation it looks like the common route is to do the following,
CSV.open("path/to/file.csv", "wb") do |csv|
  csv << ["row", "of", "CSV", "data"]
  csv << ["another", "row"]
  # ...
end

unfortunately the structure of my code is going to make that a little difficult....
Comment: As we're learning APIs we tend to paint ourselves into corners and attempt to get out of a situation by wanting to change the API rather than our code. It's better to go with the flow and use the API as it intends. You'll find your code will be more readable. As written, your code isn't idiomatic and could be rewritten more clearly. I'd consider this an opportunity to refactor. As for your "question", you didn't ask one. We can guess you want help but it'd help us and others if you'd more clearly state your goals.
Comment: What do your `key`s look like? Are they single-letters you're matching, or are you trying to find letters inside a string? Please read "[ask]" and "[mcve]". We need minimal input data and the expected output.
Comment: thank you for your comments and answer, the keys are from a hash compiled out of an excel spreadsheet using the creek gem. an entire excel spreadsheet is inside my hash, the hash keys are each cell like A1, B1, C1, A2, B2, C2 etc. my code is sorting out each row. its for working with a specific excel file template used at a specific corporation. I will rethink my approach. @theTinMan
Comment: This information needs to be entered into your question as if you'd specified it initially. Edit the question, add the information where you would have so it all makes sense. Don't use "Edit" or "Updated" tags as we can tell what was added when using SO's edit history.
Answer: This is very confusing and, if cleaned up, would help make your code much more readable and maintainable:
if key.include?('K')
  print "#{value}\n"
elsif key.include?('A')
  print "#{job_number},#{pm_lookup[job_number]},#{value},"
elsif key.include?('B') || key.include?('C') || key.include?('D') ||
  key.include?('E') || key.include?('F') || key.include?('G') ||
  key.include?('H') || key.include?('I') || key.include?('J')
  print "#{value},"
end

What is key? A string of characters or a single character? If you're matching single characters you could do something like:
if key == 'K'
  print "#{value}\n"
elsif key == 'A'
  print "#{job_number},#{pm_lookup[job_number]},#{value},"
elsif ('B'.. 'J').include?(key)
elsif
  print "#{value},"
end

and even convert:
elsif ('B'.. 'J').include?(key)

to:
elsif ('B'..'J') === key

If you're searching for a character match inside strings:
if key['K']
  print "#{value}\n"
elsif key['A']
  print "#{job_number},#{pm_lookup[job_number]},#{value},"
elsif key[/[B-J]/]
  print "#{value},"
end

At this point you're ready to tackle cleaning up the CSV output. I'd recommend starting over using one of the basic examples of CSV output in the class documentation. I'd also recommend carefully reading "Comma-separated values" so you're more familiar with the expectations of a CSV formatted file.
(Note: At this point the input sample hash was added to the question showing the actual format of the keys.)
I'll let you figure out how to incorporate CSV, but meditate on this:
cop_log = { 'A1' => 'val1', 'B1' => 'val2', 'C1' => 'val3', 'D1' => 'val4', 'E1' => 'val5', 'F1' => 'val6', 'G1' => 'val7', 'H1' => 'val8', 'I1' => 'val9', 'J1' => 'val10', 'K1' => 'val11', 'A2' => 'val12', 'B2' => 'val13', 'C2' => 'val14', 'D2' => 'val15', 'E2' => 'val16', 'F2' => 'val17', 'G2' => 'val18', 'H2' => 'val19', 'I2' => 'val20', 'J2' => 'val21', 'K2' => 'val22'}
cop_log.values.each_slice(11) do |slice|
  puts slice.join(',')
end

# >> val1,val2,val3,val4,val5,val6,val7,val8,val9,val10,val11
# >> val12,val13,val14,val15,val16,val17,val18,val19,val20,val21,val22

You need to rely on the CSV class to create CSV files; The format isn't as simple as it seems.

Here's a first pass of how I'd write the code:
require 'csv'

cop_log = { 'A1' => 'val1', 'B1' => 'val2', 'C1' => 'val3', 'D1' => 'val4', 'E1' => 'val5', 'F1' => 'val6', 'G1' => 'val7', 'H1' => 'val8', 'I1' => 'val9', 'J1' => 'val10', 'K1' => 'val11', 'A2' => 'val12', 'B2' => 'val13', 'C2' => 'val14', 'D2' => 'val15', 'E2' => 'val16', 'F2' => 'val17', 'G2' => 'val18', 'H2' => 'val19', 'I2' => 'val20', 'J2' => 'val21', 'K2' => 'val22'}

job_number = 1
pm_lookup = [0, 1]

CSV.open('./foo.csv', 'w') do |csv|
  cop_log.group_by{ |k, v| k[1] }.values.each do |row|
    csv << [ job_number, pm_lookup[job_number], *row.map{ |k, v| v } ]
  end
end

After running, foo.csv contains:
1,1,val1,val2,val3,val4,val5,val6,val7,val8,val9,val10,val11
1,1,val12,val13,val14,val15,val16,val17,val18,val19,val20,val21,val22

We don't know what your expected output is, since you didn't tell us, but you could work from that code and figure it out.
Here's a break-down of the preprocessing of the data:
cop_log.group_by{ |k, v| k[1] } # => {"1"=>[["A1", "val1"], ["B1", "val2"], ["C1", "val3"], ["D1", "val4"], ["E1", "val5"], ["F1", "val6"], ["G1", "val7"], ["H1", "val8"], ["I1", "val9"], ["J1", "val10"], ["K1", "val11"]], "2"=>[["A2", "val12"], ["B2", "val13"], ["C2", "val14"], ["D2", "val15"], ["E2", "val16"], ["F2", "val17"], ["G2", "val18"], ["H2", "val19"], ["I2", "val20"], ["J2", "val21"], ["K2", "val22"]]}
       .values # => [[["A1", "val1"], ["B1", "val2"], ["C1", "val3"], ["D1", "val4"], ["E1", "val5"], ["F1", "val6"], ["G1", "val7"], ["H1", "val8"], ["I1", "val9"], ["J1", "val10"], ["K1", "val11"]], [["A2", "val12"], ["B2", "val13"], ["C2", "val14"], ["D2", "val15"], ["E2", "val16"], ["F2", "val17"], ["G2", "val18"], ["H2", "val19"], ["I2", "val20"], ["J2", "val21"], ["K2", "val22"]]]

In the code above I'm making sure the input is in an expected order, in this case I'm grouping by single-digit rows. More robust code would use \d+ instead of 1 and would also sort to force the appropriate order.
This is really important any time you're massaging data from one format into another for later reuse. While current Rubies guarantee that a hash will maintain its insertion order, it's not a good practice to assume since old versions of Ruby didn't do that, and other languages you port the code to might not maintain order. Instead always program defensively, making sure you're going to return consistent results. To what extent you do that is something you'll learn when you find out a previous attempt wasn't enough. Programming is fun that way.
Finally, any time your code feels awkward or isn't flowing it's time to back up and look at what you're doing.
Comment: unfortunately each key is a letter number pair, it comes directly out of an excel spreadsheet, A1, B1, C1, A2, B2, C2 etc, thank you for the response though
Answer: Couldn't you do this?
CSV.open("path/to/file.csv", "wb") do |csv|
    cop_log.each do |key, value|
        if key.include?('A')
            csv << [ job_number, pm_lookup[job_number], value ]
        elsif key.include?('K') || key.include?('B') || key.include?('C') || key.include?('D') ||
            key.include?('E') || key.include?('F') || key.include?('G') ||
            key.include?('H') || key.include?('I') || key.include?('J')
            csv << [ value ]
      end
    end
end

Answer: def write_csv(cop_log, io = $stdout)
  cop_log.each do |key, value|
    if key.include?('K')
      io.print "#{value}\n"
    elsif key.include?('A')
      io.print "#{job_number},#{pm_lookup[job_number]},#{value},"
    elsif key.include?('B') || key.include?('C') || key.include?('D') ||
          key.include?('E') || key.include?('F') || key.include?('G') ||
          key.include?('H') || key.include?('I') || key.include?('J')
      io.print "#{value},"
    end
  end
end

Then
File.open('path/to/file.csv', 'w') do |f|
  write_csv(cop_log, f)
end

Answer: re fector the code
    CSV.open("test.csv", "ab") do |csv|
      b = {}
      check_num = 0
      cop_log.each do |key, value|
        num = key.gsub(/[^\d]/, '').to_i
        next if num < 8 ||
                key.include?('L') || key.include?('M') || key.include?('N') ||
                key.include?('O') || key.include?('P') || key.include?('Q') ||
                key.include?('R') || key.include?('S') || key.include?('T') ||
                key.include?('U') || key.include?('V')
        a = { key => value }
        b.merge!(a)
      end # end of each loop
      i = 8
      while ((b.length / 9) - 7) > i do
        csv << [ job_number, pm_lookup[job_number], b["A#{i}"], b["B#{i}"],
                b["C#{i}"], b["D#{i}"], b["E#{i}"], b["F#{i}"], b["G#{i}"],
                b["H#{i}"], b["I#{i}"], b["J#{i}"], b["K#{i}"] ]
        i += 1
      end
    end # end of CSV.open


MYSQL - Resultados mais recentes quando se agrupa por um certo campo

Question: Tenho as seguintes tabelas no meu banco de dados MYSQL
Tabela USUARIOS
id | login
---------------
1  | usuario1
2  | usuario2
3  | usuario3

Tabela STATUS
id | idUsuario | data                | status
1  | 1         | 2018-05-10 10:00:00 | a
2  | 2         | 2018-05-15 10:00:00 | a
3  | 3         | 2018-05-20 10:00:00 | a
4  | 3         | 2018-05-20 11:00:00 | d
5  | 1         | 2018-05-15 11:00:00 | d
6  | 3         | 2018-05-25 10:00:00 | a

Como faço uma pesquisa na tabela de STATUS agrupando por idUsuario e mostrando apenas mostrando apenas os registros onde o status com a data mais recente é igual a a
Esse é o resultado que desejo alcançar com esta query:
idUsuario | data                | status
2         | 2018-05-15 10:00:00 | a
3         | 2018-05-25 10:00:00 | a

Alguma ideia de como chego a esse resultado da forma mais eficiente possível?
Answer: Você pode fazer assim:
SELECT idUsuario, MAX(data), status FROM STATUS
WHERE status = 'a'
GROUP BY idUsuario;

Espero ter ajudado.
Comment: Obrigado por tentar ajudar... já tentei fazer algo parecido e não deu certo porque nesse caso, como você está dizendo no WHERE que quer registros com o status = 'a' ele vai mostrar o registo de id 1 na tabela de status quando ele não deveria pegar nenhum registro com o idUsuario = 1, sendo que eu desativei o usuario 1 cinco dias e uma hora depois que ele foi ativado.


Juntar vários arquivos mp3 em um único arquivo mp3

Question: Olá! Eu gostaria de criar um programa (em linguagem C ou outra capaz) que receba como entrada um texto e me devolva como saída uma música.
Para isso eu precisaria de um arquivo texto (.txt) onde eu precisaria fazer a leitura do mesmo e vários arquivos de áudio (.mp3) cada um deles com uma nota musical. Digamos que a letra A represente a nota Dó.mp3 a letra B presente a nota Lá.mp3 a sequência das letras A e C a nota Ré.mp3.
A leitura do arquivo pra mim não seria um problema a minha dificuldade é em juntar esses arquivos .mp3 de acordo com a sequencia do texto e transformá-los em um único arquivo .mp3
Eu simplesmente não sei por onde começar. Já conversei com alguns professores mas ninguém sabe como fazer. Então eu pergunto pra vocês:
Como eu faço para juntar vários arquivos mp3 em um único arquivo mp3? Vocês podem me indicar algum caminho (sites, livros, cursos, etc)?
Comment: Te dei uma resposta com o caminho das pedras, não é simples de usar samples pré gravados para o que vc quer, decodificar e codificar arquivos mp3 é um porre, se seu projeto aceitar samples .wav seria um facilitador, particularmente eu partiria para outro caminho, eu acho mais interessante sintetizar todas as notas de acordo com as entradas de seu .txt, vc entraria com as notas(frequências) e a duração de cada uma, vc poderia sintetizar as entradas usando seno ou cosseno ...
Comment: Realmente a sua pergunta está ampla. Você já tem uma resposta excelente do colega @ederwander (embora não seja numa das linguagens que você solicitou), mas eu ainda sugiro que você edite a sua pergunta para deixar ela mais focada. Pode começar definindo a linguagem (C e C++ são distintas - afinal vc quer em C ou em C++?), e pode também deixar pra lá toda essa questão de ler as notas do arquivo. O seu problema parece ser mesmo como juntar dois arquivos de áudio em formato mp3.
Comment: Ainda assim, se você deseja "compor" músicas usando notas musicais, há outras formas possíveis. Você não precisa ler um arquivo de áudio comprimido com cada uma das notas e juntá-los, você pode simplesmente *emitir* tais notas. Dependendo da biblioteca ou SO que você usa, existem funções como o [Beep](https://msdn.microsoft.com/pt-br/library/windows/desktop/ms679277(v=vs.85).aspx) que te permite definir a frequência e a duração [de uma nota](http://www.amattos.eng.br/Public/INSTRUMENTOS_MUSICAIS/Textos/Div/notas.htm). Ou, tendo os mp3/wave, basta você tocá-los na sequencia, sem juntar.
Answer: É possível de se fazer em qualquer linguagem, mas não é tão simples :-(, você vai precisar decodificar o áudio e armazenar de forma pura dentro de um vetor ou matriz, o processo lógico é:

Decodificar o primeiro arquivo .mp3
armazenar o áudio decodificado em um Vetor de N posições
Decodificar o próximo arquivo .mp3
Concatenar o novo vetor decodificado no final do outro vetor
fazer isso e um loop até terminar de ler todos os arquivos do seu .txt
Codificar o vetor para .mp3

Decodificar .mp3 é bem complexo, se insistir em usar C eu recomendo que você link seu projeto com uma lib específica capaz de fazer decode, já usei bastante o libmad pra fazer coisas parecidas em C, talvez seja mais fácil você fazer o mesmo processo usando .wav pois para decodificar e codificar é mais simples ...
Em Python2.7 pode ser relativamente simples decodificar .mp3 usando o Pymedia
import pymedia.audio.acodec as acodec
import pymedia.muxer as muxer

name='Sia - Chandelier.mp3';

name1= str.split(name,'.')

if name1[ -1 ].lower()  == 'mp3':

    dm= muxer.Demuxer( name1[ -1 ].lower() )
    f=open(name, 'rb' )
    dec= None
    s= " "
    sinal=[]
    while len( s ):
        s= f.read( 4096 )
        if len( s ):
            frames= dm.parse( s )
            for fr in frames:
                if dec== None:
                    dec= acodec.Decoder( dm.streams[ 0 ] )
                r= dec.decode( fr[ 1 ] )
                if r and r.data:
                    din = np.fromstring(r.data, dtype=np.int16)
                    sinal.append(din)

O vetor/lista sinal vai conter o áudio Sia - Chandelier.mp3 totalmente decodificado, tudo que você precisa fazer agora é ir concatenando cada arquivo lido no final do vetor sinal, por fim vc deve codificar o vetor sinal para arquivo .mp3, vc precisa de algo parecido com isso para efetuar o encode:
# Open muxer and encoder

          if enc== None:
            params= { 'id': acodec.getCodecID(type),
                      'bitrate': bitrate,
                      'sample_rate': r.sample_rate,
                      'channels': r.channels }
            print 'Encoder params:', params
            mx= muxer.Muxer( type )
            stId= mx.addStream( muxer.CODEC_TYPE_AUDIO, params )
            enc= acodec.Encoder( params )
            fw= open(fOutput, 'wb')
            ss= mx.start()
            fw.write(ss)

          enc_frames= enc.encode( pack("%dh"%len(sinal), *(sinal)) )
          if enc_frames:
            for efr in enc_frames:
              ss= mx.write( stId, efr )
              if ss:
                fw.write(ss)

Se fosse totalmente em .wav isso poderia ser feito em poucas linhas usando python, espero que isso te dê um norte!
Comment: Excelente! Vai me ajudar muito!


Error when using nginx in docker as reverse proxy to external sites

Question: I am running nginx on ubuntu server, I have it configured as a wildcard SSL frontend proxy to various other services in my network. I port forward 443 on my router to nginx only, I use dynamic DNS to configure various hosts to point to my router IP, and for each host I forward to the respective internal server.
This is pretty standard stuff, and works very well, e.g. I expose my security camera NVR, UniFi controller, Plex, etc.
I am in the process of converting my setup to docker, and with nginx as a proxy I ran into a problem:
[emerg] 1#1: host not found in upstream "plex.home.foo.net" in /etc/nginx/nginx.conf:80

I found many many references to this "host not found in upstream" error when running nginx as a reverse proxy in docker, with a variety of solutions, most dealing with proxying to other containers, but none that I can get working.
E.g. add an explicit resolver to point to docker google DNS, "resolver 127.0.0.11", did not make a difference.
E.g. use a variable instead of a FQDN, but nginx does not support variables in "proxy_redirect default" blocks.
E.g. pass in the host name as a parameter "--add-host="plex.home.foo.net:192.168.1.47", but that defeats the purpose of DNS.
E.g. use static IP's instead of FQDN's, but that defeats the purpose of DNS.
E.g. https://github.com/nginxinc/docker-nginx/issues/78
Before I spend too much time on this, anybody using nginx as a reverse proxy running in docker but proxying servers outside of docker?
Snippet from nginx.conf:
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";

server {
    listen 443 ssl;
    server_name xprotect.foo.net;

    location / {
        proxy_pass http://xprotect.home.foo.net:8081;
        proxy_redirect default;
        proxy_redirect http:// $scheme://;
    }
}

Comment: Would software like [Squid](http://www.squid-cache.org/) be more appropriate for what you're trying to achieve?
Answer: Thanks John for pointing me here:
https://development.robinwinslow.uk/2016/06/23/fix-docker-networking-dns/
nginx.conf resolver did not work:
resolver 192.168.1.1;

Docker DNS option did work:
--dns=192.168.1.1


Do capable harmony singers sing in just intonation or tempered tuning?

Question: I understand that the mathematical frequency ratios between certain intervals will correlate with the overtones that are present when a note sounds in a fundamental frequency.  Certain predictable overtones will occur naturally at frequencies that are integer multiples of the fundamental note.
Sound waves produced by musical instruments (including the voice) translate into corresponding vibrations in the basilar membrane and other mechanical components of the inner ear.  These vibrations produce their own overtones that work the same way as a plucked string on a musical instrument - producing certain predictable overtones in our auditory system that are integer multiples of the fundamental.
A perfect fifth in just or pure tuning based on the harmonic overtone series would obviously be more naturally consonant because the vibrations set off in the inner ear would flow together and not beat against one another.  So theoretically, tuning to the perfect integer multipliers which match the harmonic overtone series would yield a more pleasing harmonious blending of notes than say equal temperament tuning of modern instruments.
I know that equal temperament tuning is a compromise to allow fixed tuning instruments such as a piano or guitar (with intervals determined by fret spacing - bending of notes notwithstanding) to be played in any key without being terribly out of tune in any one key (only slightly out of tune in every key).  But tempering the tuning literally means stretching or shrinking the intervals such that they are no longer truly consonant and some dissonance is interjected by necessity.
I will acknowledge that it is likely that as we grow up listening to "out of tune" equal temperament tuned music - we develop a tolerance for and acceptance of it (some may argue even a preference for it but that is highly debatable).   However, it seems to me that perfect consonance in keeping with the pure harmonic overtones, would naturally and instinctively be more pleasing to our ears without the need for (and in spite of) conditioning.
Given that the human voice is capable of microtonal adjustments to an infinite degree and not limited by the fixed tuning imparted upon an instrument such as a piano - I am wondering if singers who harmonize with the lead vocalist subconsciously adapt and instead of singing a equal tempered third or fifth actually sing something closer to a justly intoned harmonically natural interval.
If this does occur, it might help explain why some singers sound so incredible  harmonizing together.  I have been privileged to hear some performances where the vocal harmonies actually gave me shivers up and down my spine and seemed to touch my soul with their sensual richness.
Have there been any studies (or is there compelling evidence) which attempt to ascertain if trained and capable singers who sing harmony - instinctively gravitate towards pure intonation verses singing the notes they have learned to associate with equal temperament tuned instruments?  In other words if they are singing a fifth above, would the instinctive control center of their brain override their musical training and adaptation and lead them towards singing a perfect natural fifth or would they sing something closer to a equal tempered fifth that a piano would play?
If some do and some do not, have any studies attempted to determine if there is a clear listener preference for pure harmonies vs. harmonies based on adapted and learned tempered tuning?
My personal hypothesis is that pure and natural harmonies that approximate the frequencies found in the harmonic overtone series would provide a more enjoyable listening experience unless said harmonies clashed directly with equal tempered tuned accompanying instruments.  In many cases the vocals (including harmony) are not sung in unison with chords or corresponding melody notes.
But it still may work better in a cappella singing (such as a trio or quartet).
But I will defer to the more educated music theorist and trained practitioners in the SE community for a more accurate assessment.
Comment: Pretty sure that violins will stray from 12tet into pure intonation, especially when there's no reference to 12tet.
Comment: I think it is virtually impossible to _not_ sing pure/just intervals when harmonizing, at least as long as you listen more to the other singer/singers than any accompanying (ET) instrument. It is simply a matter of gravitating towards the beatless interval.
Comment: A singer who is singing through Auto-Tune, which is almost everyone these days, is not equivalent to a fretless instrument at all, and their minor thirds will always be the same minor third.
Comment: This is one of the big things that makes autotune sound noticeably bad. The intervals in harmonies are not "humanized". There's also formant shifting, but even minor tuning adjustments to "perfectly" fit ET can take away from a harmony part that has a lot more flavor to it.
Comment: Even with instruments that are thought of as usually tempered, we often make a conscious decision against perfect equal temperament - e.g. stretch tuning on a piano, or tuning a guitar for a particular song so that a certain voicing of the tonic chord sounds best, rather than to allow harmonic movements that that song doesn't actually make.
Comment: *Tuning* denotes a static property, which in my opinion does not apply to singing and fret-less string instruments (as long as no open strings are involved). One would typically deviate all the time, e.g. making major thirds a bit larger, leading-tones higher and so on. So I expect in the best case a probabilistic answer of limited value.
Comment: I saw a "making of" clip for a movie once where John Williams was conducting the choir - he gave them a short but very technical sounding direction to reduce beating. A very interesting insight into recording a large choir... (I **believe** he was telling them to aim for just intoned intervals, though those were not the words he used.)
Comment: Definitely correct. Reposting myself from another comment:

I was a pianist for 12 years, even learned to tune pianos and set a temper by ear, before taking up singing and joining choirs:

1. Singing solo acapella, I sing tempered. As per piano memory.
2. With even ONE other voice, if there's no instrumental, *we* inevitably fall into just tuning.
3. Add a piano or organ  and *we* all fall into tempered.

All happens with no thought or effort other than listening as we sing. Most don't hear it. Even I can only hear it if I listen for it very carefully (while not singing.)
Answer: I wish I could point you to some scientific studies; I cannot. But I can speak on the basis of a lifetime of my being a semi-professional traditional choral singer and soloist who has a university music school degree in singing. I have extensive experience with a cappella choral singing, with singing accompanied by piano and organ and orchestra, and even with singing with Baroque and Renaissance groups whose instrumental accompaniment uses different historical temperaments other than the modern 12-tone equal temperament.
It's pretty simple. If a group of singers sing a cappella, they sing in pure, just intonation which is adjusted constantly throughout the piece, measure-by-measure and chord-by-chord. That is why a professional a cappella choir will sound wonderfully in tune at every given point in a long piece of music, yet at the conclusion of the piece they might discover that they are quite a few cents away from the base pitch or key that they started on. This is because all the just intonation intervals don't add up to whole numbers.
If, on the other hand, a choir or even a vocal soloist sings with a piano, organ, guitar or harp, they automatically adjust their intonation to the 12-tone equal temperament (or other historical temperament) provided by the accompaniment.
However, to my perpetual astonishment, I have learned from experience that most singers, even some highly-accomplished professional ones, are not even intellectually aware of the distinction between just intonation and 12-tone equal temperament, and are not consciously aware of making adjustments between one scheme and the other. None of us singers do any of the mathematical calculations based on physics or musicology. It's just something we all learn to do informally and by ear.
Human singers are not taught to think of their voices in terms of the physics of the tension applied to vibrating strings or the tuned resonance of open or closed pipes. They just sing pitches and use their ears and their brains to observe and adjust to what is in tune and what is not, given the current context of the music and of the instruments being used to accompany that particular piece.
I will also observe, however, that everything that I've said above about singing in choirs also applies not to singing groups but to purely instrumental ensembles such as string quartets and string orchestras, small brass ensembles, and other instrumental ensembles that do not involve any keyboard instruments or instruments with fixed temperament -- when they play amongst themselves, they always modify their intonation toward pure just intervals. When the ensemble plays with a piano, they modify their pitches to line up with the intonation of that piano. That is, if they are very good musicians.
Comment: When I was in a pop-punk band singing harmonies along with guitar and bass, I noticed that we were constantly adjusting very slightly to try to find the best sound between matching each other and matching the instruments (which are not perfectly equal tempered in the first place!) One song we did had a long harmony held at the end of the song when all the music has stopped. We would adjust our harmony (without even thinking about it) as the guitar chords died away and end up with a just interval at the very end. I think with enough singing it becomes natural and no thought is required.
Comment: @ToddWilcox interesting observation.  I have noticed the same thing.  Sometimes my band will sing a chorus a cappella and the singers sort of adjust to one another (but not sure if it's to pure intervals) until it sounds great.  We have occasionally hit a magic spot on the last you... ..... in Amie by Pure Prairie League.
Comment: That makes sense Wheat.  I used the words "subconsciously" and "instinctively" in my question on the supposition that what you believe may in fact be correct.  I have a daughter who was a a gifted singer in Chorus from Elementary school through College and she could sight read music on paper and sing the written notes.  She was graded during auditions for All State Chorus and apparently was able to sing what the examiner expected.  I just don't know if she was singing the notes in the frequency that the piano reproduced or keeping the intervals between notes close to just intonation.
Comment: "We would adjust our harmony (without even thinking about it)"  I think it can all be summed by saying "They sing in tune."
Answer: You're not the first person to ask this question. A study done by Lottermoser and Meyer in 1960 found that professional choirs tend to sing the major thirds sharp and the minor thirds flat, thus veering toward Pythagorean rather than just intonation.
An octave or fifth can be tuned easily using the common overtones of the two notes to be sung. Thus, with competent choirs, these intervals tend to be just or nearly just (an equal-tempered fifth is only 2 cents away from just).
With thirds, by contrast, the common overtones are higher and weaker, so the tuning is much more susceptible to cultural conditioning. Western music since the Baroque features the dramatic contrast of major and minor, and it makes sense for the major and minor third over a common root to be farther apart than the 71-cent just interval. String players tend to play leading tones (which are a certain subset of major thirds) sharp, so that they tend tensely toward their tonics. Such practices are easily taken up by singers today.
By contrast, keyboard instruments in the Renaissance were most often tuned to some variant of meantone temperament, with low major thirds and high minor thirds, an aesthetic consistent with a performance practice where the difference between G and G# was inconsistently notated and often left to the singer. The same aesthetic persists among players of traditional Arabic music, who have been known to complain about the high major third of the Western piano. Since Arabic music is primarily monophonic with stepwise melodies, it seems that nearer equality of the seconds may be the driving factor there, not justness of the thirds (especially since some Arabic scales feature microtonal seconds and thirds with no just basis). In short, the human ear is capable of accepting a wide range of tunings of thirds.
Answer: The top barbershop quartets very specifically use just intonation as well as vowel modification to maximize overtone ringing. And it's likely that other top a cappella groups veer in that direction, some by instinct and others deliberately.
But the average a cappella choir likely can't tell the difference between just and well tempered intonation. Lots of studies of pitch perception show that singers are given latitude by listeners for being "in tune." I've sung in, directed, and listened to thousands of a cappella groups and sadly being just "in tune" by any definition as a group is a notable accomplishment!
Answer: An extract from an interview from Ross Barbour of the Four Freshmen...

"If my note was a major seventh, I could sing it on top of the note — sing it sharp, you might say, so it and the tonic note became a little less than a half-step apart. That's what makes it buzz in your ear.
If we wanted a dominant seventh to ring, we'd sing it on the bottom of the pitch — especially if the voice leading was going down through that dominant seventh.
A major third should be sung brightly on top of the pitch, and a minor third should hang on the bottom.
We were singing those notes not because they were written and the piano said the pitch was "there." We sang them because they harmonized. They made overtones in our ears.
And we didn't discover some great breakthrough in harmony. Good barbershop singers do it all the time; in fact singers have been doing it since at least the year 1700."
Comment: Singing major thirds on top of the pitch, and minor thirds on the bottom, is an effective means of melodic expression- but it's even more out of tune with the harmonic series than equal temperament.  If you listen to good barbershop quartets, you will hear that they pitch their major thirds lower than equal temperament.  But you are right about the dominant seventh- putting it low puts it close to the real blue note, the 7/4 interval.
Answer: With tempered instruments came Bach's music, it unleashed a ton of creativity. But it caused a lot of resistance; most thought it sounded out of tune, they were used to just intonation.
It can be shown both mathematically and in practice that tempered intervals cause a beating or ringing effect, independently of the instrument's overtones. This is particularly noticeable with the major thirds, that are pretty far off when tempered. Great musicians manipulate pitch to minimize this beating effect on harmonic intervals. This creates a larger contrast with the dissonant harmonies, where some kind of beating effect is inevitable.
But writing and performing music with just intonation can be a lot harder, and requires many complex musical decisions. For example it would support two different types of dominant sevenths, the regular one coming from just scale and the more stable 4-5-6-7 pitch ratio. They both sound in tune, but serve different purposes. If you're Jacob Collier that's probably in your skill set toolbox already, but for most musicians it requires a lot more training and work.
Comment: Nobody was tuning keyboard instruments in just intonation in the 16th or 17th centuries.  It's not possible to play music of that time with such a keyboard.  They were using different temperaments that did not support every key, and around Bach's time temperaments closer to equal came into use, but it was not the sharp change implied in this answer.
Comment: He didn't write that they were using keyboards in just intonation; he wrote 'they were used to just intonation'
Answer: I disagree with your premise that a mathematically perfect tuning would be somehow preferable and that singers would naturally gravitate towards that.
Singing is a learned behavior. We gravitate towards tunings and scales that are familiar from our experience. If I grow up singing along with a piano in common tuning, playing major and minor scales, and then I sing a cappella, I'm going to sing major and minor scales in common tuning.
Auto-Tune has been almost as popular as reverb for some time now, and we see examples of young singers who sound Auto-Tuned even without Auto-Tune. They grew up hearing singers sing only a handful of very strictly tuned notes on a very tight grid, and that is what they sing back to the world.
Singers don't exist in isolation. The fact that pianos or guitars were tuned a certain way and/or play certain scales causes the singers to be tuned that way and sing those scales. It's a question of culture, not math.
Comment: So you are saying that two singers harmonizing would _not_ sing the pure (beatless) intervals but somehow manage to sing in 12TET? I also believe that the auto-tune "sound" is mostly due to the timbral change caused by the software when it corrects a note and this is what singers mimic, not the tuning it imposes.
Comment: What a good singer does with regard to intonation varies with the contexts of different pieces of music that are being sung. A good singer can choose between just intonation and 12-tone equal temperament at will. The singers in an *a cappella* choir can choose to exist in the isolation of just intonation, and in the same concert they can sing accompanied by a piano and shift gears into 12-tone equal temperament.
Comment: @SimonWhite, as a lifetime semi-professional choral singer and vocal soloist with a university degree in singing, I disagree with your premise. All singing can be infinitely microtonal in nature. Good singers can control microtonality well, and poor singers cannot.
Comment: Following the logic of this answer:  if I grow up singing along with a piano that has one note (lets say F# above middle C) which is out of tune then I am going to learn a completely different tuning for the scale of C major from that of the scale of G major.

I seriously doubt that this would be the case, although I can't actually point you towards any evidence to back me up on this.
Comment: I was wondering if that was the case Simon.  That's why I posted the question - to see if it's actually been studied using something like a spectrum analyzer applied to a recording of the performance or during the live performance.  In the absence of such a scientific analysis, its really impossible to say that you are right or wrong and it's possible that some singers do exactly as you say while others (perhaps because they don't have the skill to replicate what they hear in the instruments) instinctively gravitate towards a pure interval vs. the pure note they hear on piano.
Comment: When a singer trains do they need to sing intervals against another voice to hear and adjust for the beating? It seems easier (to me) to hear the beating when the same instruments are used. Just wondering how singers learn this.
Comment: I disagree with this answer, but your argumentation is reasonable. In particular, when someone always practises by singing along with auto-tuned recordings, it does seem plausible that they'll end up "fixing" those 12-edo intervals in their vocal chords. However I don't think this has been happening previously. The reason: singers generally don't perform unison with a 12-edo instrument. Rather, the 12-edo instruments will just lay down chords or perhaps counterpoint. But the best way to intonate to a 12-edo major chord does not necessarily use the frequency of the major third in that chord.
Comment: @leftaroundabout  Good point and I agree.  That's why I stated in my question that "In many cases the vocals (including harmony) are not sung in unison with chords or corresponding melody notes".
Comment: I was a pianist for 12 years, even learned to tune pianos and set a temper by ear, before taking up singing and choirs:

1. Singing solo acapella, I sing tempered. As per piano.
2. With even ONE other voice, if there's no instrumental, *we* inevitably fall into just tuning.
3. Add a piano or organ  and *we* all fall into tempered.

All happens with no thought or effort other than listening as we sing. Most don't hear it. Even I can only hear it if I listen for it very carefully (while not singing.)


How to add a point on the y-intercept (y-axis) using ggplot2

Question: I have a scatter plot where the y-axis scaling changes at a certain point to plot data with some extreme values. I'm trying to add some sort of visual cue on the y-axis that indicates that the scaling changes at the point.
Here's an example of a plot
library(scales)
library(ggplot2)

set.seed(104)

ggdata <- data.frame('x' = rep('a',100),
                     'y' = c(runif(90, 0, 20), runif(10, 90, 100)))

transformation <- trans_new(
  "my_transformation",
  transform = function(x) ifelse(x <= 30, x / 5, (x - 30) / 20 + 30 / 5),
  inverse = function(x) ifelse(x <= 30 / 5, x * 5, (x - 30 / 5) * 20 + 30)
)

ggplot(data = ggdata) +
  geom_jitter(aes(x = x, y = y)) +
  scale_y_continuous(trans = transformation, breaks = c(0, 10, 20, 30, 50, 70, 90, 110))

I want to add some marker to "tick 30" on y axis for scale change.
I was thinking of adding a double tick on the axis, but there is no linetype that looks like a double line. The product should look something like this. I'm aware of transforms like scale_y_log10, but I'd rather work with custom scaling that dynamically changes with the data.
EDIT: per @Tjebo's suggestion, I used annotate to add a "=" to the y axis breakpoint:
library(scales)
library(ggplot2)

set.seed(104)

ggdata <- data.frame('x' = rep('a',100),
                     'y' = c(runif(90, 0, 20), runif(10, 90, 100)))

transformation <- trans_new(
  "my_transformation",
  transform = function(x) ifelse(x <= 30, x / 5, (x - 30) / 20 + 30 / 5),
  inverse = function(x) ifelse(x <= 30 / 5, x * 5, (x - 30 / 5) * 20 + 30)
)

mybreaks <- c(0, 10, 20, 30, 50, 70, 90, 110)
tick_linetype <- rep("solid", length(mybreaks))
tick_linetype[4] <- "blank"

ggplot(data = ggdata) +
  geom_jitter(aes(x = x, y = y)) +
  annotate(geom = "point", shape = "=", x = -Inf, y = 30, size = 3) +
  scale_y_continuous(trans = transformation, breaks = mybreaks) +
  theme(axis.ticks.y = element_line(linetype = tick_linetype)) +
  coord_cartesian(clip = 'off')

Comment: Here are some related topics: https://stackoverflow.com/questions/7194688/using-ggplot2-can-i-insert-a-break-in-the-axis
Comment: @bs93 Thank you for the link. I guess producing two plots with & without the extreme values could be a solution. I'd like to see a way incorporate all information in one plot though. I'm working with genetic data so I would have tens of thousands of data, so the table wouldn't be an effective method. To be precise, the "scatterplot" I'm working wtih is a manhattan plot, and I'd like to see the distribution of lower -log10(pval) as well as the extreme values
Answer:
I was thinking of adding a double tick on the axis, but there is no
  linetype that looks like a double line.

You can use any character as point shape. Also an equal sign, or back slash, etc.
For example:
library(scales)
library(ggplot2)

set.seed(104)

ggdata <- data.frame('x' = rep('a',100),
                     'y' = c(runif(90, 0, 20), runif(10, 90, 100)))

transformation <- trans_new(
  "my_transformation",
  transform = function(x) ifelse(x <= 30, x / 5, (x - 30) / 20 + 30 / 5),
  inverse = function(x) ifelse(x <= 30 / 5, x * 5, (x - 30 / 5) * 20 + 30)
)

ggplot(data = ggdata) +
  geom_jitter(aes(x = x, y = y)) +
  annotate(geom = "point", shape = "=", x = -Inf, y = 30, size = 8, color = 'red') +
  scale_y_continuous(trans = transformation, breaks = c(0, 10, 20, 30, 50, 70, 90, 110))+
  coord_cartesian(clip = 'off')

I removed the clipping, but you can also leave it. The color was just chosen for highlighting.
Or, even better, use text annotation. You can then also change the angle - kind of nice.
ggplot(data = ggdata) +
  geom_jitter(aes(x = x, y = y)) +
  annotate(geom = "text", label = "=", x = -Inf, y = 30, size = 8, color = "red", angle = 45) +
  scale_y_continuous(trans = transformation, breaks = c(0, 10, 20, 30, 50, 70, 90, 110)) +
  coord_cartesian(clip = "off")

Created on 2020-04-21 by the reprex package (v0.3.0)
Comment: Yes thank you! This is the closest to what I've been looking for. I had no idea that I could set `x` in `annotate()` to `-Inf`, let alone including it does not change the overall x scale.
Answer: I cannot get the exact look that you linked to, but perhaps some of these ideas are useful to you.
You can make your specified value a minor break, and add a line only to minor breaks (here I was unable to pick the exact value of 20, since that was already a major break, but perhaps you can play around with the numbers to get something you like):
ggplot(data = ggdata) +
  geom_jitter(aes(x = x, y = y)) +
  scale_y_continuous(trans = transformation, minor_breaks=20.05,breaks = c(0, 10,20, 30, 50, 70, 90, 110))+
  theme(
    panel.grid.minor.y = element_line(1)
  )

Another option is to change the labels themselves. Here I have bolded and wrapped in () the 20 value, but you can add other symbols as well:
ggplot(data = ggdata) +
  geom_jitter(aes(x = x, y = y)) +
  scale_y_continuous(trans = transformation, minor_breaks = c(0, 10, 20, 30, 50, 70, 90, 110),
                       breaks  = c(0, 10, 20, 30, 50, 70, 90, 110), labels=c(0, 10, expression(bold(("20"))), 30, 50, 70, 90, 110))

You can add a segment to the plot, which here isn't the prettiest option since the x axis isn't continuous, but perhaps it will spur ideas:
ggplot(data = ggdata) +
  geom_jitter(aes(x = x, y = y)) +
  scale_y_continuous(trans = transformation, breaks = c(0, 10, 20, 30, 50, 70, 90, 110))+
  geom_segment(aes(x=-.01,y=19.5,xend=.01,yend=20.5),size=1.5)

Perhaps you could also just shade the bottom (or top) portion of your plot:
ggplot(data = ggdata,aes(x = x, y = y)) +
  geom_jitter() +
  scale_y_continuous(trans = transformation,breaks = c(0, 10,20, 30, 50, 70, 90, 110))+
  annotate("rect", xmin = .4, xmax = 1.6, ymin = 0, ymax = 21,
           alpha = .2)

Comment: Thank you for your thoughts Dylan. In fact, we've had similar ideas :) ! Adding a horizontal line could cause some confusion just because I already have dashed lines indicating the p-values. For now, I've colored the axis red at the "break point". Although it doesn't intuitively say that the scale changes at that point, but it still stands out. I still think having a "/" or "X" mark on the axis would be more visually alarming.
Comment: @J.Lee, I just had an additional thought, where you could shade one area. This may not be too ugly with other lines, etc. in the plot. See the revised answer.
Answer: This solution should help with how you want your axis to look like. FWIW I would like to caution against breaking axes unless you explicitly tell your audience about them. In the code below I created two plots, one is for the data below 30 and the other data is for the extreme points (and remove its x axis and labels). Then I use plot.margin to set the plots margins so that they overlap a bit when I put them in a grid.arrange. You might have to mess with the margins to get the labels to line up.
library(scales)
library(ggplot2)
library(gridExtra)
set.seed(104)

ggdata <- data.frame('x' = rep('a',100),
                     'y' = c(runif(90, 0, 20), runif(10, 90, 100)))

p1 <- ggplot(data = ggdata) +
  geom_jitter(aes(x = x, y = y)) +
  scale_y_continuous(breaks = seq(0,30,5), limits = c(0,30))+
  theme(plot.margin=unit(c(0,.83,0,1), "cm"))

p2 <- ggplot(data = ggdata) +
  geom_jitter(aes(x = x, y = y)) +
  scale_y_continuous( breaks = seq(60,100,10), limits = c(60,100)) +
  scale_x_discrete()+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),
        plot.margin=unit(c(0,1,-0.1,1), "cm"))

grid.arrange(p2,p1)


Finding the maximum of a function $f(x)$ without analytically evaluating $f'(x)$

Question: I'm an experimental physicist, trying to automate a relatively simple (but sensitive) optimization in my measurements that is currently done completely manually and takes up a lot of my time. I figure that machine learning should have ample tools for what I need to do, but my knowledge is quite limited and Google isn't helping me thus far. I've taken away all of the physics/measurement related details and distilled the following scenario, which I hope is general enough.
There is some function $f(x)$ that I want to maximize. However, I can only evaluate $f(x)$; I cannot evaluate its derivative explicitly. Moreover, I cannot sample a large range of $x$; if $f(x) < {\rm threshold}$, I am in trouble (and it takes me over a day to recover). Luckily, I have one starting value $x_0$ for which I know that that $f(x_0) > {\rm threshold}$ even before evaluating, and I can guess some initial step size $\varepsilon$ for which $f(x_0 + \varepsilon) > {\rm threshold}$ will also hold (however, I don't know if $f(x_0 + \varepsilon) >$ or $< f(x_0)$ before evaluating). In addition to that I know that the function is roughly parabolic. Could someone suggest an algorithmic / adaptive / feedback protocol to find the $x$ that maximizes $f(x)$ up to some tolerance $x_{tol}$? Note that evaluating $f(x)$ is somewhat costly, but that is not my primary concern at this stage.
So far I've found the golden-section search, but that requires choosing some range $(a,b)$ over which you want to maximize which I cannot do; I can't start from some wide range as that might bring me below my tolerance, and I can't figure out #x_T$, the $x$ for which I go below my tolerance, without actually evaluating. Another option would be something like a gradient descent using finite difference for the derivative, but that sounds quite inefficient?
For context, how I currently do it manually is as follows: I evaluate $f(x_0)$ and then $f(x_0 + \varepsilon)$. If this leads to a decrease, I evaluate $f(x_0-\varepsilon)$ instead. Based on the gradient (essentially I just look at if there are large changes in $f(x)$ w.r.t its distance from the threshold I cannot cross), I either increase or decrease $\varepsilon$ and continue searching in the same direction until a maximum is found, which I notice because $f(x)$ starts decreasing. I then go back to that maximum. This way I am always probing the top part of the maximum and thus remain in a safe range.
Comment: Is there a problem with numerically computing an approximation of the gradient $\frac{f(x+\epsilon)−f(x)}{\epsilon}$ (besides risk of evaluating below threshold)? Is f(x) smooth? (If not, you can still use sub-gradient.) Convex? Continuous? A complete mess?
Comment: The solutions here area all relevant https://stats.stackexchange.com/questions/193306/optimization-when-cost-function-slow-to-evaluate/193310#193310
Comment: It's approximately a parabola, which should indeed help. I'll add that to the main post. The problem with numerically computing the gradient is only that it's slow and probably not very accurate, I figured fancier methods might be out there, but indeed it can be done.
Comment: I based my idea of it being a bad idea on the discussion in https://www.reddit.com/r/MachineLearning/comments/2e8797/gradient_descent_without_a_derivative/ which I perhaps should not take as gospel.
Answer: What you're looking for is a derivative-free optimization method, and what you're describing as your current method is basically a pattern search. In one dimension (it sounds like you're x is one-dimensional but correct me if I'm wrong) a pattern search is pretty efficient and I don't think there is really any way to do it better. If your concern is that you want to implement this in programming code to automate it, then that's definitely possible (and you'll be able to find implementations of pattern search in many programming languages), but it will not (I think) be more sophisticated than what you came up with yourself.
Comment: That's great! I'll have a look at this for sure.


Where does a host app handle NSExtensionContext#completeRequest?

Question: When you call completeRequest(returningItems:completionHandler:) from an extension, where does this get handled by the host app?
Answer: Disclaimer: did not checked my assumptions, but may be this helps.
1) documentation states:

Call the completeRequestReturningItems:completionHandler: method,
  which signals the host app that its original request is complete

2) here - Figure 2-3 shows that "Host"-app - is app that starts some work with extension. For example, "Host" may be the app in which user touches "Share"-button. Then this "Host"-app sends some data (which user wants to share) to extension.
3) "Sharing data"-extension, I think, very common example of extension. So very probable that somewhere in UIActivityViewController must be way to realise completeRequest(returningItems:completionHandler:) that you looking for and that called from extension.
And this is what I found:
@property(nullable, nonatomic, copy) UIActivityViewControllerCompletionWithItemsHandler completionWithItemsHandler NS_AVAILABLE_IOS(8_0); // set to nil after call

documentation says about this property:

Upon the completion of an activity, or the dismissal of the activity view controller, the view controller's completion block is executed.

and:

returnedItems -
  An array of NSExtensionItem objects containing any modified data. Use the items in this array to get any changes made to the original data by an extension

Again, I did not test it. But this property looks like handler you looks for.
Comment: Ah ok so maybe it's only used in the case that your extension uses a share sheet?
Comment: I would say: seems `returnedItems` are used by host app in case that your extension launched by host app via share sheet.
Is this case _only_ or there are some other cases - I don't know.
Apple [describes](https://developer.apple.com/library/archive/documentation/General/Conceptual/ExtensibilityPG/) about 19 extension types for iOS. May be extension launching classes for extensions of some other types have callbacks for `returnedItems` too.