How many different options do you have for selecting 8 of these balls?

Question: You have 6 red balls, 3 of which are identical & the other 3 are distinct & different from the previous 3, 4 distinct orange balls, 6 identical purple balls. You want to select 8 balls. How many different options do you have?
I tried using the combinations formula (i.e. 16!/8!(8!)) but I know this is wrong because of the identical balls, which would reduce the total number of options. I can't find any worked textbook examples accounting for identical objects in combinations. I'm guessing there will be a subtraction involved.
Comment: Have you made any progress on this problem? What has been your attempt so far?
Comment: @CraveableBanana I tried using the combinations formula (i.e. 16!/8!(8!)) but I know this is wrong because of the identical balls, which would reduce the total number of options. I can't find any worked textbook examples accounting for identical objects in combinations. I'm guessing there will be a subtraction involved.
Comment: In future, please include your attempt in the question rather than the comments, where they might be missed.
Answer: You are right that we have to consider the identical balls. There are $3$ identical red balls and $6$ identical purple balls which really confuse the problem. Besides these $9$ tricky balls, though, we can consider the other $16 - 9 = 7$ balls to be completely distinct, as even the distinct balls of the same color can be told apart.
One approach is to just sum over all the cases. This may not be the neat closed form you might expect, but it works. Let $r$ be the number of the identical red balls chosen, and $p$ be the number of identical purple balls chosen. Then the total number of options is
$$ \sum_{r = 0}^3 \sum_{p = 0}^{\min(6, 8 - r)} {7 \choose 8 - r - p}. $$
For any fixed $r$ and $p$, the problem reduces to choosing the remaining $8 - r - p$ from the $7$ distinct balls, hence the standard combinations formula. The $\min(6, 8 - r)$ is because we cannot exceed $8$ balls with the number of red and purple we choose.


Clarification on Schoenberg's "pivot tones" in minor from Theory of Harmony

Question: While going through chapter 5 I have multiple times had to amend my understanding of the four instructions Schoenberg gives on the usage of the sixth and seventh degrees of the minor scale. My understanding of which, in brief, was at first: (in A minor) G must go to F, which must go to E. F# must go to G#, which must go to A.
At first it confused me for two reasons:

He never uses the unraised VII chord or even comments on it
He shows several unraised VI chords which leap out of it instead of going to the fifth degree like the pivot tone directions suggest.

My initial understanding was that the directions on pivot tones must be followed absolutely in all voices, and this was why VII never appeared (going to VI is prohibited at this point because of the lack of common tones.) But his treatment of VI contradicted that, which if my understanding was correct would have the same problem as VII and therefore be unusable until inversions were "unlocked."
I also realized sometimes he delays the descent or ascent after the pivot tone by sustaining the note, which I didn't realize was allowed at first. But that didn't fix the problem of the bass leaping out of VI.
So then I made a new assumption: maybe it's okay for the bass to leap if the same voice is doubled in the rest of the chord, and that voice follows the pivot rules? This theory seemed to hold up for most of the chapter. I couldn't find any cases where he broke this version of the rule without pointing out that he was breaking it.
But then when I got to the section on seventh chords in minor, that theory seems to fall apart as well. In the very first progression on this line the sixth degree goes directly to the fourth degree. In the third bar the seventh degree goes directly to the fifth:

