Updating a dataframe from another one does not work

Question: I have used the following approach many times and it works fine when one wants to update values in one dataframe from another dataframe. However, I have two dataframes that don't want to work. Below are the steps I follow. I can not figure out why this does not work. What am I missing? Can someone maybe point me to possible causes I could investigate:
Original value for "mydate" is 'not found' in df:
print(df.loc[df.FileName == '100212']['mydate'])
Out:
406    'not found'
Name: mydate, dtype: object

My "new date" value from lookup df1 is '10-2-1997'
print(df1.loc[df1.FileName == '100212']['new date']
Out:
2766    10-2-1997
Name: new date, dtype: object

The following should update "mydate" in df with "new date" in df1:
df.loc[df.FileName.isin(df1.FileName), ['mydate']] = df1['new date']

But instead of '10-2-1997' I get 'NaN':
print(df.loc[df.FileName == '100212']['mydate'])
Out:
406    'NaN'
Name: mydate, dtype: object

Answer: Series assignment is performed by index. But indices don't align between your two dataframes. You can use pd.Series.map with a series instead:
series_map = df1.set_index('FileName')['new date']
df['mydate'] = df['FileName'].map(series_map).fillna(df['mydate'])

Using fillna afterwards ensures df['mydate'] remains unchanged when filenames are not common between the two dataframes.
Comment: No problem, at 15 reputation you now have the [privilege to upvote](https://stackoverflow.com/help/privileges/vote-up) answers that helped :).


Is a finitely generated extension of a real closed field also real closed?

Question: Let $\widetilde{\mathbb{Q}}$ be the field of real algebraic numbers, and consider $\widetilde{\mathbb{Q}}(\pi)$. My question: is $\widetilde{\mathbb{Q}}(\pi)$ a real closed field?
Bonus karma points if you can say something about the general claim: Every finitely generated field extension of a real closed field is also real closed.
Thanks!
Comment: No to both. Characterization 5 [here](http://en.wikipedia.org/wiki/Real_closed_field) and a basic understanding of Galois theory should quickly demystify both questions.
Comment: The general claim is false, and $\widetilde{\mathbb{Q}}(\pi)$ is a counterexample.
Answer: Hint: If your field were real-closed, then it would contain $\sqrt[3]{\pi}$. It it did, then $\pi$ would be algebraic.


Mend reshape-based habits with plyr: melt/cast vs. ddply

Question: I'm kind-of used to do melt and cast all the time, and this time I'm looking for neat one-liner.
require(reshape)
# first I melt some data:
m <- melt(mtcars, id.vars = c("cyl", "am"), measure.vars = "hp")
# then cast it:
cast(m, cyl + am ~ ., each(min, mean, sd, max))
  cyl am min      mean       sd max
1   4  0  62  84.66667 19.65536  97
2   4  1  52  81.87500 22.65542 113
3   6  0 105 115.25000  9.17878 123
4   6  1 110 131.66667 37.52777 175
5   8  0 150 194.16667 33.35984 245
6   8  1 264 299.50000 50.20458 335

Is this possible with ddply or smth? I'm desperate for a one-liner. I tried:
ddply(mtcars, cyl + am ~ hp, each(min, max))
   cyl am  hp min   max
1    4  0  62   0 146.7
2    4  0  95   0 140.8
3    4  0  97   0 120.1
4    4  1  52   1  75.7
5    4  1  65   1  71.1
6    4  1  66   1  79.0
7    4  1  91   0 120.3
8    4  1  93   1 108.0
9    4  1 109   1 121.0
10   4  1 113   1 113.0
11   6  0 105   0 225.0
12   6  0 110   0 258.0
13   6  0 123   0 167.6
14   6  1 110   0 160.0
15   6  1 175   0 175.0
16   8  0 150   0 318.0
17   8  0 175   0 400.0
18   8  0 180   0 275.8
19   8  0 205   0 472.0
20   8  0 215   0 460.0
21   8  0 230   0 440.0
22   8  0 245   0 360.0
23   8  1 264   0 351.0
24   8  1 335   0 335.0

of course, this works, but not by summarising hp by cyl and am. It's bit a while since I used plyr and reshape so I kind-of lost my muscle... so... excuse-moi pour une question triviale... =/
Answer: summmarize may be your friend:
ddply(m, c("cyl", "am"), summarize
      , min = min(value)
      , mean = mean(value)
      , sd = sd(value)
      , max = max(value)
)

  cyl am min      mean       sd max
1   4  0  62  84.66667 19.65536  97
2   4  1  52  81.87500 22.65542 113
3   6  0 105 115.25000  9.17878 123
4   6  1 110 131.66667 37.52777 175
5   8  0 150 194.16667 33.35984 245
6   8  1 264 299.50000 50.20458 335

Comment: yepp, that was the one! thanx!
Answer: Using plyr:
> require(plyr)
> ddply(mtcars,c("cyl","am"),summarise, min=min(hp), mean=mean(hp), sd=sd(hp), max=max(hp))
  cyl am min      mean       sd max
1   4  0  62  84.66667 19.65536  97
2   4  1  52  81.87500 22.65542 113
3   6  0 105 115.25000  9.17878 123
4   6  1 110 131.66667 37.52777 175
5   8  0 150 194.16667 33.35984 245
6   8  1 264 299.50000 50.20458 335

Comment: sorry mate, @Chase beat you by 3 seconds, so he gets the checkmark. =/ But thanx a lot!
Answer: > ddply(mtcars, .(cyl, am), summarise,
        min=min(hp), mean=mean(hp), sd=sd(hp), max=max(hp))
  cyl am min      mean       sd max
1   4  0  62  84.66667 19.65536  97
2   4  1  52  81.87500 22.65542 113
3   6  0 105 115.25000  9.17878 123
4   6  1 110 131.66667 37.52777 175
5   8  0 150 194.16667 33.35984 245
6   8  1 264 299.50000 50.20458 335

I'm not sure how to avoid having to name each function twice, though...
Comment: using `with` and `each`, `ddply(mtcars, c("cyl", "am"), with, each(min, mean, sd, max)(hp))`
Comment: @baptiste, if you put this as an answer, I'd be glad to checkmark it, since it's a perfect answer! Exactly what I was looking for!


Spring Integration TCP Low Volume or High Volume Determination

Question: Our use-case is to use a Single TCP Connection (never close) and perform a request-reply model, while the next message waits until the reply is received for the current request (block mode). Should we consider 60 messages / min as Low-Volume or High-Volume, this will help us determine whether to use a Gateway or pair of Adaptors. Thanks
Answer: That would not generally be considered to be high volume, but only you can determine which architecture provides the performance you need.
e.g. the 60 messages come in 5 seconds and then no messages for 55.
Comment: It's only an issue if the request/reply is long and you have multiple threads sending requests. The connection can only be used by one request/reply at a time; there is no correlation in this case since the reply will always be for the current request.
Comment: Thanks Gary, 60 messages are more or less evenly distributed over a minute. Just for knowledge purpose, is that the overhead of correlating the `request-reply` in high-volume transactions the real concern with `gateways`? As anyways correlation has to be done either by the framework or the application anyhow right?


Problem with _update_by_the_query elastic search

Question: Elasticsearch version is about 7.x
I want to update all documents in an index and I find in the documentation that I have to use "_update_to_the_query".
This is the code:
curl -XPOST 127.0.0.1:9200/hamlet-raw/_update_by_the_query -d'
{
"query": {
"match_all": {}
},
"script" : {
"speaker": "Hamlet"
}
}'

and I get this error:
{"error":{"root_cause":[{"type":"illegal_argument_exception","reason":"Invalid type: expecting [_doc] but got [_update_by_the_query]"}],"type":"illegal_argument_exception","reason":"Invalid type: expecting [_doc] but got [_update_by_the_query]"},"status":400}

why? Any advice on update all documents by adding a new field and value ?
thank you.
Answer: Look the example in doc update by query using scripts:
Add your script inside section source.
POST my-index-000001/_update_by_query
{
  "script": {
    "source": "ctx._source.speaker = 'hammelt'",
    "lang": "painless"
  },
  "query": {
    "match_all": {}
  }
}

Comment: mmh, how can I add a new field "speaker" with value "xxx"?


Can I output the Focusrite Scarlett 2i2 to a guitar amp?

Question: Since i don't own speakers, and I don't want to use Headphones, I was looking for an alternative solution.
I want to input my guitar and use amplitube and then output to the guitar amp.
I have a roland cube, it has the guitar input and an aux line in too.
My question is wich output of the Scarlett (headphones, speaker L, R) goes to wich input of the amp (aux line in, guitar in)?
and is it possible without damaging anything?
Thanks
Answer: Try both the guitar input as well the aux input on the Cube, they're going to sound different. With the aux input you'll bypass the Cube's preamp processing. You can't break the Cube with the Scarlett. The Scarlett's headphone output is stereo and it could be connected to the aux input with a suitable stereo cable. Just don't turn the phones level too high. That way you'll get both sides of Amplitube's stereo effects to the Cube, but it's a mono speaker only so you won't hear any of the stereo field. If you go to the Cube's guitar input, connect the Scarlett's left or right output to the Cube's input.
Since the Cube is a guitar amp with a speaker, you might want to bypass Amplitube's speaker modeling and maybe use its preamp and stompbox pedal effect modeling only, maybe power amp modeling as well. The Cube will provide the speaker part. I don't know Amplitube so I can't tell what these are called there.
Comment: Each of the L and R outputs are mono. You could connect them to two separate amps if you wanted to. The headphone output is stereo and needs a TRS plug.
Comment: Just to understand: I go out of Scarlett headphone and plug it to amp Line in aux. And if I plug into L or R of Scarlett I got L and R Mono


Method to develop a key change?

Question: I know this question may seem broad, but I am a very mathematical person, I've never had much "ear" for these things.
I have a slow tempo song, about 90bpm with a VI - I - IV chord progression for a chorus, however when heading into my bridge I am adding a V onto the end  for transition into another key, I can hear it in my head so clearly, but nothing I play can satisfy me.
Is there a technical solution to knowing which key to jump into next? And also, for knowing where in that key to start?
For reference the key is E.
And I really like the V for moving keys, I would like to keep it I just don't know where to go from there.
Comment: What key are you transitioning to and from?
Comment: The question doesn't really make any sense unless you can give a bit more info. What are the chords of the bridge? Your chorus is: ||:C#min / E / A :|| it sounds like? What are the chords of the bridge? What style is the tune/song? I'm assuming that your are looking for some sort of V to lead into the Bridge. Does it change key, or stay in E? There are lots of ways to transition, and all very "mathematical", but if you could spell out the chorus, with or w/o the V you want to add, it would be a lot easier to figure out what you're looking for.
Comment: From E. I can't figure out where to go. That's sort of what this question means.
Comment: You can jump from any key to any other key with the right progression.  I'd recommend reading Modulation by Max Reger.  It will appeal to your mathematical mind.  Cadence!
Comment: Simple: use a secondary dominant. Simply make the 2nd to last chord of your profession either a ii or a IV of new key, make your last chord a V in the new key and boom, new key. If you want to be sneaky use common tones and pivot chords. If you want to be bold, don't.
Answer: How to develop a good key change depends largely on what key you are transitioning to and from.  As a mathematically-oriented person, you can probably find logic in the notion that you want to transition over chord progressions that are shared between both keys, preferably leading to the dominant of the new key (V) and then resolving to the tonic of the new key.  This is one of various techniques for implementing a key change, but the most reliable.
If you can work in the subdominant of the new key as well, all the better, as in this classic example by The Beach Boys, "Don't Worry Baby," which transitions up a whole step from E to F# using a progression that is a very simple to understand and useful example:
The main progression is:

E: I - IV - V - I
Well, it's been building up in side of me for, oh, I don't know how long...

To transition to the new key, the song uses ii - V in the original key followed by "ii - V" in the new key, before resolving to the tonic of the new key.

ii - V
but she looks in my eyes
iii(F#: ii/I) - VI(F#: V/I)
and makes me realize (when she says)
F#: I - IV - V - I
F#: Don't worry baby

Note that the transition involves setting up a chord progression that resolves to the tonic of the new key by transitioning to the chords relative to the new key, but with some overlap with the old key (iii in E, ii (supertonic functioning as subdominant) in F#).
Answer: Sounds like your sequence is C# (or C#m) to E to A for the chorus. Then you want to put a B at the end somewhere. That B (V of E) is almost duty bound to expect an E after it. After all, it is the dominant chord of E.
To modulate, or change key, you need the dominant of that key. Let's say the new key will be F, then you'll need C to get there.
If you wanted to go back into a chorus, the usual way is to play the dominant of the first chord, at the turnaround. In your original, it would be G# - leading to either C# or C#m.
Answer: If you don't want B7 to lead back to E, try going to C#m, C# major, C major, Bbmajor.  We can give those 'theory' explanations as leading-note resolutions, interrupted cadences or a b5 substitution.
But 'Theory describes, it does not command'.  Theory can be good at describing and labelling what you've done, it's not so good at telling you WHAT to do!
Is there a melody to this song?  Where do you want it to go?

Method to develop a key change?


Bash echo 3 variable (2 translate, 1 as text) problem

Question: I made a bash script to generate a vhost file for my apache.
The problem is:
I have 3 variables in it.
2 are bash variables, defined in the .sh, and I want them to be expanded.
1 is APACHE_LOG_DIR variable and of course, I want it to be as literal text to be interpreted after.
I have tried
echo "$var1 $var2 $var3" -> all expanded
echo '$var1 $var2 $var3' -> all not expanded

echo "
    ErrorLog ${APACHE_LOG_DIR}/$client-$version-error.log
" >> ./myfile

I want $APACHE_LOG_DIR to be literal text,
$client $version to be expanded
Answer: Try
echo '$var1 '"$var2 $var3"

or
echo "\$var1 $var2 $var3"

Comment: Good for you figuring out what he meant. Now that I understand, I've edited the question to say it more clearly.
Comment: Thanks so much ! the \ before $var1 worked perfectly well


Flowout Theorem

Question: I am reading Theorem 9.20 (Flowout Thoerem) from Lee's Introduction to Smooth Manifolds, Second edition.
A part of the theorem states the following:
Let $M$ be a smooth manifold and $S$ be a $k$-dimensional embedded submanifold in $M$. Let $V$ be a smooth vector field on $M$ which is nowhere tangent to $S$. Let $\theta:\mathcal D\to M$ be the maximal flow associated with $V$, and let $\mathcal O=(\mathbf R\times S)\cap D$. Let $\Phi=\theta|_{\mathcal D}$.

Then $\partial/\partial t\in \mathfrak X(\mathcal O)$ is $\Phi$-related to $V$.

First Question: What is $\partial/\partial t$? Is it defined as
$$
d(id\times \varphi)_p\left(\frac{\partial}{\partial t}\Big|_p\right)=(1; 0,\ldots, 0)\in \mathbf R\times \mathbf R^k
$$
where $id\times \varphi$ is a smooth chart on $\mathcal O$? If yes then we should also check that this is well-defined.
Second Question: What is the theorem trying to say geometrically? I can verify the details given in the proof but am having no insight as to what is really being said.
Thanks.
Answer: The vector field $\partial/\partial t$ is just the standard coordinate vector field on $\mathbb R$. By means of the canonical identification of each tangent space to a product manifold with the direct sum of tangent spaces of the factors, we can view it as a vector field on $\mathbb R\times S$. It's canonically defined, so there's no need to check that it's well defined.
As for what the theorem means geometrically, I tried to suggest the geometric meaning in the illustration that comes with it (see below). The idea is that you start with a $k$-dimensional submanifold $S$, and then flowing out along integral curves of $V$ gives you a certain $(k+1)$-dimensional submanifold containing $S$, to which $V$ is tangent.
(BTW, there's a typo in your transcription of the theorem statement -- the definition of $\mathcal O$ should be $(\mathbb R\times S)\cap \mathcal D$, not $(\mathbb R\times S)\times \mathcal D$.)
Comment: You made a typo in the same too! It is $(\mathbf R\times S)\cap \mathcal D$, not $(\mathbf R\times S)\cup \mathcal D$.
Comment: I see. This has a nice geometric meaning. My main hindrance was a lack of understanding of what $\partial/\partial t$ means. This clarifies it.
Comment: Good grief. Fixed now. Thanks.

Flowout Theorem


Is it possible to get fitted values 0 or 1 in logistic regression when the fitting algorithm converges?

Question: We have comprehensive coverage on the topic of perfect separation in logistic regression. When it happens in R we usually see two warnings:

Warning messages:
  1: glm.fit: algorithm did not converge
  2: glm.fit: fitted probabilities numerically 0 or 1 occurred

Is it possible that the algorithm did converge and fitted probabilities numerically 0 or 1 occurred nonetheless?
Comment: The problem seems related to the "vanishing gradient" issue in deep learning (i.e. for logistic near 0 or 1, gradient is near 0). The answer may depend on details of the numerical implementation, but the question seems more general. So I think it is on topic.
Answer: R is giving you two different warnings because these really are two distinct issues.
Very loosely, the algorithm that fits a logistic regression model (typically some version of Newton-Raphson) looks around for the coefficient estimates that will maximize the log likelihood.  It will estimate the model at a given point in the parameter space, see which direction is 'uphill', and then move some distance in that direction.  The potential problem with this is that when perfect separation exists, the maximum of the log likelihood is where the slope is infinite.  Because a search algorithm has to be designed to stop at some point, it doesn't converge.
On the other hand, no matter where it stops, whether it converged or not, it is (theoretically) possible to calculate the model's predicted values for the data.  However, because computers use finite precision arithmetic, when they perform the calculations, they eventually need to round off or drop extremely low decimal values.  Thus, if the arithmetically correct value is sufficiently close to 0 or 1, when it is rounded, it can end up being 0 or 1 exactly.  Values can have that property and be within the normal range of the data due to an extremely large (in absolute value) slope estimate due to complete separation, or they can just be so far out on X that even a small slope will lead to the same phenomenon.
<code># I'll use this function to convert log odds to probabilities
lo2p = function(lo){ exp(lo) / (1+exp(lo)) }
set.seed(163)                             # this makes the example exactly reproducible
x  = c(-500, runif(100, min=-3, max=3), 500)  # the x-values; 2 are extreme
lo = 0 + 1*x
p  = lo2p(lo)
y  = rbinom(102, size=1, prob=p)

m  = glm(y~x, family=binomial)
# Warning message:
# glm.fit: fitted probabilities numerically 0 or 1 occurred
summary(m)
# ...
# Coefficients:
#             Estimate Std. Error z value Pr(>|z|)
# (Intercept)   0.3532     0.3304   1.069    0.285
# x             1.3686     0.2372   5.770 7.95e-09 ***
# ...
#
#     Null deviance: 140.420  on 101  degrees of freedom
# Residual deviance:  63.017  on 100  degrees of freedom
# AIC: 67.017
#
# Number of Fisher Scoring iterations: 9
</code>
Here we see that we got the second warning, but the algorithm converged.  The betas are reasonably close to the true values, the standard errors aren't huge, and the number of Fisher scoring iterations is moderate.  Nonetheless, the extreme x-values yield predicted log odds that are perfectly calculable, but when converted into probabilities, become essentially 0 and 1.
<code>predict(m, type="link")[c(1, 102)]      # these are the predicted log odds
#         1       102
# -683.9379  684.6444
predict(m, type="response")[c(1, 102)]  # these are the predicted probabilities
#            1          102
# 2.220446e-16 1.000000e+00
</code>
Comment: @hxd1011, I mostly do it to make the code more immediately intuitive for people who don't use R.
Comment: thanks for your answer. it is very clear. I suspect they are two separate issues, but always see they come together (when perfect separation occur.) Today, I saw only 2nd warning, without first one, my first reaction is "does my algorithm converge"? That is why I am asking this question...
Comment: why we define `lo2p` function? why not directly use `plogis`? is that because `plogis` has protections on numerical overflow?
Comment: @whuber commented my [another question](https://stats.stackexchange.com/questions/230318/how-to-deal-with-not-a-number-nan-in-logistic-loss) on log underflow, is that related? Thanks!!
Comment: thanks, you are really thoughtful, I think that is why you got many upvotes,


Do I need to be concerned with drum tuning when using drum samples?

Question: I'm starting to get into writing and recording some music and am using synthesized drums for the time being. Do I need to be selecting samples based off drum tuning at all? For example, if I'm writing a song in C major vs G minor, can I (and should I) use the same samples in both tracks?
Comment: This might be a matter of opinion - plus it might depend on what kind of samples you're using. Normally I tune the drums to a frequency related to the shell's lowest resonant frequency and leave it there, without worrying about what key the song is in, but I've read about engineers and producers having drums tuned differently or using different drums based on the key of the song.
Answer: There's no correct answer, but I'd weight the argument this way...
If you're recording an entire album over many months, you may choose to pitch the drums specifically for each track, choose to mic the kit differently; even choose to record in a different room or facility.
If you're playing a live gig, no drummer is going to retune to fit each song. The audience will never notice anyway.
Anywhere between those two diametric opposites is the 'right' answer.
If your samples are meant to sound 'electronic' or 'repetitive' then retuning may spoil the final feel.
If it's meant to be reproducing a 'real live' drummer, then having multi-velocity samples & round-robin triggers is going to be far more important inside any given track than the fact that the drummer didn't buy an entire new kit for the next track.
after Todd's apropos comment
If anyone books me for a session, I'd assume it's because they already know what my kit & playing style sound like. If they want me to suddenly pull a Black Beauty out of my traps, rather than my usual piccolo... then they booked the wrong drummer ;-)
If I'm doing a drum track based on samples, I've got most of ToonTracks' Superior to go at & will use the one most appropriate [to either single track or whole album]
I think my TL:DR would be - go with what feels right.
TL:DR part 2 would be
don't just retune because the key changed - drums have natural pitches they sound 'best' at, though also 'fake' pitches you can convince a nice noise from - either is 'correct'.
Comment: From slightly different angles - tympani get tuned to specific notes, and the advent of Rototoms changed tuning perceptions somewhat.


Comparing proportions in the same sample

Question: I gathered 11 responses to a question where the options were A, B, or C.
9 people answered A. 2 people answered B. 0 people answered C.
Using Clopper-Pearson 95% confidence intervals, I obtained that P(A) ranges from (0.48, 0.97), P(B) ranges from (0.2 to 0.52), and P(C) ranges from (0, 0.28).
What statements can I make these results? Can I say that P(A) > P(C) at 95% confidence level? Seems like it would be more than that.
Answer: You are making 3 comparisons instead of one (multiple testing), so you have to account for it in computing you confidence intervals.
Instead of 5% as an acceptable risk, you have to take a lower value like 5%/3=1,66% (Bonferonni correction). In that case you would calculate the 98.34% confidence interval.
That way, the global risk to make a wrong conclusion rejecting HO (no difference) across the 3 comparison is truly 5%.
Comment: Check your calculations.
Comment: You are right, there was a mistake. Edited.


List top 404 URLs in Apache access_log

Question: I'm looking for a command to list the 10 or 20 top 404 error URLs out of my apache access_log. Can anyone help me with this?
thanks
Answer: Assuming the normal access_log format this should do it:
cat access_log | awk '{ if($9 == 404) { print $7 } }' | sort | uniq -c | sort -nr | head -10

Comment: `sort -r` sorts alphabetically in reverse, so it will put "1", "10" and "100" after "2". You should use numeric reverse sort: `sort -nr`.
Comment: There is no need to use cat and pipe the output to awk. awk can read files itself ;) `awk '{ if($9 == 404) { print $7 } }' access_log | sort | uniq -c | sort -nr | head -10`
Comment: I hadn't thought of the field math, good call. I edited to fix the error code.
Comment: @packs That was fast, I just noticed the issue when I double checked it again and you got to it before I could. :)
Comment: Ninja edit!
Comment: Per Christian Davén, sort -nr should be fixed in the answer, I had all my urls with a count of 9 up top rather then the ones with 1000's
Answer: I've done this using standard unix utilities, awk, sort, etc, and it works fairly well. Since the format of your logs could be different, you may have to change some things to work in your environment, but the basic command would be this:
cat access_log | awk '/" 404 / {print $7}' | sort | uniq -c | sort -n | tail -n10
If you are not familiar with awk, what we are doing is:
for each line
   if it contains the string '" 404', then
     print the 7th field (where fields are space delimited)

If you are using a custom apache log format, then you will need to change the $7 to match the field for the URL in the GET request.  You can also change the number of lines from the tail command to display more, or rewer, results.

List top 404 URLs in Apache access_log


Solution check: summation inequality proof by induction

Question: I'm not sure if what I've done works or if it's proof enough.
(I need to prove that the inequality is true $\forall n \in \mathbb{N}$).
$\sum_{i=n}^{2n} \frac{i}{2^i} \leq n$
$P(1)$ works. I assume the inequality to be true for $n$.
$(\sum_{i=n}^{2n} \frac{i}{2^i}) + 1\leq n + 1$
$(\sum_{i=n}^{2n} \frac{i}{2^i}) + \frac{2n+1}{2^{2n + 1}}\leq (\sum_{i=n}^{2n} \frac{i}{2^i}) + 1\leq n + 1$
I'm stuck.
Answer: To be proved: $\displaystyle \sum_{i=n}^{2n} \frac{i}{2^i} \leq n$
Base case: $n=1$, $\displaystyle \sum_{i=1}^{2} \frac{i}{2^i}=1 \leq 1$ which works.
Assume that for some $n$, $\displaystyle \sum_{i=n}^{2n} \frac{i}{2^i} \leq n$
Consider, for $n+1$, $\displaystyle \sum_{i=n+1}^{2(n+1)} \frac{i}{2^i} \leq n+1$
$\displaystyle \sum_{i=n+1}^{2n+2} \frac{i}{2^i} \leq n+1$
$\displaystyle \sum_{i=n}^{2n} \frac{i}{2^i}+\frac{2n+1}{2^{2n+1}}+\frac{2n+2}{2^{2n+2}}-\frac{n}{2^{n}} \leq n+1$
Consider now the inequality:
$\frac{2n+1}{2^{2n+1}}+\frac{2n+2}{2^{2n+2}}-\frac{n}{2^{n}}≤1$
Prove this inequality to be true, and in conjunction with the assumption and the base case the inductive proof will be complete.
EDIT:
To be neat and tidy, you might want to, following your original line of thinking, say:
Assume that for some $n$, $\displaystyle \sum_{i=n}^{2n} \frac{i}{2^i} \leq n$
Then, $\displaystyle \sum_{i=n}^{2n} \frac{i}{2^i} +1 \leq n+1$
But, $\frac{2n+1}{2^{2n+1}}+\frac{2n+2}{2^{2n+2}}-\frac{n}{2^{n}}≤1$
And so, $\displaystyle \sum_{i=n}^{2n} \frac{i}{2^i} +\frac{2n+1}{2^{2n+1}}+\frac{2n+2}{2^{2n+2}}-\frac{n}{2^{n}} \leq n+1$
Therefore, $\displaystyle \sum_{i=n+1}^{2(n+1)} \frac{i}{2^i} \leq n+1$.
Then, you can make the proper conclusion statement regarding induction (the inequality holds for base case $n=1$, and so holds for...)


What does this split stem notation mean?

Question: Here's sheet music for chopin's 2nd ballade. On page 6, in the 2nd measure in the 4th line of music, there's a D# and a D natural, with two lines coming out of them and connecting to the double bar (for the sixteenth notes). I was wondering how to play this bar. I think you have to play them at the same time, but I'm not sure.
Comment: This is a great example of an answer to this question: http://music.stackexchange.com/questions/3777/can-a-chord-contain-both-the-c-and-c%E2%99%AF-notes-as-opposed-to-containing-c-and-d%E2%99%AD
Answer: Yes, that's a "play both notes". See http://musescore.org/node/14449 for a note on the standard from the US Music Publisher's Association.
Comment: The USMPA pamphlet referenced can be found here: https://www.mpa.org/wp-content/uploads/2018/06/standard-practice-engraving.pdf
Answer: I'd like to supplement the reasoning behind this:

Note heads take space, and chords are typically sharing the stem or in absence of one are placed above each other.
If the note heads would overlap (due to very small interval between them) the first remedy is, to keep the note stem common and imagine one note head pushed to the other side of the stem (see last stem in the first 16th group). In case of whole notes lacking a stem (multi-voice) they would be placed beneath each other and the spacing has to be expanded to make clear, which notes belong together. (For an example see this question.)
If there would still be a collision (typically by an accidental, which would overlap with the stem or one/both note heads), the stem is split.

A special case (see this question) for split stem is, when the same note head needs to be notated twice, but with different accidentals. (All alternatives look even more weird.)
Answer: It's funny I saw the notation and recognized the piece right away. I can't play it very fast, but I recognized it!
Yes, it means to play both at the same time, but that's not all you want to do with this passage. If you notice there's a phrase in there that resides on the top notes. You want to balance the right hand so the top and bottom notes sound a bit louder than inner notes.


Regex Expression For Masking Characters

Question: I am using Notepad++ to mask out portions of strings in a text document.
I have strings similar to this:

B1541123412341234^TEST
  DATA^125000000,1541123412341234=00000000000125000000

I need to replace the 12 characters after B1541 with Xs. The result will look like this:

B1541XXXXXXXXXXXX^TEST
  DATA^125000000,1541XXXXXXXXXXXX=00000000000125000000

Any advice?
Comment: Is the B going to be in front of the second 1541 as well?
Answer: Replace (?<=B1541).{12} by XXXXXXXXXXXX (don't forget to tick the regexp checkbox in Notepad++).

Debuggex Demo
Comment: There can by any number of digits.
Comment: @Braj What do you mean?
Comment: There is no need that there is exactly 12 digits after 1541. If it is something like `B15411234^TEST DATA^125,154112341`
Comment: @Braj Then the OP should not have specify *the 12 characters after B1541* ;)
Answer: In Notepad++
Find what : 1541\d{12}
Replace with : 1541XXXXXXXXXXXX
output as expected:
B1541XXXXXXXXXXXX^TEST DATA^125000000,1541XXXXXXXXXXXX=00000000000125000000

Snapshot:
Answer: Capture the group of numbers you want:
(?<=B1541)(.{12})(.*?)\1(.*)

Replace:
XXXXXXXXXXXX\2XXXXXXXXXXXX\3

It finds 12 characters following B1541, then "anything", then the same characters again, then "anything else". It replaces both instances of the 12 characters with 12 'X' characters.
Live Demo (with digits only)
Live Demo (with any character)

Regex Expression For Masking Characters


How to return a response value from .post() into my function?

Question: I have some javascript validation where I check (among other things) if an email is taken, but I can't get it to work.
function validateField(input) {

    errors = false;
    messages = ''; //

    /*  Begin checks */

    if (input.hasClass('jEmailUnique')) {

        message = 'Email not taken';

        $.post('../ajax/j_validate.php', {

            step: 1,
            email: input.val()
        }, function(response){

            if (response != '0') {

                message = tipInvalid + message;

                errors = true;
            }
            else {

                message = tipValid + message;
            }

            messages += "
" + message + "
";
        });
    }

    /* End checks */

    if (errors == true) {

        input.addClass('jHasError').removeClass('jNoError');
    }
    else {

        input.addClass('jNoError').removeClass('jHasError');
    }

    setTip(input, messages); // show pop up window with error messages
}

Am I losing the scope of messages in the anonymous function in the post or something?
Comment: It is an asynchronous request. So the request will still be in progress while you are trying to use the `messages`  var. Which isn't yet filled.
Answer:
My guess is I'm losing the scope of messages in the anonymous function in the post. How can I pass these through?

You're not, but you're still doing it wrong. Your messages variable is global. Tack a var in front of it to scope it to its function.
You also need to call setTip(input, messages) in the callback, before then, messages is undefined.


how to pass cxxflag with mutli-parameters to boost.b2

Question: i want to pass c++14 and -fPIC to boost.b2 and buid static lib. use :cxxflags="--std=c++14 -fPIC" and occur below error:
g++: error: unrecognized command line option '--std=c++14 -fPIC'

    "g++"   -pthread -O3 -finline-functions -Wno-inline -Wall "--std=c++14 -fPIC" -DBOOST_ALL_NO_LIB=1 -DBOOST_ATOMIC_SOURCE -DBOOST_ATOMIC_STATIC_LINK=1 -DNDEBUG  -I"." -c -o "bin.v2/libs/atomic/build/gcc-5.4.0/release/link-static/threading-multi/lockpool.o" "libs/atomic/src/lockpool.cpp"

if delete the ", like this ./b2 cxxflags=--std=c++14 -fPIC link=static install, will occur below error:
PIC: No such file or directory
don't know how to make cxxflags=--std=c++14
don't know how to make link=static

at last, i workaround it like this:
./b2 cflags=-fPIC cxxflags=--std=c++14 link=static install

if need more than two parameter, it is no way now.
Answer: You can specify cflags= multiple times to add multiple flags


Showing that $L^{\infty}([0,1])$ is not strictly convex

Question: Can somebody give an example that shows that $L^{\infty}([0,1])$ (regarding $|| \cdot ||_{\infty}$) is not strictly convex?
Thanks in advance!
Comment: A good start would be to give the definition of a strictly convex space.
Comment: So if $L^{\infty}([0,1])$ would be strictly convex, that would mean that for $f,g \in L^{\infty}, ||f||_{\infty} = ||g||_{\infty} = 1 : ||(f+g)/2||_{\infty} = 1 \Rightarrow f=g$. But I don't have an idea for useful functions to check that.
Answer: Let $\chi_{(a,b)} $be a characteristic function of an open interval $(a,b) .$ Take $f=\chi_{\left(0,\frac{1}{2}\right)} , g =\chi_{\left(0,\frac{1}{4}\right)} .$ Then $$||f||=||g|| =\frac{1}{2} ||f+g|| =1$$ but $$f\neq g.$$


Service methods not working in android

Question: I just created a service as shown below :
package com.example.timepass;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;

public class alarm extends Service{

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
    Toast.makeText(this, "Entered in service", Toast.LENGTH_SHORT).show();

}

 public int onStartCommand(Intent intent, int flags, int startId) {

         Toast.makeText(this, "onStartCommand...", Toast.LENGTH_LONG).show();
         return 1;

        // Log.i("YourService", "Yes this works.");
     }
   @Override
   public void onDestroy() {
       super.onDestroy();
       Toast.makeText(this, "Service destroyed...", Toast.LENGTH_LONG).show();
   }

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    Toast.makeText(this, "Changed", Toast.LENGTH_SHORT).show();
    return null;
}

}

Now when I startservice from mainactivity by the following command:
Intent myIntent = new Intent("com.example.timepass.ALARM");
MainActivity.this.startService(myIntent);

By doing this there is no error, but no TOAST of Service class are dipslayed
My manifest is :
<service class=".alarm" android:name=".alarm" android:enabled="true">
  <intent-filter>
   <action android:value="com.example.timepass.ALARM"
               android:name=".alarm" />

       </intent-filter>
   </service>

Please guide me!!!
Comment: check your service is running or not from application manager
Comment: @prosper ofcourse it would not be running as it does not display any toast!!
Answer: Probably you don't have the service in your manifest, or it does not have an  that matches your action. Examining LogCat should turn up some warnings that may help.
More likely, you should start the service via:
startService(new Intent(this, alarm.class));

Comment: your manifest is ok, start your service by this way startService(new Intent(this, alarm.class));

Service methods not working in android


Principle Component Analysis on categorical predictors

Question: I tried running prcomp() on my training set, which contains some categorical/factor predictors (as well as a binary response), and was given an error saying my data needs to be numeric. Can PCA not be performed at all with categorical features? Or is there a way to work around the function...
Thank you!
Comment: Also see https://stats.stackexchange.com/questions/5774/can-principal-component-analysis-be-applied-to-datasets-containing-a-mix-of-cont
Answer: Take my answer as a comment more than a true answer (I am a new contributor so i cannot comment yet). If you can compute the varcov of the variables, then you can use PCA on that varcov matrix: of course you can compute the covariances between random variables even when they are binomial variables that numerically represent a categoriacal variable referred to two categories only (the same holds for multi-category variables). So be sure that you are representing your categorical variable via numbers (0-1 for a binomial categoriacal variable or 0-1-2,... for a categorical variable with more than 2 categories) and calculating the varcov correctly. Having said that, personally, I would prefer to keep them outside the PCA, especially if they are binomial and especially if you have just a few of them compared to the total number of features: for example, transform the set of non-categorical features via PCA to obtain a set of orthogonal features, then add the categorical variables to the set of simplified orthogonal features.
Code in python for the spectral decomposition of a simple varcov matrix obtained from two binomial variables
<code>import numpy as np
import scipy.linalg as la
a=[0,1,0,1,0,1]
b=[0,0,0,0,1,1]
eigval, eigvec=la.eig(np.cov(a,b))
</code>
Answer: The short answer is yes, PCA is intended for continuously scaled features. Categorical features which are nominally scaled (e.g., the set of teams in the NFL is a nominally scaled variable) and stored as such would cause this function to give an error.
One workaround would be to impose a ranking on a categorical feature that would convert it into an acceptable ordinal scale but that would be an imposition of a rule.
Another workaround would be to convert the categorical features into a set of dummy variables or numeric effects as described in the link below. There are those that contend that PCA is invariant to mixtures of numeric variables such as dummy, ordinal and higher scaled features but that has not been my experience. My experience is that you get results with imbalanced latent dimensions which, based on the loadings, are heavily skewed towards the dummy variables.
My opinion is that the best solution would be to use correspondence analysis (CA). CA is described as 'PCA for categorical features'. It is well reviewed in the second link below. It may require grouping the continuous variables with a large range of possible values into a smaller set of buckets, depending on the software used.
ADDITIONAL CODING SYSTEMS FOR CATEGORICAL VARIABLES IN REGRESSION
 ANALYSIS https://stats.idre.ucla.edu/sas/webbooks/reg/chapter5/regression-with-saschapter-5-additional-coding-systems-for-categorical-variables-in-regressionanalysis/
Correspondence Analysis in R: The Ultimate Guide for the Analysis, the Visualization and the Interpretation - R software and data mining http://www.sthda.com/english/wiki/print.php?id=228
Comment: Thank you very much! I am reading into correspondence analysis now, my ultimate objective is to predict my test set using principle components, do you think this will work?
Comment: Sure, just expect there to be an inevitable loss in predictive power since the resulting dimensions will recover a smaller percentage of the total variance in the inputs. Given that, why do CA or PCA at all? If you want to find a reduced set of predictors why not use a variable selection method such as the Lasso?  See https://www.r-bloggers.com/ridge-regression-and-the-lasso/
Comment: I have already selected my variables, I am trying to build a predictive model, then given the same predictors, estimate my response variable (not sure if this makes sense), if CA lacks predictive power, should I just not use this method altogether? I appreciate your help!
Comment: Why not try both CA and the predictors as separate models? Then see which one provides the better empirical fit. It makes more work for you but, per Gelman's concept of the multiverse, it might prove to be more insightful. *Increasing Transparency Through a Multiverse Analysis* http://www.stat.columbia.edu/~gelman/research/published/multiverse_published.pdf


How do I obtain joint distribution of uniform random variables conditioned on a sum constrain?

Question: Let us say, we have two random variables,
x1 --> U(10,20) i.e. x1 is uniformly distributed between 10 and 20, and
x2 --> U(20,40) i.e. x2 is uniformly distributed between 20 and 40.
Moreover, it has to be ensured that x1+x2 = 40 always.
How do I compute the joint distribution P(X1,X2|X1+X2=40)?
In other words, how do I find joint distribution based on a sum constraint?
Answer: The joint density function of continuous random variables $X$ and $Y$ conditioned on $X+Y=a$ does not exist. Conditioned on $X+Y=a$, the random point $(X.Y)$ is constrained to lie on the straight line through $(a,0)$ and $(0,a)$ and so doesn't have a joint density in the sense of $f_{X,Y}(x,y)$ telling you how dense the probability mass is in the vicinity of $(x,y)$: the units are probability mass per unit area and since $(X,Y)$ is constrained to lie on a line (which has zero area!), the only nonzero "value" we can ascribe to the joint density is $\infty$.  What we do have is a line density measured in probability mass per unit length.
Comment: I really want to thank you for answering my question, I really really appreciate it. So basically, what happens is if we are given n measurements each of which are uniformly distributed within certain intervals, and that the total sum of the n measurement is always constant, the joint density always loses a degree of freedom.

If n=3, then instead of evaluating probabilities on volume, it is evaluated on surface. Could you please give an example of how to actually compute it? I tried by writing out the joint pdf of two uniform densities but was unable to accomodate the sum constraint


How many numbers below $100$ can be expressed as a difference of two perfect squares in only one way?

Question:
How many numbers below $100$ can be expressed as a difference of two
  perfect squares in only one way?

Please explain your approach.
ADDED: I can determine whether a number could be represented as difference of two squares,say $N = a^2-b^2$ ,where $a,b,N \in \mathbb{N}$,which gives $N = (a+b)(a-b)$ hence,$(a+b)$ and $(a-b)$ must be both odd or both even,observing the prime factorization of $N$ we can determine whether it is possible to represent $N$ in that form or not,but I am not sure if I could use this for this problem.
Comment: [Might be useful...](http://www.fq.math.ca/Scanned/40-3/nyblom.pdf)
Comment: You're on the right track. Keep thinking. When would such a representation be unique?
Comment: @J. M.:Thanks,but I think that paper is talking about the number of representation $N$ as the difference of two natural numbers.
Answer: The answer depends on whether you count $0^2$ as a perfect square or not.  For the analysis below, $0^2$ is a perfect square.  And we interpret "number below $100$" as meaning positive integer below $100$.  Also, note that $5=3^2-2^2=(-3)^2-2^2$.  Representations will always be non-unique if we allow sign changes.  So we rule out using squares of negative integers.
The easy way to solve this problem is to look at  $1$ to $99$, one after the other. For each, check whether it satisfies the condition, and keep a running tally.  After a little while, we notice some patterns, and then the work is quick. As a partial compromise, we could look up a general result, and use that.  But that is not interesting, so we develop all the theory we need.
Let $n$ be a positive integer. We look for non-negative integer solutions of
$$x^2-y^2=n, \qquad\text{that is, of}\qquad (x-y)(x+y)=n.$$
We must then have
$$x-y=d\qquad x+y=\frac{n}{d}$$
where $d$ is a (positive) divisor of $n$.
Solving for $x$ and $y$, we obtain
$$x=\frac{d+\frac{n}{d}}{2}\qquad\text{and}\qquad y=\frac{-d+\frac{n}{d}}{2}.$$
From the above equations, $x$ and $y$ are integers precisely  when $d$ and $n/d$ are both even or both odd. And since $y$ must be non-negative, we need to have $d \le n/d$, that is, $d\le \sqrt{n}$. Any factor $d$ of $n$ satisfying those conditions gives us a solution, and different factors yield different solutions.
Thus the number of ways of expressing $n$ as a difference of $2$ squares is precisely the same as the number of divisors $d$ of $n$ such that $d\le \sqrt{n}$ and $d$ and $n/d$ have the same parity.
In particular, if $n$ is divisible by $2$ but not by $4$, there is no representation of $n$.
Look first at the case $n$ odd.  There is only one factorization of $n$ of the desired type iff $n$ is an odd prime or $n=1$.
Look next at the case $n$ even.
The number of representations of $n$ is the number of ways of splitting $n$ into two even factors $d$ and $n/d$, with $d \le n/d$.
This is the same as the number of ways of expressing $n'=n/4$ as a product of $d'$ and $n'/d'$, where $d' \le n'/d'$.
There is only one such factorization precisely if $n'$ is a prime or $n'=1$.
Now counting is easy, though somewhat tedious. For the odds, count $1$, plus the odd primes $\le 99$.
There are $24$ odd primes less than $100$, for a total of $25$.
For the evens, count $1$, plus all primes $\le 24$.  There are $9$ such primes, giving a total of $10$ even numbers.
So overall $35$ numbers qualify.
Comment: If we don't allow $0^2$ as a perfect square, some changes need to be made. The most obvious ones are that $1$ and $4$ should not be counted. But the situation is more complicated than that. For the odd case, if $p$ is a prime, then $p^2$ now only has one representation, since $p^2-0^2$ is not allowed, so it should be counted. Similarly, in the even case, now $4p^2$ only has one representation.
Comment: @MaX: Thanks. "How many numbers below $n$ can be expressed" is easy to get at without tedious counting, it is just everybody except numbers $\equiv \pmod{4}$. The uniqueness requirement in your question makes it unfortunately necessary to count the primes $<n$. This can be hard to do by hand even when $n$ is only moderately large.
Comment: I don't think I fully understand your counting..." For the odds, count $1$, plus ... plus all primes $≤24$. There are $10$ such primes."
Comment: That's because I can't count.  There are $9$ primes less than $25$. Thanks!
Comment: Andre,take a look at [this](http://www.artofproblemsolving.com/Wiki/index.php/1997_AIME_Problems/Problem_1)
Comment: Yes, when I find this (the url one) problem I thought about this one (related) hence thought of posting it here :-)
Answer: HINT:
The differences between perfect squares conform to a strict pattern.
$1^2 = 1$
$2^2 = 1^2 + 3$
$3^2 = 2^2 + 5 = 1^2 + 8$
$4^2 = 3^2 + 7 = 2^2 + 12 = 1^2 + 15$
$5^2 = 4^2 + 9 = 3^2 + 16 = 2^2 + 21 = 1^2 + 24$
One could write a program to test the answers if you wanted, as above a certain number $m$ (I'll let you find out what that is - though it isn't so bad) the possible differences of it's square with other squares are simply too big. It's okay, too, since this number is not very big.
Second HINT:
$x^2 - y^2 = (x+y)(x-y)$
Answer: Any number that can be written as the product of two even or two odd integers can be written as the difference of two squared integers. This includes all odd integers, N, because they can be written as 1 x N = N.
Numbers that cannot be written as the difference of two squared integers are all numbers that can be written as 2 x (any product of odd primes). Because they cannot be written as the product of two even or two odd integers.
For uniqueness, only odd numbers which can be written as the product of two odd numbers in only one way, can be written uniquely as the difference of two squared integers. That leaves only odd prime numbers, which can be written as 1 x P.
The only even numbers that can be written uniquely as the difference of two squared integers have the form 4P, because 2 x 2P is the only way of writing the even number as   the product of two even numbers.
Proof: Given any number T = a x b, where a and b are either both even or both odd and a < b. [a=b, would require that zero be considered a squared integer]
Define integers N and M as:  N = (a+b)/2 and M = N-a = b-N.   [Note a + b = 2N]
Then N^2 - M^2 = 1/4(a+b)^2 - (N-a) x (b-N) = a x b = T
If a and b are odd, then the answer is unique only if a or b is the number 1 and the other  is a prime number. Because if a=p and b=p' for example. Then T = a x b = 1x pp' = p x p'. This would give two different representations:  N = (1+ pp')/2 and N' = (p +p')/2.
For even numbers a = 2 and b = 2P, N and M are unique as N = (2+2P)/2 = P+1 and
M = N-2 = 2P - N = P-1
So for number less than 100:
Even numbers that are 4 times each odd prime less than 25 = 8 even numbers.
Odd numbers : 1x (all odd primes less than 100) = 24
Total = 8 even + 24 odd = 32 numbers less than 100 that can be represented uniquely as the  difference of two squared integers.

If we allowed 0^2 as a perfect square as was suggested by others, corresponding to a=b so T=a^2, then every number, T, that is a perfect square,must be considered, because if T= a^2, then a^2 - 0^2 = T. None of these would be unique however.
If T is odd, then, besides T=a x a, we also have T = 1 x a^2, giving N=(1+a^2)/2, and M=N-1=a^2 - N' = (a^2-1)/2 . None of these cases affect the count of odd numbers above because these cases weren't counted.
If T is even, T=a^2 where a =2c is even. Then T can be written in multiple ways making the rendition not unique:  T = 4 c^2 = 2c x 2c = 2 x 2C^2 So N = a or N =(2+2c^2)/2. This does not affect the count of even numbers above since these cases weren't counted.
Answer: 0^2 is a perfect square : Total valid cases - 35
0^2 is a not perfect square : Total valid cases - 38
A computer generated output is available at www.careerbless.com/aptitude/qa/numbers.php.
Answer: I came across a question in a Singapore Math Olympiad Grade 8 paper which asked " How many 2-digit positive integers can be expressed as the difference of two perfect square numbers? I am sharing my solution here.
First of all the positive integer, Say N > 9 and N<100
We will approach this problem with assuming the possible count of N when N is an odd number and then when N is an even number.
Lets assume first that N is an odd number so N = 2K+1, where K is any whole number starting from 0.
Now N = 2K+1=(K+1+K)1= {(K+1)+K)}{(K+1)-K}=(K+1)^2-K^2.  This means, All N which are odd numbers in the form of 2K+1 can be represented as difference of two perfect squares of K+1 and K.  From the range of N, we further get that there are {(99-11)/2+1}= 45 odd numbers which can be represented as difference of perfect squares where largest N is 99 and smallest is 11 and largest K is 49 and smallest K is 5. So if we get odd number N=2K+1, we can quickly find out K+1 and K as K = (N-1)/2.
So we have got 45 two digits odd numbers which can represent the difference of two perfect squares.
Now lets consider N as an even number and lets assume N = a^2-b^2 where a and b are whole numbers.
Now lets assume N = a^2-b^2 = (a+b)*(a-b) where a>b and try to find out what conditions will fullfill this.  Now for N to be an even number either both a and b has to be even (Case 1) or both of them have to be odd (Case 2).  If one of them is even and one of them is odd then both a+b and a-b will be odd and the product of two odd numbers is an odd number which is not the original assumption since N is an even number.
Case 1:  Lets say both a and b are odd, therefore we can say that a+b is even and also a-b is even.  Now lets assume a=2p+1 and b=2q+1 where p>q.
Therefore, N= (a+b)(a-b) = (2p+1+2q+1)(2p+1-2q-1)= (2p+2q+2)(2p-2q)
=4(p+q+1)(p-q).  Therefore we can safely say that N has to be a multiple of 4 when a and b are odd numbers.  Also, please note that (p+q+1)(p-q) will always be an even number for all all p's and q's and One of them, either (p+q+1) or (p-q) will be even and the other one odd.
In this scenario if even number N is given, we can quickly divide it by 4 and see if it {(p+q+1)(p-q)} is an even number and then see two factor combinations. If the factors have even and odd combination, then you can find p and q from there and further find a =  2p+1 and b = 2q+1. eg. p=4 and q= 3 which gives a= 9 and b = 7 so N = a^2-b^2 = 4(p+q+1)*(p-q) = 81-49 = 32.Please note that this scenario also happens when both a and b are even in some cases so N is not for unique cases of differences of perfect square.
Case 2: Lets say both a and b are even, therefore we can say that a+b is even and also a-b is even.  Now lets assume a=2p and b=2q as they are even numbers where p>q and p can be even or odd.
Therefore, N= (a+b)(a-b) = (2p+2q)(2p-2q)= 4*(p^2-q^2).  Therefore we can safely say that N has to be a multiple of 4 when a and b are even numbers also.
Here if we know N, we can divide it by 4 and see if p^2-q^2 is an even or odd number.  If its an odd number say O which will happen only when one of them is even and the other one odd, then we can find using p=2K+1 and q = K, where K=(O-1)/2.  Then we can find a and b which are 2p and 2q respectively.
However, in this case, we might get p^2-q^2 as an even number E also and in that case p and q needs to be figured out as both will be either odd or both will be even.  We can use the factor (p+q)*(p-q) to check what values of p and q satisfy for E and where both p & q are either even or odd.
From these two cases of N being and N number we also derived that only multiples of 4 will satisfy the condition. So the highest two digit multiple is 96 and lowest is 12 so there are {(96-12)/4+1)= 22 cases when N is even.
So over all we have 45 odd and 22 even values of N where N is a two digit positive integer and represents the difference of two perfect squares.


