Forecasting time series regression in R using lm and lag

Question: I would like to predict using a linear model in R.  The model that I have is of the form lm(y~ lag(x)).  It seems like I should be able to predict using the predict function, but this does not look ahead into the future.
Here is the lag function that I have been using from within R.
lag1 = function (x) c(NA, x[1:(length(x)-1)])

This lag function adds an NA at the beginning of the data, shifts everything down, and cuts off the last observation.
I am mostly interested in the predictions made on the last line of the data.  This line of data seems to be ignored by the fitted and predict functions.
The best workaround I have found was to multiply each of the model coefficients by each of my dependent variables, and add them up for each prediction.  None of the dependent variables are lagged at this point, when I set up this equation.  The problem with this is that each time I change the model formula, the names of the variables have to be changed to match the new formula.  It seems like there should be a more intuitive solution to this.
Comment: Simply feed the future regressor values to the `newdata` parameter of `predict.lm()`. Make sure they are in a `data.frame` with the same names as used in the formula in `lm()`.
Comment: Not sure I understand. Did you give new `x` values to the `predict()` function as the second argument?
Comment: @Stephan Kollasa, For time series data your solution unfortunately does not work.
Answer: Estimating with lags and using model for predicting is a sore point in base R. Here is the example:
set.seed(1)
y<-ts(rnorm(10))
x<-ts(rnorm(10))
lm(y~x)

Call:
lm(formula = y ~ x)

Coefficients:
(Intercept)            x
     0.2006      -0.2749

>    lm(y~lag(x))

Call:
lm(formula = y ~ lag(x))

Coefficients:
(Intercept)       lag(x)
     0.2006      -0.2749

Notice that in both cases the result is the same. This happens because of the somewhat peculiar behaviour of the default lag function. Compare x and lag(x)
 x
Time Series:
Start = 1
End = 10
Frequency = 1
 [1]  1.51178117  0.38984324 -0.62124058 -2.21469989  1.12493092 -0.04493361 -0.01619026  0.94383621  0.82122120
[10]  0.59390132
> lag(x)
Time Series:
Start = 0
End = 9
Frequency = 1
 [1]  1.51178117  0.38984324 -0.62124058 -2.21469989  1.12493092 -0.04493361 -0.01619026  0.94383621  0.82122120
[10]  0.59390132

As you can see the data is the same, only the attributes, in this case the time, are different. Hence the lm sees the same data, since it ignores the attributes. There are several ways of working around this behaviour. Here are few.
First you can convert the data to time series format for which the lag behaviour is "standard".  One of such formats is xts from package xts:
yy<-xts(y,as.Date(1:10))
xx<-xts(x,as.Date(1:10))
lm(yy~xx)

Call:
lm(formula = yy ~ lag(xx))

Coefficients:
(Intercept)      lag(xx)
     0.2754      -0.2798

See now the coefficient is different, since lag now correctly shifts the data:
lag(xx)
                  [,1]
1970-01-02          NA
1970-01-03  1.51178117
1970-01-04  0.38984324
1970-01-05 -0.62124058
1970-01-06 -2.21469989
1970-01-07  1.12493092
1970-01-08 -0.04493361
1970-01-09 -0.01619026
1970-01-10  0.94383621
1970-01-11  0.82122120

Another way is to estimate the regression using the function dynlm from package dynlm:
dynlm(y~L(x))

Time series regression with "ts" data:
Start = 2, End = 10

Call:
dynlm(formula = y ~ L(x))

Coefficients:
(Intercept)         L(x)
     0.2754      -0.2798

This covers the estimation. Now predicting is trickier. To get the fitted values you can simply use predict function:
predict(dynlm(y ~ L(x)))
          2           3           4           5           6           7           8           9          10
-0.14757748  0.16632219  0.44920672  0.89503027 -0.03934318  0.28796556  0.27992365  0.01132412  0.04562977
predict(lm(yy ~ lag(xx)))
          2           3           4           5           6           7           8           9          10
-0.14757748  0.16632219  0.44920672  0.89503027 -0.03934318  0.28796556  0.27992365  0.01132412  0.04562977

Predicting ahead in a future though presents a problem. The default behaviour of predict function is to expect newdata argument. But for one step ahead forecast in this case, no new data is required. So standard predict function will not work in this case. I would love to see a general solution for this problem, but in my knowledge different packages provide different ways of getting such forecasts and if you do not want to write the function yourself you need to cast your model in a form which is required by a specific forecasting function from a specific package. And you need to know that package pretty well.
One of such packages is midasr (of which I am developer). One step ahead forecast for such model would be implemented in the following way:
midas_u(y~mls(x,1,1))

Call:
lm(formula = y ~ mls(x, 1, 1), data = ee)

Coefficients:
 (Intercept)  mls(x, 1, 1)
      0.2754       -0.2798

forecast(midas_u(y~mls(x,1,1)),newdata=list(x=NA))
[1] 0.1092301

The package midasr works with mixed frequency data. The function mls has 3 arguments, data, lag numbers and frequency ratio. In this case the frequency is the same so the third argument is 1. In that case the function works exactly as the function lag for xts objects. For forecasting it is necessary to supply new data. As we do not know it we supply the NA which works in this case, since one-step ahead forecasts in this case needs only the data which we already know.
The last value of x is  0.59390132, so you can check that the result is the correct one directly
> 0.59390132*(-0.2798)  +0.2754
[1] 0.1092264

The answer is correct to 4 decimal places, since I used the coefficients with 4 digit accuracy.


Swift Dictionary getting optional values