(As a side note, I also don't understand why he marks the II-VII progression above as unusable. It seems like he can just sustain all the notes outside of the bass.)
It also occurs in the phrase examples for sevenths, in multiple places. For example, on the second line the G in III goes to A:

And the F in VI6 from the second line here leaps to C:

Unlike the previous phrase examples where me points out such choices as mistakes, he doesn't comment on these. I'm not sure how much this matters, assuming the restrictions will be lifted, but if I am going to go through this book I would like to do it properly without going halfway.
Am I still missing something in the meaning of these four points? Is it a coincidence that he didn't use the unraised VII chord this whole chapter until the section on seventh chords?
Comment: From the same part of the book: [What did Schoenberg mean with this?](https://music.stackexchange.com/q/120482/70803).
Comment: Yeah, it is from the same section, although the question isn't directly related from what I can tell. I think Schoenberg is fairly clear multiple times in the text that raised 6-7th degrees can't connect to unraised 6-7th degrees and vice versa. My question is separate from that.
Comment: @arkwright Not having my copy of the Schoenberg in front of me, is it possible that the stipulations at the beginning of your question are *melodic* tendencies (i.e., in a single voice), and the remaining examples are *harmonic* tendencies. In other words, is it possible the top of the question explains what single voices with these pitches do while the bottom explains what chords with these pitches as roots do?
Answer: From what I remember about the book, it is not directly required that the seventh and sixth non-raised degrees go to their corresponding 'resolution tones'. However, they need to do just that to be neutralized, and neutralizing is a necessary condition for "unlocking" the raised degrees. In the case of the raised degrees, if I remember correctly, as they are considered by Schoenberg as 'alterations' they must be followed by the degree in which they are neutralized, save for held notes.
In other words, the instructions (in A minor), 'G must go to F' and 'F must go to E', mean that they must eventually follow that 'resolution' in order to permit the introduction of the raised degrees. Since the raised seventh degree is necessary to form a dominant and, therefore, cadence ,in minor tonality, that needs to happen eventually, in the context of an exercise. So neutralizing the non-raised degrees, although not a direct requirement, ends up being mandatory due to other rules.
One must note, though, that neutralization is not a sufficient condition for 'unlocking' the correspondent degree, as memory chromaticism must be avoided by introducing the raised (non-raised) degree in a voice other than the one in which the non-raised (raised) degree was neutralized.
The II-VII7 connection in the example is impossible, I think, because the tenor can't go to D (parallel fifths) or B (doubling of the third), which leaves only doubling the G as an option. Although the neutralization does not have to be immediate, I still believe Schoenberg forbids doubling of the sixth and seventh non-raised degrees. I imagine the reason for that is the voice-leading complications that neutralizing first the G in one voice and only then in the other would cause.


Erro ao rodar app mobile react-native

Question: Ao executar react-native run-android dá o seguinte erro:
FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:mergeDebugResources'.

Error: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException:

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED
Total time: 2 mins 21.254 secs
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/getting-started.html
Informações do JDK:

java version "1.8.0_181" Java(TM) SE Runtime Environment
  (build 1.8.0_181-b13) Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)

Informações do react-native:

react-native-cli: 2.0.1
  react-native: 0.55.4

Já tentei rodar no Genymotion, no próprio celular e no Android Studio, mas da o mesmo erro.
API 23 e 28.
Answer: Linux e MacOS
Rode os seguintes comandos no terminal, ou salve-os dentro de um destes arquivos existente no sue sistema: ~/.bash_profile , ~/.profile ou ~/.zshrc
export ANDROID_HOME=~/Android/Sdk
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/platform-tools

Depois execute o seguinte comando:
~/Android/Sdk/tools/bin/sdkmanager  "platform-tools" "platforms;android-27" "build-tools;27.0.3"

Caso tenha dúvidas: https://github.com/Rocketseat/ambiente-react-native/blob/master/unix-android-sdk.md
Windows
Realize os seguintes passos deste tutorial: https://github.com/Rocketseat/ambiente-react-native/blob/master/windows-android-sdk.md
Fonte: https://github.com/Rocketseat/ambiente-react-native
Answer: Caio, uma pergunta, está com a variável de ambiente ANDROID_HOME setada? Se não souber, rode o comando: echo $ANDROID_HOME para mac ou linux.
Caso não tenha definido a variável, defina ela apontando para aonde está o seu SDK Android.
Caso esteja definido a variável, faça o seguinte:
Abra o Genymotion > Settings > ADB > Marque a opção Use custom Android SDK tools > Selecione a pasta que está definido o seu ANDROID_HOME.
Comment: Olá Thiago, não tinha a variável ANDROID_HOME, configurei todas as variáveis e ainda coloquei um caminho para o SDK no Genymotion, porém está dando os mesmo erro.
Comment: @CaioLucasTeixeiraF.O. quando você dá o comando android, ele identifica a variável?

Erro ao rodar app mobile react-native


Fret diagrams for chord backing in Lilypond

Question: I have created the following Lilypond code:
% one octave above middle c
song = {
  \relative c'' {
    \time 4/4
    \tempo 4 = 66
    c c d e
    f1
    f4 f c d
    e1 | \break
    e4 e f e
    d e d2
    c4 d c a
    g1 | \break
    d'2 d4 b
    c1
    e4 f e d
    c1 | \break
    c4 d e f
    g2 e
    f4 e d c
    c1 \bar "|."
  }
}

\score {
  <<
    \chords {
      c d:m f:m c
      a:m d f:m c
      g c d f
      f:m c2 a d:m g c
    }
    \new Staff { \song }
    \new TabStaff { \song }
  >>
}

which produces both the melody in the staves and the backing chords:

I want to add fret diagrams for the backing chords by using
\include "predefined-guitar-fretboards.ly"
but if I use ChordMode, then it seems that the notes in the staves become the chords.
Answer: Here's how I would do it:
\version "2.18.2"

\include "predefined-guitar-fretboards.ly"

% one octave above middle c
song = {
  \relative c'' {
    \time 4/4
    \tempo 4 = 66
    c c d e
    f1
    f4 f c d
    e1 | \break
    e4 e f e
    d e d2
    c4 d c a
    g1 | \break
    d'2 d4 b
    c1
    e4 f e d
    c1 | \break
    c4 d e f
    g2 e
    f4 e d c
    c1 \bar "|."
  }
}

theChords = \chordmode {
  c d:m f:m c
  a:m d f:m c
  g c d f
  f:m c2 a d:m g c
}

\score {
  <<
    \new ChordNames { \theChords }
    \new FretBoards { \theChords }
    \new Staff { \song }
    \new TabStaff { \song }
  >>
}

Comment: Thanks but this is what I tried earlier. The fretboards appear but the melody notes are now interpreted as half notes. Twiddling things to see if I can get this to all work.
Comment: @timbo: The chord names in theChords variable don't have endurance values (e.g c1 d2:m, etc.)  Add these and you should be fine.
Answer: @ksnortum's answer structures the chords in a variable, but curiously:

the melody notes timing changes unexpectedly from quarter notes to half notes
the chords are presumed to be four per measure

Setting the timings explicitly on the first note and first chord produces the desired result:
theChords = \chordmode {
  c1 d:m f:m c
  a:m d f:m c
  g c d f
  f:m c2 a d:m g c
}

% one octave above middle c
song = {
  \relative c'' {
    \time 4/4
    \tempo 4 = 66
    c4 c d e
    f1
    f4 f c d
    e1 | \break
    e4 e f e
    d e d2
    c4 d c aes
    g1 | \break
    d'2 d4 b
    c1
    e4 f e d
    c1 | \break
    c4 d e f
    g2 e
    f4 e d c
    c1 \bar "|."
  }
}

\score {
  <<
    \new ChordNames { \theChords }
    \new FretBoards { \theChords }
    \new Staff { \song }
    \new TabStaff { \song }
  >>
}


How to compute a non linear mix model with links between the parameters and their variance in R?

Question: I'm working on a biological problem where we want to modelize the impact of a treatment and a chemical modification on the measured quantity of a molecule (peptides).
We will note $x_{ijk}$ the measure of this quantity, where $i\in\{1,2\}$ is the treatment, $j\in\{1,2\}$ is the chemical modification and  $k\in[|1,n_k|]$ are the replicates. Let $\Pi = \{ (\alpha_j)_j,(b_{ij})_{ij},(\sigma_i)_i,\sigma\} $ be the set of parameters (both random and fixed) we want to estimate.
I want to compute the following mixed non-linear model :
(M1) : $\forall i,j,k : \left\{ \begin{array}{ll}
 x_{ijk} = \mu + g(\Pi) + \alpha_j + b_{ij} + \theta_{ik} + \epsilon_{ijk}  \\
b_{1j} = 0 ,& \theta_{ij} \sim \mathcal{N}(0,\sigma_i)\\
\alpha_1 = 0, & \epsilon_{ijk} \sim \mathcal{N}(0,\sigma)
\end{array} \right.
$
And $g$ is defined thanks to a biological equation as :
$g : \Pi \rightarrow \left\{ \begin{array}{lcl} e^{0.5\times log^2(2)\times(\sigma_2^2-\sigma_1^2)}\times\frac{1+2^{b_{22}}}{1+2^{b_{21}}} & if & i = 2 \\
0 & if & i = 1
\end{array} \right.$
To make it more understandable : $\alpha_j$ is the common effect of the chemical modification, $b_{ij}$ is the effect of the chemical modification in each treatment, $\theta_{ik}$ is the random effect (due to the replicates) in each treatment and $\epsilon_{ijk}$ is the residual error. The term $g(\Pi)$ can be seen as the effect of the treatment or a constraint between the parameters.
My question is : How can I compute the parameters and the variance in R (basically i want to estimate $\Pi$)?
I tried to use the packages nlme and saemix but they do not seems to provide solutions for non-linear mixed models when, in the model, there are links between the parameters of the model and their variance. Is there a solution in with a bayesian approach?
NB: I am not interested in a solution with an unspecified $g$ function but as i'm not really sure that this constraint is enough to have a unique solution i'll probably have to change a bit the $g$ function so solutions with tricky substitution will not help me a lot.
Others view of the problem (bonus)
I tried to formulate (M1) as a ill posed linear mixed model (ill posed because there is not a unique solution) plus a non linear constraint between my parameters (to reduce the number of solutions) :
Here we change a little bit $\Pi$ and $g$ to $\Pi'$ and $g'$ defined as :
$\Pi'= \{ (c_i)_i,(\alpha_j)_j,(b_{ij})_{ij},(\sigma_i)_i,\sigma\}$, we add a $c_i$ the effect of the treatment.
$g' : \Pi' \rightarrow  c_2 -  e^{0.5\times log^2(2)\times(\sigma_2^2-\sigma_1^2)}\times\frac{1+2^{b_{22}}}{1+2^{b_{21}}} $ is g but view as a constraint between the parameters.
Then we can rewrite (M1) as :
(M2) : $\forall i,j,k : \left\{ \begin{array}{ll}
 x_{ijk} = \mu + c_i + \alpha_j + b_{ij} + \theta_{ik} + \epsilon_{ijk}  \\
b_{1j} = 0 ,& \theta_{ij} \sim \mathcal{N}(0,\sigma_i)\\
\alpha_1 = 0, & \epsilon_{ijk} \sim \mathcal{N}(0,\sigma)\\
c_1=0 & g'(\Pi') = 0
\end{array} \right.
$
The first three lines of (M2) is the linear mixed model and the last line is the constraint.
This problem seems to be a problem of optimization with constraints but with random terms. Is there some package in R to solve those type of problems.
I tried to look at solutions like a lasso model where my penality is $g'$ but I didn't found any R package which allows to do those type of resolution.
Thank a lot, if anyone have an idea or some papers/books I can read it would help me a lot!
Answer: I suspect you'll have to fit the model yourself using a more general purpose optimization package. The power of a non-linear mixed model is that the parameters of the non-linear function can be specified as varying across individuals and groups. This, however, is no the case in your model, since $\theta_{ik}$ is not a part of $g$. Assuming that both errors are iid, then instead you can fit the model $$x_{ijk}= g(z_{ijk},\Pi, \sigma_1, \sigma_2)+\epsilon_i$$ where $\epsilon_i\sim\mathcal{N}(0, \sigma^2+\sigma_i^2)$ and $z_{ijk}$ is a vector of indicator variables (I moved the variance parameters outside of $\Pi$ for notational convenience). As a log-likelihood, we had that $$\log P(X|Z,\Pi) = \frac{1}{2}\sum_{i,j,k}\frac{(x_{ijk}-g(z_{ijk},\Pi, \sigma_1, \sigma_2))^2}{\sigma^2+\sigma_i^2}$$. If, however, you want the $\theta_{ij}$ jointly distributed as $\theta_i\sim\mathcal{N}(0,\Sigma_i)$ and the $e_{ijk}$ as $\epsilon\sim\mathcal{N}(0,\Sigma)$, in vector notation, $$\log P(X|Z,\Pi)=\frac{1}{2}(x-g(Z,\Pi,\text{diag}(C)))^TC^{-1}(x-g(Z,\Pi,\text{diag}(C)))$$ where $C = \Sigma + \Sigma_1\oplus\Sigma_2$, we constrain all matrices to have a constant diagonal, and the $x$ vector is partitioned appropriately. This case is a little harder, but still workable, though requires some tricks from convex optimization to maintain positive definiteness in the covariance matrices.


Clustering of mixed type data with R

Question: I wonder whether it is possible to perform within R a clustering of data having mixed data variables. In other words I have a data set containing both numerical and categorical variables within and I'm finding the best way to cluster them. In SPSS I would use two - step cluster. I wonder whether in R can I find a similar techniques. I was told about poLCA package, but I'm not sure ...
Comment: Isn't [SPSS TwoStep](http://www.spss.ch/upload/1122644952_The%20SPSS%20TwoStep%20Cluster%20Component.pdf) designed for handling large datasets? (I provide a response to a related question [here](http://stats.stackexchange.com/a/10170/930).) Otherwise, would my response to [Can principal component analysis be applied to datasets containing a mix of continuous and categorical variables?](http://stats.stackexchange.com/q/5774/930) be of any help?
Comment: Don't confuse method with implementation. First look for a clustering algorithm that makes sense. _Then_ look for an R package that implements it.
Comment: [Gower similarity](http://stats.stackexchange.com/a/15313/3277) can be used.
Comment: @gung recently closed a very similar question I asked. I was told that my question was off topic because it was predominantly about software. This appears to be similarly about software. I'd be very interested to know why the rules here are being enforced inconsistently. Mind you, I think the question is informative, but the rules should be the rules.
Comment: @Weiwen It helps to pay attention to dates.  In the early days of this site, software-oriented questions were more widely accepted.  That some of these threads still hang around--especially the more highly voted ones--is not a valid reason to accuse us of inconsistency: these threads are indicators of *improvement.*  Better information about our policies is available at our [help] and on the meta site.
Comment: Within the R package [cluster](http://cran.r-project.org/web/packages/cluster/index.html) there is [?daisy](http://stat.ethz.ch/R-manual/R-patched/library/cluster/html/daisy.html) which will create a dissimilarity matrix for mixed data (Gower similarity coefficient). Then you can use [?agnes](http://stat.ethz.ch/R-manual/R-patched/library/cluster/html/agnes.html) or other clustering functions.
Answer: This may come in late but try klaR (http://cran.r-project.org/web/packages/klaR/index.html)
install.packages("klar")

It uses the non-hierarchical k-modes algorithm, which is based on simple matching as a distance function, so the distance δ between a variable m of two data points $x$ and $y$ is given by
$$
\delta(x_m,y_m) = \begin{cases}
1 & x_m \neq y_m,\\
0 & \text{otherwise}
\end{cases}
$$
There is a flaw with the package, that is if two data points have the same distance to a cluster-center, the first in your data is chosen as opposed to a random point, but you can easily modify the bit in the code.
To accommodate for mixed-variable clustering, you will need to go into the code and modify the distance function to identify numeric and non-numeric modes and variables.
Answer: Another appealing way of handling variables of mixed types is to use the proximy/similarity matrix from Random Forests: http://cogns.northwestern.edu/cbmg/LiawAndWiener2002.pdf. This faciliates a unified way of equally treating all variables (nevertheless, be aware of the variable selection bias issue). On the other hand, there is really no gold universal way of defining distance for variables of mixed types. It all depends on the application contexts.
Answer: You might use multiple correspondence analysis to create continuous dimensions from the categorical variables and then use them with the numerical variables in a second step.
Comment: How would you treat numerical variables in MCA? Using discretization?
Comment: There are extensions of MCA which can include continuous variables, see for example homogeneity analysis homals
Answer: Well, you certainly can. By making the categorical variables artificially numeric. Or using a distance-matrix based clustering (fpc can probably do that). The question you should first try to answer is: does it actually make sense?
Answer: You could use the universal similarity coefficient of Gower (see Sneath & Sokal 1973, pp 135-136), which for two OTUs $j$ and $k$ is
$$S_G = \frac{\sum_{i=1}^n{w_{i,j,k} s_{i,j,k}}}{\sum_{i=1}^n{w_{i,j,k}}}$$
for all characters $i$.
The weight $w_{i,j,k}$ is either 1 or 0, depending on whether the the comparison is valid or not (missing data, absence of binary character in both OTUs). More complicated weighing schemes have been published.
$s_{i,j,k}$ is calculated for

binary variables: 1 for concordance, 0 for discordance (equivalent to Jaccard's coefficient if $w_{i,j,k}$ is set to 0 for concordant absences)
multistate characters(nominal or ordinal): 1 for equality, 0 else (equivalent to the simple matching coefficient)
cardinal character: $s_{i,j,k} = 1 - \frac{|X_{i,j} - X_{i,k}|}{R_i}$ with $R_i$ the range of character $i$ (either in the population or in the sample).

The nice thing about $S_G$ is that it can not only handle all types of data, but is also robust towards missing data. It also results in positive semi-definite similarity matrices, i.e., OTUs are represented by points in Euklidian space (at least if not too many data are missing).
The distance between OTUs can be represented by $\sqrt{1-S_G}$
Comment: Can you define what is "character" (and "cardinal character") in your answer? Do by that you mean variable/attribute/feature? Besides, I might add that Gower can be computed for ordinal variables without treating them as nominal ("multistate"), [see](https://stats.stackexchange.com/a/15313/3277).
Comment: Caracter, variable, feature are all synonyms. Cardinal means either interval or rational scale.
Comment: Thank you for claring it. I just asked because your terminology is apparently not very common in statistics or machine learning: "character" is unusual, and what you call "cardinal" variable type is typically known as "scale" variable aka "metrical" variable, it opposed to categorical.
Answer: If possible values of categorical variables are not too many, then you may think of creating binary variables out of  those values. You can treat these binary variables as numeric variables and run your clustering. That's what I did for my project.
Answer: k-prototypes clustering might be better suited here. It combines k-modes and k-means and is able to cluster mixed numerical / categorical data. For R, use the Package 'clustMixType'.
https://cran.r-project.org/web/packages/clustMixType/clustMixType.pdf
Answer: VarSelLCM package offers

Variable Selection for Model-Based Clustering of Mixed-Type Data Set with Missing Values

On CRAN, and described more in paper.
Advantage over some of the previous methods is that it offers some help in choice of the number of clusters and handles missing data. Nice shiny app provided is also not be frowned upon.

Clustering of mixed type data with R


Black Holes and Diagrams of Different Coordinate Systems

Question: In General Relativity by Woodhouse there are the three following diagrams in Chapter 9 about Black Holes. Despite a (very brief) description of these diagrams in the book itself, I am struggling to understand what they exactly correspond to? Does anyone have good way of looking at how these diagrams help convey a) the properties of the particular coordinate system and b) a understanding of how black holes work in the particular coordinate system being looked at.
Comment: Crossposted from https://physics.stackexchange.com/q/450464/2451
Answer: The radial null geodesics for the Schwarzschild metric have the form
$$
t \pm [r + 2 m \ln (r - 2m)] = k \tag{1}
$$
where $k$ is a constant. This is a plot for different values of $k$

The plots you showed are just an attempt to represent these geodesics in three spatial coordinates. Unfortunately that cannot be done trivially, so instead Woodhouse decided to ignore one of the coordinates and draw Eq. (1) in the other two. You can do that by setting $x = r\cos\phi$ and $y = r \sin\phi$ for $0\leq \phi \leq 2\pi$. Or equivalently by rotating the curves in the figure above around the $t$ axis. This is an example for $k = 1$

This is just a fancy extension of the first figure above, but it is completely unnecessary, since the problem has spherical symmetry, and adding an extra coordinate just adds to the noise without any benefit.
Comment: Hi what software did you use  for plotting?
Comment: @magma Good old python


Cisco PIX and VPN: Copy config to backup devices

Question: Cisco newb question here. My company currently has one PIX and one VPN concentrator at our colo site. We purchased duplicate devices for redundancy. I need to copy the configs from the running devices and slap them on to the new duplicate devices. How do I do this?
Answer: You will actually want to setup stateful fail over (at least for the PIX/ASA) instead of just copying the config, that way if one device goes down at most you have a blink of non-stateful protocols.
here is example of my fail over config:
<code>failover
failover lan unit primary
failover lan interface FAILOVER GigabitEthernet0/2
failover key *****
failover link FAILOVER GigabitEthernet0/2
failover interface ip FAILOVER 192.168.1.9 255.255.255.0 standby 192.168.1.10
</code>
Cisco Documentation for PIX/ASA failover
This will keep the configs in sync as you make updates as well.
Sorry I can't speak to how to how to setup failover on the VPN Concentrator although the quick google search seems to indicate the use of VRRP for the Cicso VPN 3000 concentrator.
Comment: Bear in mind that failover requires the primary PIX to have an unrestricted license, and the secondary to have either an unrestricted or failover-only license. It is also only supported on PIX 515 and up. VPN concentrator failover depends on the model, but you are correct that VRRP would be the preferred method with the VPN 3000 series. If you are using PIX for VPN termination, failover works, but it is not seamless and sessions will be dropped during the transition.
Comment: @James: Thanks for the reminder about licensing, we buy everything UR so I always forget about that.
Answer: If you do "copy running-config ?" you'll see a list of different options for copying the config. Easiest one to use depends on your situation, but I'd recommend setting up a tftp server on the same network. Then you can do copy running-config tftp: and follow the prompts.
One thing that often trips people up when using tftp: Create a file of the same name as the one you want to copy over beforehand. It can be empty, it just has to exist and be writable.
Edit: forgot to mention that on the destination device, you just do the reverse:
copy tftp: running-config
:)
Comment: The copy running-config command is not working. We have a PIX 515E btw. When I issue the copy running-config, it comes back with:

PIX# copy running-config tftp:
Usage:  copy capture: tftp:/// [pcap]
        copy http[s]://[:@][:]/
                flash[:[image | pdm]]
        copy tftp[:[[//location][/pathname]]] flash[:[image | pdm]]
Comment: Actually I have a 515E as well.

What happens if you just type "copy " and then add a question mark? Does it give you "running-config" as an option?


I have interesting view when application running

Question: I used .xib
Here design page

Here when application run

When I open others view and back view like this.
I want to be like this when run first
Comment: Check you auto-resizing / auto-layout rules.
Comment: Incomprehensible.... Please rephrase and provide more detail
Comment: @Wain Where is it in Xcode ?
Comment: In the utilities view. http://developer.apple.com/library/mac/#documentation/ToolsLanguages/Conceptual/Xcode_User_Guide/000-About_Xcode/about.html
Answer: it looks like you have designed this with iphone 4" display mode on in the story board, then you are running it on a 3.5" display simulator, which will move some elements around. check out what your autosizing is doing to the buttons, and take off the 4" mode in the storyboard (if that is what is going wrong here)
edit: sorry you are using a xib, not story board, in that case check that the size property of the view is not on 4" mode or freeform and that it is the right size.


Write a list of files in the Documents folder and keep them in memory

Question: I have several files to be saved in the Documents folder, this list of files put in a mutable array. The files must remain in the memory of the iPhone application also closed. The first file is saved, but when I change view controllers and then go back the mutable array becomes empty. How do I keep the data in memory in the Documents folder?
in DetailExpViewController.h
  //....
  @property (nonatomic, strong)NSMutableArray *arrayFavorites;
  @property (nonatomic, assign)BOOL existsArray;
  //....
  @end

in DetailExpViewController.m
- (void)viewDidLoad
 {
      //.....
      if (!self.existsArray){
          /*when I load the view controller this array is always nil even
            has already  been created*/

           self.arrayFavorites =[[NSMutableArray alloc]init];
     }else{
          NSLog(@"The array exists");
      }
      //....
 }

 -(void) addFavorites:(id)sender{

     //.....
   NSArray *paths = NSSearchPathForDirectoriesInDomains
  (NSDocumentDirectory, NSUserDomainMask, YES);
   NSString *documentsDirectory = [paths objectAtIndex:0];

   NSString * text= [NSString stringWithFormat:@"%@.txt",self.name];
   NSString * documentsPath = [documentsDirectory stringByAppendingPathComponent: text];

   [self.arrayFavorites addObject:text];
   [self.arrayFavorites writeToFile:documentsPath atomically:YES];
   self.existsArray=YES;

   for (id obj in self.arrayFavorites) {

    NSLog(@"%@", self.arrayFavorites);
    //only writes the file at the time, then it is deleted

  }

}
Comment: in view didload array be nil always and then u alloc it
Comment: why dont you use sqlite for storing data always
Comment: Because is only list of file
Answer: U can save NSArray in Document Directory like this.
Note : saving and retrieving filename remains same.
Its also easy retrieve saved array from doc dir.
EDIT : If data is complex and large better use SQLITE.

EDIT : In view Controller's Add to favourite button click event:
 //check favourite saved in doc dir
 if(!saved) //not saved
   //NSMutableArray has not data first time
   //[NSMutableArray addObject:newFavourite];
   //save new data in doc dir
 else // saved
   //firstly retrieve data from doc dir as NSMutableArray
   //[NSMutableArray addObject:newFavourite];
   //Now save again NSMutableArray in doc dir.

By following these instruction files remain permanently in the Documents folder.
Comment: I have a mutable array is not a static array as shown. In my application there is a view controller inside which there is a button called "Add Favorites" if the user presses the button, the file should be saved in the Documents folder, otherwise not. I can not know in advance what will save the user, so I created a mutable array. These files must remain permanently in the Documents folder. How can I do?
Comment: refernce link example shows static data. but u can have dyanamic data


What is the difference between a Hamiltonian Path and a Hamiltonian Cycle?

Question: The title says it all. I've seen confusing definitions of this, and would appreciate if someone can succinctly clear this up with definitions and examples.
Comment: And this is true for every path/cycle e.g. Eulerian path...
Comment: A cycle is, with an abuse of notation, a closed polygon, while a path is a polygonal-line, open...
Answer: The cycle starts and ends in the same vertex, but the path does not.
Comment: @Agile_Eagle Note that this also means that in a graph with $n$ vertices, a Ham-path has $n-1$ edges, while a Ham-cycle has $n$ edges.
Comment: Arguably you should merely say that a Hamiltonian cycle includes an edge from the end node to the start node, since the essence of a Hamiltonian traverse is that the nodes are only visited once. I'm not sure anyone worries about such minor technicalities though.
Comment: Oh! I feel stupid for asking this now! For some reason I was getting confused reading the formal definitions.... Thanks
Answer: Hamiltonian cycle = a cycle (path ending in the same vertex it starts) that visits every vertex ($ n $ edges);
Hamiltonian path= a path that visits every vertex ($ n  - 1 $ edges).
In the graph represented by the matrix of adiacence:
01001
10100
01010
00101
10010

We have 1 - 2 - 3 - 4 - 5 or 1 - 5 - 4 - 3 - 2 Hamiltonian paths.
Also, 1 - 2 - 3 - 4 - 5 - 1 is a Hamiltonian cycle.
Answer: Hamiltonian path is a path in an undirected or directed graph that visits each vertex exactly once
Hamiltonian cycle is a Hamiltonian path that is a cycle, and a cycle is closed trail in which the "first vertex = last vertex" is
the only vertex that is repeated.
For more info https://www.whitman.edu/mathematics/cgt_online/book/section05.03.html
https://en.wikipedia.org/wiki/Hamiltonian_path


$\ell^{\infty}(\mathbb N)$ is not a separable space

Question: I have to prove that $\ell^{\infty}(\mathbb N)$ is not separable.
My attempt
Consider a SUBSET $V$ of $\ell^{\infty}(\mathbb N)$ consisting of bounded sequences that have only $0$, $1$ entries, e.g. $(0,1,1,0,0,0,0,1,0,0,\dots)$
Now assume that this SUBSET is uncountable.
If we take a radius $r=1/4$ then balls with origins that are elements of $V$ would be disjoint and because any base of  $\ell^{\infty}(\mathbb N)$ must contain a subset of each element of the set of these balls, base of  $\ell^{\infty}(\mathbb N)$ can't be countable so it doesnt satisfy the second axiom fo countability and thus is not separable (since  $\ell^{\infty}(\mathbb N)$ is a metric space).
Could someone check this? And I still need to prove that $V$ is uncountable...
Comment: Thre is no neeed to assume that your set $V$ is uncountable, for it is uncountable. You can do a standard diagonal argument to show this; notice that there is an obvious bijeection between your $V$ and the set of subsets of $\mathbb N$.
Comment: What you have is right. A bit problematic is using the word "subspace" for $V$, since in the context of (topological) vector spaces, "subspace" usually denotes linear subspaces. Use "subset" to avoid that. Regarding the uncountability of $V$, can you draw a connection between $V$ and $\mathfrak{P}(\mathbb{N})$?
Comment: Sorry, by *separable*, do you mean that you'd like to prove that $\ell^\infty$ has no countable dense subset?  If so, it seems you're going in the wrong direction...
Comment: My approach would be as follows: given a countable subset $\{x_n\}$ of $\ell^\infty$, find a $y$ such that $\|y-x_n\| \geq 1$ for each $n$.
Comment: Exactly, no countable dense subset. Could you tell me what is wrong? thanks
Comment: Daniel, you mean connection between the power set of $N$ and $V$? Your remark about subspace vs subset is 100% correct.
Comment: @luka5z :Don't you need finitely-many 1's in your sequence of 0's and 1s,, so that it is in $l^{\infty}$?
Comment: No. From definition $\ell ^{\infty} (\mathbb{N})$ is space of all sequences of natural numbers, such that each element of that sequence is finite.
Answer: As the OP guessed, the right subset to consider is the set $A\subset\ell^\infty$ consisting of all the sequences with zeros and ones, i.e., $\{a_n\}\in A$ if and only if
$a_n\in\{0,1\}$, for all $n$.
Clearly, if $\{a_n\},\{b_n\}\in A$ and $\{a_n\}\ne\{b_n\}$, then
$$
\|\{a_n\}-\{b_n\}\|_\infty=1,
$$
since there exists at least one $n$, for which $a_n\ne b_n$, and hence $|a_n-b_n|=1$.
Also $|A|=\big\lvert 2^{\mathbb N}\big\rvert= 2^{\aleph_0}$. Hence $A$ is uncountable, and in fact equinumerous to $\mathbb R$.
The open sets
$$
\big\{B\big(\{a_n\},\tfrac{1}{3}\big): \{a_n\}\in A\big\},
$$
are uncountably many mutually disjoint open sets. The fact that such a collection of open sets exists means that $\ell^\infty$ is not separable.


Is every element a union of some subset, for a set closed under arbitrary unions?

Question: Consider a set $A$ satisfying $Y\subset A\implies \bigcup Y\in A$ for any $Y$.
Now, I intuitively expect that any set $X\in A$ will satisfy $X = \bigcup Y$ for some $Y\subset A$. But I am not completely sure, and I have no idea how to prove or disprove it.
Any help?
Comment: Let $Y=\{X\}$, a singleton family.
Comment: @GeoffreyTrang Sorry, I don't get you example/counterexample.
Comment: @GeoffreyTrang I now get it. Thanks!
Comment: You've gotten a good Answer, but you might want to note that the union over an empty family of sets is by convention [the empty set](https://math.stackexchange.com/questions/370188).
Answer: If $X\in A$, then $X\subset A$
whence $X = \bigcup \{X\}$.
Comment: Oh! How could I not get this!


Block Problem w w/o Replacement

Question: Assume that a bin has 40 green and 60 red blocks.  Four are selected at random. Let X be the number of green blocks in the sample. Construct the probability table for X assuming that sampling is:
a. with replacement
$$P(X=4)=\binom{4}{4}{2/5}^4{3/5}^{0}=0.0256$$
$$P(X=3)=\binom{4}{3}{2/5}^3{3/5}^{1}=0.1536$$
$$P(X=2)=\binom{4}{2}{2/5}^2{3/5}^{2}=0.3456$$
$$P(X=1)=\binom{4}{1}{2/5}^1{3/5}^{3}=0.3456$$
$$P(X=0)=\binom{4}{0}{2/5}^40{3/5}^{4}=0.1296$$
b. without replacement
$$P(X=j)=\frac{\binom{40}{j}\binom{60}{4-j}}{\binom{100}{4}}$$
$$P(X=4)=\frac{\binom{40}{4}\binom{60}{4-4}}{\binom{100}{4}}=\frac{\binom{40}{4}\binom{60}{0}}{\binom{100}{4}}=\frac{91,390}{3,921,225}=0.0233$$
$$P(X=3)=\frac{\binom{40}{3}\binom{60}{4-3}}{\binom{100}{4}}=\frac{\binom{40}{3}\binom{60}{1}}{\binom{100}{4}}=\frac{592,800}{3,921,225}=0.1512$$
$$P(X=2)=\frac{\binom{40}{2}\binom{60}{4-2}}{\binom{100}{4}}=\frac{\binom{40}{2}\binom{60}{2}}{\binom{100}{4}}=\frac{1,380,600}{3,921,225}=0.3521$$
$$P(X=1)=\frac{\binom{40}{1}\binom{60}{4-1}}{\binom{100}{4}}=\frac{\binom{40}{1}\binom{60}{3}}{\binom{100}{4}}=\frac{1,368,800}{3,921,225}=0.3491$$
$$P(X=0)=\frac{\binom{40}{0}\binom{60}{4-0}}{\binom{100}{4}}=\frac{\binom{40}{0}\binom{60}{4}}{\binom{100}{4}}=\frac{487,635}{3,921,225}=0.1244$$
Can you please check my calculations?
Comment: In what you did, you should have on the left not $\Pr(X=j)$ but first $\Pr(X=4)$, then $\Pr(X=3)$, and so on. Your expressions look right. The computations are not, the probabilities should add to $1$.
Comment: ${40\choose1}\times{60\choose3} = 1368800$
Answer: A is rather straightforward - since you replace the block every time you draw, the probability of drawing a green block is just 40% every time.  Use the binomial distribution.
For B, it looks like you've done the right thing - sampling without replacement requires the hypergeometric distribution.  But you should check your calculations - the 5 probabilities that you have do not sum to 1, and they should.  If you draw four times, you have a probability of 1 that you got somewhere between 0 and 4 green blocks. This looks like a homework question, so I'm not going to point out where the math error is; compare the fractions you get against the decimal values.
Comment: Thank you all for your help! I got the calculation error and I'll try doing A now!
Answer: Your working for B looks right. For A, since you replace the blocks every time, probability of a green block is $\frac{2}{5}$ and a red block is $\frac{3}{5}$ - use the binomial distribution.

Block Problem w w/o Replacement


Beginner: Styling ReactJS Checkbox using CSS Pseudo Elements

Question: I am trying to style reactjs checkbox component using CSS. It uses pseudo-elements :after and :before.
Mock it up on html and css and it worked! Fiddle Link
input[type="checkbox"]#checkbox + label::before {
   content: "";
   display: inline-block;
   vertical-align: -25%;
   height: 2ex;
   width: 2ex;
   background-color: white;
   border: 1px solid #c3c4c6;
   border-radius: 4px;
   margin-right: 0.5em;
}

input[type="checkbox"]#checkbox:checked + label::after {
   content: '';
   position: absolute;
   width: 1.2ex;
   height: 0.4ex;
   background: rgba(0, 0, 0, 0);
   top: 0.5ex;
   left: 0.4ex;
   border: 3px solid #60cd18;
   border-top: none;
   border-right: none;
   -webkit-transform: rotate(-45deg);
   -moz-transform: rotate(-45deg);
   -o-transform: rotate(-45deg);
   -ms-transform: rotate(-45deg);
   transform: rotate(-45deg);
}

But when i tried to implement it on my reactjs component that display checkbox,maybe the :after doesn't work. Fiddle ReactJS Component Link
How should i achieve the same style on ReactJS checkbox component?
Answer: There's couple of ways to use pseudo elements on React such as Radium, but afaik it doesn't support :after/:before, instead according to this and this, it suggest creating an element in place of the pseudo-elements. I didn't find any React example of this and i think the availability of pseudo elements was to avoid creating unnecessary DOM elements.
With all that limitations, my current solution for customising the checkbox in react so that it works on most browsers was to create an element that acts,looks, and feel like a checkbox(imposter), but not a checkbox by itself (input type="checkbox"). I achieved this by using ReactJS to trigger the visibility of the span element and font-awesome icon.
Example
/*  html   */

/* JS  */
var Checkbox = React.createClass({
        getDefaultProps: function() {
        return {
        value: true,
        name: '',
        borderWidth: '1px',
        borderStyle: 'solid',
        borderColor: '#c3c4c6',
        borderRadius: '4px',
        checkColor: '#60cd18',
        height: '1px',
        width: '',
        namePaddingLeft: '10px',
        namePaddingRight: ''
        };
    },
    render: function() {
        var style = {
            boxStyle: {
            borderWidth: this.props.borderWidth,
            borderStyle: this.props.borderStyle,
            borderColor: this.props.borderColor,
            borderRadius: this.props.borderRadius,
            paddingLeft: this.props.width,
                    paddingRight: this.props.width,
            paddingTop: this.props.height,
            paddingBottom: this.props.height
          },
          show: {
            visibility: 'visible',
            color: this.props.checkColor
          },
          hidden: {
            visibility: 'hidden',
            color: this.props.checkColor
          },
          name: {
            paddingLeft: this.props.namePaddingLeft,
            paddingRight: this.props.namePaddingRight
          }
        };
        return (

           {this.props.name}

        );
    }
});

var WrapperCheckbox = React.createClass({
    getInitialState: function(){
    return {value: false}
  },
  handleClick: function(){
    console.log('Click Fires!');
    this.setState({value: !this.state.value});
  },
    render: function(){
    return (

            <Checkbox name='Reserve Guarantee' value={this.state.value}/>

    );
  }
});

React.render(<WrapperCheckbox />, document.getElementById('container'));


2008 Group Policy Manager not propagating registry preferences into windows server 2003 boxes

Question: I have a Windows 2008r2 Domain with 2008r2/2012 Group Policy Manager.
In my domain, I still have windows server 2003 boxes (about 50 of them)
I'm trying to push registry updates via Preferences\Windows Settings\Registry.
While they show perfectly, I'm getting a 'N/A' in the gpresult registry settings in the boxes.
Other GPO line items propogate perfectly.
There's no errors in the 2003 servers.  It's as if the GPO decides not to push registry settings.
Of note, I also attempted to add a startup bat script, and that's not getting propogated either.
Where can I go and dig out why the registry settings are not being pushed out to my servers?
Thanks.
Answer: Please install the Group Policy Preference Client Side Extensions. (It's a download for xp, 2003, 2003 r2)
GPP was introduced in 2008, thus any OS below need the extension installed to be abl;e to process them.

Multiple Group Policy Preferences have been added to the Windows
  Server 2008 Group Policy Management Console (which are also available
  through the Remote Server Administration Toolset (RSAT) for Windows
  Vista SP1). Group Policy Preferences enable information technology
  professionals to configure, deploy, and manage operating system and
  application settings they previously were not able to manage using
  Group Policy. After you install this update, your computer will be
  able to process the new Group Policy Preference extensions. After you
  install this item, you may have to restart your computer.

From Group Policy Preference Client Side Extensions for Windows Server 2003 (KB943729)


How to create SFTP service in Windows xp sp3?

Question: Hi We can create ftp server in Windows XP SP3 OS using IIS ftp server.  In my project i need to connect SFTP server so, How can I create SFTP server in Windows xp SP3 operation system? Is it possible to creat using IIS as we create FTP server?  Can anyone
provide me tutorial or links to create SFTP server in my desktop machine? nrk
Answer: You can use the FileZilla FTP Server, which supports SFTP.
Comment: Filezilla supports FTP and FTPS, *not* SFTP.
Comment: Thanks, as it is opensource I can use it.
Answer: I use a project from sourceforge called sshwindows. It's basically a wrapper around the cygwin OpenSSH library. It's minimal and works a charm.
Answer: Take a look at WinSSHD (by the makers of putty). Simple, easy to use, and free for non-commercial use.
Comment: Citation for the putty link?  Putty is written by Simon Tatham, I can't see any link between him and Bitvise.
Answer: Take a look at CompleteFTP, which supports SFTP on Windows, and runs as a Windows service. Commercial product btw.
Answer: I am able to setup SFTP server, the below link explains how to setup SFTP server on windows  machine:
http://www.xenocafe.com/tutorials/windows/openssh_sftp_server/index.php
everyone for the quick help.
nrk


Media 7.0-2.x and Plupload

Question: Is there any combination of Media module in version 2.x for Drupal 7 which works with Plupload Integration of any version?
I installed the newest dev versions of File entity, Media and Plupload but they don't work togheter.
Is there any other Bulk upload for Media which already works with version 2.x?
Are there any patches I can apply to get Media togheter with Plupload working?
Comment: Hey there. I struggled with that combo for awhile, but started to phase it out when it became too troublesome to maintain. With Media 7.x-2.0-unstable7 I had to add the [Multiple Forms](http://drupal.org/project/multiform) module and (if I recall correctly) [Media Multiselect](https://www.drupal.org/sandbox/fangel/1652676) to keep bulk uploads working at the time. I do keep copious notes so let me know if there is more I can tell you.
Comment: @othermachines Thx a lot :-). Installation of the missing `Media Multiselect` module helped out. Although I had to apply [the following patch](https://www.drupal.org/node/2216273#comment-9642477) to the current master commit to get it working with the newest dev versions of Media and Plupload Integration. Now it seems to work fine if I change the Widget type for my `File` field. You may create an answer for my question and I will mark it as correct.
Comment: Hey, that's really great. Glad you got it sorted. I've posted my suggestion as an answer, with an added note about the patch.
Answer: It's been a little while for me and it was tricky at the time, but enabling these modules should help:

Multiple Forms
Media Multiselect (provides a "Media Multiselect" widget instead of the standard Media Browser)

There was an additional patch to Media and a plethora of other issues (mostly related to permissions and editing files) that I noted as resolved as of 2014-Sep.
As you point out in the comments, a patch to the Media Multiselect module was still required to get the most recent dev versions of Plupload and Media 2.x working together by changing the widget type to that provided by Media Multiselect:
Patch (required for now but under review): Issue #2216273: Latest media changes break the multiselect (Comment #52)
Cheers -
Answer: maybe the file field sources module works with media - i did not check yet.
Answer: For the media module, I believe the issue to follow is https://www.drupal.org/node/951004

Media 7.0-2.x and Plupload


Could somebody prove that there are infinite values of a and b where both 6a-1 and 12b-1 are prime?

Question: By asking this question, I hope that someone, somewhere, has an answer, not to the conjecture, but the question itself. Then, that person has proved an unsolved conjecture. I do have a proof, which is quite long, that all Germain primes are of the form 6n-1. For more details, go to the question: Are there an infinity of Sophie Germain primes? My second answer provides a full proof.
Comment: What is the question?  And why on earth is the answer urgently needed?
Comment: I believe the maximum we can use is the [Green–Tao theorem](https://en.wikipedia.org/wiki/Green%E2%80%93Tao_theorem#Extensions_and_generalizations)
Comment: I'm not sure what you are trying to ask, but one interpretation is equivalent to "are there infinitely many Sophie Germain primes?" and this is (so far as I know, at time of posting) unknown. It would help if you could state your question clearly in the body of the question - where it is easier to format, and also you don't have to summarise. Is it "are there infinitely many positive integers $n$ for which $6n-1$ and $12n-1$ are both prime?" ?
Comment: Note:  I don't believe you have shown that there are infinitely many Sophie Germain primes.  Perhaps you meant something else?
Comment: Note that every prime of the form $12n-1$ is also of the form $6n-1$ so if there are infinitely many primes of the form $12n-1$ (which there are) then these same primes will be an infinite set of primes of the form $6n-1$ (there are also infinitely many primes of the form $12n+5$). Simply because the two sets are infinite does not guarantee that there are infinitely many pairs.
Comment: Voting to close the question as it is not clear what you are asking.  If you can, please edit your post for clarity.
Comment: Mark, sorry, but I think I implied it in the notice underneath the question.
Comment: Responding to your first comment, lulu, I do mean to prove the infinity of Germain primes. I asked this question to get someone else's perspective. Thank you for your comment, though.
Comment: rtybase, sorry, but I am not sure how to answer your comment.
Comment: The question in the title is probably not what you intent. There are infinite many pairs $(a/b)$ such that both $6a-1$ and $12b-1$ are prime if $a$ and $b$ are not related. If they have to be equal, it is an open question whether infinite many positive integers $n$ exist such that $6n-1$ and $12n-1$ are both prime. The Bunyakovsky conjecture implies that this is the case.
Answer: $2(6n-1)+1=12n-1$. Thus, if $6n-1$ and $12n-1$ are both prime, then $6n-1$ is a Sophie Germain prime and $12n-1$ is the associated safe prime. Thus, for both to be prime infinitely often, there would have to be infinitely many Sophie Germain primes. As this is currently an unproved conjecture (at least according to Wikipedia), you probably won't get a proof here.
Comment: joriki, I am actually trying to prove the infinity of Germain primes. Thanks for clarification, though, but I still edited it for reasons of the question being unclear.
Comment: @mngi: I don't get it. You asked for a quick answer that proves a well-known open conjecture?
Comment: I'm trying to phrase it in a way which maybe someone had the answer to, therefore proving the conjecture. Thank you for your question.


$\tan(\theta) = x/2 \Rightarrow \sin(\theta) = x/\sqrt{4+x^2}$

Question: I do not see why if we have $\tan(\theta) = x/2$ we know that $\sin(\theta) = x/\sqrt{4+x^2}$
Can someone please explain that to me?
Thanks in advance
Comment: Draw the right-angled triangle, then you can get intuition.
Answer: $$\tan(\theta)=\frac{O}{A}\implies O=x, A = 2\implies H = \sqrt{4+x^2}$$
$$\implies \sin(\theta)=\frac{O}{H}=\frac{x}{\sqrt{4+x^2}}$$
Edit: As others have pointed out, I should really make explicit the assumption that $\tfrac{-\pi}{2}< \theta < \tfrac{\pi }{2}$. This assumption seems to be standard when dealing with trigonometric substitutions, which is where you may more commonly have to make such inferences, but should be stated regardless.
Answer: You can't prove the equality you're after, because it is false.

We have, in general,
$$
\sin^2\theta=\frac{\sin^2\theta}{\sin^2\theta+\cos^2\theta}=
\frac{\sin^2\theta/\cos^2\theta}{(\sin^2\theta+\cos^2\theta)/\cos^2\theta}=
\frac{\tan^2\theta}{\tan^2\theta+1}
$$
In your case,
$$
\sin^2\theta=\frac{x^2/4}{(x^2/4)+1}=\frac{x^2}{x^2+4}
$$
This entails
$$
\lvert\sin\theta\rvert=\frac{|x|}{\sqrt{x^2+4}}
$$
which is the most you can say.
For instance, if $\theta=3\pi/4$, we have
$$
\tan\frac{3\pi}{4}=-1
$$
so $x=-2$; on the other hand,
$$
\sin\frac{3\pi}{4}=\frac{1}{\sqrt{2}}
$$
whereas
$$
\frac{x}{\sqrt{x^2+4}}=\frac{-2}{\sqrt{4+4}}=-\frac{1}{\sqrt{2}}
$$
Answer: Hint
$$\forall t\in\mathbb R \; \frac{1}{ 1+(\tan(t))^2}=1-(\sin(t))^2$$
Answer: In the right angled triangle the side opposite $\theta $ is $x$ and adjecent side is $2$ and so  hypotenuse is$\sqrt{4+x^2}$ and so $\sin \theta= \dfrac{x}{\sqrt{4+x^2}}. $  If $\sin \theta $ is given then we get back $ \tan \theta = \dfrac{x}{2}.$
If $\sin \theta $ admits both signs due to $\pm$ before radical sign then  $\tan \theta $ also admits the same two. You should check other quadrant, other than first quadrant, for the two solutions obtained.


Adding Link To Drupal 6 Views Slideshow

Question: Probably a stupid question. I'm more used to Drupal 7, but I'm working on a new site today and it's Drupal 6. There is a Views Slideshow on the home page. The buttons and images automatically cycle. We want to add a link to each button/image so people can click and go to a related page.
http://simulab.com
I looked at the nodes for the content used for each image and I was surprised that there is no field to store a link--as is common in most slideshows I see now.
The Links module is installed, but again there is no Link field type in the node content used to store each image/button in the view.
Looking at the HTML, I see that there is no href for each button or img. Apparently one can hover over a button to switch visible images, but cannot -click- to go to another URL.
What's the preferred way to add a click URL to each of the images and/or buttons in the view?
TIA
Answer:
Add a link field using CCK for the content type.
override the label output to include the rendered link in the View.
Comment: For any future travelers, the 'trick' such as it is:

1. Add a plain text field to the Content Type. (I tried using a 'Link' type, but this kept generating -crazy- html and I just needed to get 'er done.)

2. By default, the Slideshow appears to work with the 'Node' row type. You have to change to 'Fields' and then change the Slideshow Style options and check the image field in the 'Main Frame Field' box.
3. You then need to make sure the Image field is set with a picture type of 'Picture'.
4. The code for the Rewrite Output is then:
[field_my_image_fid]
Comment: OK, I'll need to change the Row Style to Fields and create the fields I need. I am unclear as to what replacement patterns I will need to use for the link. 1) Should I use Rewrite option and then type in something like '<a href="[field_button_url_url]" img src="field_img"..etc. Or should I use the 'Output This Field As A Link' option? And if so, what replacement token should I use? Any specifics would be appreciated! TIA.
Comment: your questions depend on how far you intend to theme it -- but you have the correct questions. I recommend your first approach with the `` tag, although i think all you need is the `href` and no `img src`. You can accomplish the img src stuff solely with CSS ... you just want to fix the link tag itself.
Comment: Thanks. I think I'll wait until 2am to try this. :D Back tomorrow with success/failure.
Comment: Well, that didn't go so well. When I converted the Row Style to Fields, this immediately made the Slideshow stop working so I stopped. Any idea -why-? The generated SQL seems very different... which suprised me since there is really only one field in the node besides the usual 'weight' etc.
Comment: Did you build this theme ? If not you'd have to understand how the view template is constructed for each slide -- while dirty you could look to see how that works and tweak code in the template file to meet your needs. Or use hook_views_pre_render() to alter the links as well -- the solution I tried to outline above was via next to no code. These other solutions require PHP and Drupal themeing/coding knowledge.
Comment: No I am not the themer. It's the standard Slideshow Views 2.6 module... I guess it must be pretty ancient if it doesn't support links natively. I do understand PHP, but not D6 or this module. Anyhoo, I figured it -should- work without any coding so I asked before wasting time trying to 'reverse engineer'. I figured I was missing something totally obvious. I'll take yer advice and play around then report back with my next dilemma. :D Thanks for helping out!
Comment: I'm voting this as 'answered' although it's far from complete. I could've easily gone off in the wrong direction (again). NOT 'tenken's fault at all. He gave it a great shot! The only reason I'm picky about this is because the learning curve in Drupal is -so- steep and what I find most often is that people give answers that get ya about 1/3 the way there... and then yer on yer own. Not the poster's fault of course. Right now I'm in this 'uncanny valley' between knowing a little and knowing what I'm doing. The Drupal community needs to work to bridge that gap somehow.

Adding Link To Drupal 6 Views Slideshow


Drupal Multisite (subdomain) Not Working

Question: Drupal 6, default installation, default .htaccess, default http.conf for Apache.
sites/ directory looked like this:
all
default
subdomain1.maindomain.com

default site and subdomain1 working well.
Added a new directory, subdomain2.maindomain.com. It has the same ownership and permissions as subdomain1.maindomain.com. It contains default.settings.php, the out-of-the-box one, and settings.php, which is a copy of default.settings.php. The permissions and ownership of the two files are correct.
The 'sites' directory now looks like this:
all
default
subdomain1.maindomain.com
subdomain2.maindomain.com

Visiting subdomain2.maindomain.com returns an error. Visiting subdomain2.maindomain.com/install.php returns an error. I can download an example file from  maindomain.com/sites/subdomain2.maindomain.com/files/example.txt when it is located at /sites/subdomain2.maindomain.com/files/example.txt.
Basically, I've followed all the steps in the docs, and I'm unable to create another 'subsite' accessible from a new subdomain. What am I doing wrong? What else should I be doing?
Comment: I think you have a DNS issue and/or an Apache config issue.  dig subdomain2.maindomain.com and make sure it points to the right place.  Then watch the request with Firefox Live HTTP Headers and see what is happening.  Then check the Apache access and error logs and try to match everything up.
Comment: What exact error does subdomain2.maindomain.com return?
Comment: 'Connection has timed out'. hmm....
Comment: You just create new subdomain2.maindomain.com domain that have code base from your main default drupal site. If you run at local you must input new line in hosts file to make it works
Answer: If you want to run several sub-domains on the same code base you need to make sure that either both the sub-domains resolve to the same IP address as your main domain, or that your main domain supports wildcard DNS. You also might consider giving Subdomain module and Domain Access module a try.
Answer: Check that subdomain2.maindomain.com should point to the same directory as is subdomain1.maindomain.com in the cpanel. This directory is the root of Drupal installation.
Firstly simply create a symbolic link ( ln -s subdomain1.maindomain.com  subdomain2.maindomain.com ) and see if the subdomain2 is accessible. Otherwise it is configuration issue with Apache/Cpanel.


Using Change of Variables to get the distribution function

Question: I have a random variable, call it $X$. This is a uniform random variable that is defined on the $[0,1]$ interval. Now consider its transformation $Z$ defined as:  $$Z=klog\times(X)$$ where $k$  is a negative real number. I now wish to calculate the distribution function of $Z$. This is what I have done. Now, by definition, $$F_{Z}(Z)\equiv Pr(z\leq Z)=Pr(klog(X)\leq Z)$$   $$=Pr(logX\geq Z/k)=Pr(X\geq 10^Z/k)=1-Pr(X\leq 10^Z/k)$$  $$=1-(10^Z)/k$$
Is this correct?
Answer: No. You have a few errors:

Usually we use the capitol $Z$ to represent the random variable, so $F_Z(Z) = Pr(Z \le z)$.
Your end result is a distribution function, you need to differentiate this to obtain the density
The inverse of $\log$ is $\exp$. In statistics, $\log$ is always $\log_e$ not $\log_{10}$.
Comment: @ChinG well since you're posting on a statistics site, you should write base 10. It's just an exponential variable either way, but your mean is not necessarily $1/k$.
Comment: Thanks..I agree with the first two points. This variable was generated in a programming language, so I am not sure if we are talking about the natural log (depends what the term "log" corresponds to in the specific language)


Get position of item in item in recycler view

Question: I have a recyclerView with CardView items. In CardViews I have an imageView with same resource id in all items.
I need to get position of clicked imageView in cardview (position of cardView). For Cardviews I hasn't any problems to get an index of clicked CardView (for this I made custom listener). But I got stuck with imageView into cardView... pic with recycler.
How can I get the position? Is it possible? In my opinion, I can handle click of imageview in cardview listener (like recyclerview.setOnClickListener{ if (imageview.isClicked()...) }), but I think that it isn't best solution.
Answer: You're probably setting the OnClickListener of the recycler item in the ViewHolder. If so, just use the ViewHolder's adapterItemPosition.
If for some reading you're not inside the ViewHolder. Make a way to access the position. Something like the tag, or a custom OnClickListener implementation.


In Unity, is UI system much worse in terms of performance than using 2D sprite?

Question: I'm making a card game(such as Hearthstone) with Unity, since there're many texts, I'm using the UI system to make the whole game, meaning each card is an UIImage with an animator on it.
My game is kind of slow when running on old cell phones such as iPhone 6S. I'm not sure if it's caused by not using sprite system with UI texts' transforms attached to the card sprites.
So as the title says, is UI system much worse in terms of performance than using 2D sprite?
Answer: Yes, in general, UI is worse.
This opinion is based on the Unity optimization videos and articles.
where they mention things like:

When one or more elements change on a Canvas, the whole Canvas has to be re-analyzed to figure out how to optimally draw its elements.. and other similar performance issues (see article link below)

references:

https://create.unity3d.com/Unity-UI-optimization-tips
https://youtu.be/_wxitgdx-UI?t=1418 (lots of details about why its slow)

But of course you should use profiler your app in device to see whats the actual cause for slow down.
Comment: Thank you for your help. In my case all cards have texts which must be rendered with UI, and these UI's transforms must follow the cards' transforms. So even if I change all cards using 2D sprites, the texts on them will still cost the almost the same. So there's no point changing them into 2D sprites right?
Comment: The UI is only worse if you don't understand how it is optimized. Once you create your UIs in the right way it will be *much* better than sprites.


How should I interpret this exercise from Chiswell & Hodges Mathematical Logic?

Question: Exercise 5.4.7 on page 127 of Chiswell and Hodges "Mathematical Logic" is:

Let $\sigma$ be a signature, $r$ a term of qf LR($\sigma$), $y$ a variable and $\phi$ a formula of qf LR($\sigma$). Let $D$ be a qf $\sigma$-derivation, and write $D^{\prime}$ for the diagram got from $D$ by replacing each occurrence of the formula $\phi$ in $D$ by $\phi[r/y]$. Show that $D^{\prime}$ is also a qf $\sigma$-derivation.

The book defines LR as a "language of relations". A formula of qf LR($\sigma$) is a formula in which quantifier symbols do not appear ("quantifier free"). A $\sigma$-derivation is defined as a tree structure that satisfies the logic rules for LR($\sigma$) (definion 5.4.5 on page 125).
I interpret the question above as follows. We "fix" the signature $\sigma$, term $r$, variable $y$, and formula $\phi$ first. Then, we are given a $\sigma$-derivation $D$. For each node in $D$, we replace occurrences of the formula $\phi$ that appear as sub-formula within the left label of the node (the left label of a derivation node is a formula, the right label is the name of the rule used to derive the formula in the left label) with the formula $\phi[r/y]$. We want to show that the tree that results from this process is a qf $\sigma$-derivation.
After struggling to prove the result, I looked at the solution on page 239-240. The solution only describes the proof for one part of the $\sigma$-derivation (the $\sigma$-derivation requirements of a node that has two daughters and right label "=E"), but it appears to be describing a proof for a problem where the formula $\phi$ is not fixed. For clarity, this is the proposition that I think the solution is proving:
Let $\sigma$ be a signature, $r$ a term of qf LR($\sigma$), $y$ a variable. Let $D$ be a qf $\sigma$-derivation, and write $D^{\prime}$ for the diagram got from $D$ by substituting the term $r$ for the variable $y$ in the formula of each left label in $D$ (i.e. for each formula $\phi$ that appears as a left label in a node of $D$, replace the left label with $\phi[r/y]$). Show that $D^{\prime}$ is also a qf $\sigma$-derivation.
I concluded this because the solution proves that, given some node $\nu$ with formula $\psi$ as its left label, the formula $\psi[r/y]$ satisfies the requirements for that type of node (a "=E" node). It doesn't delve into any reasoning about whether some pre-existing formula $\phi$ is equal to $\psi$, not equal to $\psi$, or is a sub-formula of $\psi$, which I expect would be required if $\phi$ were fixed before the derivation $D$ was considered. (Note: my description of the solution is a rough summary based on my understanding of it, refer to page 239 of the book for the details.)
My questions:
Is the wording of this exercise clear?
Is there a better wording that might help me understand it better?
If you are familiar with the book, does it appear that the solution is proving something that is not the same as the problem defined in the exercise? Or, if the wording of the exercise is fine, and the solution is correct, can you help me understand why the solution only deals with substituting $r$ for $y$ and doesn't deal with contents of the formula $\phi$?
EDIT: response to Mauro's question (What do you mean with "the contents of the formula $\phi$ ?):
I don't understand how the proof for case (=E) could be correct: to quote from the solution,

The formulas at the corresponding nodes in $D^{\prime}$ are $\phi[t/x]^{\prime}$ at $\nu$ and $\phi[s/x]^{\prime}$ and $(s = t)^{\prime}$ at its daughters.

where the solution defines the prime notation by stating

we write $t^{\prime}$ for $t[r/y]$ and $\phi^{\prime}$ for $\phi[r/y]$.

This is my confusion with the solution: the corresponding nodes of $D^{\prime}$ should only be modified ($r$ substituted for $y$) at places where the formula $\phi$ (fixed before we modified a derivation D) occurs in the left label. So why does the solution assume that the left label of BOTH $\nu$ AND its daughters are modified such that $r$ is substituted for $y$? Shouldn't the "contents"/"form"/"parse tree" of the $\phi$ have to match the left label of a node for the formula to be modified?
Comment: *Comment*: why the hint suggests to check only case (=E) ? Because - up to that point of the book - the **only** rules dealing with *terms* are these involving $=$; thus, you can consider it as a "representative sample".
Comment: What do you mean with "the contents of the formula $\phi$" ?
Comment: @MauroALLEGRANZA: Yes I don't have any issue with the solution only discussing the case (=E), that part makes sense to me. Response to your second question given in an edit.
Answer: Maybe I understand it now...
Your concern is right: what the exercise proves is something like:

if $\Gamma \vdash \phi$, then $\Gamma [r/y] \vdash \phi[r/y]$,

i.e. every occurrence of formulae $\phi$ must be replaced with $\phi[r/y]$.
At node $\nu$ of the corresponding tree, we have the left leaf $ϕ[t/x]$ and we have to replace it with $ϕ[t/x]′$. But it may be the case that $y$ occurr also inside $t$, and thus the replacement acts also on the "part" of $ϕ[t/x]$ where that occurrence of $y$ is "imported" by $t$. This is way we have to consider also $(s=t)′$.
Consider this silly derivation $D$ in the qf language of arithmetic:
1) $z=y$ --- is: $s=t$
2) $z=S(0)$ --- is: $\phi[s/x]$, where $\phi$ is: $x=S(0)$
3) $y=S(0)$ --- is: $\phi[t/x]$; from 1) and 2) by (=E).
Now we want to build $D'$ with $S(x)$ as $r$, replacing each occurrence of the formula $y$ in $D$ by $r$.
The "receipe" is:

modify $D$ such that the corresponding nodes in $D′$ are $ϕ[t/x]′$ at $\nu$ and $ϕ[s/x]′$ and $(s=t)′$ at its daughters.

Thus, working upside-down, we have the new tree:
3') $S(x)=S(0)$ --- this is: $ϕ[t/x]′$
2') $z=S(0)$ --- this is: $ϕ[s/x]′$
1') $z=S(x)$ --- this is: $(s=t)′=(s'=t')$.
If, as you noted, we do not apply the substitution of $r$ in place of $y$ to the leaf $(s=t)$, what we get is a wrong derivation:
3'') $S(x)=S(0)$ --- this is: $ϕ[t/x]′$
2') $z=S(0)$ --- this is: $ϕ[s/x]′$
1') $z=y$ --- this is: $(s=t)$.
Comment: Would you say that your example given here is a counterexample to the proposition the exercise asks us to prove? It seems so to me, as we can suppose $\phi$, $r$, and $D$ as in your example. Let $\phi$ is $y = S(0)$, $r$ is $S(x)$, and $D$ is the derivation as you defined it. Then, as described in the exercise, the derivation $D^{\prime}$ will only differ from $D$ in the label of the root node, because our chosen $\phi$ will only "occur" in that node, and doesn't "occur" in the daughters of that node (since their labels are $z = y$ and $z = S(0)$, read respectively from left to right).
Comment: @yorble - exactly; I agree with you that (presumably) the exercise is ill-stated, while the proof hinted at is correct (but for a different result).


Button needs to be clicked twice to work - why?

Question: My issue is the Button in my activity needs to be clicked twice to make the code execute written in the onClick method.
While I am sharing my Activity code and Layout file code. Please guide me to solve the issue.
Activity (Fragment)
public class SelfFamilyInfoActivity extends Fragment {

Button btnUpdateFamily;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.self_mem_details_family_info,
  container, false);

    try {

        btnUpdateFamily = v.findViewById(R.id.btnUpdateFamily);

        btnUpdateFamily.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Toast.makeText(getActivity(), "Button Clicked",
        Toast.LENGTH_SHORT).show();

            }
        });

    } catch (Exception e) {
        e.printStackTrace();
    }

    return v;

}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}
}