Foreign Key não respeita integridade referencial

Question: Estou tentando unir tabelas e adicionar uma chave estrangeira, para que por exemplo, uma tabela de compras tenha referência da id da tabela de compradores.
Fiz da seguinte forma:
alter table compras add foreign key (compradores_id) references compradores(id);
insert into compras (valor, recebido, data, compradores_id) values (1500, 1, '2016-06-02', 15);

*As id's da tabela compradores só vão até 3
*Ambas as colunas (compradores.id e compras.compradores_id) foram configuradas como int not null
Ele aceita o comando de insert numa boa e grava, como posso corrigir isso ?
Comment: Você poderia postar os campos e o tipo de cada campo destas duas tabelas?
Comment: O engine da sua tabela é innodb ou mysam?
Comment: É preciso ter constraint, tem que ser do tipo igual, integer (11), integer (11), unsignet, not null e por aí vai...
Comment: Na criação da tabela no final tem essa informação.
Comment: @rray, ambas são MyISAM
Comment: Tenta colocar InnoDB
Comment: @rray, como verifico isso ?
Comment: @Gumball, eu setei ambas do mesmo jeito :/ por isso não entendo o pq de estar bugando
Answer: A integridade referencial no MySQL funciona somente quando as tabelas usam o engine innoDB. O primeiro passo é mudar o tipo das tabelas e depois aplicar a foreign key, uma vez que os valores devem obedecer as restrição.
ALTER TABLE nome_da_tabela ENGINE=INNODB

