How to interpret 3-way interaction with one continuous variable in mixed model

Question: I have problems interpreting the direction of the effects in my model. Can you help me with this?
I conducted an experiment which includes

between subject factor:
group=2 (coded as 0-1)
within subject factor:

stimulus type=3 (coded as -1 0-1)
empathy questionnaire which I centred (subtracted the mean). Participants could answer 1-4 on each item and I calculated their mean answer.
another questionnaire which I centred (subtracted the mean)

The depenendent variable is categorical: yes/no (0-1)
The SPSS syntax I used is shown below:
MIXED in_team_yes_no BY stimulustype group WITH empathy PT_centred
  /CRITERIA=CIN(95) MXITER(100) MXSTEP(10) SCORING(1) SINGULAR(0.000000000001) HCONVERGE(0, ABSOLUTE) LCONVERGE(0, ABSOLUTE) PCONVERGE(0.000001, ABSOLUTE)
  /FIXED=stimulustype group empathy stimulustype*group stimulustype*empathy group*empathy stimulustype*group*empathy PT_centred stimulustype*PT_centred group*PT_centred stimulustype*group*PT_centred | NOINT SSTYPE(3)
  /METHOD=ML
  /PRINT=COVB DESCRIPTIVES  SOLUTION TESTCOV
  /RANDOM=INTERCEPT | SUBJECT(id) COVTYPE(VC)
  /EMMEANS=TABLES(OVERALL)
  /EMMEANS=TABLES(stimulustype) COMPARE ADJ(SIDAK)
  /EMMEANS=TABLES(group) COMPARE ADJ(SIDAK)
  /EMMEANS=TABLES(stimulustype*group) .

In the output, there is an interaction between group*stimulus and type * empathy. But what is significantly larger versus what? I hope you can clarify this for me.
This is part of the output:
**Type III Tests of Fixed Effectsa**

stimulustypeNumerator df=2;Denominator df=175.999999999999;F=25.1625067300411;Sig.=2.44708998141032E-10;=;

groupNumerator df=1;Denominator df=88.0000000000013;F=0.182104461000037;Sig.=0.670613087293204;=;

empathyNumerator df=1;Denominator df=88.0000000000006;F=2.64490681880741;Sig.=0.107458165008125;=;

stimulustype * groupNumerator df=2;Denominator df=176.000000000002;F=0.393575958791748;Sig.=0.675232333852088;=;

stimulustype * empathyNumerator df=2;Denominator df=175.999999999999;F=0.436679732184867;Sig.=0.646876527043373;=;

group * empathyNumerator df=1;Denominator df=88.0000000000007;F=0.0205898398771826;Sig.=0.886230015228424;=;

stimulustype * group * empathyNumerator df=2;Denominator df=176.000000000002;F=3.85067166016453;**Sig.=0.023**0796672084849;=;

PT_centredNumerator df=1;Denominator df=88.0000000000006;F=0.780733693066422;Sig.=0.379324440222066;=;

stimulustype * PT_centredNumerator df=2;Denominator df=176.000000000002;F=0.0268007378853535;Sig.=0.973559187279457;=;

group * PT_centredNumerator df=1;Denominator df=88.0000000000007;F=0.265321415628692;Sig.=0.60777909887368;=;

stimulustype * group * PT_centredNumerator df=2;Denominator df=176.000000000002;F=0.357575654993585;Sig.=0.699876675215139;=;

Table: Estimates of Fixed Effects (this is output from the same model)
[stimulustype=-1];Estimate=3.29244254001684;Std Error=0.225268732947286;df=216.95359688355;t=14.6156215154248;Sig.=3.9122956206142E-34;

[stimulustype=0];Estimate=3.11592342177773;Std Error=0.225268732947286;df=216.95359688355;t=13.8320280005609;Sig.=1.2853156112195E-31;

[stimulustype=1];Estimate=2.18642210821693;Std Error=0.225268732947286;df=216.95359688355;t=9.70583924191808;Sig.=9.98676090898553E-19;

[group=.00];Estimate=-0.0871216158027804;Std Error=0.330560977978059;df=216.953596883549;t=-0.263556867285657;Sig.=0.79237155076331;

[group=1.00];Estimate=0b;Std Error=0;df=;t=;Sig.=;

empathy;Estimate=1.17744019177937;Std
Error=0.563748889564515;df=216.953596883548;t=2.08858981999755;Sig.=0.0379111000598545;

[stimulustype=-1] * [group=.00];Estimate=0.322580523902738;Std Error=0.382857667976268;df=176;t=0.842559914257049;Sig.=0.400618137515222;

[stimulustype=-1] * [group=1.00];Estimate=0b;Std Error=0;df=;t=;Sig.=;

[stimulustype=0] * [group=.00];Estimate=0.253441749589722;Std Error=0.382857667976268;df=176;t=0.661973811127722;Sig.=0.508853817603762;

[stimulustype=0] * [group=1.00];Estimate=0b;Std Error=0;df=;t=;Sig.=;

[stimulustype=1] * [group=.00];Estimate=0b;Std Error=0;df=;t=;Sig.=;

[stimulustype=1] * [group=1.00];Estimate=0b;Std Error=0;df=;t=;Sig.=;

[stimulustype=-1] * empathy;Estimate=-1.34747175897676;Std
Error=0.65293727802683;df=176;t=-2.06370780827342;Sig.=0.0405131556011519;

[stimulustype=0] * empathy;Estimate=-0.940798167490195;Std Error=0.65293727802683;df=176;t=-1.44087066116561;Sig.=0.151397919015566;

[stimulustype=1] * empathy;Estimate=0b;Std Error=0;df=;t=;Sig.=;

[group=.00] * empathy;Estimate=-1.31554938904041;Std Error=0.75223224868924;df=216.953596883547;t=-1.74886066282421;Sig.=0.0817293498796308;

[group=1.00] * empathy;Estimate=0b;Std Error=0;df=;t=;Sig.=;

[stimulustype=-1] * [group=.00] * empathy;Estimate=2.10908428142564;Std Error=0.87123981260977;df=176;t=2.42078501337989;**Sig.=0.01**65032903786237;

[stimulustype=-1] * [group=1.00] * empathy;Estimate=0b;Std Error=0;df=;t=;Sig.=;

[stimulustype=0] * [group=.00] * empathy;Estimate=2.07833508789358;Std Error=0.87123981260977;df=176.000000000001;t=2.38549140869492;**Sig.=0.01**81184114665423;

[stimulustype=0] * [group=1.00] * empathy;Estimate=0b;Std Error=0;df=;t=;Sig.=;

[stimulustype=1] * [group=.00] * empathy;Estimate=0b;Std Error=0;df=;t=;Sig.=;

[stimulustype=1] * [group=1.00] * empathy;Estimate=0b;Std Error=0;df=;t=;Sig.=;

PT_centred;Estimate=0.155115894939361;Std Error=0.589136705351013;df=216.953596883549;t=0.263293550597806;Sig.=0.792574217512385;

[stimulustype=-1] * PT_centred;Estimate=0.314817967290445;Std Error=0.682341595519122;df=176.000000000002;t=0.461378830424273;Sig.=0.645096534364194;

[stimulustype=0] * PT_centred;Estimate=0.489619040733416;Std Error=0.682341595519122;df=176.000000000002;t=0.717557076907961;Sig.=0.473981736575375;

[stimulustype=1] * PT_centred;Estimate=0b;Std Error=0;df=;t=;Sig.=;

[group=.00] * PT_centred;Estimate=0.134214472802144;Std Error=0.813980628541158;df=216.953596883548;t=0.164886568667718;Sig.=0.869186792494091;

[group=1.00] * PT_centred;Estimate=0b;Std Error=0;df=;t=;Sig.=;

[stimulustype=-1] * [group=.00] * PT_centred;Estimate=-0.570241358210639;Std Error=0.942757149156938;df=176.000000000001;t=-0.604865588895908;Sig.=0.546047353847579;

[stimulustype=-1] * [group=1.00] * PT_centred;Estimate=0b;Std Error=0;df=;t=;Sig.=;

[stimulustype=0] * [group=.00] * PT_centred;Estimate=-0.767649075872404;Std Error=0.942757149156938;df=176.000000000001;t=-0.814259617716902;Sig.=0.416596578011685;

[stimulustype=0] * [group=1.00] * PT_centred;Estimate=0b;Std Error=0;df=;t=;Sig.=;

[stimulustype=1] * [group=.00] * PT_centred;Estimate=0b;Std Error=0;df=;t=;Sig.=;

[stimulustype=1] * [group=1.00] * PT_centred;Estimate=0b;Std Error=0;df=;t=;Sig.=;

a. Dependent Variable: in_team_yes_no.
b. This parameter is set to zero because it is redundant.

What do these t-tests mean, for example the significant three-way interaction which I made bold? What t-tests are conducted exactly? What comparisons are made?
Apart from the interpretation, how should I report these results?
Comment: You can put a link to your image, we will convert this as an inline image for you.
Answer: It's not exactly clear where these effect estimates in your output are coming from. I'm unfamiliar with SPSS, so bear with me.
I will assume that SPSS has treated all the 0 levels of your factors as "referent" levels. So the intercept represents the mean effect among people having group=0, stimulus=0, and empathy=0. I'm also assuming that empathy (or empathy score) is treated as "continuous".

I think the first model is testing for the global interaction between empathy and stimulus. Which is why it's a 2-df numerator F-test. The full model has the additional parameters for levels where [stimulus==-1]*empathy and [stimulus==1]*empathy, hence a difference of parameters of tow.
I think the second model is a pairwise test for the individual parameters I mentioned above. In the full model, we have three possible effects for empathy stratified by stimulus whereas in the reduced model there is only one. We examine the differences of empathy across each strata empirically, but there are only two t-tests available to us to describe the pairwise disparity in such effects relative to the null model.
I do not understand your output. It's unclear to me whether there were insufficient samples to estimate effects in these groups, or whether SPSS has determined some tests as redundant as before (but is unable to report them).

At any rate, you want to focus on global tests, as was the case in model 1, because the scientific question when testing for interaction is stated as follows, "Is there any stratum in the sample for which the estimated effect of our predictor of interest is significantly different than the stratified effect estimate?" This leads us to the proper interpretation for the p-value of the F-test reported above. You can follow this up by reporting the most significantly different estimated difference in effects based on the pairwise comparisons, but this is unreliable and can be confusing.
I should mention again that, if you're interested in the test of 3-way interaction, then the F-test should have 1 numerator degree of freedom. This is because you should have all 2-way interactions included in the null model. Or perhaps you're interested in whether there are any 2-way interactions instead (giving a 5 numerator degrees of freedom F test). It begs the question whether you're asking for the test you really want here.
Comment: Dear Adam, thank you for your reply! I made some changes in my post. It is a shame I can't upload an image. Do you think for stimulus -1 will be used as the reference you are talking about? Or you think both 'one' and 'minus one' are tested against zero? Maybe my model is incorrect in that case. -1 refers to low threatening faces, 0 to neutral, 1 to highly threatening face stimuli. I have 88 participants equally divided over the two groups.


timevarying effects in regression vs state space models