Layout File
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:scrollbars="vertical">

<ScrollView

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    android:scrollbars="vertical">

    <LinearLayout

        android:id="@+id/llLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="12dp"
        android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp"
                android:gravity="center">

                <Button
                    android:id="@+id/btnUpdateFamily"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    android:layout_marginBottom="5dp"
                    android:background="@drawable/button_background"
                    android:paddingLeft="10dp"
                    android:paddingRight="10dp"
                    android:text="Update Family Info"
                    android:textColor="@color/buttonTextColorWhite"
                    android:textSize="18sp" />

            </LinearLayout>

        </LinearLayout>

 </ScrollView>
 </android.support.v4.widget.NestedScrollView>

While this fragment is being initialized in Another MainActivity.
Comment: you want double click or its working on the second click
Comment: its working on the second click. while it is supposed to work on first click.
Comment: try click from xml
Comment: do u mean to say OnClick property in button xml code?
Comment: Do you mind removing the `try-catch` around the button initialization and see if there's an actual exception thrown?
Comment: @YasinYILDIRIM : tried .. but same thing is happening.
Comment: @MilanPansuriya : on using OnClick in xml i get exception
Could not find method btnFamilySubmit(View) in a parent or ancestor Context for android:onClick attribute
NOTE: I have declared the method in fragment also.
Comment: can you add what you tried
Comment: could you please try adding "clickable" and "focusable" params as true in xml ?
Comment: Might be worth a try, can you try onTouch instead of onClick?
Comment: @MilanPansuriya  : in XML-
            android:onClick="btnTest"
