Solving nonlinear 1D advection pde with MoC

Question: I would like to solve the 1D nonlinear advection equation with the method of characteristics. Here is my notation:
\begin{equation}
\begin{cases}
\rho_t + (1+\rho)\rho_x = 0\\
\rho = \rho(x,t); \quad \rho(x,0) = \frac{1}{1+x^2}
\end{cases}
\end{equation}
What I have been up to is the following, using the parameter s:
\begin{align}
&\frac{d\rho}{dt} = \frac{dx}{ds}\frac{\partial \rho}{\partial x} + \frac{dt}{ds}\frac{\partial \rho}{\partial t} = 0\\
\Longrightarrow \; & \frac{dt}{ds} = 1 ;\quad  t(0)=0 \; \Longrightarrow \; t=s \\
\Longrightarrow \; & \frac{d\rho}{ds} = 0 ;\quad \rho(0)=\rho_0 \; \Longrightarrow \; \rho = \rho_0 \\
\Longrightarrow \; & \frac{dx}{ds}=1+\rho= 1+\rho_0 ;\quad x(0) = f(\rho_0) \; \Longrightarrow \; x = (1+\rho_0)s + f(\rho_0)
\end{align}
So that I end up with
\begin{equation}
    f(\rho) = x - (1+\rho)t \; \Longrightarrow \; \rho = F(x - [1+\rho]t )
\end{equation}
I tried to apply several techniques I found to find the solution of the above Riemann problem using the method of characteristics. I have the general form of the solution as F but I would like to have the analytic solution for this case so I can plot for several times and see the shockwave.
Note: This problem comes from this online document, chapter 11.
Comment: You must provide a condition on the "inflow" boundary, for instance $\rho(0,t)=1$. If you just want to visualize the solution I can provide two lines of Wolfram code that will do the trick.
Comment: I think you haven't used the initial condition on $\rho$ yet, which yields $\rho_0 = \frac{1}{1+f(\rho_0)^2}$?
Comment: As J.Jacquelin did below, using the unitial condition on $\rho$ leads to a cubic equation that I have no idea how to solve.
Answer: Your calculus is correct. You found the general solution :
$$\rho=F\left(x-(1+\rho)t\right)$$
Condition :
$$\rho(x,0)=\frac{1}{1+x^2}=F\left(x-(1+\rho)0\right)=F\left(x\right)$$
The function $F$ is determined :
$$F(X)=\frac{1}{1+X^2}$$
We put this function into the general solution where $X=x-(1+\rho)t$
$$\rho=\frac{1}{1+(x-(1+\rho)t)^2}$$
This is the solution on implicit form.
In order to obtain the explicit solution, solve the cubic equation for $\rho$ :
$$(1+(x-(1+\rho)t)^2)\rho-1=0$$
ADITION after the discussion in comments.
There is no difficulty to plot the figures that you saw in the document :
https://courses.physics.ucsd.edu/2011/Spring/physics221a/LECTURES/CH11_SHOCKS.pdf
For exemple, to plot the curves corresponding tu figure 11.1 :
$$x=(1+\rho)t\pm\sqrt{\frac{1}{\rho}-1}$$
Plot the two branches with signs $+$ and $-$.

Inverse the axis if you want it in the standard position.
Comment: Thamks for answering. I actually came to the same conclusion a few minutes ago. My next problem is when I'm computing the $\delta = b^2 - 4ac$ of this equation, which sign is undetermined because, well, in (x,t) parameters are supposed to be both varying parameters and though $\delta$ is not a scalar but a space of solutions.
Comment: Apologies, I had a slightly different in mind indeed.. Still you are right, the formula cannot be written explicitly.
Why I would like to have a explicit formula is to plot the solution for several time step to compare with what is shown in the book I mentionned.
Another contributor kindly proposed a Wolfram code to do that but I wanted to do it on gnuplot or python. You know, the old way..
Comment: There is no need for an explicit formula to plot $\rho(x,t)$ as a function of $t$ for given $x$. Compute the formula of $t$ as a function of $\rho$ which is an explicit equation. Plot $t$ as a function of $\rho$ with $t$ on horizontal axis and $\rho$ on vertical axis.
Comment: If I rewrite the equation as
\begin{equation}
\frac{1}{\rho}-1=[x−(1+ρ)t]^2
\end{equation}
Then I cannot isolate t from ρ because of the square
Comment: Here the advection velocity depends on $\rho$ itself, which is the problem when I look for an explicit analytic solution. Perhaps I should quit looking for a beautiful formula, but do you have an idea of how they did in fig. 11 of the book to plot the solution ?
Comment: $$t=\frac{x-\sqrt{\frac{1}{\rho}-1}}{1+\rho}$$
Comment: @Dash. I cannot understand why you don't know how to plot the figures corresponding to those of the book. It is very easy. For example, see the addition to my main answer.


Does natural amplification TRULY exist in acoustics or does it have to be turned into an electrical signal first?

Question: I have seen people claim these two scenarios as being possible acoustic amplifications. My question is, are they TRULY amplification or are there any other types of acoustic amplification in existence.

An acoustic megaphone (is it amplification or just a focus of the sound?)

Singing in a chapel (is the sound amplified or is it just reverb and delay)

