Special case of $\varepsilon-\delta$ continuity

Question: Realted with the of "epsilon-delta" definition of continuity, I am looking some example of a continuous function defined on [0,1] such that $|f(t)-f(s)|<\delta/2$ whenever $|t-s|\leq \delta$.
Of coruse, any continuosly differentiable $f$ with $|f'(t)|<1/2$ for each $t\in [0,1]$ satisfies the above condition, but do you know others examples?
Many thanks in advance for your comments.
Comment: This condition is known as [Lipschitz](https://en.wikipedia.org/wiki/Lipschitz_continuity), with constant $\frac12$.
Comment: Yes, but there is a not Lipschitz function such the above condition is satifies?
Comment: There are many Lipschitz functions that aren't differentiable. Take, for instance, $|x|$ (or in your case $\frac12|x|$), or a triangular wave. I know there exists functions that are differentiable at significantly fewer points, but I don't know of a concrete example.
Comment: The Weierstrass function is nowhere differentiable, or the Hilbert space-filling curve.  The question (sorry for not writing the statement correctly) is if there are not Lipschitz functions.
Comment: Then have a look at the [following theorem](https://en.wikipedia.org/wiki/Rademacher%27s_theorem) that I just found. Turns out I was wrong, and Lipschitz continuous functions are necessarily almost everywhere differentiable.
Comment: Yes, the Rademacher theorem ;)
Answer: Define the periodic sawtooth function
$$\phi(t):=\left\{\eqalign{|t|\quad &\qquad(-1\leq t\leq 1),\cr \phi(t+2)&\qquad\forall\>t\in{\mathbb R}\ .\cr}\right.$$
Then choose an $N\gg1$ and put
$$f(t):={1\over2}\sum_{n=1}^N{1\over 2^n}\>\phi\bigl(2^n t\bigr)\ .$$
Comment: Many thanks Christian Blatter!!  What a beatiful  "strange" function! ;)


Is there a word can I use to express the fact that a piece of music has no notes in?

Question: I was wondering if there was a word to describe a (lack of) tonality of a piece of music - or section of a piece of music - to the extent that it is without any identifiable notes? A couple of examples would be They're Coming to Take Me Away, Ha-Haaa! and The Whisper Song (warning - a bit rude, if you don't know it!).
4′33″ would also fit the bill, I suppose...
Comment: Well They're coming to take me away has a melody that you can sing. The notes are different.  The Whisper song is closer to being monotone as it's hard to make a musical sound by whispering.
Comment: At least one of the songs you used as and example has notes that are sung.
Comment: I don't personally hear *They're coming to take me away* as a melody, just exaggerated spoken intonation - I wonder if we're listening to the same version?
Comment: In general, I wouldn't lump all the songs you've listed together. Yes the music doesn't have the feel of a central pitch (tonic) or any pitches at all in some, but what drives each piece is different.
Comment: Hmm - what bit of which song?
Comment: You said " section of a piece of music - without any identifiable notes" - do you mean lyrics that are only spoken and not sung or would a drum solo also fit that definition?
Comment: A drum solo could be another example - although of course some drums have very definite pitches! The minimal drums in 'whisper' are a pitched sound, but the pitch envelope on each takes the resultant sound away from being 'notes', to my ear/mind.
Comment: I don't know a specific word for what you are looking for but hopefully someone will provide a useful answer.
Comment: Are you just referring to music that is **unpitched**?
Comment: well we talk about unpitched sounds, so just saying *unpitched music* makes sense I guess!
Answer: Unpitched. It means sounds that have indefinite pitch. Sprechstimmung like They're coming to take me away or the Geographical Fugue qualifies. Pieces using unpitched percussion certainly qualify. 4'33" is maybe more conceptual, but it probably qualifies if there isn't any music playing in the background... :D
Answer: Noteless or perhaps toneless.
Music by definition does not require notes, only vocal or instrumental sounds.
I believe most of the serious composers I've known would call noteless music experimental or avant garde.
Answer: Maybe "indeterminate pitch"?  The Beatles piece "A Day in the Life" has one or two passages where the orchestra is instructed to glide from one pitch to another individually.  It seems to fit your description.  Since we are talking here about mainstream pop music, "avantgarde" or "atonal" is not really a fitting label, and "unpitched" also does not fit the bill as we are just talking unsynchronized pitched instruments.
Of course, your example of 4'33" trivially meets the label "unpitched".  And so does a number of purely percussive pieces (note that some percussive instruments have determinate pitch as well, like timpani and cowbells, and some are used melodically, like tubular bells, marimba, glockenspiel, xylophone, celesta...).
So generally your description covers a rather large body of music, large enough that it would probably be a bit difficult to subsume all of it under a single label.
Comment: I wasn't looking for a genre label that has to give an idea of what the piece sounds like - simply a term for music made essentially from sounds of indeterminate pitch. It would cover a wide body of music, but then so would a term like 'polyrhythmic' or 'diatonic'.
Answer: The term 'indefinite pitch' is used in Australian schools.
Answer: The word you're looking for is Atonal
Comment: atonal just means it's not written in any key, which is very different from "without any identifiable notes", which is not a lack of tonality.  I have no idea what the original poster wants.
Comment: Atonal has come to mean music without a tonal 'center' - so while it could be correct to describe the pieces I've mentioned as atonal, it's lumping them in with works such as 12-tone technique works - I was looking for a term that would distinguish them.
Comment: Which is what I was doing- describing the pieces you mentioned. 12-tone technique works are their own separate thing, no matter how people lump them together.


How to analyze mm. 5-8 in the first movement of Beethoven Piano Sonata No. 8

Question: Everything makes sense until mm. 5. It looks like it moves from c minor to Eb major.
Suppose we're in Eb major starting at mm. 5
From the end of mm. 5 to the very beginning of mm. 6, it's a vii°7/vi in Eb. It cannot be vii°7 because the root is B. It can't be CT°7 of the next chord because the root of the next chord is not in it.
Then it moves to the V7 chord. But it's not used functionally because it never resolves.
Next, it becomes even more interesting. It goes to vii°42/D and V42/D. And it resolves to D6 in mm. 7.
Finally, it goes to vii and V of c minor in mm. 8-9 (simplified a bit here).
mm. 5 is probably never in Eb
That D chord in mm. 7 is probably not in Eb major. It makes more sense to be a V/V in c minor.
If we work backward, that vii°7/vi in Eb should be vii°7 in c. It came from iv42 in c (instead of ii42 in Eb). Beethoven just used that long dominant chord in mm. 4 to tonicize to III of c minor.
But what is that unresolved dominant in mm. 6?
It probably makes sense in the context of a sequence. The voice leading takes precedence of its function. And it sounds surprising. I guess there can be a better explanation here. I'm curious to hear what people think.

Conclusion
Thanks @Aaron for the response. I think everything makes more sense taking into account the enharmonic spelling. So this is what I have. Everything is in c minor.
measure 5
It starts on III of c minor. Goes to iv42 on beat 3.
On beat 4, it moves from CT°7 -> iv64 -> vii°7/III.
measure 6
It moves from vii°7/III to V7/III on beat 2.
In the rest of the measure, instead of resolving the V7, it moves on from vii°42/V/V -> V42/V/V -> vii°43/V/V.
measure 7-8
It resolves that vii°43/V/V to V6/V.
Starting from beat 3 until the end of beat 2 on measure 8, it goes through inversions of vii°42 and lands on V7 in beat 3.
Finally, it moves from V7 -> iv7 -> V7.
At a high level
If we ignore those fancy applied chords (vii -> V on those tonicized centers), this is what happens from measure 5-8 (ignoring the inversions).
III -> iv -> V/III (or VII, unresolved) -> V/V -> V -> iv -> V -> i
I still find that unresolved dominant in measure 6 very interesting. It's Beethoven telling you "Hey, think I'll resolve to Eb? Guess where I go next!". In terms of listening, it creates a strong sense of searching.
Another interpretation
I originally tried to find a linear progression here but I couldn't because I was trying to find one that connects the entire passage.
If we only look at measure 5 beat 3 until measure 6 beat 3, it is a linear progression connecting iv42 and vii°42/V/V.
I also found https://www.harmony.org.uk/book/linear_progressions.htm, which has a Mozart example with a similarly unresolved V chord in the progression.
Some people believe that Beethoven was inspired by this Mozart sonata. I think that makes sense. There are many similarities between the two and Beethoven just takes it to the next level.
Comment: I learned the concept of linear progression back in school, but I'm not sure that I can find the two functional chords that it's connecting. And it still doesn't explain that unresolved major-minor 7th chord. I guess nobody made the rule that it has to be resolved, but I find it really interesting.
Comment: @Aaron. Oh. My bad. I meant Eb. I'll edit the post
Answer: TL;DR
Beethoven is using a combination of common-tone and enharmonic modulation. Common-tone diminished chords are discussed in various posts here; a list can be found here. Enharmonic modulation, as used in mm. 5–8, is where a diminished chord is reinterpreted according to an enharmonically equivalent diminished chord.

Analysis
measure 5
Begins in III (E♭), moving to ii[4-2]/III (Fm7/Eb) on beat 3.
The chord on beat 4 is spelled as viio[6-5] (Bdim/D), but interpretively, it's rooted on F: a common-tone chord, which undergoes a voice exchange by passing through an apparent ii[6-4]/III, but which is best considered as "just a passing chord".
The Bdim spelling is to help clarify the descending motion of the bass: Eb-D-C-B-Bb across m. 5 into m. 6.

Functionally, the second half of measure 5 is ii/III, the harmony being prolonged via a common-tone diminished chord and voice exchange within that chord.
Contrapuntally, the diminished chord serves to bridge the ii[4-2]/III chord with the upcoming V7/III chord in m. 6 beat 2.