in Activity - public void btnTest(View v){
Toast....}
Comment: btnTest write in your fragment not in activity
Comment: @javabee I tested your code and it works, maybe there is another problem with the activity, can you add the code of the activity, try with other devices
Comment: Guys. It worked in first run , it didnt work again. please give more suggestions.
Comment: @Ahmed.ess : I am trying this on 3 devices i have.
on all of them it doesnt work.
Answer: For fragment it is good to use your all view click in onViewCreated method. May be view not prepared but you start clicking . And you use try catch block did you see any exception in your log. I am not sure. But you can try your click listener in your onViewCreated method.
UPDATED
try to use this code. this code working in my section
 Button btnUpdateFamily;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.self_mem_details_family_info,
            container, false);

    return v;
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    btnUpdateFamily = view.findViewById(R.id.btnUpdateFamily);

    btnUpdateFamily.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Toast.makeText(getActivity(), "Button Clicked",
                    Toast.LENGTH_SHORT).show();

        }
    });

}

Comment: Thanks brother. This Worked for me.
Comment: Welcome! @java bee
Comment: hi. I guess the problem is not solved yet. i run the app and it worked on first run while applying to the changes you suggested. and it is giving the same issue now.
buttons needs to be clicked twice to work.
Comment: buttonName.bringToFront(); try it
Comment: still the same.
Sorry for removing the answer flag.
I am badly in need to resolve this issue.
Comment: It worked in my section well. try to use this code in you r fragment class. i updated my answer
Comment: i have changed my code according to your code. but still sometimes the button works on first click and sometimes on second click.
I think the issue is in creating the view.
I will take some more efforts to resolve this issue. and post it here.
thanks for the brilliant help tariqul and other friends.
Comment: i used your view. I have doubt  your activity. It will good to show your activity xml