So, is amplification actually even possible in acoustics or does it have to be turned into an electrical signal first?
Note: I understand the definition of acoustic is not having electrical amplification. I'm not sure how to word it other than "amplification of air", and I'm not sure if that is correct either. If someone can edit it for me or tell me how to fix the terminology please let me know. Thanks.
Comment: **Comments have been [moved to chat](https://chat.stackexchange.com/rooms/150231/discussion-on-question-by-lecifer-does-natural-amplification-truly-exist-in-acou); please do not continue the discussion here.** Before posting a comment below this one, please review the [purposes of comments](/help/privileges/comment). Comments that do not request clarification or suggest improvements usually belong as an [answer](/help/how-to-answer), on [meta], or in [chat]. Comments continuing discussion may be removed.
Answer: Previous answers have already elaborated how mechanical means can improve the efficiency of sound transfer from source to ears (or transfer from vibration to sound). From deflectors, to horns to sound boards to tin-can-telephone-toys. What they have in common, is that the perceived sound is louder than without, but they do not add energy into the systems. That puts practical limits on the amount of amplification.
Electric solutions (mic/pickup + amp + speaker) can also make sound louder, but they insert extra energy (the amp draws power). There are fewer practical limits here: You can blast a full Wembley stadion with the sound of a single needle drop.
There are, however, also non-electric means to amplify sound by injecting extra energy. In the early 1900's they had gramophone players with pneumatic amplifiers. The sound is amplified through valves, powered by compressed air. I'm pretty sure that the same principle could be used for a compressed-air-powered megaphone
See also http://www.vias.org/crowhurstba/crowhurst_basic_audio_vol1_028.html
Answer: An example of actual amplification (rather than just impedance transformation like most acoustic string instruments do, i.e. leading to much reduced sustain times of concert acoustic guitars compared to electric guitars) would be the amplification of free and forced reed vibrations (harmonica, accordion, reeded organ pipes, reed and brass instruments), namely the amplification of a small primary oscillator by letting it control the passage of a compressed air stream.
The energy of the amplified sound comes from the compressed air, not the primary oscillator (that actually gets its energy from the same source).
Comment: In addition to playing, I've spent VERY much time thinking about harmonicas and would claim to know how they work. I know that it's the airstream that's making the sound, and that the frequency is determined by how fast the reed opens and closes the airway. Further, I'm a certified radio amateur, so I know a little about electric oscillators and amplifiers. Yet, I never thought about harmonicas as amplifiers before now. This is great!
Answer: According to the law of conservation of energy you can't amplify sound without an energy input.
What you can do is concentrate the sound locally in one direction using a megaphone at the cost of reducing the sound output in other directions.
Comment: Even though sound boards and resonant bodies used in chordophones do not add total energy, we still call them "amplifiers". The *acoustic* energy put out by a vibrating guitar string in free space is much lower than the *acoustic* energy of the same string vibrating with one end connected to a guitar body. Kinetic energy is changed into acoustic energy by the guitar top and body. The acoustic gain of the top and body is greater than 1, so it is an acoustic amplifier.
Comment: @Lecifer No, your examples are not amplification, neither are wind instruments.
Comment: @ToddWilcox we call it amplifier by convention, but the word is misleading. In terms of physics, it's actually wrong. Strings have little effect on sound and acoustic energy, because they have a very small surface affecting the air, and a lot of their kinetic energy may be dissipated by the parts that keep the string in place (eventually transforming it in small amounts of heat). When at least one of those parts allows transfer of kinetic energy, then we have a better acoustic energy performance because the dissipation has a longer run: the bridge, then the sound board, and finally the air.
Comment: So it is amplification just that it isn't anywhere close to as powerful as it can be once turned to electricity? And are brass or like woodwind instruments technically amplification as well? Basically, are there any instances of very loud amplification in air or is that as loud we can get.
Comment: **Comments have been [moved to chat](https://chat.stackexchange.com/rooms/150208/discussion-on-answer-by-piedpiper-does-natural-amplification-truly-exist-in-acou)**; please continue this interesting discussion there.
Answer: Adding on PiedPiper's answer, energy must be conserved. Acoustic "amplification" is, as already stated, focusing the energy in one direction but also (the point of this answer) to do acoustic impedance adaptation between the medium creating the sound (tube, string) and the open air. That's for instance the purpose of parabolic shapes of horns but also what is done with the sound tables of string instruments.
Comment: +1 for mentioning impedance matching. Increasing coupling efficiency of energy already there rather than adding more energy.
Answer:
Does natural amplification TRULY exist...?

If we replace the word "natural" (since it's not clear what that means in this context) with "non-electrical", then the answer is definitely:
Yes
Discussions of conservation of energy and/or requirement of the input of additional (i.e., non-signal) energy are irrelevant, since the word "amplifier" is used in engineering contexts to refer to devices that do not use an additional source of energy to increase the strength of the input signal.
The category of non-electrical amplifiers relevant to sound and music are called mechanical amplifiers. A very simple non-resonant mechanical amplifier is a lever. In a lever, input force and displacement are coupled to output force and displacement such as either the force is amplified at the cost of displacement or vice-versa. Despite the fact that no additional energy is added to the system beyond the "input" energy, a lever is considered a mechanical amplifier.
Another type of mechanical amplifier that is clearly relevant to acoustics is the resonant amplifier. Soundboards and bodies of string instruments combine resonant and non-resonant mechanical amplification.
While some may disagree that the definition of "amplifier" should include passive devices (i.e., no non-signal energy is added), it is clear that such devices are called "amplifiers" in many contexts. One particular example is the following quote from the Wikipedia page on mechanical amplifiers:

No new energy is created. However, through mechanical amplification, more of the available power spectrum can be utilised at a more optimal efficiency rather than dissipated.

https://en.wikipedia.org/wiki/Mechanical_amplifier
Comment: I concur with your explanation, but, at the same time, we could call the same amplifier device as an attenuator, if we consider the other involved component (without mentioning other energy transfers, like heat). For instance, we can cut paper closer to the fulcrum of a scissor either to get more power, or to get less and more precise movement. And your last quote is straight to the point: *efficiency*. An acoustic "sound amplifier" doesn't really amplify the sound (as opposed to a *real* amplifier), it transmits it more efficiently, *through* mechanical amplification, preventing dissipation.
Comment: Throw in constructive interferance too. Not sure why this whole Q&A lost its mind, but the comments sections are in dire need of moderation.
Comment: @Yorik I understand resonance is the result of constructive interference.
Comment: @ToddWilcox However, not all constructive interference is resonance...I think...
Answer: As the other stated, you can't make energy out of nothing.
In addition to the two mechanisms you listed (focusing the sound towards the listener and adding reverberation), I would add one more: increasing the efficiency of transferring the vibration to the air. Many of the common sound sources don't do it well naturally.
For example, a moving string creates a slight overpressure in front of it, and a slight underpressure behind it. As the string has a very small diameter, these two regions are very close to each other, and the two resulting sound waves in opposite phases almost entirely cancel each other. This is why an electric guitar without amplification is so quiet. In a classical or acoustic guitar the string vibrations are transferred to the body of the instrument, which is large and much more efficient in transferring the vibration to the air. But this still cannot be called an amplification, as this efficiency is never greater than 100%, i.e. the amount of the sound energy cannot exceed the work performed by the musician to pluck the string.

So, is amplification actually even possible in acoustics or does it have to be turned into an electrical signal first?

What you certainly do need is an additional source of energy. In an electric amplifier you draw this energy from the electrical outlet. I don't know if non-electrical amplifiers were ever made, but in principal no laws of physics forbid it.
Consider pipe organ. A musician presses the key, they allow the air to flow through a pipe. The sound energy can be much larger than the work the musician did to press the key. This is because the energy comes from an air pump, which is powered by a separate motor, or a human assistant, rather than the fingers of the musician. This is an example of purely mechanical amplification of energy. This is not really sound amplification, as the sound is produced only in the "amplifier", not before it, but I hope it can be an inspiring example of amplification that doesn't require electricity.
Answer: On the basic assumption that 'amplification' means making a sound louder, then, no, a sound doesn't need to be turned into an electrical signal first.
What's needed is an 'acoustic amplifier'. Consider a tuning fork: in open air, very quiet, placed on a table, for example, much louder - amplified. A solid electric guitar, with a slab for the body; against a round hole acoustic guitar. A trumpet mouthpiece which then gets attached to the rest of the pipework, particularly the bell. A drum head compared a complete drum. A megaphone compared to just a voice.
Al those devices are amplifiers without using an electrical signal. Even the design of a church or cathedral will bear in mind these factors, and try to amplify the sound source at the pulpit, for example.
Answer: The term "amplification" in acoustic context is ambiguous and often misleading. While it is widely used and accepted, it's not correct: you can use it, but with awareness.
You are having correct doubts about aspects related to electric amplification, and, interestingly enough, you are involuntarily getting to the point: it doesn't really matter if we're talking about sound or electricity.
Sound is still energy.
To extend what correctly pointed out in other answers, since energy is always conserved (in some form), it cannot be created from nothing, but must be transferred ("added") in some way, so that the original vibrations can be amplified.
In order to amplify something, you always need to add energy from somewhere else.
Electric (real) amplification
Let's take the example of voice amplification (instead of stringed instruments with sound boards, I'll explain why later).
A microphone is an electrical device that transforms kinetic energy of a membrane (that moves following the vibrations in the air) into changes in an electric current: when there's no air pressure, there is no passage of current, when the pressure increases, more current passes through it. Since sound is based on variations of pressure (including negative pressure) over small amounts of time, you get lots of changes in the current.
This is an oversimplification, but try to follow me anyway.
Then that current comes and returns through a powered circuit that is able to multiply (amplify) it. For instance, if it gets current 1, it becomes 4, if it gets 2 it becomes 8, if it gets 0, it remains 0.
Finally, that current goes to a speaker, that works like an inverted microphone, transforming electric signals into kinetic energy: more current, more pressure. And the resulting sound is much louder than the original.
Acoustic attenuation
Before going on on the concept of "natural amplification", let's understand what actually happens whenever we hear a sound.
As we all know, physical sound is an abstract concept that, for us humans, is the result of variations of air pressure in time. We need to have frequent changes in air pressure in order to perceive sound, and we need something that alters those pressure changes.
When some object is in contact to the air and that object starts to "vibrate", changes in its physical displacement create pressure waves that may eventually arrive to our ears.
Pressure changes expand radially in waves from their origin point (the classic pebble in the pond example), and eventually dissipate after some time, possibly transforming the kinetic energy into thermal energy in the meantime.
If the waves encounter a different pressure (like a harder surface), they may be reflected back in the opposite direction, meaning that a certain point may receive back a wave similar to one they already got.
But if the waves encounter a surface that is able to absorb ("stop") that kinetic energy, those waves are easily dissipated. That energy doesn't disappear, it is normally transformed in small amounts of heat.
An electric guitar has a fixed body that absorbs most of the vibrations of the strings, meaning that most of the potential energy that could eventually be transmitted from those strings is practically nullified. The pick-up is able to transform a small part of the energy of the vibration (causing changes in the magnetic field) into an faint but sufficient electric signal, usually between 100 and 300 mV.
Acoustic ("natural") amplification
Simply put: it doesn't exist. That's because, in normal conditions, no energy is being added. If you want "more sound", it means that you want "more energy", but, as said above, you cannot create energy from nothing.
So, how is it possible that, with the same sound source, we can get "louder" sounds?
The reason is that "acoustic amplifiers" are, in reality, energy transformers and better energy "conductors". They are more efficient in transforming and propagating the original vibrations (including those of physical objects like strings).
When you get a louder sound, you're not getting more energy than originally produced, but more of the originally produced energy, which is otherwise dissipated in other ways as explained above (heat).
The acoustic megaphone
An acoustic megaphone just redirects the acoustic energy in a focused direction.
Imagine somebody speaking in a direction in an open, flat field, and you standing a few meters behind them.

when they speak, you will probably hear them somehow clearly;
when speaking into the megaphone, keeping it close to their face, you will hear them much less than before; if there is a vertical obstacle large enough (like a building) a few meters in front of you, you'll hear the reflected sound much more clearly;

That's because when the megaphone is put right in front of their mouth, the sound is forced to a specific direction.
It would be almost the same as they were speaking with their mouth next to a hole in a wall: if you're standing behind them, you'll hear almost nothing, but if you're on the other side of that hole, you'll hear them very clearly.
Sound in a chapel or church
Again, not amplification.
Chapels and churches are large structures with big and very reflective surfaces (concrete walls/domes/arches, glass windows, marble floors, etc) that are both flat and curved (concave): a flat surface reflects sounds in the opposite direction, while a concave curve focuses it.
The sum of that combination results in focused sounds easily reflected by flat surfaces, and since some of those reflections arrive at very close intervals, you get a "louder" sound because of the sum of those vibrations arriving almost at the same time.
One common effect of similar structures is that known as "whispering-gallery waves": when one whispers in a very specific point of the structure, that whisper can be clearly heard at another very specific point which is sometimes quite far away, even if, in normal condition, that distance wouldn't allow the listener to hear the original sound as clearly.
Concert halls
The concept is similar to that of churches, but with less reverberation: the sound waves are better and uniformly propagated in the whole space, allowing audiences to clearly hear any sound coming from the stage even at 30-40 meters away. Specific architecture elements are used to provide better sound propagation, including special panels put on walls or hanging from the ceiling, shaped in ways that improve sound reflections.
Sound boards
Most of the sound of instruments having sound boards doesn't come directly from the strings, but from the vibrations of the sound board itself.
The vibration of the strings passes through elements that are able to resonate (vibrate at similar frequencies): the bridge, the sound/soul post, and the sound board itself.
The hollow space, type of materials and their thinness used in sound boards all contribute in a better efficiency of sound propagation, due to their matching the acoustic impedence. Simply put: they are able to get a better performance of the kinetic energy coming from the vibration of the strings, transforming most of it in air vibrations instead of dissipating that energy.
Pneumatic amplification
There are other ways of amplifying sound, not involving electricity. As it's now quite clear, we still need power coming from another source, though.
One example is the pneumatic amplifier.
It used a simple mechanism: a diaphragm put at the end of a "microphone" cone would transmit the vibration through a valve, put within a channel that had pressurized air coming from a pump: the increased air pressure, finally exiting through an output cone, made the sound much louder than its original source. It obviously wasn't very accurate, but the concept was quite ingenuous.
Here is a diagram of its mechanism.
Comment: @ToddWilcox Voltage amplifiers increase voltage but also reduce current. A mechanical amplifier (like a lever) can only increase *one* component, while losing the other: it's either force or displacement. The amplitude of the vibrations (the kinetic energy) is not increased, it's transmitted more efficiently instead of being absorbed by the dampening (small amounts of thermal energy) or by vibrations that have insufficient areas or mechanical properties to cause any resonance, possibly decreasing the frequency in some way or, again, transforming it into thermal energy.
Comment: @ToddWilcox I agree that the definition of "amplifier" might not be very strict, but note that the passive component used to increase the voltage is commonly called a transformer, not amplifier.
Comment: "In order to amplify something, you always need to add energy from somewhere else." - I guess this is the same assertion you've made in a comment. Do you have a source for this? You mention acoustic/mechanical impedance matching devices that do not add energy and therefor you do not call them amplifiers, but there are passive electronic devices that do impedance matching and have a voltage gain greater than unity - so they are voltage amplifiers. Are you asserting that such devices are *not* amplifiers even though they have a gain greater than 1?
Comment: @ToddWilcox As pointed in other comments, we could have different levels of the concept of "amplifier". I admit, I should rephrase the last part and be more specific: *in terms of physics* (thus, considering all forces in a closed system), it's not correct. A "voltage amplifier" is a known and accepted concept, but it is also based on the awareness that electricity has two fundamental components: current and power. In reality it's not a real amplifier, it's a transformer: its very definition assumes that the output impedance is lower than that of the input.
Comment: The problem here seems to be hinging on definitions.  A lever can amplify one of displacement or force, at the expense of the other.  What is not amplified is work, which is the product of the two.  (Nor power, which is the time derivative of work.)  The same is true of electrical analogs, like voltage and current.  For _sounds_, however, amplification usually requires additional energy to be put into the system, usually electrical.  One can argue that a mechanical phonograph can be amplified by using a stronger motor and a heavier needle, adding more mechanical energy into the system...
Comment: This article, and more directly its cited sources, contradicts your assertion that the word "amplifier" is only used for systems that add total energy to the input: https://en.wikipedia.org/wiki/Mechanical_amplifier
Comment: @ToddWilcox The resulting output energy is always the same: the energy caused by a vibrating string is not amplified. What makes an instrument sound "louder" is how efficiently the original vibration can cause resonation to other physical elements (for instance, the sound board) and finally the air. But there is no real amplification, because the initial forces cannot be higher: what we call acoustic amplification is more like a "lesser-dampening", or better resonation. A possibly related post: [How is energy conserved in resonance?](https://physics.stackexchange.com/q/231603).
Comment: Of course. Just because one part of a signal is diminished while another part is increased does **not** preclude a device from being an amplifier. If we required all components of the input to be increased in magnitude by a device in order to consider that device an "amplifier", then most active electronic amplifiers would not be worthy of the term.
Comment: A mechanical amplifier is also a known and accepted concept.
Comment: ...at least until mechanical destruction of the recording grooves results!  (We perceive sounds by the work done on our inner ears, through the medium of air.  Louder sounds require more work, once you've exhausted what you can do by improving efficiency and directionality of the original source.)
Answer: Most string instruments include a natural amplifier. As one example, the sound-board of a piano amplifies the sound of the string, which would be quite soft otherwise.
Comment: @PiedPiper The vibration of the strings creates the sound. The bridge transmits the vibration to the sound-board, which amplifies it.
Comment: @musicamante "from the physics point of view that's not the correct term" - can you please cite a source for this assertion? I've been looking for one on my own and haven't found it yet.
Comment: The resonance of the sound-board *creates* the sound, it doesn't amplify it.
Comment: @Aaron While we normally consider it amplification, from the physics point of view that's not the correct term. Vibrating strings alone have a defined amount of energy which cannot be "amplified" (due to the law of conservation mentioned by PiedPiper). If there's no sound board, the strings are the only mean of sound diffusion (the capacity of moving a certain volume of air) due to their little area and most of their energy is dissipated by "fixed" (non resonating) elements that keep strings in place. The sound board becomes that element, vibrating along with the strings, and since it has a »
Comment: @Aaron » greater area exposed to the air, it's able to move much more air around it, causing a louder sound. Also, the strings do not "create the sound": they create the initial vibration that *affects* the overall sound, but most of it comes from the soundboard (and other elements, like the bridge). While the choice of strings certainly is important, they have limited effects on the final sound: good strings can only make a slightly better sound on a bad instrument, but it will still be bad; bad strings may not get 100% from a good instrument, but it will still be good.
Comment: @Aaron Imagine the case of concert halls: if you play/sing in a small room with tiles (like a bathroom) you'll only get some harmonics with, possibly, annoying results; if that room has moquette on floor, walls and ceiling, you'll get a smaller and dampened sound; if you are in a church, you'll have a lot of reverb and mixed sounds; in a *good* concert hall, you'll have clear and well defined sound, even at great distance. In all these cases, the amount of energy is the same, what changes is how the vibration may be absorbed or reflected, partially affecting the sound at some level.
Comment: @musicamante I agree that, technically, amplification means that the amplitude of the wave increases, which means adding energy to the system. The OP, then, gets at the heart of what we actually mean by "amplification". Your comments on this and PiedPiper's post would make a good post in themselves, to explain the difference between "real" amplification and the kind of amplification done by a sound board.
Comment: @Aaron Increasing amplitude does not require adding energy, just that the energy comes from something else. For example wind instruments convert pressure into amplitude.
Answer: I think word missing is resonator. In old churches, you can see a large, thick, octagonal or circular board over the pulpet. It resonates the speaker's words from the pulpit and the acoustics of the sanctuary conduct the sound down the length of the building. If you've ever spoken or sang in an old church, you will know that you don't necessarily need electric microphones, your voice is resonated from the front of the church to the back seats.
Similarly, the sound board in some instruments resonates the music, it doesn't amplify it. Just like an echo can be resonated against the walls of a tunnel or narrow hall. Some structures make sound "bounce".
This is how "sound amplification before electricity" was explained to me. I hope this helps.
Comment: Consider an Edison cylinder (or even platter) recorder. The entire sound is driven by the ridges on the plastic cylinder. It's transferred from a diamond-tipped steel needle to a metal or plastic horn. If the horn isn't attached, there is no sound. I think the vibrations of the needle do not disturb the air very much, The needle can transfer its energy to the horn and thence to the air. The coupling constants from cylinder to needle, needle to horn, and horn to air are large. The needle and cylinder do not couple the air. Much of this may be frequency-dependent.
Comment: If you take a (once-common) _electric_ phonograph and disconnect the speaker, you can still hear faint sounds coming from the needle.  A horn-less acoustic phonograph doesn't have _no_ sound.  But neither is usable this way.
Answer: A flame can provide non-electronic amplification of sound. Typically the gas flow in the flame must be close to a transition from laminar to turbulent regimes.
https://massless.info/images/Popular%20Electronics%20May%201968%2031401532-Flame-Amplification.pdf
Answer: As well as mechanical amplification, there is Chemical amplification (where sound pressure amplifies chemical reaction, which amplifies sound pressure) and Ultrasonic amplification (modulating high energy ultrasonic pressure).
Both are inherently non-linear processes, and although they can be linearized, to my knowledge, neither has been demonstrated with good fidelity.
Answer: To add to the other examples of non-electric amplification, you have humans [*]!
Imagine a single speaker who says a few words, and then a crowd that repeats the words said by the speaker. Your signal has been amplified.
The signal has changed in the process - but the content is the same. It is not uncommon for amplification to distort signals (e.g. guitar amps)
It doesn't have to be words - it works with melodies and rythm too, for example Freddy Mercury making a crowd at Wembley sing simple phrases.
[*] Unless you consider humans to be electric...


Interesting problems concerning factorization and simplifictions of expressions

Question: I feel that deep within the knowledge of many users here dwell great problems regarding clever tricks for simplifying problems, and factoring algebraic expressions. I would be very much interested in seeing a large list of problems, regarding such problems.
Any problem that is clever, has something to do with factorization or simplification should be placed here. Now, I would hope that only the crème de la crème. The very best of such problems. Not just a mass of standard ones.
Any problem that does not require advanced math such as, topology, linear algebra, differential equations are allowed or imaginary numbers. The problem may indeed be very difficult, but it should not consist of topics beyond the first year of college.
Does anyone have any similar problems, or expressions like the small list I compiled below? (My favourite problem of the answers, will get the reward.)

If possible simplify these expressions into simpler terms
If further simplification is not possible, factor the expressions as much as possible in the reals.

$$   \qquad \frac{7}{\sqrt{7}}$$
$$   \qquad 2x^2 -1 + 2x^2$$
$$   \qquad x(x-1)-2(x-1)$$
$$   \qquad x^2+3x-2x-6$$
$$   \qquad \frac{t^2-6t+9}{t^2-8t+15}$$
$$   \qquad \frac{t^2 - 2t - 4}{2t + \sqrt{2}}$$
$$    \qquad \frac{1}{2} \ln \left( \frac{\sqrt{3}+\sqrt{2}}{\sqrt{3}-\sqrt{2}}\right) $$
$$    \qquad \big(\cos(x) + \sin(x)\big)^2+\big( \cos(x) - \sin(x) \big)^2$$
$$    \qquad \frac{3 - 4\sqrt{3}x}{\sqrt{3}}$$
$$    \qquad \frac{1-4y^2}{6y-3}$$
$$     \qquad \frac{\cos x \cdot (\sin x+1)^2 - \cos \cdot (\sin x-1)^2}{(\sin x)^4 - (\cos x)^4}$$
$$   \qquad \sqrt{4 - 2\sqrt{3}}$$
$$   \qquad \frac{2t^2-1}{2t + \sqrt{2}} $$
$$    \frac{2^{2x-1} - 2^{x-1}}{2^{2x-1}}$$
$$    \frac{\qquad\dfrac{5p+10}{p^2-4}\qquad}{\dfrac{3p-6}{(p-2)^2}}$$
$$    \sqrt[3]{\frac{x^3-6x^2+12x-8}{x^3+3x^2+3x+1}}$$
$$    y^2 - 4 - x^2 + 4x$$
$$    \sqrt{9x^2-6x+1}$$
$$    \ln \left( \sqrt{x-1} \right) \exp \left( \ln(4) + \ln \left( \frac{1}{2} \right)\right)$$
$$    \sqrt[\Large 4]{\dfrac{6 - 2\sqrt{5}}{6 + 2\sqrt{5}}}$$
$$    \dfrac{\left( 1 + \dfrac{1}{\sqrt[4]{x}}\right) (x-1)}{\left( 1 + \dfrac{1}{\sqrt{x}}\right)}$$
$$  \qquad \dfrac{x^{\frac{3}{2}} \cdot \sqrt[2]{\frac{y}{x} \cdot  }\left( x^2 - 2x y^3 + y^6 \right) }{\left( \sqrt{x} - \sqrt{y^3} \right) x \left( \sqrt{x} + \sqrt{y^3} \right) }$$
$$    \qquad \Large 2^{\frac{\log\left( \frac{100}{x}\right) - 1 }{- \log(2)}}$$
$$    x^6-2x^3+1$$
$$    x^6+3x^4+3x^2+1$$
$$    x^3+x^2-x-1$$
$$    (2k+1)^8-1$$
$$    x^3 + 1$$
$$    x^4 + 1$$
$$    x^4 + x^2 + 1$$
$$    \sqrt{18(\sqrt[3]10 - 2)} $$
$$    \frac{n! + (n-1)n!}{(n-2)!} $$
$$    \qquad \sqrt{12 + 5 \sqrt 6}$$
$$    \sqrt{\frac{1}3 \sqrt{6} (12 + 5\ \sqrt 6)}$$
$$    x^4-6x^3+11x^2-6x+1$$
$$    x^4+6x^3-5x^2-10x-3$$
$$    \sqrt{1 + \sin 2x}$$
$$    x(x+1)(x+2)(x+3) - 120 $$
$$    \sqrt{ \frac{1}{1 + \sin x } } $$
$$    \qquad \frac{\sin t + \sin 3t}{\cos 3t + \cos t} $$
$$    \sqrt[3]{26+15\sqrt{3}}$$
$$    x^5+x+1$$
$$   \sqrt{2^{6/7}}$$

Regards werner
Comment: Why don't you just post your own simplifications as an answer?
Comment: Are you saying to post the answer to these problem as an answer, or the problems themselves as an anwer?

I merely want more answers like these
Comment: I don't understand why you are asking question 1 when it seems that you know what the "answers" are before hand.
Comment: The only question i proposed was if people would post similar problems to the ones I posted. When one posts equations one must adress, what is supposed to be done with these. Whichis what I wrote in 1 and 2. So the answers I am looking for, are answers that can be solved following 1 and 2. If you know a cleared way to state this, feel free to edit my post =)
Comment: This looks like a good candidate for a [big-list] CW sort of question...
Answer: $$
2x^2 y^2 + 2x^2 z^2 + 2y^2 z^2 - x^4 - y^4 - z^4 = (x+y+z)(x+y-z)(x-y+z)(-z+y+z)
$$
Answer: Your expression involving a quotient of sines and cosines is an instance of the tangent-half-angle formula in the form
$$
\frac{\sin\alpha + \sin\beta}{\cos\alpha+\cos\beta} = \tan\frac{\alpha+\beta}{2}.
$$
If you want to include trigonometric identities in your list, look at Wikipedia's list of trigonometric identities.  Some of the items there are routine things; others are exotic.  As an example that's only a little bit exotic, everybody raise your hands if you knew that
$$
\sec(\theta_1 + \cdots + \theta_n) = \frac{\sec\theta_1 \cdots \sec\theta_n}{e_0 - e_2 + e_4 - \cdots}
$$
where $e_n$ is the $n$th-degree elementary symmetric polynomial in the variables $\tan\theta_1,\ldots,\tan\theta_n$.  Or the fact that if $x+y+z=\pi$ then $\sin(2x)+\sin(2y)+\sin(2z)= 4\sin x\sin y\sin z$, which I think is not well known in some parts of the world.
To get more sophisticated, there's Hermite's cotangent identity (or see the "main" article).
Comment: Thats really cool


jQuery Plugin not working for all elements that is applied upon

Question: Consider the following jQuery Plugin code:
(function($){
$.fn.MyPluginMethod= function() {
    $(this).after('Hello');
    };
})(jQuery);

if we call this function like this:
$('a').MyPluginMethod(); for each  tag that exists, it will add a  tag after it.
If we change it like this:
(function($){
$.fn.MyPluginMethod= function() {
    title= $(this).attr('title');
    alert(title);
};
})(jQuery);

It will not alert the title for each  tag that exists, only for the first occurence.
Why this behaviour?
Thanks
Answer: This is because you are creating 1 instance of the plugin, so the alert() is called once. The reason the first example results in span elements after every a is because the after() jQuery function loops through the matching set of elements.
To get your latter example to work as you want, you need to loop manually:
(function($){
    $.fn.MyPluginMethod= function() {
        this.each(function() {
            title = $(this).attr('title');
            alert(title);
        });
    };
})(jQuery);

You can check to see if the plugin has been instantiated on multiple elements by using this.length
Comment: @user2653125 no because .attr() method will return only first matched element
Comment: but in the second example, i call it with the $('a') selector, shouldn't this one loop through each of the matched elements too, and alert for each of them?
Comment: No, because as I mentioned you are creating 1 instance of the plugin.
Comment: @RoryMcCrossan  this is already refering to matched set of elements, no need to wrap it again: `this.each()`
Comment: @roasted, so, the 'this' keyword, doesn't point to each specific elements, but to the list of elements?
Comment: @user2653125 ya, here 'this' refers to the jquery object (set of elements targeted by selector) on which method is apply. for example, using a method as .css(), you wouldn't need to do an each loop here. BTW, for keeping chaining, you should return the element: `return this.each()`.
Comment: one last question: what is the difference between `this` and `$(this)`, because sometimes it works with this, sometimes not, and i must use $(this)
Answer: It will alert when you call it,
Also use $.each to call it for multiple elements like
HTML

test

test123

SCRIPT
(function($){
$.fn.MyPluginMethod= function() {
    return $(this).each(function(){
      title= $(this).attr('title');
      alert(title);
    });
};
})(jQuery);
$('div').MyPluginMethod();

Updated Fiddle
Read http://learn.jquery.com/plugins/basic-plugin-creation/


Storing php query result into an array

Question: How can I store php query result into an array in Computed field code(PHP)?
For example:
<code>$query = db_query('SELECT field_holiday_date_value FROM field_data_field_holiday_date');
</code>
how can I store it into an array?
Answer: <code>$result = $query->fetchAll();
</code>
This will store the records in $result as an array. You then need to store it in the computed field, which is something like this:
<code>$entity_field[0]['value'] = $result;
</code>
References:
https://api.drupal.org/api/drupal/includes%21database%21database.inc/function/db_query/7
https://drupal.org/node/126522
Comment: You asked a clear question and I gave the clear answer. Let's keep it this way for future people looking for the same thing. Now you're asking a different question with a different problem. If you want that answered you should make a new question and give specific examples of what data you are working with and what you are trying to achieve. This isn't a forum for helping people, it's a question and answer website. If you want a specific answer you need to ask that question.
Comment: is $result an array?
Comment: Yes, just as I said. If you read the documentation in the first link and read the first comment, you can see what ->fetchAll does.
Comment: But when I tried to use it like this

if(in_array($curr2,$result))

it did not get what I wanted to output.
Comment: I just thought that if it was saved as an array, I can access it using in_array.

FYI.Im not asking another question in my comment. I just SAID(not ASK) what was the output so that other people will know the output :)

thanks for answering anyway.
Comment: No problem. The array that is output is an associative array of standard PHP objects, as described in the documentation in the first link. `in_array` would only work if you were searching for that PHP object, which I suspect you are not. See http://stackoverflow.com/questions/11743527/how-does-in-array-check-if-an-object-is-in-an-array-of-objects

Storing php query result into an array


Prever o proximo ID do Banco

Question: Bom pessoal estou querendo organizar melhor as imagens das postagem porem para isso preciso saber qual será o proximo ID para que eu verifique primeiro a imagem antes de inserir o resto dos dados.
 if (is_uploaded_file($_FILES["foto"]["tmp_name"])) {
$imagem = time() . '_' . $_FILES["foto"]["name"];
$diretorio = 'fotos/ {{{AQUI VIRIA O NUMERO DO ID }}}' . $imagem;
if (!move_uploaded_file($_FILES["foto"]["tmp_name"], $diretorio)) {
  $error = TRUE;
}

estou usando pdo para conexao
Comment: http://pt.stackoverflow.com/q/45676/91
Comment: esse dai arrumar o id apos o insert essa minha duvida em questao agora é outra é pegar antes
Answer: Se seu id estiver com auto_increment basta buscar as informações da tabela com o sql abaixo:
SHOW TABLE STATUS LIKE 'nome_tabela'

Pegue o valor da coluna Auto_increment
Caso não esteja com auto_increment e você está inserindo o id manualmente, basta buscar o maior id ou o último registrado respectivamente:
SELECT MAX(id)+1 AS id FROM nome_tabela

e
SELECT id+1 AS id  FROM nome_tabela ORDER BY id DESC LIMIT 1

Basta implementar no seu código da forma que desejar.
Espero que ajude, abraços!
Comment: sim mais nesse caso ai eu so poderia pegar o ultimo id inserido certo ?
Comment: sim, bastar somar +1, terá o próximo! (editei o SQL pra ficar mais claro)
Comment: EX: supondo que o ultimo id é o 40 queria dar um jeito de pegar o 41 mesmo ele nao existindo ainda
Comment: Exato! Com o SQL atual já estou somando 1 para que ele traga o próximo id
Comment: Ficaria mais ou menos assim $sql = "SELECT Nid FROM posts ORDER BY id DESC LIMIT 1;
   $stmt = $DB->prepare($sql);
   $stmt->bindValue(":cid", intval($_GET["cid"]));

   $stmt->execute();
   $results = $stmt->fetchAll();
 $idfuturo= ($results[0]["NID"] + 1);
Comment: Isso aí! :D
não esqueça de trocar o outro id:
SELECT Nid FROM posts ORDER BY Nid DESC LIMIT 1

Prever o proximo ID do Banco


How do I set a path alias for each forum?

Question: I created a forum on a site using the core Forum module. When we create a new forum, Drupal creates it as a taxonomy term. When we create the new forum, if we associate a path alias, that URL alias is only associated to the taxonomy term and not to the forum.
If we click on a specific forum from the index page (example.com/forum) we are sent to example.com/forum/nn.
How can I associate a path alias? I'm not being able to do it via the Pathauto module. Can someone tell me how to do it with that module or using any other solution?
Comment: The Pathauto module does support the Forum module. What did you get from it, and how did it differ from what you expected to get?
Comment: I was able to get a path alias for each forum, using the Pathauto module, but it seems that in the /forum page (the one listing all the existing forums) the path aliases aren't used. I get the path alias in the page showing a forum topic, in the link to to the forum.
Comment: As I pointed out below you solved my issue teaching me an additional functionality of Path/pathauto (The generation of individual alias, that I didn't realise it was still available after installing Pathauto).
Regarding the Pathauto usage I think that there might be a bug ibn it, because after enabling the forum module (from the core), when I tried to use the "Bulk Generation", I had available a "Forum" option on the sub tab: "Select the types of paths for which to generate URL aliases", but, at the same time on the tab: "Settings", subtab: "ENABLED ENTITY TYPES" there is no "Forum" option
Comment: After I created a Pattern of type: "Forum", and that Pattern runs, but doesn't generate Alias.
May be a Drupal Apprentice with 5 months experience shouldn't use the word "bug" but I think the interaction of Pathauto and Forum modules is not working properly. If you want I will give you "admin" permission to my site so that you can inspect it.
Nevertheless your solution solved my issue via the individual alias generation, and I'm very thankful to you.
Comment: Yes, it is a little confusing that in the settings you don't explicitly enable the automatic path aliases the Pathauto module creates for forums, but you need to select _Forum_ when you create a pattern for path aliases. It is even more confusing that the path aliases assigned to forums are really assigned to the taxonomy terms associated to the forums. I added the screenshots to show the Pathauto settings I used in the test site.
Comment: Thank you once again for your additional help, definitely the module UI need some fine tune, but you showed me the manual solution and gave me a Drupal Lesson. I'm impressed by your knowledge on Drupal and capability to share it. You show be doing Tutorial… :)
Comment: If I find a way to set path aliases that are used in both the /forum page and in the forum topic pages with code, I will update my answer.
Answer: It is possible to add a path alias to a forum, without installing any third-party modules.
You could install the Pathauto module, but that is more for automatically assigning the path aliases when creating/editing an entity, or for bulk-assigning path aliases to existing entities. If you install the Pathauto module to create path aliases for the forums, notice that under Enabled entity types on /admin/config/search/path/settings, you don't see an entry like Forum. Use the default values for that form field (which include Content and Taxonomy term that you cannot deselect), and you will be able to set path aliases for the forums.

It is a quite confusing, since in /admin/config/search/path/patterns/add you need to select Forum for Pattern type.

Maybe it would be less confusing if Forum would be an option for Enabled entity types too.
In this case, anyway, the path aliases that the Pathauto module says to assign to forums are really assigned to the taxonomy terms associated with the forums. The effect of this is that the /forum page would not use any path alias for the forum links.
I created a sandbox site on simplytest.me, and I just enabled the Forum module. I created two forums (Module development and Theme development), and created a forum topic (Porting the "User activity" module to Drupal 8). I went to /admin/config/search/path, and created the following path aliases.

/forums/1/general-discussion pointing to /forum/1
/forums/2/module-development pointing to /forum/2
/forums/3/theme-development pointing to /forum/3

Doing so, the /forum page used the path aliases I set, in the links to the forums, but the forum topic pages used links like https://dsze.ply.st/taxonomy/term/2 under Forums.
So, or you set a path alias that is used from the /forum page (but not from the forum topic pages), or you set a path alias that is used from the forum topics page (but not from the /forum page), or you set two different sets of path aliases (a set used from the /forum page, and a set used in the forum topic pages).
Comment: My most Sincere gratitude for the solution and lesson on Drupal. You are not only an expert, but you invest your time to help the apprentices like me. Rare and remarkable, thank you very much
Answer: I have just tested this feature on Drupal 10 and forum URL aliases worked fine.

First install Pathauto if you don't yet have it:  https://www.drupal.org/project/pathauto
Then, from Extend in the administration panel, install Pathauto,
Chaos tools, and Token. If you used Composer to install
Pathauto, the other modules were also downloaded automatically.

Once Pathauto is installed, assuming the Forum module is also authorized, create a forum post for testing (if you don't have any yet).
Now, let's create a URL pattern via Pathauto for your forum posts.

Go to "Configuration", "Search and Metadata", then "URL Aliases".
Do not click on Add alias.
Instead, switch from List to Patterns (top tabs).
From Patterns, click on Add Pathauto pattern.
Once there, select Content from Pattern type (do not select forum).
On Path pattern, write forum[node:title] as the pattern.
On Content type, select Forum Topic.
Write label title on the next window. You can type anything to remind you what this pattern represents (I typed "URL Patter Forums").
SAVE.

The next thing to do is to convert your existing URLs.

From the Search and Metadata page (you should be there now), select the "Bulk Generate tab".
Select the type of paths for which to generate URL aliases. You can select all, since it will only do the ones that are authorized, but at least Content and Forum should be selected.
Keep the "General URL alias for un-aliased paths only" checked. However, if you already had some aliases that you would like to override, check, instead, one of the other options.
Press Update.

Lastly, you may have to clean the cache.

Go Configuration.
Performance.
Clear all caches.

I hope it helps.

Note: As for general-discussions (this is the forum name). Since it is not user generated, you can use the core alias functionality.
There are two entities that point to general-discussions:
node/x and term/x.
(By x I mean the node number you have in your Drupal).
Here, you click on Configuration/Search and metada
Then, from the List tab, click on Add Alias.
then, you could enter /node/x as /general-discussion/, then save it.
And then add another alias for term/x using the same general-discussion label or something else, then save it.
Clear the cache.
Answer: We can set forum patterns using the following trick.
First create a forum pattern:

Then we can use the following code in custom module:
<code>function my_custom_pathauto_alias_alter(&$alias, array &$context) {

  if (!empty($context['data']['term']) && $context['data']['term']->bundle() == 'forums') {

    $alias_bk = $alias;
    $alias = preg_replace('~^/forum/~', '/forum_term/', $alias);

    $tid = $context['data']['term']->id();

    $pids = \Drupal::entityQuery('path_alias')
        ->condition('path', '/forum/' . $tid)
        ->accessCheck(FALSE)
        ->execute();

    if ($pids) {
      $pids = array_values($pids);
      $pid_main = $pids[0];

      unset($pids[0]);

      foreach ($pids as $pid) {
        $alias_to_del = \Drupal\path_alias\Entity\PathAlias::load($pid);
        if ($alias_to_del) {
          $alias_to_del->delete();
        }
      }

      $alias_to_change = \Drupal\path_alias\Entity\PathAlias::load($pid_main);
      if ($alias_to_change) {
        $alias_to_change->set('alias', $alias_bk)->save();
      }
    }
    else {
      $path_alias = \Drupal\path_alias\Entity\PathAlias::create([
            'path'  => '/forum/' . $tid,
            'alias' => $alias_bk,
      ]);

      $path_alias->save();
    }
  }
}
</code>
So the generated pattern will be used for forums, but forum terms aliases will be changed to something else we want.


Regex. Avoid matching string until condition is met?

Question: Need help with regex.
String:
(can contain more levels of "test")
<code>[test]
[inner]
    [test]
        [inner]*anything*
        [/inner]
    [/test]
[/inner]
[/test]

[test]
    [inner]*anything*
    [/inner]
[/test]
</code>
Should match:
1.
<code>[test]
[inner]
    [test]
        [inner]*anything*
        [/inner]
    [/test]
[/inner]
[/test]
</code>
2.
<code>[test]
    [inner]*anything*
    [/inner]
[/test]
</code>
Question:
How to write regex that matches wanted outcome in PHP?
Here's my example:
https://regex101.com/r/tA2wN8/2
Comment: And the question is?
Comment: Are you expecting an answer in JavaScript or PHP?
Comment: Need this in PHP. Casimir et Hippolyte answer is fine.
Answer: You need to use a recursive pattern:
<code>~\[test](?:[^[]+|\[(?!/?test])|(?R))*+\[/test]~
</code>
details:
<code>~                     # pattern delimiter
\[test]
(?:                   # non-capturing group (possible content between test tags)
    [^[]+             # all that is not a [
  |
    \[(?!/?test])     # a [ not part of a test tag (opening or closing)
  |
    (?R)              # repeat the whole pattern (recursion)
)*+                   # repeat the group zero or more times (possessive quantifier)
\[/test]
~
</code>
Note this way is only possible wih PHP or Perl, there is no way for Javascript that doesn't have a recursion feature.


R's mvrnorm returning seemingly biased samples

Question: I am trying to generate random vectors with the same covariance, mean and sd as a set I have. I am using R's mvrnorm with Empirical = F because the underlying distribution is in general not normal.
However when running this many times I get the impression that specific elements of the returned vectors are too similar to the original vector.
Is there a way to verify this quantitatively? and if this is indeed the case, how can I generate vectors that are "completely different" from the original (while maintaining same sd and mean)?
For example:
> df
     A        B
1 1.138289 1.918876
2 1.621082 2.432379
3 1.295929 2.241403
4 1.325516 1.845258

mvrnorm(n = 4, mu = center, Sigma = as.matrix(cov(df)), empirical = F)
        A        B
[1,] 1.364986 2.235192
[2,] 1.116274 1.828175
[3,] 1.438028 2.256231
[4,] 1.586585 1.956803

Although the bias cannot be shown from this example (but only for a large number of samples), there are pairs which are the same as the original (up to 2 digits after the decimal point), which are returned significantly more than others.
Comment: (1) The empirical argument has nothing to do with normality of the original sample, the function will return normal draws in each case. (2) Why exactly you consider the draws to be strange..? How large are the samples you are taking about? If you'd toss two coins simultaneously, then at some point you'll toss two heads at random...
Comment: While this is not a forum for debugging code, could you perhaps share the R-code to make it clear what you are doing, and what results you are seeing?
Answer: I'm assuming in my answer that center = colMeans(df).
You don't have to worry about mvrnorm "replicating" your data frame. The function doesn't even "know" what your data looks like (you only pass the mean and covariance matrix). The randomization in mvrnorm depends on rnorm which is very well tested. If the patterns you see don't seem random enough for you it is probably because the human eye is very bad at discerning randomness.
mvrnorm will always produce samples from a normal. The option empirical will scale the sample so that the sample mean and covariance equal exactly the numbers that you provided. It has nothing to do with accommodating non-normal distributions. To see this, run the following code:
df <- data.frame(A = c(1.138289, 1.621082, 1.295929, 1.325516),
B = c(1.918876, 2.432379, 2.241403, 1.845258))
colMeans(df)
cov(df)
my_sample <- MASS::mvrnorm(n = 100, mu = colMeans(df), Sigma = as.matrix(cov(df)),
  empirical = TRUE)
colMeans(my_sample)
cov(my_sample)

If you want to maintain mean and covariance structure then you want empirical = TRUE.
Comment: I would like to maintain mean and covariance *per sample*, which holds for both empirical = True or False. My suspicion that very close values are returned are corroborated by running the code 1000 times and seeing that a specific pair is returned more than others. But how can I check this suspicion? Is there a measure that will indicate "perfect randomness" for many samples? Something like comparing within cluster distance for the original vs. the sampled vector?
Comment: I don't think the randomization is the problem here. You are aware that you are generating highly correlated data?
Comment: Yes. I am starting to think that since the algorithm assumes underlying normality, the pair which is closest to the mean will be sampled more than a pair close to the tail. Could this be the issue?
Comment: That's right (where "closeness" will not be measured by the usual Euclidean metric because of the correlation). Maybe you are looking for a way to generate samples from your distribution nonparametrically? How to do this is probably the topic of a new question. The easiest way is resampling from the empirical distribution.


Python Django how can't render my variables from views.py on html file

Question: How can i render my variables from models in a html file, they was rendering a time ago before I made html link slug with class(DetailView) in my views.py

HTML FILE (product.html)

{{ product.name }}

                      {% for category in product.category.all %}
                        {{ category }}
                      {% endfor %}
                      {#

 #}

                    {% for link in links %}

                        DOWNLOAD MIRROR NUMBER {{ links.number }}

                    {% endfor %}

                        Description

{{ product.description }}

                           System Requirements

Processor: {{ product.processor }}

                           Graphic Card: {{ product.video }}

                           Memory: {{ product.ram }}

                           Disk Space: {{ product.disk_space }}

                           OS: {{ product.oS }}

                  {% for image in product_images %}

                  {% endfor %}

News

                {% for articles in news_articles %}

                    {{ articles.article.created }}

views.py

from django.shortcuts import render
from products.models import *
from news.models import *
from django.shortcuts import get_object_or_404
from django.views.generic.detail import DetailView

class GameLink(DetailView):
    # model = Product
    # context_object_name = 'product'

    def get_object(self):
        return get_object_or_404(Product, slug__iexact=self.kwargs['slug'])

class ArticleLink(DetailView):
    model = Article
    context_object_name = 'article'

    def get_object(self):
        return get_object_or_404(Article, slug__iexact=self.kwargs['slug'])

def product(request, product_id):
    product = Product.objects.get(id=product_id)
    product_images = ProductImage.objects.filter(is_active=True, is_main=False, id=product_id)
    links = ProductDownload.objects.filter(is_active=True, product=product_id)
    news_articles = NewsImage.objects.filter(is_active=True, is_main=True)
    return render(request, 'products/product.html', locals())

urls.py

from django.contrib import admin
from django.conf.urls import *
from products import views
from products.views import *

urlpatterns = [
   # url(r'^games/(?P<product_id>\w+)/$', views.product, name='product'),
   url(r'^games/(?P<slug>[-\w]+)/$', GameLink.as_view(template_name = 'products/product.html'), name='product'),
   url(r'^articles/(?P<slug>[-\w]+)/$', ArticleLink.as_view(template_name = 'news/article.html'), name='article')
]

models.py

`

from django.db import models
from django.urls import reverse

class ProductCategory(models.Model):
    name = models.CharField(max_length=128, blank=True, null=True, default=None)
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return '%s' % self.name

    class Meta:
        verbose_name = 'Category'
        verbose_name_plural = 'Categories'

class Product(models.Model):
    name = models.CharField(max_length=128, blank=True, null=True, default=None)
    description = models.TextField(default=None)
    processor = models.CharField(max_length=300, blank=True, null=True, default=None)
    video = models.CharField(max_length=300, blank=True, null=True, default=None)
    ram = models.CharField(max_length=300, blank=True, null=True, default=None)
    disk_space = models.CharField(max_length=300, blank=True, null=True, default=None)
    oS = models.CharField(max_length=300, blank=True, null=True, default=None)
    video_trailer = models.CharField(max_length=10000, blank=True, null=True, default=None)
    img = models.CharField(max_length=10000, blank=True, null=True, default=None)
    category = models.ManyToManyField(ProductCategory, blank=True, default=None)
    is_active = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)
    slug = models.SlugField(primary_key=True, max_length=250, unique=True, default=None)

    def __str__(self):
        return '%s' % self.name

    def get_absolute_url(self):
        return reverse('product', args=[str(self.slug)])

    class Meta:
        verbose_name = 'Game'
        verbose_name_plural = 'Games'

class ProductDownload(models.Model):
    product = models.ForeignKey(Product, blank=True, null=True, default=None, on_delete=False)
    link = models.CharField(max_length=10000, blank=True, null=True, default=None)
    is_active = models.BooleanField(default=True)
    number = models.PositiveIntegerField(blank=True, default=True)

    def __str__(self):
        return '%s' % self.product.name

    class Meta:
        ordering = ['number']

    class Meta:
        verbose_name = 'Download Link'
        verbose_name_plural = 'Download Links'

class ProductImage(models.Model):
    product = models.ForeignKey(Product, blank=True, null=True, default=None, on_delete=False)
    image = models.CharField(max_length=10000, blank=True, null=True, default=None)
    is_main = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return '%s' % self.product

    class Meta:
        verbose_name = 'Image'
        verbose_name_plural = 'Images'

HTML file show only Product variables that are called with {{ product.___ }} but doesn't renders the rest like my links called with :
{% for link in links %}
{{ link.link }}
{% endfor %}
 or like my articles...
How should I proceed to render on my page needed models.

Image of file paths
  here
Comment: I'm a full noob in programming, and my english is not very good, so please explain simply.
Answer: There are different forms to add adicional 'variables' using a DetailView   (link)
For example:
class GameLink(DetailView):

    def get_object(self):
        return get_object_or_404(Product, slug__iexact=self.kwargs['slug'])

    def links(self):
        return ProductDownload.objects.filter(is_active=True, product=self.object)

And in product.html:
{% for link in view.links %}

        DOWNLOAD MIRROR NUMBER {{ links.number }}

{% endfor %}

IF you don't want to change HTML, instead of declaring the "def links(self)":
class GameLink(DetailView):

    def get_object(self):
        return get_object_or_404(Product, slug__iexact=self.kwargs['slug'])

    def get_context_data(self, **kwargs):
        context = super(GameLink, self).get_context_data(**kwargs)
        context['links'] = ProductDownload.objects.filter(is_active=True, product=self.object)
        return context

Comment: I'll use first))
Comment: It works with links and product_images but doesn't work with articles
Comment: It work with `def links` and`def product_images` but don't works with `def articles` :
 `def articles(self):
        return NewsImage.objects.filter(is_active=True, is_main=True, article=self.object)`
Comment: says `Cannot query "The Witcher 3: Wild Hunt": Must be "Article" instance`.
Comment: @YourLogarithm, about the second one: i edited the line "context = super(GameLink, self)" it was with a typo
Comment: I can't see NewsImage on your model


Different right / left identity and two sided identity element

Question: Maybe this will be a trivial question but I can't find a solution for this. I checked already on a lot of questions here and on google but can't find a solution for my specific problem.
Given an operation $\ast: Z \times Z \xrightarrow[]{} Z$ defined as: $a\ast b = 3a + b$ prove that $\ast$ is 1)commutative, 2)associative and 3)exist the identity element. I proved 1) and 2) without problem, is neither commutative and associative(correct me if I'm wrong) but I have some problem with 3). From definition I know that exist the identity element $\iff$ $ \forall a \in Z \quad \exists u \in Z: \quad a\ast u = u \ast a = a$. So essentially I must solve 2 equation one for left side identity element and another one for right side identity element, in my case:
$$
a \ast u = 3a+u
$$
I should solve the equation: $3a+u=a$. So the left identity element will be $ u= -2a$
Similarly for the other side:
$$
u \ast a = 3u+a
$$
I should solve the equation: $3u+a=a$. So the left identity element will be $ u= 0$.
If I did everything correct $u_l \neq u_r$.
My question arises from this situation, I should consider that identity element $u$ doesn't exists because $u_l \neq u_r$ or I should write only that $u_l \neq u_r$ without specifing if $u$ exists? Briefly, does the identity element exists in this case?
Therefore, is right to say that when an operation isn't commutative then will never exist the identity element? This conclusion seems almost strange to me because if I consider a simple non-abelian monoid my conclusion isn't correct. Thanks all in advance.
Answer: You have the definition of identity element wrong. $u$ is an identity element if for all $a$ one has $a * u = a = u * a$. That is, you have your quantifiers wrong, it is not "for all $a$ there is $u$", but rather "there is $u$ such that for all $a$". In other words, $u$ must be independent of $a$.
In your case you have a left identity, but not a right one, because the equation $3 a + u = a$ does not have a solution $u$ which is independent of $a$.
Comment: You're absolutely right! thanks
Answer: well, in case there is a left identity which is'nt a right identity and a right one that is'nt a left identity , we do'nt usually call any of those an identity.
notice that, if there is an identity $e$, and a left(right) identity $l$($r$), then $$e=el=l(r=re=e)$$, so if there is an left identity that is not a right identity, there is no identity element.
about your specific question, in the first equation you did'nt get a "solution", but some relation, so only because $u$ depends on $a$, you cansay that there is no element that sucj that the right identity equation holds for all elements.
finally, if a monoid is'nt comutative, it does'nt mean that there is no element that act "comutativly", but that not all element act like that.
Comment: Thanks a lot!! So is right to generalize and say that when an equation solution is dependent from some parameters, then there's no  identity element?
Comment: yes, but it is not that simple to recognize if that is the case.


Sobrepor a seta para voltar ao topo sobre videos, imagens, etc

Question: Não estou conseguindo sobrepor a seta para voltar ao top que é fixa em minha página.
Sempre quando passa por imagens, videos e algumas aplicações que usam JavaScript ela some.
Gostaria de saber se há alguma solução especifica.
Uso os seguintes código para uso da seta

E o CSS da classe o outro é :
.botaotopo {
  display:scroll;
  position:fixed;
  bottom:2px;
  right:2px;
}

E o JS:
(function($){$.fn.UItoTop=function(options){var defaults={text:'To Top',min:200,inDelay:600,outDelay:400,containerID:'toTop',containerHoverID:'toTopHover',scrollSpeed:1200,easingType:'linear'},settings=$.extend(defaults,options),containerIDhash='#'+settings.containerID,containerHoverIDHash='#'+settings.containerHoverID;$('body').append(''+settings.text+'');$(containerIDhash).hide().on('click.UItoTop',function(){$('html, body').animate({scrollTop:0},settings.scrollSpeed,settings.easingType);$('#'+settings.containerHoverID,this).stop().animate({'opacity':0},settings.inDelay,settings.easingType);return false;}).prepend('').hover(function(){$(containerHoverIDHash,this).stop().animate({'opacity':1},600,'linear');},function(){$(containerHoverIDHash,this).stop().animate({'opacity':0},700,'linear');});$(window).scroll(function(){var sd=$(window).scrollTop();if(typeof document.body.style.maxHeight==="undefined"){$(containerIDhash).css({'position':'absolute','top':sd+$(window).height()-50});}
if(sd>settings.min)
$(containerIDhash).fadeIn(settings.inDelay);else
$(containerIDhash).fadeOut(settings.Outdelay);});};})(jQuery);

Answer: Elementos com um z-index maior são empilhados diante dos elementos com um menor z-index
 .botaotopo {
   z-index: 1;
   ..........
   ..........

No seu caso isso vai funcionar, só vai parecer que não lá no rodapé que é da mesma cor :)
Comment: Excelente resolveu meu problema, muito obrigado!


Why no Placeholder text on my Ionic 3 project

Question: I cannot see any placeholder text on my project.Can you tell me why? If I create a new project then it works.This is a really strange issue. Any clue about this behavior?

 <ion-list>
    <ion-item>
      <ion-label color="primary">Inline Label</ion-label>
      <ion-input placeholder="Text Input"></ion-input>
    </ion-item>
 </ion-list>

I'm using latest ionic.

@ionic/cli-utils  : 1.15.0
ionic (Ionic CLI) : 3.15.0

global packages:
cordova (Cordova CLI) : 7.0.1

local packages:
@ionic/app-scripts : 3.0.1
Cordova Platforms  : android 6.2.3
Ionic Framework    : ionic-angular 3.7.1

System:
Android SDK Tools : 25.2.5
Node              : v6.10.0
npm               : 3.10.10
OS                : Windows 8.1

Environment Variables:
ANDROID_HOME : C:\Program Files (x86)\Android\android-sdk

Misc:
backend : pro

Here you can see that it renders correctly.Then where is the problem? I have tested this on the device too. Same horror :(
Comment: Try adding a `type` property to the input: ``
Comment: Can't see the computed style but is it possible that it somehow got shifted out of visible part of the parent element? I had this once a few years ago on iOS with ionic, some parent class made huge margin or something. It bugged me for 1 hour before I got the idea to check the style.
Comment: No. Same horror :( @David
Comment: Then probably some other style you have set is interfering with you input element as @DanteTheSmith said. Check the element with chrome dev tools and try removing/adding css selctors to figure out whats causing the trouble.
Comment: Yep, Found the issue. I have given `$text-input-placeholder-color: rgba(255, 255, 255, 0.5);` globally. That cause the issue. I would like to close this post. Would you like to post it as an answer or? @David
Comment: Sure, I'm glad you could solve it! :)
Answer: OP's Feedback
I have set the $text-input-placeholder-color: rgba(255, 255, 255, 0.5); on variables.scss file. That was the issue.
David's Feeback
Most probably some other (global, higher level) style is infering with the placeholder property. Try inspecting the input element with chrome dev tools and remove/add css selctors one by one to find out which one is causing the trouble (check especially colors, margin, padding, opacity).


Access Denied OutLook DCOM

Question: I'm trying an ASP.NET App and I have a problem with OutLook.
Code behind :
<code>OutlookApplication = new Application();
NameSpace nameSpace = OutlookApplication.GetNamespace("MAPI");
nameSpace.Logon("", "", missing, missing);
nameSpace = null;
</code>
When I play the app with Visual Studio it's ok.
When I play the app with IIS then :

System.UnauthorizedAccessException: Retrieving the COM class factory for >component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the >following error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005 >(E_ACCESSDENIED)).

I already tried to change DCOM Configuration for "OutLook Message Attachment" with :
Proprieties -> Identity -> Execute user
Proprieties -> Security -> all kind of acces autorized for "everybody".
NB : I have no problem with others Office programm (Excel and Word).
Comment: If you tag your questions correctly, you're more likely to reach the appropriate audience, and thus more likely to get an answer. This is emphatically NOT [tag:asp-classic].
Answer:
I'm trying an ASP.NET App and I have a problem with OutLook.

Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.
If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution. Read more about that in the Considerations for server-side Automation of Office article.
As a workaround you may consider using a low-level API on which Outlook is based on (Extended MAPI) or any third-party wrappers around that API, for example, Redemption.
Comment: Hi Eugene,

Thanks a lot for answering. I'll have a look to the Redemption API as advised :)

Access Denied OutLook DCOM


is the use of link-local address mandatory for IPv6 static routing next hop?

Question: The RFC for Neighbor Discovery (RFC4861), in section 8 states:
"A router MUST be able to determine the link-local address for each of
   its neighboring routers in order to ensure that the target address in
   a Redirect message identifies the neighbor router by its link-local
   address.  For static routing, this requirement implies that the next-
   hop router's address should be specified using the link-local address
   of the router.  For dynamic routing, this requirement implies that
   all IPv6 routing protocols must somehow exchange the link-local
   addresses of neighboring routers."
Yet, all documentation I encountered, including Cisco and Juniper, use simple Global Unicast Address or Local Unicast Address as next hop for IPv6 static routing.
. is the use of link-local address mandatory as IPv6 static routing next hop?
. is the use of link-local address a best practice as IPv6 static routing next hop?
Thanks for any clarification
Answer: In practice using GUA addresses is perfectly fine.
The restriction (well, strong recommendation, as it is specified as SHOULD) is to make it possible for the device with the static route to send redirect messages. These days redirect messages are often already disabled because of security and performance issues, so using a GUA as next hop is no problem.
Comment: So if I understand well, we have a RFC on one side; and security, performances, ease of use (using FE80::/10 as next hop is less straightforward) and common practices on the other. Should we formulate the answer as 'As a rule of thumb, don't use link-local address as next hop'? What would be the cases where using a link-local address should be preferred ? Saving /64 subnets in core routing ?
Comment: Routing protocols use link local next hops. It's great for automatic stuff! When manually configuring a route, using global addresses makes things easier for the network admin.


What's the difference between a component and a factor in parallel analysis?

Question: The psych package in R has a fa.parallel function to help determine the number of factors or components. From the documentation:

One way to determine the number of factors or components in a data
  matrix or a correlation matrix is to examine the "scree" plot of the
  successive eigenvalues. Sharp breaks in the plot suggest the
  appropriate number of components or factors to extract. "Parallel"
  analyis is an alternative technique that compares the scree of factors
  of the observed data with that of a random data matrix of the same
  size as the original. fa.parallel.poly does this for tetrachoric or
  polychoric analyses.

When I run the function I get the following output:
Parallel analysis suggests that the number of factors =  7
                            and the number of components =  4

What is the difference between a factor and a component?
Comment: possible duplicate of [What are the differences between Factor Analysis and Principal Component Analysis](http://stats.stackexchange.com/questions/1576/what-are-the-differences-between-factor-analysis-and-principal-component-analysi)
Comment: There does seem to be a question here that is not answered in the duplicate, @rolando2: FA "rotates" the principal components, and so ought (by rights) to produce exactly as many "factors" as "components."  This "parallel analysis" method (with which I am unfamiliar) appears somehow to select a different number of "factors."
Answer: You might wish to read Dinno's Gently Clarifying the Application of Horn's Parallel Analysis to Principal Component Analysis Versus Factor Analysis. Here's a short distillation:
Principal component analysis (PCA) involves the eigen-decomposition of the correlation matrix $\mathbf{R}$ (or less commonly, the covariance matrix $\mathbf{\Sigma}$), to give eigenvectors (which are generally what the substantive interpretation of PCA is about), and eigenvalues, $\mathbf{\Lambda}$ (which are what the empirical retention decisions, like parallel analysis, are based on).
Common factor analysis (FA) involves the eigen-decomposition of the correlation matrix $\mathbf{R}$ with the diagonal elements replaced with the communalities: $\mathbf{C} = \mathbf{R} - \text{diag}(\mathbf{R}^{+})^{+}$, where $\mathbf{R}^{+}$ indicates the generalized inverse (aka Moore-Penrose inverse, or pseudo-inverse) of matrix $\mathbf{R}$, to also give eigenvectors (which are also generally what the substantive interpretation of FA is about), and eigenvalues, $\mathbf{\Lambda}$ (which, as with PCA, are what the empirical retention decisions, like parallel analysis, are based on).
The eigenvalues, $\mathbf{\Lambda} = \{\lambda_{1}, \dots, \lambda_{p}\}$ ($p$ equals the number of variables producing $\mathbf{R}$) are arranged from largest to smallest, and in a PCA based on $\mathbf{R}$ are interpreted as apportioning $p$ units of
total variance under an assumption that each observed variable contributes 1 unit to the total variance. When PCA is based on $\mathbf{\Sigma}$, then each eigenvalue, $\lambda$, is interpreted as apportioning $\text{trace}(\mathbf{\Sigma})$ units of total variance under the assumption that each variable contributes the magnitude of its variance to total variance. In FA, the eigenvalues are interpreted as apportioning $< p$ units of common variance; this interpretation is problematic because eigenvalues in FA can be negative and it is difficult to know how to interpret such values either in terms of apportionment, or in terms of variance.
The parallel analysis procedure involves:

Obtaining $\{\lambda_{1}, \dots, \lambda_{p}\}$ for the observed data, $\mathbf{X}$.
Obtaining $\{\lambda^{r}_{1}, \dots, \lambda^{r}_{p}\}$ for uncorrelated (random) data of the same $n$ and $p$ as $\mathbf{X}$.
Repeating step 2 many times, say $k$ number of times.
Averaging each eigenvalue from step 3 over $k$ to produce $\{\overline{\lambda}^{r}_{1}, \dots, \overline{\lambda}^{r}_{p}\}$.
Retaining those $q$ components or common factors where $\lambda_{q} > \overline{\lambda}^{r}_{q}$

Monte Carlo parallel analysis employs a high centile (e.g. the 95$^{\text{th}}$) rather than the mean in step 4.
Comment: I upvoted this answer a long time ago (+1), but would like to remark that the procedure for factor analysis used by the `psych` package is not what is described in this answer. There are several common methods of factor extraction (and `psych` implements several of them), but as far as I know **none of them** amounts to an eigen-decomposition of $\mathbf{C} = \mathbf{R} - \text{diag}(\mathbf{R}^{+})^{+}$ as this answer seems to imply.
Comment: @amoeba Gorsuch, R. L. (1983). *Factor Analysis* 2nd ed. NJ: Lawrence Erlbaum Associates. Of course there are other ways to estimate the communalities (e.g. iterated factors, etc.). Stata, for example, calculates the default "principal factors" using the math I have outlined.
Comment: I have an electronic copy of the first edition of this book. Can you refer me to a specific section please? In any case, I looked up the manual of `psych` package and am pretty confident that the method you describe (even if it does exist in the literature) is not implemented there.
Comment: @amoeba Dang it, you are right about the Gorsuch reference (it's been a while since I cited for this area... forgot that I cite him for the common factor model, as opposed to the principal factor extraction formula). Will chase proper refs down now... (re: psych, *right* they don't do 'common factors'/'principal factors')
Comment: @amoeba Ok, the notation I used is an isomorphism of the r^2 in Gorsuch for common factors still tracking down refs...
Answer: It's talking about principal components. First, it finds the eigenvalues of the correlation matrix which it takes as input. Then it decides how many of those values are "reasonably big" by doing simulations and comparing them with the simulated values. Here is the key part of the code:
valuesx <- eigen(rx)$values

and then later on:
pc.test <- which(!(valuesx > values.sim$mean))[1] - 1
        results$nfact <- fa.test
    results$ncomp <- pc.test
    cat("Parallel analysis suggests that ")
    cat("the number of factors = ", fa.test, " and the number of components = ",
        pc.test, "\n")

The whole function is written in R, so you can read its source code by typing its name in the R terminal.
Here is a presentation which compares factor analysis with PCA and hopefully answers your question (see the last slide in particular):
http://www.stats.ox.ac.uk/~ripley/MultAnal_HT2007/PC-FA.pdf
Comment: So, if I understand your answer, a factor is an output of factor analysis. A component is simply an output of principal component analysis?
Comment: Yes. I believe the package is using "component" as shorthand for "principal component" in the output that you quoted.
Answer: Actually there are two lines, one for the pca and the other for the minres procedure (default) unless another is selected.  The program uses the fa$values and the eigenvalues fa$e.values.  The fa$values are the values from the common factor solution. The fa$values are less than the eigenvalues.


Confidence interval for a binomially distributed observation with few trials?

Question: If there are few trials and you want to get the confidence interval of a binomially distributed observation, is it still okay to use the normal approximation interval, or is that only accurate for a large n (following central limit theorem)?
If it's not accurate, how else can the confidence interval determined when the sample is small?
Answer: For small sample sizes, usually the Clopper-Pearson exact CI is appropriate, although it should be emphasized that it will frequently have a coverage probability well in excess of the desired confidence level.
http://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval


How do I convert a DateTime variable to return date in the 'mm/dd/yy' format

Question: private DateTime OrderDate;
OrderDate = Convert.ToDateTime("05/20/15")

How do I assign the above OrderDate variable a value of 05/20/15.
I tried using Convert.ToDateTime, but it seems to work for yyyy format but not yy.
Comment: All you've shown is a field. That's just a date and time - it doesn't have a format. We have no idea how you're converting that to or from a string...
Comment: Each `DateTime` object has different attributes just like `Year`, `Month` and `Day`... You can easily initialize them by valid integer values you would like...
Comment: @Jon Skeet - I have modified my question now.
Answer: You will want to create a new date time object and assign it to the property.
OrderDate = new DateTime(2015, 5, 20);

Comment: I think he is talking about a 2 digit year that he has in his format. e.g. 15 instead of 2015
Comment: @Rob: The variable is just a `DateTime`. It doesn't have a format. You can format it using `ToString` and providing whatever format you want. It's really important that you understand the difference between what the `DateTime` stores, and how it can be represented in a string...
Comment: He is asking how his date time property can be assigned this value. He needs to change his question for what you are suggesting.
Comment: Thanks. I need the OrderDate in mm/dd/yy format. So, the variable should return me a date of 05/20/15.
Answer: To assign it, you would use OrderDate = new DateTime(2015, 5, 20);
When displaying the value the .Net Framework will use the local culture or your machine.
If you want to use a different display format, (without changing the culture) you can use String.Format("{0:MM/dd/yy}", OrderDate)
Comment: Thanks. I need the OrderDate in mm/dd/yy format. So, this DateTime variable(not string) should return me a date of 05/20/15.
Comment: What you're actually asking for ... is that the DateTime *value* should be **decoded** into a printable string that conforms to a particular, specified, *format.*  You do that by asking for the value to be decoded, and supplying the format-string that you want to use.  Remember that "the 'value of'" a DateTime, internally speaking, is "just a floating-point number."  But its value is *opaque.* You don't care what it actually is.  You can **encode** a string (or a vector of numbers) to produce it, then **manipulate** it (using provided *methods*!), then finally **decode** it for printing.
Comment: @Rob, I'm pretty sure (open to correction here) that the date format you see when you inspect the variable is driven by the culture of your machine.  The internal implementation of `DateTime` is culture agnostic - it stores a date in its own way, the format/culture etc. only matters when you wish to display it and (as numerous posters have already pointed out) the default format is machine culture dependent but (again, as pointed out by many) there are techniques and classes allowing you to control this.
Answer: Lots of info about converting/formatting dates you can find here:
https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/8kb3ddd4%28v=vs.110%29.aspx
I guess in particular you need this example:
MSDN snippet:
public class Example
{
   public static void Main()
   {
      string[] dateValues = { "30-12-2011", "12-30-2011",
                              "30-12-11", "12-30-11" };
      string pattern = "MM-dd-yy";
      DateTime parsedDate;

      foreach (var dateValue in dateValues) {
         if (DateTime.TryParseExact(dateValue, pattern, null,
                                   DateTimeStyles.None, out parsedDate))
            Console.WriteLine("Converted '{0}' to {1:d}.",
                              dateValue, parsedDate);
         else
            Console.WriteLine("Unable to convert '{0}' to a date and time.",
                              dateValue);
      }
   }
}
// The example displays the following output:
//    Unable to convert '30-12-2011' to a date and time.
//    Unable to convert '12-30-2011' to a date and time.
//    Unable to convert '30-12-11' to a date and time.
//    Converted '12-30-11' to 12/30/2011.

Comment: I imagine that Jon Skeet might disagree that that's everything one needs to know :)  But it should suffice for the original question.
Comment: Yes, you are right. I'll update my text to "Lots of info about".. to prevent further discussion about this type of textual details :)
Answer: You can't, Unless you change the date string  to the correct format, it cannot guess which millennium you are reffering.
or you can take each part of the date sepretly and pass it in the constructor:
OrderDate = new DateTime(2015, 5, 20);

Answer: You can use DateTime.ParseExact to achieve this
DateTime OrderDate = DateTime.ParseExact("05/20/15", "MM/dd/yy", CultureInfo.InvariantCulture);

Answer: I would use DateTime.TryParseExact:
DateTime time;
if (DateTime.TryParseExact("05/20/15", "MM/dd/yy", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out time))
{
   do something ...
}


Get a notification if a new version (tag) is created

Question: Before there was a RSS fead that got update if a new release of drush is available, see question:
Getting an email notification when a new Drush version is available.
But after drush is moved to github it seems that the RSS feed does not get updated anymore.
Is there a possibility to get an email notification if a new release tag is created on the github site?
Answer: Not directly through Github, but check https://sibbell.com
It's notifies you of new Github releases.
Answer: Doesn't the standard release feed work for Drush?
https://github.com/drush-ops/drush/releases.atom
Anyway, this questions isn't really about Drush, but about Github and the feeds they provide. I suspect somebody will close this question ;-)
Added: Looking closely at the question, I see that what is requested is an email notification. Then probably the other answer is better. My bad.


Função com quantidade variável de parâmetros, qual melhor maneira de fazer?

Question: Gostaria de fazer uma função sem definir a quantidade de parâmetros necessários. Quais as maneiras ou alternativas que posso utilizar para obter esse resultado?
Answer: Pode usar o .call() ou o .aplly ou mesmo chamar a função da forma mais convecional, e dentro da função, usar a palavra reservada arguments
function foo() {
    console.log(this, arguments);
}
foo.call('foo', 1, {animal: 'cão'}, 3)
foo.apply('foo', [1, {animal: 'cão'}, 3])
foo('foo', 1, {animal: 'cão'}, 3, 4);

http://jsfiddle.net/NDZeV/
Estas 3 maneiras diferentes de chamar uma função e passar argumentos dão o mesmo resultado nos dois primeiros casos.
'foo', // usando o call() e o apply() o primeiro argumento é o this
Arguments[3] // aqui o arguments têm em forma tipo array os restantes argumentos
    0: 1                // o mesmo que arguments[0], ou seja 1
    1: {animal: 'cão'}  // o mesmo que arguments[1], ou seja {animal: 'cão'}
    2: 3                // o mesmo que arguments[2], ou seja 3

No caso do ultimo exemplo, chamando a função diretamente o this é relativo ao escopo em que se está, provavelmente window e não tem a ver com os parametros passados à função. Neste caso o àrgumentstem somente valores passados da forma mais comum ou sejafunc(a, b, c)`. Neste exemplo de código acima isso dá:
window, // aqui o "this" nõ tem a ver com os parametros da função e vai buscar o valor do this no escopo em que a função estiver
Arguments[3] // argumentos
    0: 'foo'            // o mesmo que arguments[0], ou seja 'foo'
    1:                  // o mesmo que arguments[1], ou seja 1
    2: {animal: 'cão'}  // o mesmo que arguments[2], ou seja {animal: 'cão'}
    3: 4                // o mesmo que arguments[3], ou seja 3
    4: 4                // o mesmo que arguments[4], ou seja 4

Este objeto arguments é uma variável local da função e não é um array mas sim como o @bfavaretto indicou é um array-like object, e partilhar por exemplo a  propriedade length das arrays.
MDN:

arguments
.call()
.apply()
Comment: Uso parametros nomeados. Tem ajax em toda aplicacao e sempre tenho que criar a string data com os parametros e valores para enviar ao Controller C#. Ai gostaria de montar essa função para simplificar.
Comment: Se eu chamar a função foo(numero), onde int numero = 10; Como dar um alert dessa variavel dentro da função?
Comment: Obrigado @bfavaretto. Só mais uma pergunta. Se eu quiser dar um alert que mostre o nome da variável, como ficaria?
Comment: @JoaoPaulo como assim, o que quer dizer com "o nome da variável"?
Comment: @bfavaretto tens toda a razão. Vou corrigir...
Comment: Se eu chamar foo(numero, letra) e quiser mostrar na tela a string "numero" e "letra", ou seja, o nome das variaveis que passei como parametro.
Comment: @JoaoPaulo, para ter nomes têm de usar objectos, aí tem de usar `Object.keys(numero);`, se quiser saber que tipo de variável é tem de usar o `typeof`. Pode especificar melhor qual deles procura?
Comment: O meu objetivo final é fazer uma função que crie uma string montando um objeto Json. quando eu chamasse foo(numero, letra); ai ficaria assim: "{ 'numero': '1', 'letra' :'A' }"; Por isso, gostaria de extrair o nome da variavel.
Comment: @JoaoPaulo Não dá para extrair os nomes dos parâmetros da função. Quer dizer, até dá, mas é uma baita gambiarra. Agora, o que você queria não era justamente passar qualquer quantidade de parâmetros? Nesse caso você não usaria parâmetros nomeados, certo?
Answer: A resposta do Sergio é excelente e concordo que seja a correta. Vou deixar uma alternativa apenas para aumentar o leque de opções para quem quiser trabalhar com múltiplos parâmetros.
Existe uma técnica que é receber um único parâmetro - um dicionário de opções. Essa técnica é utilizada em frameworks como o jQuery, por exemplo.
Um exemplo:
function AplicaCSS (options) {
    if (!options) return;
    var font = options.font || "arial 12";
    var height = options.height || "15px";
    var width = options.width || "100px";
    /*etc., etc.*/
}

Note que, dessa forma, você simplesmente passa um objeto cujas propriedades podem variar. Se eu chamar a função dessa forma:
AplicaCSS({font: "comic sans bold"});

... Funciona. Do jeito que a função está, as propriedades "faltantes" recebem valores padrão. Se eu chamar a função da seguinte forma:
AplicaCSS({height: "10px", width: "50px"});

... Ou:
AplicaCSS({});

... Ou mesmo:
AplicaCSS({bar: "lolwut"}); // Como é uma propriedade que não espero, 'bar' é ignorada.

... Funciona do mesmo jeito. Assim, a quantidade de parâmetros variáveis é do objeto que você passa, não da função em si. Isso lhe dá muita flexibilidade, além de você ter uma função com assinatura fixa e conhecida. Vale a pena também documentar as propriedades que você procura no objeto recebido, para quem for usar sua função ;)
Answer: você pode utilizar um array para os parametros ou seja não sendo necessário defini-los.
cria uma regra para tratar dinamicamente estes valores e resolveu seu problema.
Utilizo muito isso
Comment: Você podia acrescentar um exemplo a sua resposta.


Qual a diferença entre dynamic e Object?

Question: Qual a diferença entre utilizar dynamic e Object no Dart?
Por exemplo, funções que não sei o tipo de retorno:
Future<dynamic> getQuery ou Future<Object> getQuery

Para fazer casting:
final myvar = myReturn as dynamic

final myvar = myReturn as Object

Answer: Object é um tipo como outro qualquer que é usado como base para os outros tipos e possuem alguns poucos membros conforme pode ver na documentação. Então ele é usado mais para compor outros tipos ou indicar que você aceita qualquer objeto em determinado local do código (o que está fazendo na pergunta).
Se estiver acessando o objeto por esse tipo só pode ver os membros de Object mostrado na documentação. Só poderá acessar outros membros se fizer um cast para um subtipo, o que só é possível se o objeto concreto for desse subtipo (se não for a aplicação quebra).
Então ele é uma generalização, uma abstração, mas é um tipo regular muito simples e que não tem utilidade específica.
dynamic (notou o minúsculo?) não é um tipo, é uma indicação que o objeto pode ser de um tipo qualquer e qualquer coisa que você tente acessar o compilador deixará sem dar erro (não quer dizer que funcionará, poderá dar erro durante a execução se o objeto concreto não possuir o membro que está acessando). É só uma sintaxe para desligar a verificação de tipos.
Então o objeto que foi declarado que será dinâmico permite trabalhar livremente como acontece em uma linguagem de tipagem dinâmica sem impedir a compilação porque está acessando um membro que não existe. Ele deixa a aplicação mais lenta, além de menos robusta.
Eles parecem iguais porque a ideia é poder não definir o tipo exato, mas a forma como lida com isso é bem diferente. O Object tem pouca utilidade real, você precisa converter para um subtipo para fazer uso específico de alguma funcionalidade do objeto, enquanto que dynamic subverte o sistema de segurança de tipos.
Em todas linguagens que tem esses mecanismos vejo os programadores abusando, em geral eles são menos necessários do que parece quando tem disponível generics e outros mecanismos mais seguros e úteis. Em Dart não é diferente, é mais robusto e as vezes mais fácil usar um objeto específico, mesmo que de forma genérica. Raros os casos que precisa aceitar um objeto qualquer ou um objeto que você não sabe sua composição.
Coloquei no GitHub para referência futura.