MySQL - innoDB documentação
Comment: muito obrigado, assim que alterei pra INNODB rodou liso :D
Answer: Segundo o W3 Schools o comando correto seria o seguinte:
ALTER TABLE compras
ADD CONSTRAINT fk_compras_compradores_20161215
FOREIGN KEY (compradores_id)
REFERENCES compradores(id)

Também é importante verificar se compradores_id é do mesmo tipo que o id do comprador.
Comment: Eu posso estar enganado, mas acho que W3Scholls não tem nada a ver com W3C.
Comment: Se puder postar a estrutura das tabelas, vai ajudar a elucidar um pouco mais
Comment: Opa, perdão rsrsrsr. Fazendo mil coisas aqui rsrsrsr
Comment: Continua inserindo, mesmo com a adição de `constraint`


Simulating an ODE model with non-constant parameter

Question: I have a model, I can formulate the model using ordinary differential equation with parameter $P$. I want to simulate the model, but instead of using a fixed constant $P$ for the parameter, I want to force that the parameter $P$ is normally distributed. Can I do this ?
NB: I can also run a Gillespie Algorithm for my mode, but can I use a non-constant rate for my parameter ?
Thanks...
Answer: There is many way to introduce uncertainty of the parameters in a ordinary differential equation (ode) corresponding to different physical interpretation.
First example : Your parameter $P$ is theoricaly fix but the measure of this parameter came from a statistical study that shows that the estimator of $P$ :  $\hat P \tilde\ \mathcal N$.
In this case you can sample $P$ in its law and do as much ode resolution as the number of sample.
In R code  :
<code># Your ode
x0 = ..
nu = ..
a = ..