How can I override or alter a module's help text?

Question: I am trying to override or alter Layout Builder's default help text. Is is possible to do this? If so, how?
I have added some help text in a hook_help() function in a custom module but I can only get it to add to Layout Builder's help text. I can't find a way to override the default text.
Answer: I don't recall doing exactly this, but I think you can use a hook_module_implements_alter() for this:
function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook === 'help') {
    unset($implementations['layout_builder']);
  }
}

This should disable layout_builder_help(), and then just yours will run.  A hook_help_alter() would be nice, but I don't recall ever seeing an issue for it.
Comment: Thank you! I had the hook_module_implements_alter part working but I couldn't figure out how to remove the existing layout builder help. This works!


Centralizar texto com Card

Question: Preciso alinhar esse titulo e paragrafo junto com a Imagem abaixo, já utilizei, margin-left, padding, display:Inline-block; display: inline-flex; e outros recursos, mais nenhum funcionou.. não quero utilizar o Margin-left: 20px; porque em outras dimensões não ira acompanhar o texto com a imagem..

.card{
  width: 300px;
  height: 350px;
  background-color: #333;
  border-radius: 10px;
  outline: 1px solid rgba(255, 255, 255, .5);
  outline-offset: -8px;
  box-shadow: 3px 3px 10px rgba(0, 0, 0, .1);
  position: relative;
  overflow: hidden;
  grid-template-columns: 100px 100px 100px 100px;
  display: inline-block;
  margin: 0 20px 0 0;
}