Question: It's been about years since I've done any work in macOS and more than two since I've touched Swift. I'm running myself in circles on this:
I have two functions, the first contains a while loop to check the value within a dictionary returned by the second. :
func checkPath(_ strPath:String) {

...
while bIsDesktop == false {
    let dictResults:Dictionary<String, Any> = checkPath(arrPath)

    if dictResults["isDesktop"] { //-->I'm getting crushed here
        //do something with returned array
    }

}

private func checkPath(_ arrPath:Array<String>) -> Dictionary<String, Any> {
    var bIsDesktop = false
    var arrPath = arrPath
    if arrPath[0] != "Desktop" {
       arrPath.removeFirst()
    } else {
       bIsDesktop = true
    }

    return ["paths":arrPath, "isDesktop":bIsDesktop]
}

arrPath is an array of strings (file path items)
I know the returned dictionary is like so [String:Any]
Problem is no matter what I do I run into some sort of compiler error like:
Optional type 'Any?' cannot be used as a boolean; test for '!= nil' instead

In the grander scheme of things, in case there's a more elegant solution, what I am trying to do is strip the path to a folder selected by the user of the ///File:User/username/Desktop/... and just have Desktop/... If there's a better solution than what I am attempting I'd appreciate seeing it but if you could also explain why I can't get the optional out of the dictionary I'd appreciate that as well.
I've tried:
guard let bIsDesktop = dictResults["isDesktop" as Bool else { ...
if dictResults?["isDesktop"]...

and various other permutations. Either I get nil or a compiler error.
Comment: Look up "conditional binding". More generally, read the Swift language guide, cover to cover. https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html
Comment: You shouldn't be using `String` paths for file handling. Use `URL`s instead, which have helper properties/methods, such as `lastPathComponent` that will come in handy for your goals.
Comment: I honestly don't know what you are trying to do just by reading your code. So you want to delete everything before `Desktop`? What if the path does not have `Desktop`?
Comment: @DávidPásztor better to get the URL resource values (localizedname) https://stackoverflow.com/questions/28570627/how-to-find-file-uti-for-file-withouth-pathextension-in-a-path-in-swift/34772517?r=SearchResults&s=2|31.8892#34772517
Answer: I do think you ran into a complex error and I didn't test your entire story. My apologies for that and still trying to post this as a solution.
To my first knowledge, you are trying to see if a variable is true or not with the statement:
if dictResults["isDesktop"] { //-->I'm getting crushed here
        //do something with returned array
    }

The problem is that you know, or imply, that the dictionary entry at dictResult["isDesktop"] is a boolean. However, your compiler doesn't know, since your provided it with the knowledge it can be of type "Any".
This doesn't't sit well with the compiler, since it cannot determine that an "Any" type is either true or false.
As far as I understand, you first have to cast dictResult["isDesktop"] to a boolean before you can ask the compiler to evaluate it to be true or false. If you don't cast it to a boolean, you have to treat it as a none boolean type and tell the compiler in the if-statement to evaluate it to the value you want.
The compiler error is basically telling you: "I don't know what type Any? is, but I know it can be some value or none. If you put in a statement "if (type), I assume you want me to evaluate this optional to have a value or not. This is not what you want, you want to tell the compiler that it needs to evaluate the statement as a bool.
I think either should work:
if let result = dictResults["isDesktop"] as? bool {

}

or
if (dictResults["isDesktop"] as bool) {

}

Again, I haven't tested it and I'm sorry. I do think this is the solution to this problem.
Kind regards,
MacUserT


Can it be over fitting when validation loss and validation accuracy is both increasing?

Question: Training a simple neural network over a very sparse matrix (Has 2400 features and 18000 train rows) for a binary classification problem. At the end of 1st epoch validation loss started to increase, whereas validation accuracy is also increasing. Can i call this over fitting? I'm thinking of stopping the training after 6th epoch. My criteria would be: stop if the accuracy is decreasing. Is there something really wrong going on?
ps: I have perfectly balanced binary classification dataset and a random classifier would result around %50 accuracy.
Comment: Based on the second graph you would say that your model is overfitting, since a similar increase in accuracy from the training set does not happen on the test set.
Comment: Yes but the accuracy is increasing a bit, even to the %65 accuracy level.. If i stop my network when validation loss is increasing i get %55 accuracy. Wouldn't it be better to have %65 accurate network over %55? I am questioning the stopping criteria.
Comment: I would say from epoch 3 forward the increase is marginal. Maybe this validation loss criterion is not the best in your case.
Answer: Yes, absolutely. First of all, overfitting is best judged by looking at loss, rather than accuracy, for a series of reasons including the fact that accuracy is not a good way to estimate the performance of classification models. See here:
https://stats.stackexchange.com/a/312787/58675
Why is accuracy not the best measure for assessing classification models?
Classification probability threshold
Secondly, even if you use accuracy, rather than loss, to judge overfitting (and you shouldn't), you can't just look at the (smoothed) derivative of accuracy on the test curve, i.e., if it's increasing on average or not. You should first of all look at the gap  between training accuracy and test accuracy. And in your case this gap is very large: you'd better use a scale which starts either at 0, or at the accuracy of the random classifier (i.e., the classifiers which assigns each instance to the majority class), but even with your scale, we're talking a training accuracy of nearly 100%, vs. a test accuracy which doesn't even get to 65%.
TL;DR: you don't want to hear it, but your model is as overfit as they get.
PS: you're focusing on the wrong problem. The issue here is not whether to do early stopping at the 1th epoch for a test accuracy of 55%, or whether to stop at epoch 7 for an accuracy of 65%. The real issue here is that your training accuracy (but again, I would focus on the test loss) is way too high with respect to your test accuracy. 55%, 65% or even 75% are all crap with respect to 99%. This is a textbook case of overfitting. You need to do something about it, not focus on the "less worse" epoch for early stopping.
Comment: What would be the best way to approach to the problem i have tried noises, dropouts etc? I wouldn't expect a better test accuracy then %65 for this dataset. Should i be preventing the network to get a high train accuracy? Or should i prevent the gap to be widen a lot?
Comment: as a side note: I have perfectly balanced binary classification dataset.
Comment: it's impossible to answer if you don't a) describe in detail what's your problem, b) explain the why you don't expect a better than 65% test accuracy for this dataset. Of  course "I have a hunch that test accuracy can't better than 65%" is **not** a valid reason, while "I have extensive bibliographic evidence that SOTA on this dataset, or on a _extremely similar_ one, cannot exceed 65%" is a valid reason. See https://stats.stackexchange.com/a/363895/58675 for some references on SOTA results for different ML problems (alas, mostly NLP and CV). And btw, note that how to reduce the test error 1/
Comment: 2/ on your problem is a completely different question from what you asked. You need to ask a new question and describe your actual dataset & model much more in detail, as well as describe extensively all the things you have already tried. For your own sanity, I hope you're not using Jupyter notebooks to keep track of this kind of extensive numerical experiments.
Comment: @DeltaIV interesting, what do you suggest using instead of Jupyter notebooks to track this kind of experiments? That's a serious question as I've been doing exactly that lately and starting to feel this pain.
Comment: @Jivan comments are not for extended discussion or question answering. Check which SE site would be more appropriate for such a question and ask there. I don't think CV is the right place to ask about tools to track deep learning numerical experiments....you may still ask on Meta    to get a second opinion though.
Comment: @DeltaIV well I was just hoping that you'd throw a couple/handful of words here in order to get on the right track, nothing elaborate or extended
Answer: There is at least two possible cause to this curve variation in this case that can happen. The reasonable possible distinctions that we can assume by looking at this graphical dataset, is as follow :
1- This training network indicate validation loss because the model is overfitting.
This answer here could be is a personal review by myself while studying this subject, and having hard time to come over the conclusion. There is many answer here, but the ideal choice would be the number 1 answer that i have mentioned.
2- Other possible cause would be that this training network have unknown variante or error in the trained dataset, like a spontaneous reaction for example.
Feel free to comment.


Views REST Endpoint With paragraph field

Question: I've created a REST export view to get a paragraph field in a JSON format but I cannot get the result properly, so I used Rest Views module but I got the results including something like these characters <code>\u003Ca href=\u0022\/colors\/gray-metallic\u0022 hreflang=\u0022en\u0022\u003EGray Metallic\u003C\/a\u003E</code>
Also, this paragraph field includes a term reference field.
So I want to render the data properly without these characters and as a plain text
Answer: I have solved by using jQuery.parseHTML() or you can use Javascript DOMParser
Something like this
<code>$.ajax({
    type: 'GET',
    url: drupalSettings.path.baseUrl + 'REST_VIEW_PATH/' + nid,
    success: function (data) {
        {
            var paragraphField = data[0]['FIELD_NAME'];
            $.each(paragraphField, function (index, item) {
                var fieldItem = $.parseHTML(item.FIELD_ID_IN_PARAGRAPH);
                console.log(fieldItem[0]['innerText']);
            });
        }
    }
});
</code>


In HighStock, linking secondary yAxis to master yAxis can cause secondary values to be cropped outside the chart

Question: Simplifying my story, consider 2 series where I link their yAxes. In other words on the second yAxis there is a property linkedTo: 0
So the first yAxis is the master, hence sets extremes for both series.
However sometimes the second series has high values which are too high to be plotted in the visible area and so they get cropped.
To make matters worse, when the yAxes are linked to each other, the legend doesn't play ball: clicking on the master series name in the legend will hide both series. Clicking on the secondary series name will hide none.
Check out this JSFiddle - values on the right are cropped, legend functionality is broken.
What am I missing? How can I get both series to scale together and be all visible? How do I get the legend to work as expected? (click on series name should toggle it)
Thanks!
EDIT: As it turns out, if I remove yAxis.id (JSFiddle here) the chart and legend work as expected. However linking series to yAxis based on position in the array (I think?) instead of by some ID (string) sounds less than ideal.
Ideas?
Comment: Could you recreate your issue in the jsfiddle.net ?
Comment: http://jsfiddle.net/zYpcm/13/
Answer: Why you are trying assigning second series to axis which is just copy of proper one? I advice to set both series to master yAxis, and second yAxis use just as extra info on the right side of a chart.
Otherwise I don't understand the purpose of linking second axis to get THE SAME extremes as master yAxis, and then expecting to scale that yAxis according to series you have attached to that yAxis.
Something like this I think is better approach, see: http://jsfiddle.net/zYpcm/15/
        series: [{
            name: 'master',
            data: self.masterData,
            yAxis: 'master'
        }, {
            name: 'secondary',
            data: self.secondaryData,
            //yAxis: 'secondary'
        }],

        yAxis: [{
            id: 'master'
        }, {
            id: 'secondary',
            opposite: true,
            linkedTo: 0
        }]

Comment: How does the second series get linked to the first yAxis? To me it looks as if secondary **series** is linked to second **yAxis** (without yAxis indicated in the series, I assume they are linked by having the same position in the array?) and that second **yAxis** is `linkedTo` the first **yAxis**.
Put in other words, in your solution I can't see the value of `yAxis: 'master'`
Comment: No, if you don't specify `yAxis: index/id` all series are linked to first yAxis. Of course, you can remove `yAxis: 'master'` it's unnecessary there.


Expected minimum distance from a point with varying density

Question: I'm looking at how the expected minimum Euclidean distance between randomly uniform points and the origin changes as we increase the density of random points (points per unit square) around the origin. I have managed to come up with a relationship between the two described as such:
$$\text{Expected Min Distance} =\frac{1}{2\sqrt{\text{Density}}}$$
I came up with this by running some Monte Carlo simulations in R and fitting a curve manually (code below).
My question is: could I have derived this result theoretically rather than through experimentation?
#Stack Overflow example
library(magrittr)
library(ggplot2)

#---------
#FUNCTIONS
#---------
#gen random points within a given radius and given density
gen_circle_points <- function(radius, density) {
  #round radius up then generate points in square with side length = 2*radius
  c_radius <- ceiling(radius)
  coords <- data.frame(
    x = runif((2 * c_radius) ^ 2 * density, -c_radius, c_radius),
    y = runif((2 * c_radius) ^ 2 * density, -c_radius, c_radius)
  )
  return(coords[sqrt(coords$x ^ 2 + coords$y ^ 2) <= radius, ])#filter in circle
}

#Example plot
plot(gen_circle_points(radius = 1,density = 200)) #200 points around origin
points(0,0, col="red",pch=19) #colour origin

#return euclidean distances of points generated by gen_circle_points()
calculate_distances <- function(circle_points) {
  return(sqrt(circle_points$x ^ 2 + circle_points$y ^ 2))
}

#find the smallest distance from output of calculate_distances()
calculate_min_value <- function(distances) {
  return(min(distances))
}

#Try a range of values
density_values <- c(1:100)

expected_min_from_density <- sapply(density_values, function(density) {
  #simulate each density value 1000 times and take an average as estimate for
  #expected minimum distance
  sapply(1:1000, function(i) {
    gen_circle_points(radius=1, density=density) %>%
      calculate_distances() %>%
      calculate_min_value()
  }) %>% mean()
})

results <- data.frame(density_values, expected_min_from_density)

#fit based off exploration
theoretical_fit <- data.frame(density = density_values,
                              fit = 1 / (sqrt(density_values) * 2))

#plot monte carlo (black) and fit (red dashed)
ggplot(results, aes(x = density_values, y = expected_min_from_density)) +
  geom_line() +
  geom_line(
    data = theoretical_fit,
    aes(x = density, y = fit),
    color = "red",
    linetype = 2
  )

Comment: The $2$ is the width of your square.
Comment: The (asymptotic) direct dependence on the inverse root of density follows easily and immediately from considerations of the units of measurement, so the only question concerns why the multiple is $1/2.$
Comment: @whuber Yes I'd noticed the units lined up nicely and yes, the question becomes: where did the 2 come from?
Answer: Consider the distance to the origin of $n$ independently distributed random variables $(X_i,Y_i)$ that have uniform distributions on the square $[-1,1]^2.$
Writing $R_i^2 = X_i^2+Y_i^2$ for the squared distance, Euclidean geometry shows us that
$$\Pr(R_i \le r \le 1) = \frac{1}{4} \pi\, r^2 $$
while (with a little more work)
$$\Pr(1 \le R_i \le r \le \sqrt{2}) = \frac{1}{4}\left(\pi\, r^2 + 4\sqrt{r^2-1} - 4 r^2 \operatorname{ArcTan}\left(\sqrt{r^2-1}\right)\right).$$

Together these determine the distribution function $F$ common to all the $R_i.$
Because the $n$ points are independent, so are the distances $R_i,$ whence the survival function of $\min(R_i)$ is
$$S_n(r) = (1 - F(r))^n,$$
implying the mean shortest distance is
$$\mu(n) = \int_0^\sqrt{2} S_n(r)\, dr.$$
For $n\gg 1,$ almost all the area in this integral is close to $0,$ so we may approximate it as
$$\mu_\text{approx}(n) = \int_0^1S_n(r)\, dr = \int_0^1\left(1 - \frac{\pi}{4}r^2\right)^n\,dr.$$
The error is not greater than the part of the integral that was omitted, which is in turn no greater than
$$(\sqrt{2}-1)(1-F(1))^n = (\sqrt{2}-1)(1 - \pi/4)^n,$$
which obviously decreases exponentially with $n.$
We may in turn approximate the integrand as
$$\left(1 - \frac{\pi}{4}r^2\right)^n \approx \exp\left(-\frac{1}{2} \frac{r^2}{2/(n\pi)}\right).$$
Up to a normalizing constant, this is the density function of a Normal distribution with mean $0$ and variance $\sigma^2=2/(n\pi).$  The missing normalizing constant is
$$C(n) = \frac{1}{\sqrt{2\pi \sigma^2}} = \frac{1}{\sqrt{2\pi\ 2 / (n\pi)}} = \frac{\sqrt{n}}{2}.$$
Therefore, extending the integral from $1$ to $\infty$ (which adds an error proportional to $e^{-n}$),
$$\mu_\text{approx}(n) \approx \int_0^\infty e^{-t^2/(2\sigma^2)}\,dt = \frac{1}{C(n)} \frac{1}{2} = \frac{1}{\sqrt{n}}.$$
In the process of obtaining this approximation three errors were made.  Collectively they are at most of order $n^{-1},$ the error incurred when approximating $S_n(r)$ by the Gaussian.

This figure plots $n$ times the difference between $1$ and $\sqrt{n}$ times the mean shortest distance observed in $10^5$ separate simulated datasets for each $n.$  Because they decrease as $n$ grows, this is evidence that the error is $o(n^{-1}/\sqrt{n}) = o(n^{-3/2}).$
Finally, the factor $1/2$ in the question derives from the size of the square: the density is the number of points $n,$ per unit area and the square $[-1,1]^2$ has area $4$, whence
$$2\sqrt{\text{Density}} = 2\sqrt{n/4} = \sqrt{n}.$$

This is the R code for the simulation:
n.sim <- 1e5  # Size of each simulation
d <- 2        # Dimension
n <- 2^(1:11) # Numbers of points in each simulation
#
# Estimate mean distance to the origin for each `n`.
#
y <- sapply(n, function(n.points) {
  x <- array(runif(d*n.points*n.sim, -1, 1), c(d, n.points, n.sim))
  mean(sqrt(apply(colSums(x^2), 2, min)))
})
#
# Plot the errors (normalized) against `n`.
#
library(ggplot2)
ggplot(data.frame(Log2.n = 1:length(n), Error=sqrt(n)* (1 - y * n^(1/d))),
       aes(Log2.n, Error)) + geom_point() + geom_smooth()
  ylab("Error * n") + ggtitle("Simulation Means")

Comment: Wow! What an answer! Thanks a lot, this is great. Thanks!
Comment: @Michael Thank you, there is a typo--but it's not the one you suggest: one of my "$r$" should have been "$4$."  I have fixed that one.
Comment: Hi @whuber, I was trying to reproduce your $F(r)$ and I noticed your equation for $F(\sqrt{2})$ doesn't  return $1$ like your graphs shows. When I calculated $\text{Pr}(1 \leq R_i \leq r \leq \sqrt{2})$ I got $\pi/4 - r (r \text{ArcCos}(1/r) - \sqrt{1-1/r^2})$ which gives the curve you provided. Have you made a typo?


Cook's Distance

Question: The formula of Cook's distance is
$$D_i=\frac{(\hat Y-\hat Y(i))^{\prime}(\hat Y-\hat Y(i))}{p\times MSE}$$
where,
$\hat Y$ is the prediction from the full regression model  and $\hat Y$ is a $(n\times 1)$ matrix
$\hat Y(i)$ is the prediction from a refitted regression model in which observation $i $ has been omitted. That is ,  $\hat Y(i)$ is a $((n-1)\times 1)$ matrix.
So the order of $\hat Y$ and  $\hat Y(i)$ is not same. Then How can i subtract this two matrix since for subtracting we need equal order of two matrices.
Answer: You can exclude the $i{^\mathrm{th}}$ observation while estimating the model and include it again when predicting $\hat{Y}(i)$, thus resulting in a matrix of the same order as $\hat{Y}$.

Cook's Distance


Split String with comma and get the last two values

Question: I have field type string that can get two type of values on it:

simple field  e.g. p1
complex fields     p1/p2/p3/p4

Now I have 2 questions:

how can I identify that the  type is complex with little effort as possible since
the check is runs in loop?
when I got type complex I need to store the last two properties for
example p3 and P4?
Comment: What did you try? Have you read API documentation?
Comment: I have tried something like String[] prop = strprop.split("/"); but How I got the last two properties with size -1 there is more convenient way ?
Answer: just use split operation and check length.
String[] prop = strprop.split("/");
if(prop.length > 1){
    String El = prop[prop.length];
    String El0 = prop[prop.length-1];
}

Comment: you should use [java naming conventions](http://java.about.com/od/javasyntax/a/nameconventions.htm)... And also, `prop[prop.length];` will return a ArrayIndexOutOfBoundsException
Comment: I have tried your code String str = "p1\\p2\\p3";

  String[] prop = str.split("\\");

  if (prop.length > 1)
  {
   String El = prop[prop.length];
   String El0 = prop[prop.length - 1];

   System.out.println("test");
  }
Comment: the error in str.split at java.util.regex.Pattern.error(Unknown Source)
 at java.util.regex.Pattern.compile(Unknown Source)
 at java.util.regex.Pattern.(Unknown Source)
Comment: @FedorE: Note that [split](http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#split(java.lang.String)) accepts a regular expression.
Answer: To answer 1) I would use (assuming variable str contains your value):
str.contains("/"); // If true => complex type

For 2):
String[] vals = str.split("/");
String lastVal = vals[vals.length-1];
String preLastVal = vals[vals.length-2];

Please note that you should check for array length before trying to get the values, otherwise you're likely to get an ArrayIndexOutOfBoundsException.
Comment: Array has no length() method.
Comment: HI I have test your code and i got dump in String[] prop = str.split("\\"); the code is :      String str = "p1\\p2\\p3";

  String[] prop = str.split("\\");

  if (prop.length > 1)
  {
   String El = prop[prop.length];
   String El0 = prop[prop.length - 1];

   System.out.println("test");
  }
Comment: the error is at java.util.regex.Pattern.error(Unknown Source)
 at java.util.regex.Pattern.compile(Unknown Source)
 at java.util.regex.Pattern.(Unknown Source)
 at java.util.regex.Pattern.compile(Unknown Source)


Cross validated $R^2$ and the adjusted $R^2$?

Question: What are the similarities and differences between cross validated $R^2$ and adjusted $R^2$?
Comment: I can think of several different ways to construct a "cross-validated $R^2$."  What exactly do you mean by this?
Answer: Both allow you to compare models. But.
Cross-validated $R^2$ is likely to give you the $R^2$ you would observe generalizing your model to unseen data (provided the distributions of the train data and the test data remain the same).
Adjusted $R^2$ is a way to compare models, possibly helps you to pick up the best, penalizing them for the number of predictors they use. This does not give you any hint regarding the performance of the models on new data.
Answer: When you add more predictors to your regression model, the classical R2 artificially increases for the same prediction quality. That's why there is an adjusted one. You can find more information on Minitab's blog
Comment: Your Answer doesn't really address the question of the OP, which is what are differences/similarities between a cross-validated $R^2$ and the adjusted $R^2$.


Why is my Drupal ajax form not populating the radio buttons

Question: I have a form which send an ajax request to my server. The form is:
function dokimi_add_to_list_form($form, $form_state) {

  $form = array();

  $options=array(
      'option1'=>'option1',
      'option2'=>'option2'

  );

  $form['private_list'] = array(
    '#type' => 'radios',
    '#title' => 'Private lists',
    '#options' => $options,
    '#prefix'=>'
',
    '#suffix'=>'
'
  );

  $form['add_new']= array(
    '#type' => 'fieldset',
    '#markup' => 'Add a list'
  );

  $form['add_new']['new_list']= array(
    '#type' => 'textfield',
    '#title'=> 'New list',
    '#default_value' => '',
  );

  $form['add_new']['add']= array(
    '#type' => 'button',
    '#value' => t('Add'),
            '#ajax'=>array(
              'callback' => 'add_to_list_callback',
              'wrapper'=>'list_list'
                  // 'wrapper' is the HTML id of the page element that will be replaced.
        )
      );

 return $form;
}

And the callback function is:
function add_to_list_callback($form, $form_state){

    $options=array(
      'newoption1'=>'newoption1',
      'newoption2'=>'newoption2',
      'newoption3'=>'newoption3'
  );
    $form['private_list'] = array(
        '#type' => 'radios',
        '#title' => 'Private list',
        '#options' => $options,
        '#prefix'=>'
',
        '#suffix'=>'
'
  );

    $commands = array();
    $commands[]=ajax_command_replace('#list_list', render($form['private_list']));
    return array(
        '#type'=>'ajax',
        '#commands'=>$commands
    );

}

When the 'Add' button is clicked, a new array of options should be returned, but I get an empty list instead.
The form is rendered in a ctools modal if that is of importance.
Thanks for any help with this - it's driving me barmy.
Answer: I think you need to reorganize your code.
First you need two ['Private_list'] at the same function Form and at this same function form you need to declare the array variables for each private list.
$list1_options = array(......);
$list2_options = array(.......);

['Private_list1´]: these are the first choice the user need to do: here you use the ajax call back.
['Private list2']: these one have the choices the user need to pick according to the first selection on ['Private_list1´]: at this 'Private_list2' you use the wrapper prefix and suffix.
the ajax call back function should only look something like this most of the times:
function example_change_callback($form, &$form_state) {
  return $form['private_list2'];
}

Your basicly using the call back to identify wich form you need to update on event change.
I recommend you study this drupal dependent ajax example, dispate the example is using dropdown list, you should be able to aply it to radio buttons, just follow the same structure.
I hope i was hepfull, tell us later how it went...
Have a good coding!
Comment: Yes thanks Hawk. I did finally work this out. I was trying to construct the form element in my callback, whereas it should be done in the main form function. the options were just to illustrate it, the main point is the callback.
Comment: Glad to hear that!


Combination of Password Question

Question: Suppose that a password for a computer system must have at least 8, but not more than 12, characters, where each character in the password is a lowercase English letter, an uppercase English letter, a digit, or one of the six special characters *, >, <, !, +, and =.
(a) How many different passwords are available for this computer system?
(b) How many of these passwords contain at least one occurrence of at least one of the six special characters?
My attempt:
lowercase = $26$ chances
uppercase = $26$ chances
digits = $10$ chances
characters = $6$ chances
$26 + 26 + 10 + 6 = 68$
$68^{12} - 68^8 = 21,381,376$ combinations.
Another attempt of mine, I dunno which is correct:
$$
{68\choose 12} - {68\choose 8} = 7,282,025,622,664 - 7,392,009,768 = 7.2746\times 10^{12}
$$
Comment: Can you justify why you took $68^{12} - 68^{8}$?
Comment: @martin For the b) question I would use your first attempt and without the special characters and then just what you got from a) - b).
Answer: a) There are 68 characters. Can you justify why you took $68^{12} - 68^{8}$?
Your first approach would be nearly correct.
b) Hint: How many passwords do not contain one of the 6 special characters?
Comment: i thought there are 68 characters and the lenght is between 8 and 12 so max is 12 68^12 and minus all the combinations before 8 length so we only get the between values. @Calvin Lin
Comment: @matin Note that we allow for passwords of length 8. How many passwords of minimum length 12 and maximum length 12 are there?
Comment: im really confused now :D we can only allow length 8-12 right ? if its less than 8 then not acceptable, more than 12 also the same...
Comment: @Matin try answering this different question using your logic: How many passwords have a minimum length of 12, and a maximum length of 12?
Comment: i guess it will be 68^12 ?
Comment: @matin Good, but what if you tried it using your previous logic? You would have said $68^{12} - 68^{12}$ right?
Comment: correct, so now how i can correct my answer above with new logic ?
Comment: @matin That is a good question. How would you correct it? What was the mistake that you were making? Why were you thinking of subtracting something away? What does the number $68^{12}$ represent?
Comment: $68^12$ gives is choosing 12 characters between 68 characters including repetition of characters...
Comment: Great. And what is the question asking for? It wants the number of passwords with ….
Comment: yes but with respect to the length ofcourse
can you solve it for me, then i can understand better.
thanks
Comment: @CalvinLin Please correct me if I am wrong: $68^{12} - 68^{7}$. Basically $68^{12}$ represents all combinations of passwords of length 12 with the above mentioned characters.
Answer: I think should be like this 68^8+68^9+....+68^12=9.9207*10^21.
about the second question is that, it should be 9.9207*10^21-(62^8+62^9+....+62^12)=6.6415*10^21.
Comment: [Here's a MathJax tutorial](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) :)
Answer: You have choice of a string length 8, 9, 10, 11, or 12. The set of acceptable characters contains 68 possibilities. So the total number of possibilities for the 8-string is $68^8$, for the 9-string is $68^9$, so the total number of possible passwords is $\sum_{i=8}^{12} 68^i \approx 9.92\times10^{21}$
For the second question, the number of passwords that contain at least one of the six characters in the "special set" is the total minus those the contain none from that set. The total possibilities containing none from the special set can be calculated using a reduced character space of 62, and it would be $\sum_{i=8}^{12} 62^i \approx 3.28 \times 10^{21}$ so the number of passwords with at least one of character from the set is:
$$
\sum_{i=8}^{12} \left(68^i - 62^i\right) \approx 6.64\times 10^{21}
$$
Comment: Your summation formula is incorrect. You want $8 \le i \le 12$ and not $1 \le i \le 12$ as written.
Comment: Yup; good catch. The values are correct, but the indices were not. Thanks.

Combination of Password Question


Stacked Bar Plot with barplot() from CSV

Question: I am trying to obtain a barplot from a CSV file but I having some problems.
P;I;R;F1;F2;F3
20140101;50;20;7;7;16
20140108;55;22;9;9;15
20140115;52;21,4;8,6;10;12

First I open my .csv
d<-read.csv('d:\\Users\\140050es\\Desktop\\R\\test2.csv', header = F, sep = ",")

Then I assign a table: ( I don't know if this step is ok)
data<-table(d$I,d$R,d$F1,d$F2,d$F3)

And then I plot my data:
barplot(data,main="barplot()",xlab="Periodo",col=c("blue","red","green","orange","gold")

But R doesn't plot anything.
Comment: I think one probles is that R reads wrong the csv. file.
Comment: One error is in the sep="" field
Comment: Try using `read.csv2` instead or defining `sep = ";"`. Your data is separated by ";" not ",". That is the default in `read.csv2` so you wouldn't need to specify the `sep` argument in that case.
Comment: ok! Thats correct! but is ok the way I asign the "data" table for plotting after?
Comment: I doubt that that is necessary. When reading your data from a `csv` file, you have it in `d` which is a `data.frame` and you can use that as input for plotting a barplot. `table()` is a function that creates a table of frequencies, see `?table` - It's not clear to me what exactly you want to plot. Can you describe the desired barplot based on the sample data that you show in your question?
Comment: # Stacked Bar Plot with Colors and Legend
counts <- table(mtcars$vs, mtcars$gear)
barplot(counts, main="Car Distribution by Gears and VS",
  xlab="Number of Gears", col=c("darkblue","red"),
  legend = rownames(counts))
Comment: try to compile this and you will see exactly what do I want! thanks
Comment: That is an example of a stacked barplot, but what I meant is which exact variables (columns) do you want to plot in your stacked bar plot? In your sample data there are the variables P (which is a date), I, R, F1, F2, F3 -> what should be the x-axis (equivalent to Number of Gears) and what is the stacking variable (equivalent to 0/1)?
Comment: Exactly!! The equivalent to "Number of Gears" is my variable P and the stacking variable are I,R,F1,F2,F3.

I wanted to reprent for example row 1:
in 50 (I) there are 20 (R) + 7(F1) 7 (F2) and 16 (F3)
Answer: In barplot each column of the input matrix corresponds to a group of bars, and each row to different bars within groups. Because it seems like your groups are defined by the 'P' variable, you need to transpose the data. Then each column corresponds to one 'P date', and rows correspond to values for respectively I, R, F1, F2 and F3.
The 'Value' of the barplot call is "A numeric vector [...] giving the coordinates of all the bar midpoints drawn, useful for adding to the graph.". Thus, we collect these midpoints in a variable 'bp', and use them as positions (at argument) for the x axis labels.
df <- read.csv2(text = "P;I;R;F1;F2;F3
                20140101;50;20;7;7;16
                20140108;55;22;9;9;15
                20140115;52;21,4;8,6;10;12")

bp <- barplot(t(df[ , -1]), col = c("blue", "red", "green", "orange", "gold"))

axis(side = 1, at = bp, labels = df$P)

Comment: Your trip on the R path will be so much smoother if you read some basic introductory texts (see e.g. [**here**](http://stackoverflow.com/tags/r/info)), and read carefully about subsetting data. See e.g. `?Extract`, [**here**](http://www.burns-stat.com/documents/tutorials/impatient-r/more-r-subscript/) and [**here**](http://adv-r.had.co.nz/Subsetting.html). Then try `df[ , -c(1:2)]`.
Comment: Exactly!! The equivalent to "Number of Gears" is my variable P and the stacking variable are I,R,F1,F2,F3. I wanted to reprent for example row 1: in 50 (I) there are 20 (R) + 7(F1) 7 (F2) and 16 (F3)
Comment: you are representing the sum os my stacking variables.
Maybe this barplot() i want isn't named Stacked Bar Plot .......
Comment: To me it is unclear what you wish to achieve with `table(d$V1,d$V2,d$F1,d$F2,d$F3)`. The variable names does not correspond to your data. Please also read carefully about the `height` argument in `?barplot`, and play with the examples. And yes, the plot in my answer is a stacked barplot.
Comment: What should I do if I don't want to consider my variable P (because its the sum and its indifrent to have it on the bar plot)???
Comment: And I really don't understand what you mean by "don't want to consider my variable P". Which variable should be on the x-axis?
Comment: Sorry Henrik I meant my variable I
Comment: without changing my .csv how can i do to 'ignore' I column


How to select by default nodes of a content type in admin/content through a link?

Question: I'd like to make a link to admin/content/, but when the page was displayed I'd like to have it filtered by a certain content type.
The link can be like this admin/content/house so when I click it, the admin/content page is already filtered by house Content Type.
Is this possible?
Is something like this How to link to dblog filtered by type? but for the admin/content path.
Edit: If I click in a link that can be like this admin/content/house I can have in the admin/page the Content Types filtered by House, something like this picture
Comment: What do you mean filter by a content type?
Comment: @Namari I edit with a picture
Comment: It doesn't work with the SYSTEM PATH SETTINGS and the contextual filter on the "admin_views_node". You might have to do the changes in node.admin-content.inc or with a views function.
Comment: @Namari the use of /admin/content/house is just and example, the path can be other.
Comment: Yes I know, that's why I was looking into the "/%" but you can use the parameters with GET as suggested by gapple
Answer: It looks like you're making use of the Admin Views module, so you can add filter options as GET parameters in the URL: http://localhost/admin/content?type=article
You can also make a clone of the content admin view and modify it. This would allow you to set contextual filters, modify the exposed filter fields, or adjust visible columns to make a more targeted content listing.
Comment: Yes I use the Admin Views module, can you tell me where do you found the answer, just for read a little about this?
Comment: I'm just familiar with views.  If you hover over the table header links, you can view all of the parameters that are set for filters and sorting.
Comment: I see that I can use all the filters :-D


Download certain part of HTML code

Question: I am trying to make a push notification about Internet page update, but downloading the full page (700k) again every minute is quite troublesome for users. Is there is a way to download only a specific part of page?
As far as I have read there isn't any way to get delta information about the page. Is there a method which allows that? I haven't found one for a day (if there is, how can I locate the certain byte where my information is placed in the first place?
Comment: Is this your page? Why is it 700KB?
Comment: "Why worry about server-side databases? Just send **all of the data** with each HTTP request and let the JavaScript sort it out client-side!"
Comment: We need more info.  Downloading a specific part of HTML can be achieved with Asynchronous Javascript And XML, i.e. AJAX.
Comment: Not mine. Heavy table with data.
Comment: Well i am unfamiliar with java scripts only Objective-c(
Answer: What you want to do is learn some basics in AJAX calls.
You set an auto timer to reload div contents on whatever needs to be updated.
Comment: Well, it's time to learn about it though surfing for an hour didn't do any good last time. Maybe you could call me method ?
Answer: You could use a Range header like this:
<code>Range: bytes=0-1000
</code>
This will obviously get you the first 1000 bytes.
Comment: @DanKanze Well, I agree to a certain point, but I think is usable in some cases. If he needs like 100 bytes from 700KB page, isn't it better for users and server to just fetch those 100 bytes?
Comment: It's not just first 100 bytes, you can declare from byte position as well as end byte position, that's why it'c called range.
If the content is dynamic he most likely can't use this method, but I'm guessing it's not dynamic otherwise he wouldn't ask for such a solution.
Comment: Headers don't have anything to do with byte position of content. Plus he never mentioned any browser, for all I know he is building Windows/Linux/Mac application.
Comment: This is really crude and not a standard practise.
Comment: No because you are just getting the first 100 bytes. What if he needed the 100 bytes in the middle? What if the content is dynamic?
Comment: lol there are so many other factors. like what if browsers set different headers. or what if doctype is forced in different browsers? cache issues cross browser? all fo these factors can affect byte postion for start AND end. this just wont work. ever. period.
Comment: Headers do have ALOT to do with byte position content. find me ONE source that says they do not.

Download certain part of HTML code


R sprintf or paste getting c(value) results

Question: I have two databases that are on different servers.  So I'm querying one database putting that result into a list. Then trying to sprintf or paste that list into another sql query.  When I use sprintf or paste I get the c() around the list values.
    testing <- sprintf("all codes in %s",code_list)
    cat(testing,"\n")
    Results: all codes in c("1", "4", "5", "6", "7", "8", "9", "F", "N", "R", "S", "Y", "Z", "0", "E", "H", "A")

dput(code_list)
structure(list(CODE_CLASS = c("1", "4", "5", "6", "7", "8", "9","F", "N","R", "S", "Y", "Z", "0", "E", "H", "A")), .Names = "CODE_CLASS", row.names = c(NA,17L), class = "data.frame")

The results I'm hoping for is: all codes in ("1", "4", "5", "6", "7", "8", "9", "F", "N", "R", "S", "Y", "Z", "0", "E", "H", "A")
basically get rid of the c.
Comment: It appears that the issue is `code_list` but you show us neither the contents nor the code that generated it. could you please run `dput(code_list)` and paste the results into your question?
Comment: I just added the dput code to the question
Answer: We could use glue to do this
library(glue)
glue("all code in ({toString(unlist(code_list))})")
#all code in (1, 4, 5, 6, 7, 8, 9, F, N, R, S, Y, Z, O, E, H, A)

Update
If we need it in quotes
glue("all code in ({toString(shQuote(unlist(code_list)))})")
#all code in ('1', '4', '5', '6', '7', '8', '9', 'F', 'N', 'R', 'S', 'Y', 'Z', 'O', 'E', 'H', 'A')

Or in double quotes
glue("all code in ({toString(dQuote(unlist(code_list)))})")

data
code_list <- list(c(1, 4, 5, 6, 7, 8, 9), c("F", "N", "R", "S", "Y", "Z",
    "O", "E", "H", "A"))

Comment: Need them in Quotes.
Comment: @Tony In that case, just wrap with `as.character(glue(..`
Comment: That put the whole string in quotes, need each character in quotes, see my question post about what I expect for a results.
     as.character(glue("all code in ({toString(unlist(code_list))})"))
     [1] "all code in (1, 4, 5, 6, 7, 8, 9, F, N, R, S, Y, Z, 0, E, H, A)"
Answer: testing <- sprintf("all codes in %s",paste0("(",toString(unlist(code_list)),")"))
> cat(testing,"\n")
all codes in (1, 4, 5, 6, 7, 8, 9, F, N, R, S, Y, Z, 0, E, H, A)

But you can go ahead and directly do:
cat("all codes in",paste0("(",toString(unlist(code_list)),")"),"\n")
all codes in (1, 4, 5, 6, 7, 8, 9, F, N, R, S, Y, Z, 0, E, H, A)

Comment: Need them in Quotes.


Regular Expression: if, else if to use in Java

Question: I am trying to write a regular expression in which I want to compare the URL's.
Any URL Matches
http://*.xyz.com
Except or Excluding
http://m.xyz.com and http://m.product.xyz.com
So far I was trying to do it by using if else in RegExp but I couldn't be able to do it right...
(^http:\/\/)(((1)<!(m|m\.product))\.xyz\.co\.jp)?

Comment: Show us what you tried.
Answer: You can try that:
^http:\/\/(?!m\.xyz\.com|m\.product\.xyz\.com).*\.xyz\.com$

Regex101 Demo
Comment: @ShanArshad Could you accept the answer if it solved your issue?
Comment: It worked perfectly. Now i know what was the mistakes i was doing. Thanks very much
Answer: https?:\/\/(?!m\.|m\.product\.).*\.xyz\..*
This regex accepts all *.xyz.* domains except m.xyz.* and m.product.xyz.*. Also takes care of http or https.
Demo


Increase in Spam Effectiveness

Question: Over the last few days, I've seen a drastic increase in the amount of blatant spam making it inside of my organization.  (Exchange 2003 behind Ironmail, Symantec Mail Security.)  My security products are up-to-date and appear to be functioning correctly (aside from, of course, the additional V1agr4 messages).  I have looked at the headers and don't see anything out of the ordinary.  Exchange is passing mail
Is anybody experiencing this as well?  If so, can you provide any insight into how the messages are getting through?  Any recommendations on how to prevent?
Answer: I have seen a spike in rejection and deferals.  There has been an increase in emails with domain literals like [192.0.2.14].
Main blocks which work for me:

spamhaus.org blacklist (big spike in rejections the last couple of days).
Reject all mail which uses a hostname in HELO command.
Reject all mail which uses my address is HELO command.
Reject all mail which uses a raw ip address (192.0.2.15) in HELO command.
Defer all mail when SPF exists and does not allow the address.  I check the logs and enable valid address.  Based on history, I may change this to reject if IP address doesn't have a valid DNS configuration for an email server.
Answer: We've seen a small increase lately but are unaffected. We use MessageLabs but I've installed Mailcleaner at our end, which is catching all the stuff that's getting past MessageLabs. I've heard that MessageLabs used to be a decent spam filtering service but of course that was before Symantec got their hands on it and did what they do best - run it into the ground.
Answer: We're seeing it as well. We're currently using Postini and the only real options as far as I can see are to ride out the current wave or make your spam filters more aggressive. Of course if you do make your filters more aggressive then you'll have users complaining that they're not getting legitimate emails... go figure.
Comment: That was my initial conclusion as well.  I've opened a case with the vendor, following my "we pay support; make it their problem" strategy.
Answer: We use a mail-filter set up like this in front of our Exchange 2003 system, and have NOT seen a recent increase in spam.
Comment: No, but perhaps if you get more responses about what IS and IS NOT experiencing an increase, you may be able to isolate the problem better.
Comment: Good to know, but I don't think that this will be the time for a change in architecture.  I'll keep it in mind, however.

Increase in Spam Effectiveness


Every real number can be represented as a sum of plus-minus of the terms of infinite geometric sequence $2^{-n}$.

Question:
Every $C\in \mathbb R$ can be represented as
$
C = \sum_{n=k}^\infty \pm 2^{-n}
$
for some $k\in \mathbb Z$.

Trivially, every real number can be represented as $\sum_{n=1}^\infty \pm 2^{-a_n}$ for some strictly increasing sequence $\{a_n\}$. However, there might be missing terms in the geometric sequence, i.e. $a_{n+1}$ might be greater than $a_n$ for some $n$.
Is there a shorted / easier to follow proof than I provide among answers?
This question was inspired by the post: Conjecture about the representation of a constant $C=0.6516...$
Comment: An extension of this question: https://math.stackexchange.com/questions/4612272/for-which-infinite-geometric-sequences-every-real-number-can-be-represented-as-t
Answer: Strategy: Notice that
$$
  2^{-2} = 2^{-1} - 2^{-2},
$$
using this fact you can always "fill the gaps" in the sequence $\{a_n\}$. It allows me to prove a much stronger result in fact.
Proof.
If $C = 0$, then $C = 2^0 - \sum_{n=1}^\infty 2^{-n}$. It is enough to show that $C>0$ can be represented in the desired way, as in order to represent $-C$ it is enough to switch the signs.
In the rest of the proof we consider $C>0$. Since every positive real number can be represented in basis 2, there exist a (possibly finite) strictly increasing sequence $\{b_n\}$ such that $C = \sum_{n=1}^\infty 2^{-b_n}$. If the sequence was finite and $b_M$ was the last term, we could replace $2^{-a_M}$ by
$$
  \sum_{m=1}^\infty 2^{-(a_M+m)} = 2^{-a_M}.
$$
We conclude that there is at least one way to represent $C$ as $\sum_{n=1}^\infty \pm 2^{-c_n}$, where $\{c_n\}$ is a strictly increasing sequence (with terms possibly apart by more than $10$). Let $\mathcal{S}$ be the set of all such sequences $\{c_n\}$. If $\mathcal{S}$ contains an arithmetic sequence of the form $c_1,c_1+1,\ldots$, we are done. Suppose that not. For a sequence $\{c_n\} \in \mathcal{S}$ define
$$
  f(\{c_n\}) = \min\big\{n\in \mathbb N:c_{n+1}-c_n>1\big\}.
$$
and let
$$
  N = \max\big\{ f(\{c_n\}) : \{c_n\} \in \mathcal{S}\big\}.
$$
Define the subset of $\mathcal{S}$ containing the sequence of "earliest occurance of a gap",
$$
  \mathcal{T} = \big\{ \{c_n\} \in \mathcal{F} : f(\{c_n\}) = N \big\}.
$$
Finally, pick any sequence $\{c_n\}$ from $\mathcal{T}$ for which $c_{N+1}-c_N$ is minimal. By the definition of $N$ and $\mathcal{T}$, $c_{N+1}-c_N > 1$. By replacing $\pm 2^{-c_{N+1}}$ with
$$
\pm 2^{-(c_{N+1}-1)} \mp 2^{-c_{N+1}},
$$
we obtain new sequence $\{c'_n\}$ that can be written as $c_1,\ldots,c_n,c_{N+1}-1,c_{N+1},\ldots$ and it belong to $\mathcal S$. If $c_{N+1}-c_{N}=2$, then the beginning of the new sequence contains more than $N$ consecutive integers ($f(\{c'_n)>N$), which is a contradiction with the maximality of $N$. Last, if $c_{N+1}-c_{N}>2$, then the new sequence $\{c'_n\}$ belongs to $\mathcal T$ and $c'_{N+1}-c'_{N} <c_{N+1}-c_{N}$, which is a contradiction with the way $\{c_n\}$ was chosen out of all the sequences in $\mathcal T$. That concludes the proof.
Answer: Somewhat shorter proof:
Using the same argument as in the other proof, we can assume $C>0$. Let $\sum_{n=k}^\infty b_n 2^{-n}$, where $k\in \mathbb Z$ and $\{b_n\}\in \{0,1\}^\infty$, be the binary representation of $C$. Then
$$
  C = \sum_{n=k}^\infty b_n 2^{-n} = \sum_{n=k}^\infty 2b_n 2^{-(n+1)} = 2^{-k} + \sum_{n=k}^\infty (2b_n-1) 2^{-(n+1)},
$$
where $2b_n-1 = \pm 1$ for all $n=k,k+1,\ldots$. This is the desired representation.


Memorizing diatonic chord progressions in a tune

Question: Let's say that the tune is mostly in Aeolian mode. I found that I keep forgetting the changes because when I think V it is not a chord I used to associate with this number and I find myself 'translating' it to Ionian-based numbering (so I mind-map it as III chord; Phrygian collection).
In literature you can find explicit numberings for each possible mode, so that I may mean Aeolian, Phrygian collection etc. depending on mode. I'm an amateur and I have never seen an explanation why they are using so much space to show stuff that can be easily derived or what should I do with it (except memorizing). I always assumed it there is to help in sight reading.
Having run into this problem, should I unlearn to auto-associate say, V with Mixolydian collection or Dominant function? Is it customary to think of II-V-I changes as anything else if they are diatonic to given mode and not harmonic cadences with obvious dominant function of V?
How can I memorize tunes if I don't see obvious patterns, cadences, not many key changes etc.?
Comment: @Dom Most musicians? It's acceptable for classical musicians to have notation on stage but it's frowned upon or laughed at in all other genres.
Comment: Do you have to memorize the progression? Most musicians use some kind of notation (sheet music, lead sheets, tabs, ect) to aid in playing so it is not necessary to memorize the whole piece.
Comment: @Fergus Every choir has notation when they preform, any type of ensemble uses notation when they preform, any brass or string group uses notation when they preform, any pianist uses notation when they preform, jazz groups use notation when they preform, musicians hired as extras by band use notation when they preform. The only two groups that don't use notation when they preform are musicians acting (not the musicians in the pit they use notation) in musicals and musicians who "write there own songs".
Comment: @Dom The OP mentions the II V I, which is mostly used in jazz although it is a staple of all popular, contemporary music. A competent Jazz player (including Pianists) will have at least 100 standards committed to memory. A professional jazz player will know many more. It is a integral part of both formal and informal jazz education.  I'm sure some jazz musicians have fake books on stage but it is an exception to the rule and is definitely frowned upon.
Comment: @Fergus It's not though. Many Jazz players especially horn players have sheet music or have lead sheets for preforming. When they play 100 different songs maybe they can remember them all, but what about 1000? Any performer can't be expected to know every note at any second for that many songs especially when almost every working musician has to constantly learn new songs. It's nothing to be ashamed of it's there for a reason.
Comment: In Jazz, no one can know every note of every second. Jazz is primarily improvisational, you learn the melody and the progression, the rest is up for interpretation. But clearly I can't convince you, maybe try the allaboutjazz.com forum to see the consensus is that most don't read on stage.
Comment: @Dom - Fergus is right.
Answer: Your problem is a little unusual, I'll just give general tips on memorizing progressions.
First of all, all progressions will have obvious and familiar patterns, If you're listening to something really obscure you may have to look a little harder but they will be there. The more music you learn and listen to the more obvious they become.

Many chord progressions are not diatonic so don't rely your method to memories prog's.
Look (on your instrument, or the notation) at the movement of the chord tones. listen to the movement of the chord tones.
Sing the top note while playing through it, repeat for the the second highest notes and on to the lowest. repeat this with the chord tones (they will have different movements unless all chords are identical voicings) sing the third of every chord, then sing the 5th etc
Play the progression in other keys and with other voicings, how does this affect it's sound? Does it lose it's essence? Has the the chord tone movements lost their distinctive characteristics or is it still clearly recognizable? Why?
Take note of stylistic idioms of each genre you play e.g. bVII, bVI and bIII  in major keys are common in rock and pop. Remember how they sound, experiment to see how they sound in different progressions. Listen out for them when listening to the radio etc
Loop the prog. and improvise over it, having to follow and anticipate the changes and hit chord tones will cement the prog. in your mind.
Learn the melody, how does it fit with the harmony? what chord tones are played? Which chord extensions could be added without detracting from the melody? reharmonize the song.
Write it down in roman numeral form and analyse it, what other songs use it? what movements are familiar which are more unusual? Why are they unusual?
You are most likely to memorize a prog. if you learn it by ear. The focus and time required will almost guarantee you remember it.
Read others analysis of songs.
If you have any interest in popular music this is an amazing resource:
http://www.icce.rug.nl/~soundscapes/DATABASES/AWP/awp-notes_on.shtml


Method response with timeout

Question: how to get response from method into variable(or console in my example) if method has some delay?
testMethod = (number) => {

    setTimeout(function() {
         return number+number;
    }.bind(this), 100);
}

testMethod2 = (number) => {

         return number+number;
}

calling functions
console.log(this.requests.current.testMethod(44))
console.log(this.requests.current.testMethod2(44))

testMethod returns undefined
testMethod returns 88
how to get output from testMethod?
Comment: You do have to wait for it. If using ajax there is success function use that
Comment: You can use a promise or a callback. E.g. `testMethod = (number) => new Promise(resolve => setTimeout(() => resolve(number + number), 100)); this.requests.current.testMethod(44).then(console.log);`
Answer: You are not returning anything from your testMethod. What you return inside of the function given to setTimeout will not be returned from testMethod, since setTimeout is asynchronous.
You can use a promise or a callback for asynchronous logic.
Promise

const testMethod = (number) => {
  return new Promise(resolve => {
    resolve(number + number);
  }, 100);
}

testMethod(44).then(console.log);

Callback

testMethod = (number, callback) => {
  setTimeout(() => {
    callback(number + number);
  }, 100);
}

testMethod(44, console.log)
Comment: How to get promise value into variable? if i try var xx = this.requests.current.testMethod().then(xx);  i get promise object
Comment: @Bobek You can't get value from asynchronous logic like that in JavaScript. You need to do your logic in the function given to `then` instead, e.g. `this.requests.current.getSessionID().then(result => { var xx = result; });`
Answer: The problem, is that you function testMethod returns nothing, i.e. undefined
You can use, as suggested by Tholle use promise:
testMethod = (number) => {
    return new Promise((resolve) => {
          setTimeout(function() {
             resolve(number + number);
          }, 100);
    });
}

testMethod2 = (number) => {
         return number+number;
}

this.requests.current.testMethod(44).then((res) => {
  console.log(res);
})
console.log(this.requests.current.testMethod2(44))

Method response with timeout


Passing NSString from a ViewController to a NSObject

Question: Hi Im trying to pass a NSString thats in a ViewController over to a NSString in an NSObject.
Here is the code that I am using in my NSObject to call the string and pass it to my new string.
    RegisterDeviceViewController *S = [[RegisterDeviceViewController alloc] init];
tempRegCode = S.checkString;
NSLog(@"tempRegCode=%@",tempRegCode);

the problem being once the button it pressed on the view that starts the method in my NSObject it works sweet however nothing gets passed to tempRegCode.. here is my Log.

[Session started at 2011-05-03 09:27:35 +1200.]
  2011-05-03 09:27:36.264 instaCode1.3[1456:207] yum yum feed me more cookie!! func=ERROR
  Code=1
  Text=Please Register Device
  2011-05-03 09:27:36.266 instaCode1.3[1456:207] cookieCode = code1
  2011-05-03 09:27:37.983 instaCode1.3[1456:207] alerts.m OK button pressed
  2011-05-03 09:27:49.539 instaCode1.3[1456:207] Users Registration is '22222-22222-22222-22222'
  2011-05-03 09:27:49.540 instaCode1.3[1456:207] tempRegCode=(null)

As you can see at the end there 'tempRegCode=(null)??
EDIT::
This is how I passed the variable to checkString
- (IBAction)submitRegistration:(id)sender{
//NSLog(@"submit Registration button has been pressed");

//add text format here
checkString = regTextField.text;
NSLog(@"Users Registration is '%@'",checkString);

regConnection *Reg= [[regConnection alloc] init];
[Reg startRegConnect];

}
Comment: Perhaps you can show an example of the attempt you made to pass the value ? passing it as a method parameter or setting a Property or variable ?
Answer: Do you set the property checkString to anything in the -init method of your view controller? If you don't, it will default to NULL.
Something like this (in your RegisterDeviceViewController.m file):
- (id)init {
    self.tempRegCode = @"My String";
}

If you are trying to get a string that is in an already-instanciated copy of RegisterDeviceViewController, you need a reference to that copy, not to a newly allocated one. For example, if you have an instance of RegisterDeviceViewController in your XIB file, use an IBOutlet to this instance in your NSObject subclass then call -tempRegCode on that instance.
Comment: yea I'm setting it off a UITexField like this

checkString = regTextField.text;
Comment: Why does the view controller have any text within regTextField upon init?
Comment: thats not my code adam, that was a suggestion from Kyle, My code is above.. sorry I didn't show how I was passing the text from the textfield over to the NSString because I had tested it and it was showing the code that was passed to it.. Thus I thought the error was over in the NSObject... but I have updated my post and added all the code involved with the weird problem.


FileContentResult from c# save as pdf from ajax call in javascript

Question: I am returning a pdf byte array from a c# controller as follows:
return new FileContentResult(pdfBytes, "application/pdf") { FileDownloadName = "test.pdf" };.
My client side code is as below. I am not able to successfully download the pdf from the response. I can see that it's returning the pdf in the response (by logging) but I am missing something here
<code>   $.ajax({
        type: "POST",
        url: config.ExportUrl,
        contentType: "application/json",
        data: JSON.stringify(params),
        success: (response, status, error) => {

            this.isExporting = false;
            var defaultFileName = "test.pdf";

            var blob = new Blob([response]);
            var blobUrl = window.URL.createObjectURL(blob);
            var anchor = document.createElement('a');
            anchor.download = defaultFileName;
            anchor.href = blobUrl;
            document.body.appendChild(anchor);
            anchor.click();
            document.body.removeChild(anchor);
            return response.content;
        },
</code>
Any help would be greatly appreciated.
thanks
Angelo
Comment: Since you get the PDF file through an AJAX call, have you tried to use the `config.ExportUrl` as the url for the anchor instead?
Comment: I still need to POST the params, not sure how I can do that
Comment: I missed, that it is a POST request. What I wrote won't be possible then.
Answer: Found a similar post like below and it worked:
<code>    var req = new XMLHttpRequest();
    req.responseType = "blob";
    req.open("POST", config.ExportUrl, true);
    req.setRequestHeader('Content-Type', 'application/json');
    req.onreadystatechange = function () {
        if (req.readyState === 4 && req.status === 200) {
            if (typeof window.chrome !== 'undefined') {
                // Chrome version
                var link = document.createElement('a');
                link.href = window.URL.createObjectURL(req.response);
                link.download = defaultFileName;
                link.click();
            } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
                // IE version
                var blob = new Blob([req.response], { type: 'application/pdf' });
                window.navigator.msSaveBlob(blob, defaultFileName);
            } else {
                // Firefox version
                var file = new File([req.response], defaultFileName, { type: 'application/force-download' });
                window.open(URL.createObjectURL(file));
            }
            //callback();
        }
    };
    req.send(JSON.stringify(params));
</code>
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Getting unexpected error (type=Method Not Allowed, status=405) error while access /refresh actuator is not working

Question: I created one @RestController class and trying to use /refresh actuator values from config server.
/refresh actuatoris not working. I am getting below error. Spring boot version is 2.0.0-Release. I can not upgrade spring boot version.
http://localhost:8888/secondservice/admin/refresh
    Whitelabel Error Page
    This application has no explicit mapping for /error, so you are seeing this as a fallback.

    Thu Jan 23 10:16:10 EST 2020
    ***There was an unexpected error (type=Method Not Allowed, status=405).
    Request method 'GET' not supported***

Dependency:-
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-config</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

Foo.Class
    @RefreshScope
    @RestController
    public class Foo {

        @Value("${welcome.message}")
        private String personName;

        @RequestMapping(value ="/", produces = "application/json", method = RequestMethod.POST)
        public String greet(){
            return "hello " + "POST "+ personName;
        }

    }

bootstrap.yml
    server:
      port: 8888
    spring:
      application:
        name: secondservice
      cloud:
        config:
          uri: http://localhost:8890/configserverdemo
          fail-fast: false
          enabled: true
          server:
            bootstrap: true
    management:
      context-path: /admin
      security:
        enabled: false
      endpoints:
        web:
          exposure:
            include: "*"
      endpoint:
        refresh:
          enabled: true

Answer:
There was an unexpected error (type=Method Not Allowed, status=405).
      Request method 'GET' not supported

The above error means that HTTP GET is not supported on that particular endpoint.
To refresh the config from spring config server you need to make an HTTP POST request on http://localhost:8888/secondservice/admin/refresh
Below is from the Spring guide

You can invoke the refresh Actuator endpoint by sending an empty HTTP POST to the client's refresh endpoint

To make the HTTP POST request, you can use any HTTP client, eg Postman or cURL. To use cURL, you can run the below command on a terminal
curl -X POST http://localhost:8888/secondservice/admin/refresh

Comment: I am already using "RequestMethod.POST" on @RequestMapping. how will i make HTTP Post request?
Comment: @user84 The `RequestMethod.POST` that you added is on the `greet()` method is for that particular endpoint and not for refreshing the config. The refresh endpoint is added by Spring, and the POST request can be made using any http client. You can even do it using curl on the terminal like `curl -X POST http://localhost:8888/secondservice/admin/refresh`


Construct a circle cutting two other circles at right angles

Question: I have the following problem:
On a line $l$ on this line are the centers of two circles $C_1$ and $C_2$ . Circles $C_1$ and $C_2$ do not intersect and are not tangent to eachother. (but one could be completely inside the other)
How to construct the circle $C_3$ also with its center on line $l$ that cuts both  $C_1$ and $C_2$ at right angles?
This construction is (a bit) described at https://en.wikipedia.org/wiki/Ultraparallel_theorem there the explanation is a bit to complex (because it wants to use specified hyperbolic motions) and is i think not complete.
I would like to learn a simplified straight edge and compass construction.
Answer: there are lots of circles that are orthogonal to both $C_1, C_2.$ they all have centers on the radical axis of $C_1, C_2.$  radical axis is line orthogonal to the center line $l$ and has tangents of equal length to $C_1, C_2$
we can construct the radical axis by drawing a circl $C$ on one side of the line(say) of $l$ cutting both circles $C_1, C_2.$  now, find the points where $C, C_1$ cut and draw the line. similarly, draw the line at which $C, C_2$ cut. these two lines intersect on the radical axis.
pick any point $P$ on the radical axis of $C_1, C_2$ and draw the two equal tangents to $C_1, C_2.$ find the contact points $T_1, T_2.$ draw a circle with center $P$ and radius equal $PT_1.$ this circle will be orthogonal to both.
do the same on the other side of $l.$ now you have two points on the radical axis. draw any circle with center on this radical axis, and it must cut $C_1, C_2$ orthogonally.


If the Gibbs Sampler assumes knowledge of full conditionals -- why can't we just solve for the full joint density and avoid Gibbs?

Question: Suppose that $y_1, y_2$ are data drawn from a density function $f$ with parameters $\theta_1, \theta_2$ which are unknown. Suppose I applied some prior on $\theta_1, \theta_2$. Then, the Gibbs sampler states that if we know the FULL conditional distributions:
$$
p(\theta_1|\theta_2, y) \ \ \ \text{and} \ \ \ p(\theta_2|\theta_1, y)
$$
then we may draw from each and be able to approximate draws from the joint distribution $p(\theta_1, \theta_2)$, which is assumed to be hard to find (which is why we do Gibbs here to begin with).
We may rewrite the above as:
$$
p(\theta_1|\theta_2, y) = \frac{p(\theta_1,\theta_2, y)}{p(\theta_2, y)} \ \ \ \text{and} \ \ \ p(\theta_2|\theta_1, y) = \frac{p(\theta_2,\theta_1, y)}{p(\theta_1, y)}
$$
Now, I assume that we know $p(\theta_1, y)$ and $p(\theta_2, y)$ from the prior specification. Then, if we know $p(\theta_1, y)$ and $p(\theta_1|\theta_2, y)$, don't we also know $p(\theta_1,\theta_2, y)$?
What exactly is the Gibb's sampler doing here?
Answer: Mathematically, this is correct: once you know
$$p(\theta_1|\theta_2, y) \ \ \ \text{and} \ \ \ p(\theta_2|\theta_1, y)$$
you can derive the joint posterior distribution as
$$p(\theta_1,\theta_2|y) = \dfrac{p(\theta_1|\theta_2,y)}{\int p(\theta_1|\theta_2,y)\big/p(\theta_2|\theta_1, y)\,\text{d}\theta_1}$$
[This is Theorem 9.3 in our book.]
However the reason for running Gibbs sampling is that/when this expression is not available in closed form and hence cannot be simulated directly. In the event one knows $p(\theta_1,y)$ or $p(\theta_2,y)$ in closed form and can simulate $\theta_1$ or $\theta_2$ from the former or the latter, resp., then one does not require Gibbs sampling as direct simulation becomes feasible.
Comment: Gibbs sampling does not aim at recovering the joint density, only at simulating from this density.
Comment: So you're basically saying that even if I can compute $p(\theta_1,\theta_2, y)$ from the full conditionals, to get to $p(\theta_1,\theta_2|y)$, I still need the $p(y)$ on the denominator, which is the normalizing constant and hence  whose closed form is the deciding factor in whether to use Gibbs or not?
Comment: I see, so $\int p(\theta_1|\theta_2,y)\big/p(\theta_2|\theta_1, y)\,\text{d}\theta_1 = \frac{1}{p(\theta_2,y)}\int p(\theta_1, y)d\theta_1 = \frac{p(y)}{p(\theta_2,y)}$. For the closed form and simulation requirement, is to facilitate the calculation of the integral part $\int p(\theta_1, y)d\theta_1$ or the fraction part $\frac{1}{p(\theta_2,y)}$? Thank you!
Comment: When you say **"However the reason for running Gibbs sampling is that/when this expression is not available in closed form and hence cannot be simulated directly."**, when is it NOT available in closed form? Is it when you cannot evaluate the integral in the denominator above?
Comment: @user321627: when the integral is not available in closed form or when it involves an expression complicated enough to prevent simulating from this distribution, conditionals need be used instead.


Creating a block programmatically in a theme on Drupal 8?

Question: So I was hoping to have my theme create special blocks for different parts of the front page so that they can be moved around easily later. I added the files to mytheme/src/Plugin/Block/BlockName.php but they never show up anywhere on the site or the block manager even after clearing cache.
Here's the code for one of my blocks (MediaPanel.php):
<code><?php
/**
 * @file
 * Contains \Drupal\mytheme\Plugin\Block\MediaPanel.
 */

namespace Drupal\mytheme\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides my custom block.
 *
 * @Block(
 *   id = "media_panel",
 *   admin_label = @Translation("Media Panel"),
 *   category = @Translation("Blocks")
 * )
 */
class MediaPanel extends BlockBase {

/**
   * {@inheritdoc}
   */
  public function build() {
    return array('#markup' => 'hello world');
  }
}

?>
</code>
Do I have to use a module for creating Blocks? It would be inconvenient to have to make a module to create blocks that will be specific to my theme anyway.
Comment: If it's just markup/content, you could potentially save custom block content on install.
Answer: Yes. Themes can't provide plugins.
Comment: Really? I know the Drupal 8 Bootstrap theme comes with an src/Plugin directory full of PHP class files. I was hoping it would be possible since I don't want to unpack the blocks' markup from the theme by having it go in the modules folder.
Comment: bootstrap does its own weird thing, it has special plugin types with special discovery that it implements itself. Those things actually *only* work with themes. Normal plugins do not.
Comment: Is there any work around to create a block problematically only for my theme?


input to command prompt from perl script

Question: How to supply input to command prompt from perl script. For example selecting an option from command prompt supplying username or password to command prompt etc..I think i am clear enough.
Comment: Just to be totally clear, do you want to prompt the user via the perl script or answer an external prompt given to you via a perl script?
Answer: #!/usr/bin/perl -w

use strict;

my $input = <STDIN>;

chomp($input);

print "You wrote: $input\n";

Comment: hi thanks for your reply. I am not saying getting input which is given to the command prompt rather giving input to command prompt from my script. For example supplying username or password from script whenever required without manually entering in the command line.
Comment: You can write to STDOUT but I'd ask what you're trying to do, because there's probably a CPAN module that will handle the authentication for you. The most abstract is [Expect](http://search.cpan.org/~rgiersig/Expect-1.15/Expect.pod) but there's probably something more specific. To print to STDOUT simply do: `print STDOUT $output;`
Answer: And if you're looking for options rather than the user typing in something, consider GetOpt::Long.
Answer: See Term::Prompt, Term::UI, IO::Prompt, IO::Prompter, IO::Prompt::Tiny modules, and all that.


How to delete MIDI channel in Logic Pro X?

Question: I'm studying the manual atm and the feature that I tried recently is splitting MIDI regions by pitch. It works fine, but when I removed all tracks that has been created as a result I'm stuck with 16 non-used channels in the Mixer and I have no idea how to delete them. I tried using delete/backspace, I have checked the menus, I even checked the manual when it comes to MIDI channels :(
Can anybody help me?
Comment: Have you tried using the apple command key & delete.
Comment: Yeah, I tried it bro, cmd+delete deletes a currently selected track, not a channel
Comment: Add a screenshot please? Are there no - buttons next to the original channel source? Like when adding seperate stereo channels from a main channel source in the mixer.
Answer: An old post but I just ran into this problem. Open midi environment window from the 'Window' menu (command+0), select the 'MIDI Instr.' layer in the drop down at the top left of the window.
Here you can find and delete all the midi channels you don't want.
Answer: I haven't used Logic, but most DAWs are similar. I use Live 9. Try highlighting/selecting the channels in the mixer view, and right click - deleting them.
Answer: It sounds like you are running up against a bug, because when you delete a track in the track view, the corresponding mixer channel in the mixer view should disappear also.
If you don't have any content in this document, I suggest you just create a new document. (One of the big advantages of Logic is the templates, so choose the right template for what you are doing carefully and you may not even have to manage any tracks.)
If you do have content in the document, one thing you can try is to Save the document, then Close it, and in Finder, first duplicate your document to make a backup, and then context-click (2-finger tap or right-click) the original document and choose "Show Package Contents" from the pop-up menu and the document will open as a folder. Inside, there are files and folders. Go into the "Alternatives" folder, then into the "000" folder, and find a file called "DisplayState.plist" and put that file in the Trash. Then close the windows you just created.
The "DisplayState.plist" file contains a bunch of options for how your document should be displayed by Logic, and it is the source — unfortunately — of some Logic Pro X bugs. By putting it in the Trash, you reset the non-content parts of your document to being a new document.
Then open your document in Logic and with any luck the phantom channels will be gone from the mixer.
Answer: An old post but I just ran into this problem. Open midi environment window from the 'Window' menu (command+0), select the 'MIDI Instr.' layer in the drop down at the top left of the window.
Here you can find and delete all the midi channels you don't want.
This is what helped me. It worked after 2 days of trying. Thanks.


Is there a typo on page 27 of 'Mastering the Scales and Arpeggios'?

Question: Cooke's 'Mastering the Scales and Arpeggios', from 1931, came recommended to me as the one-stop reference for learning to play scales. On page 27, I find A-flat. The text says, 'Right hand: Fourth finger on B flat'.
However, the fingering given on the staff at the bottom of the page starts out 2-3-1 instead of 3-4-1, thus alternating between 3 and 4 on b-flat. This is like nothing else in the book, and there's no mention of it in the prose. So I think it's a typo, but I wonder if there's some good reason that's escaping me.
Answer: A lot of guides will always have you start on 1 or 2.  Your index finger is normally the strongest, so it makes some sense to start on 2 here.  That said I much prefer consistency myself, and would start on 3 in order for the fingering to be the same as you play up to the octave.
See also: What is the proper way to play A-Flat scales on piano?


Receber valor do RadioButton no RecyclerView

Question: boa noite.
Gostaria do auxilio de vocês em um problema que estou tendo, estou desenvolvendo um app pra um trabalho da faculdade, no caso eu vou ter uma activity que vai ter uma especie de pesquisa, ou quiz, como queiram chamar.
A pergunta, e as respostas estão armazenadas no firebase, eu listo tudo em um tela, onde o usuário poderá selecionar as opções para cada pergunta. Ai está minha dúvida, o que eu quero e o seguinte, o usuário devera selecionar todas as respostas, e no final clicar no botão, que irá redirecionar para uma outra activity que ira mostrar o resultado.
Esse é o problema, eu estou usando um recyclerview pra fazer a listagem das perguntas e respostas, todas em uma unica activity, como que eu faço para armazenar as respostas do usuario, para depois enviar o resultado para outra activity?
xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/fundo_degrade"
    android:fitsSystemWindows="true"
    tools:context="br.com.cifrasemusica.cifrasmusica_teoriamusical.activity.ExercicioActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar">

        <include
            android:id="@+id/Toolbar_Exercicio"
            layout="@layout/toolbar">
        </include>

    </android.support.design.widget.AppBarLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior = "@string/appbar_scrolling_view_behavior">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/RecyclerView_Exercicio"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        </android.support.v7.widget.RecyclerView>

    </ScrollView>

    <Button
        android:id="@+id/Button_enviarExercicio"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/fundo_botao"
        android:text="Confirmar"
        android:layout_margin="5dp"
        android:layout_gravity="bottom" />

</android.support.design.widget.CoordinatorLayout>

activity
public class ExercicioActivity extends AppCompatActivity {

    // Variaveis globais
    private Toolbar toolbar;
    private String key;
    private String name;
    private String description;
    private ArrayList<Questao> mContent;

    // Firebase
    private FirebaseFirestore firestore;
    private Query query;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exercicio);

        // Recuperando os dados passados
        Bundle extra = getIntent().getExtras();
        if (extra != null) {
            this.key = extra.getString("key");
            this.name = extra.getString("name");
            this.description = extra.getString("description");

        }

        // Instanciando os objetos
        firestore = ConexaoFirebase.getFirestore();
        mContent = new ArrayList<>();

        // Configurando a toolbar
        toolbar = findViewById(R.id.Toolbar_Exercicio);
        toolbar.setTitle(this.name);
        toolbar.setTitleTextColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
        setSupportActionBar(toolbar);

        // Buscando conteudo no BD
        DocumentReference documentReference = firestore.collection("exercicios/").document(this.key);
        query = documentReference.collection("questoes/").orderBy("question");
        query.addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
                mContent.clear();
                //Verificando se existem erros
                if (e != null) {
                    Log.w("Error", "Erro ao ler as questões", e);
                    return;
                }

                // Lendo os dados e salvando no array
                for (DocumentSnapshot doc: documentSnapshots) {
                    if (doc != null) {
                        Questao questao = doc.toObject(Questao.class);
                        questao.setKey(doc.getId());
                        mContent.add(questao);
                    }
                }
                initRecyclerView();
            }
        });
    }

    private void initRecyclerView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        RecyclerView recyclerView = findViewById(R.id.RecyclerView_Exercicio);
        recyclerView.setLayoutManager(layoutManager);
        ExercicioAdapter adapter = new ExercicioAdapter(this, mContent);
        recyclerView.setAdapter(adapter);
    }
}

adapter
public class ExercicioAdapter extends RecyclerView.Adapter<ExercicioAdapter.ViewHolder>{

    private static final String TAG = "RecyclerViewAdapter";

    // Variaveis globais
    private ArrayList<Questao> mContent = new ArrayList<>();
    private Context mContext;

    public ExercicioAdapter(Context mContext, ArrayList<Questao> mContent) {
        this.mContent = mContent;
        this.mContext = mContext;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.lista_exercicios, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
        holder.question.setText(mContent.get(position).getQuestion());
        holder.op1.setText(mContent.get(position).getOp1());
        holder.op2.setText(mContent.get(position).getOp2());

    }

    @Override
    public int getItemCount() {
        return mContent.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView question;
        RadioButton op1;
        RadioButton op2;
        Button botao_exercicio;

        public ViewHolder(View itemView) {
            super(itemView);
            this.question = itemView.findViewById(R.id.TextView_titulo_exercicio);
            this.op1 = itemView.findViewById(R.id.RadioButton_op1_exercicio);
            this.op2 = itemView.findViewById(R.id.RadioButton_op2_exercicio);
            this.botao_exercicio = itemView.findViewById(R.id.Button_enviarExercicio);
        }
    }
}

Answer: Tive um problema semelhante, só que não encontrei nada a respeito. Então para resolver eu decidi fazer com que o usuário respondesse uma questão por vez, meio que ordenei as questões por números crescente no database, ai carregava a primeira questão, daí quando o usuário respondia ela jogava a resposta no db e adicionava +1 em uma "int" que criei para ser a  variável das questões e carregava a próxima questão (usando a mesma tela so fazendo outra consulta no db), ia fazendo isso até a variável das questões não existir no banco de dados.
É meio complicado entender, mas essa foi a base que usei, da pra começar a pensar a partir disso ai, boa sorte.


Show that the $\Delta$-complex obtained from $\Delta^3$ by performing edge identifications deformation retracts onto a Klein bottle.

Question: I am going through some exercises in Hatcher's Algebraic Topology.
You have a $\Delta$-complex obtained from $\Delta^3$ (a tetrahedron) and perform edge identifications $[v_0,v_1]\sim[v_1,v_3]$ and $[v_0,v_2]\sim[v_2,v_3]$. How can you show that this deformation retracts onto a Klein bottle?
Answer: Flatten the tetrahedron and draw it in the plane (triangle with a vertex inside and edges going out to the vertices of the triangle); i.e. smoosh the 3-cell.  If you smoosh and cut it up a little, you're looking at the standard "rectangle-with-sides-identified" picture of the Klein bottle.
Comment: I remember from doing this exercise that the rectangle-with-sides-identified isn't quite the standard one (by which I mean pairs of opposite sides identified, one with a twist). The edge orientations that are specified by the delta-complex structure mean that you end up with something that needs a little cutting and gluing to see that it is your friendly ordinary klein bottle.
Comment: Bit confused about how to go about the squishing of it. Whenever I try it doesn't get to the Klein bottle square.
Comment: @NKS yes you do have to cut it up, my bad
Comment: @yoyo May I ask what does the black shaded part represent? Also why is the vertex 0 in the center in the first diagram but not in the center for the larger second diagram? Thanks!
Answer: The 3-simplex obviously deformation retracts onto the union of the surfaces obtained by $[v_0,v_1,v_3]$ and $[v_0,v_2,v_3]$. Note that the continuous image of a deformation retract, where the map identifies the points in the retract only, is still a deformation retract.


Can't implement Parcelable because I can't make the CREATOR field static

Question: The Parcelable docs say that the CREATOR field must be static, but when I try to implement it this way I get the error "Inner classes cannot have static declarations".
I attempted to resolve this by putting my CategoryButton in a separate class (not declaring it as an inner class in MainActivity) but then I couldn't call getApplicationContext() in the constructor to pass to the super.
public class MainActivity extends ActionBarActivity {

    private class CategoryButton extends Button implements Parcelable{
        private ArrayList<CategoryButton> buttons = null;
        private RelativeLayout.LayoutParams params = null;
        public CategoryButton(Context context){
            super(context);
        };
        public void setButtons(ArrayList<CategoryButton> buttons){
            this.buttons = buttons;
        }
        public void setParams(RelativeLayout.LayoutParams params){
            this.params = params;
        }
        public ArrayList<CategoryButton> getButtons(){
            return this.buttons;
        }
        public RelativeLayout.LayoutParams getParams(){
            return this.params;
        }

        public int describeContents() {
            return 0;
        }
        public void writeToParcel(Parcel out, int flags) {
            out.writeList(buttons);
        }
        public static final Parcelable.Creator<CategoryButton> CREATOR // *** inner classes cannot have static declarations
                = new Parcelable.Creator<CategoryButton>() {
            public CategoryButton createFromParcel(Parcel in) {
                return new CategoryButton(in); // *** 'package.MainActivity.this' cannot be referenced from a static context
            }

            public CategoryButton[] newArray(int size) {
                return new CategoryButton[size];
            }
        };

        private CategoryButton(Parcel in) {
            super(getApplicationContext());
            in.readList(buttons, null);
        }

    }

// ...other activity code

Comment: I dont understand why you do extend button and implement Parcerable
Comment: Because for my app I need to have a button that has a property `buttons` that contains other buttons...
Comment: Why do you need to implement `Parcelable`?
Comment: Because I need to pass the `buttons` property to an `Intent` as an `extra` and it's an `ArrayList` so `CategoryButton` needs to implement `Parcelable` in order for me to call `putParcelableArrayListExtra(String name, ArrayList value)` on the `Intent`.before I pass it to `startActivity()`.
Answer: You need to set your CategoryButton as inner static, i.e.
private static class CategoryButton extends Button implements Parcelable {
    ...

Comment: I just tried this and although it fixes the `CREATOR` field problem, it makes it so I can't call `getApplicationContext()` to pass to the super in the constructor.
Comment: Button is a view, i.e. change your call to context as `super(getContext());`
Comment: Hmm now I get the error `Cannot reference 'View.getContext()' before supertype constructor has been called`
Comment: Well, it is a custom constructor, just replace it with `private CategoryButton(@NonNull Context context, Parcel in) {...`. But depends of your logic, you may need to change the way you are calling this private constructor.
Comment: I just tried changing the signature of the constructor as you describe and then calling it from `createFromParcel()` like this: `return new CategoryButton(getContext(), in);` but then I'm back to the error `Non-static method 'getContext()' cannot be referenced from a static context` :\
Comment: Please look [here](http://stackoverflow.com/questions/3542333/how-to-prevent-custom-views-from-losing-state-across-screen-orientation-changes/3542895#3542895) how to restore from `Parcelable`