# Your random parameter
n = 100 # number of sample
P  = rnorm(n,p_theo=0,p_sd=1)

out = as.list(1:n)
for( i in 1:n)
{
 params = list(P=P[i],..)
 out[[i]] <- out <- ssa(x0,a,nu,params,tf=100,simName="My model")
}
</code>
Then you will have $n$ different trajectories in out that represent all the possible trajectories of your model.
Second example : Your parameter $P$ is theoricaly random : it can depend on complex biological aspect of an individual in an epidemiological study, it can depend on the humitity level (respiratory diseases)...
Here you can randomly chose your parameter $P$ at each step of your ode resolution.
With gillespieSSA you can call the iteration time of the algorithm with : <code>.t</code>
<code># Your ode
x0 = ..
nu = ..
a = c('P(.t)*...',...)
params = ...

# Your random parameter
P <- function(t){return(rnorm(10,0,1))}
out <- out <- ssa(x0,a,nu,params,tf=100,simName="My model")
</code>
Note that in the first example you can use an other ode resolution algorithm like a deterministic algorithm.
In the second example there is many ways to model those type of uncertainty, this is not as simple as in the first example. In particular, depending on your algorithm of resolution, you can incerase the variability of your solution with the number of step that your algorithm have done.
Matt Keeling wrotted a good book on those subjects : Modeling Infectious Diseases in Human and Animals. If you want to model those type of uncertainty i advise you to read this book or some article about those issues because there is a lot of issues hidden behind this simple question.
Comment: +1 Welcome to our site, Alex!  Thank you for formulating a careful answer to an old question.