@media screen and (max-width: 770px ) {
  .card{
    width: 22em;
    display: flex;
    margin: 0 auto 20px;
  }
}

.card-image{
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform .75s;
}

.card:hover .card-image{
  transform: scale(1.15);
}

.card-title{
  position: absolute;
  left: 15px;
  font-family: Arial, Helvetica, sans-serif;
  bottom: 15px;
  font-size: 17px;
  padding: 4px 10px;
  text-shadow: 0 0 1px rgba(0, 0, 0, .5);
  color: white;
  border: 2px solid rgb(255, 255, 255);
  border-radius: 15px;
}

.card-title:hover{
  color: rgb(228, 228, 228);
  transition: .30s ease-in-out;
  text-decoration: none;
}

  .titulo h2 {
  color: white;
  font-family: 'Rye', cursive;
  }

  .titulo p {
  color: white;
  font-family: Arial, Helvetica, sans-serif;
  }

TATTOO

Fazemos todos os estilos de tatuagem.

                VEJA MAIS

                VEJA MAIS

BODY PIERCERS

Tipos de perfurações.

            VEJA MAIS

            VEJA MAIS

Answer: Olá, você pode fazer de duas formas:
Ou você coloca uma largura automática no teu container (para acompanhar o tamanho dos conteúdos):