Question: Consider the following regression model:
$z_t = \alpha + trend_t + seasonality_t + \epsilon$
$\alpha \sim HalfNormal(1)$,
$trend_t = \mu t$ where as $\mu \sim Normal(0, 1)$
$seasonality_t = \sum_k^K [\nu_k S_k(t) + \lambda_k C_k(t)]$
$\nu_k \sim Normal(0, 1), \lambda_k \sim Normal(0, 1)$
where as $S_k(t) = sin(\frac{2\pi kt}{7})$ and $C_k(t) = cos(\frac{2\pi kt}{7})$
That can be estimated with MCMC sampling which also allows us to incorporate nonlinear parameters if we want to.
Why would one want to use a state space formulation of an process instead of adding time-varying effects like above in a model?
I see some negatives, it makes it much harder to incorporate nonlinear parameters, we need particle filters..
The positive i see is that the parameters are allowed to vary over time, even if they do this in this case aswell they are not stochastically evolving over time, i assume if we would try to do this with the above approach we would have far more parameters.. is this the sole reason?
Answer: A couple of thoughts on this:

I wouldn't describe any of the effects in this regression model as time-varying. As you correctly point out in the last paragraph, this is a deterministic seasonal pattern, consisting of a linear trend plus trigonometric components.

Are the priors on the model coefficients $\alpha, \mu, \{ \nu_k \}, \{ \lambda_k \}$ essential? Given enough observations, you could just estimate them with OLS.

I agree that a state-space model would give you more flexibility. Allowing time-varying coefficients is one advantage, but there are others:

Your starting point would be a linear state-space model, so you don't need particle filters. You can implement this very easily (and efficiently) with the Kalman filter.

Even if you assume that your model coefficients are fixed, the Kalman filter would give you estimates of these coefficients at each time point using only the data that has already been observed. This is particularly useful if you're interested in 1-step-ahead forecasts.
Comment: As for the last bulletpoint, lets say i am interested in longer forecasts such as 30-steps, would this change this scenario. Secondly, if i assume the model coefficients are fixed, isnt it strange to then model them stochastically thus allowing for changes w.r.t time? just clarify this and i accept and upvote. thanks
Comment: Suppose that $\mu \sim \mathcal{N}(0,1)$, as in your model. This is a static parameter, so we have $\mu_t=\mu$ for all $t$. The Kalman filter will give you the estimate $\hat{\mu}_t = \mathbb{E}(\mu|z_1, \ldots, z_{t-1})$ at every time point. In other words, the coefficient itself does not change, but our _estimate_ of it changes as we observe more data.
Comment: The KF will give you the 1-step-ahead forecast by default, but it's straightforward to forecast more steps into the future with this sort of linear model.
Comment: but isnt this the same as in a normal regression context given that we recompute the estimates every timestep -> now this obviously decrease the computational efficiency drastically.


Doubt regarding the variance and covariance matrix

Question: I have a general doubt regarding the variance and covariance matrix. I know that the general structure of variance and covariance matrix is such that it's diagonal elements represents the variance and non diagonal elements represents the covariance. Also, for a $2×2$ matrix, the non diagonal elements will represent the same covariance term. The diagonal terms cannot be negative as they represents variance term. Then, my doubt is why the following cannot be a variance covariance matrix, since it satisfies all the properties which is applicable for such matrices:
$\begin{pmatrix}
1 &2 \\
2  & 2
\end{pmatrix}$
Thanks.
Answer: If $\mathrm{Cov}(X,Y)=2$, $\mathrm{Var}(X)=1$, $\mathrm{Var}(Y)=2$ then
$$E(XY)-E(X)E(Y)=2$$
$$E(X^2)-E(X)^2=1$$
$$E(Y^2)-E(Y)^2=2$$
Now the means can be anything without affecting the variance, so let' assume $E(X)=E(Y)=1$. Then we get
$E(XY)=3$, $E(X^2)=2$, $E(Y^2)=3$. But then $E((X-Y)^2)=2-2\cdot 3+3<0$ which is impossible.

If you're wondering where that came from, it was inspired by a proof of the Cauchy-Schwartz inequality. (In general the key phrase is that covariance matrices must be positive semidefinite.) Note $$0\le E[(X+aY)^2]=1+\mu_X^2+2a(2+\mu_X\mu_Y)+a^2(2+\mu_Y^2)=(\mu_X+a\mu_Y)^2+1+4a+2a^2$$
(where $\mu_X=E(X)$ and $\mu_Y=E(Y)$).
But if $a=-\mu_X/\mu_Y$ and $\mu_Y=1=\mu_X$, then this is impossible.
Answer: A real matrix is a covariance matrix if and only if it is symmetric positive semi-definite.  A consequence of this is that all diagonal elements must be non-negative.  So diagonal elements being non-negative is necessary for a matrix to be a covariance matrix, but it is not sufficient.
Indeed, to be a covariance matrix, the matrix must be symmetric, and have all eigenvalues non-negative.  The eigenvalues are the variances in the independent coordinate frame (i.e., after the matrix has been rotated to be diagonal).  So for a real symmetric matrix to be a covariance matrix, it is necessary for all of its eigenvalues to be non-negative (and it does not suffice for all diagonal elements, i.e., variances, to be non-negative, unless the matrix is diagonal, in which case the variances, i.e., the diagonal elements, are the eigenvalues).
Comment: I realized after almost 3 years of asking this question that this is more elegent approach. Thank you. It went over my head back then


Image classification and machine learning (not deep learning) algorithms

Question: Do you know any algorithms and methods that may be successful in image classification? I've read about some combined method using SVM and deep learning, however, I would like to know whether is it possible also to utilize any advantages from approaches other than deep learning.
Comment: What about Decision trees?
Answer: Support Vector Machines
Support vector machines are supervised learning models with associated learning algorithms that analyze data used for classification and regression analysis. Please note that the SVM is a machine learning algorithm and not deep learning. It can be used for image classification.
Advantages:

It  provides a good generalization  capability.
Reduction in computational complexity.
It gains flexibility in the choice of the form of the threshold.

Decision trees
Decision trees have influenced a wide area of machine learning, covering both classification and regression.
A decision tree is drawn upside down with its root at the top. The end of the branch that doesn't split anymore is the decision/leaf, the classification step.
Advantages:

1.Can handle non parametric training data.
Does not require extensive design and training.
Simple and computational efficiency is good.

It can be seen that the decision tree above may be utilized for image classification.


WSO2 VFS transport process file that not complete

Question:
I write a vfs proxy to route files from one folder to another. But recently I'm facing a problem.
The vfs transport seems to process a file that not yet completed (I copy a file to the source path), so for example I copy a 18mb file to the source path but when the file is copied just 1mb its already processed by the vfs transport. In the end, only that 1mb part of file is sent to the target path. So, how can I make my vfs proxy to wait the file to be copied completely then processed it?My proxy look like this
<proxy name="XXX" transports="vfs" startOnLoad="true" trace="disable">
  <description/>
  <target>
     <inSequence>
        <log level="custom">
           <property name="File" value="Moved"/>
        </log>
     </inSequence>
  </target>
  <parameter name="transport.vfs.ActionAfterProcess">MOVE</parameter>
  <parameter name="transport.PollInterval">1</parameter>
  <parameter name="transport.vfs.FileURI">file:///SourcePath</parameter>
  <parameter name="transport.vfs.MoveAfterProcess">file:///TargetPath</parameter>
  <parameter name="transport.vfs.FileNamePattern">.*.*</parameter>
  <parameter name="transport.vfs.ContentType">text/plain</parameter>

Answer: add this property and go through the wso2 docs for large file need to modify axis2 files streaming property
<property name="transport.vfs.Streaming" value="true" scope="default"/>

further assistance go for docs
http://docs.wso2.org/display/ESB480/VFS+Transport


Blob images are not pushed to an array in the right order

Question: I have function toBlobConverter which is sent to a for loop to cut an image into 9 pieces but the images are not arranged in right order. Happy to hear from you.
const toBlobConverter = async (x, y) => {
  var canvas = document.createElement("canvas");
  canvas.width = widthOfOnePiece;
  canvas.height = heightOfOnePiece;
  var context = canvas.getContext("2d");
  context.drawImage(
    image,
    y * widthOfOnePiece,
    x * heightOfOnePiece,
    widthOfOnePiece,
    heightOfOnePiece,
    0,
    0,
    canvas.width,
    canvas.height
  );
  async function operation() {
    return new Promise(function (resolve, reject) {
      canvas.toBlob(resolve);
    });
  }
  const compOperation = await operation();
  console.log(compOperation);
  return imagePieces.push({
    url: URL.createObjectURL(compOperation),
    blob: compOperation,
  });
}
for (var x = 0; x < 3; ++x) {
  for (var y = 0; y < 3; ++y) {
    toBlobConverter(x, y)
  }
}

Answer: Right now, the asynchronous operations are in a race with each other. They're all started one after another by your for loops, and then they complete in whatever order they complete in, which is what determines where they end up in the array. Nothing waits for toBlobConverter to finish its asynchronous work.
If you want them to do their work in parallel, you can use Promise.all to get the results in the order you asked for them. That will require reorganizing your code slightly but arguably for the better since it doesn't require toBlobConverter to "magically" fill in imagePieces; see the *** comments:
const toBlobConverter = async (x, y) => {
  var canvas = document.createElement("canvas");
  canvas.width = widthOfOnePiece;
  canvas.height = heightOfOnePiece;
  var context = canvas.getContext("2d");
  context.drawImage(
    image,
    y * widthOfOnePiece,
    x * heightOfOnePiece,
    widthOfOnePiece,
    heightOfOnePiece,
    0,
    0,
    canvas.width,
    canvas.height
  );
  async function operation() {
    return new Promise(function (resolve, reject) {
      canvas.toBlob(resolve);
    });
  }
  const compOperation = await operation();
  console.log(compOperation);
  // *** Return the entry rather than pushing it
  return {
    url: URL.createObjectURL(compOperation),
    blob: compOperation,
  };
}

// *** Build an array of the promises in the  order you want
const promises = [];
for (var x = 0; x < 3; ++x) {
  for (var y = 0; y < 3; ++y) {
    promises.push(toBlobConverter(x, y));
  }
}

// *** Wait for the operations to complete
Promise.all(promises)
.then(results => {
    // *** `results` is in the same order `promises` was
    imagePieces.push(...results);
})
.catch(error => {
    // Handle/report errors
});

If you want them done one after another (in series), just put your for loops in an async function and await the result of toBlobConverter:
(async () => {
    for (var x = 0; x < 3; ++x) {
      for (var y = 0; y < 3; ++y) {
        await toBlobConverter(x, y)
      }
    }
})()
.catch(error => {
    // Handle errors...
});

For what it's worth, when writing modern code, I strongly recommend not using var. Anywhere. :-) Use let or const.


If $\|f_n\| \leq c$ and $f_n \rightarrow f$ in weak-star topology, then $\|f\| \leq c$?