How to control an analog or digital mixer (every channel seperatly) from laptop using vst plugins live

Question: First of all I would like to apologize for my English. I am from Greece but I will try to be clear.
So, I have a band and I want to make gigs using VST plugins live (on real time), and I am wondering (for example), if I can connect my guitar to channel 1 on my analog or digital mixer and use my VST plugins from my laptops DAW (for example cubase) to create my sound, and at the same time to connect the bass instrument to channel 2 and control it from my pc using VST and connect the microphones on channel 3 (to do the same thing) and my e drums (to do the same thing).
I know that there are many digital mixers that can do almost the same thing that I am describing as it carries some software with built in VSTs but I really don't like them and I think (I am not sure) also that I cant install/add to that kind of software my VST plugins that I am intending to use. If there was a way to add VST on digital mixers it would be the solve of my problem.
I personally thought that if an analogue mixer has a built in sound card then maybe the cubase could see that interface and let me control any channel and at the same time let me use my plugins live.
If anyone have any thoughts I would be glad to hear.
Comment: When you say "connect the bass instrument to channel 2 and control it from my pc using VST", what do you mean by "control"?  do you mean applying effects from a VST effect plugin?
Comment: I don't know about every Xenyx product, but if you look at the manual of the [XENYX X1204USB](https://www.bhphotovideo.com/lit_files/61849.pdf), it says that only stereo audio can be sent to from the mixer - in other words, there's no advantage over your two channel sound card. On the other hand, if you look at https://www.soundcraft.com/en/product_families/soundcraft-signature-mtk-series, you will see that they can send 12 or 22 channels to the computer and back, which they say "allows plug-ins to be inserted on any input channel". That is somewhat unusual though....
Comment: ...and I'm not sure if you can control the mixer from the computer as such - for that, you're likely to need a digital mixer. But of course if you're OK with the latency of going into and out of the computer via USB, again that raises the question - why use a mixer at all? Why not just use an audio interface with enough inputs and mix in the computer?
Comment: As you're involving a computer for the VST plugins, is it possible that you don't need a mixer at all, but just an audio interface that allows you to route your instruments and microphones into the computer, and get a mix out?
Comment: There are some digital mixing platforms that allow you to purchase and use (non-VST) third-party plugins, but they are generally more expensive. Avid Venue and the UAD platform are examples. There are also software packages that let you mix in the software but they can be high latency or demand very powerful computers (MainStage). When I try to distill this question down to its essence, it seems like you're looking for a recommendation for equipment, which is off topic here. If you're asking how to do this with any kind of equipment, well you can't. You have to get certain gear to do this.
Comment: Yes, I meant to apply vst plugins
Comment: Before some years I sold my mixers , so I am asking because I didn't currently own a mixer and so I can't test some ideas that maybe will solve my problem. Maybe Monica is right that I just need an external pro sound card but I think will have a problem with latency , so if anyone has any idea about how to install /add vst plugins in to digital mixers software, or how to apply vst plugins from pc to mixer for gigs purposes I am still listening.
Comment: Also  for example I noticed that you can apply waves multi track to digital mixer behringer xr 18, so I think  there would be a way to do what I am thinking
Comment: Certainly going into a computer with a sound card will involve some latency, but that would also be true if you were applying vst plugins from pc to channels in your mixer. If you are basically playing in a conventional band situation, I think it's much more common to use standalone pedal and rack effects (as well as perhaps some effects on the mixer) rather than to use VSTs. Would that be an acceptable way to go?
Comment: Yes I know that, but as I am looking through the internet I noticed that there are many analog mixers like behringer xenyx series that have a build in sound card, that means it works like an audio interface so I am still wondering if I can apply vst without any problem. I currently own a sound card and I am able to use vst plugins without latency but my sound card has only 2 channels and I need more and that the reason I am asking if I can do it using an analog mixer (that has a built in audio interface)
Comment: Monica you are right, I read alot of manuals and different theories that I could try but your suggestion is the easiest way to do what I was looking for, in deed soundcraft mtk offers the solution to me, although this week I will rent some mixers to try to achieve to apply vst plugins from my daw without any  problem. Thanks for your advice, (if I will fail, I would follow your advice that seems to be the best and easiest way)
Answer: You have a few different options.