.container{
  width:fit-content;
}

Ou você centraliza o conteúdo interno do container:

.container{
  text-align:center;
}

Veja nos exemplos:
Com fit-content:

Com text-align:

Centralizar texto com Card


how to deal with undefined / unprovided content-type in REST

Question: Now that content-type header (defining the request content type) is optional according to   HTTP 1.1 specification:

Any HTTP/1.1 message containing an entity-body SHOULD include a
Content-Type header field defining the media type of that body. If and
only if the media type is not given by a Content-Type field, the
recipient MAY attempt to guess the media type via inspection of its
content and/or the name extension(s) of the URI used to identify the
resource. If the media type remains unknown, the recipient SHOULD
treat it as type "application/octet-stream".

my question is
1- if content-type is defined in the REST service swagger file, but the request sent doesn't contain a content-type, shall I consider this a correct request or bad request
2- if content-type is not defined in the REST service swagger file, but the request sent contains a content-type, shall I consider this a correct request or bad request
3- if content-type is defined in the REST service swagger file, but the request sent contains a different content-type, shall I consider this a correct request or bad request (I believe not)
Answer: 1- Does the Content-Type header in the request specify the content type of the request body or the desired content type of the response body?
Answer -> Content-Type header in the request specify the content type of the request body only
2- Supposing the Content-Type header specifies the content type of the request body, is there another header to specify the desired content type of the response body?
Answer -> you have to use:
Accept: <MIME_type>/<MIME_subtype> | <MIME_type>/* | /
to specify the desired content type of the response body
Will the response to my request have a Content-Type header or another header to specify the content type of its body (response body)?
Answer -> Content-Type: Indicates the media type (e.g. text/html or application/json) of the response sent to the client by the server, this will help the client in processing the response body correctly.
Comment: thanks for the hint, however I was mainly asking about the discrepancy between the request content-type defined in the swagger and the one passed in the actual request ... rather than the content-type of the request vs the content-type of the response, I edited the question for more clarity
Answer: DEFAULT MEDIA TYPE
I prefer to have a default media type when possible. For many endpoints this is JSON. If no content-type header is provided then either fail with a clear message as below:
status: 400
{
  "code": "invalid_content",
  "message": "The content of the request was supplied incorrectly"
}

Alternatively attempt to process the request as JSON. If this fails, also return the same error message.
MULTIPLE CHOICES
If an endpoint allows a user to upload an image, there may be no default. In such a case failing as above makes most sense.
CONSUMER FOCUS
More important than any technical concerns is a consumer focus towards REST clients. This includes documentation and a clear code example on how to call the endpoint, and any error responses that may be returned.
Some API stacks reject requests without a content-type but may also return a poor error response that confuses and blocks client developers.
DESIGN CHOICES
As the HTTP spec indicates, the solution is up to the implementer of the REST endpoint. My personal preference is to completely ignore the content-type header in my code unless there are multiple choices.
Even if the default media type becomes suboptimal in future, I could handle that, either by requiring clients to use a newer content-type or by releasing a new major version of my REST component that uses a different default media type. Changes to behaviour would be published to consumers in release notes.
Comment: `415` is probably the better error here: https://evertpot.com/http/415-unsupported-media-type
Comment: I cant make a default content-type to fall back to since the content-type by definition and according to my business must be optional , but i accepted the answer specifically for the point of returning it to the implementer


Incompatibilidade de CSS com jquery blockUI no IE 8

Question: Estou usando jquery 1.11.0 junto com o plugin jquery-blockui 2.66.0 e ao bloquear a tela, a div fica com fundo branco nos IE 8 e anteriores.
Seguem as imagens:

A chamada para o blockUI:
$.blockUI({
    message: "
Não houve resultado para o seu filtro.

Fechar
",
    timeout: 5000,
    onOverlayClick: $.unblockUI
});

Sei que devo fazer um CSS hack, mas não conheço bem front-end, alguém poderia me explicar como fazer para manter o comportamente igual à primeira imagem também no IE 8 e anteriores?
Como requisitado, segue a alteração de estilo do css:
$.blockUI.defaults.css = {
    border: "none",
    backgroundColor: "rgba(255, 255, 255, 0)",
    textAlign: "center",
    padding: 0,
    margin: 0,
    width: "30%",
    top: "40%",
    left: "35%",
    color: "#000000",
    cursor: "wait"
};

Comment: Usando seu código na [página de exemplo do plugin](http://malsup.com/jquery/block/) o fundo fica branco. Você deve estar substituindo o estilo padrão no CSS e por algum motivo isso não funciona no IE8. Poderia editar mostrando esses estilos?
Comment: @GustavoRodrigues Pelo que entendi o usuário quer o comportamento da primeira imagem e não da segunda o que implica realmente em mudar um pouco o CSS.
Comment: exatamente, quero o comportamento da primeira imagem.
Answer:  backgroundColor: "rgba(255, 255, 255, 0)",

Cores escritas como RGBA não são suportadas no IE8. Use isso:
 backgroundColor: "transparent",

Comment: Funcionou perfeitamente @GustavoRodrigues! Muito Obrigado cara!


a dataset to which a linear regression model is fitted& ^a and ^b are numbers. its means that there cannot be probability distributions for ^a and ^b?

Question: I have a dataset to which a simple linear regression model is fitted and ^a and ^b are numbers. Does this tells that there can not be probability distributions for ^a and ^b or i can not conclude that?
Answer: This depends a bit on your interpretation, but in a general sense no, you can not conclude that.
You think your data is generated by some probabilistic process, which you do not "observe" or know. For example, you collect some data, but either you can not collect all relevant data for all observations, or the observations that you have do not cover the space of what reality might be.
Let's say that data is $X$, but is only a subset of all possible data that either exists (and you don't have it), or that may exist (if things were different, for example if the sun was shining when you collect the data instead of it raining all over you!).
What that means is that your estimates $\hat{a}$ and $\hat{b}$ are functions of the data $X$. If your data were different, say $X'$, then you'd get different estimates $\hat{a}'$ and $\hat{b}'$.
So, in as much as your data is probabilistic - coming from some unknown process, your estimates are as well, because you derive them based on that data.
In practice, you may say that you observe some $y$, some $x$ and you know that there is also some $\epsilon$ you do not observe, so that for each observation
$$y = a+b x + \epsilon$$
And $\epsilon$ has some probabilistic distribution. Then clearly, your estimates of $\hat{a}$, say, are a function not only of $x$, but also of the $\epsilon$ you do not see. And therefore, $\hat{a}$ also has a probability distribution.
If you had a different $\epsilon$, you'd have a different $\hat{a}$.
And if you know that, for example, $\epsilon$ is normally distributed, and $x$ is something you can decide on, then (with some work) you'd even be able to show that $\hat{a}$ is also normally distributed.
Here is a yet another way to think about this.
Let's assume you do your regression and get some $\hat{a}$. Now, tomorrow you collect new data, and you run your regression again. Now you get another, different $\hat{a}$. And if you repeat that for many, many times, then all the different $\hat{a}$ you get form a distribution.
For frequentist statisticans, this is the sense of how $\hat{a}$ has a distribution.
For Bayesians, in contrast, it would encode what other values $\hat{a}$ might have had, and how certain you are about that.
Comment: thank you so much for your help!! i wanna ask and something else..for example if i have y=0.5x+7 as regression line and the model is fitted to 2 datasets, the likelihood functions and the solutions to the likelihood equations will be the same for the 2 datasets?
Comment: Note sure if I understand you. If y=0.5x+7, that is, $a$ and $b$ are fixed, then the likelihood function is the same as long you assume the same thing for your $\epsilon$ (or alternatively the distribution of $(y,x)$, depending on the approach of teaching).

However, note that if you fit it to two datasets, then this is essentially now one new dataset, right? If you fit it separately for two datasets, you'll likely get a different value for your parameters.


Why is Random.nextInt() %16 skewed while Random.nextInt(16) works perfectly fine?

Question: I am writing a Bukkit plugin that treats snowballs as paintballs. When I accidentally used:
(byte) (random.nextInt() % 16)

instead of
(byte) (random.nextInt(16))

I noticed that lower numbers appeared way more than higher numbers. Why does that happen?
Ex: Before:
00010
01200
06001
30010
00502

Ex: After:
74108
73447
98956
17386
26574

Comment: It's not at all clear how your code relates to your output. Can you provide a [mcve] that demonstrates the problem?
Comment: What research have you done? Did you create a histogram to see how the distribution happens? Did that correspond to your expectations? What hypothesis did you form to explain the behaviour? Do you think the byte cast might be relevant? Stack Overflow should be a last resort, not just a "hey that's curious -- let's ask them".
Comment: The numbers you show could not come from either expression, as those return integers in the range 0-15.
Comment: @JimGarrison It was an example of 0-9.
Answer: random.nextInt() can also return negative values, and my program was treating negatives as zero, doubling tripling the chance for a zero to occur.
Comment: Nice catch! And yeah, the `%` operator can trick people - it doesn't mean "Modulo", which a lot of people think it does, it means "Remainder". The difference is that Remainder can be negative, while Modulo will always be positive.


Conditionally fetching associated entity avoiding SELECT N+1 problems

Question: Suppose I have the following domain:
public class Company
{
    public long Id;
}

public class EmployeeDetailsInCompany
{
    public long Id;
    public Company Company;
}

public class Employee
{
    public long Id;
    public List<EmployeeDetailsInCompany> EmployeeDetailsInCompany;
}

public class Position
{
    public long Id;
    public Employee Employee;
    public Company Company;
}

(Please note that this is a very simplified version to make the problem easier to understand.)
Basically I want to access the EmployeeDetailsInCompany of the Employee I have in a Position entity. Currently I have to loop through the list I have on Employee and find the EmployeeDetailsInCompany whose Company.Id match that of my Company entity. This is because a Position is only valid for a certain Employee on a certain Company, so that's where the EmployeeDetailsInCompany gets in.
The best option here would be to have an association between Position and EmployeeDetailsInCompany, but that's not possible because the data on that table can change (e.g. a company might decide to wipe out all of its employees details and load new data again).
Is it possible to rewrite those associations so I don't fall into SELECT N+1 problems (which is happening now that I have to loop through the list)? How could I change it to make it easier to locate the details I want without much hassle?
I have considered creating a EmployeeDetailsInCompany on Position that would be mapped using a formula, but that would give me a readonly column and I'm trying to avoid HQL.
Answer: Read the chapter on improving performance in the reference documentation if you haven't done so. I think especially the section on batch fetching is relevant. It means that NHibernate can fetch several potentially interesting database rows in one go, when you ask for one of them.
Another option is to write a specialized query that would generate SQL to let the DBMS do the work.
Comment: Batch fetching solves my problem since a single `Employee` is unlikely to have a lot of corresponding `EmployeeDetailsInCompany`.


Z-test for a population proportion

Question: I'm asked to carry out a Z-test for a population proportion on whether a die is fair. The only information I'm given is that "A die fell showing a "four" on $124$ occasions out of $500$".
I'm not sure how to do this, but after giving it a try, this is what I have:
$H_0: p = 0.1667$ (die is fair, outcomes are equally likely)
$H_1: p \neq 0.1667$
Here, I will assume that the significance level is $\alpha = 5\%$
Using the Z-test statistic formula, I have that $Z_{\text{observed}} = 10.9$
Is this right? Would really appreciate some help.
Comment: Which formula are you using for your calculation. As a hint, you are testing a single proportion against an assumed value.
Comment: @mfloren hi, I added a picture of the formula into the question. Regarding your hint, so do I just do it like a normal Z-test?
Answer: If the die is fair, the proportion of $4$'s to expect is $1/6=0.1667$. Is your observed proportion of $p_{\text{ obs}}=124/500=0.248$ far enough from it to exclude the null hypothesis, $H_0: p_{\text{ true}}=0.1667$, based on the observed proportion at a $5\%$ significance level?
You can investigate this in two different ways:

Using asymptotic calculations (normal approximation or Z test):

$$\text{test statistic}= \frac{p_{\text{ obs}} - p_{\text{ true}}}{\sqrt{\frac{p_{\text{ true}}\,(1\,-\,p_{\text{ true}})}{n}}}=\frac{0.248-0.1667}{\sqrt{\frac{0.1667\times(1-0.1667)}{500}}}=4.88$$

Using the binomial test:

$$\Pr(\text{fours} \geq 124)=  \sum_{x=124}^{500} {500\choose x} \,0.1667^x\, (1-0.1667)^{500-x}$$
a calculation that explains the reliance on the first method (particularly before modern computers).

Z-test for a population proportion


Average of a tail of a normal distribution

Question: I have a sample that is pretty normally distributed with a mean greater 0. Is there any way to get a closed form estimate for the mean of all values that are less than 0? In other words, given a mean, variance and a variable x, can I estimate the average of all values that are smaller than x?
Comment: See [truncated normal distribution](http://en.wikipedia.org/wiki/Truncated_normal_distribution).
Comment: Not in the usual sense of *closed form*; if you admit the use of the cdf of a standard normal, then, the answer is yes.
Answer: Cyan offered a link that answers the question but since the question remains without an actual answer, I'll put one in.
While not strictly "closed form" by the usual definitions, I expect people doing statistical work will mostly want to admit the normal cdf (or the error function, which would serve the same purpose) into what they call "closed form".
Given $X\sim N(\mu,\sigma^2)$,
$$E(X\mid X<b)=\mu -\sigma \frac {\phi (\frac{b-\mu}{\sigma})}{\Phi (\frac{b-\mu}{\sigma})}$$
where $\phi$ is the standard normal density and $\Phi$ is the standard normal cdf.
For the present problem, $b=0$, giving us:
$$E(X\mid X<0)=\mu -\sigma \frac {\phi (\frac{-\mu}{\sigma})}{\Phi (\frac{-\mu}{\sigma})}$$
(An expression for the variance can be found at the above link.)