measure 6
The common-tone diminished chord proved to be a contrapuntal, passing chord connecting measure 5's ii/III with V/III on beat 2.
Beat 3 immediately employs another common-tone diminished chord, this time Bbdim, but spelled as C#dim (viio[4-2]/V/V) to hint at the arrival on D major (V/V) in m. 7.
Beats 3 and 4 comprise a contrapuntal expansion of the diminished chord, again via voice exchange, which conveniently places the "passing" V/V/V (A major) on beat 4 — a strong rhythmic position compared to the diminished chord on the &-of-3 and &-of-4.
measures 7 and 8
After an initial arrival on V/V (D major), beat 3 sees the arrival of another common-tone diminished chord: Ddim spelled as Bdim to reflect the larger context of C minor.
This time, instead of voice exchange, Beethoven takes the diminished chord through its various inversions, all of which serve as an extended chromatic passing chord between V/V in measure 7 with V7 in measure 8.
Finally, V7 is expanded by briefly visiting iv6 (Fmin/Ab) on beat 4.
Comment: Thanks for the detailed analysis! Based on what I've learned, the root of the resolution of a CT-dimished chord must appear in the CT chord. But this never happens in the score. However, I think your interpretation of the enharmonic spelling makes sense (though I'm not really sure what the problem is to change B natural to C-flat at the end of mm. 5 and the beginning of mm. 6).
Comment: (Don't know how to put new lines in a comment. Let me edit my post instead)

So mm. 5 beat 4 and mm. 6 beat 1-2 are simply [vii -> V] of Eb major (III).
Then this V is never resolved and moves to [vii -> V] of D (V/V) in mm. 6 beat 3-4 and mm. 7 beat 1-2.
Everything after until mm. 9 is [vii -> V -> iv -> V] of c minor.

If we treat those [vii -> V]'s as voice leading additions, the entire passage is basically [III -> iv -> V/III (or VII, unresolved) -> V/V -> V -> iv -> V -> i] of c minor.  The unresolved V is still very interesting.
Comment: @lbbl59 - I'll note that your "V -> iv" is actually V -> iv6, which, according to my Royal Conservatory of Music-approved textbook, actually *is* a permitted chord progression in common practice period harmony due to its strong resemblance to a V -> VI deceptive cadence.
Comment: @Dekkadeci, I ignored the inversions and showed only the functions. I thought that sounds smooth because of the voice leading but I think the textbook is right that it sounds like V->VI. Similar to how an N chord sounds like IV.


List compreension vs ciclo for

Question: Eu tenho os seguintes segmentos de código:
def is_even(num):
    if(num % 2 == 0):
        return True
    return False

1.
lista = range(50)
pares = [i for i in lista if is_even(i)]
# pares = [0, 2, 4, 6, 8...]

2.
lista = range(50)
pares = []
for i in lista:
    if is_even(i):
        pares.append(i)
# pares = [0, 2, 4, 6, 8...]

Neste caso, deve-se usar algum em detrimento de outro? Ou é indiferente? Porquê?
Comment: Depende. Sob qual aspecto?
Comment: Performance/viabilidade por ex. Neste mesmo que está apresentado. Qual escolheria? Vantagens e desvantagens
Answer: Fazendo um teste com o primeiro script:
def is_even(num):
    if(num % 2 == 0):
        return True
    return False

lista = range(5000000)
pares = [i for i in lista if is_even(i)]

E com o segundo script:
def is_even(num):
    if(num % 2 == 0):
        return True
    return False

lista = range(5000000)
pares = []
for i in lista:
    if is_even(i):
        pares.append(i)

Através do comando "time" (ex: time python script.py) e extrapolando o valor do tamanho da lista de 50 para 5000000 é possível ter um ideia de que o primeiro método é mais rápido. No entanto para apenas 50 iterações creio que se pode dizer que a diferença é marginal.
O código da primeira solução também parece mais elegante e de melhor leitura.
Comment: Obrigado. `+1` pelo comando que eu não conhecia `time python file.py`

List compreension vs ciclo for


uniformly convergence of $\sum\limits_{n=1}^{+\infty} {{x^2+n} \over {n^2x^4+n^4+1}}$

Question: $f_n(x)={{x^2+n} \over {n^2x^4+n^4+1}}$.
pointwise convergence: in all R because $|f_n(x)|\sim {{1} \over {n^3}}$ general term of a convergent series
uniformly convergence: I study it in $[0,+\infty)$ because $f_n(x)$ are even.
I proved to calculate sup$_R |f_n(x)|$ but is complicated.Is there another way?
Answer: Hint: If $x^2 \leq n$, then $|f_n(x)| \leq \frac{2n}{n^4+1} \leq 2n^{-3}$.
If $x^2 > n$, $|f_n(x)| \leq \frac{2x^2}{n^2x^4} \leq 2n^{-3}$.
Answer: Let $f_n(x)=\frac{x^2+n}{n^2x^4++n^4+1}$. Then
$$n^2x^4+n^4+1\ge n^2x^4+n^4=n^2(x^4+n^2).$$
Now, it is clear that for $|x|\ge1$, $x^2+n\le x^4+n^2$. Then, for $|x|\ge 1$, $0\le f_n(x)\le \frac{1}{n^2}$ and the Weierstrass Mayoration Test do the job.
For $|x|\le 1$, $0\le f_n(x)\le \frac{1+n}{n^4}$ and again Weierstrass Mayoration Tests guarantees the uniform convergence.


Angjularjs Adding Controller to index.html gives blank page

Question: Brand new to Angular.  I have a controller that when I add it to my list of script files on in index.html page, my site stops working and I get blank pages for all of my views.  I'm not sure what I'm doing wrong?  I'm adding the controller to my index.html file like this

And I'll paste my controller code below if that's part of the problem.
var app = angular.module('crm.ma', ['ngAnimate', 'ui.bootstrap']);

app.controller('ModalDemoCtrl', function ($scope, $uibModal, $log) {

$scope.items = ['item1', 'item2', 'item3'];

$scope.animationsEnabled = true;

$scope.open = function (size) {

    var modalInstance = $uibModal.open({
        animation: $scope.animationsEnabled,
        templateUrl: 'myModalContent.html',
        controller: 'ModalInstanceCtrl',
        size: size,
        resolve: {
            items: function () {
                return $scope.items;
            }
        }
    });

    modalInstance.result.then(function (selectedItem) {
        $scope.selected = selectedItem;
    }, function () {
        $log.info('Modal dismissed at: ' + new Date());
    });
};

$scope.toggleAnimation = function () {
    $scope.animationsEnabled = !$scope.animationsEnabled;
};

});

app.controller('ModalInstanceCtrl', function ($scope, $modalInstance, items) {

$scope.items = items;
$scope.selected = {
    item: $scope.items[0]
};

$scope.ok = function () {
    $modalInstance.close($scope.selected.item);
};

$scope.cancel = function () {
    $modalInstance.dismiss('cancel');
};
});

If anyone could help me that'd be great.  Thanks in advance.
Comment: what errors are thrown? What is `$uibModal`?
Answer: The service $uibModal has been introduced very lately, in version 0.14.0 of ui-bootstrap. I guess you are still on a version < 0.14.0 of ui-bootstrap, therefore, replace:
$uibModal

with
$modal

Or update ui-bootstrap to 0.14+


Converting categorical variables to numerical ones

Question: I am working on a binary classification task where one of the input variables takes values in {A, B, C}.  A lot of classifiers only take numerical attributes as inputs so I was wondering what the best way to do this is.  If I just map them to integers like A:1, B:2, C:3, I am worried that this would mean that A is more similar to B and less similar to C (because |1-2|=1 and |1-3|=2) but that is not necessarily true.  So won't this method introduce some sort of bias?
Comment: What about Dummy coding?
Answer: The use of dummy coding (aka indicator variables) is probably your best bet. As you've mentioned, converting categorical variables to numerical ones not only assumes they have a clear ordering 1 (A) < 2 (B) < 3 (C), but also for many tasks that the "change" between A and B and B and C are equal, and half that of the change between A and C.


How to set 0 to white at a uneven color ramp

Question: I have an uneven color ramp and I want the 0 to be white. All negative colors have to be bluish and all positive colors have to be reddish.
My current attempted displays the 0 bluish and the 0.7 white.
Is there anyway to set the 0 to white?
import numpy as np
import matplotlib.colors as colors
from matplotlib import pyplot as m

bounds_min = np.arange(-2, 0, 0.1)
bounds_max = np.arange(0, 4.1, 0.1)
bounds = np.concatenate((bounds_min, bounds_max), axis=None)
norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)      # I found this on the internet and thought this would solve my problem. But it doesn't...
m.pcolormesh(xx, yy, interpolated_grid_values, norm=norm, cmap='RdBu_r')

Answer: The other answer makes it a little more complicated than it needs to be. In order to have the middle point of the colormap at 0, use a DivergingNorm with vcenter=0.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import DivergingNorm

x, y = np.meshgrid(np.linspace(0,50,51), np.linspace(0,50,51))
z = np.linspace(-2,4,50*50).reshape(50,50)

norm = DivergingNorm(vmin=z.min(), vcenter=0, vmax=z.max())
pc = plt.pcolormesh(x,y,z, norm=norm, cmap="RdBu_r")
plt.colorbar(pc)

plt.show()

Note: From matplotlib 3.2 onwards DivergingNorm will be renamed to TwoSlopeNorm
Answer: In order to get the desired norm, set the same number of colors on the negative as on the positive side.
Alternatively, you could use the unmodified norm, and create a special colormap. Such a colormap would have 1/3rd of blue-to-white colors and 2/3rd white-to-red colors. A benefit would be that the colorbar looks nicer. Such an approach only works if the balance between negative and positive numbers isn't too extreme.
Here is demo code with generated data. zz is chosen to be a sine rotated around the center, and scaled to go from -2 to 4, so symmetric around 1. At the left the image is shown with the modified colormap. At the right, the norm is changed to force white at zero.
Because of the red coloring of all positive values, the red bands are wider than the blue. In an image without changing norms nor colormaps, the bands would have equal width. The colorbars indicate the zero to be white.
import numpy as np
import matplotlib.colors as colors
from matplotlib import pyplot as plt

x = np.linspace(-20, 20, 500)
y = np.linspace(-20, 20, 500)
xx, yy = np.meshgrid(x, y)
zz = np.sin(np.sqrt(xx * xx + yy * yy)) * 3 + 1

negatives = -2.0
positives = 4.0

bounds_min = np.linspace(negatives, 0, 129)
bounds_max = np.linspace(0, positives, 129)[1:]
    # the zero is only needed once
    # in total there will be 257 bounds, so 256 bins
bounds = np.concatenate((bounds_min, bounds_max), axis=None)
norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)

num_neg_colors = int(256 / (positives - negatives) * (-negatives))
num_pos_colors = 256 - num_neg_colors
cmap_BuRd = plt.cm.RdBu_r
colors_2neg_4pos = [cmap_BuRd(0.5*c/num_neg_colors) for c in range(num_neg_colors)] +\
                   [cmap_BuRd(1-0.5*c/num_pos_colors) for c in range(num_pos_colors)][::-1]
cmap_2neg_4pos = colors.LinearSegmentedColormap.from_list('cmap_2neg_4pos', colors_2neg_4pos, N=256)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

mesh1 = ax1.pcolormesh(xx, yy, zz, cmap=cmap_2neg_4pos)
ax1.set_aspect('equal')
ax1.set_title('using a modified cmap')
fig.colorbar(mesh1, ax=ax1)

mesh2 = ax2.pcolormesh(xx, yy, zz, norm=norm, cmap='RdBu_r')
ax2.set_aspect('equal')
ax2.set_title('using a special norm')
ticks = np.append(np.arange(-2.0, 0, 0.25), np.arange(0, 4.001, 0.5))
fig.colorbar(mesh2, ax=ax2, ticks=ticks)

plt.show()

Following code plots the norm, which looks like a step function. Only with 257 bounds this step function has the correct shape everywhere (zooming to x at -2, 0 and 4).
nx = np.linspace(-3,5,10000)
plt.plot(nx, norm(nx))

PS: There is an alternative method to create a similar colormap. But trying it out, it is clear that the RdBu colormap is fine-tuned and produces much better looking plots.
norm_2neg_4pos = mcolors.Normalize(negatives, positives)
colors_2neg_4pos = [[0, 'blue'],
                    [norm_2neg_4pos(0.0), "white"],
                    [1, 'red']]
cmap_2neg_4pos = mcolors.LinearSegmentedColormap.from_list("", colors_2neg_4pos)