Mix completely "in the box", i.e. all mixing happens in software in the DAW. Your audio interface has enough input channels to bring all audio things into the DAW for mixing, processing with plugin effects and combining with software instruments. Output the main mix and maybe monitor mixes. DAW software such as Ableton Live, Cubase and Reaper should be able to handle so many input and output channels that from your perspective there is no limit, but the computer system including the audio interface, has to be good enough to handle low latencies reliably. You will have to test the entire system thoroughly to know if it's reliable for live use.

Hybrid solution 1: use a normal mixer (digital or analog, it doesn't matter), but run the guitar and bass through an audio interface and DAW (with plugins) before outputting to the mixer's input channels. Your computer/DAW only works as an amp+effects simulator, and for the whole mix you'll use the real mixer. You could just as well use a hardware amp simulator instead of a computer.

Hybrid solution 2: use a digitally controllable hardware mixer that has a few input/output channels connected to the computer's DAW, so you can process some channels with the plugins you want. With MIDI or other kinds of control protocols, you could remote-control the mixer. There are even rack-mount stage box mixers where the only method for controlling and changing mix balance, EQ etc. is via a remote-control application. But do you really want to control the mix with the DAW software in realtime? Why? Do you have pre-programmed songs with effect and balance automation changes during the songs?

Use the DAW computer and plugins as insert effects in a mixer's input channel. Maybe a weird and far-fetched scenario, and for electric guitar you want a proper Hi-Z input with 1 Mega Ohm input impedance or more.
Answer: On SE we don't want to give recommendations for specific equipment, but there are some general considerations:

How many channels there are in the audio interface. If a mixer has 10 channels, but the integrated audio interface has only 2 input channels (quite common), then at best you can use only two different effects simultaneously.

Such configuration will unavoidably add some latency. The audio interface, as well as your PC need to be good enough to keep the latency sufficiently low for you.  This may also affect how many effects you can use simultaneously.

Do you want the effects to process the whole signal from a channel, or do you want to add it them parallel?

In the first case (e.g. how typically a guitar amp modeler is used) you need to make sure the mixer allows you to mute given channel while still sending it to your PC, so that you don't hear the clean signal in the mix
The latter case it's easier, but the latency introduced by the whole system might be an issue. It may cause phase cancellation, it will change the sound of modulation effects, etc.

You will need to study user manuals of the mixers and perhaps search for reviews of the specific equipment to answer these questions for you.
Answer: I think I know what he's asking.
Assigning a midi or usb midi controller so that to use it's nobs, sliders, and buttons to control parameters on a DAW and VST plugin.
The problem I had with this is that you can only assigning links to your midi remote in the DAW(if your DAW supports MIDI remote control) and not plugins, and vice a versa, you can only link a controller to a VST(that is supported) and not the host application's configurable parameters.
Sounds to me like you want to control knobs, sliders, and buttons that are in your VST with a generic USB controller.  This will only work if the VST or DAW supports it.  Assuming your setup consists of guitar gear I heard of some VSTs that support remote triggering from a foot pedal, but this linkage only works with the VST software specific to the pedal and circumvents the DAW entirely.  It would be nice to control features in the host application with the foot pedal.
Looking at your existing configuration I'm pretty sure you can configure midi remote control of your channel volumes in real time application, but, any other knobs on the VST that you want to tweak live will be untranslatable even though you can tweak it in real-time with the mouse pointer.
Triggering effects with a mouse or USB remote can be recorded too, but this then neglects any real-time play/performance that I think you're after.
Let me know if this is what you were asking.


How to set nginx conf (403 forbidden page) to pass OWASP security test

Question: This is my nginx conf:
upstream django {

    server 127.0.0.1:8001;
}

server {
    listen     80;
    server_name 127.0.0.1;
    charset     utf-8;

    #security
    add_header X-Content-Type-Options "nosniff";
    add_header X-Frame-Options "DENY";
    add_header X-XSS-Protection "1; mode=block";

    location /static {

        alias /usr/share/nginx/mysite/staticfiles;

    }

    location / {
        uwsgi_pass  django;
        include     /etc/nginx/uwsgi_params;
    }
}

And my settings.py :
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SESSION_COOKIE_SECURE = True
SECURE_FRAME_DENY = True

But It still have security problem with static files, What else should I set??

UPDATE
I found as @LinnTroll said ,It seems the the nginx 403 page didn't have security protect. How should I set it??
Answer: It is not django problem. Nginx returns error code (403) for direct access to path like /static/, and directive add_header doesn't work for responses with error codes. If you use nginx version >= 1.7.5, add third parameter 'always' to add_header directive:
add_header X-Content-Type-Options "nosniff" always;

If you have nginx version lower then 1.7.5, i know the following simple ways to solve your problem:

update nginx to version >= 1.7.5
enable directive autoindex on; for you /static location. (warning: all you static files will be available for anyone, including search engines!)
add following location before you /static location:

location ~* ^/static.*/$ {
    add_header X-Content-Type-Options "nosniff";
    # ... you other headers ...
    add_header 'Content-Type' 'text/html; charset=UTF-8';
    return 200;
}
Comment: My version is 1.6.3 .I still not find a solution yet
Comment: Thank you so much. Share with you another method I found : add ````error_page 403 /403;````, ````/403```` is my web page


Can I use restricted cubic splines to model non-linear relationships if the underlying variable is not normally distributed?

Question: I am estimating the association between an exposure ("time in therapeutic range", possible values from 0% to 100%)) and time to a binary outcome ("chronic kidney disease"). I would like to assess potential non-linear relationships between the exposure and outcome.
The exposure is not normally distributed with many participants having a value of 0% or 100%. Is it still valid to model non-linear associations for this type of variable distribution using restricted cubic splines? I feel like the 0% and 100% participants are exerting outsized influence on the results. Additionally, the 0% and 100% categories don't provide the most clinically relevant information because it is obvious that 0% is bad and 100% is good.
Here are the splines with and without the 0%/100% patients. 4 knots minimized the AIC if 0%/100% participants were included. The relationship between the exposure (time in therapeutic range) and outcome was not non-linear after excluding the 0%/100% participants.
Your help is much appreciated.
Answer: In general, the question is whether the spline modeling accurately represents the association of the continuous but range-limited predictor with outcome. Unless there is reason to believe that there is some discontinuity in that relationship associated with the 0% or 100% groups then it doesn't matter.
Note, however, that with restricted cubic splines the association is forced to be linear beyond the outer knots. I suppose that you could devise a model that handles the 0% and 100% groups separately while modeling the intermediate groups continuously. You can already see the difference that would make. For example, with a predictor value of 10%, such separate modeling would predict a value just below 4 per 1000 person-years; continuous modeling including the endpoints would predict a value just above 4. Does that make a substantive difference? Alternatively, you could force the outer knots to be closer to the edges by manually choosing their positions instead of accepting the defaults.
In this specific context, however, I'm more worried about the nature of the predictor: "time in therapeutic range." For a time-to-event study, that sounds like it has a risk of introducing survivorship bias. You don't want your "predictor" of good outcome to be essentially a measure of how long time someone has gone without an event. Think carefully about that possibility, based on your knowledge of the subject matter.