Question: Let $E=(E,\|\cdot \|_E)$ be a Banach space over $\mathbb{C}$. Consider $E'$ the dual of $E$, with norm $\|\cdot\|_{E'}$. Let $(f_n)_{n \in \mathbb{N}} \subset E'$ such that $f_n \rightarrow f$ in the weak-star topology of the $E'$, for some $f \in E'$.
Question. If there exists $c>0$ such that
$$\|f_n\|_{E'} \leq c, \; \forall \; n \in \mathbb{N} \tag{1}$$
then $$\|f\|_{E'} \leq c? \tag{2}$$
I think if $f_n \rightarrow f$ in the strongly topology of the $E'$, then $(2)$ holds. But I wonder if the same is true in the weak-star topology. Or $(2)$ also holds, since $\|\cdot\|_{E'}$ is defined via $\sup$ and $f_n \rightarrow f$ in the weak-star topology implies
$$f_n(x) \rightarrow f(x), \; \forall \; x \in E, $$
(strongly) in $\mathbb{C}$?
Comment: Surely $|f(x)| \le c$ is sufficient to conclude that $\|f\| \le c$?
Answer: You do not need heavy machinery like Banach-Alaoglu.
Let $x \in E$ be arbitrary. From (1) you get
$$|f_n(x)| \le c \, \|x\|_E.$$
Due to weak-star convergence, you can pass to the limit and get
$$|f(x)| \le c \, \|x\|_E \qquad\forall x \in E.$$
By definition of the dual norm
$$\| f \|_{E'} = \sup\{ |f(x)| \;\mid\; \|x\|_E \le 1\} \le c.$$
Answer: Yep! The closed ball $B_{E'}[0; c]$ is weak$^*$ compact (Banach-Alaoglu), and hence weak$^*$ closed, and thus $E' \setminus B[0; c]$ is weak$^*$ open. If $f \in E' \setminus B[0; c]$, then by definition of sequence convergence, the sequence $f_n$ must eventually lie in $E' \setminus B[0; c]$, i.e. $\|f_n\| > c$ for sufficiently large $n$, contradicting our assumption.


Pycharm stopped working in remote interpreter

Question: I have been using remote interpreter all the times before, but suddenly it shows failed error message: can't run python interpreter: error connecting to remote host:
I am using SFTP, and I have tried "Test SFTP connection", got success message with the same host.
I am wondering how do I see verbose message in the remote debugging connection.
I am using PyCharm 2017.2 professional.
Comment: Try upgrading to PyCharm 2017.3 EAP 4, they've enhanced and refactored remote SSH debuggers .. you might have success. https://blog.jetbrains.com/pycharm/2017/10/pycharm-2017-3-eap-4
Answer: Solve the problem. There are two places to edit the same remote interpreter. One is from Default Setting-> Project Interpreter -> Setting Icon -> More -> edit icon, another is from Tools -> Deployment -> Configuration. The settings in both places need to be correct for the same remote interpreter.
For some reason, the password in my first location was cleared.


How do I express this hypothesis using symbols?

Question: I'm just making this up to understand the rules...
Claim: People wearing roller blades can get to places in lesser time than those who don't. (Assuming on foot)
Now, I'd like to express this using symbols (that's what I call them, unless there's another name for this).
I'm guessing: If there's no problem with the symbol to be used, I'd like to use t as the time taken to walk. So my $H_0$ would be that even with roller blades on, they would need the same amount of time.
Based on this, is it correct to express the following?
$H_0$ : $\mu$ = t
Or is there a better way to express this?
Please feel free to correct me - I really want to learn this!
Thanks!
Answer: For simplicity, let us fix definite start and end points to the hypothesis, so in words the hypothesis might be

"People traveling from point A to point B by roller blade arrive sooner than those who walk."

Probably the simplest way to express this hypothesis is to add the qualifier "... on average".
Then the hypothesis becomes a definite statement about the conditional expectation of the travel time, given the mode of transportation.
To proceed you would then introduce a symbol for the travel time, say $T$, and a symbol for the mode of travel. If we are assuming that all travelers either use roller blades or they walk, then we can represent the travel mode by a dummy variable such as
$$R=\begin{cases}1 & \text{if roller blade} \\
0 & \text{if walk} \end{cases}$$
Then the hypothesis becomes

$$\mathbb{E}[\,T\mid R=1\,] < \mathbb{E}[\,T\mid R=0\,]$$

where $\mathbb{E}[\,x\mid a\,]$ should be read as "the expected value of $x$, given $a$".
Usually the symbol $H_0$ that you use is reserved for the null hypothesis, which is typically the negation of the hypothesis of interest. So for example in this case, $H_0$ might be "roller blading is no faster than walking".

One last point: The hypothesis as expressed in the equation above is not actually empirically testable, because the theoretical expectations cannot be literally computed. So usually a next step is to use the theoretical hypothesis to generate predictions about what would be observed in a data-set (sample) of actually observed $(T,R)$ pairs.
Comment: For the first: In the hypothesis (gray box), change $<$ to $geq$ (this is literally the "negation of the hypothesis of interest"). For the second: I am not really a statistician, so I tend to use whatever symbols are convenient! (I mentioned $H_0$ because that one is pretty standard in this context; AFAIK for the various ["t" statistics](https://en.wikipedia.org/wiki/T-statistic) the lower-case $t$ is used ... but that is also used for ["time" series](https://en.wikipedia.org/wiki/Time_series) of course!)
Comment: That is one of the most beautiful explanations I've seen in a long time on the entire stackexchange. Thanks! I do have 2 questions on the what you've mentioned. First, how do I express the statement **roller blading is no faster than walking** as a symbols. Second, I thought that **T** is reserved for other things like the T-Score. So are we really free to use that symbol? Thanks a again!


"Best" Submultiplicative / Subordinate norm?

Question: I have $y = Ax$ where x, y are vectors and $A$ is a matrix.
I want to get the best $K$ such that $||y|| \leq K||x||$. Ideally, $K$ is a matrix norm. Especially, $K$ can be a subordinate matrix norm. I tried with Spectral norm and Frobenius norms and they provide a very loose bound for $K$. Are there studies in this direction?
I have also tried the largest sigular value of A and that is a worse bound too.
If that helps in my case A can be expressed as $(I-BC)^{-1}$ where $B$ and $C$ are symmetric metrices.
Answer: Let $\lVert A \rVert_\epsilon := \lVert D^{-1} T^{-1} A T D \rVert_\infty$ where $D := \operatorname{diag}\{\delta, \delta^2, \dots, \delta^n\}$ for some $1 > \delta > 0$ and $T$. It is easy to check that $\lVert \cdot \rVert_\epsilon$ is a submultiplicative norm.
Let $T$ be such that $T^{-1} A T = \Lambda + U$ where $\Lambda$ is diagonal and $U$ is strictly upper triangular. Therefore,
$$ \lVert A \rVert_\epsilon = \lVert \Lambda + D^{-1} U D \rVert_\infty \leq \rho(A) + \lVert D^{-1} U D \rVert_\infty $$
where $\rho(\cdot)$ is the spectral radius. Note that $(D^{-1} U D)_{ij} = \delta^{j-i} U_{ij}, \forall j > i$. Therefore,
$$ \lVert D^{-1} U D \rVert_\infty = \max_i \sum_{j=1}^n \lvert \delta^{j-i} U_{ij} \rvert \leq \delta \max_i \sum_{j=1}^n \lvert U_{ij} \rvert = \delta \lVert U \rVert_\infty $$
By choosing $\delta := \epsilon / \lVert U \rVert_\infty$ for some $\epsilon > 0$, we can obtain
$$ \lVert A \rVert_\epsilon \leq \rho(A) + \epsilon $$
Now you can make $\epsilon$ as small as you like.


Server auto update with tripwire IDS

Question: I have a ubuntu server with weekly auto update/upgrade and tripwire installed.
The problem is that the auto update kind of makes tripwire useless as changes always occur on my server. Therefore I constantly have violations flagged by tripwire.
If there were any malicious changes I would miss them.
What is the best practice in such a situation? Is there a way to have automatic updates and useful tripwire reports? How do people usually combine the two?
Answer: I haven't used tripwire in ages but conceptually:
You could choose to limit the tripwire report to alert/report only on missing and newly created files in the */bin/, */sbin/ and */lib/ directories rather than comparing the checksums of the files in those directories.
You then use the package manager to report on the integrity of the packages as explained in for instance  this question which should detect when binaries have been replaced or when the package manager has been used to replace existing packages with untrusted packages.
Admittedly it appears that the RPM format is a bit stronger in requiring signed packages although this article explains how to enforce and verify signed packages on Debian and Ubuntu.
Comment: So what is the best practice? Having automatic updates or using a IDS like Tripwire. How do people usually combine the two?
Comment: The idea to use a tool such as tripwire is to make sure that files are not tempered by hackers. It is a requirement of such things as PCI DSS (not tripwire, but what tripwire does). It is ill advised to tell OP to only check a few directories and not the kernel and other files that tripwire does by default.

Server auto update with tripwire IDS


Terraform: how to attach volumes from previous EC2 instance?

Question: I have a terraform file that creates an EC2 instance along with a couple of volumes:
resource "aws_instance" "generic" {
  count                  = "${lookup(var.INSTANCE_COUNT, var.SERVICE)}"
  ami                    = "${var.AMI}"
  instance_type          = "${lookup(var.INSTANCE_TYPE, var.BLD_ENV)}"
  subnet_id              = "${element(var.SUBNET,count.index)}"
  vpc_security_group_ids = ["${var.SECURITY_GROUP}"]
  key_name               = "${var.AWS_KEY_NAME}"
  availability_zone      = "${element(var.AWS_AVAILABILITY_ZONE,count.index)}"
  iam_instance_profile   = "${var.IAM_ROLE}"

  root_block_device {
    volume_type           = "gp2"
    delete_on_termination = "${var.DELETE_ROOT_ON_TERMINATION}"
  }

  ebs_block_device {
    device_name           = "${lookup(var.DEVICE_NAME,"datalake")}"
    volume_type           = "${lookup(var.DATALAKE_VOLUME_TYPE, var.SERVICE)}"
    volume_size           = "${var.NONDATADIR_VOLUME_SIZE}"
    delete_on_termination = "${var.DELETE_ROOT_ON_TERMINATION}"
    encrypted             = true
  }

  ebs_block_device {
    device_name           = "${lookup(var.DEVICE_NAME,"datalake_logdir")}"
    delete_on_termination = "${var.DELETE_ROOT_ON_TERMINATION}"
    volume_type           = "${lookup(var.LOGDIR_VOLUME_TYPE, var.SERVICE)}"
    volume_size           = "${var.NONDATADIR_VOLUME_SIZE}"
    encrypted             = true
  }

  volume_tags {
    Name = "${lookup(var.TAGS, "Name")}-${count.index}"
  }
}

If the ec2 instance terminates how can I attach the existing volumes to the new ec2 instance created when I rerun terraform?  I was hoping that terraform could somehow tell from the state file the the instance is gone but the volumes aren't and therefore they should be attached to the newly created EC2.
Thanks in advance!
Answer: First, separate your instances, volumes and volume attachments like so:
resource "aws_instance" "generic" {
  ami           = "${var.ami_id}"
  instance_type = "${var.instance_type}"
  count         = "${var.node_count}"
  subnet_id     = "${var.subnet_id}"
  key_name      = "${var.key_pair}"

  root_block_device = {
    volume_type           = "gp2"
    volume_size           = 20
    delete_on_termination = false
  }

  vpc_security_group_ids = ["${var.security_group_ids}"]
}

resource "aws_ebs_volume" "vol_generic_data" {
  size              = 120
  count             = "${var.node_count}"
  type              = "gp2"
}

resource "aws_volume_attachment" "generic_data_vol_att" {
  device_name = "/dev/xvdf"
  volume_id   = "${element(aws_ebs_volume.vol_generic_data.*.id, count.index)}"
  instance_id = "${element(aws_instance.vol_generic_data.*.id, count.index)}"
  count       = "${var.node_count}"
}

Then, if your instance gets manually terminated TF should detect that the instance is gone but still referenced in TF state and should try to recreate it and attach the existing volume. I have not tried this. However, I have tried importing an existing instance and its volume into TF state so the same logic should apply for just importing the volume alone and attaching to an existing TF managed instance. You should be able to simply import the existing volume like so:
terraform import module.generic.aws_ebs_volume.vol_generic_data vol-0123456789abcdef0

Then TF will attach the volume or update the state if already attached.
Comment: For anyone else reading this, although not listed by the OP, the above code will not present the added devices at a specific mount point.  This needs to be done separately.
Answer:
Create the EBS volume using a separate resource: aws_ebs_volume.
Configure the Instance to attach the volume during boot. For example, you could have a User Data script that uses the attach-volume command of the AWS CLI.
If the Instance crashes, or if you want to replace it to deploy new code, you run terraform apply, and the replacement Instance will boot up and reattach the same EBS Volume.

If you want the Instance to be able to recover itself automatically, it gets trickier.

You can configure your Instance with Auto Recovery, but that only detects if the actual VM dies; it won't detect if the app running on that VM dies (e.g., crashes, runs out of memory).
A better approach is to use an Auto Scaling Group (ASG) with a Load Balancer. If any of the Instances in the ASG fail the Load Balancer health checks, they will be replaced automatically. The catch is that an Instance can only attach an EBS Volume in the same Availability Zone (AZ), but an ASG can launch Instances in any AZ, so an Instance might launch in an AZ without any EBS Volume! Solving this, especially in a way that supports zero-downtime deployment, typically requires going outside of Terraform. For example, the Auto Scaling Group module in the Gruntwork IaC Library implements this using multiple ASGs and a Python script activated via an external data source.
Answer: After a lot of searching and reading documentation, I came to a solution for this problem.
Here, I will illustrate with a simple example how to preserve your ebs volumes using terraform i.e. you can create and destroy instances and they will be attached to the same ebs volume each time:

I have created a new Terraform folder in which I have written a script to create an ebs volume with a specific tag.
In my main script I have added a data source to search for ebs volumes with specific tags:

    data "aws_ebs_volume" "test" {
      filter {
        name   = "volume-type"
        values = ["gp2"]
      }

      most_recent = true
    }
    locals { # save the volume id value in this local
      ebs_vol_id = "${data.aws_ebs_volume.test.id}"
    }
    output "volume_id" { # print the volume id value
      value = "${local.ebs_vol_id}"
    }

I have used this local (which now holds the volume id) in my aws_volume_attachment resource.

# attach the instacne to a volume
resource "aws_volume_attachment" "ebs_att" {
  device_name   = "/dev/sdh"
  volume_id     = "${local.default_ami}"
  instance_id   = aws_instance.ec2_instance.id
  skip_destroy  = true # (if true) Don't detach the volume from the instance to which it is attached at destroy time, and instead just remove the attachment from Terraform state.

}

Holaaa, know every time you run terraform apply or terraform destroy, your ec2instance will connect to the sameebs` volume.

Discussion:

This is such a workaround to achieve the intended behavior.
You can achieve the same by using terraform import but, I think this way is easier.
The main drawback of this solution is that now we have two terraform states which is now a recommended option.


Do Virtual Synth Softwares need any physical buttons? Do I need to have any extra buttons on my MIDI keyboard?

Question: I am looking to buy an MIDI keyboard. I want to use it with VST as a Synth. Please guide me. I am completely new in this space.
Comment: piiperi's answer below is exceptional in its thoroughness, but since you are new to this space, my advice is to get a keyboard controller that has some general controls that you will find useful.  I've owned MIDI keyboards for the last 3 decades, and searched for awhile for a MIDI controller to pair up with my computer that had a good set of controls and decent keyboard feel, and finally settled on this one: https://www.amazon.com/Alesis-VI61-Advanced-Keyboard-Controller/dp/B00IWW5H24
Comment: Hi Abhishek - are you looking to perform with the virtual synth as part of a live performance / jamming with other musicians, or do you just want to use it for creating sequenced parts while producing music in the studio? Also, are you planning to use the VST in a particular DAW?
Answer: TL;DR Extra knobs and buttons are not absolutely necessary, but then again a MIDI keyboard is not absolutely necessary either, because you can just use a mouse. But since you're buying a MIDI keyboard, you most likely want to make it easier to play virtual synthesizers, and for that purpose the extra knobs and buttons are very useful.
Even something very simple like using a modulation wheel or control pedal for filter cutoff can raise your musical expression to a completely new level compared to just pressing keyboard keys.
Physical controllers like pitch-bend and modulation wheels or a combined bend/modulation stick, buttons, sliders, pedals and knobs that can send MIDI Control Change messages are very useful for playing virtual instruments. Usually you'll be able to remap or assign any controller knob/slider/wheel/stick/pedal/button to any parameter in a virtual instrument, because they usually send CC messages, just with different controller numbers. (Pitch Bend being an exception that might need special handling, because it has a 14-bit range as opposed to the 7-bit range of CC. Program Change / Bank Change, for switching sounds (programs/patches) might have separate buttons and/or knobs, on some keyboards or controllers. Controller-mapping capabilities are somewhat dependent on the DAW software, but usually modern DAW applications and virtual instruments are well equipped to map almost any physical controller to almost any feature in a virtual instrument.
Sliders can be useful for

Drawbar organ instruments like NI B4. Each slider controls one drawbar, so a keyboard with at least nine sliders side-by-side would give you a nice drawbar controller.
ADSR envelope and other parameters on synthesizers, though knobs will do just as well. It's a matter of preference.
Adjusting channel balance when mixing. You'll typically want to assign each channel (or group/bus) its own slider, so 8 sliders lets you mix 8 channels.
Performance expression parameters, for things like expression dynamics, i.e. how hard a virtual player is blowing her flute. (a modulation wheel/stick can be equally good for this, particularly if it's spring-loaded like a Roland/Korg style modulation stick, providing some natural physical tension)
Effect parameters like rotary speaker ("Leslie") speed, or effect wet/dry level.

Knobs can be useful for

Synthesizer tone control parameters, most commonly filter cutoff frequency and resonance
Effect parameters like effect strength, dry/wet
"Type" parameters like switching between filter types (low-pass/band-pass/etc.)
Program Change i.e. switching sounds, depending on whether the particular keyboard/controller can send Program Change messages with one of its knobs. Many keyboards have a dedicated program change wheel (and sometimes bank change buttons).

Push buttons can be useful for

Toggle-type things like rotary speaker slow/fast, or effect on/off
Controlling the DAW's playback and recording ("transport control"): start/stop/pause, play/rec, seek forwards/backwards
Track record arming
Trigger-type things like launching sequences or samples, though it might be preferrable to use dynamic "drum/trigger pads" for that

Drum/trigger pads are for triggering notes, drums, clips or samples, but they can usually also be used like push-buttons. Many hip-hop and EDM artists use trigger pads for beat-making. The trigger pads usually send Note-On/Off messages just like piano keyboard keys, sometimes even with After-Touch, so you can keep the pad pressed and push it harder or softer and it will keep sending information about how hard it is being pushed.
Pitch Bend wheel or stick is useful for ... pitch bends.
Modulation Wheel or mod wheel can be spring-loaded or not, and it is useful for

modulation, usually meaning "vibrato" but also things like brightness or resonance
expression, for dynamics in virtual wind instruments, strings, accordion, etc. Many virtual instruments like Garritan Personal Orchestra (GPO) use the mod wheel for dynamics (strength) by default.

In addition to those, a keyboard/controller can have connectors for plugging in pedals and other inputs like breath control, and additional controllers can greatly enhance your musical expressivity with synth plugins.
Switch/toggle-type pedals can be used as

Sustain or sostenuto pedal
"Punch in/out" i.e. toggle recording on/off while the transport is rolling
Transport control, e.g. start/stop playback
Rotary speaker (Leslie) speed high/low (nice when you're playing Hammond type sounds and holding down keys with both hands)
or anything where you might also use push-buttons

Controller/expression pedals can be used for

Volume/dynamics/expression
Synthesizer parameters like filter cutoff or attack speed.
or anything where you might also use rotary knobs or sliders

Breath control input can be used for musically expressive control for synth sounds and particularly virtual wind instruments. If you have any experience at all with playing wind instruments, even a school recorder, a breath controller can raise your musical expression to a new level.
You're most probably going to learn what you really need and prefer only after using a controller for awhile.
I recommend reading up on MIDI to know the difference between various MIDI message types: Pitch Bend, Control Change, Program Change, Note On/Off, etc.
Answer: Rather more succinctly:
You need sufficient controllers for the parameters of the VSTi that you need to control in real-time, actually while playing.  Give us more details of how you intend to work - is this for live performance or are you always recording into a sequencer?  Then we can be more helpful.
Answer: No. You don't need them.Everything you can do with them you can also do with your mouse directly with the VST. The knobs and sliders etc. are convenient shortcuts to save you going back and forth from computer to controller.
Comment: How do you know what the OP needs or doesn't need? This is only true for a small minority of virtual instrument players. In practice, using the mouse for musical expression control is as convenient as using the mouse for pressing the keyboard keys.
Comment: The point I was trying for was that there are no hidden or secret functions that are only accessible if you have a controller.


Inspect TSA timestamp

Question: I'm trying to validate a XAdES signature with a SignatureTimeStamp-element (which is a base64-encoded block). The Java-Lib xades4j basically does the validation for me. However, I'd like to manually inspect the timestamp (especially when validation fails). With inspect I mean to show the contents like the used certificates, their validity, the timestamp, etc.
What tool can I use? Does openssl do the trick? Can you give me an example of how to use it?
Answer: Xades4j uses Bouncy Castle to generate and validate timestamps. BC probably allows you to get that info from the timestamp token in the signature.

Inspect TSA timestamp


Number of equivalence relation on $A=\{1,2,...,11\}$ such that $|A\setminus R| = 2$.

Question: I am still trying to understand the question, I know that if a relation is reflexive (and equivalence relation is surely reflexive), then for every $a\in A$ , $(a,a)\in R$. But that means every equivalence relation on $A$ has atleast $11$ elements, which makes $|A \setminus R=0|$, because the cardinality of $R$ is surely $11$ or more.
The final answer was $2^{10}-1$, so seems like I have some big misunderstanding that I don't understand where it comes from, I would really appreciate any explanation.
Thanks in advance.
Comment: The fact that $(a,a)\in R$ does not mean than there are $11$ equivalence classes.  We could, for instance, have the trivial equivalence relation in which every element is equivalent to every other element.  That one only has $1$ equivalence class.
Answer: The notation $A/R$ represents the set of equivalence classes (with respect to $R$). So, the question is: how many equivalence relations can you define on $A$ such that there are exactly two equivalence classes? And the answer is: it's half the number of subsets $B$ of $A$ such that neither $B$ nor $A\setminus B$ is empty, because, for any such set $B$, you can define the equivalence relation$$a_1\mathrel Ra_2\iff a_1,a_2\in B\text{ or }a_1,a_2\notin B$$and the equivalence classes of $R$ and $B$ and $A\setminus B$; besides, $B$ and $A\setminus B$ induce the same equivalence relation. There are $2^{11}-2$ such sets, and therefore the answer is $2^{10}-1$.
Comment: I suggest that you check that the relation $R$ that I defined is indeed an equivalence relation and that the equivalence classes are $B$ and $A\setminus B$. Clearly, if I define $R$ starting from $A\setminus B$ instead of $B$, then I will get the same equivalence relation and therefore the same equivalence classes. On the other and, if $C\subset A$, if neither $C$ nor $A\setminus C$ is empty, if $C\ne B$, and if $C\ne A\setminus B$, then the equivalence relation that I get from $C$ is different from the one that I get from $B$, since the equivalence classes are distinct.
Comment: So, what remains to be done is to count the number of subsets $B$ of $A$ such that neither $B$ nor $A\setminus B$ are empty. The set $A$ has $2^{11}$ subsets, but neither $\emptyset$ nor $A$ matter here. So, there are $2^{11}-2$ possibilitites for $B$. And since the only other subset of $A$, other than $B$, that induces the same equivalence relation as $B$ is $A\setminus B$, the answer is$$\frac{2^{11}-2}2=2^{10}-1.$$
Comment: Don't you need to divide by $2$ to account for symmetry?
Comment: @marlasca23 I missed that. It seems to be correct now.
Comment: Thank you, this clears my doubts about the question, but I didn't quite get the idea of the subsets, I have basic understanding of equivalence classes partitioning $A$, so we're searching for relations with $2$ equivalence classes which means we need to have exactly $2$ unempty equivalence classes. but I'm struggling with linking them with subsets $B$ that you mentioned, and couldn't understand the calculations after it.
Comment: Honestly thanks alot, took me alot to grasp the idea, but I now get it better, I got a last question, about starting R from $A\setminus B$, why would we get the same equivalence classes? wouldn't we get the opposite equivalence classes from starting at $B$? or this is exactly the idea, like let $A=\{ 1,2,3,4 \}$, if we start at $A\setminus B=\{ 1\}$, we get $R= \{ (1,1) \}$ on $B$ and $ R={(2,2),(3,3),... } $ on $A\setminus B$, and that's one partition: $ \{ \{ 1 \},\{2,3,4\}\}$. then we keep counting until we reach  $\{ \{1,2,3\},\{4\}\}$. Thanks alot for everything.
Comment: I made a mistake in the definition of $R$. What I had there was not an equivalence relation. Sorry about that. Please check the edited version.
Comment: Thanks alot this clears everything, appreciate the help and explanations!


Qwt plot is not reploting

Question: I have a Qwt plot defined in a class method:
plot = new QwtPlot();
const int margin = 5;
plot->setContentsMargins( margin, margin, margin, 0 );
plot->setTitle( "Support polygon" );
plot->setCanvasBackground( Qt::white );
plot->setAxisScale( QwtPlot::yLeft, -0.8,0.8 );
plot->setAxisScale( QwtPlot::xBottom, -0.8,0.8 );

QBoxLayout *layout = new QBoxLayout(QBoxLayout::LeftToRight);
layout->addWidget(plot);
setLayout(layout);

curve_ = new QwtPlotCurve();
curve_->attach( plot );
xData = new double[4];
yData = new double[4];

QTimer *replotTimer_ = new QTimer(this);
connect(replotTimer_, SIGNAL(timeout()), this, SLOT(updateMe_()));
replotTimer_->start(100);

the data is updated when the timer calls the callback function updateMe_() and the plot should be updated
void Support_polygon::updateMe_()
{
    curve_->setRawSamples(xData,yData,4);
    plot->replot();
}

xData and yData are also being modified in a thread, whose callback function is:
void Support_polygon::callback_()
{
    msg_mutex.lock();
    for (size_t ii=0; ii<msg.contacts.size(); ii++)
    {
        xData[ii] = 1.4f*float(std::rand())/float(RAND_MAX)-0.7;
        yData[ii] = 1.4f*float(std::rand())/float(RAND_MAX)-0.7;
    }
    msg_mutex.unlock();
}

(right now I'm only putting random numbers, but when this works the data will be passed by a ROS message, that's why is in a different thread)
The problem is that the plot is never updated. As if replot() is never called. I tested and all callback functions are being called.
Surprisingly, the plot gets updated if I resize the window... if I keep re-sizing, the plot gets updated while I do it.
The replot call is being done on the main thread by the timer timeout signal. I don't understand what is going on.
Answer: Even though in the documentation it says that setAutoReplot is not recommended and that performance wise is better to use replot, I tested setting setAutoReplot to true
plot->setAutoReplot( true );

removed the replot call in updateMe_(), and everything works.
But to me this seems like a bug.
Note: I'm using Qwt 6.1.2.
note: after many more issues with qwt I switched to qtcustomplot. Only one header and one cpp file. My two cents in case anyone is looking for a substitute.

Qwt plot is not reploting


Bundle CrossRider as a single installer

Question: Let me detail what I'm trying to accomplish: I have an application that besides the specific app code and installer, also bundles a CrossRider browser extension. The problem is that my installer generates one entry in Programs & Features, while the CrossRider extension generates a different one.
Is there a way to show only my installer in the Programs & Features, and hide/have the CrossRider entry to be a part of my main installer?
Thank you,
Mihnea
Answer: I'm afraid there isn't an option to hide the Crossrider extension in the Control Panel.
However, if you open a Crossrider support ticket (email email@example.com) the person who deals with such matters (who is away this week) will be happy to discuss any options we can consider implementing to assist you.
Comment: Thank you @Shlomo, I will send a support ticket for this. If you have the time, maybe you can also assist me with another question on CrossRider: http://stackoverflow.com/questions/15882802/customize-crossrider-installer - thank you again.
Comment: Regarding the other question, I answered there in a similar manner :-)

Bundle CrossRider as a single installer


What is the difference between "32 bar form", "song form", and "ternary" with a repeated first section?

Question: There are separate wikipedia articles for 32 bar form, but song form and ternary are in one article. From my understanding, repeats do not change the form in terms of classification, which is something emphasized by this article; yet the AP Barron's Music Theory Textbook says that "thirty-two bar song form" evolved from ternary with the first section repeated.
So what I'm confused about is: what makes song form, and "thirty-two bar song form" for that matter, different from ternary form? Is it the time period? Or are they equivalent or subsets of each other?
Answer: 32-Bar form is a special case of ternary form that is so commonly used that it is deserving (at least in Wikipedia's estimation) of its own discussion

Ternary form and song form are essentially two terms for the same thing. This is reflected in the Wikipedia entry:

Ternary form, sometimes called song form ... [emphasis original]

32-bar form is also a ternary form, but it is so commonly used — and rather specific to American "Tin-Pan Alley" music of the early 20th century — that it gets its own term.

Though the 32-bar form resembles the ternary form of the operatic da capo aria, it did not become common until the late 1910s. It became "the principal form" of American popular song around 1925–1926. (SOURCE: Wikipedia)

32-Bar form is specifically AABA with each section being 8 measures long. In general, however, the A and B sections of ternary form can be of any length, and they may or may not be repeated.
Comment: Since Wikipedia is edited by multiple people, I was worried that articles could contradict each other, so it would be nice to have a non-Wikipedia source. But pointing out the specific quotations, thanks for making it a bit clearer. I suppose in the sentence "Though the 32-bar form resembles the ternary form of the operatic da capo aria", "the ternary form [*that* is used in the] operatic da capo aria" is a specific thing, rather than referring to "the ternary form [*which* is used in the] operatic da capo aria". ?
Comment: @awelotta Yes, "da capo aria" is a ternary form. There is also "minuet-trio form", which is a ternary form. I'll look around for a more authoritative source; just know, Wikipedia does have it right in this case.


JS: erro função not defined (ao chamar uma funcao dentro de outra)

Question: Estou tendo o seguinte erro: "minhafuncao is not defined"
Com a estrutura a baixo:
var myobject = object.extend({
   init: function () {
        minhafuncao();
   },

   minhafuncao: function() {
      console.log("oi");
   }
});

Comment: Relacionada: https://pt.stackoverflow.com/questions/37770/qual-a-diferen%C3%A7a-entre-this-e-this-e-this/
Answer: Use o this para indicar o escopo da função:

var obj  = {
  init: function() {
    this.minhafuncao();
  },

  minhafuncao: function() {
    console.log("oi");
  }
}
obj.init();
Comment: Olá, editei minha pergunta pois vi que estava faltando coisas. Tentei fazer como mencionou mas não funcionou, continua o erro. :(
Comment: O que é `object.extend` @sabrinabgbc? É de alguma outra biblioteca?
Comment: é so para estanciar o objeto
Comment: Deu certo, obrigada !


Hashicorp Vault - AWS EKS vs EC2

Question: Is it possible to install a Hashicorp Vault cluster to EC2 only or is EKS required and would there be a big advantage to one over the other?
Answer: Vault runs on EC2 just fine. It is a a typical Kubernetes vs. Virtual machine descision. Vault has very little that's specific to it with that regard.
Running on virtual machine is generally more complex to setup because you'll have to provision storage, load-balancers, etc. But if you don't already have a EKS cluster ready and Kubernetes expertise it will be easier to deploy Vault on EC2.
Also, running on a virtual machine makes it easier to keep mlock enabled and hook to an HSM (Vault Enterprise only).

Hashicorp Vault - AWS EKS vs EC2


how does "Disk-backed" replication work in redis cluster

Question: the redis.conf says:
1) Disk-backed: The Redis master creates a new process that writes the RDB
                file on disk. Later the file is transferred by the parent
                 process to the slaves incrementally
I just dont know what does "transferred by the parent process to the slaves" mean?
thank you
Answer: It is simple. First read the RDB file into a buffer, and use socket.write to send this to salve's port which is listenning this.
The implemention is more complex than what I said. But this is what redis do. You can refer the replication.c in redis/src for more details.
EDITED:
Yes, the disk-less mechanism just use the child process directly sends the RDB over the wire to slaves, without using the disk as intermediate storage.
Actually, if you use disk to save the RDB and redis master can serve many slaves at the same time without queuing. Once the disk-less replication serve on slave, and if another slave comes and want do a full sync, it need to be queued to wait for the first slave to finish. So there are another settings repl-diskless-sync-delay to wait more slave to do this parallel.
And these two method only occur after something wrong happens. In the normal case, the redis master and salve through a well connected wire to replicate the redis command the slave to keep the same between the master and slave. And if the wire is break or the slave fall down, then need do a partial resync action to obtain the part slave missed. If the psync is not possible to achieve, it will try do full resync. The full resync is what we talked about.

This is how a full synchronization works in more details:
The master starts a background saving process in order to produce an RDB file. At the same time it starts to buffer all new write commands received from the clients. When the background saving is complete, the master transfers the database file to the slave, which saves it on disk, and then loads it into memory. The master will then send all buffered commands to the slave. This is done as a stream of commands and is in the same format of the Redis protocol itself.

And the disk-less replication is just a new feature which supports the full-resync in that case to deal with the slow disk stress. More about it refer to https://redis.io/topics/replication. such as how do psync and why psync will fail, you can find answer from this article.
Comment: Thank you. so it's the same as "diskless" ?

"# 2) Diskless: The Redis master creates a new process that directly writes the
#              RDB file to slave sockets, without touching the disk at all."

     It seems that both "disk-backed" and "diskless" use socket.write to send data.  The only difference is, "disk-backed" creates RDB file while "disk-less" doesn't.


Need to find Secure Websocket Broker for MQTT

Question: Is there a test broker that supports secure websockets for MQTT ? ( wss:// )
Can anyone point out the right resources if available ?
Answer: Mosquitto should support Secure Websockets.
And example of the configuration can be found here:
http://jpmens.net/2014/07/03/the-mosquitto-mqtt-broker-gets-websockets-support/
Comment: Thanks ! This is what I was looking for.


Protecting a file in an apk

Question: I'm working to create a dictionary for android. I have a csv file containing all the data, which I worker for few months to complete.
The problem is anybody can explode the apk and extract the csv file. I wish secure the file. How can I protect a file inside the apk by not breaking the application?
Thanks for reading.
Answer: You could save an encrypted version of the file, and decrypt it inside your application.
EDIT: for instance, this is a quick an simple solution for encrypting/decrypting data.
Comment: True. However, unless we are talking about valuable data targeted by tens of crackers, a well-encrypted file should keep at bay at lease the majority of them.
Comment: Yes, this may prevent casual ripoffs but ultimately becomes an arms race of obfuscation and discovery, because the algorithm/keys used to decrypt it are present in the app and available to extract, too.  The only way to truly protect it would be to keep it on a server and rate-limit queries, but that leads to poor usability.  Perhaps try to have the value somewhere other than the dataset?

Protecting a file in an apk


db_select group by of union

Question: I'm quite new to drupal ad I've some problem with parsing a query throught the API:
    SELECT t.pg,p.classe, sum(t.punti) AS punti, sum(t.vinte) AS vinte, sum(t.perse) AS perse, (sum(t.vinte)+sum(t.perse)) AS giocate
    FROM(
        SELECT sid, team_member_a_1 AS pg, punti_team_a AS punti, 1 AS vinte, 0 AS perse
        FROM `webform_views_unusual_arena__risultati_6` AS t1
        WHERE tipologia_risultato = 0
            AND vincente = 0
        UNION
        SELECT sid, team_member_a_2 AS pg, punti_team_a AS punti, 1 AS vinte, 0 AS perse
        FROM `webform_views_unusual_arena__risultati_6` AS t1
        WHERE tipologia_risultato = 0
            AND vincente = 0
    ) AS t
    JOIN webform_views_i_miei_pg_1 AS p ON t.pg = p.nome_pg
    GROUP BY pg

But I can't find any documentation about a subquery or how to add field like "1 AS vinte"
EDIT
Thank's to Tenken this is the code I used.
$subquery_1 = db_select('webform_views_unusual_arena__risultati_6', 't')
    ->condition('t.tipologia_risultato', 0, '=')
    ->condition('t.vincente', 0,'=')
    ->fields('t', array('sid'));
$subquery_1->addExpression('team_member_a_1', 'pg');
$subquery_1->addExpression('punti_team_a', 'punti');
$subquery_1->addExpression(1, 'vinte');
$subquery_1->addExpression(0, 'perse');
$subquery_2 = db_select('webform_views_unusual_arena__risultati_6', 't')
    ->condition('t.tipologia_risultato', 0, '=')
    ->condition('t.vincente', 0,'=')
    ->fields('t', array('sid'));
$subquery_2->addExpression('team_member_a_2', 'pg');
$subquery_2->addExpression('punti_team_a', 'punti');
$subquery_2->addExpression(1, 'vinte');
$subquery_2->addExpression(0, 'perse');
$query = $subquery_1->union($subquery_2);

$query->addExpression('sum(vinte)', 'vinte');
$query->addExpression('sum(perse)', 'perse');
$query->addExpression('sum(punti)', 'punti');
$query->groupBy('pg');
$query->orderBy('punti', 'DESC');

Hope it will help someone else
Answer: See this WEALTH OF DOCUMENTATION on Dynamic Queries in D7 ... it will answer EVERYTHING :) .... in all seriousness :).
To add SUM(blah) as foo you want to add an SQL Expression to your Select clause with addExpression().
To add Group by COLNAME you want to use groupBy() with your db_selection, see group by docs.
Comment: I already tried to group by as you suggest, but i keep on getting the error message:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 't.pg' in 'group statement'
Comment: `fields` go in the `fields()` array. I've never used `addField()` like that, I always use `addExpression()` which your not using at all ... see comments here http://api.drupal.org/api/drupal/includes%21database%21select.inc/function/SelectQuery%3A%3AaddField/7

I speak and write english and spanish. In my opinion you should try to make your PHP code 1 language and not two (or 3) ... it's easier for people to understand.
Comment: You were totally right!
I will update my question with the final code.

db_select group by of union


php mysql query finding closest results

Question: How would the best way to approach this problem be?

Search for user by first name, where the parameter is a string. The result should display a list
of the 10 users whose first name is closest to the searched string.

Clearly there are different ways to approach this one. Is there any mysql functionality that does this already?
Should I just query all my rows and run some kind of search function?
Comment: You could use the [SOUNDEX](http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_soundex) function of MySQL if you mean "sounds close enough".
Comment: Are you using InnoDB or MyISAM engine for the table?  How many users do you plan on having in the DB?
Comment: 10, 000 it is just a test query I have to write. No worry about efficiency on this one.
Comment: I just found http://www.w3schools.com/php/func_string_levenshtein.asp which is looking like the way to go in this instance.
Answer: Have a look at MySQL Full-Text search functions which will automatically return results based on relevancy, though it will not work with InnoDB.
Comment: There is a pretty big drawback to using MySQL Full-Text searches: you cannot search for substrings (just for prefixes).

php mysql query finding closest results


Service versus BroadcastReceiver

Question: Qual a diferença, no Android, entre Service e BroadcastReceiver?

Quanto tempo um Service pode ficar executado (rodando)?
Quanto tempo um BroadcastReceiver pode ficar executado (rodando)?
Posso cria notificações via BroadcastReceiver ou apenas via Service?
É uma boa prática (a pergunta anterior)?
Answer: A documentação define Serviço da seguinte forma:

Um Service é um componente do aplicativo que pode realizar operações longas e não fornece uma interface do usuário. Outro componente do aplicativo pode iniciar um serviço e ele continuará em execução em segundo plano mesmo que o usuário alterne para outro aplicativo. Além disso, um componente poderá vincular-se a um serviço para interagir com ele e até estabelecer comunicação entre processos (IPC). Por exemplo, um serviço pode lidar com operações de rede, reproduzir música, executar E/S de arquivos, ou interagir com um provedor de conteúdo, tudo a partir do segundo plano.

Por sua vez um BroadcastReceiver é um componente que permite ser registado para receber eventos.
Todos os receptores registados para um evento são notificados pelo SO Android uma vez que este evento aconteça.
Quanto tempo um Service pode ficar executado (rodando)?
Quando iniciado através de startService() o serviço permanecerá em execução até ser interrompido por conta própria com stopSelf() ou pelo componente que o iniciou, chamando stopService().
Quando iniciado através de bindService() ele ficará rodando enquanto houver clientes vinculados.
Um serviço pode ser destruído pelo SO quando a memória estiver baixa e precisar recuperar recursos do sistema.
Quanto tempo um BroadCastReceiver pode ficar executado (rodando)?
Um BroadcastReceiver é iniciado pelo SO se ele for elegível para o evento lançado.
Um BroadcastReceiver é válido apenas para a duração da chamada ao método OnReceive()
Uma vez o código retornar desse método, o sistema considera o objecto concluído e não mais activo, podendo ser destruído pelo SO.
A documentação diz que após 10 segundos o receiver será bloqueado e poderá ser destruído.
Posso cria notificações via BroadCastReceiver ou apenas via Service?
Se você está a referir-se às notificações(NotificationManager) que aparecem na área de notificação do dispositivo, sim, é até uma forma usual de utilização dos BroadcastReceiver.
Você pode fazer tudo o que quiser no método onReceive() desde que seja de forma síncrona(1).
Como esse código corre na main thread não os use para processos longos.
É uma boa prática (a pergunta anterior)?
Sim, como disse anteriormente, lançar notificações é uma forma usual de utilização dos BroadcastReceiver.
(1)Essa limitação pode ser evitada usado registerReceiver (BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler)
Answer: Um service é um componente que executa ações de longo prazo em segundo plano, ele não apresenta uma interface para o usuário. Como exemplo você poderia criar um service que acessa uma certa API externa em busca de novos dados, ao constatar que existem atualizações seu service poderia fazer um broadcast dos dados usando sendBroadcast (método de um parent class), sendo que nesse ponto entraria o BroadcastReceiver, que é a classe utilizada para "escutar" broadcasts gerados por chamadas de sendBroadcast.
Quanto ao resto:

Pelo tempo que for necessário. O service pode ser criado pela aplicação e executar continuamente por tempo indefinido, mesmo com ela parada (quando está aberta mas você está executando outra aplicação);
Também indefinidamente. Você pode registrar um por uma Activity, nesse caso ele só executa enquanto a activity executar, ou então pelo manifest da aplicação, nesse caso ele executa de maneira independente da activity;
Como o próprio nome indica BroadCastReceiver ("Receptor de broadcasts") é utilizado para receber notificações e não envia-lás;
Não faz sentido ;(.

Service versus BroadcastReceiver


Finding all critical points of a function

Question: Given : $ f(x,y,z) = xyz - x^2 - y^2 -z^2 $ .
I need to find all critical values of $f$ and to determine whether they are max,min, or saddle points.
Solving for $\nabla f=0 $ gives me the following equations:
$ yz=2x , xz=2y, xy = 2z $ , from which we get the five solutions:
$ (0,0,0) , (2,2,2) , (2,-2,-2) , (-2,2,-2) , (-2, -2, 2) $ .
We also have that: $ f_{xx} = -2 , f_{yy} = -2 , f_{zz}=-2 , f_{xy}=z , f_{xz}=y, f_{yz}=x $ .
As for $(0,0,0)$ , we have that it is a maximum, since the Hessian is negative.
My problem is with the other points, since their Hessian gives a matrix that is not negative nor positive, so I can't deduce anything!
Can you please help me understand what kind of points are all the points except for (0,0,0)?
Thanks !
Answer: Hint: Calculate the eigenvalues of the matrix.
Positive definiteness occurs when all eigenvalues are positive, negative definiteness when all eigenvalues are negative.  A critical point is a saddle point if there are both negative and positive eigenvalues; thus, the only indeterminant case is when you have you don't have any of the above cases, e.g. some positive, some zero.
Answer: I am filling in the details of the calculation for the Hessian, as we can derive a couple of relations that will save some work further along. You presumably found the critical points from
$$  yz \ = \ 2x \ \ , \ \ xz \ = \ 2y \ \ , \ \ xy \ = \ 2z \ \ \Rightarrow \ \ xyz^2 \ = \ 4xy \ = \ 8z \ \ ; $$
[multiplying the first two equations together, and also applying the third]
we may either take $ \ x \ = \ y \ = \ z \ = 0 \ $ , or, using this last equation with $ \ z \ \ne \ 0 \ $ ,
$$ xyz \ = \ 8 \ \ \Rightarrow \ \ xy \ = \ \frac{8}{z} \ = \ 2z \ \ \Rightarrow \ \ z^2 \ = \ 4 \ \ . $$
[applying the third critical point equation again]
From this, you found that $ \ z \ = \ \pm 2 \ $ , and then the coordinates you list.
The second partial derivatives you show produce the Hessian matrix (as you would have obtained)
$$ \left[ \begin{array}{ccc}-2&z&y\\z&-2&x\\y&x&-2\end{array}  \right] \ \ , $$
for which the characteristic equation is
$$ - (2 + \lambda)^3 \ + \ 2 \ xyz \ - \ (x^2 + y^2 + z^2) \ [  -(2 + \lambda) \ ] \ = \ 0 \ \ .  $$
The point of setting this up is that we can find first (as you did) that for the critical point at the origin, all of the eigenvalues are $ \ -2 \ $ (which also comes directly from the fact that the Hessian is diagonal in that case), but also that for all four of the other critical points,
$$ xyz \ = \ 8 \ \ , \ \ x^2 \ = \ y^2 \ = \ z^2 \ = \ 4 \ \ \Rightarrow \ \ - (2 + \lambda)^3 \ + \ 2 \cdot 8 \ - \ 3 \cdot 4 \ [ \ -(2 + \lambda) \ ] \ = \ 0 $$
$$ \Rightarrow \ \ \lambda^3 \ + \ 6 \ \lambda^2 \ - \ 32 \ = \ 0 \ \ \Rightarrow \ \  \lambda \ = \ 2 \ , \ -4 \ , \ -4 \ \ . $$
Since there are both positive and negative eigenvalues, all of the remaining critical points are saddle points [as Hayden remarks].
$$ \ $$
Another approach we can take is to look at "cross-sections" of the hypersurface described by $ \ f(x,y,z) \ $ near these critical points (in the absence of a convenient way to "visualize" the function).  This turns out to be important because a simple assessment of values of the function can be deceptive.  We have
$$ f(2, \ 2, \ 2) \ = \ f(-2, \ -2, \ 2) \ = \ f(-2, \ 2, \ -2) \ = \ f(2, \ -2, \ -2) $$
$$ = \  8 \ - \ 3  \ (\pm 2)^2 \ = \ -4 \ \ . $$
For example, if we look at $ \ (2, \ 2, 2) \ $ and calculate values in the immediate vicinity of that points, we find (for instance)
$$ f(2.1, \ 2, \ 2) \ = \ f(1.9, \ 2, \ 2) \ = \ -4.01 \ \ ; $$
owing to the symmetry of the function, a similar small step in the $ \ y- \ $ or $ \ z-$ coordinate gives the same values.  So one might reasonably form the impression that this point is a relative maximum, as the origin is.
If we take the "slice" $ \ x \ = \ y \ = \ z \ $ , however, our function becomes
$ \ f(x, \ x, \ x) \ = \ x^3 \ - \ 3x^2 \ $ , for which we find that $ (0, \ 0, \ 0) \ $ is a relative maximum (as we would expect) and $ \ (2, \ 2, \ 2) \ $ is a relative minimum (concavity is "upward" there).  On the other hand, if we look at a "slice" perpendicular to that along $ \ x  \ = \ z \ \ , \ \ y \ = \ 4  -  x \ $ , the behavior of our function is $ \ f(x, \ 4 - x, \ x) \ = \ -x^3 \ + \ x^2 \ + \ 8x \ - \ 16 \ $ .  Along this slice, $ \ (2, \ 2, \ 2) \ $ is a relative maximum ("downward" concavity).  So this point is not a relative extremum of $ \ f(x,y,z) \ $ , but rather is a saddle point.  Similiar analyses can be carried out for each of the other three critical points in question.


Can bowler bowl with two hands (left & right) in international cricket

Question: Recently I've seen in domestic match there was one bowler (spinner) who used his both hands while delivering the ball?
I've doubt can it be possible in International Cricket.
Does ICC has any rule about this?
Answer: This is perfectly legal, so long as the bowler informs the umpire before changing from bowling left-handed to right-handed or vice versa. Quoting Law 21.1.1, Mode of delivery:

The umpire shall ascertain whether the bowler intends to bowl right handed or left handed, over or round the wicket, and shall so inform the striker.
It is unfair if the bowler fails to notify the umpire of a change in his/her mode of delivery.  In this case the umpire shall call and signal No ball.

There is nothing in any of the ICC Playing Conditions for Test Matches, One Day Internationals or T20 Internationals which overrides this.


Find n words starting with capital letter before 2 words of capital letters (regex)

Question: I have written this regex but this is not working as expected.
((?:[A-Z][\w]+)?),[\s]([A-Z]{2})

Following are sample inputs.
Fort Worth, TX
This is Forth Worth, TX
We are looking for someone from Columbus, MS.

I expect City and State out of above string samples with regex in python but this is just no working as expected.
print re.findall('((?:[A-Z][\w]+){1,2}),[\s]([A-Z]{2})', input)

What am I missing?
Comment: The space in between the city names.
Comment: You may want to use some sort of natural language parsing instead.
Answer: Why not just:
([A-Z][^,]+),\s([A-Z]{2})

Or if you can only have word characters and spaces in the city name then:
([A-Z][\w\s]+),\s([A-Z]{2})

Regex101 Demo
Comment: Second regex will bring whole text "We are looking for someone from Columbus, MS." won't it?
Comment: @UmairAshraf Yes it does, but how can you be sure that the city name isn't more than 2 words ? anyway your problem seems to be solved.
Comment: I have seen complete set of data to which this regex will be applied so yes I am sure why city max at 2 words.
Answer: You probably want to add a white space character in your city name group, like this:
re.findall('((?:[A-Z][\w]+\s*){1,2}),[\s]([A-Z]{2})', input)

This will match a capital Latin letter followed by one or more word characters and zero or more white space characters, all of which may be appear one or two times, captured in group 1, followed by a comma, a white space character, and two capital Latin letters, captured in group 2.
Comment: Works and your answer didn't break my other rules so answer goes to you.


como centralizar as abas de um TabbedPane?

Question: Eu andei dando um pesquisada, porém não encontrei. Gostaria de saber, como centralizar as abas de um TabbedPane. Elas sempre se iniciam da esquerda, porém como são apenas duas abas, queria que elas ficassem centralizadas.
Exemplo ilustrativo:

Exemplo simples:
package telas;

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

public class Tela1 extends JFrame {

    JTabbedPane tabbedPane = new JTabbedPane();

    public Tela1() {
        setTitle("Tela");
        tabbedPane.addTab("Página 1", painel1());
        tabbedPane.addTab("Página 2", painel2());
        tabbedPane.setPreferredSize(new Dimension(getWidth(), 300));
        add(tabbedPane, BorderLayout.SOUTH);
        //setResizable(false);
        setVisible(true);
        setSize(600, 500);
        setLocationRelativeTo(null);
        setMinimumSize(new Dimension(getWidth(), getHeight()));
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    public static void main(String[] args) {
        Tela1 tela  = new Tela1();
    }

    public JComponent painel1() {
        JPanel painel1 = new JPanel();
        JLabel label1;
        label1 = new JLabel("Página 1");
        painel1.add(label1);
        return painel1; // retorna painel.
    }

    public JComponent painel2() {
        JPanel painel2 = new JPanel();
        JLabel label2;
        label2 = new JLabel("Página 2");
        painel2.add(label2);
        return painel2;
    }
}

Comment: Assim, obrigado !   :(
Comment: Estou olhando alguns exemplos no SOEn, caso encontre algum semelhante ao que você disse, eu posto aqui.
Comment: ok, muito obrigado !
Comment: Você quer centralizar os rotulos das abas? Isso não é possivel apenas utilizando o componente nativo, ele só permite posicionar na parte de cima, abaixo, ou a esquerda ou direita, como pode ser visto[aqui](https://docs.oracle.com/javase/8/docs/api/javax/swing/JTabbedPane.html#setTabPlacement-int-). Você terá que criar um proprio componente baseado em JPanel para fazer esse comportamento.
Answer: consegui desta forma:
1º - Criar esta classe
    import javax.swing.plaf.basic.BasicTabbedPaneUI;
    import java.awt.*;

    public class CenterTabbedPane extends BasicTabbedPaneUI {

        @Override
        protected LayoutManager createLayoutManager() {
            return new TabbedPaneLayout();
        }

        class TabbedPaneLayout extends BasicTabbedPaneUI.TabbedPaneLayout {

            private Insets getVisualMargin() {
                Insets margin = new Insets(3, 0, 3, 0);
                return add(-3, -3, -4, -3, margin);
            }

            @Override
            protected void calculateTabRects(int tabPlacement, int tabCount) {
                Dimension size = tabPane.getSize();
                Insets insets = add(tabPane.getInsets(), getVisualMargin());
                Insets tabAreaInsets = getTabAreaInsets(tabPlacement);
                FontMetrics metrics = getFontMetrics();
                int fontHeight = metrics.getHeight();
                int selectedIndex = tabPane.getSelectedIndex();
                int tabRunOverlay;
                int i, j;
                int x, y;
                int returnAt;
                boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);

                //
                // Calculate bounds within which a tab run must fit
                //
                switch (tabPlacement) {
                    case LEFT:
                        maxTabWidth = calculateMaxTabWidth(tabPlacement);
                        x = insets.left + tabAreaInsets.left;
                        y = insets.top + tabAreaInsets.top;
                        returnAt = size.height - (insets.bottom + tabAreaInsets.bottom);
                        break;
                    case RIGHT:
                        maxTabWidth = calculateMaxTabWidth(tabPlacement);
                        x = size.width - insets.right - tabAreaInsets.right - maxTabWidth;
                        y = insets.top + tabAreaInsets.top;
                        returnAt = size.height - (insets.bottom + tabAreaInsets.bottom);
                        break;
                    case BOTTOM:
                        maxTabHeight = calculateMaxTabHeight(tabPlacement);
                        x = insets.left + tabAreaInsets.left;
                        y = size.height - insets.bottom - tabAreaInsets.bottom - maxTabHeight;
                        returnAt = size.width - (insets.right + tabAreaInsets.right);
                        break;
                    case TOP:
                    default:
                        maxTabHeight = calculateMaxTabHeight(tabPlacement);
                        x = insets.left + tabAreaInsets.left;
                        y = insets.top + tabAreaInsets.top;
                        returnAt = size.width - (insets.right + tabAreaInsets.right);
                        break;
                }

                tabRunOverlay = getTabRunOverlay(tabPlacement);

                runCount = 0;
                selectedRun = -1;

                if (tabCount == 0) {
                    return;
                }

                // Run through tabs and partition them into runs
                Rectangle rect;
                for (i = 0; i < tabCount; i++) {
                    rect = rects[i];

                    if (!verticalTabRuns) {
                        // Tabs on TOP or BOTTOM....
                        if (i > 0) {
                            rect.x = rects[i - 1].x + rects[i - 1].width;
                        } else {
                            tabRuns[0] = 0;
                            runCount = 1;
                            maxTabWidth = 0;
                            rect.x = x;
                        }
                        rect.width = calculateTabWidth(tabPlacement, i, metrics);
                        maxTabWidth = Math.max(maxTabWidth, rect.width);

                        // Never move a TAB down a run if it is in the first column.
                        // Even if there isn't enough room, moving it to a fresh
                        // line won't help.
                        if (rect.x != 2 + insets.left && rect.x + rect.width > returnAt) {
                            if (runCount > tabRuns.length - 1) {
                                expandTabRunsArray();
                            }
                            tabRuns[runCount] = i;
                            runCount++;
                            rect.x = x;
                        }
                        // Initialize y position in case there's just one run
                        rect.y = y;
                        rect.height = maxTabHeight/* - 2*/;

                    } else {
                        // Tabs on LEFT or RIGHT...
                        if (i > 0) {
                            rect.y = rects[i - 1].y + rects[i - 1].height;
                        } else {
                            tabRuns[0] = 0;
                            runCount = 1;
                            maxTabHeight = 0;
                            rect.y = y;
                        }
                        rect.height = calculateTabHeight(tabPlacement, i, fontHeight);
                        maxTabHeight = Math.max(maxTabHeight, rect.height);

                        // Never move a TAB over a run if it is in the first run.
                        // Even if there isn't enough room, moving it to a fresh
                        // column won't help.
                        if (rect.y != 2 + insets.top && rect.y + rect.height > returnAt) {
                            if (runCount > tabRuns.length - 1) {
                                expandTabRunsArray();
                            }
                            tabRuns[runCount] = i;
                            runCount++;
                            rect.y = y;
                        }
                        // Initialize x position in case there's just one column
                        rect.x = x;
                        rect.width = maxTabWidth/* - 2*/;

                    }
                    if (i == selectedIndex) {
                        selectedRun = runCount - 1;
                    }
                }

                if (runCount > 1) {
                    // Re-distribute tabs in case last run has leftover space
                    normalizeTabRuns(tabPlacement, tabCount, verticalTabRuns ? y : x, returnAt);

                    selectedRun = getRunForTab(tabCount, selectedIndex);

                    // Rotate run array so that selected run is first
                    if (shouldRotateTabRuns(tabPlacement)) {
                        rotateTabRuns(tabPlacement, selectedRun);
                    }
                }

                // Determine how much we want to pad the tabs
                int maxPad = 0;
                /*
                for (i = runCount - 1; i >= 0; i--) {
                int start = tabRuns[i];
                int next = tabRuns[i == (runCount - 1)? 0 : i + 1];
                int end = (next != 0? next - 1 : tabCount - 1);

                maxPad = Math.max(maxPad, rects[end].x + rects[end].width - rects[start].x);
                }*/
                switch (tabPlacement) {
                    case LEFT:
                    case RIGHT:
                        maxPad = size.height - tabAreaInsets.top - tabAreaInsets.bottom;
                        break;
                    case BOTTOM:
                    case TOP:
                    default:
                        maxPad = size.width - tabAreaInsets.left - tabAreaInsets.right;
                        break;
                }

                // Step through runs from back to front to calculate
                // tab y locations and to pad runs appropriately
                for (i = runCount - 1; i >= 0; i--) {
                    int start = tabRuns[i];
                    int next = tabRuns[i == (runCount - 1) ? 0 : i + 1];
                    int end = (next != 0 ? next - 1 : tabCount - 1);
                    if (!verticalTabRuns) {
                        for (j = start; j <= end; j++) {
                            rect = rects[j];
                            rect.y = y;
                            rect.x += getTabRunIndent(tabPlacement, i);
                        }
                        if (shouldPadTabRun(tabPlacement, i)) {
                            padTabRun(tabPlacement, start, end, maxPad);
                        }
                        if (tabPlacement == BOTTOM) {
                            y -= (maxTabHeight - tabRunOverlay);
                        } else {
                            y += (maxTabHeight - tabRunOverlay);
                        }
                    } else {
                        for (j = start; j <= end; j++) {
                            rect = rects[j];
                            rect.x = x;
                            rect.y += getTabRunIndent(tabPlacement, i);
                        }
                        if (shouldPadTabRun(tabPlacement, i)) {
                            padTabRun(tabPlacement, start, end, maxPad);
                        }
                        if (tabPlacement == RIGHT) {
                            x -= (maxTabWidth - tabRunOverlay);
                        } else {
                            x += (maxTabWidth - tabRunOverlay);
                        }
                    }
                }

                // Pad the selected tab so that it appears raised in front
                padSelectedTab(tabPlacement, selectedIndex);

                // if right to left and tab placement on the top or
                // the bottom, flip x positions and adjust by widths
                if (verticalTabRuns) {
                    int rightMargin = size.width - (insets.right + tabAreaInsets.right);
                    for (i = 0; i < tabCount; i++) {
                        rects[i].x = rightMargin - rects[i].x - rects[i].width;
                    }
                }

                switch (tabPlacement) {
                    case LEFT:
                    case RIGHT: {
                        int availableTabAreaHeight = size.height - insets.top - insets.bottom - tabAreaInsets.top - tabAreaInsets.bottom;
                        int usedTabAreaHeight = 0;
                        int pad = 0;
                        for (int run = 0; run < runCount; run++) {
                            int firstIndex = tabRuns[run];
                            int lastIndex = lastTabInRun(tabCount, run);
                            if (run == 0) {
                                usedTabAreaHeight = 0;
                                for (i = firstIndex; i <= lastIndex; i++) {
                                    usedTabAreaHeight += rects[i].height;
                                }
                                pad = (availableTabAreaHeight - usedTabAreaHeight) / 2;
                            }
                            for (i = firstIndex; i <= lastIndex; i++) {
                                rects[i].y += pad;
                            }
                        }
                        break;
                    }
                    case BOTTOM:
                    case TOP:
                    default: {
                        int availableTabAreaWidth = size.width - insets.left - insets.right - tabAreaInsets.left - tabAreaInsets.right;
                        for (int run = 0; run < runCount; run++) {
                            int firstIndex = tabRuns[run];
                            int lastIndex = lastTabInRun(tabCount, run);
                            int usedTabAreaWidth = 0;
                            for (i = firstIndex; i <= lastIndex; i++) {
                                usedTabAreaWidth += rects[i].width;
                            }
                            int pad = (availableTabAreaWidth - usedTabAreaWidth) / 2;
                            for (i = firstIndex; i <= lastIndex; i++) {
                                rects[i].x += pad;
                            }
                        }

                        break;
                    }
                }

            }

            private Insets add(Insets i1, Insets i2) {
                return new Insets(
                        i1.top + i2.top,
                        i1.left + i2.left,
                        i1.bottom + i2.bottom,
                        i1.right + i2.right
                );
            }

            private Insets add(int top, int left, int bottom, int right, Insets i1) {
                return new Insets(
                        i1.top + top,
                        i1.left + left,
                        i1.bottom + bottom,
                        i1.right + right
                );
            }

        }

    }

2º - Adicioná-la ao tabbedpane
tabbedPane.setUI(new CenterTabbedPane());

classe teste:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Tela1 extends JFrame {
    JTabbedPane tabbedPane;

    public Tela1() {
        setTitle("Tela");
        tabbedPane = new JTabbedPane();
        tabbedPane.addTab("Página 1", painel("painel 1"));
        tabbedPane.addTab("Página 2", painel("painel 2"));
        tabbedPane.setPreferredSize(new Dimension(getWidth(), 300));
        tabbedPane.setUI(new CenterTabbedPane());
        add(tabbedPane, BorderLayout.CENTER);
        JButton adicionar = new JButton("adicionar");
        adicionar.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                int tab = tabbedPane.getTabCount() + 1;
                tabbedPane.addTab("Página " + tab, painel("painel " + tab));
            }
        });
        adicionar.setBackground(Color.green);
        add(adicionar, BorderLayout.SOUTH);
        setVisible(true);
        setSize(600, 500);
        setLocationRelativeTo(null);
        setMinimumSize(new Dimension(getWidth(), getHeight()));
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    public static void main(String[] args) {
        new Tela1();
    }

    public JComponent painel(String titulo) {
        JPanel painel = new JPanel();
        JLabel label;
        label = new JLabel(titulo);
        painel.add(label);
        return painel; // retorna painel.
    }

}

Comment: Apesar de ser uma solução interessante, você não centraliza as tabs. Nesse exemplo mesmo, se adicionar tabs em runtime, perde a centralização. E não funciona com todos os LAFs do java. Testa ai com nimbus: http://pastebin.com/RypmNQER
Comment: correto, o que eu queria passar é que seria uma propriedade de LAFs que ele poderia manipular para resolver o problema, eu não postei como comentário pois queria mostrar como o código ficaria. Vou procurar uma melhor forma de explicar.  vlw
Comment: Só um adento: [sempre inicie uma aplicação grafica dentro da **EDT**](https://pt.stackoverflow.com/a/193456/28595). Achei interessante como resolveu, reescrevendo o componente, só que agora nenhum LAF aplica a ele, só o basic. Se o OP estiver usando o nimbus ou outro proprio, não vai aplicar neste componente `CenterTabbedPane`. Dai fica a criterio do OP essa perda.
Comment: @DavidCabral, você descobriu alguma forma de funcionar com o look&Fell ?
Comment: @GustavoSantos atualizei a resposta.. tenta agora.


Menu drop-down com bootstrap

Question: Estou estudando bootstrap. precisamente, um menu.
e fiquei confuso porque não esta repetindo o dropdown novamente. Porém so em 1 "LI" especifico.
Obrigado!
CSS
HTML:

 Página Inicial

                         Cadastrar

Cliente

Corretor

Moto

 Charts

 Panels

 Notifications

                         Cadastrar

Cliente

Corretor

Moto

 Tables

 Typography

 Icons

CSS:
https://pastecode.xyz/view/f8aaee66
Comment: Boa noite especifique mais a sua pergunta por favor.
Comment: O codigo abaixo do comentario serve para criar um drop down. De fato na primeira vez do codigo abaixo do comentario funciona. más se eu repetir ele abre o de cima e não o de baixo(drop down)
Comment: Vc está usando o mesmo `id` em ambos.
Comment: Não é um conflito com os ID's?
Answer: Não é um conflito de ID's? tente usar o seguinte  código.

 Página Inicial

                     Cadastrar

Cliente

Corretor

Moto

 Charts

 Panels

 Notifications

                     Cadastrar

Cliente

Corretor

Moto

 Tables

 Typography

 Icons

Como pode ver eu apenas alterei o ID da primeira DIV, lembre-se no HTML ID é único e cada elemento deve possuir um diferente caso contrário pode ocorrer conflitos, estou a disposição.
Comment: obrigado por responder pessoal! também pensei que era o ID. fiz a troca. mesmo assim permanece. digamos que eu coloquei o #subPages2. mesmo assim o #subPages é chamado.
Comment: HAHAHHAHAH QUE ERRO GROTESCO. FALTOU EU ALTERAR O ID DO DE BAIXO. VALEU POVO!
Comment: Já que minha resposta te ajudou ,você poderia dar um voto a favor na resposta para me ajudar?

Menu drop-down com bootstrap


Pathauto does not trigger on node_save when programatically creating nodes

Question: I am programatically saving nodes. From my reading, it sounds as if Path auto is trigged to autmatically create a URL alias when node_save() is called.  However, this is not happening.
I later read that I needed to set $node->path_set_alias = TRUE. However, this is not working correctly either.
Using 7.12 and the latest versions of pathauto.
Here is my code.
<code>$node = new stdClass();
        //set other defaults
        node_object_prepare($node);

        $node->type = $page_data['content_type'];
        $node->body[LANGUAGE_NONE][0]['value'] = $page_data['description'];
        $node->body[LANGUAGE_NONE][0]['summary'] = text_summary($page_data['description']);
        $node->body[LANGUAGE_NONE][0]['format']  = 'filtered_html';
        $node->title = $page_data['title'];
        $node->field_product_price[LANGUAGE_NONE][0]['value'] = $page_data['price'];
        $node->field_item_location[LANGUAGE_NONE][0]['postal_code'] = $page_data['zipcode'];
        $node->uid = "1";
        $node->status = 1;
        $node->active = 1;
        $node->pathauto_perform_alias = TRUE;

    //the name of my actual field is 'product images'
    $node->field_product_images[LANGUAGE_NONE] = $images;
    unset($images);

    $node->field_baby_clothes_category[LANGUAGE_NONE][0]['tid'] = $page_data['category'];

    if($node = node_submit($node)) { // Prepare node for saving
        node_save($node);
}
</code>
Thoughts on how to get this to work correctly? Thanks!
Comment: UPDATE - my problem still exists, however, something weird is happening. The paths are being generated and listing correctly in the url alias list.  The problem now is Drupal refuses to use them. What I mean is, even though the aliases exist, drupal uses node/xx instead. How do I get Drupal to use the alias?
Comment: You mean when visiting yoursite.com/my-article-title it redirects to yoursite.com/node/123, is it what you are saying?
Answer: We discussed on Drupal.org that not setting the $node->language property causes this issue to happen. Either setting $node->language = LANGUAGE_NONE or $node->language = 'en' should fix this.
Also using $node->path['pathauto'] = TRUE rather than $node->pathauto_perform_alias for Drupal 7.