Can we use linear regression to define the objective function in linear programming?

Question: This is a general question about how linear programming is used in the analytics community.
Is it common, or feasible to use linear regression (or perhaps even more complex models like regression trees) to act as the objective function in a linear program?
I'm interested in statistically deriving linear models of complex phenomena (i.e energy transfer through a surface) and finding optimal combinations of the variables using some optimization methods. Here's an example to clarify my question.
** UPDATED (SO THERE'S NO TRIVIAL SOLUTION) **
Let's say I fit a regression to some heat transfer data, and derive a regression line that can predict the mechanical heating of a room (Qh).
So my regression might look like this:
Qh = b0 + (b1 * km) + (b2 * kg) + (b3 * Am) + (b4 * Ag) + (b5 * dT) + (b6 * Qr)

Where:

Qh = Mechanical heating of the room (Wh)
Qr = Solar radiation flux transmitted through glass (W/m2)
km = Conductance of masonry (low) (W/m2/K)
kg = Conductance of glass (high) (W/m2/K)
Am = Area of masonry (m2)
Ag = Area of glass (m2)
dT = Temperature difference between outside and inside (K)
b0, b1, b2, b3, b4, b5, b6 = regression coefficients.

Solving the regression might give us something like this:
Qh = 1 + (2 * km) + (3 * kg) + (4 * Am) + (5 * Ag) + (6 * dT) + (7 * Qr)

(Note that I'm deliberately not going to use variables to represent the regression weights since they're not variables in this case, the regression has been solved so they are constants).
I would like to find the optimal combination of the wall/glass area that reduces mechanical heating of the room. So the variables for the linear program are (Am, Ag) and we assume everything else is a constant.
This problem is somewhat tricky since, reducing the (high conductance) glass area will reduce heat loss through the wall, and reduce mechanical heating - but will also reduce the transmitted solar radiation that also will reduce mechanical heating.
Can I therefore create a linear program that finds this for me?
In my linear program, this new optimization problem would be represented as:
Objective_function = min(Qh = 1 + (2 * km) + (3 * kg) + (4 * Am) + (5 * Ag) + (6 * dT) + (7 * Qr))
Variables = Am, Ah (everything else would be a constant determined by the user).
Constraints: 0 < Am < 10; 0 < Ag < 10; Am + Ag = 10.0

** END UPDATE **
Could I use my regression as a simulation (aka surrogate model) and find the optimal combination of a the variables this way via linear programming? My sense is that a linear program would be uniquely suited for this kind of problem, since it can only represent linear relationships.
However, after some google/stack overflow searches, I haven't been able to find any examples of this particular combination. I'm getting a lot of hits about using linear programming to optimize the regression itself (i.e to minimizing the cost), but not about it's use as the objective function.
Is this just because the use of regressions in linear programming is so obvious, and self-evident no one needs to mention it explicitly? Or am I missing something about why regressions aren't used in linear programming?
Comment: By the way, your new problem is still relatively simple, the optimum is either all glass or all concrete, depending on whether b3b4. So do you have a situation where b3 ≈ b4 and you wish to describe the probability/rate of choosing the wrong option? Or you wish to make some other statistical model related to the final solution/outcome of the linear programming problem? (e.g. some Bayesian posterior probability for the probability that glass or concrete is the better choice). The objective function also doesn't seem to make sense to me. Is this your real problem?
Comment: So each data point would consist of value for Qh, k, and A. The k, A columns are the predictors, and the Qh would be the response. We could obtain multiple data points from a series of time-consuming, mechanistic simulations. From there we build a regression that predicts Qh from inputs k, A. Then, in our linear program, we would define the objective as finding the: min(10 + (20 * k) + (30 * A)). So now we have a quick regression model that can be used as a 'surrogate model' of our deterministic simulation, to find an optimal combinations of k, A.
Comment: Note that I forgot to add the min/max function to the objective function in the original post, so it was confusingly not really optimizing anything. Fixed it now.
Comment: @SextusEmpiricus, yes your assumptions are all correct, and critique of the problem formulation valid. I've updated the original post to show a more complex optimization problem that shouldn't result in a trivial solution. The basic idea now is that we're trying to minimize the mechanical heating of a room, and increasing one of the variables (Area of glass) acts to both increase heat loss through the wall (which increases mech heating) and increase solar radiation (which reduces mech heating). Still a simple problem, but there's no trivial solution where you can set all variables to just 0.
Answer: I believe that in the case of linear programming the quantity you are min/maximising is linearly linked with your parameters (decision variables). In linear regression, you are looking for the vector $\beta$ that minimises the squared error:  $y^Ty-2\beta^TX^Ty+\beta^TX^TX\beta$ (obviously $\beta$ is not linearly related to it).
Moreover, in case of linear programming you have constraints, whereas in simple linear regression you do not. However, maybe if you consider the relationships between the variables you want to analyse and the relevant constraints, you could add some penalties to the above function, which will restrict the parameters from going to the area of unfeasible solutions. Nevertheless, still this will not be an equivalent to linear programming, but could be useful for what you want to do.
Comment: Thanks for answering, I'm getting a better idea of the context of linear programming/regression from your answer. But I'm not sure I understand why this wouldn't be considered a valid linear program. Once you have solved your linear regression, can't you use your vector B as coefficients for the linear program objective function? And while it's true linear regression traditionally does not have constraints, it's pretty normal to add constraints in optimization that don't exist in the simulation model (in this case the simulation model is the regression).
Answer: I finally found an answer to this in my class notes. The objective function in a linear program can be derived from other analytic models, which includes linear regression, as long as you can identify constraints to demarcate the feasible solution space.
Note that, it seems that everyone who tried to answer this question got it confused with a related, but more frequently cited problem: using the linear program to optimize the regression (where the coefficients in the regression are what you solve). I'm suggesting reversing that process, solving the regression, then using it as an input in the linear program (so we're solving for the variables).
Comment: I've been looking all day for this post.  I'm guessing you can accomplish with Python using Pulp?  or some other Linear Optimizer package.  I'm in the same situation - I have run the regression, have the coefficients, need to find the optimal value of the variables.  Additionally, I need to be able to solve for a fixed value of the dependent variable.  If I'm reading this correctly, it seems like this can be done.
Comment: @logisiticregress I missed this question, but I think there's very clearly a way to use the regression as the objective function, since they both define a linear equation. However I haven't been able to identify a non-trivial solution for the cases where this can be used (that's why I struggled with the example problem in my posts above).
Answer: You seem to describe a case of linear programming where there is uncertainty in the objective function (and you could generalize this and have uncertainty in the linear boundaries as well).

Could I use my regression as a simulation (aka surrogate model) and find the optimal combination of a the variables this way via linear programming?

No.
Doing this would mean that you fix the linear programming problem and ignore the uncertainty that is inherent to the regression problem.
Yes.
You can do that (and probably many people do it, a two-step approach is simpler and more practical), but it might not be the best way to solve your problem.
What your problem/situation is that is actually not so much clear in your question. But, you may imagine that one has more specific wishes regarding the cost function that is optimized in the regression step. For instance it could be that we do not wish to minimize the residuals of the regression line, but instead we wish to minimize the expectation value of the objective function.

Example
In your example case the solution is always at the end points. The uncertainty in the equations defining the linear programming problem is not so relevant for the solution of the problem.
We can however come up with an alternative problem where there is a more clear discrepancy between the minimization of the regression problem (minimizing the sum of squares of the residuals) and plugging that solution into the linear programming, or minimizing more holistically the outcome of the linear programming.
Let's use for this type of example the following cost function (which is to be minimized):
$$y = \frac{1}{3} x^3 - a x$$
This problem may look contrived, but we choose it because it is easy to see that the optimum of the function $y(x)$ occurs in the point $x=\sqrt{a}$.
So for some given set of measurements of $y$ (dependent variable) given several $x$ (independent variable) we could solve the regression problem and say that the solution is $\hat{x}_{min}=\hat{a}^{0.5}$, with the objective value $\hat{y}_{min}=\hat{a}^{1.5}$
But... that is an optimization for the value of $\hat{a}$.

We might, instead, want to minimize the solution for $\hat{x}_{min}$ or $\hat{y}_{min}$. The sample distributions of these values may not need to be nice symmetric functions around the mean (they are different from the estimate of $\hat{a}$). So possibly this could lead to choosing a different way to select the optimum (e.g. some correction for bias of the estimator).
At the same time the example shows that it might not matter that much. Even when we make the model with only a few points or with a lot of noise, the result turns out to be quite well. (But, this may not be the case for some more complex model, especially when there is asymptotic and non-linear behavior or non-symmetric cost functions.)

set.seed(1)
layout(matrix(1:3,3))

simulate_A <- function() {
  # model
  x <- c(1,3,7,9)
  y <- (1/3) * x^3 -  5^2 * x + rnorm(4,0,100)
  #plot(x,y)
  # fitting
  mod <- lm((y-x^3/3)~0+x)
  # outcome
  return((-mod$coefficients)^0.5)
}

sample_dist <- replicate(10^5, simulate_A())
hist(sample_dist, main = "histogram of a^0.5", breaks = seq(0,20,1/10), xlim = c(0,10))
hist(sample_dist^2, main = "histogram of a", breaks = seq(0,150,1/2), xlim = c(0,50))
hist(sample_dist^3, main = "histogram of a^1.5", breaks = seq(0,1350,5/2), xlim = c(0,250))

Comment: @saeranv My answer is just a nuance. The two-stage idea that you proposed is not so bad. The outcome from different methods of optimization are often not so far apart. A simple method will often already be close to the optimal solution, and a more complex method is often doing only some fine-tuning to give a slightly better result. Whether you can get something out of it will depend on the type of model and the type of goal/application that is to be optimized.
Comment: @saeranv It is 'yes and no' because, on the one hand it can matter when you ignore error propagation and do it as two steps instead of a combined method, but on the other hand it may only be a minor offence. In your example, with a trivial solution that is not much influenced by the regression error it doesn't matter. In my example it matters, but only a little but (I could not really come up with an extreme example that is also clear).
Comment: Thank you for your detailed response. I'm marking this as the right answer (and gave you the bounty) because it has the clearest discussion of the problem (clearer then mine) and some of the problems inherent to it, however I would still appreciate some further clarification on your comment before I fully understand your reasoning. Specifically, what do you mean by: "No. Doing this would mean that you fix the linear programming problem and ignore the uncertainty that is inherent to the regression problem. Yes. You can do that..." I'm confused by the No and then Yes. Are both true?
Comment: Re: "For instance it could be that we do not wish to minimize the residuals of the regression line, but instead we wish to minimize the expectation value of the objective function." I haven't been thinking of my problem this way, but I think this is correct, (if I'm understanding you correctly). If I have many parameters with some variance in my objective function, I want to use the linear model to explore the feasible solution space of the problem, and minimize it's expectation.
Comment: just to make sure I understand: when you say 'ignore error propagation', are you referring to the uncertainty in the regression model that we are ignoring when we use it in the linear model?
Comment: @saeranv that is what I was thinking of. Your regression model comes with uncertainty. You are *estimating* a solution of the linear programming model, the uncertainty in this estimate comes from uncertainty in the regression model. The goal of the regression is to find some solution with minimal uncertainty. The way to do that depends on how you define the cost function to be optimized. (but in addition to estimation error, you might also think about prediction error, ie. potentially the value for the coefficients b are not constant due to variations in the materials used to build the room).
Comment: Got it, now I'm satisfied this has answered my original post fully. My proposal was not as simple as I originally thought, and I'll have to rethink my idea with some of the issues you raise.
Answer: Least squares regression doesn't have a linear objective function, as the name suggests. However, Linear Programming is the standard way to solve Least Absolute Deviation, or more generally, quantile regression problems. The difference is that least squares gives you a forecast of the conditional mean of the response variable, given the data, while LAD/quantile regression gives you a forecast of the conditional median/quantiles. So if your model is $y = Xb + u$, and you want to find $b$ to minimize the objective:
$\min \sum |Xb - y| $
then you can achieve this by solving the following linear program:
$\min \sum u^+ + u^-$
subject to $y = Xb + u^+ - u^-$ and $u^+, u^- \ge 0$ (so $u^+$ and $u^-$ can be thought of as the positive and negative components of the residuals, respectively)
This is the LAD estimator, its solution, $\hat{b}$, gives a forecast $\hat{y} = X\hat{b}$ of the conditional median of $y$ given $X$. This can be extended to forecasts of arbitrary quantiles. Note that the solution for $\hat{b}$ isn't necessarily unique (fun exercise: when does that happen?), and it's convential to use the lowest value in that case.
Historically, the first examples of regression problems were actually closer to this approach than the now quasi-standard least squares, its modern treatment is largely due to Roger Koenker (here's a great resource if you're interested).
Comment: If I'm understanding your response correctly, I think this is confusing the use of linear program techniques to find the best linear regression (by optimizing/minimizing the error), with what I'm actually asking. What I'm asking for is the opposite - once you have solved the linear regression, can you use the (solved) coefficients to define the linear program objective function. Basically, I want to use the linear regression as a simulation model (aka surrogate model), and the linear program to find ways to optimize associated variables.
Comment: Note I've updated my question to clarify the distinction. Hopefully that helps!
Answer: Firstly, great question in terms of linear regression versus    linear programming within an optimization context - but I'm still    unsure of how you are proposing to use linear regression to derive    the objective function:

Linear regression requires a Y-value and, in this instance, the
Y-value is the result of the objective function so this wouldn't work
as step 1 of an optimization process. Unless I've missed something of
course...

Simulation of a demarcated solution space is simple enough in terms
of randomly generating (bounded) independent values according    to
relevant distributions. But, you don't need linear    regression to
do      this. You do however need an objective function    to
generate the    corresponding Y-values.

Furthermore, to play devil's advocate, once you've generated such a
bounded solution space you don't need linear programming to find the
optimal solution to minimize/maximise the objective function -
sorting the solution space will suffice.

To-date, I've found linear regression (and decision trees, etc) to be useful - after simulation of the solution space - in cross-checking the coefficients/feature importance in more complicated models.
And of course, linear programming has some impressive algebra to expedite finding the optimal point(s) of a constrained solution space in the first place.
I hope this helps...
Comment: OK, I think we're working on the same question/problem here :- why can't we use linear programming to optimise a regression model built on past (but not necessarily all possible) values by exploring a well-bounded solution space that includes best (better?) estimates of possible values based on domain knowledge. If this is in-line with your objective, I'd like to update my post...
Comment: For point 1, I am thinking of a scenario where, for example, you have a sparse set of inputs/y-labels that you want to develop a model for (our regression equation) and then use that model to explore other combinations of inputs that weren't present in the original sparse dataset. The relationship between our inputs and the y is what we need for linear programming, not the y-value.
Comment: For point 2: the objective function is the regression equation. For point 3, you may be right... but why isn't this be true for any linear programming problem? Every linear programming problem defines some bounded solution space that relates constrained inputs to some objective function, why can't you just sort the solution space in those cases as well?
Comment: That is a much clearer way to say what I was trying to express. I assumed all my failed efforts to think of a non-trivial problem where the objective function was a regression was a coincidence. I believe @SextusEmpiricus also ended up finding his solution was trivial, but he assumed, like I did that: "'...this may not be the case for some more complex model, especially when there is asymptotic and non-linear behavior or non-symmetric cost functions.)." It seems you are suggesting there is a reason for this, if so, that would really awesome to find out.


React Native - ListView

Question: O ListView do ReactNative aceita um array de arrays ?
Pois preciso receber os dados da API da seguinte forma :
[[{"userId":1,"userName":"Ricardo"},{"userId":1,"userName":"Ricardo"}],[{"userId":1,"userName":"Ricardo"},{"userId":1,"userName":"Ricardo"}]].

Fiz o seguinte código para exibi-lo :
renderRowUsers(rowData, sectionID, rowID) {
     return rowData.map(function(user, i){
        return(
          <View key={i}>
            <Text>{user.userId}</Text>
            <View>
              <Text>{user.userName}</Text>
            </View>
          </View>
        );
    });
}

e
const usersDS = new ListView.DataSource({
    rowHasChanged: (r1, r2) => r1.user !== r2.user
});

this.state = {
    usersDataSource: usersDS.cloneWithRows([{
        "userId": "",
        "userName": "Ricardo"
    }])
}

<ListView
    style={{paddingTop: 2, height:100}}
    dataSource={this.state.usersDataSource}
    renderRow={this.renderRowUsers.bind(this)}
/>

Mas isso me retorna o seguinte erro :

"StaticRender.reder():A valid React element(or null) must be retorned. You may
  have returned undefined, an array or some other invalid object."
Comment: Podes mostrar o código de `ListView`? dá-me ideia que essa array de `this.renderRowUsers` devia ir para dentro do jsx de `ListView`
Comment: Acrescentei no código, fiquei na dúvida do que colocar no rowHasChanged , pois como ele vai comparar os arrays ?
Comment: Era melhor colocares o(s) teu(s) component completo, assim pedaços dele é dificil saber como é a lógica.
Answer: Concordo que você deve por os components em completo. Só com o que você tém agora aqui não dá para a gente saber o que está acontecendo.
Verifique a existência da função render() de cada component, porquê é necessária para cada um. A sua resposta da API parece ser simples, nada demais. Se for só uma array dentro de outra, eu só faria isso: usaria resposta[0] para pegar a array de objetos e fazia um map pra criar Item components baseado em cada objeto.
Não sei o contexto que você pôs this.state, mas você não pode mudar o state só fazendo um reassignment da variável state. É contra immutability da variável, que é um dos princípios do React. Quando você quiser mudar o state, você usa this.setState({ chave1: valor1, chave2: valor2 }), por exemplo, para definir um novo estado pros valores incluidos. O unico local que voce pode definir o state usando this.state = {} é na função constructor se você estiver usando ES6 (se não, defina o estado initial usando função getInitialState(), retornando um objeto literal com chave-valores dela).

React Native - ListView


Shorter syntax for casting from a List to a List?

Question: I know it's possible to cast a list of items from one type to another (given that your object has a public static explicit operator method to do the casting) one at a time as follows:
List<Y> ListOfY = new List<Y>();

foreach(X x in ListOfX)
    ListOfY.Add((Y)x);

But is it not possible to cast the entire list at one time? For example,
ListOfY = (List<Y>)ListOfX;

Comment: Presuming X derives from Y, and Z derives from Y, think what would happen if you added Z to your List which is really a List.
Answer: If X can really be cast to Y you should be able to use
List<Y> listOfY = listOfX.Cast<Y>().ToList();

Some things to be aware of (H/T to commenters!)

You must include using System.Linq; to get this extension method
This casts each item in the list - not the list itself. A new List<Y> will  be created by the call to ToList().
This method does not support custom conversion operators. ( see Why does the Linq Cast<> helper not work with the implicit cast operator? )
This method does not work for an object that has an explicit operator method (framework 4.0)
Comment: Have another gold badge. This was quite useful.
Comment: I had to google H/T btw. I've never seen that before in my life
Comment: Yeah "H/T" is "Hat tipping", or thanking basically.
Answer: The direct cast var ListOfY = (List<Y>)ListOfX is not possible because it would require co/contravariance of the List<T> type, and that just can't be guaranteed in every case. Please read on to see the solutions to this casting problem.
While it seems normal to be able to write code like this:
List<Animal> animals = (List<Animal>) mammalList;

because we can guarantee that every mammal will be an animal, this is obviously a mistake:
List<Mammal> mammals = (List<Mammal>) animalList;

since not every animal is a mammal.
However, using C# 3 and above, you can use
IEnumerable<Animal> animals = mammalList.Cast<Animal>();

that eases the casting a little. This is syntactically equivalent to your one-by-one adding code, as it uses an explicit cast to cast each Mammal in the list to an Animal, and will fail if the cast is not successfull.
If  you like more control over the casting / conversion process, you could use the ConvertAll method of the List<T> class, which can use a supplied expression to convert the items. It has the added benifit that it returns a List, instead of IEnumerable, so no .ToList() is necessary.
List<object> o = new List<object>();
o.Add("one");
o.Add("two");
o.Add(3);

IEnumerable<string> s1 = o.Cast<string>(); //fails on the 3rd item
List<string> s2 = o.ConvertAll(x => x.ToString()); //succeeds

Comment: @Jamiec I didn't +1 because he starts with "No, it's not possible", while burying the answer many who find this question are looking for. Technically, he did answer the OP's question more thoroughly though.
Comment: I cant believe ive never +1'd this answer until now. Its so much better than mine above.
Answer: To add to Sweko's point:
The reason why the cast
var listOfX = new List<X>();
ListOf<Y> ys = (List<Y>)listOfX; // Compile error: Cannot implicitly cast X to Y

is not possible is because the List<T> is invariant in the Type T and thus it doesn't matter whether X derives from Y) - this is because List<T> is defined as:
public class List<T> : IList<T>, ICollection<T>, IEnumerable<T> ... // Other interfaces

(Note that in this declaration, type T here has no additional variance modifiers)
However, if mutable collections are not required in your design, an upcast on many of the immutable collections, is possible, e.g. provided that Giraffe derives from Animal:
IEnumerable<Animal> animals = giraffes;

This is because IEnumerable<T> supports covariance in T - this makes sense given that IEnumerable implies that the collection cannot be changed, since it has no support for methods to Add or Remove elements from the collection. Note the out keyword in the declaration of IEnumerable<T>:
public interface IEnumerable<out T> : IEnumerable