Experiencing problems filtering view programmatically

Question: I'm using a views block in my website, the content of this view is filtered programmatically. I now get messages from users who see the wrong information. The filter is based on the currently logged in user. Since I need this information in the regular filter and not in the contextual filter I created a simple module to change the filter value.
My filter is like this:
<code>(
Content type = contenttype_a
AND
uid(nodes author) = */this value is programmatically added*/
)

OR

(
Content type = contenttype_b
AND
user_target_id(reference) =  */this value is programmatically added*/
)
</code>
Than I use this in my module:
<code> */
function entity_access_views_pre_view(ViewExecutable $view, $display_id, array &$args){
  $currentUser = \Drupal::currentUser();
  $cuid = $currentUser->id();

    /* @ Filter View: Media  */
    if ($view->id() == 'my_view_id') {
      if ($display_id == 'block_1' || $display_id == 'page_1' || $display_id == 'page_2') {
        $filters = $view->display_handler->getOption('filters');
        $filters['uid']['value']['value'] = $cuid;
        $filters['user_target_id']['value']['value'] = $cuid;
        $view->display_handler->overrideOption('filters', $filters);
      }
    }
}
</code>
Since I can't seem to find the problem I'm having doubts about if above is working as I want it to. So I wanted to check if you see anything strange or false. Can this filter value be cached in some way? Or maybe there is a better way to do this.
I can't use the contextual filter, which I would prefer, because the view is showing two content types where on each content type the filter should be different.
Thanks in advance.
Answer: First you can try to add a cache context to the render element of the View before it is rendered:
<code>/**
 * Implements hook_views_pre_render().
 *
 */
function mymodule_views_pre_render(ViewExecutable $view) {
  if ($view->id() == 'my_view_id') {
    if ($view->current_display == 'block_1') {
      $view->element['#cache']['contexts'][] = 'user';
      // or add a cache max-age 0 for a high user count
      $view->element['#cache']['max-age'] = 0;
    }
  }
}
</code>
This doesn't help however if Views is caching the query internally. Then you can try to disable caching by configuring the None or Time-based  cache plugin within the View. You can't configure a cache context here, though, only a cache max-age of 0. This is not necessarily a bad idea if you have a high user count and don't want to cache the same amount of variants. Drupal has a great caching system for delivering non-cacheable blocks to authenticated users (Dynamic Page Cache + BigPipe).
Comment: Thanks, disabling the cache in the view itself is my first try to solve this. I'm now waiting to see if this solves the problem.


Pass by value or Pass by reference in Java?

Question: I read many articles and all says Java is pass by value. But i still don't construe the difference between pass by value and reference. I wrote a sample program and it executes like this..
public class PassByValue {

   private int a;
   private int b;

   public PassByValue(int a, int b) {
    this.a = a;
    this.b = b;
   }

   public static int mul(int a, int b) {

       int z = a * b;
       System.out.println("The Value of Z inside mul: " + z);
       return z;

   }

   public static void main(String args[]) {

    int z = 100;

        int x = 40;
        int y = 20;

    mul(x,y);

    PassByValue pass = new PassByValue(x,y);
    mul(pass.a,pass.b);

        System.out.println("The Value of Z" + z);

   }

}

Execution
800
800 and
100

Can anyone explain me these questions...

What is Pass By Value means...
Answer: Its just passing the numbers or value stored in the variable to a function. Am i right or wrong.

How do you say Java is Pass By Value?
Why is Java is Pass By Value and not by reference?
Does the above program Tries shows an example of Pass by value and Reference... but still does things via Pass by Value only... I wrote that program.
Comment: How many times do we need that question? Look at any of the "Related" links, there's a good chance reading two of those that were actually answered and not closed as duplicates clears things up.
Comment: http://stackoverflow.com/a/7034719/489364
Comment: possible duplicate of [Is Java "pass-by-reference" or "pass-by-value"?](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value)
Answer: The confusion is probably due to the fact that a variable can't contain an object in the first place. A variable can only contain a reference to an object. (In other words, objects aren't passed at all, not by reference, not by value.)
Once you realize this, it is quite clear that nothing is pass-by-reference in Java. A variable refering to an object stores a reference, and this reference is passed by value.

1. What is Pass By Value means...
Answer: Its just passing the numbers or value stored in the variable to a function. Am i right or wrong.

That's right. The value contained in the variable is passed, and not the variable itself.

1. How do you say Java is Pass By Value?

Java is pass by value because primitives are passed by value, and references are passed by value. (Objects are never passed.)
You can't implement a swap method in Java for instance. I.e., you can't do
String str1 = "hello";
String str2 = "world";
swap(str1, str2);
// str1 can't refer to anything but "hello"
// str2 can't refer to anything but "world"

2. Why is Java is Pass By Value and not by reference?

As explained above, even references are passed by value.
Answer: You are right in your answer, but you are lacking detail.  If you do
Dog d = new Dog()
d is a reference to an instance of Dog, i.e.  What pass by value means is that you when pass d into a method
walkDog(d);
the a copy of the reference (i.e. the value of the reference, not the reference itself) to the Dog is passed into the method.  So you have 2 references to the one instance of the Dog, the one in the calling scope, and the one in the called scope.  Lets say in the walkDog method there is a line
d = new Dog();
the d reference in the method only points to the new Dog.  The original reference where the method was first called still points to the original Dog.  If Java had pass by reference, the same reference, not a copy of the reference would be used in the method, and so changing the value of the reference would affect the reference in both the calling and the called scope.
EDIT -- based on your comment, I want to make on thing clear.  Since the reference in the original scope and the method scope both point to the same object, you can still change things on that object in both scopes.  So if you do
d.drinkWater();
in the walkDog method, and drinkWater changes some variable on the dog object, then since both references point to the same object, which was changed.
It's only  a distinction between what the references actually are in each scope.  But it does come up a lot.
Comment: @theJava, no there are 2 references that point to the same dog.  Changing one of the references doesn't change the other, but using either reference to change the object changes the same object.
Comment: hvgotcodes: Thanks... perfect explanation... correct me if i am wrong, i am not sending the orginal variable or reference to my function... instead a copy... so the value does change only in that scope and not every where....
Comment: so the copy reference and the original reference points to the same address location.... but to different instance of DOG.
Comment: For the C people: Its functionally equivalent to passing a pointer in C and then making a copy of that pointer immediately upon entering the function to use within the function.  The data the pointer aims at is identical unless you change the value of the pointer within the function.
Comment: @hvgotcodes why then do Strings not change when they're pass into a method? They're objects, not primitive data types.
Answer: You can think of pass-by-value as passing only the value contained in the variable and not the variable itself. So then the value is copied into another temporary variable. In contrast, you can think of pass-by-reference as passing the actual variable and no temporary copies are made, so that any changes in the variable is 'saved'. Although there is more to it, it might be easier way to thinking about it
Answer: I think instead creeping around if Java supports pass by reference or values, one should be clear about the way of using the instances of the classes in Java in his implementation. It all happens to be the type of instances - mutable/immutable which is gonna decide the way we pass things to the functions! That's up to you to explore this difference!
Let me clarify my argument of why there is no need of chasing back at passing what?! Consider this...
First Code:
    void foobar(int *a){
        printf("%d", *a);
    }

    int main(){
        int a = 5;
        foobar(&a);
        return 0;
    }

Here in this C code, what are you passing... the address of the variable 'a'. This happens to be the pass by reference! :)
Let us consider another one...
Second Code:
    void foobar(int* a){
        printf("%d", *a);
    }

    int main(){
        int a = 5;
        int *p = &a;
        foobar(p);
        return 0;
    }

Here in this C code, what am I passing....? The value of the variable 'p', doesn't matter whether it is pointer or something :P
So what do you call this as pass by value/pass by reference? I leave this to you! But all we need to look at is how we gonna implement... :)
So in Java... with what we pass we can say - It supports "Pass by value" or "Pass by reference of some instance" and not "Pass by reference"
***Only thing which I can clearly conclude is with the primitive data types in Java. Since there is no pointers with which one can edit the content of a byte without the actual variable, we can't have pass by reference for them(I mean the primitive data types) in Java.


External URL to internal images

Question: Suppose I have a link field for internal images. $node->file_image->uri will for instance return:
internal:/sites/default/files/image/image.jpeg

I need to convert this into an absolute URL for metadata. I can do this manually, of course, but let's see what the usual functions do:
file_create_url() = "https://example.com/internal%3A/sites/default/files/image/image.jpeg"
file_build_uri() = "public://internal:/sites/default/files/image/image.jpeg"
file_create_url(file_build_uri()) = "https://example.com/sites/default/files/internal%3A/sites/default/files/image/image.jpeg"

No cigar, not even close. The new functions?
Url::fromUri()->toString() = "internal:/sites/default/files/image/image.jpeg"
Url::fromUri()->toUriString() = "base:sites/default/files/image/image.jpeg"

So, how to do it without doing it manually, of course? Removing internal: and prepending $base_url is very simple but still a hack.
Comment: You sure your first bit is right? normally an image stored in /sites/default/files/image/image.jpeg would have a uri of internal:/image/image.jpeg (So without the sites/default/files bit as well)
Comment: Yes, I'm sure. The wording might not be perfect. It isn't an image widget but a link field that accepts an URL and is set to only accept internal references. That's what's inside, yes, and I can handle it everywhere else in twigs and similar with relative ease.
Answer: Found it finally:
Url::fromUri($node->field_image->uri)->setAbsolute(TRUE)->toString()

External URL to internal images


How to use JQuery UI slide effect to seamlessly slide out one div and slide in another div?

Question: I am using
<code>$( "#viewPort" ).effect( "slide", hideoptions, 1000, callback )
</code>
to slide out the "viewPort" div, and in the callback() function I am sliding in the new div into the display by calling
<code>$( "#viewPort2" ).effect( "slide", showoptions, 1000 )