Still another simple solution is rescaling everything between -4 and 4. However, this would lose the darker blues. An alternative to 'RdBu_r' is 'seismic' with a different way to run from red over white to blue.
ax.pcolormesh(xx, yy, zz, vmin=-positives, vmax=positives, cmap='RdBu_r')

Comment: Thank you for your help! It took me a while to get it right, but now it works. Do you know if it is possible to have the negative bar shorter than the positive bar?
Comment: Yes, that can also be done. In that case, the norm is not needed, only the colormap needs to be recalculated. It won't work well if there is a huge difference between negative and positive, but with a factor of 2 it would work well. Give me some time to create an example.


there is a crash use the afnetworking 3.0.4 , [NSProgress setTotalUnitCount:], anyone who can tell me the reason

Question: After I upgrade AFNetworking to 3.0.4, there was a crash in my APP,but the crash not always occur, i don't find any information in stack overflow , here are some crash information, someone who can inform the reason ,thx
<code>Crashed: com.apple.main-thread
0  libobjc.A.dylib                0x181339b9c objc_msgSend + 28
1  Foundation                     0x1825aa3c4 -[NSObject(NSKeyValueObserverNotification) willChangeValueForKey:] + 324
2  Foundation                     0x18278d8d4 -[NSProgress _setValueForKeys:settingBlock:] + 264
3  Foundation                     0x18278dbc4 -[NSProgress setTotalUnitCount:] + 124
4  QCQ                     0x100408e08 -[AFURLSessionManagerTaskDelegate init] (AFURLSessionManager.m:141)
5  QCQ                     0x10040c230 -[AFURLSessionManager addDelegateForDataTask:uploadProgress:downloadProgress:completionHandler:] (AFURLSessionManager.m:621)
6  QCQ                     0x10040d1e0 -[AFURLSessionManager dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:] (AFURLSessionManager.m:771)
7  QCQ                     0x10040d0b0 -[AFURLSessionManager dataTaskWithRequest:completionHandler:] (AFURLSessionManager.m:756)
8  CoreFoundation                 0x181cc8a60 __invoking___ + 144
9  CoreFoundation                 0x181bc0488 -[NSInvocation invoke] + 284
10 QCQ                     0x100493480 +[QCQService taskWithRequest:andBlock:andInvocation:cacheResponse:] (QCQService.m:316)
11 QCQ                     0x100493cc0 +[QCQService startDataTaskWithParameters:apiPath:HTTPMethod:cachePolicy:completionBlock:] (QCQService.m:397)
12 QCQ                     0x1002be060 +[QCQSystemSettingService noticeCenterDataWithBlock:] (QCQSystemSettingService.m:44)
13 QCQ                     0x10013dc88 -[QCQMoreViewController loadSystemNoticeCount] (QCQMoreViewController.m:97)
14 QCQ                     0x10013d9f0 -[QCQMoreViewController viewWillAppear:] (QCQMoreViewController.m:70)
15 UIKit                          0x186e39374 -[UIViewController _setViewAppearState:isAnimating:] + 628
16 UIKit                          0x186e390e8 -[UIViewController __viewWillAppear:] + 156
17 UIKit                          0x186f65c78 -[UITabBarController transitionFromViewController:toViewController:transition:shouldSetSelected:] + 876
18 UIKit                          0x186f658f8 -[UITabBarController transitionFromViewController:toViewController:] + 68
19 UIKit                          0x186f65730 -[UITabBarController _setSelectedViewController:] + 404
20 UIKit                          0x186f653fc -[UITabBarController setSelectedIndex:] + 136
21 QCQ                     0x1003e072c -[QCQMainViewController setSelectedIndex:] (QCQMainViewController.m:271)
22 QCQ                     0x1003e06cc -[QCQMainViewController tabBar:didSelectItem:] (QCQMainViewController.m:266)
23 UIKit                          0x187030a2c -[UITabBar _sendAction:withEvent:] + 312
24 UIKit                          0x186e58be8 -[UIApplication sendAction:to:from:forEvent:] + 100
25 UIKit                          0x186e58b64 -[UIControl sendAction:to:forEvent:] + 80
26 UIKit                          0x186e40870 -[UIControl _sendActionsForEvents:withEvent:] + 436
27 UIKit                          0x187030738 -[UITabBar(Static) _buttonUp:] + 112
28 UIKit                          0x186e58be8 -[UIApplication sendAction:to:from:forEvent:] + 100
29 UIKit                          0x186e58b64 -[UIControl sendAction:to:forEvent:] + 80
30 UIKit                          0x186e40870 -[UIControl _sendActionsForEvents:withEvent:] + 436
31 UIKit                          0x186e58454 -[UIControl touchesEnded:withEvent:] + 572
32 UIKit                          0x186e10c0c _UIGestureRecognizerUpdate + 8988
33 CoreFoundation                 0x181c78728 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 32
34 CoreFoundation                 0x181c764cc __CFRunLoopDoObservers + 372
35 CoreFoundation                 0x181c768fc __CFRunLoopRun + 928
36 CoreFoundation                 0x181ba0c50 CFRunLoopRunSpecific + 384
37 GraphicsServices               0x183488088 GSEventRunModal + 180
38 UIKit                          0x186e8a088 UIApplicationMain + 204
39 QCQ                     0x100064fb0 main (main.m:16)
40 libdispatch.dylib              0x18173e8b8 (Missing)
</code>
Comment: Any Errors? Any suggestions from your side? Please add some more Informations to your Question!
Comment: @MiBrock yeah , i have add the description to the question ,thanks for your reply ,can you help me
Comment: can you post code if possible
Answer: AFNetworking has fix it , you can see here https://github.com/AFNetworking/AFNetworking/issues/3580
Answer: Check out this post: https://github.com/AFNetworking/AFNetworking/issues/2597
As I understand you have to hold a strong reference of:
1: The Manager (AFHTTPSessionManager or AFURLSessionManager)
2: NSProgress


What ciphers are compatible with both Java 6/Tomcat 7 and IE8 (XP)?

Question: I have disabled SSL3 and restricted the ciphers available to a recommended set but now I can't access my server using IE8 on Windows XP. If I allow all ciphers then I can connect using IE8 but when I specify a restricted set of ciphers I can't. Seems to me that I need to add the right cipher and then IE8 will work fine.
When I have all ciphers enabled and access the site using IE8 I can see the connection is using TLS 1.0, RC4 with 128 bit encryption and RSA:

I tried adding this cipher: TLS_RSA_WITH_RC4_128_SHA. But I don't think Tomcat/Java recognised it.
My connector looks like this:
<Connector port="443" protocol="org.apache.coyote.http11.Http11Protocol"
           maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
           clientAuth="false" sslProtocol="TLS" sslEnabledProtocols="TLSv1.2,TLSv1.1,TLSv1" keystoreFile="C:\somewhere\my.keystore"
           ciphers="TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
           TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_RSA_WITH_RC4_128_SHA,
           TLS_RSA_WITH_AES_128_CBC_SHA256,TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA256,
           TLS_RSA_WITH_AES_256_CBC_SHA" />

I'm using Tomcat 7 and Java 6
This might be a red herring but I've been referring to these cipher suites as I think I'm restricted to these by Java 6. Additionally I've been referring to the ciphers this document (page 30) says IE8 on XP supports. Unfortunately I can't find a match between the 2 sets of ciphers.
UPDATE:
My IE8 browser on XP seems to only support these cipher suites:

I've updated the ciphers for Tomcat to include all of these but I still can't connect:
ciphers="TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_RSA_WITH_RC4_128_SHA,TLS_RSA_WITH_AES_128_CBC_SHA256,TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA256,TLS_RSA_WITH_AES_256_CBC_SHA,TLS_RSA_WITH_RC4_128_MD5,TLS_RSA_WITH_RC4_128_SHA,TLS_RSA_WITH_3DES_EDE_CBC_SHA,TLS_RSA_WITH_DES_CBC_SHA,TLS_RSA_EXPORT1024_WITH_RC4_56_SHA,TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA,TLS_RSA_EXPORT_WITH_RC4_40_MD5,TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5,TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA,TLS_DHE_DSS_WITH_DES_CBC_SHA,TLS_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA"

I don't know why I can connect with ALL ciphers enabled but if I specify every cipher supported by the browser I still can't connect
Comment: So it's not connecting with the cipher spec you have listed, correct?  But with all ciphers enabled on the same Tomcat service it connects?
Comment: That's right. So there must be a common cipher that both support... surely
Comment: Try `SSL_RSA_WITH_RC4_128_SHA`?
Comment: That works... but isn't this an SSL connection? My main intention is to disable SSL and weak ciphers where possible
Answer: SSL_RSA_WITH_RC4_128_SHA should work - the reason for this is just a difference in terminology, the ciphers in Java 6 that required TLS were the only ones that have the TLS on the name.  This particular cipher spec works under TLS as well as SSL despite the name.
This configuration should allow connections from IE8 on XP while still rejecting SSLv3 connections, since the enabled protocols are controlled with sslEnabledProtocols="TLSv1.2,TLSv1.1,TLSv1".
Verify that it's not accepting SSLv3 connections with openssl s_client -ssl3 -connect example.com:443.


How to deal with static final variable

Question: I'm a beginner in Java and I have got some problems with the static final variable. I have a login page from which I can get the username of the currently logged in user.
Login Page Code
import javax.swing.*;

public class ProfileLogin extends JFrame {

    public ProfileLogin() {
        initComponents();
    }

    private void initComponents() {

        jPanel1 = new JPanel();
        proName = new JTextField();
        jButton2 = new JButton();
        jLabel2 = new JLabel();
        jPanel2 = new JPanel();
        logName = new JTextField();
        jButton1 = new JButton();
        jLabel1 = new JLabel();

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setTitle("Sound Recognition System");
        setResizable(false);

        jPanel1.setBorder(BorderFactory.createTitledBorder("Create Profile"));

        jButton2.setText("Create New");
        jButton2.setToolTipText("Click to create a new profile");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel2.setText("Choose a Profile Name:");

        GroupLayout jPanel1Layout = new GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(proName, GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE)
                    .addComponent(jLabel2)
                    .addComponent(jButton2, GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel2)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(proName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE)
                .addGap(16, 16, 16))
        );

        jPanel2.setBorder(BorderFactory.createTitledBorder("Select Profile"));

        jButton1.setText("Login");
        jButton1.setToolTipText("Click to Login");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel1.setText("Enter your Profile Name:");

        GroupLayout jPanel2Layout = new GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(logName, GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE)
                    .addComponent(jButton1, GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(logName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addGap(23, 23, 23))
        );

        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jPanel1, GroupLayout.Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, GroupLayout.Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, GroupLayout.PREFERRED_SIZE, 111, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-195)/2, (screenSize.height-294)/2, 195, 294);
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        String profileName;
        String empty;
        empty = "";
        profileName = proName.getText();

        try {
            if(profileName.equalsIgnoreCase("")) {
              JOptionPane.showMessageDialog(null, "Please Enter a Profile Name!");
              return;
            }

           database.rs = database.st.executeQuery("select pname from login where pname='"+profileName+"'");

           if(database.rs.next()) {
               JOptionPane.showMessageDialog(null, "Username Already Existing!");
               return;
           }

            database.st.executeUpdate("insert into login(pname) values('"+profileName+"')");
            JOptionPane.showMessageDialog(null, "Profile successfully created!");
            proName.setText(empty);;

        }
        catch(Exception e)
        {}

    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        try {
            String loginName=logName.getText().trim();
            if(loginName.equalsIgnoreCase(""))
            {
              JOptionPane.showMessageDialog(null, "Please Enter Profile Name!");
              return;
            }
            database.rs = database.st.executeQuery("select pname from login where pname='"+loginName+"'");
            if (database.rs.next()) {
                Account a = new Account();
                a.setVisible(true);
                this.dispose();
            }
            else
            {
                JOptionPane.showMessageDialog(null, "No such username!");
            }

        } catch (Exception e) {

            System.out.println(e);
            e.printStackTrace();

        }

    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {

                new ProfileLogin().setVisible(true);
            }
        });
    }

    private JButton jButton1;
    private JButton jButton2;
    private JLabel jLabel1;
    private JLabel jLabel2;
    private JPanel jPanel1;
    private JPanel jPanel2;
    private JTextField logName;
    private JTextField proName;
    private DatabaseConnection database = new DatabaseConnection();
}