(Here's further explanation for the reason why mutable collections like List cannot support covariance, whereas immutable iterators and collections can.)
Casting with .Cast<T>()
As others have mentioned, .Cast<T>() can be applied to a collection to project a new collection of elements casted to T, however doing so will throw an InvalidCastException if the cast on one or more elements is not possible (which would be the same behaviour as doing the explicit cast in the OP's foreach loop).
Filtering and Casting with OfType<T>()
If the input list contains elements of different, incompatable types, the potential InvalidCastException can be avoided by using .OfType<T>() instead of .Cast<T>(). (.OfType<>() checks to see whether an element can be converted to the target type, before attempting the conversion, and filters out incompatable types.)
foreach
Also note that if the OP had written this instead: (note the explicit Y y in the foreach)
List<Y> ListOfY = new List<Y>();

foreach(Y y in ListOfX)
{
    ListOfY.Add(y);
}

that the casting will also be attempted. However, if no cast is possible, an InvalidCastException will result.
Examples
For example, given the simple (C#6) class hierarchy:
public abstract class Animal
{
    public string Name { get;  }
    protected Animal(string name) { Name = name; }
}

public class Elephant :  Animal
{
    public Elephant(string name) : base(name){}
}

public class Zebra : Animal
{
    public Zebra(string name)  : base(name) { }
}

When working with a collection of mixed types:
var mixedAnimals = new Animal[]
{
    new Zebra("Zed"),
    new Elephant("Ellie")
};

foreach(Animal animal in mixedAnimals)
{
     // Fails for Zed - `InvalidCastException - cannot cast from Zebra to Elephant`
     castedAnimals.Add((Elephant)animal);
}

var castedAnimals = mixedAnimals.Cast<Elephant>()
    // Also fails for Zed with `InvalidCastException
    .ToList();

Whereas:
var castedAnimals = mixedAnimals.OfType<Elephant>()
    .ToList();
// Ellie

filters out only the Elephants - i.e. Zebras are eliminated.
Re: Implicit cast operators
Without dynamic, user defined conversion operators are only used at compile-time*, so even if a conversion operator between say Zebra and Elephant was made available, the above run time behaviour of the approaches to conversion wouldn't change.
If we add a conversion operator to convert a Zebra to an Elephant:
public class Zebra : Animal
{
    public Zebra(string name) : base(name) { }
    public static implicit operator Elephant(Zebra z)
    {
        return new Elephant(z.Name);
    }
}

Instead, given the above conversion operator, the compiler will be able to change the type of the below array from Animal[] to Elephant[], given that the Zebras can be now converted to a homogeneous collection of Elephants:
var compilerInferredAnimals = new []
{
    new Zebra("Zed"),
    new Elephant("Ellie")
};

Using Implicit Conversion Operators at run time
*As mentioned by Eric, the conversion operator can however be accessed at run time by resorting to dynamic:
var mixedAnimals = new Animal[] // i.e. Polymorphic collection
{
    new Zebra("Zed"),
    new Elephant("Ellie")
};

foreach (dynamic animal in mixedAnimals)
{
    castedAnimals.Add(animal);
}
// Returns Zed, Ellie

Comment: Hey, I just tried the "Using foreach() for type filtering" example using:

var list = new List() { 1, "a", 2, "b", 3, "c", 4, "d" };

foreach (int i in list)
    Console.WriteLine(i);

and when I run it I get "Specified cast is not valid." Am I missing something? I didn't think foreach worked this way, which is why I was trying it.
Comment: Also, it's not a reference vs. value type thing. I just tried it with a base class of 'Thing' and two derived classes: 'Person', and 'Animal'. When I do the same thing with it I get: "Unable to cast object of type 'Animal' to type 'Person'." So it's definitely iterating through each element. IF I were to do an OfType on the list then it would work. ForEach would probably be really slow if it had to check this, unless the compiler optimized it.
Comment: Thanks Brent - I was off course there. `foreach` does not filter, but using a more derived type as the iteration variable will coerce the compiler into attempting a Cast, which will fail on the first element which doesn't comply.
Answer: You can use List<Y>.ConvertAll<T>([Converter from Y to T]);
Answer: This is not quite the answer to this question, but it may be useful for some: as @SWeko said, thanks to covariance and contravariance, List<X> can not be cast in List<Y>, but List<X> can be cast into IEnumerable<Y>, and even with implicit cast.
Example:
List<Y> ListOfY = new List<Y>();
List<X> ListOfX = (List<X>)ListOfY; // Compile error

but
List<Y> ListOfY = new List<Y>();
IEnumerable<X> EnumerableOfX = ListOfY;  // No issue

The big advantage is that it does not create a new list in memory.
Comment: I like this because if you have a large source list, there is no performance hit in the beginning. Instead there is a small not noticable cast for each entry being processed by the receiver. Also no huge memory build up. perfect for processing streams.
Answer: In case when X derives from Y you can also use ToList<T> method instead of Cast<T>
listOfX.ToList<Y>()

Answer: items.Select(x => (Object Cast)x);
Answer: dynamic data = List<x> val;
List<y> val2 = ((IEnumerable)data).Cast<y>().ToList();


Como alterar os valores de um Hash?

Question: Preciso de um loop para alterar os valores desse objeto
{
    [ "Begin", "Dom" ] => 0,
    [ "Begin", "Seg" ] => 8,
    [ "Begin", "Ter" ] => 10,
    [ "Begin", "Qua" ] => 30,
    [ "Begin", "Qui" ] => 20,
    [ "Begin", "Sex" ] => 1,
    [ "Begin", "Sáb" ] => 0,
    [ "Finish", "Dom" ] => 0,
    [ "Finish", "Seg" ] => 1,
    [ "Finish", "Ter" ] => 0,
    [ "Finish", "Qua" ] => 0,
    [ "Finish", "Qui" ] => 0,
    [ "Finish", "Sex" ] => 0,
    [ "Finish", "Sáb" ] => 0
}

Preciso mudar os valores 0,8,10,30,20...
Como posso fazer isso?
Answer: Modificando os valores
Primeiro armazene o Hash em uma variável
meu_hash = {
    [ "Begin", "Dom" ] => 0,
    [ "Begin", "Seg" ] => 8,
    [ "Begin", "Ter" ] => 10,
    [ "Begin", "Qua" ] => 30,
    [ "Begin", "Qui" ] => 20,
    [ "Begin", "Sex" ] => 1,
    [ "Begin", "Sáb" ] => 0,
    [ "Finish", "Dom" ] => 0,
    [ "Finish", "Seg" ] => 1,
    [ "Finish", "Ter" ] => 0,
    [ "Finish", "Qua" ] => 0,
    [ "Finish", "Qui" ] => 0,
    [ "Finish", "Sex" ] => 0,
    [ "Finish", "Sáb" ] => 0
}

Depois crie um loop para modificar os valores para o que quer que queira e pronto! Veja:
meu_hash.each_key do |key|
  meu_hash[key] = 5
end

Utilizei o Hash#each_key já que não precisei o value do Hash durante o loop. Se você for utilizar, use o Enumerable#each dessa forma:
meu_hash.each do |key, value|
  meu_hash[key] = value * 5
end

Também pode optar pelo Enumerable#map, mas não gosto dessa solução no Hash, já que não modifica ou retorna um Hash:
novo_hash = Hash[meu_hash.map {|key, value| [key, value * 5]}]

Essa forma é pura por não afetar o meu_hash, criando uma nova instância.
Deixando o código um pouco mais idiomático
Pode utilizar um atalho para criar um array de strings, o %w ou %W. Ficaria assim:
meu_hash = {
  %w[Begin Dom] => 0,
  %w[Begin Seg] => 8,
  %w[Begin Ter] => 10,
  %w[Begin Qua] => 30,
  %w[Begin Qui] => 20,
  %w[Begin Sex] => 1,
  %w[Begin Sáb] => 0,
  %w[Finish Dom] => 0,
  %w[Finish Seg] => 1,
  %w[Finish Ter] => 0,
  %w[Finish Qua] => 0,
  %w[Finish Qui] => 0,
  %w[Finish Sex] => 0,
  %w[Finish Sáb] => 0
}

Como alterar os valores de um Hash?


What is the best strategy in ice hockey when drawing a penalty on a PP?

Question: Say a team has a 1 man power play with 1 minute left, and they then draw another penalty, should they immediately give the puck to the other team for a 5-on-3 power play or pull the goalie for a 6-on-4 and a 2 minute PP when they lose the puck?
Answer: The majority of the time it is a better plan to draw the penalty then immediately get the 5 on three. This situation actually just came up one the Blackhawks vs Kings games for the Semi Finals of the Stanley Cup. One of the Hawks forwards drew a second penalty in the offensive zone. They pulled the goalie and tried the 4 on 6 for about 25 seconds but had nowhere to go with the puck. Unless an obvious opportunity presented itself, such as one of the King's defensemen was without a stick, it would have been better for them to get the 5 on 3. It gives the primary PP forwards a chance to rest, regroup, and decide how to proceed on the play and hopefully convert.


Como buscar um elemento com a mesma classe dependendo da quantidade de filhos?

Question: O meu cenário é o seguinte, eu tenho duas ul com li. As uls possuem a mesma classe, porém eu queria manipular apenas uma delas, no caso, a que possui apenas uma li como filha.
Exemplo:
http://codepen.io/anon/pen/OMXpVg
Exemplo 2:

1

2

3

1

Eu preciso manipular apenas a ul teste que tenha apenas 1 filho, que no caso é a segunda.
Pensei em selecionar todas as uls, e fazer uma verificação com o childElementCount, se fosse maior que 1, eu aplicaria um CSS na ul, se não, nada aconteceria. Porém tentei usar o próprio childElementCount e não consegui fazer a comparação, tentei o .find() também.
Comment: Nao entendi o que você quer fazer.
Comment: [Olhe isso](https://api.jquery.com/children/)
Comment: @PauloHDSousa, veja se entende agora
Answer: você pode procurar pela li pertencente a .teste que é filha unica, então acessar o parentNode da mesma.

var itens = document.querySelectorAll(".teste li:only-child");
var listas =[].map.call(itens, function (item, indice) {
  return item.parentNode;
})
console.log(listas);

1

2

3

1

caso prefira, em jQuery:

var listas = $(".teste li:only-child").parent();
console.log(listas);

1

2

3

1

Comment: @PedroCamaraJunior tinha esqueci que o `.parent()` faz exatamente a mesma coisa que o meu `.map` estava fazendo.
Comment: funcionou perfeitamente, só achei a utilização do Jquery.filter mais simples pro meu entendimento.
Comment: @haykou pode ficar ainda mais simples utilizando o exemplo do TobyMosque `var $minhaUl = $(".teste li:only-child").parent();`
Comment: valeu galera, nao sei nem qual marcar como resposta porque todas funcionaram
Answer: Uma maneira é utilizando o jQuery.filter()

var $elementos = $(".teste");

var $minhaUl = $elementos.filter(function() {
  return $(this).find('li').length === 1;
});

$minhaUl.css('background', 'blue');

1

2

3

1

Answer: Peguei segue seu código js e adicionei o if que você precisa.
var lista = document.querySelectorAll('.lista');
console.log(lista);
var listaj = $('.lista');
console.log(listaj.size());
$( ".lista" ).each(function( index ) {
 if( $(this).find("li").length == 1)
   //Código aqui apenas 1 item na LI.
});

Comment: método .size ()  é obsoleto a partir do jQuery 1.8.
Comment: @durtto ele fez assim no código dele, só adaptei a parte final
Answer: Tente isso, colocar uma id na sua ul.

Elemento 1

Elemento 2

Para saber o tamanho:

$("#minhaLista li").length


Missing http header in Ajax response

Question: I'm having an issue with some missing http headers in a Ajax response. The ajax-page (.NET) adds som additional info to the http header by using Me.Response.AddHeader("ResponseCode", mResponseCode). If I access the ajax-page directly and use httpAnalyser to check the headers, I can see that the headers are added correctly. But when I call the Ajax page through jQuery, the headers are missing.
I'm puzzled. Anyone out there that can help me?
Best regards,
Steffen
Answer: In your complete or success method the first parameter is an XMLHttpRequest object that contains this information. You can retrieve any response header like this:
xmlHttpRequest.getResponseHeader('header-name');

Comment: Yes - I know. But when I try that I get an empty string, because the header that I'm accessing is not present in the http header when I call the page through Ajax. It is however present if I access the Ajax page directly.
Comment: You can also check the headers for AJAX calls with Firefox's Firebug add-in (using the Net tab). So you know if the header is really missing and if the problem is on the server or on the client.
Comment: The headers was not present, but it turned out that is was a problem elsewhere which cause the problem.

But thanks for trying to help me out :-)

Missing http header in Ajax response


Yet another  error message

Question: I'm using EasyPhp DevServer with Apache 2.4.25, PHP 5.6.30, and PHP 7.1.3 installed.
For times, I usually switch between those two PHP versions, without changing any configuration element anywhere, and it works fine.
Now I just added PHP 8.1.2, and when I switch to it I get the well known error message:

PHP Warning:  PHP Startup: Unable to load dynamic library 'openssl' (tried: C:\Program Files (x86)\EasyPHP-Devserver-17\eds-binaries\php\php812vs16x86x230327010135\ext\php_openssl (Le module spécifié est introuvable), C:\Program Files (x86)\EasyPHP-Devserver-17\eds-binaries\php\php812vs16x86x230327010135\ext\php_php_openssl.dll (Le module spécifié est introuvable)) in Unknown on line 0

Obviously I read a lot of answers about that, but no one seem to be of help in my case, since the php.ini for 8.1.2 includes the same needed specifications than the two other ones:

extension_dir = "C:\Program Files (x86)\EasyPHP-Devserver-17\eds-binaries\php\php812vs16x86x230327010135\ext", which is the correct path where resides php_openssl.dll
extension=openssl, rather than extension=php_openssl.dll for the older versions (but the error message says it did search for php_openssl.dll)

Also, despite of what is said in https://www.php.net/manual/en/openssl.installation.php:

Note to Win32 Users
In order for this extension to work, there are DLL files that must be available to the Windows system PATH.
(...)
This extension requires the following files to be in the PATH: libeay32.dll, or, as of OpenSSL 1.1, libcrypto-*.dll

openssl is correctly loaded by PHP 5.6.30 and PHP 7.1.3 although nor the DLL nor other cited files are present in the Windows system PATH.
So I remain stuck: what else can I try?
Answer: Looking for as many different advices as possible, I found a page from RAD Studio: https://docwiki.embarcadero.com/RADStudio/Sydney/en/OpenSSL.
Only oriented to openssl itself for any purpose, it gives precise information about how to install it on Windows.
So I tried following its recommandation, which was to include a copy of the libeay32.dll and ssleay32.dll dynamic library files to the file system, using the OpenSSL installer https://slproweb.com/products/Win32OpenSSL.html to install OpenSSL 1.1.1t Light.
And now PHP 8.1.2 works fine with openssl enabled, and without any other change or addon!
I can't figure out why these libraries are necessary for PHP 8.1.2 when the older versions worked without them, especially since they are not exactly the ones cited by the PHP manual page https://www.php.net/manual/en/openssl.installation.php.

Yet another  error message


Question about covariant derivative of the vector field

Question: Actually, I am getting confused in the following line "$\nabla_{X_p}Y$" is the directional derivative of the vector field $Y$ along the tangent vector $X_p$.
When we say that the directional derivative of the vector field $Y$ along a curve say $\gamma$ that is $\nabla_{\dot{\gamma(t)}}Y$ so in this case we fix a point $\gamma(t)$ on the curve in the manifold and choose some other point $p$ and then we have a tangent vector $Y_p$ and then we parallel translate the tangent vector at $\gamma (t)$ say $X_{\gamma(t)}$ to point $p$.Then we look for the change and accordingly define the covariant derivative.
My question is in the case of the directional derivative along the curve we moved the vector at $\gamma(t)$ to $Y$ along the curve but what in the case of the directional derivative along the tangent vector $X_p$ mean geometrically? I mean how we are moving our point along what??
Comment: "along" is not the right word; just like in calculus, we're computing the covariant derivative of the vector field $Y$ at $p$ *in the direction of* $X_p$.
Comment: This should be $\nabla_{\gamma'(t)}Y$, not $\nabla_{\gamma(t)}Y$.
Comment: ohh yes ,thanks.
Comment: I find your question hard to understand. You are studying how the vector field $Y$ is changing instantaneously at $p$ as you move along any curve $\gamma$ with $\gamma(0)=p$ and $\gamma'(0)=X_p$. One option, if you have the vector field $X$, is to take the integral curve of $X$ through $p$.
Comment: Actually, my question is that when we say that directional derivative of the vector field $Y$ along $X_p$ what does it mean I mean are we moving along with the curve parallel from one point to another? I am finding it difficult to visualize.
Answer: When computing the derivative of a vector field, you want to somehow construct the difference quotient between $Y_p\in T_pM$ and $Y_{γ(t)}\in T_{γ(t)}$.
Now the tangent vector spaces are not the same, they form a bundle over the manifold, which implies some continuity, but that does not allow to embed one into the other uniquely.
So what is needed is some map $A_t:T_{γ(t)}\to T_pM$, so that then the divided quotient $\frac{A_tY_{γ(t)}-Y_p}{t}$ makes sense, has a limit, and that limit does only depend, additionally to $Y$, on $γ'(0)$.
The question is now transformed on how to construct such a map that it is uniquely defined for every path $p$ in some consistent way, independent of the coordinate system used in its construction.
If the maps $A_t$ are isometric towards some Riemannian metric on $M$ and in some sense $t\mapsto A_t$ realizes the "least torsion", one can call it "parallel transport along the path". In extension, also non-metric variants of it are called parallel transport, especially on general vector bundles that have no inherent connection to the metric on the manifold.
Answer: Another way to think of it is this.  Many books define the tangent space as an equivalence class of paths going through that point.  So just pick one of the curves in the equivalence class.
Here is an example reference:
https://en.wikipedia.org/wiki/Tangent_space#Definition_via_tangent_curves
Comment: How is it related to covariant derivatives or affine connections?
Comment: As I understood the question, it was how to intuitively understand the covariant derivative along a vector, when one intuitively understood the covariant derivative along a path.
Comment: Sure. But your answer points to the definition of the tangent space (particularly to its definition via equivalent classes of curves). This is not directly related to covariant derivatives. The covariant derivative (along a path) is another object
Comment: But it does answer his question.
Comment: I am really not convinced, but well, if you say so
Comment: The question is: if I understand X in terms of Y, how can I understand X in terms of Z?  Answer: here is how to understand Z in terms of Y.  No need to mention X in the answer.
Comment: Ok, I see what you mean there


If $ f:G \to H $ is a homomorphism between groups $ G$ and $ H $ and if $ X \subseteq G $ then $ f (\langle X \rangle) = \langle f (X) \rangle $.

Question:
Let $\langle X \rangle$ denote the subgroup generated by $ X. $ If $f: G \to H$ is a homomorphism between groups $G$ and $H$ and if $ X \subseteq G $ then $ f (\langle X \rangle) = \langle f (X) \rangle$.

How do I use the homomorphism property to prove this with subgroups? I've only been introduced to the definition that is defined for elements $ a, b \in G $ such that $ f(ab) = f (a) f (b). $ Would I just elements  $a, b \in \langle X \rangle$ instead?
Comment: Ok. Set $a=x_1x_2\ldots x_k\in\langle X\rangle$. If $x_i\in X$, then $f(x_i)\in f(X)$; if $x_{i}^{-1}\in X$, then $f(x_i)=f((x_i^{-1})^{-1})= f(x_i^{-1})^{-1}$ is an inverse of element in $f(X)$, hence is in $\langle f(X)\rangle$. Now $f(a)= f(x_1)f(x_2)\ldots f(x_k)\in\langle f(X)\rangle$. This proves $\subseteq$. The part $\supseteq$ is very similar.
Comment: Note that $\langle X\rangle$ is the smallest subgroup of $G$ containing $X$, and $\langle f(X)\rangle$ is the smallest subgroup of $H$ containing $f(X)$. Now, note that $f(\langle X\rangle)$ is a subgroup of $H$ containing $f(X)$, hence $f(\langle X\rangle)\supseteq \langle f(X)\rangle$, since $\langle f(X)\rangle$ is the smallest subgroup containing $f(X)$. Also $f^{-1}(\langle f(X)\rangle)$ is a subgroup containing $X$, hence $f^{-1}(\langle f(X)\rangle)\supseteq \langle X\rangle$, hence $f(\langle X\rangle)\subseteq f(f^{-1}(\langle f(X)\rangle))\subseteq \langle f(X)\rangle$
Comment: Use that $\langle X\rangle= \{x_1x_2\ldots x_k\mid k\geq 0,\,x_i\in X\mbox{ or }x_i^{-1}\in X\mbox{ for all }1\leq i\leq k\}$ and similar for $\langle f(X)\rangle$.
Comment: How do I use this with the homomorphism property? I know that every element of $\langle X \rangle $ will have that form but I do not know how use that with the homomorphism
Comment: Thanks, the problem is much more clear now.
Answer: Since $X\subset \left\langle X\right\rangle$, $f(X) \subseteq f(\left\langle X\right\rangle)$ and thus $\left\langle f(X)\right\rangle \subset f(\left\langle X\right\rangle)$. Let $J$ be any subgroup of $H$ which contains $f(X)$. Since $f$ is a homomoprhism, $f^{-1}(J)$ is a subgroup of $G$ containing $X$, which implies $f^{-1}(J)$ contains $\left\langle X\right\rangle$. Therefore, $J$ contains $f(\left\langle X\right\rangle)$. Since $\left\langle f(X)\right\rangle$ is itself a subgroup of $H$ which contains $f(X)$, we obtain the reverse inclusion $\left\langle f(X)\right\rangle \supseteq f(\left\langle X\right\rangle)$. Therefore, $f(\left\langle X\right\rangle) = \left\langle f(X)\right\rangle$.


Condition for Implicit Function Theorem

Question:
Given $f(x,y)$ continuously differentiable in a domain of the plane, $f(a,b) = 0$ and $f_x(a,b)\ne 0$. Can you show $f(x,y) = 0$ in a finite neighborhood of $(a,b)$?

Examples

Sphere tangent to the plane.
$f(a,b )= 0$ at one point but $f_x(a,b) = 0$ and $f_y(a,b) = 0$ and there is no neighborhood of $(a,b)$ in which $f(x,y)=0$.

Sphere intersecting the plane.
There are points $(a,b)$ (on the circle of intersection) where $f(a,b) =0 $ , $f_x(a,b)\ne 0$ , and $f(x,y)=0$ in a neighborhood of $(a,b)$, (circular arc through $(a,b)$ )

But how do you show this in general without geometry?
Application: Implicit Function Theorem.
Comment: A circular arc through $(a,b)$ *isn't* a neighborhood of $(a,b)$.
Comment: Let z=f(x,y). Sphere tangent to plane: (z+2)^2+x^2+y^2=4, z=f(x,y)=0 only at x=0 and y=0.  Sphere intersecting plane: (z+1)^2+x^2+y^2=4, z=f(x,y)=x^2+y^2-3=0 is circle of intersection. An arc of the circle goes through a finite neighborhood of any point on the circle and on that arc f(x,y)=0.
Comment: What do you exactly mean with ".... in a finite neighborhood ..."? With $\forall$ and $\exists$.
Comment: Draw a small circle in the x,y plane with center at a point of intersection of sphere and plane: You can put it in any lanquage you like.
Answer: Utterly false:
$$f(x,y) = x,\qquad f(0,0) = 0,\qquad f_x(0,0) = 1\ne 0.$$
Comment: Nice example, but not false: Equation of plane. z=f(x,y) =x is equation of plane through y axis at 45deg with z axis. Intersection of plane with xy plane (z=(f(x,y)=0) is the y axis. Any point on the y axis has a finite neighborhood in t f9he xy plane in which
Comment: Accidentally interrupted my comment and not enough time to finish edit. Nice example, but not false:  z=f(x,y) =x is equation of a plane through y axis at 45deg with z axis. Intersection of plane with xy plane (z=(f(x,y)=0) is the y axis. Any point on the y axis has a finite neighborhood in the xy plane in which f(x,y)=0, the segment of y axis in the neighborhood. But I am looking for a general proof to satisfy an assumption Rudin makes to prove the implicit function theorem.
Comment: For some background on this question, you may wish to visit http://math.stackexchange.com/questions/1254343/validity-of-implicit-function-theorem/1255740?iemail=1&noredirect=1#1255740
Comment: f(x,y)=x satisfies all conditions of Implicit Function Theorem. Does f(x,y)=0 have a solution in an xy neighborhood of a point on the y axis where f(x0,y0)=0? Indeed it does: f(x,y)=0 for x=g(y)=0y and g(y) is C' (continuous derivative). Without a proof for general case (OP), ie, that f(x,y)=0 exists, I wouldn't buy the IFT as proven. Unfortunateley it's hard to discuss because the proof is intricate and Baby Rudin 9.18 is not generally available. I would have posted it complete if I knew how.
Answer: Apostol, Mathematical Analysis, 13.4, The Implicit Function Theorem. Toward the end he states:
"Let To = {t;teRk, (0,t)eY}," (0,t) is our (f(x,y)=0,y). You cannot simply "Let" this be true. You have to show To, (f(x,y)=0), exists for the given conditions of the theorem. Examples confirm but do not prove this.
So at this point it appears the Implicit Function Theorem, and hence linearization about a point of f(x,y)=0 and implicit differentiation, is not proven. Implicit Function Postulate?
Apostol Math Analysis is online. You don't have to wade through the whole proof to appreciate this point, which comes at end. One is reminded of Dieudonne's proof which begins "Write the relation f(x,y)=0."- I don't pretend to follow the rest of it, too much work.
Answer: Inverse Function Theorem
Given E a subset of Rn and f:E->Rn
If y=f(x), if Difj=dfj/dxi i,j=1,2,3, exist and are continuous on E, and if det (Difj) ='0, at x=a, and if b=f(a)
Then y=f(x) is invertible in a finite neighborhood of y=b.
Illustration of terminology:
y1=f1(x1,x2,x3), b1=f1(a1,a2,a3)
y2=f2(x1,x2,x3), b2=f2(a1,a2,a3)
y3=f3(x1,x2,x3), b3=f3(a1,a2,a3)
x1=g1(y1,y2,y3)
x2=g2(y1,y2,y3)
x3=g3(y1,y2,y3)
Finite Neighborhood: not just in the limit as (y1,y2,y3)->(b1,b2,b3)
Implicit Function Theorem
Let z=f(x,y)
z1=f1(x1,x2,y)
z2=f2(x1,x2,y)
Let Difj  (D3f1=df1/dy, D3f2=df2/dy) i=1,2,3 j=1,2 exist and be continuous.
Let det (D1f1,D1f2; D2f1,D2f2)='0 at x,y=a,b where f(a,b)=0.
Consider the map F(z,w) where z=f(x,y), w=y
F1=f1(x1,x2)
F2=f2(x1,x2)
F3=y
Then Difj i,j=1,2,3 exists and is continuous. Furthermore det (DiFj)='0. By the Inverse Function Theorem it follows that F is invertible in a neighborhood of (f(a,b),b)=(0,b):
x1=g1(F1,F2,F3)
x2=g2(F1,F2,F3)
y=y
So far so good. If F1=0 and F2=0 in a subset of the neighborhood of (f(a,b)=0,b), then
x1=g1(0,0,y)
x2=g2(0,0,y)
in a neighborhood of y=b, ie, x=g(y).
But you can't assume this. You have to prove F1=0 and F2=0 in a subset of  a neighborhood of (0,b) under given conditions, ie, f(x,y)=0 in a subset of a neighborhood of x,y=a,b. I haven't seen this proof anywhere.
Conclusion: The Implicit Function theorem is unproven, ie, you can't start off a discussion of implicit functions by writing;
f1(x1,x2,x3,y1,y2)=0
f2(x1,x2,x3,y1,y2)=0
f3(x1,x2,x3,y1,y2)=0
because you don't know that condition exists, unless you solve it in which case the Implicit Function Theorem is academic. Assuming it exists is tantamount to assuming it is invertible (under usual conditions).
Ref: Baby Rudin, Inverse and Implicit function theorem. Also 3rd Ed.
Comment: Please use LaTeX
Answer: Switching to literal notation of Courant, Kaplan, Taylor, etc:
For F(x,y) satisfying conditions of IFT, Courant (D&I Calc II, 119) shows F(x,y) =0 has a solution y=f(x) in a neighborhood of (x0,y0). He says the extension to F(x,y...,u,v) is straight-forward:  F(x,y...,u,v)=0 has a solution v=f(x,y,..,u) in a neighborhood of P0.
Under conditions of IFT, Taylor (Adv Calc) shows F(x,y,z,u,v)=0 and G(x,y,z,u,v)=0 are satisfied in a neighborhood of P0 with u=f(x,y,z) and v=g(x,y,z).  He does this by first showing v=f(x,y,z,u) exists for F(x,y,z,u,v)=0 per above and then showing u=g(x,y,z) exists for G(x,y,z,f(x,y,z,u))= H(x,y,z,u)=0.
Finally, Taylor indicates the general case can be solved by induction.
Apostol and Rudin typify a different approach, presented abstractly, which led me to believe IFT was unproven because buried in the abstract proof was a false assumption, noted previously.
Comment: The above (not Taylor's) proof is incorrect:
For F(x,y,z,u,v)=0,  v=  f(x,y,z,u) exists in a neighborhood of P0=(x0,y0,z0,u0,v0).
For H(x,y,z,u)=0, u=g(x,y,z) exists in a neighborhood of P0'=(x0,y0,z0,u0).
But P0' is not a neighborhood of P0 so you have not shown that u=g(x,y,z) exists in a neighborhood of P0 and you have not proven IFT.
Comment: The same argument as my previous comment applies to a proof by induction. Substituting the sol for m-1 equations into mth equation changes the neighborhood. So the induction proof is invalid.
Answer: Under conditions of the Implicit Function Theorem (IFT), Courant's Differential and Integral Calculus, vol. 2 shows a neighborhood $N$ of $P_0=(x_0,y_0)$ where $F(P_0)=0$ exists such that $F(x,y)=0$ has a solution $y=f(x)$ for $x \in N$.
The proof extends to $F(x,y,z,..,u,v)$:  A neighborhood $N$ of $P_0$ exists such that $F(x,y,z,..,u,v)=0$ has a solution $v=f(x,y,z,..,u)$ for $(x,y,z,..,u) \in N$.
Given $F_1(x,y,z)$ and $F_2(x,y,z)$ and IFT conditions, a neighborhood $N_1$ of $P_0$ exists such that $F_1(x,y,z)=0$ has a solution $z=f_1(x,y)$, and a neighborhood $N_2$ of $P_0$ exists such that $F_2(x,y,z)=0$ has a solution $z=f_2(x,y)$.
Let $N=N_1 \cap N_2$. Then $z=f_1(x,y)$ for $(x,y) \in N$, and $F_2(x,y,f_1(x,y))$ has a solution $y=g(x)$ for $(x,y) \in N$:

$Y=g(x)$ for x,y in N,
$Z=f_1(x,g(x))$ for x,y in N.
$F_1,x$ or $F_1,y$ & $F_2,x$ or $F_2,y$ =0$.

That sets the stage for proof by induction, I assume.
As a specific example from everyday calculus, if $F_1(x,y,z)=0$ and $F_2(x,y,z)=0$ are equations of surfaces, then $F_1(P_0)$ and $F_2(P_0) = 0$ is the condition that they intersect at a point and $J=0$ is the condition that the normal to both surfaces are unequal at $P_0$ (i.e., not tangent). Then they intersect in a curve in a neighborhood of $P_0$.  The difference between this and general case is that you know beforehand that $F_1(x,y,z)$ and $F_2(x,y,z) = 0$ in $S$.  In the general case, you show it in a neighborhood of $P_0$.
I haven't  gone into the details because my concern is that the structure make sense, which it doesn't (for me) for Apostol's or Rudin's proof of IFT, as pointed out earlier.  But at least now (for me) the IFT seems sound in principle.

Condition for Implicit Function Theorem


Graph API: Using $filter with schema extensions data not working when request sent as part of a batch operation

Question: According to the Graph API documentation, making a GET request to get groups with extension data that includes a filtered response is acceptable.  For example, according to the doc referenced the following request should be valid:
GET https://graph.microsoft.com/v1.0/users/${id}/memberOf?$filter=graphlearn_courses/courseId eq '123'&$select=displayName,id,description,graphlearn_courses

This works when making the request as a singleton but fails and returns no response when the same request is made as part of a batch request:
POST https://graph.microsoft.com/v1.0/$batch
Accept: application/json
Content-Type: application/json

{
  "requests": [
    {
      "id": "1",
      "method": "GET",
      "url": "/users/${id}/memberOf?$filter=graphlearn_courses/courseId eq '123'&$select=displayName,id,description,graphlearn_courses"
    }
    ...
  ]
}

Can I fix this myself, or do I need MS support?
Comment: FYI, this fails with both /v1.0 and /beta versions of the Graph API.
Comment: I have a different behavior with you. Could you share a screenshot of the successful call of singleton? (including the full request and response)
Comment: Please note that Schema extensions (legacy) are not returned with $select statement, but are returned without $select. So i would recommend you to try that and see if it helps. It's documented in Microsoft Graph API limitations - https://learn.microsoft.com/en-us/graph/known-issues#delta-query
Comment: Do you still need help on this issue? If yes, please share more details I mentioned above.
Answer: Schema extensions (legacy) are not returned with $select statement, but are returned without $select. So i would recommend you to try that and see if it helps. Documentation available @ Microsoft Graph API limitations.


Can we use System IPC in android NDK code

Question: Here I want to use System IPCs methods like
<code>  <sys/msg.h>   /* SysV message queues */
  <sys/ipc.h>   /* General IPC definitions */
</code>
Here my android NDK code is in C language and I used message queue IPC mechanism for communication for other C application.
So please Let me know is there any way to achieve this IPC goal?
How can I implement this IPC mechanism in android NDK code?
Comment: [What have you tried?](http://mattgemmell.com/2008/12/08/what-have-you-tried/)
Comment: @JoachimPileborg Thanks for Your interest here i am asking about its feasibility
Answer: One year ago I wrote a survey about this topic. Here is a part of it:
2 Unix IPC mechanisms
Unix IPC mechanisms include:

Unix signals.
Unix pipes.
Unix domain sockets.

At the same time Unix System-V IPC mechanisms are not included in Android.
Bionic intentionally does not provide support for System-V IPCs mechanisms, like the
ones provided by semget(), shmget(), msgget(). The reason for this is to avoid denial-
of-service [11].
2.1 Unix signals
One of the best explanations how unix signals work we can find in wikipedia: "A
signal is a limited form of inter-process communication used in Unix, Unix-like, and
other POSIX-compliant operating systems. Essentially it is an asynchronous notifica-
tion sent to a process in order to notify it of an event that occurred. When a signal is
sent to a process, the operating system interrupts the process's normal flow of execu-
tion. Execution can be interrupted during any non-atomic instruction. If the process has
previously registered a signal handler, that routine is executed. Otherwise the default
signal handler is executed."
It seems that unix signals are rearly used in Android programming. Moreover,
some signals have been disabled in debug mode. However, it is a possible IPC
mechanism.
2.2 Unix pipes
Pipe is a communication mechanism that allows to connect directly the output stream
of one process with the input stread of another process. There are two types of unix
pipes: named pipes and unnamed pipes. It seems that in Android programming only
named pipes are used. In this case two processes interact using a special file that
connects the output and input. It should be mentioned that pipe is one-direction way
of communication, i.e. one process is always reader and the second is always writer.
The communication file has to be created on Linux filesystem, because sdcard's FAT32
does not allow to create pipe. Here is an example how a named unix pipe can be created
and used in Android (In Russian). The source code for this example can be found here.
2.3 Unix domain sockets
Unix domain sockets, on the contrary of unix pipes, allow to tranfer information in
both ways: from server to client and from client to server. Unix domain sockets
and unix pipes use file system as address name space. That means that server and
client use special file to establish communication. Considering Android there are two
classes that are used to program unix domain sockets: LocalServerSocket and
LocalSocket. All the implementation can be built around these two classes and it is
not required to use native code to make a unix domain socket. A simple example how
to use unix domain sockets is shown here.
[11] Android ndk documentation. NDK documentation for android-ndk-r6b
Comment: Android itself uses unix domain sockets in places where binder would add complexity for little useful gain.
Comment: No, it's not. It's better to use special Android IPCs like Binder, for instance. I wrote this survey to show that it is possible, but it is not recommended.
Comment: So i can Use Unix domain sockets in android ndk Becuase it would be good for communication.
Comment: But How can i communicate this things to C service application which are running on android. Binder is working for communication between Android NDK C code to other C application code?
Comment: Binder is Android IPC mechanism. Thus, yes it can be used to communicate between two native processes.


I have data from an unknown, continuous probability distribution. How do I calculate a percentile/quantile?

Question: I'm going to collect a sample of data that comes from an unknown, likely continuous, probability distribution. I don't really know anything about the data other than that it's somewhat chaotic. I want to know how to calculate a given percentile.
For example, suppose the dataset is 10 items, but I want to calculate the distribution's 95th percentile (the dataset isn't actually that small, this is just an example.) 95% of 10 is 9.5, and obviously there's no 9.5th smallest item.
So how do I calculate a percentile of this unknown distribution?
Comment: You can use the sample estimates of the mean and standard deviation, but you can say a little more than that on the basis of prior knowledge. Do know anything about the data? What do the numbers represent?
Comment: (This seems like an XY problem where you have question X (how to calculate quantiles) that you think you can solve by method Y (estimate the entire distribution), so you ask about Y instead of X, so I will assume you are interested in X.) The documentation in `R` for `quantile`, accessed via `?quantile`, gives insights into methods of calculating quantiles. For instance, for `x <- seq(1, 100, 1)`, I get different answers for `quantile(x, 0.504)` and `quantile(0.505)`.
Comment: The documentation discusses theory, which is independent of software.
Comment: @Dave thanks but I use TypeScript, not R.
Comment: @Dave Thanks for pointing me to the documentation,but it's so full of mathematical jargon that it's difficult for me to follow along (I didn't take any statistics after graduating High School)
Comment: Are you asking how to compute more percentiles than you have data points, or just how to compute percentiles in general? You give an example of the former, but then indicate that it's not actually your use case.
Answer: If you are familiar with a software package you can start by producing a histogram of the data and request the software to produce sample estimates of the percentiles.  You can then investigate the calculations of percentile estimates by hand to better understand the methodology and compare your work to the software's results. In the example you provided if you have a sample of $10$ ordered values and are interested in estimating the $95^{th}$ percentile of the population, one approach would be to take the average of the $9^{th}$ and $10^{th}$ ordered values in your sample.
Answer: Rough estimate:

Let "a" be the list of numbers.
Sort "a" in ascending order if this has not already been done.
The index i of the nth percentile = round(n * len(a)/100) - 1, where "round" rounds to the nearest whole number, and len(a) represents the length of the array.
The nth percentile is the ith element of a.
Comment: Do you know nothing about the nature of the numbers? Probably you should do nothing more than summarise them with a dotplot.


Binomial Probability to find N? Problem

Question: A doctor thinks that, when treated with a new drug, a patient has a probability of $\frac25$ to
improve. How many patients must he treat to be sure (at $p >.95$) that at least one
patient will improve?
Comment: What have you tried? Any thoughts on what distribution is appropriate?  Are the patient results independent?
Answer: Hints:

If the probability a patient will improve is $p$ then the probability a patient will not improve is $q=1-p$
If the patients' improvements are independent then the probability none of $n$ of them will improve is $q^n$
What probability values do you want for this event?

Set up the inequality and solve, possibly using logarithms and rounding.

Binomial Probability to find N? Problem


Changing article text and summary with template_preprocess_node()

Question: I use Drupal 7.9 with Views module (if the latter is important). I've created a small module for my site that changes transliteration of Japanese words in articles from Latin to Cyrillics and vice versa (yes, I need such a thing). User sees a form with radio button set, chooses transliteration, his choice goes to $_COOKIE and then I change transliteration in article summary and body based on user's choice. Or better to say I'm trying to change it but it doesn't work. The code goes like this:
function mymodule_preprocess_node(&$variables) {
    /* Suppose we have a summary containing only one word 'Yamamoto' that has to be changed to 'Ямамото' */
    $variables['node']->body['und'][0]['summary'] = 'Ямамото';
}

After this code is executed, the changed variable has the correct value of 'Ямамото'. But in the main page for some reason I see the unchanged 'Yamamoto'. What am I doing wrong? Do I change the wrong field? Do I mess up working with parameters passed by reference? Do I use the wrong hook?
Answer: I believe that the node has already been rendered by the time template_preprocess_node() is called so changing any values on the node object will have no effect. You can try looking at $variables['node']->content to see if you can modify the text in that (I think this is the full HTML rendered node though, so lots of extra text/markup to deal with here).
You're probably better off using hook_node_load() instead. This gives you a chance to alter the node object directly before it gets rendered.
Comment: Oh. That's why it didn't work for me. Okay, thanks, I'll use $variables['content']. hook_node_load() for some reason is not called in my module, and when i write something plain and simple like

`function mymodule_node_load($nodes, $types)
{
    die('Died on node_load');
}`

my site happily continues to work. I suspect it has something to do with the fact that I have a form in my module but am not very sure as I'm a newbie to Drupal. So I'll use $variables['content'].
Comment: You can always open another question if you wanna try `hook_node_load()` in the future. Good luck!


What are some examples of 2-polytope/3-polytope that are not simple?

Question: I've learned lots of stuffs in class about how to identify a simple polytope. But I've never seen a counter-example.
We use the following definition of simple polytope:
Comment: "Simplicial" means it only has simplex (triangle) facets. A counter-example is a cube. I assume this isn't what you meant.
Comment: Given the definition of simplicity you mentioned in the question, to find an example of a non-simple polytope you need only find a 3-polytope which has a vertex which is contained in 4 facets. I am amazed that you cannot find an example of that. I bet that if you mention 3 polytopes, at least one of them is non-simple.
Comment: @mr_e_man sorry my question shouldn't include that part about simplicial. I'll edit it. Thanks.
Comment: You won't find a 2-polytope (polygon) counter-example. They are all simple and simplicial, because every vertex figure and every facet (edge) is a 1-simplex (line segment).
Comment: You could really not find an example? Did you not think to ask this in class while you were learning all that stuff that you were learning about simple polytopes?
Comment: @MarianoSuárez-Álvarez what's the difference between asking there and asking here? It's not like we spent the whole lecture musing about what is and what is not a simple polytope.
Comment: I am very certain that all that you learned about how to identify simple polytopes would have been infinitely much more productive if you had had examples of non-simple polytopes. If you do not have any example of a non-simple polytope, how do you possibly understand how a test to see whether a polytope is simple or not works?
Comment: When you phrase the definition like that, it helps. But I don't see how me taking the sarcasm and rhetorical questions from you would. My brain is tired, and I agree this is not the brightest question ever been asked, but this reaction is just disappointing.
Comment: I am not being sarcastic. I am simply suggesting better ways to deal with your problem, thay of not having an example of a non-simple polytope while at the same time being taught how to recognize simple polytopes. Notice that I did not "phrase" anything: the definion of simple that quoted says exactly that.
Comment: As an instructor, there are very few things more disappointing than having a student **not** ask such an obvious question as the one you had at the time it popped in your mind. Much effort is lost uselessly after that, on both sides.
Comment: In the end, it is not the definition of simplicity or examples of non-simple polytopes that you need to learn: what you need to learn is how to learn, how to take the most advantage of your classes and other sources of instruction, how to pick a definition and find examples and non-examples. Don't let anyone talk to you about an object which you simply don't understand, much as you would probably object if your teacher started to do lectures in Croatian.
Answer: Just take the dual of a non-simplicial polytope. For example, a cube's dual is an octahedron, which has 4 edges per vertex, not 3.
Comment: Not every simplicial polytope works, though.
Comment: Sorry, I meant non-simplicial. I'll edit.
Comment: (I would guess that this only transforms the problem of the OP into "I've never seen an example of a non-simplicial polytope"…)


O que são tipos no retorno de um método?

Question: Utilizei o PHP e nunca vi isso, sabemos que existe os tipos de retorno double, float, int, boolean.
No Java quando queremos retornar um int fazemos assim:
public int soma(int numero1,int numero2) {
return numero1+numero2;

}

Agora o que eu não estou entendendo é que recentemente vi algo novo nesses tipos de retorno. Estou vendo códigos que retorna variável do tipo Connection do tipo. O que significa isso?:
public static Connection obterConexao() {
     Connection conn = null;
   try{
    conn = DriverManager.getConnection("jdbc:mysql://:3306/banco","root","senha");
   }catch(SQLException e) {
       System.out.println("erro ao conectar");
   }
   return conn;
}

Vai retornar string, int, double? Como funciona isso?
Também esse static que não vi no PHP.
Não é só nisso, já vi vários códigos usando retornos sem ser
int, float, double, boolean, eles estão usando nome de variável como assim isso? Como usar isso? Pra que serve?
Comment: @edenilson poderia explicar seu edit? Me parece que a postagem foi vandalizada, e isto não é permitido aqui. Estou aguardando uns instantes antes de efetuar o procedimento nesses casos, caso tenha sido só um engano.
Comment: O procedimento não é exclusão, e sim reversão e aviso para não fazer novamente. Uma vez postado, o conteúdo faz parte do esforço coletivo da comunidade. Mais detalhes em [help] e nos termos que aceitou ao criar a conta. Sobre as respostas, a votação classifica conforme a comunidade entender útil (mais detalhes no [tour]).
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Comment: Nos pontos que você mencionou, não existe diferença entre PHP e Java. Em ambas as linguagens é possível a criação de novos tipos pelo programador, e esses tipos podem, naturalmente, constituir valor de retorno de um método ou função. No seu caso, a função `obterConexao` retorna uma objeto do tipo Connection (ou uma instância da classe Connection). Quanto a `static`, PHP também permite a criação de métodos estáticos, isto é, que pertencem a classe e não a uma instância específica.
Comment: Obrigado vander
Comment: pode excluir , depois de umas respostas que eu recebi,
Comment: blz ta tudo certo
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver 15 pontos).
Answer: A pergunta é confusa e mostra que está aprendendo sem uma estrutura. Isso não dá certo, aprende tudo pela metade, coisas erradas, pula etapas. É como construir uma casa sem alicerce, faltando tijolos. Não aconselho fazer isso. Aprendeu alguns itens, agora aprenderá outro que faltou, mas continuará faltando outros. Falta estrutura até no texto, em código é necessário mais estrutura ainda.
Isso é exatamente um tipo, nada mais que isso. Se aprendeu que tipo é uma lista de meia dúzia de nomes, aprendeu errado. Um tipo é o que define como um dado deve ser ou se comportar. A linguagem tem alguns próprios, a biblioteca da linguagem tem outros, bibliotecas de terceiros também tem, e sua aplicação criará vários outros.
Em PHP também é assim, embora de forma um pouco mais limitada. Em PHP 7 e 8 nem é tão limitado assim (apesar de ser uma gambiarra da linguagem), então não é algo de Java, é de programação em geral (mais).
Não temos como saber o que é o tipo Connection porque podem ter vários tipos com esse nome em contextos diferentes. A biblioteca padrão tem uma interface com esse nome, que não deixa de ser um tipo. Olhando a documentação, que deve fazer sempre, pode ver mais sobre isso.
Mas pode não entender o que é interface, como funciona a Connection. Mas aí é porque pulou etapas demais. Tem que começar com coisas mais simples. Não dá para escrever um livro de programação inteiro aqui para falar de tudo o que está faltando saber.
Se pegar exemplos ruins vai aprender errado. Esse parece um que faz errado (muito comum), mas não tenho informação suficiente para afirmar. Hoje na internet é um lugar ruim para se aprender, porque um faz errado, se torna popular, e todo mundo copia o errado fazendo parecer que está certo. Isso tem destruído a capacidade das pessoas aprenderem certo. Quem está começando não é capaz de separar conteúdo bom de ruim. Um emite uma opinião, você gosta e acha que aquilo é verdade.
O static também tem em PHP, o fato de não ter visto é só que não aprendeu PHP bem o suficiente. E começa ter perguntas demais na mesma postagem. Eu respondi muito sobre isso, outras pessoas também (mas nem todos organizam para ser fácil de achar). Pesquise no site que quase tudo o que quiser já foi perguntado antes. Ainda não é a melhor forma de aprender, mas ajuda. Ainda deve procurar um livro de qualidade, moderno.
Pode pesquisar sobre as perguntas mais populares. Pode ir só nas de Java, mas perderá muitos conceitos importantes como exemplo: Em programação, o que é um objeto?, O que é estilo de tipagem? e Qual a diferença entre uma linguagem de programação estática e dinâmica?.
Por fim: Como uma máquina identifica o tipo de dado?. Mas tem outros sobre tipagem. Só reforço para aprender primeiros os conceitos, os fundamentos, os mecanismos mais básicos, só para depois ir para coisas mais sofisticadas. Você não aprende equação do segundo grau quando não sabe aritmética. O problema é a metodologia de aprendizado.


How to get Sphericity in R for a nested within subject design?

Question: Thank you for reading. I am trying to get sphericity values for a purely within subject design. I have been unable to use ezANOVA, or Anova(). Anova works if I add a between subject factor, but I have been unable to get sphericity for a purely within subject design. Any advice?
I already read the R newsletter, fox chapter appendix, EZanova, and whatever I could find online.
My original ANOVA
anova(aov(resp ~ sucrose*citral, random =~1 | subject, data = p12bl, subset = exps==1))
anova(aov(resp ~ sucrose*citral, random =~1 | subject/sucrose*citral, data = p12bl, subset = exps==1))

> str(subset(p12bl, exps==1))
'data.frame':   192 obs. of  12 variables:
 $ exps     : int  1 1 1 1 1 1 1 1 1 1 ...
 $ Order    : int  1 1 1 1 1 1 1 1 1 1 ...
 $ threshold: Factor w/ 2 levels " Suprathreshold",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ SET      : Factor w/ 2 levels " A"," B": 1 1 1 1 1 1 1 1 1 1 ...
 $ subject  : Factor w/ 16 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ stim     : chr  "S1C1" "S1C1" "S1C1" "S1C1" ...
 $ resp     : num  6.01 5.63 0 2.57 6.81 ...
 $ id       : int  1 2 3 4 5 6 7 8 9 10 ...
 $ X1       : Factor w/ 1 level "S": 1 1 1 1 1 1 1 1 1 1 ...
 $ sucrose  : Factor w/ 4 levels "1","2","3","4": 1 1 1 1 1 1 1 1 1 1 ...
 $ X3       : Factor w/ 1 level "C": 1 1 1 1 1 1 1 1 1 1 ...
 $ citral   : Factor w/ 4 levels "1","2","3","4": 1 1 1 1 1 1 1 1 1 1 ...

subset(p12b,exps==1)
   exps Order       threshold SET observ S1C1 S1C2 S1C3 S1C4 S2C1 S2C2 S2C3 S2C4 S3C1 S3C2 S3C3 S3C4 S4C1 S4C2 S4C3 S4C4
1     1     1  Suprathreshold   A      1  6.0  7.1  7.5  8.6 15.0 15.4 15.0 13.1 16.9   13 13.1 16.5   24   16   21   20
2     1     1  Suprathreshold   A      2  5.6  0.8  4.0  5.6  5.6 11.3 12.9 14.5 18.5   15 12.9 14.5   24   26   29   28
3     1     1  Suprathreshold   A      3  0.0  0.0  1.7  0.0  5.0  8.4  8.4  5.0 11.7   20 18.5 16.8   29   37   37   30
4     1     1  Suprathreshold   A      4  2.6  3.3  9.1 16.3  5.4 10.0  9.6 16.8 13.5   12 22.2 23.1   19   20   22   23
5     1     1  Suprathreshold   A      5  6.8  5.3 15.4 14.5 11.5  8.3 14.5 14.2  8.9   17 11.2 15.1   24   23   19   19
6     1     1  Suprathreshold   A      6  2.6  2.8  2.6  5.2 13.4 15.6 13.7 13.0 13.7   15 16.0 18.9   22   24   25   25
7     1     1  Suprathreshold   A      7  1.3  5.8 10.2  9.8 11.9 12.3 17.7 16.7 11.4   19 19.2 21.1   16   19   18   19
8     1     1  Suprathreshold   A      8  2.0  5.6  3.9  2.0  4.9  5.2  7.5  4.9 20.2   21  8.2  9.5   30   26   32   45
9     1     1  Suprathreshold   A      9  9.4 11.3 11.7 12.1 14.7 13.8 12.6 14.9 15.2   15 15.9 13.9   17   18   15   18
10    1     1  Suprathreshold   A     10  4.5 17.8 18.5 21.6  5.8 10.9 17.0 20.2  6.6   10 17.8 18.7   12   12   16   19
11    1     1  Suprathreshold   A     11  9.8 13.0 16.1 18.0 10.5 11.6 15.4 17.3 10.1   14 15.2 16.7   13   15   15   17
12    1     1  Suprathreshold   A     12  9.6 10.4 13.3 11.3 12.1 12.6 13.6 13.6 14.9   16 15.1 16.3   16   18   18   17

Sample output
ezANOVA( data = subset(p12bl, exps==1)  , dv= .(resp), sid = .(observ), within = .(sucrose,citral), between = NULL, collapse_within = FALSE)
Note: model has only an intercept; equivalent type-III tests substituted.
$ANOVA
          Effect DFn DFd  SSn  SSd     F       p p<.05   pes
1        sucrose   3  33 4953 3263 16.70 9.0e-07     * 0.603
2         citral   3  33  410  553  8.16 3.3e-04     * 0.426
3 sucrose:citral   9  99   56  791  0.77 6.4e-01       0.066

Warning messages:
1: You have removed one or more Ss from the analysis. Refactoring "observ" for ANOVA.
2: Too few Ss for Anova(), reverting to aov(). See "Warning" section of the help on ezANOVA.
Comment: Do you want to look at sphericity or a factor to correct F-values because of violations in sphericity?
Comment: @John I need to see if I need the correction
Answer: Try:
library(ez)
ezANOVA(data=subset(p12bl, exps==1),
  within=.(sucrose, citral),
  wid=.(subject),
  dv=.(resp)
  )

and the equivalent aov command, minus sphericity etc, is:
aov(resp ~ sucrose*citral + Error(subject/(sucrose*citral)),
    data= subset(p12bl, exps==1))

Here's the equivalent using Anova from car directly:
library(car)
df1<-read.table("clipboard", header=T) #From copying data in the question above
sucrose<-factor(rep(c(1:4), each=4))
citral<-factor(rep(c(1:4), 4))
idata<-data.frame(sucrose,citral)

mod<-lm(cbind(S1C1, S1C2, S1C3, S1C4, S2C1, S2C2, S2C3, S2C4,
        S3C1, S3C2, S3C3, S3C4, S4C1, S4C2, S4C3, S4C4)~1, data=df1)
av.mod<-Anova(mod, idata=idata, idesign=~sucrose*citral)
summary(av.mod)

Comment: Do you get any error messages when using ezANOVA? Whenever I use it, I get a nice table of sphericity tests and GG/HF corrections.
It does not work for ANCOVA models, for this you will need to use the lme4 package, and there are other things to account for variance.
Comment: Thank you for taking the time to answer my question. however, your response doesn't answer my question. I already mentioned in my post that I already came across the ezANOVA function. I tried it without success. I am also already familiar with the aov notation you metnion.
Comment: It would probably help if you put the output of "str(p12bl)" or "str(subset(p12bl, exp2==1))" here.
Comment: @Matt thank you for the very helpful edit. I was trying other things after the ~ except 1 - as in your answer. Thanks again!
Comment: Ah, it seems that there's a bug in the current version of ez (v1.6.1). I've tracked it down to the fact that in converting to the formats that Anova() likes, ez was failing to turn something into a factor. I'm not sure whether this was always a bug, or whether Anova() recently changed in a way that broke ez. Regardless, I'm preparing ez v2.0, and this is one of the bug fixes. Stay tuned...
Comment: Thanks Mike, it seems to have happened fairly recently. I just finished an analysis last month using your package and haven't noticed any problems until this question came up.
Comment: @ Matt, I still get the same EZanova warning msg. for Anova I get another error msg:
Note: model has only an intercept; equivalent type-III tests substituted.
Error in linearHypothesis.mlm(mod, hyp.matrix, SSPE = SSPE, idata = idata, : The error SSP matrix is apparently of deficient rank = 0 < 1
Comment: This may help with the type-III thing https://stat.ethz.ch/pipermail/r-help/2007-October/144240.html ; and I've edited my answer to reflect the updated version of ez, which has changed "sid" to "wid". I don't get your problem with the data you've given me.
Comment: #Try this with the code I've written for the car Anova
#transfer data back to long to perform ezANOVA
df2<-melt(df1, id.vars="observ", measure.vars=names(df1)[6:21])
df2$suc<-substr(df2$variable,1,2)
df2$cit<-substr(df2$variable,3,4)
df2$observ<-factor(df2$observ)
ez1<-ezANOVA(data=df2,
  within=.(suc, cit),
  wid=.(observ),
  dv=.(value)
  )
Comment: updated ez, but still doesn't work 2: Anova() failed for some reason (maybe there are too few Ss?). should having too few Ss matter?
Comment: What's the error message?
Answer: Did you try the car package, from John Fox? It includes the function Anova() which is very useful when working with experimental designs. It should give you corrected p-value following Greenhouse-Geisser correction and Huynh-Feldt correction. I can post a quick R example if you wonder how to use it.
Also, there is a nice tutorial on the use of R with repeated measurements and mixed-effects model for psychology experiments and questionnaires; see Section 6.10 about sphericity.
As a sidenote, the Mauchly's Test of Sphericity is available in mauchly.test(), but it doesn't work with aov object if I remembered correctly. The R Newsletter from October 2007 includes a brief description of this topic.
Comment: I was just about to recommend this.  The ez package relies on car for some analysis.
Comment: @Adam In the on-line help for Anova(), you will find a working example with within- and between-subjects factors; the main caveats of Anova() is that you need to pass idata/idesign parameters in addition to your lm object. Also see this thread on the r-help mailing list, http://j.mp/9lphud.
Comment: Here is the correct link, http://j.mp/c6nDvn.
Comment: Thank you, the R newsletter is where I picked the mlm direction from. alas, I am still figuring how to choose idata idesign for a nested within subject design. I will try to figure out Anova().
Comment: @ John Anova() is supposed to take my aov() object as a model, but for some reason I am having problems making it work.
Comment: @Adam Did you mean the example included in the help file for Anova? In this case, I grabbed the R transcript and put it there, http://j.mp/9pGtKY. HTH
Comment: @chl thank you! for some reason I couldn't find an on-line help for car Anova(). but this example is already in the R off-line help at ?Anova. I am starting to understand this method.
Comment: @Adam Ah ok, my answer was thus a little bit out... What I call on-line is indeed the help() or ? call under R. For external references, you can try http://www.rseek.org/ or http://search.r-project.org/ (much better than directly goggling about R). Also I just this post with a nice illustration: http://j.mp/dnJgW0.
Answer: I generally recommend avoiding these types of sphericity tests altogether by using modern mixed modeling methods.  If you are not working with few subjects this will give you a great deal of flexibility in modeling an appropriate covariance structure, freeing you from the strict assumption of sphericity when necessary.  I infer from the str output that you have 16 subjects with 12 observations each (I assume balance b/c you areusing clasical method-of-moments tools) which should be enough data to fit a mixed model with structured covariance matrices via (restricted) maximum likelihood.
Without being close to your data I can't offer specific model recommendations, but a place to start in R would be to replace aov in your model specifications with lme (after library(nlme)). The reason this will work is that you have mistakenly provided an nlme-style random argument to aov (when, as @Matt Albrecht pointed out, an Error term would have been approriate).  In nlme, with the random argument set to ~ 1|<your grouping structure>
and no correlation or weight arguments, you are specifying a random intercept for each group, implying the response covariance within groups is ZGZ' + R = 1G1'+ \sigma^2 I ==> compound symmetry with between-group variance off-diagonal and between-group variance + within-group variance on the diagonal ==> a spherical structure.  From there you can begin to explore (e.g. using the built-in graphical methods), model, and test (e.g. comparing information criteria or using LRTs for nested models) the various forms of non-sphericity. Some of the tools for the modeling component are:

Using the weights argument to model non-constant variance (diagonals) within or between groups (e.g. error variance changes between sucrose levels).
Using the correlation argument to model non-constant covariance (off-diagonals) within groups (e.g. a structure within a group where residual errors that are closer together in time (e.g. AR1 structure) or space (e.g. Spherical structure) are more similar).
Modeling random slopes by adding terms to the LHS of the | in the random formula.

Though the process can be complex with many potential pitfalls, I believe it will lead you to think more about the data generating mechanism, and when combined with careful graphical checks (I recommed lattice b/c nlme has excellent lattice-based plotting methods -- but ggplot works well too) you are likely to have not only a better scientific understanding of the process, but also less biased and more efficient estimators with which to draw inferences.
Answer: ez has now been updated to version 2.0. Among other improvements, the bug that caused it to fail to work for this example has been fixed.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackexchange.com/rooms/51126/discussion-on-answer-by-mike-lawrence-how-to-get-sphericity-in-r-for-a-nested-wi).


Unique solutions to non-homogeneous equations

Question: I have two problems that I've been working on, and I want to make sure that my work is correct. I'm simply finding unique solutions to non-homogeneous equations, as shown below.
(1) an - 2an - 1 = 5      with a0 = 1
(2) an - 2an - 1 = 2n with a0 = 1
My work:
(1) For our general solution, we use an - 2an - 1 = 0.
This gives us r - 2 = 0, where r = 2, and so our root is 2. Our general function is h(n) = k(2)n where k is a constant.
Try p(n) = c. So we need p(n) - 2p(n-1) = 5.
c - 2c = 5
-c = 5
c = -5
So our general solution an = h(n) + p(n) is:
an = k(2)n + (-5). Our initial condition is a0 = 1.
1 = k(2)0 + (-5)
1 = k + (-5).  So our k = 6.
Our unique solution is an = 6(2)n + (-5).
(2) The general solution is is the same as above, with root 2 and h(n) = k(2)n.
But for p(n), trying c2n gives us 0 = 2n, and so we add n.
p(n) = cn2n
cn2n - c(n-1)2n = 2n
c = 1
So we now have h(n) + p(n) = k(2)n + 1.
1 = a0 = k(2)0 + 1
1 = k + 1. So our k = 0.
Our unique solution should be:
an = 0(2)n + 1.
Answer: You could make life simpler for the first case.
Consider $$a_n-2a_{n-1}=b\qquad \text{with}\qquad a_1=c$$ and rewrite the recurrence as $$(a_n-b)-2(a_{n-1}-b)=0$$ So, define $d_n=a_n-b$ to get
$$d_n-2d_{n-1}=0\qquad \text{with}\qquad d_1=c+b$$ and you know how to solve it.


Where should this android database code live?

Question: I'm working on an android application, and I'm having an issue figuring out where some code should live.
The application is based on some of the Commonsware stuff, along with the Notepad tutorial.  It has projects, and each project can be opened, have properties edited, or "ran".
Right now, there's a dbadapter class that has the basic CRUD operations for a "project".  It doesn't seem to make sense to put the open, edit, or run methods in there, because those methods involve starting activities, and I can't do that from inside the dbadapter.
I currently have the code inside the detail view for the project.  I want to be able to call those same methods from context menus in other activites than the detail view.
Where should the code live?  Should I have a Project class?  How would that interface with the dbadapter and cursors?  Should I make some sort of invisible Fragment--probably not, but I'm grasping at straws a little bit?
Answer: You should seperate your database code from the activities.. Having CRUD operations in DB adapter is a good practice. You can also write a provider on top of that database which can use those CRUD operations at the top level to maintain the community between your activities and the database.


Ativar e desativar função em jquery

Question: Preciso desativar uma função em jquery, por exemplo, quando eu clicar em uma div, uma função que eu defini não vai mais ser executada, apenas quando eu clicar em outra div ela volta a funcionar. A função é carregada quando o site for carregado.
Preciso que quando eu clique em uma div essa função não funcione mais, apenas quando clicar em outra div ela volte.

function executar_whell() {
    function debounce(fn, delay) {
        var timer = null;
        return function () {
            var context = this, args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function () {
                fn.apply(context, args);
            }, delay);
        };
    }
    var scrollervateira = debounce(function (event) {
        if (event.originalEvent.wheelDelta >= 0) {
            $('.flexhome').flexslider('prev');
            console.log('passa_slide');
            return false;
        } else {
            $('.flexhome').flexslider('next');
            console.log('volta_slide');
            return false;
        }
    }, 250);
    $(window).bind('mousewheel', scrollervateira);
}
;

A função executar_whell não vai poder funcionar quando eu clicar em uma div ( div onclick=outrafuncao) e quando eu clicar em outra div ( div onclick-funcionar) ela voltara a funcionar.
Comment: Se colocares mais código é possivel ajudar mais, mas para essa funcionalidade que referes podes usar uma flag, ou retirar o event handler e colocar novamente com `.on()` e `.off()`, ou bund/unbind. Um à parte: essa defenião de função ` function debounce(fn, delay) {` não precisa estar dentro de `executar_whell`. Fica meio confuso estar aí.
Answer: você pode usar o addEventListener para ativar o evento e o removeEventListener para remover o evento.
segue um exemplo com o evento mousemove.

var x = document.getElementById("x");
var y = document.getElementById("y");
var track = document.getElementById("track");

var onMouseMove = function (event) {
  x.value = event.x;
  y.value = event.y;
}

track.addEventListener("click", function (event) {
  var ativo = track.dataset.ativo == "true";
  if (ativo) {
    track.dataset.ativo = false;
    track.value = "Ativar";
    window.removeEventListener("mousemove", onMouseMove);
  } else {
    track.dataset.ativo = true;
    track.value = "Desativar";
    window.addEventListener("mousemove", onMouseMove);
  }
});

window.addEventListener("mousemove", onMouseMove);

    X:
    <input id="x" type="text" />

    Y:
    <input id="y" type="text" />

  Track Mouse:
  <input id="track" type="button" value="Desativar" data-ativo="true" />

Comment: Isso mesmo, vou somente trocar, obrigado!
Answer: Como complemento a resposta do TobyMosque, deixo uma opção com um efeito bem semelhante, porém feito em JQuery.
Para adicionar um evento em jquery você pode usar o .bind(), já para remover esse evento pode usar o .unbind(). Veja no JsFiddle abaixo:
JsFiddle
Um código bem simples como exemplo:
$('input:text').bind('keyup', function(){
  $('span').text(this.value);
})
$('input:button').click(funtion(){
  $('input:text').unbind('keyup');
})

Com o unbind() também é possível especificar a função em questão a se remover, juntamente com o evento. Por exemplo: unbind('keyup', escrever), assim a função escrever() não será mais executada no evento keyup.
Não usei o Stack Snippet pois estou no mobile.

Ativar e desativar função em jquery


Setting navigation item title issue.. why my navigation item seems many?

Question: I want to change the title of navigation bar but it seems somewhat confusing..
I did self.navigationItem.title = "ipsum" or self.navigationController?.navigationBar.topItem?.title = "ipsum" and so on.. but it fails..
It only succeeds changing the title when trying self.title = "ipsum" but it is not what I want because it causes tabBarItem's title to change too.
I tried debugging and found out strange result.

as you see the picture above.. there seems to be more than two navigationBar so when self.navigationItem.title = "ipsum" it actually changes some other or invisible navigationItem's title so that I can see from the log.
But the UI stays "lorem". Tell me if you figure something out! What am I missing?
EDIT 1:
Main.storyboard

Menu.storyboard

I put NavigationController in TabBarController and refactored NavigationController to another storyboard reference.
self.navigationItem.title = "ipsum" is called in the viewDidLoad() function.
Answer: Now View controllers are:
ViewController1 attached to item1:
override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title="View1"

    }

ViewController2 attached to item2:
override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title="View2"

    }

Result:
Answer: I used self.navigationItem.title="????".  It worked for me:)
Comment: I edited putting storyboard configuration.. if you want to check more .. tell me :)
Comment: Yeah.. usually it ends only with that.. but it doesn't work for me .. ;(
Answer: You should always use just
navigationItem.title = ""

because each controller has it's own navigationItem and if you trying to set title like this - self.navigationController?.navigationItem.title you possible set it to wrong place.


Flask & Tweepy - I can't handle the errors

Question: I want to print when there is a problem with Tweepy. When I look at Tweepy's docs, it seems possible with the try except. But after try except, user variable does not come. I get this error in user_profile_image: UnboundLocalError: local variable 'user' referenced before assignment.
How can I solve this problem? Thank you
@app.route("/twitter", methods=['GET', 'POST'])
def twitter():
    if request.method == 'POST':
        username = request.form.get('text')
        auth = tweepy.OAuthHandler("myoauthhandlers")
        auth.set_access_token("myaccesstokens")
        api = tweepy.API(auth)
        try:
            user = api.get_user(username)
        except tweepy.TweepError as e:
             print("Error")

        user_profile_image = user.profile_image_url.replace('normal', '400x400')

Comment: First of all you should define a default value for user before exception handling. But you need to find out why the exception is raised.
Answer: You need to define user with a statement like user = None before the try/except block. Here, it gets defined in the scope of the try/except block, and so isn't accessible from outside of it, hence the exception.
Comment: It says `AttributeError: 'NoneType' object has no attribute 'profile_image_url'`
Comment: @zicxor Then you caught a ```tweepy.TweepError``` exception, and your ```user``` variable didn't get initialized in the block because of this. Instead of just printing the error, you should also quit the current function, or run different code than the ```profile_image_url``` line