var hideoptions = {  "direction" : "left",  "mode" : "hide";

var showoptions = {"direction" : "right","mode" : "show"};
</code>
The problem is that it is not seamless transition: first the content slides out leaving behind a blank area then the new content slides in.
Is there a way to avoid the blank display?
Comment: Change 1000 to something smaller, like 10.
Answer: It's because you're calling the effect on #viewPort2 in the callback to the effect of #viewPort. That means it will occur only once the effect on #viewPort has fully finished. Try calling the effect on #viewPort2 right after the one on #viewPort, for example:
<code>$( "#viewPort" ).effect( "slide", hideoptions, 1000); //notice, no callback
$( "#viewPort2" ).effect( "slide", showoptions, 1000);
</code>


Value of $\sum_{n=2}^\infty (-1)^n ((\sum_{k=1}^\infty 1/{k^n})-1)$

Question: To find the value of:
$\displaystyle\sum_{n=2}^\infty (-1)^n ((\sum_{k=1}^\infty 1/{k^n})-1)$
The answer says: $1/2$
My attempt:
$=(\displaystyle\sum_{k=1}^\infty 1/{k^2})-1-(\sum_{k=1}^\infty 1/{k^3})+1+(\sum_{k=1}^\infty 1/{k^4})-1-\cdots$
$=(1+1/2^2+1/3^2+1/4^2+\cdots)-(1+1/2^3+1/3^3+1/4^3+\cdots)+(1+1/2^4+1/3^4+1/4^4+\cdots)-\cdots$
$=(1/2^2-1/2^3+1/2^4-\cdots)+(1/3^2-1/3^3+1/3^4-\cdots)+(1/4^2-1/4^3+1/4^4-...)+\cdots$
$=S_1+S_2+S_3+\cdots$
With:
$S_2=(1/2^2-1/2^3+1/2^4-\cdots)$
$S_3=(1/3^2-1/3^3+1/3^4-\cdots)$
$S_4=(1/4^2-1/4^3+1/4^4-\cdots)$
...
It looks like geometry series with alternating signs.
If I apply the geometric series value: $S=\frac{1}{1-z}$
Gives:
$S_2=2-1-1/2=1/2$
$S_3=3/2-1-1/3=1/2-1/3$
$S_4=4/3-1-1/4=1/3-1/4$
...
Original equation:
$=1/2+1/2-1/3+1/3-1/4+1/4-1/5+\cdots=1$
This is different than the answer (1/2) given.
Could any one help? Thanks,
Comment: Also I think you've calculated $S_2$ wrong.  The sum $\sum_{n=2}^\infty(-1/2)^n = \frac{1}{1-(-1/2))} - 1 + 1/2 = 1/6$ if I'm not mistaken.
Comment: Be careful, you can't rearrange a series if it doesn't converge absolutely.  Also, this seems to imply $\zeta(n)\to1$ as $n\to\infty$.  Is that really true?
Comment: Gregory, I think if it is a series when $n \to \infty$, then it can be freely rearranged. Am I right? As for the $ζ(n)$ it converges if $n>1$, doesn't necessarily tends to 1.
Comment: You can't rearrange a series $\sum a_n$ unless you know that $\sum|a_n|$ also converges.  And if $\zeta(n)$ does not converge to one as $n\to\infty$ than the series can't converge because $\sum a_n$ converges $\Rightarrow$ $a_n\to0$.
Comment: Thanks! Yes, I made a calculation error on all S. Corrected and seems that after the correction, it matches the answer. I will add it as answer and see if anyone find it correct and useful.
Comment: Cool, I went ahead and upvoted your answer and posted my comment as an answer since it seems to be what got you over the hump.  Please check it off so this question can be removed from the queue.
Answer: So I made calculation error when using the equation on geometric series.
$S_2=2/3-1+1/2=1/2-1/3$ (with z=-1/2)
$S_3=3/4-1+1/3=1/3-1/4$ (with z=-1/3)
$S_4=4/5-1+1/4=1/4-1/5$ (with z=-1/4)
Sum them up gives the value of original equation:
$=1/2-1/3+1/3-1/4+1/4-1/5+...=1/2$
Answer: You've calculated $S_2$ wrong. The sum $\sum_{n=2}^\infty(−1/2)^n=\frac1{1−(−1/2))}−1+1/2=1/6$


How to disable keybinding in Tmux

Question: Using Tmux and Vim is a pain sometimes. One of the collisions for me is Control-S. I use it in Vim for opening buffers in split, but when using Tmux, well...
Tmux does something stupid with it, I can't figure out whats the purpose. But basically, when C-s is pressed in Tmux, screen freezes. And it unfreezes with C-q. I've no idea whats that good for, if anything.
unbind C-s
unbind C-q

I tried to unbind C-s in tmux.conf, but it didn't work. How can I unbind it?
Also I freed the binding from Terminal, in .bashrc
stty -ixon -ixoff

Comment: To make sure that tmux registered the stated bindings you should check the output of `tmux list-keys` within your tmux session.
Answer: First of all, I would say that the Ctrl-S (suspend the output) "feature" doesn't belong to tmux. The Ctrl+S and Ctrl+Q is actually the XON/XOFF protocol. It lives with Unix/linux for long time.
You can disable it by:
stty -ixon

or
stty stop undef

you could check by stty -a before and after the change.  easier is, try the commands above, and press Ctrl-S to see if it worked.
good luck.
Comment: I only have this problem when using Tmux. I already disabled suspend output thing in .bashrc. Somehow tmux enables it again?
Comment: Actually, adding `stty stop undef` on top of -ixon fixed it.

How to disable keybinding in Tmux


Upgrade to Drupal 10.1.6, Theme Doesn't Load Outside Maintenance Mode

Question: I'm working to upgrade a site from 9.5.11 to 10.1.6. I followed the instructions provided here:
https://www.drupal.org/docs/upgrading-drupal/upgrading-from-drupal-8-or-later/upgrading-a-composer-based-site
The upgrade went fine using composer, but when I visit the site after the upgrade I noticed that the site's theme isn't being loaded. The site is displayed as a long series of menus with content at the bottom of my browser window. I flushed all caches, still no luck. On a whim, I put the site back into maintenance mode, and suddenly everything looks fine again. The problem reappears if I bring the site out of maintenance mode.
I have full access to all menus while viewing the theme-less site, and I've tried switching themes, including trying to use the default Olivero theme, to see if that made a difference. It doesn't. Did I miss something with the upgrade? Can anyone help identify the problem?
Comment: What happens when you disable JavaScript and CSS aggregation?
Comment: Hmm, it works after disabling both JavaScript and CSS aggregation. Should those options not be used?
Comment: Yes they should be used. Back when Drupal 10.1 released it shipped with some changes to the front-end asset system—to aggregation specifically. This was a problem for some sites. What does the web browser console log? Look through the recent asset system issues: https://www.drupal.org/project/issues/drupal?text=&status=All&priorities=All&categories=All&version=All&component=asset+library+system
Comment: Also read the release notes for recent versions.
Comment: Thanks for all the responses! Sure enough, the change to my nginx configuration was needed. the issue remained after that change though, and I saw multiple "too many redirects" errors in the browser console log. The fix described in https://www.drupal.org/project/drupal/issues/3368769 (comment #11) finally did the trick.
Answer: Drupal 10.1.x introduced CSS and JavaScript aggregation performance improvements in that there is change to <code>.htaccess</code> file as well.
Sites using nginx/php-fpm may need to update their nginx.conf file to pass through the css/js path to Drupal.
Before
<code># Passes style generation to PHP.
location ~ ^/sites/.*/files/styles/ {
  try_files $uri @rewrite;
}
</code>
After
<code># Passes image style and asset generation to PHP.
location ~ ^/sites/.*/files/(css|js|styles)/ {
  try_files $uri @rewrite;
}
</code>
Refer Change Record for more details.


How do I convert AddressField "Administrative Area" abbreviation to full name

Question: The Address Field module automatically converts administrative area (i.e., State/Province) abbreviations to full names on node display.  I need to do this in my own custom module but can't find the function that the Address Field module uses to do this.  How can it be done?
Comment: @PatrickKenny Have a look at the `addressfield_format_address_generate()` function in `plugins/format/address.inc`. The abbreviation -> full name mapping seems to be hard coded into that function
Comment: http://drupal.stackexchange.com/a/34163/5147  This answer on a related question may give you some hints...
Comment: Thanks for the link to that (I answered that one!), the problem is that something like country_get_list() doesn't exist for state/provinces, but something like that is exactly what I'm looking for!
Comment: It seems like this should be a hook or at least a standalone function in addressbook.module but it doesn't look like it is.  Might end up being a feature request.
Comment: The Location Taxonomize module also has a function that does this at line 109 of location_taxonomize_af.module.  I don't understand what's going on there but it may help in finding the solution.
Answer: As mentioned earlier, there's no function in addressfield that does this, it's hard coded and not re-usable.  Instead, there's a function in addressfield_tokens module which DOES do this.
Using this function isn't really good practice because it's not an official hook (so it could change at anytime without notice), but as long as you're aware of what's going on and you use the proper checks that the module exists, it's the most flexible way to make this happen.  Here's how to use it:
First, ensure that addressfield_tokens.module is installed.  Then you can use this function from line 338 in the .module file:
_addressfield_tokens_state($country, $state)

You need the $country because abbreviations are sometimes the same for different countries.  So, if we wanted to find the full name of California, we would do this:
$california_fullname = _addressfield_tokens_state('US', 'CA')
return $california_fullname;

Comment: Can this works with Facets ?
Answer: Drupal 8,
For Country List
$full_country_list = \Drupal::service('country_manager')->getList();
State or Administrative_area list
$full_state_list = \Drupal::service('address.subdivision_repository')->getList(['US']);
Hope, it will be helpful to someone.
Comment: Thank you @allabakash.g This is very useful in 2024.
Answer: For someone who wants to convert the country name as well, use:
_addressfield_tokens_country($country)

Answer: Address field contains a very useful function:
addressfield_get_administrative_areas($country);

This returns the administrative areas for the country specified, keyed by the abbreviations.
e.g.
$australian_states = addressfield_get_administrative_areas('AU');

This would result in the following array:
$australian_states = array(
   'ACT' => t('Australian Capital Territory'),
   'NSW' => t('New South Wales'),
   'NT' => t('Northern Territory'),
   'QLD' => t('Queensland'),
   'SA' => t('South Australia'),
   'TAS' => t('Tasmania'),
   'VIC' => t('Victoria'),
   'WA' => t('Western Australia'),
);

Comment: This is the function that you need to use with newer versions of Address Field. The function `_addressfield_tokens_state` mentioned in the accepted answer is no longer available.
Comment: Also, it looks like you need to call `module_load_include('inc', 'addressfield', 'addressfield.administrative_areas');` when `addressfield_get_administrative_areas` isn't defined.
Answer: Take a look at example/plugins/format/addressfield-example.inc. This file handles all the formatting changes. These look like they're hardcoded in.
Take a look at plugins/format/address.inc as well.
Answer: Background
I needed to output the Province code as the full Province name as well. I dug into the module and in addressfield.address_formats.inc I found the following comment:
- render_administrative_area_value: True if the value should be rendered

I also found the following in address.inc:
'#render_option_value' => $address_format['render_administrative_area_value'],

From this, it appears that, if you retrieve the render array for the addressfield for a given entity, you can simply set the administrative_area sub-field's #render_option_value attribute to TRUE. I did this (code sample below) and, lo and behold, the Addressfield default formatter is observing this attribute nicely. I've got the full province name just as I wanted.
PS: I am making use of entity and uuid_entity modules to store some static content that needs to be version controlled in code and made deployable - thus, instead of node_load($nid) you see entity_load_single_by_uuid('node', $somvar['uuid']); in the code sample below.
Code Sample
$node = entity_load_single_by_uuid('node', $somvar['uuid']);
$address = field_view_value(
  'node',
  $node,
  'field_address_primary',
  $node->field_address_primary[LANGUAGE_NONE][0],
  'default'
);
$address['locality_block']['administrative_area']['#render_option_value'] = TRUE;

return render($address);

Hope this proves useful!