Now I have a java page in which I need to embed the username from Login page to the static final variable. But I don't know how to pass the variable from the login page and embed the value to a static final variable.
import javax.sound.sampled.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SoundRecording extends JDialog {
        String name="JACOB";
    public static final String SAVE_PATH = "./data/recordings/"+name;

    private JLabel operationLabel;
    private JPanel recordPanel;
    private JButton applyButton;
    private JButton cancelButton;
    private JComboBox operationList;
    private JButton playButton;
    private JButton recordButton;
    private JButton stopButton;
    private JSeparator separator;
    private AudioVisualizer visualizer;

    private AudioInputStream audioStream;
    private SourceDataLine sourceLine;
    private AudioFormat audioFormat;
    private TargetDataLine line;
    private ByteArrayOutputStream output;

    public SoundRecording(JFrame parent) {
        super(parent, "Record", true);

        initComponents();
    }

    @SuppressWarnings("unchecked")
    private void initComponents() {
        recordPanel = new JPanel();
        recordButton = new JButton();
        stopButton = new JButton();
        playButton = new JButton();
        operationLabel = new JLabel("Select Operation:");
        operationList = new JComboBox();
        applyButton = new JButton();
        cancelButton = new JButton();
        separator = new JSeparator();
        visualizer = new AudioVisualizer();

        recordPanel.setBorder(BorderFactory.createTitledBorder("Options"));

        recordButton.setText("Record");
        recordButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                recordButtonActionPerformed(evt);
            }
        });

        stopButton.setText("Stop");
        stopButton.setEnabled(false);
        stopButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                stopButtonActionPerformed(evt);
            }
        });

        playButton.setText("Play");
        playButton.setEnabled(false);
        playButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                playButtonActionPerformed(evt);
            }
        });

        operationList.setModel(new DefaultComboBoxModel(new String[] { "Shutdown", "Sleep", "Close", "Minimize" }));

        applyButton.setText("Apply");
        applyButton.setEnabled(false);
        applyButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                applyButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        GroupLayout recordPanelLayout = new GroupLayout(recordPanel);
        recordPanel.setLayout(recordPanelLayout);
        recordPanelLayout.setHorizontalGroup(
            recordPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(recordPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(recordPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(operationList, GroupLayout.PREFERRED_SIZE, 148, GroupLayout.PREFERRED_SIZE)
                    .addComponent(separator, GroupLayout.PREFERRED_SIZE, 148, GroupLayout.PREFERRED_SIZE)
                    .addComponent(visualizer, GroupLayout.PREFERRED_SIZE, 148, GroupLayout.PREFERRED_SIZE)
                    .addGroup(recordPanelLayout.createSequentialGroup()
                        .addGroup(recordPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                            .addComponent(operationLabel, GroupLayout.PREFERRED_SIZE, 115, GroupLayout.PREFERRED_SIZE)
                            .addGroup(recordPanelLayout.createSequentialGroup()
                                .addComponent(recordButton)
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(stopButton, GroupLayout.PREFERRED_SIZE, 67, GroupLayout.PREFERRED_SIZE))
                    .addComponent(playButton, GroupLayout.PREFERRED_SIZE, 148, GroupLayout.PREFERRED_SIZE)))))
        );
        recordPanelLayout.setVerticalGroup(
            recordPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(recordPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(operationLabel)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(operationList, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(separator, GroupLayout.PREFERRED_SIZE, 10, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(visualizer, GroupLayout.PREFERRED_SIZE, 30, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(recordPanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(recordButton)
                    .addComponent(stopButton, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(playButton)
                .addContainerGap(10, Short.MAX_VALUE))
        );

        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(32, 32, 32)
                        .addComponent(applyButton)
                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton)
                        .addGap(0, 8, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(recordPanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(recordPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(applyButton)
                    .addComponent(cancelButton))
                .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        setSize(215, 299);
        setResizable(false);

        /*
         * This is used to position the frame into
         * the center of the screen.
         */
        setLocationRelativeTo(null);
    }

    private void recordButtonActionPerformed(ActionEvent evt) {
        recordButton.setEnabled(false);
        stopButton.setEnabled(true);
        playButton.setEnabled(false);
        applyButton.setEnabled(true);

        /*
         * Construct the data line from the microphone using
         * the custom audio format.
         */
        try {
            audioFormat = Microphone.getAudioFormat();
            DataLine.Info dataLineInfo = new DataLine.Info(TargetDataLine.class, audioFormat);
            line = (TargetDataLine) AudioSystem.getLine(dataLineInfo);
        } catch(Exception ex) {
            ex.printStackTrace();
        }

        /*
         * Create a thread to capture the microphone data
         * into an audio file and start the thread running.
         */
        CaptureThread capture = new CaptureThread();
        capture.start();
    }

    private void stopButtonActionPerformed(ActionEvent evt) {
        stopButton.setEnabled(false);
        recordButton.setEnabled(true);
        playButton.setEnabled(true);

        line.stop();
        line.close();
    }

    private void playButtonActionPerformed(ActionEvent evt) {
        playButton.setEnabled(false);

        PlaybackThread playback = new PlaybackThread();
        playback.start();
    }

    private void applyButtonActionPerformed(ActionEvent evt) {
        /*
         * Set the file type and the file extension.
         */
        String operation = operationList.getSelectedItem().toString();
        File audioFile = new File(SAVE_PATH + operation + ".wav");

        /*
         * Display the confirmation dialog.
         */
        if(audioFile.exists()) {
            Toolkit.getDefaultToolkit().beep();

            Object[] options = {"Yes", "No",};
            int returnValue = JOptionPane.showOptionDialog(this,
                "This recording already exists, do you want to overwrite?", "Overwrite",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                null,
                options,
                options[1]);

            if(returnValue == JOptionPane.NO_OPTION) {
                return;
            }
        }

        /*
         * Write the stored buffer bytes into the
         * saved audio file.
         */
        byte[] audioData = output.toByteArray();
        ByteArrayInputStream stream = new ByteArrayInputStream(audioData);
        try {
            AudioInputStream audioStream = new AudioInputStream(stream, audioFormat, audioData.length);
            AudioSystem.write(audioStream, AudioFileFormat.Type.WAVE, audioFile);
        } catch(IOException ex) {
            ex.printStackTrace();
        }

        this.dispose();
    }

    private void cancelButtonActionPerformed(ActionEvent evt) {
        this.dispose();
    }

    /*
     * Inner class to capture data from microphone and
     * write it to an output audio file.
     */
    class CaptureThread extends Thread implements Runnable {

        @Override
        public void run() {
            /*
             * Start writing audio data into the data line.
             */
            try {
                /*
                 * Close the current running line while we
                 * listen for input on a new line.
                 */
                Microphone.getLine().stop();
                Microphone.getLine().close();

                /*
                 * Open the new line for recording
                 * sound clips.
                 */
                line.open(audioFormat);
                line.start();

                /*
                 * Start the drawing of the visualizer.
                 */
                visualizer.start();

                /*
                 * Create a buffer which the data can be stored in
                 * and listen for input data.
                 */
                output = new ByteArrayOutputStream();
                while(true) {
                    if(!line.isOpen()) {
                        break;
                    }

                    /*
                     * Get the total about of bytes which
                     * are available on the line.
                     */
                    int available = line.available();

                    /*
                     * Make sure something is pending on
                     * the line before trying to read.
                     */
                    if(available > 0) {
                        byte[] buffer = new byte[available];
                        int read = line.read(buffer, 0, buffer.length);

                        if(read > 0) {
                            output.write(buffer, 0, buffer.length);
                        }

                        /*
                         * Set the chunk of data into the
                         * visualizer.
                         */
                        visualizer.setData(buffer);
                    }
                }

                /*
                 * Close the ouput buffer.
                 */
                output.close();

                /*
                 * Stop the drawing of the visualizer.
                 */
                visualizer.stop();

                /*
                 * Re-open the line and start it running
                 * again.
                 */
                Microphone.getLine().open(audioFormat);
                Microphone.getLine().start();
            } catch(Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /*
     * This class is used for playing back audio which is
     * saved into a buffer. This feeds the audio into the
     * output speaker line.
     */
    class PlaybackThread extends Thread implements Runnable {

        @Override
        public void run() {
            byte[] audioData = output.toByteArray();
            ByteArrayInputStream stream = new ByteArrayInputStream(audioData);

            /*
             * Get the data line to the output speakers.
             */
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
            try {
                sourceLine = (SourceDataLine) AudioSystem.getLine(info);
                sourceLine.open(audioFormat);
            } catch(Exception ex) {
                ex.printStackTrace();
            }

            /*
             * Start the audio output line.
             */
            sourceLine.start();

            /*
             * Write the data into the audio stream.
             */
            int read = 0;
            byte[] data = new byte[stream.available()];
            while(read != -1) {
                try {
                    read = stream.read(data, 0, data.length);
                } catch(Exception e) {
                    e.printStackTrace();
                }

                if(read > 0) {
                    @SuppressWarnings("unused")
                    int written = sourceLine.write(data, 0, read);
                }
            }

            /*
             * Flush any unused bytes from the stream and
             * close the audio line to the speakers.
             */
            sourceLine.drain();
            sourceLine.close();

            /*
             * Re-enable the play button, allowing the user to
             * play the clip again.
             */
            playButton.setEnabled(true);
        }
    }
}

The username has to be added to the static final variable SAVE_PATH so that it will become
"./data/recordings/username"
I have tried to add an sample username directly to this as given below
String name="JACOB";
public static final String SAVE_PATH = "./data/recordings/"+name;

But it says Non-static variable name cannot be referenced from a static context.
Can anybody help me on this?
Comment: Too much code. Cut out the noise.
Comment: Just a small suggestion, Here you are talking about passing Username and Password to another class, instead of doing that, since both these things belong to an entity, like Student, Visitor, Employee etc. You can make a new class with this name and save these credentials inside that class and then call this class as and when needed, instead of mixing this whole thing inside `Swing`
Answer: The easiest way is to make name static as well:
static String name = "JACOB";

But usually, you want to create the path in your member method which is not static:
final String path = SAVE_PATH + name;

Since I can't see how you are using the name variable I can't really tell you what the correct approach in your case would be.
Comment: Just edited the question with the full code. Can you check it now?
Comment: Also, the variable `name` is just an example. Actually the username has to be taken from the Login page, which I don't know how to pass!
Answer: If you need to set or change your static variable you can create a simple static method like
public static void setGlobalSavePath(String name) {
  SoundRecording.SAVE_PATH = "./data/recordings/" + name;
}

And call it when you need, for example
SoundRecording.setGlobalSavePath("JACOB");

But to do it, remove final from SAVE_PATH declaration, or you cannot change its value.

How to deal with static final variable


There are currently no logon servers available

Question: we are using free-ipaserver(192.168.0.200) on fedora, clients are windows xp.
we are successfully added two xp clients(m01(192.168.0.60, m02(192.168.0.61) on test environment.
and also our server name is ipaserver & domain name is xyz.com , samba has been configured working fine.
problem is whenever we access from one xp machine another xp machine  we are getting this error, There are currently no logon servers available to service the logon request,
please give the solutions.
Answer:
make sure the computers in the same network, the same workgroup and have created
the same username.
use net.exe to cache the credential


Combine Bootstrap Tags Input and Jquery UI Selectable

Question: Im at the beginning of a hopefully long journey of trying to learn some programming skills.
This is my first question on stackoverflow :)
When I click on an item in my selectable list Id like it to be added to my Tags Input input field. (So I can either select from a predetermined list of selectable tags or input tags not on the list).
Im using backbone.js.
My html template file has this in it:

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

    <input type="text" class="form-control tags" name="tags" placeholder="tags" data-role="tagsinput">

But I dont know what to put in the js view file.  Right now all I have is the method pretty close to how I copied from Tags Input documentation. (im even unsure what should replace "some tag".
 events: {
  'addtags': 'addtags'
},

addtags: function(e) {
  $('input').tagsinput('add', 'some tag');
}

Answer: It doesn't take the items that have been selected out of the input if you click them a 2nd time, but it does let me click on an item in my selectable list Id like it to be added to my TagsInput input field, and I can still type any tag directly to the input field.
return BaseView.extend ({
    template: function() {
      $('.tags').tagsinput();
      $("#selectable").bind("mousedown", function(e) {e.metaKey = true;}).selectable();
    },
    events: {
      'mousedown #selectable': 'addtags'
    },

    addtags: function(e) {
     // if($(e.target).hasClass('selected')){
       $('.tags').tagsinput('add', e.target.innerHTML);
    },


Notice: Undefined index:

Question: estou com diversas msg de error de :
SecureStore
Notice: Undefined index:
basicamente no meu sistema de login quando não está logado aparece esse error
no carrinho de compras qnd não tem nenhum produto aparece esse error.
(Quando tem um produto no carrinho( não aparece o error, pq tem dados na tabela do mysql)
(Quando estou logado no site também não aparece error.)
codigo:

   <?php
                $sessao = $_SESSION['pedido'];
                $consulta = $pdo->prepare("SELECT * FROM carrinho_temporario WHERE temporario_sessao =:ses");
                $consulta -> bindValue(':ses', $sessao);
                $consulta -> execute();
                $linhas = $consulta -> rowCount();
                ?>

Carrinho(<?= $linhas ?>)

</form>

<?php
if ($_SESSION['logged_in'] != true){
?>

       <form action="login.php" method="post">
        Email:

        <input type="text" name="email" id="email">

        Senha:

        <input type="password" name="password" id="password">

        <input type="submit" value="Entrar">
    </form>

<?php
}
?>

Answer: Você precisa pelo que eu percebi, é inicializar a sessão no PHP, pois se não fizer isso, você não vai conseguir acessar algo como $_SESSION['Alguma_Coisa'];
Aprovei para verificar os nomes das chaves das sessões.

   <?php
            if (!session_start())
                session_start();
            $sessao = $_SESSION['pedido'];
            $consulta = $pdo->prepare("SELECT * FROM carrinho_temporario WHERE temporario_sessao =:ses");
            $consulta->bindValue(':ses', $sessao);
            $consulta->execute();
            $linhas = $consulta->fetchall(PDO::FETCH_ASSOC);
            if (count($linhas) > 0) {
                $linhas = $consulta->rowCount();
                ?>

Carrinho(<?= $linhas ?>)

                <?php
            }
            ?>
            </form>

<?php
if (!isset($_SESSION['logged_in'])) {
    ?>
    <form action="login.php" method="post">
        Email:

        <input type="text" name="email" id="email">

        Senha:

        <input type="password" name="password" id="password">

        <input type="submit" value="Entrar">
    </form>

    <?php
} else {
    if (isset($_POST["email"]) && isset($_POST["password"])) {
        // Faz as ações de busca no banco de dados...
    } else {
        // mostra as coisas de login invalido...
    }
}
?>

Comment: eu já iniciei mano, ele consegue acessar de boa o problema é quando não tem nada no mysql aparece esse error: Se eu adicionar 1 item ao carrinho ele some, e fazer o login o problema do login também some.
Comment: Editei a resposta para você, para ver se serve. coloquei a contagem de linhas retornadas do mysql.
Comment: opa mano creio que isso der uma ajudada, mas acho que o problema está nessa session pedido pois deu esse error: Notice: Undefined index: pedido in C:\xampp\htdocs\skincs\logar.php on line 2
Comment: Veja a modificação na resposta em relação a $_SESSION['logged_in'], que estava sendo verifica de forma que se não existisse, retornaria erro.
Comment: crlho tu é o cara mano mds kkkkkkkkkkkkkkkkkkk
Comment: eu tava desde ontem quebrando a cabeça por um negocio tão simples ...'
Comment: Isso é normal amigo, todos nós já sofremos muito um dia! Abraço e boa caminhada nos código!
Comment: será que se utilizar uma logica parecido no  $sessao = $_SESSION['pedido']; daria certo?
Comment: Sim, claro, essa é a melhor forma que conheço para testar sessões. vai fundo!
Comment: if ($_SESSION['logged_in'] != true){

    echo 'Login';

}else{

    echo $_SESSION['user_name'];
}
?>
Comment: vc poderia me ajudar nessa parte? Quando não está logado aparece o undefined para o username e eu não estou conseguindo utilizar essa logica nisso.
Comment: O mesmo nome que você der para o name no input do html, você recupera no post $_POST["name do input aqui"], aí depois, faz o lance do isset para saber se existe, ou !isset para saber se NÃO existe.
Comment: tem como vc mandar o codigo? Eu não entendi mt bem kk.
Comment: To montando algo aqui, mas fica atento pois você não tem username no codigo mostrado aqui, e sim email e é ele que tu recupera lá no php. vai testando aí enquanto eu faço.
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/83741/discussion-between-luis-alberto-batista-and-gabriel-costa).

Notice: Undefined index:


Kleene closure over a formal language

Question: Given a formal language L, is $L \subset L^*$ or is $L \subseteq L^*$?
To give context, I am tasked with proving whether or not there exists a language such that $(L^*)^c = (L^c)^*$. Assuming the logic behind my proof is correct, I've concluded that if $L \neq L^*$ then $(L^*)^c$ cannot equal $(L^c)^*$. I won't go into my proof as it's the not primary subject of my question (that is, unless someone is interested enough to check my work).
Thanks for any assistance!
Comment: Does $\neg L$ stand for the complement of a language? I have seen $\bar L$, $L'$ and $L^c$ to denote complements, not $\neg L$. [I prefer the notation $L^c$ to the other two.]
Comment: Yes, it stands for the complement. I will edit the post to use a more familiar notation.
Answer: Both are possible. For example, we have $\{a\}\subsetneq \{a\}^*$, but $\{a^n\mid n\ge 0\}=\{a^n\mid n\ge 0\}^*$.
For your "contextual" question, consider $L=\varnothing$...
Comment: Thanks! I had been considering when L is the null set, but I wasn't sure whether the null set was a valid language.
Comment: Why shouldn't it?

Kleene closure over a formal language


Burn bootable OpenBSD ISO imagine with Mac OS X (10.6)

Question: I'm trying to make a bootable OpenBSD CD image on Mac OS X Snow Leopard (10.6). Unfortunately, the expected route to success, download + burn with Mac OS X, does not result what seems to be a bootable CD.
I suspect the problem lies with the burning process with Mac OS X. I am downloading the images (install47.iso, cd47.iso and cdemu47.iso), and trying to burn them with Disk Utility, which I presume is the same as the Finder "Burn" command when you right-click on an ISO image. I've tried both methods of burning the ISO.
I've also tried creating .DMG files from the .ISO files in a few ways (e.g. copying the files, creating a read-only image from the contents of the ISO, etc.), and then burning those. As none of those attempts have proven successful, I won't repeat the details here.
That being said, I'm not certain the problem is with the burning process. The target machine is the only machine that I can test the boot-ability of the burnt CD is a Compaq Presario 5320CA (circa 2001). The BIOS from this machine certainly indicates that it can boot from CD, but it consistently displays the messages "Non-system disk or disk error.". I've tried burning several CD's, however, which I'd expect to eliminate error.
The target machine seems to be able to read the image fine once it boots into the currently installed operating system (i.e. Windows XP). The disc certainly seems readable.
I'd be very much obliged for any suggestions on how to burn a bootable OpenBSD 4.7 image from Mac OS X -- or feedback and suggestions on what may be the problem.
Incidentally, I don't have Roxio Toast, and I would prefer solutions that do not involve buying it or other commercial packages. I'm investigating using cdrecord now, and if that proves successful I'll post results here.
Thank you.
Brian
Comment: You seem to be doing everything correctly.  This may sound silly, but are you using the x86 versions of the OpenBSD .iso's.  There are also macppc ones that won't do much of anything if you try to boot them on a PC.
Comment: When you put the CD in to a drive after burning it, what shows up when you open the drive? A big file called .iso? Or a series of files? If it's a series of files, it sounds like you might be burning a usable disk, but the computer isn't able to boot from it (maybe what Gabe mentioned)
Comment: @gabe: Yep, using the i386 .isos, but good question! @Bart Silverstrim: The files showing up are those in the ISO that one would expect (i.e. TRANS.TBL, 4.7, 4.7/i386, etc). Everything in the ISO is being written to the disc. Incidentally, however, the 'information' tab says "Bootable: No". I wonder if/how the El Torito extensions are handled by Mac OS X is an issue.
Comment: This sounds awfully familiar... I seem to recall having a similar issue once upon a time, trying to do the exact same thing, unfortunately, I can't remember what I did to make it work.
Comment: @gabe Aye. If I didn't need to install OpenBSD for every 6 years or so I'd be way more up to speed. ;) I may install Ubuntu (which has a liveCD that boots fine) and install OpenBSD from bsd.rd:--ramdisk.
Comment: I ended up doing as I thought I might; installed Ubuntu from LiveCD, added `bsd.rd` to Grub, rebooted into bsd.rd to install. Painful, but it works.
Answer: You could also try using 'dd'... should work, though I'm not super familiar with using it on the mac.
Answer: What happens when you try: Launch DiskUtility, Images menu, select your .iso, click Burn
That's how I've burned my BSD .iso's in the past
Comment: Aye, that's what I tried. Works fine with e.g. Ubuntu 10.04 Live CD; OpenBSD 4.7 CD doesn't boot.


The database connection is not serializable

Question: I'm getting this error. The database connection is not serializable. This probably means you are serializing an object that has an indirect reference to the database connection
I'm using Lightning 2.1.6.
I set up a media upload field on my page content type using reference to content/ reference media. It also uses the media browser to upload images. This field allows a single image upload. I get the error when you try to upload an image. And the image doesn't get added. If i allow multiple upload instead of single the error goes away. Also If I disable the "Interface Translation" module the error goes away and the images can be uploaded.
Comment: Sounds like you ran into the core bug "StringTranslationTrait consumers cannot be reliably serialized without DependencySerializationTrait". Try using the patch from comment #21 here: https://www.drupal.org/node/2893029
Comment: What is the question? : D
This sounds more like a contrib module bug. Post it on Lightning distribution issue page.
Comment: I found that if i uninstall the Interface Translation module the error goes away.
Comment: Okey, go and post it here:

https://www.drupal.org/project/issues/lightning?categories=1
Comment: Thank you! I posted under normal Drupal issues. Because the translation modules are part of Drupal core not Lightning. https://www.drupal.org/node/2905618
Comment: Thank you too! Taking the effort pointing out bugs is always a help!: )
Answer: I experienced this issue after manually deleting some translated configuration files. From then on I was not able to successfully config import anymore without being interrupted with the fatal error from your question.
I then tried to run config import after uninstalling locale, which worked but have also deleted lots of translation from the database. Bad.
I could restore the configs in question and then remove them from the UI before exporting them again. Boring.
So I deleted the original configuration objects from an update function (and thereby also deleted the translations), and afterwards run configuration import again, where the original configs then got restored automatically (as their files still existed) WITHOUT translation.
/**
 * Remove unwanted translations.
 */
function MYMODULE_update_8005(&$sandbox) {

  $configs = [
    'image.style.crop_thumbnail',
    'views.view.user_admin_people',
  ];

  foreach ($configs as $config) {
    Drupal::configFactory()->getEditable($config)->delete();
  }
}

EDIT: Only shortly after I had the same problem again. Again it was a missing config (I deleted manually, don't do that) and took me hours to find out which one exactly. This time it was menu_item_extras which required menu_item_extras.utility.yml. Actually I uninstalled menu_item_extras but maybe menu_item_extras can't be uninstalled that simply. But that's a different issue.
What's left to conclude now is: Did you manually delete some config files prior to getting this error?


Is it true that $p\mid [\mathbb Q(\cos{\frac{\pi}{p^2}}):\mathbb Q]$?

Question: Is it true that $$p\mid [\mathbb Q(\cos{\frac{\pi}{p^2}}):\mathbb Q],\forall p\in \mathbb P,$$ where $[K:\mathbb Q]$ is the degree of a field extension ?
Comment: For $p$ odd the minimal polynomial of $\cos\frac{\pi}{p^2}$ should have degree $\varphi(p^2)/2=p\frac{p-1}{2}$, so sure. (I use the same reasoning in the answer I have over on [this question](http://math.stackexchange.com/q/460930/11763).)
Comment: @anon I wonder how to prove it?
Comment: Yes $2\cos(2\pi/m)$ generates the real subfield of the $m$th cyclotomic field. The latter has degree $\phi(m)$, so the real subfield is an extension of degree $\phi(m)/2$. In thepresent case $m=2p^2$, as in anon's answer.
Answer: This is a slight variant of anon's answer, together with additional information about the minimal polynomial over ${\bf Q}$.  We want to compute $[{\bf Q}(\beta):{\bf Q}]$ where $\beta=\cos(\frac{\pi}{m})$, with $m$ a positive integer.  The moral of Galois theory is that

when studying questions about field extensions, it is often helpful to translate them into questions about groups.

To achieve such a translation, we need to fit the extension ${\bf Q}(\beta)/{\bf Q}$ inside a Galois extension.  We do this by writing $\zeta:=\cos(\frac{\pi}m) + i\sin(\frac{\pi}m)$, and noting that $\zeta^{-1}=\cos(\frac{\pi}m) - i\sin(\frac{\pi}m)$, so that $\zeta+\zeta^{-1}=2\beta$.  This shows that ${\bf Q}(\beta)$ is a subfield of ${\bf Q}(\zeta)$; in fact, it shows that $[{\bf Q}(\zeta):{\bf Q}(\beta)]\le 2$, since $\zeta$ is a root of the degree-$2$ polynomial $X^2+1-2\beta X$ whose coefficients are in ${\bf Q}(\beta)$.  Now, the advantage of introducing $\zeta$ is that we know from Galois theory that the extension ${\bf Q}(\zeta)/{\bf Q}$ is Galois.  Writing $G$ for its Galois group, there is an isomorphism
$$ \rho:({\bf Z}/2m{\bf Z})^\times\rightarrow G$$
defined by
$$ \rho(k):\zeta\mapsto \zeta^k.$$
Since ${\bf Q}(\beta)$ is an intermediate field between ${\bf Q}$ and ${\bf Q}(\zeta)$, and ${\bf Q}(\zeta)/{\bf Q}$ is Galois, it follows that ${\bf Q}(\zeta)/{\bf Q}(\beta)$ is Galois as well, say with Galois group $H$.  Moreover, $[{\bf Q}(\zeta):{\bf Q}(\beta)]=\#H$, so we already know that $\#H\le 2$.  But we can see that $\#H\ge 2$ as well, since $\rho(-1)$ interchanges $\zeta$ and $\zeta^{-1}$, so $\rho(-1)$ fixes $\zeta+\zeta^{-1}=2\beta$.  Thus $2\le \#H\le 2$, so $\#H=2$.  Finally, since
$$[{\bf Q}(\zeta):{\bf Q}] = [{\bf Q}(\zeta):{\bf Q}(\beta)]\cdot [{\bf Q}(\beta):{\bf Q}],$$
we find that
$$[{\bf Q}(\beta):{\bf Q}] = \frac{[{\bf Q}(\zeta):{\bf Q}]}{[{\bf Q}(\zeta):{\bf Q}(\beta)]} = \frac{\#G}{\#H} = \frac{\#({\bf Z}/2m{\bf Z})}{2} = \frac{\varphi(2m)}2.$$
Finally, the question asked about the case that $m=p^2$ where $p$ is prime.  If $p$ is odd then $\varphi(2m)=p^2-p$, so that indeed $[{\bf Q}(\beta):{\bf Q}]=p\frac{p-1}2$ is divisible by $p$.  If $p=2$ then $\varphi(2m)=2$, so $[{\bf Q}(\beta):{\bf Q}]=1$ (which can also be seen directly, since $\beta=\cos(\frac{\pi}2)=0$ is clearly a rational number).
We can go further and obtain information about the minimal polynomial of $\beta$ over ${\bf Q}$.  I do this in part to explain the empirical observation made in the comments to this other question, according to which the minimal polynomial is related to a Chebyshev polynomial.  By Galois theory, we know that the roots of the minimal polynomial of $\beta$ over ${\bf Q}$ are the elements $\sigma(\beta)$, where $\sigma$ ranges over a set of representatives for the left cosets of $H$ in $G$.  Since $H$ is generated by $\rho(-1)$, this means $\sigma$ ranges over the set $\rho(S)$ where $S$ is a subset of $({\bf Z}/2m{\bf Z})^\times$ which contains precisely one element of $\{k,-k\}$ for every $k\in ({\bf Z}/2m{\bf Z})^\times$.  One such $S$ is the set of elements of $({\bf Z}/2m{\bf Z})^\times$ corresponding to integers between $1$ and $m$ which are coprime to $2m$.  Thus, the roots of the minimal polynomial of $\beta$ over ${\bf Q}$ (which are the same thing as the conjugates of $\beta$ over ${\bf Q}$) are precisely the elements $(\rho(k))(\beta)$, where $1\le k\le m$ and $\gcd(k,2m)=1$.  Since $\rho(k)$ maps $\zeta\mapsto \zeta^k$, it also maps $\zeta+\zeta^{-1}\mapsto \zeta^k+\zeta^{-k}$.  Since $\beta=\frac12(\zeta+\zeta^{-1})$, it follows that $\rho(k)$ maps $\beta$ to $\frac12(\zeta^k+\zeta^{-k})$, which equals $\cos \frac{\pi k}m$.  Thus, the minimal polynomial of $\beta$ is
$$ \prod_{\substack{1\le k\le m \\ \gcd(k,2m)=1}} (X-\cos\frac{\pi k}m).$$
To write this polynomial in a simpler way, recall the Chebyshev polynomial (of the first kind) $T_n(X)$, which is defined by the functional equation
$$ T_n(\cos\theta)=\cos(n\theta).$$
Here $T_n(X)$ is a degree-$n$ polynomial with integer coefficients.
The functional equation implies that
$$ T_m(\cos\frac{\pi k}m) = \cos(\pi k),$$
which equals $-1$ when $k$ is odd.  Thus, $T_m(X)$ is a degree-$m$ polynomial with integer coefficients whose roots include all the numbers $\cos(\frac{\pi k}m)$ where $1\le k\le m$ and $k$ is odd.  In particular, $T_m(\beta)=-1$, so $T_m(X)+1$ is a multiple of the minimal polynomial of $\beta$ over ${\bf Q}$.  We already computed the degree of this minimal polynomial, namely $\varphi(2m)/2$.  So we need to identify a factor of $T_m(X)+1$ having this degree (and having $\beta$ as a root).  First note that $T_m(X)+1$ has repeated roots whenever $m>1$.  To see this, note that the functional equation defining $T_m(X)$ implies that
$$
T_m\left(\frac{Y+Y^{-1}}2\right) = \frac{Y^m+Y^{-m}}2
$$
is true whenever $Y$ is a complex number of absolute value $1$.  But both sides of this equation are rational functions in $Y$, so their difference is a rational function in $Y$ which vanishes for infinitely many values of $Y$.  Hence the numerator of this difference is a polynomial in $Y$ which has infinitely many roots, so this numerator must be zero, whence the displayed equation is an equality of rational functions.  In order to factor $T_m(X)+1$, write $X=(Y+Y^{-1})/2$ so that
$$
T_m(X)+1 = T_m\left(\frac{Y+Y^{-1}}2\right) +1= \frac{Y^m+Y^{-m}}2+1 = \frac12(Y^{m/2}+Y^{-m/2})^2.
$$
If $m$ is even then we compute
$$
T_m(X)+1 = 2\left(\frac{Y^{m/2}+Y^{-m/2}}2\right)^2 = 2\left(T_{m/2}\left(\frac{Y+Y^{-1}}2\right)\right)^2
= 2(T_{m/2}(X))^2,
$$
so that the minimal polynomial of $\beta$ over ${\bf Q}$ divides $T_{m/2}(X)$.
If $m$ is odd then we have to work harder to obtain this sort of conclusion, since $Y^{m/2}+Y^{-m/2}$ is not a function of $X$.  In this case, write
$$ T_m(X)+1 = \frac12(Y^{1/2}+Y^{-1/2})^2\cdot\left(\frac{Y^{m/2}+Y^{-m/2}}{Y^{1/2}+Y^{-1/2}}\right)^2.$$
The first factor is nice:
$$\frac12(Y^{1/2}+Y^{-1/2})^2 = \frac12(Y+2+Y^{-1}) = X+1.$$
To make the second factor nicer, multiply numerator and denominator by $Y^{1/2}-Y^{-1/2}$ to get
$$\frac{Y^{m/2}+Y^{-m/2}}{Y^{1/2}+Y^{-1/2}} = \frac{Y^{(m+1)/2}-Y^{(m-1)/2}+Y^{(1-m)/2}-Y^{(-1-m)/2}}{Y-Y^{-1}}.$$
Now recall that the Chebyshev polynomial of the second kind, $U_n(X)$, is a degree-$n$ polynomial with integer coefficients which satisfies
$$ U_n(\cos\theta) = \frac{\sin((n+1)\theta)}{\sin\theta}.$$
As above, this equation implies that
$$ U_n\left(\frac{Y+Y^{-1}}2\right) = \frac{Y^{n+1}-Y^{-n-1}}{Y-Y^{-1}}.$$
Thus, when $m$ is odd and $X=(Y+Y^{-1})/2$, we have
$$T_m(X)+1 = (X+1)\cdot \left(U_{(m-1)/2}(X) - U_{(m-3)/2}(X)\right)^2.$$
Since $\beta\ne -1$ when $m>1$, it follows that if $m$ odd and $m>1$ then the minimal polynomial of $\beta$ over ${\bf Q}$ divides $U_{(m-1)/2}(X)-U_{(m-3)/2}(X)$.  Finally, if $m$ is an odd prime then the minimal polynomial of $\beta$ has degree $\varphi(2m)/2=(m-1)/2$, so it must be a constant times $U_{(m-1)/2}(X)-U_{(m-3)/2}(X)$.  Analogous expressions for other values of $m$ are more complicated.
In the
earlier question, it was observed empirically that, if $\zeta$ is a primitive $13$-th root of unity, then the minimal polynomial of $\zeta+\zeta^{-1}$ over ${\bf Q}$ is a polynomial $f(X)$ which satisfies
$$T_{13}\left(\frac{X}2\right)-1=\frac{X-2}2\cdot f(X)^2.$$
The above argument explains this observation, and shows how it generalizes to other roots of unity.  For, if we write $\alpha:=\zeta+\zeta^{-1}$ where $\zeta$ is a primitive $m$-th root of unity, then
$$ T_m\left(\frac{\alpha}2\right) = \frac{\zeta^m+\zeta^{-m}}2 = 1.$$
Thus $\alpha$ is a root of $T_m(X/2)-1$, so the minimal polynomial of $\alpha$ over ${\bf Q}$ is a factor of $T_m(X/2)-1$.  Now write $X=Z+Z^{-1}$, so that
$$ T_m\left(\frac{X}2\right)-1 = \frac{Z^m+Z^{-m}}2-1 = \frac12(Z^{m/2}-Z^{-m/2})^2.$$
If $m=2n$ is even then $\alpha=\cos(\pi k/n)$ for some integer $k$ which is coprime to $2n$, and we analyzed this case in the previous paragraph.
If $m$ is odd then
$$ \frac{Z^{m/2}-Z^{-m/2}}{Z^{1/2}-Z^{-1/2}} = \frac{(Z^{m/2}-Z^{-m/2})(Z^{1/2}+Z^{-1/2})}{(Z^{1/2}-Z^{-1/2})(Z^{1/2}+Z^{-1/2})} =
\frac{Z^{(m+1)/2}+Z^{(m-1)/2}-Z^{(1-m)/2}-Z^{-1-m)/2}}{Z-Z^{-1}} = U_{(m-1)/2}\left(\frac{X}2\right) + U_{(m-3)/2}\left(\frac{X}2\right),$$
so that
$$T_m\left(\frac{X}2\right)-1 = \frac12(Z^{1/2}-Z^{-1/2})^2\cdot\left(U_{(m-1)/2}\left(\frac{X}2\right) + U_{(m-3)/2}\left(\frac{X}2\right)\right)^2 =
\frac12(X-2)\cdot\left(U_{(m-1)/2}\left(\frac{X}2\right) + U_{(m-3)/2}\left(\frac{X}2\right)\right)^2.$$
If $m>1$ then $\alpha\ne 2$, so if $m$ is odd and $m>1$ then the minimal polynomial of $\alpha$ over ${\bf Q}$ divides
$$U_{(m-1)/2}\left(\frac{X}2\right) + U_{(m-3)/2}\left(\frac{X}2\right).$$
Finally, if $m$ is an odd prime then the first paragraph of this answer shows that the minimal polynomial of $\alpha$ over
${\bf Q}$ has degree $\varphi(m)/2=(m-1)/2$, which equals the degree of the polynomial displayed above, so the minimal polynomial is a constant times the displayed polynomial.  One can easily check that the displayed polynomial is monic, so it equals the minimal polynomial of $\alpha$ over ${\bf Q}$.  Thus the empirically observed factorization for $m=13$ generalizes at once to any odd prime, and is a special case of a more general result valid for all odd $m>1$.
Answer: To quote my previous answer on the Galois machinery behind all of this:

Suppose $\rm L/K$ is Galois with $\rm G=Gal(L/K)$ and $\rm m(x):=minpoly_{\alpha,K}(x)$. Then
$\quad \rm m(\sigma(\alpha))=\sigma(m(\alpha))=\sigma(0)=0$ implies $\rm (x-\sigma\alpha)\mid m$ in $\rm L[x]$ for all $\rm \sigma\in G$,
$\quad \rm(x-\beta)$ all coprime, $\rm \beta\in G\alpha$, implies $\rm f(x):=\prod\limits_{\beta\in G\alpha}(x-\beta)\mid m$ in $\rm L[x]$,
$\quad \rm \sigma f(x)=f(x)$ for all $\sigma\in G$ implies $\rm f(x)\in K[x]$; $\rm f(\alpha)=0$ implies $\rm m(x)\mid f(x)$ in $\rm K[x]$,
$\quad \rm f(x)\mid m(x)$ and $\rm m(x)\mid f(x)$ and both $\rm f,m$ monic implies $\rm f(x)=m(x)$.
Therefore the zeros of $\rm\alpha$'s minimal polynomial over $\rm K$ are precisely its $\rm Gal(L/K)$-conjugates.

Now, $\alpha=2\cos(2\pi\frac{n}{m})=\zeta^n+\zeta^{-n}$ where $\zeta=e^{2\pi i/m}$ is a primitive $m$th root of unity (we assume $n/m$ is reduced). As ${\rm Gal}({\bf Q}(\zeta)/{\bf Q})\cong({\bf Z}/m{\bf Z})^\times=U(m)$, the Galois conjugates of $\alpha$ are $\zeta^\sigma+\zeta^{-\sigma}$ as $[\sigma]$ ranges over $U(m)$. For each $[\sigma]\in U(m)$, $[\sigma]\alpha=[-\sigma]\alpha$ by symmetry. Finally, $\cos$ is injective on the interval $[0,\pi]$ so $\{\cos(2\pi r/m):0\le r\le m/2,[r]\in U(m)\}$ is a complete set of conjugates without any repetitions. As $[K(\alpha):K]=\deg{\rm minpoly}_{\alpha,K}$, we therefore have
$$[{\bf Q}(\cos2\pi\frac{n}{m}):{\bf Q}]=\begin{cases}\varphi(m)/2 & m>2 \\ 1 & m=2 \end{cases} $$
since $m/2\in{\bf N}$ and $(m/2,m)=1$ iff $m=2$. Your case corresponds to $n=1$, $m=2p^2$.
More information: Galois theory and Cyclotomic fields.


Show Hyperlink Field only for Not NULL values

Question: I am pulling out data from certain database and displaying it on a table and the data displayed will be in hyperlink form. But there is one problem where the data shown is including null value.
my code is :
<code>    <asp:TemplateField HeaderText="NCR" ItemStyle-Width="150px" >
     <ItemTemplate>
     <asp:HyperLink ID="HyperLink1" runat="server" Text = '<%#Eval("form")%>' NavigateUrl = '<%# Eval("form","~/sapphire/nca" + Mid(Eval("form"), 4, 1) + ".aspx?form={0}") %>' />
</code>

let`s say i have 5 rows of data fetched (null,hey,yoyo,null,null)
the output should be like in table form under NCR :
<code>     -,*hey*,-,*yoyo*,-,-
</code>
where hey and yoyo are clickable link.
please help ><
Comment: check this link http://forums.asp.net/t/959419.aspx?how+to+handle+null+values+for+Templatefield+hyperlink+etc+
Comment: @sharad i`ve tried the IIF method but it gave me this error"Overload resolution failed because no accessible 'IIf' accepts this number of arguments"
Answer: Try using ternary operator for checking null values
<code><asp:HyperLink ID="HyperLink1" runat="server" Text = '<%#Eval("form")%>' NavigateUrl = '<%# Eval("form")==null? "" : String.Format("{0}{1}{2}","~/sapphire/nca", Mid(Eval("form"), 4, 1),".aspx?form={0}" ) %>' />
</code>


CreateThread function parameter gets passed wrong

Question: When I use the CreateThread function like so
CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)MyModule::MyFunction, (LPVOID)&wsParam, 0, &dwThreadId);

The parameter's address gets passed wrongly, making the wstring (or any other type of parameter) invalid. The address simply doesn't point to the data that was passed.
The function that gets called as a new thread:
std::wstring MyModule::MyFunction(LPVOID stringParam) {
    std::wstring wsParam = *reinterpret_cast<std::wstring*>(stringParam); //Bad alloc
}

Comment: Never cast the function pointer argument! Either it fits and works without a cast, or you're hiding a **serious** error.
Comment: a c-style cast says "I dont care about any potential issues" very explicitly ;). Use a `static_cast` if you want to make some conversion into an explicit cast. If the `static_cast` does not work, then very likely the c-style cast was wrong too
Comment: Please provide a [mcve]. With the given info, the problem could be outside of the code shown as well.
Comment: Why are you even using windows API when C++ has [`std::thread`](https://en.cppreference.com/w/cpp/thread/thread) (since C++11 !!) and lambda expressions for explicit modeling of what data you want to capture (and how : value or reference). Anything you can do without using the windows API do it without using the windows API
Comment: The callee's std::wstring return value requires space on the stack, reserved by the caller.  But that's not what CreateThread() knows, it assumes a function that returns a DWORD.  A value that doesn't require stack space.  Inevitably the callee's stack frame is off with parameter values at wrong addresses.  Do question the usefulness of returning an std::wstring, assuming it were possible, the caller would have to wait for the  thread to complete to obtain the result.  Making it pointless to use a thread, it might as well call the function directly.
Comment: Almost certainly the `wsParam` variable is being destructed before the thread procedure can read it.
Comment: It worked without casting it too, I just thought being explicit is a good practice
Comment: Explicit casting is bad practice, it tells the compiler to shut up. If you need a cast then use it, but if you think you don't then don't, and let the compiler tell you if you are right or wrong.
Comment: The problem is not outside of the code shown, I posted this question with the answer your question checkbox ticked.
Comment: Stackoverflow elitism nicely done. I've had trouble with using CreateThread which I am using because I have to for undiscussed reasons, but I get asked why I don't use X or Y instead? I've had my reason for it that's why I asked a question about CreateThread and not std::thread. Also this question was asked after I found the answer so I can share it with others having the same problem, but feel free to close the question, or even remove it please
Comment: https://stackoverflow.com/help/self-answer "To encourage people to do this, there is a checkbox at the bottom of the page every time you ask a question. If you have more than 15 reputation and already know the answer, click the checkbox that says "Answer your own question" at the bottom of the Ask Question page. Type in your answer, then submit both question and answer together."

Nicely encouraged
Comment: @66Gramms sorry, this is not elitism. Your question is pretty unclear and so is your answer, that's all. And if they ask "why don't you use xyz", it's just suggestions, it might be relevant or not, nobody but you can know, take it or leave it. BTW the DVs are not mine.
Answer: Even though it doesn't seem to be documented in the Windows API (or at least I didn't find it) the function being called for the new thread must return a DWORD.
Changing the called function's header to return a DWORD passes the parameter correctly.
DWORD MyModule::MyFunction(LPVOID stringParam) {
    std::wstring wsParam = *reinterpret_cast<std::wstring*>(stringParam); //Works now
}

Comment: Using `std::thread` will help avoid these sort of problems
Comment: Its documented very clearly. From the documentation of [`CreateThread`](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createthread) https://learn.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms686736(v=vs.85): _lpStartAddress :
A pointer to the application-defined function to be executed by the thread. This pointer represents the starting address of the thread. For more information on the thread function, see [`ThreadProc`](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms686736(v=vs.85))_.
Comment: I was checking the documentation for the CreateThread function which didn't say anything on the matter. Thanks for the link! https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createthread
Comment: Everything is in the dcocumentation. Read the documentation of  `CreateThread` closely, especially the description of the _lpStartAddress_ parameter.
Comment: Oh yeah I see now, my bad. It was a good learning experience, I'll be much more thorough with reading it in the future. Still I hope this post will help someone else in the future, encountering the same issue
Comment: BTW: With `void` instead of `DWORD`, the call to `CreateThread()` would not have compiled unless you put in an explicit cast, I'm sure. The cast is just a "shut up, compiler, I know what I'm doing", which was unfortunately not the case.
Comment: @66Gramms `MyFunction` doesn't do anything useful. and it's even wrong because it doesn't return anything. What's the deal?
Comment: std::thread is not related to the question. MyFunction is obviously not the function I use in the actual code, but it's the part that's relevant


Sharing variables using event object in html/jscript

Question: I have two functions as follows. Is there a way to access the variable "result" in the top function using "e" when I am not allowed to modify the bottom function? Here, the 'add' event is auto triggered by the button click.
elem.addEventListener('add',function (e) {
    // need to do something with the variable "result"
},true);

$(#myButton).click(function(evt) {
       var result = myFunction();
       if (result != null) {
       doSomething();
    }
});

Comment: declare result before `elem.addEventListener`
Answer: Frist of is this javascript or jQuery? lol just javascript do this:
Please note the javascript event listener is looking for an add event and not a click.
elem.addEventListener('click',function(e) {
    var result=myFunction();
    if(result!==NULL)doSomething();
},true);

using a jQuery library:
$('#myButton').click(function() {
       var result=myFunction();
       if(result!==NULL)doSomething();
});

Passing variables using parameters:
var variable=2;//send an int
myFunction(variable);
myFunction('send a string');
variable===true;//send a boolean
myFunction(variable);

myFunction(passedOver){
    console.log(passedOver);
}


Find unknown factor in series so it converges to a given value

Question: I'm trying to find $F(z)$ such that:
$$\lim_{N \to\infty} \sum_{n=1}^N F\left(\exp\bigg(\frac{2 \pi i n}{N}\bigg)\right) \cdot \log\left|\exp\bigg(\frac{2 \pi i n}{N}\bigg) - \exp(i \theta)\right| = \\\log|a \exp(i \phi) - \exp(i \theta)| $$
where $a \in (0, 1)$ is fixed.
I thought I could express this as an integral:
$$\begin{matrix}\displaystyle
\int_0^{2\pi} F\big(\exp(it)\big) \log|\exp(it) - \exp(i \theta)| dt &= \log|a \exp(i \phi) - \exp(i \theta)| \\
\displaystyle\oint F(z) \log|z - \exp(i \theta)| \frac{dz}{iz} &= \log|a \exp(i \phi) - \exp(i \theta)| \\
\end{matrix}$$
in which case
$$F(z) = \frac{1}{2 \pi} \frac{z}{(z - a \exp(i \phi))}$$
However when I plug in this $F(z)$ and do some example partial sums I get values which are not close to the expected values and are not even off by a constant factor, which makes me think I've screwed something up.
Comment: There is no $\phi$ on the left of the first display and it appear on the right.  Is $\phi$ a parameter to $F$ that has been suppressed on the left?  (Your last display has $F$ depending on $\phi$ without making that explicit in "$F(z)$".)
Comment: Yeah you can think of it as $F(z, \phi)$ if that helps.  I didn't mark it as a parameter because it doesn't vary over the sum.
Comment: @JayLemmon I think you screwed up in the question. The sum should be multiplied by $\frac{1}{N}$ so that it is the integral you claimed it is.
Comment: @mathworker21 I don't know for sure it's the integral I claimed it was; that may be where I made the mistake.  The sum itself is ultimately "correct", in that it's what I'm trying to find, and since my integral expression didn't actually give me the desired result it's entirely possible it's incorrect.
Answer: The solution concerns for the case when the sum is equal to zero.
$\lim\limits_{N \to\infty} \sum\limits_{n=1}^N F\left(e^{\frac{2 \pi i n}{N}}\right) \cdot \ln\left|e^{\frac{2 \pi i n}{N}} - e^{i \theta}\right| = \ln|a e^{i \phi} - e^{i \theta}|$
Let's transform the $\ln$ part of LHS:
$\ln\left|e^{\frac{2 \pi i n}{N}} - e^{i \theta}\right|=\overbrace{\ln|e^{\frac{\pi i n}{N}-\frac{i\theta}{2}}|}^0+\ln|\overbrace{e^{\frac{\pi i n}{N}-\frac{i\theta}{2}}-e^{-\frac{\pi i n}{N}+\frac{i\theta}{2}}}^{2i\sin(\frac{\pi n}{N}-\frac{\theta}{2})} |$
Let  $F=\frac{1}{N}F^*$ we have the following Riemann sum:
$\lim\limits_{N \to\infty} \frac{1}{N}\sum\limits_{n=1}^N F^*\left(e^{\frac{2 \pi i n}{N}}\right)\ln|{2\sin(\frac{\pi n}{N}-\frac{\theta}{2})}|=\int\limits_0^1F^*\left(e^{2 \pi i x}\right)\ln|{2\sin(\pi x-\frac{\theta}{2})}|dx$
Using that $\int f'(x) f(x)dx=\frac{1}{2}f^2(x)+c$
$f(x)=\ln|{2\sin(\pi x-\frac{\theta}{2})}|$
$f'(x)=F^*(e^{2 \pi i x})=\pi |\cot(\pi x-\frac{\theta}{2})|$
We get:
$\int\limits_0^1\pi |\cot(\pi x-\frac{\theta}{2})|\ln|{2\sin(\pi x-\frac{\theta}{2})}|=\frac{1}{2}\ln^2|{2\sin(\pi x-\frac{\theta}{2})}|\Big|_0^1=0$
So  $\ln|a e^{i \phi} - e^{i \theta}|$ must be equal to $0$.
$a(a-2\cos(\theta-\phi))=0$
As $a \in (0, 1)\rightarrow$ $a=2\cos(\theta-\phi)$
Finally $\theta=\cos^{-1}(\frac{a}{2})+\phi$
Comment: Thanks, looks like the sum is divergent unless $F(z) = 0$, which I wasn't expecting.
Comment: Thank you for the question and the points.


formulario de contato com Laravel 5.1

Question: preciso criar um formulário de contato simples com laravel 5.1, no entanto, como sou mais de front-end, gostaria de alguma ideia do que posso fazer para criar esse formulário, alguns sites até explicam como se faz, mas não é com a versão atual do laravel, alguns pacotes do packagist geram um formulário mas também não explicam com clareza como usá-los.
alguém pode me dar uma luz?
Comment: É uma questão bastante ampla. Você precisa nos dizer se ao menos você já o tem instalado e se está rodando.
Comment: O Formulário é um HTML basicamente, nada mais, nada menos.
Comment: A partir do laravel 5 o Form foi removido por padrão do framework você pode usar html normalmente, ou instalar segue o link explicando melhor [Forms & HTML](http://laravelcollective.com/docs/5.0/html). :)
Answer: Para conseguir isto e muito simples
Layout:
{{ Form:: open(array('action' => 'ContactController@getContactUsForm')) }}

@foreach($errors->all('
:message
') as $message)

@endforeach

{{ Form:: textarea ('message', '', array('placeholder' => 'Message', 'class' => 'form-control', 'id' => 'message', 'rows' => '4' )) }}

{{ Form::submit('Submit', array('class' => 'btn btn-primary')) }}
{{ Form:: close() }}

Addicionar a seguinte route
Route::post('contact_request','ContactController@getContactUsForm

E o seguinte controller
public function getContactUsForm(){

        //Get all the data and store it inside Store Variable
        $data = Input::all();

        //Validation rules
        $rules = array (
            //'first_name' => 'required', uncomment if you want to grab this field
            //'email' => 'required|email',  uncomment if you want to grab this field
            'message' => 'required|min:5'
        );

        //Validate data
        $validator = Validator::make ($data, $rules);

        //If everything is correct than run passes.
        if ($validator -> passes()){

           Mail::send('emails.feedback', $data, function($message) use ($data)
            {
                //$message->from($data['email'] , $data['first_name']); uncomment if using first name and email fields
                $message->from('email@example.com', 'feedback contact form');
    //email 'To' field: cahnge this to emails that you want to be notified.
    $message->to('firstname.lastname@example.com', 'John')->cc('email@example.com')->subject('feedback form submit');

            });
            // Redirect to page
   return Redirect::route('home')
    ->with('message', 'Your message has been sent. Thank You!');

            //return View::make('contact');
         }else{
   //return contact form with errors
            return Redirect::route('home')
             ->with('error', 'Feedback must contain more than 5 characters. Try Again.');

         }
     }
}

https://laracasts.com/discuss/channels/general-discussion/creating-a-contactfeedback-form-with-laravel?page=1
Comment: Além de erros de sintaxe (espaços após ` Form::`), seu código não irá funcionar na versão 5.1.

formulario de contato com Laravel 5.1