qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
331,337
I am in confidence with Taylor expansion of function $f\colon R \to R$, but I when my professor started to use higher order derivatives and multivariate Taylor expansion of $f\colon R^n \to R$ and $f\colon R^n \to R^m$ I felt lost. *Can somean explain to me from scratch multivariate Taylor?* In particular I don't understand the notation $$ f(x+h) = \sum\_{k=0}^p \frac{1}{k!} f^{(k)}(x)[h,...,h] + O(h^{p+1}) $$ Why we need the k-linear form $ \frac{1}{k!} f^{(k)}(x)[h,...,h]$? This k-linear form is the derivative or the derivative is only $f^{(k)}(x)$? I'm quite lost. Thank you.
2013/03/15
[ "https://math.stackexchange.com/questions/331337", "https://math.stackexchange.com", "https://math.stackexchange.com/users/66897/" ]
For 2 variables I believe the following expression to be correct. If it is incorrect then I should like to know! $$f(x,y) = \sum\_{m=0}^{\infty} \sum\_{n=0}^{\infty} \beta\_{m,n} (x-x\_0)^m (y-y\_0)^n$$ $$\beta\_{m,n} = \frac{1}{n! m!} \left[ \frac{\partial^{m+n}}{\partial x^m \partial y^n} \ f(x,y) \right]\_{(x=x\_0,y=y\_0)}$$ Where the square bracket notation with coordinate subscript means evaluate at. I previously derived the following formula, however I now suspect that it is not correct. Perhaps someone better than myself at proof by induction could verify this? $$f(x,y) = \sum\_{k=0}^{\infty} \frac{1}{k!} \sum\_{j=0}^{k} \alpha\_{k,j} (x-x\_0)^{j} (y-y\_0)^{k-j}$$ $$\alpha\_{k,j} = \,^{k}C\_{j} \left[ \frac{\partial^{k}}{\partial x^j \partial y^{k-j}} \ f(x,y) \right]\_{(x=x\_0,y=y\_0)}$$ In order to prove the first form, I did the following: $$\left[ f(x,y) \right]\_{(x0,y0)} = \sum\_{m=0}^{\infty} \sum\_{n=0}^{\infty} \beta\_{m,n} \cdot 0^m \cdot 0^n = \beta\_{0,0}$$ Differentiating partially with respect to x we find $$\left[ \frac{\partial f(x,y)}{\partial x} \right]\_{(x0,y0)} = \sum\_{m=0}^{\infty} \sum\_{n=0}^{\infty} \left( \beta\_{m,n} \cdot m \cdot 0^{m-1} \cdot 0^n + \left(\frac{\partial \beta\_{m,n}}{\partial x} \right) \cdot0^m\cdot0^n\right) = \beta\_{1,0} $$ where $\tfrac{\partial \beta\_{m,n}}{\partial x} = 0$. Continuing this process for all combinations of partial derivatives with respect to both x and y, we find that in general $$\beta\_{m,n}=\frac{1}{m!n!}\cdot \left[ \frac{\partial f(x,y)}{\partial x} \right]\_{(x=x0,y=y0)}$$ Unless I have made a mistake that is. (In which case please add a comment so I can correct my answer.)
You need to understand gradient vector to understand this article, although it is quite useful and can direct you to formulate the taylor series formula more concisely: <http://www.math.ucdenver.edu/~esulliva/Calculus3/Taylor.pdf>.
331,337
I am in confidence with Taylor expansion of function $f\colon R \to R$, but I when my professor started to use higher order derivatives and multivariate Taylor expansion of $f\colon R^n \to R$ and $f\colon R^n \to R^m$ I felt lost. *Can somean explain to me from scratch multivariate Taylor?* In particular I don't understand the notation $$ f(x+h) = \sum\_{k=0}^p \frac{1}{k!} f^{(k)}(x)[h,...,h] + O(h^{p+1}) $$ Why we need the k-linear form $ \frac{1}{k!} f^{(k)}(x)[h,...,h]$? This k-linear form is the derivative or the derivative is only $f^{(k)}(x)$? I'm quite lost. Thank you.
2013/03/15
[ "https://math.stackexchange.com/questions/331337", "https://math.stackexchange.com", "https://math.stackexchange.com/users/66897/" ]
One can think about Taylor's theorem in calculus as applying in the following cases: 1. Scalar-valued functions of a scalar variable, i.e. $f : \mathbb{R} \rightarrow \mathbb{R}$ 2. Vector-valued functions of a scalar variable, i.e. $f : \mathbb{R} \rightarrow \mathbb{R}^n$ 3. Scalar-valued functions of a vector variable, i.e. $f : \mathbb{R}^n \rightarrow \mathbb{R}$ 4. Vector-valued functions of a vector variable, i.e. $f : \mathbb{R}^n \rightarrow \mathbb{R}^m$ All of these can be derived & proven based on nothing more than [integration by parts](http://books.google.ie/books?id=XUjod_RjjX8C&dq=Lang+Calculus+taylor%27s+theorem&q=Taylor%27s+theorem#v=snippet&q=Taylor%27s%20theorem&f=false) (the last one needs to be developed in a banach space & the third one is more commonly reduced to the first one which is just a shorthand for re-proving it via integration by parts) if you set things up correctly (as is done in Lang's Undergraduate, Real & Functional Analysis books) & so your main obstacle here is formalism - this is no small obstacle as we'll see below. Now I'm not sure if your expression for Taylor's formula is map 3 or map 4, one would think it is map 3 since you used the word "linear form" which is standard parlance for maps from vector spaces into a field but you did ask about maps of the form $f : \mathbb{R}^n \rightarrow \mathbb{R}^m$ - are you sure you are differentiating these kinds of maps because they add a whole world of complexity compared to the first 3? If you're asking about maps of the form in 3 then some intuition is given in [this](http://www.youtube.com/watch?v=Z7yTsoMTjnM) video & some examples & a proof are given in [this](http://www.youtube.com/watch?v=D8AjFhLhFvA) video. After these you should have enough of a grasp of what's going on & if you focus on developing the formalism properly you should be able to prove it yourself in more general spaces. If you're actually asking about map 4 then you may be used to the definition of the derivative of the last map as $f : \mathbb{R}^n \rightarrow \mathbb{R}^m$ as something like $\mathcal{f'} : \mathbb{R}^n \rightarrow \mathcal{L}(\mathbb{R}^n,\mathbb{R}^m)$ satisfying [all the conditions](http://en.wikipedia.org/wiki/Frechet_derivative#Definition) a differentiable map does, well it's second derivative is defined similarly using a map of the form $f'': \mathbb{R}^n \rightarrow \mathcal{L}(\mathbb{R}^n,\mathcal{L}(\mathbb{R}^n,\mathbb{R}^m))$ & so on, however you see no such entity as a "k-linear form" in any of this & that's because [there is a theorem](http://books.google.ie/books?id=VfxGB5nYv1MC&pg=PA5&dq=banach+isomorphism+multilinear&hl=en&sa=X&ei=Z2BDUY7dOZON7AbRg4GICA&ved=0CDAQuwUwAA#v=onepage&q=banach%20isomorphism%20multilinear&f=false) which allows one to think of maps like the second derivative above in terms of multilinear maps & so one can re-cast the theory using multilinear maps which eases the development & allows for nice proofs etc... but without this being explained it might appear odd to randomly start pulling out multilinear maps. In any case the derivative is a linear map by definition & so that is why you're coming across the word linear, but since you didn't put subscripts on the $[h,...,h]$ I'm not sure how deep I can go, because I see two possibilities here so if the above isn't enough of an explanation as it stands just let me know.
For 2 variables I believe the following expression to be correct. If it is incorrect then I should like to know! $$f(x,y) = \sum\_{m=0}^{\infty} \sum\_{n=0}^{\infty} \beta\_{m,n} (x-x\_0)^m (y-y\_0)^n$$ $$\beta\_{m,n} = \frac{1}{n! m!} \left[ \frac{\partial^{m+n}}{\partial x^m \partial y^n} \ f(x,y) \right]\_{(x=x\_0,y=y\_0)}$$ Where the square bracket notation with coordinate subscript means evaluate at. I previously derived the following formula, however I now suspect that it is not correct. Perhaps someone better than myself at proof by induction could verify this? $$f(x,y) = \sum\_{k=0}^{\infty} \frac{1}{k!} \sum\_{j=0}^{k} \alpha\_{k,j} (x-x\_0)^{j} (y-y\_0)^{k-j}$$ $$\alpha\_{k,j} = \,^{k}C\_{j} \left[ \frac{\partial^{k}}{\partial x^j \partial y^{k-j}} \ f(x,y) \right]\_{(x=x\_0,y=y\_0)}$$ In order to prove the first form, I did the following: $$\left[ f(x,y) \right]\_{(x0,y0)} = \sum\_{m=0}^{\infty} \sum\_{n=0}^{\infty} \beta\_{m,n} \cdot 0^m \cdot 0^n = \beta\_{0,0}$$ Differentiating partially with respect to x we find $$\left[ \frac{\partial f(x,y)}{\partial x} \right]\_{(x0,y0)} = \sum\_{m=0}^{\infty} \sum\_{n=0}^{\infty} \left( \beta\_{m,n} \cdot m \cdot 0^{m-1} \cdot 0^n + \left(\frac{\partial \beta\_{m,n}}{\partial x} \right) \cdot0^m\cdot0^n\right) = \beta\_{1,0} $$ where $\tfrac{\partial \beta\_{m,n}}{\partial x} = 0$. Continuing this process for all combinations of partial derivatives with respect to both x and y, we find that in general $$\beta\_{m,n}=\frac{1}{m!n!}\cdot \left[ \frac{\partial f(x,y)}{\partial x} \right]\_{(x=x0,y=y0)}$$ Unless I have made a mistake that is. (In which case please add a comment so I can correct my answer.)
331,337
I am in confidence with Taylor expansion of function $f\colon R \to R$, but I when my professor started to use higher order derivatives and multivariate Taylor expansion of $f\colon R^n \to R$ and $f\colon R^n \to R^m$ I felt lost. *Can somean explain to me from scratch multivariate Taylor?* In particular I don't understand the notation $$ f(x+h) = \sum\_{k=0}^p \frac{1}{k!} f^{(k)}(x)[h,...,h] + O(h^{p+1}) $$ Why we need the k-linear form $ \frac{1}{k!} f^{(k)}(x)[h,...,h]$? This k-linear form is the derivative or the derivative is only $f^{(k)}(x)$? I'm quite lost. Thank you.
2013/03/15
[ "https://math.stackexchange.com/questions/331337", "https://math.stackexchange.com", "https://math.stackexchange.com/users/66897/" ]
For 3 variables: $$f(x,y,z)=f(x\_0,y\_0,z\_0)$$ $$+\frac{\partial f\_0}{\partial x}(x-x\_0)+\frac{\partial f\_0}{\partial y}(y-y\_0)+\frac{\partial f\_0}{\partial z}(z-z\_0)\quad \Rightarrow Order 1$$ $$+\frac{1}{2} \bigg(\frac{\partial^2 f\_0}{\partial x^2}(x-x\_0)^2+\frac{\partial^2 f\_0}{\partial y^2}(y-y\_0)^2+\frac{\partial^2 f\_0}{\partial z^2}(z-z\_0)^2+2\frac{\partial^2 f\_0}{\partial x\partial y}(x-x\_0)(y-y\_0) $$ $$+2\frac{\partial^2 f\_0}{\partial x\partial z}(x-x\_0)(z-z\_0)+2\frac{\partial^2 f\_0}{\partial z\partial y}(z-z\_0)(y-y\_0)\bigg)\quad \Rightarrow Order 2$$ And it goes like this to higher orders
You need to understand gradient vector to understand this article, although it is quite useful and can direct you to formulate the taylor series formula more concisely: <http://www.math.ucdenver.edu/~esulliva/Calculus3/Taylor.pdf>.
331,337
I am in confidence with Taylor expansion of function $f\colon R \to R$, but I when my professor started to use higher order derivatives and multivariate Taylor expansion of $f\colon R^n \to R$ and $f\colon R^n \to R^m$ I felt lost. *Can somean explain to me from scratch multivariate Taylor?* In particular I don't understand the notation $$ f(x+h) = \sum\_{k=0}^p \frac{1}{k!} f^{(k)}(x)[h,...,h] + O(h^{p+1}) $$ Why we need the k-linear form $ \frac{1}{k!} f^{(k)}(x)[h,...,h]$? This k-linear form is the derivative or the derivative is only $f^{(k)}(x)$? I'm quite lost. Thank you.
2013/03/15
[ "https://math.stackexchange.com/questions/331337", "https://math.stackexchange.com", "https://math.stackexchange.com/users/66897/" ]
For 3 variables: $$f(x,y,z)=f(x\_0,y\_0,z\_0)$$ $$+\frac{\partial f\_0}{\partial x}(x-x\_0)+\frac{\partial f\_0}{\partial y}(y-y\_0)+\frac{\partial f\_0}{\partial z}(z-z\_0)\quad \Rightarrow Order 1$$ $$+\frac{1}{2} \bigg(\frac{\partial^2 f\_0}{\partial x^2}(x-x\_0)^2+\frac{\partial^2 f\_0}{\partial y^2}(y-y\_0)^2+\frac{\partial^2 f\_0}{\partial z^2}(z-z\_0)^2+2\frac{\partial^2 f\_0}{\partial x\partial y}(x-x\_0)(y-y\_0) $$ $$+2\frac{\partial^2 f\_0}{\partial x\partial z}(x-x\_0)(z-z\_0)+2\frac{\partial^2 f\_0}{\partial z\partial y}(z-z\_0)(y-y\_0)\bigg)\quad \Rightarrow Order 2$$ And it goes like this to higher orders
Let's suppose the function we're to investigate is a C(k+1) function within its open domain which includes a as an internal point. The purpose is to somehow find "the best" (polynomial) approximation to the function, at points like x, inside an open sphere around our reference point a, about which we know the value of the function there as well as all the (mixed) partial derivatives up to the kth degree. Now the first (and interstingly the most intuition-based) step to take is to somehow map our orthonormal bases to another orthonormal bases (using orthogonal transformations), such that one base will lie along the vector x-a. Now, with this change of coordinates, it's as though we're changing only one variable to go from a to x. Therefore, the problem turns into that of single variable Taylor expansion of the kth order. The other cool part of the attempt to "construct" the multivariable polynomial with only that for the single-variable at hand is that one will be able to and therefore should find all (mixed) partial derivatives of f at a, "this time in the direction of the vector x-a": (it becomes interesting when one thinks about how what they already have (here: all the (mixed) partials) enables them to obtain what they need to have (here: directional first, second,..., kth derivative of f at a with respect to x-a, if I'm rigth). It may also be illuminating to think about the relationship of the kth derivative in the direction of x-a and that of all the mixed partials at a.) Once the job is completed in thar coordinate system, one, quite clearly, needs to describe all they have obtained until there, in the language of the former coordinate system, thereby having constructed the multivariable polynomial approximation.
331,337
I am in confidence with Taylor expansion of function $f\colon R \to R$, but I when my professor started to use higher order derivatives and multivariate Taylor expansion of $f\colon R^n \to R$ and $f\colon R^n \to R^m$ I felt lost. *Can somean explain to me from scratch multivariate Taylor?* In particular I don't understand the notation $$ f(x+h) = \sum\_{k=0}^p \frac{1}{k!} f^{(k)}(x)[h,...,h] + O(h^{p+1}) $$ Why we need the k-linear form $ \frac{1}{k!} f^{(k)}(x)[h,...,h]$? This k-linear form is the derivative or the derivative is only $f^{(k)}(x)$? I'm quite lost. Thank you.
2013/03/15
[ "https://math.stackexchange.com/questions/331337", "https://math.stackexchange.com", "https://math.stackexchange.com/users/66897/" ]
For 2 variables I believe the following expression to be correct. If it is incorrect then I should like to know! $$f(x,y) = \sum\_{m=0}^{\infty} \sum\_{n=0}^{\infty} \beta\_{m,n} (x-x\_0)^m (y-y\_0)^n$$ $$\beta\_{m,n} = \frac{1}{n! m!} \left[ \frac{\partial^{m+n}}{\partial x^m \partial y^n} \ f(x,y) \right]\_{(x=x\_0,y=y\_0)}$$ Where the square bracket notation with coordinate subscript means evaluate at. I previously derived the following formula, however I now suspect that it is not correct. Perhaps someone better than myself at proof by induction could verify this? $$f(x,y) = \sum\_{k=0}^{\infty} \frac{1}{k!} \sum\_{j=0}^{k} \alpha\_{k,j} (x-x\_0)^{j} (y-y\_0)^{k-j}$$ $$\alpha\_{k,j} = \,^{k}C\_{j} \left[ \frac{\partial^{k}}{\partial x^j \partial y^{k-j}} \ f(x,y) \right]\_{(x=x\_0,y=y\_0)}$$ In order to prove the first form, I did the following: $$\left[ f(x,y) \right]\_{(x0,y0)} = \sum\_{m=0}^{\infty} \sum\_{n=0}^{\infty} \beta\_{m,n} \cdot 0^m \cdot 0^n = \beta\_{0,0}$$ Differentiating partially with respect to x we find $$\left[ \frac{\partial f(x,y)}{\partial x} \right]\_{(x0,y0)} = \sum\_{m=0}^{\infty} \sum\_{n=0}^{\infty} \left( \beta\_{m,n} \cdot m \cdot 0^{m-1} \cdot 0^n + \left(\frac{\partial \beta\_{m,n}}{\partial x} \right) \cdot0^m\cdot0^n\right) = \beta\_{1,0} $$ where $\tfrac{\partial \beta\_{m,n}}{\partial x} = 0$. Continuing this process for all combinations of partial derivatives with respect to both x and y, we find that in general $$\beta\_{m,n}=\frac{1}{m!n!}\cdot \left[ \frac{\partial f(x,y)}{\partial x} \right]\_{(x=x0,y=y0)}$$ Unless I have made a mistake that is. (In which case please add a comment so I can correct my answer.)
Let's suppose the function we're to investigate is a C(k+1) function within its open domain which includes a as an internal point. The purpose is to somehow find "the best" (polynomial) approximation to the function, at points like x, inside an open sphere around our reference point a, about which we know the value of the function there as well as all the (mixed) partial derivatives up to the kth degree. Now the first (and interstingly the most intuition-based) step to take is to somehow map our orthonormal bases to another orthonormal bases (using orthogonal transformations), such that one base will lie along the vector x-a. Now, with this change of coordinates, it's as though we're changing only one variable to go from a to x. Therefore, the problem turns into that of single variable Taylor expansion of the kth order. The other cool part of the attempt to "construct" the multivariable polynomial with only that for the single-variable at hand is that one will be able to and therefore should find all (mixed) partial derivatives of f at a, "this time in the direction of the vector x-a": (it becomes interesting when one thinks about how what they already have (here: all the (mixed) partials) enables them to obtain what they need to have (here: directional first, second,..., kth derivative of f at a with respect to x-a, if I'm rigth). It may also be illuminating to think about the relationship of the kth derivative in the direction of x-a and that of all the mixed partials at a.) Once the job is completed in thar coordinate system, one, quite clearly, needs to describe all they have obtained until there, in the language of the former coordinate system, thereby having constructed the multivariable polynomial approximation.
331,337
I am in confidence with Taylor expansion of function $f\colon R \to R$, but I when my professor started to use higher order derivatives and multivariate Taylor expansion of $f\colon R^n \to R$ and $f\colon R^n \to R^m$ I felt lost. *Can somean explain to me from scratch multivariate Taylor?* In particular I don't understand the notation $$ f(x+h) = \sum\_{k=0}^p \frac{1}{k!} f^{(k)}(x)[h,...,h] + O(h^{p+1}) $$ Why we need the k-linear form $ \frac{1}{k!} f^{(k)}(x)[h,...,h]$? This k-linear form is the derivative or the derivative is only $f^{(k)}(x)$? I'm quite lost. Thank you.
2013/03/15
[ "https://math.stackexchange.com/questions/331337", "https://math.stackexchange.com", "https://math.stackexchange.com/users/66897/" ]
One can think about Taylor's theorem in calculus as applying in the following cases: 1. Scalar-valued functions of a scalar variable, i.e. $f : \mathbb{R} \rightarrow \mathbb{R}$ 2. Vector-valued functions of a scalar variable, i.e. $f : \mathbb{R} \rightarrow \mathbb{R}^n$ 3. Scalar-valued functions of a vector variable, i.e. $f : \mathbb{R}^n \rightarrow \mathbb{R}$ 4. Vector-valued functions of a vector variable, i.e. $f : \mathbb{R}^n \rightarrow \mathbb{R}^m$ All of these can be derived & proven based on nothing more than [integration by parts](http://books.google.ie/books?id=XUjod_RjjX8C&dq=Lang+Calculus+taylor%27s+theorem&q=Taylor%27s+theorem#v=snippet&q=Taylor%27s%20theorem&f=false) (the last one needs to be developed in a banach space & the third one is more commonly reduced to the first one which is just a shorthand for re-proving it via integration by parts) if you set things up correctly (as is done in Lang's Undergraduate, Real & Functional Analysis books) & so your main obstacle here is formalism - this is no small obstacle as we'll see below. Now I'm not sure if your expression for Taylor's formula is map 3 or map 4, one would think it is map 3 since you used the word "linear form" which is standard parlance for maps from vector spaces into a field but you did ask about maps of the form $f : \mathbb{R}^n \rightarrow \mathbb{R}^m$ - are you sure you are differentiating these kinds of maps because they add a whole world of complexity compared to the first 3? If you're asking about maps of the form in 3 then some intuition is given in [this](http://www.youtube.com/watch?v=Z7yTsoMTjnM) video & some examples & a proof are given in [this](http://www.youtube.com/watch?v=D8AjFhLhFvA) video. After these you should have enough of a grasp of what's going on & if you focus on developing the formalism properly you should be able to prove it yourself in more general spaces. If you're actually asking about map 4 then you may be used to the definition of the derivative of the last map as $f : \mathbb{R}^n \rightarrow \mathbb{R}^m$ as something like $\mathcal{f'} : \mathbb{R}^n \rightarrow \mathcal{L}(\mathbb{R}^n,\mathbb{R}^m)$ satisfying [all the conditions](http://en.wikipedia.org/wiki/Frechet_derivative#Definition) a differentiable map does, well it's second derivative is defined similarly using a map of the form $f'': \mathbb{R}^n \rightarrow \mathcal{L}(\mathbb{R}^n,\mathcal{L}(\mathbb{R}^n,\mathbb{R}^m))$ & so on, however you see no such entity as a "k-linear form" in any of this & that's because [there is a theorem](http://books.google.ie/books?id=VfxGB5nYv1MC&pg=PA5&dq=banach+isomorphism+multilinear&hl=en&sa=X&ei=Z2BDUY7dOZON7AbRg4GICA&ved=0CDAQuwUwAA#v=onepage&q=banach%20isomorphism%20multilinear&f=false) which allows one to think of maps like the second derivative above in terms of multilinear maps & so one can re-cast the theory using multilinear maps which eases the development & allows for nice proofs etc... but without this being explained it might appear odd to randomly start pulling out multilinear maps. In any case the derivative is a linear map by definition & so that is why you're coming across the word linear, but since you didn't put subscripts on the $[h,...,h]$ I'm not sure how deep I can go, because I see two possibilities here so if the above isn't enough of an explanation as it stands just let me know.
Let's suppose the function we're to investigate is a C(k+1) function within its open domain which includes a as an internal point. The purpose is to somehow find "the best" (polynomial) approximation to the function, at points like x, inside an open sphere around our reference point a, about which we know the value of the function there as well as all the (mixed) partial derivatives up to the kth degree. Now the first (and interstingly the most intuition-based) step to take is to somehow map our orthonormal bases to another orthonormal bases (using orthogonal transformations), such that one base will lie along the vector x-a. Now, with this change of coordinates, it's as though we're changing only one variable to go from a to x. Therefore, the problem turns into that of single variable Taylor expansion of the kth order. The other cool part of the attempt to "construct" the multivariable polynomial with only that for the single-variable at hand is that one will be able to and therefore should find all (mixed) partial derivatives of f at a, "this time in the direction of the vector x-a": (it becomes interesting when one thinks about how what they already have (here: all the (mixed) partials) enables them to obtain what they need to have (here: directional first, second,..., kth derivative of f at a with respect to x-a, if I'm rigth). It may also be illuminating to think about the relationship of the kth derivative in the direction of x-a and that of all the mixed partials at a.) Once the job is completed in thar coordinate system, one, quite clearly, needs to describe all they have obtained until there, in the language of the former coordinate system, thereby having constructed the multivariable polynomial approximation.
331,337
I am in confidence with Taylor expansion of function $f\colon R \to R$, but I when my professor started to use higher order derivatives and multivariate Taylor expansion of $f\colon R^n \to R$ and $f\colon R^n \to R^m$ I felt lost. *Can somean explain to me from scratch multivariate Taylor?* In particular I don't understand the notation $$ f(x+h) = \sum\_{k=0}^p \frac{1}{k!} f^{(k)}(x)[h,...,h] + O(h^{p+1}) $$ Why we need the k-linear form $ \frac{1}{k!} f^{(k)}(x)[h,...,h]$? This k-linear form is the derivative or the derivative is only $f^{(k)}(x)$? I'm quite lost. Thank you.
2013/03/15
[ "https://math.stackexchange.com/questions/331337", "https://math.stackexchange.com", "https://math.stackexchange.com/users/66897/" ]
One can think about Taylor's theorem in calculus as applying in the following cases: 1. Scalar-valued functions of a scalar variable, i.e. $f : \mathbb{R} \rightarrow \mathbb{R}$ 2. Vector-valued functions of a scalar variable, i.e. $f : \mathbb{R} \rightarrow \mathbb{R}^n$ 3. Scalar-valued functions of a vector variable, i.e. $f : \mathbb{R}^n \rightarrow \mathbb{R}$ 4. Vector-valued functions of a vector variable, i.e. $f : \mathbb{R}^n \rightarrow \mathbb{R}^m$ All of these can be derived & proven based on nothing more than [integration by parts](http://books.google.ie/books?id=XUjod_RjjX8C&dq=Lang+Calculus+taylor%27s+theorem&q=Taylor%27s+theorem#v=snippet&q=Taylor%27s%20theorem&f=false) (the last one needs to be developed in a banach space & the third one is more commonly reduced to the first one which is just a shorthand for re-proving it via integration by parts) if you set things up correctly (as is done in Lang's Undergraduate, Real & Functional Analysis books) & so your main obstacle here is formalism - this is no small obstacle as we'll see below. Now I'm not sure if your expression for Taylor's formula is map 3 or map 4, one would think it is map 3 since you used the word "linear form" which is standard parlance for maps from vector spaces into a field but you did ask about maps of the form $f : \mathbb{R}^n \rightarrow \mathbb{R}^m$ - are you sure you are differentiating these kinds of maps because they add a whole world of complexity compared to the first 3? If you're asking about maps of the form in 3 then some intuition is given in [this](http://www.youtube.com/watch?v=Z7yTsoMTjnM) video & some examples & a proof are given in [this](http://www.youtube.com/watch?v=D8AjFhLhFvA) video. After these you should have enough of a grasp of what's going on & if you focus on developing the formalism properly you should be able to prove it yourself in more general spaces. If you're actually asking about map 4 then you may be used to the definition of the derivative of the last map as $f : \mathbb{R}^n \rightarrow \mathbb{R}^m$ as something like $\mathcal{f'} : \mathbb{R}^n \rightarrow \mathcal{L}(\mathbb{R}^n,\mathbb{R}^m)$ satisfying [all the conditions](http://en.wikipedia.org/wiki/Frechet_derivative#Definition) a differentiable map does, well it's second derivative is defined similarly using a map of the form $f'': \mathbb{R}^n \rightarrow \mathcal{L}(\mathbb{R}^n,\mathcal{L}(\mathbb{R}^n,\mathbb{R}^m))$ & so on, however you see no such entity as a "k-linear form" in any of this & that's because [there is a theorem](http://books.google.ie/books?id=VfxGB5nYv1MC&pg=PA5&dq=banach+isomorphism+multilinear&hl=en&sa=X&ei=Z2BDUY7dOZON7AbRg4GICA&ved=0CDAQuwUwAA#v=onepage&q=banach%20isomorphism%20multilinear&f=false) which allows one to think of maps like the second derivative above in terms of multilinear maps & so one can re-cast the theory using multilinear maps which eases the development & allows for nice proofs etc... but without this being explained it might appear odd to randomly start pulling out multilinear maps. In any case the derivative is a linear map by definition & so that is why you're coming across the word linear, but since you didn't put subscripts on the $[h,...,h]$ I'm not sure how deep I can go, because I see two possibilities here so if the above isn't enough of an explanation as it stands just let me know.
It is enough to understand the case $f:\ {\mathbb R}^n\to {\mathbb R}$, and we expand $f$ at $x=0$. So we are interested in polynomials of low degree $d$ in the variables $x\_1$, $\ldots$, $x\_n$ that approximate $f$ in the neighborhood of $0\in{\mathbb R}^n$. The best polynomial of degree $\leq0$ for this purpose is obviously the constant function $$j^0:\quad x\mapsto j^0(x)= f(0)\ .$$ In fact we have $$f(x)=j^0(x)+ r(x),\quad \lim\_{x\to0} r(x)=0\ .$$ The best approximating polynomial of degree $\leq1$ is the function $$j^1:\ x\mapsto j^1(x)=f(0)+\nabla f(0)\cdot x\ ,$$ where $\nabla f(0):=\left({\partial f\over\partial x\_1},\ldots,{\partial f\over\partial x\_n}\right)\_0$. In fact we have $$f(x)=j^1(x)+ r(x),\quad \lim\_{x\to0} {|r(x)|\over |x|}=0\ .$$ Advancing to $d=2$ we have to be aware that the dimension of the space of homogeneous polynomials of degree $2$ is ${n(n+1)\over2}$, because we have to envisage all terms of the form $x\_k^2$ and also mixed terms $x\_ix\_j$ with $i\ne j$. It follows that $j^2(x)$ will have the already known terms of degree $0$ and $1$ and "quadratically in $n$ many" terms of degree $2$. The latter are best arranged in a matricial way, so that one has a sum $\sum\_{1\leq i\leq n,\ 1\leq j\leq n}a\_{ij} x\_ix\_j$. The coefficients $a\_{ij}$ will be related to the second partials of $f$ at $0$ in a particular way established in the proof of the general theorem. Going into the details one obtains $$j^2(x)=f(0)+\nabla f(0)\cdot x+{1\over2}\sum\_{1\leq i\leq n,\ 1\leq j\leq n}\left({\partial^2 f\over\partial x\_i\partial x\_j}\right)\_0 x\_ix\_j\ ,$$ and one can prove that $$f(x)=j^2(x)+ r(x),\quad \lim\_{x\to0} {|r(x)|\over |x|^2}=0\ .$$ The formula you displayed is a systematic and condensed way to write this all up. E.g., in degree $3$ we shall obtain a triple sum of $n^3$ monomials $x\_i x\_j x\_k$, each of them multiplied with the appropriate third partial derivative of $f$ at the origin.
331,337
I am in confidence with Taylor expansion of function $f\colon R \to R$, but I when my professor started to use higher order derivatives and multivariate Taylor expansion of $f\colon R^n \to R$ and $f\colon R^n \to R^m$ I felt lost. *Can somean explain to me from scratch multivariate Taylor?* In particular I don't understand the notation $$ f(x+h) = \sum\_{k=0}^p \frac{1}{k!} f^{(k)}(x)[h,...,h] + O(h^{p+1}) $$ Why we need the k-linear form $ \frac{1}{k!} f^{(k)}(x)[h,...,h]$? This k-linear form is the derivative or the derivative is only $f^{(k)}(x)$? I'm quite lost. Thank you.
2013/03/15
[ "https://math.stackexchange.com/questions/331337", "https://math.stackexchange.com", "https://math.stackexchange.com/users/66897/" ]
For 3 variables: $$f(x,y,z)=f(x\_0,y\_0,z\_0)$$ $$+\frac{\partial f\_0}{\partial x}(x-x\_0)+\frac{\partial f\_0}{\partial y}(y-y\_0)+\frac{\partial f\_0}{\partial z}(z-z\_0)\quad \Rightarrow Order 1$$ $$+\frac{1}{2} \bigg(\frac{\partial^2 f\_0}{\partial x^2}(x-x\_0)^2+\frac{\partial^2 f\_0}{\partial y^2}(y-y\_0)^2+\frac{\partial^2 f\_0}{\partial z^2}(z-z\_0)^2+2\frac{\partial^2 f\_0}{\partial x\partial y}(x-x\_0)(y-y\_0) $$ $$+2\frac{\partial^2 f\_0}{\partial x\partial z}(x-x\_0)(z-z\_0)+2\frac{\partial^2 f\_0}{\partial z\partial y}(z-z\_0)(y-y\_0)\bigg)\quad \Rightarrow Order 2$$ And it goes like this to higher orders
For 2 variables I believe the following expression to be correct. If it is incorrect then I should like to know! $$f(x,y) = \sum\_{m=0}^{\infty} \sum\_{n=0}^{\infty} \beta\_{m,n} (x-x\_0)^m (y-y\_0)^n$$ $$\beta\_{m,n} = \frac{1}{n! m!} \left[ \frac{\partial^{m+n}}{\partial x^m \partial y^n} \ f(x,y) \right]\_{(x=x\_0,y=y\_0)}$$ Where the square bracket notation with coordinate subscript means evaluate at. I previously derived the following formula, however I now suspect that it is not correct. Perhaps someone better than myself at proof by induction could verify this? $$f(x,y) = \sum\_{k=0}^{\infty} \frac{1}{k!} \sum\_{j=0}^{k} \alpha\_{k,j} (x-x\_0)^{j} (y-y\_0)^{k-j}$$ $$\alpha\_{k,j} = \,^{k}C\_{j} \left[ \frac{\partial^{k}}{\partial x^j \partial y^{k-j}} \ f(x,y) \right]\_{(x=x\_0,y=y\_0)}$$ In order to prove the first form, I did the following: $$\left[ f(x,y) \right]\_{(x0,y0)} = \sum\_{m=0}^{\infty} \sum\_{n=0}^{\infty} \beta\_{m,n} \cdot 0^m \cdot 0^n = \beta\_{0,0}$$ Differentiating partially with respect to x we find $$\left[ \frac{\partial f(x,y)}{\partial x} \right]\_{(x0,y0)} = \sum\_{m=0}^{\infty} \sum\_{n=0}^{\infty} \left( \beta\_{m,n} \cdot m \cdot 0^{m-1} \cdot 0^n + \left(\frac{\partial \beta\_{m,n}}{\partial x} \right) \cdot0^m\cdot0^n\right) = \beta\_{1,0} $$ where $\tfrac{\partial \beta\_{m,n}}{\partial x} = 0$. Continuing this process for all combinations of partial derivatives with respect to both x and y, we find that in general $$\beta\_{m,n}=\frac{1}{m!n!}\cdot \left[ \frac{\partial f(x,y)}{\partial x} \right]\_{(x=x0,y=y0)}$$ Unless I have made a mistake that is. (In which case please add a comment so I can correct my answer.)
331,337
I am in confidence with Taylor expansion of function $f\colon R \to R$, but I when my professor started to use higher order derivatives and multivariate Taylor expansion of $f\colon R^n \to R$ and $f\colon R^n \to R^m$ I felt lost. *Can somean explain to me from scratch multivariate Taylor?* In particular I don't understand the notation $$ f(x+h) = \sum\_{k=0}^p \frac{1}{k!} f^{(k)}(x)[h,...,h] + O(h^{p+1}) $$ Why we need the k-linear form $ \frac{1}{k!} f^{(k)}(x)[h,...,h]$? This k-linear form is the derivative or the derivative is only $f^{(k)}(x)$? I'm quite lost. Thank you.
2013/03/15
[ "https://math.stackexchange.com/questions/331337", "https://math.stackexchange.com", "https://math.stackexchange.com/users/66897/" ]
It is enough to understand the case $f:\ {\mathbb R}^n\to {\mathbb R}$, and we expand $f$ at $x=0$. So we are interested in polynomials of low degree $d$ in the variables $x\_1$, $\ldots$, $x\_n$ that approximate $f$ in the neighborhood of $0\in{\mathbb R}^n$. The best polynomial of degree $\leq0$ for this purpose is obviously the constant function $$j^0:\quad x\mapsto j^0(x)= f(0)\ .$$ In fact we have $$f(x)=j^0(x)+ r(x),\quad \lim\_{x\to0} r(x)=0\ .$$ The best approximating polynomial of degree $\leq1$ is the function $$j^1:\ x\mapsto j^1(x)=f(0)+\nabla f(0)\cdot x\ ,$$ where $\nabla f(0):=\left({\partial f\over\partial x\_1},\ldots,{\partial f\over\partial x\_n}\right)\_0$. In fact we have $$f(x)=j^1(x)+ r(x),\quad \lim\_{x\to0} {|r(x)|\over |x|}=0\ .$$ Advancing to $d=2$ we have to be aware that the dimension of the space of homogeneous polynomials of degree $2$ is ${n(n+1)\over2}$, because we have to envisage all terms of the form $x\_k^2$ and also mixed terms $x\_ix\_j$ with $i\ne j$. It follows that $j^2(x)$ will have the already known terms of degree $0$ and $1$ and "quadratically in $n$ many" terms of degree $2$. The latter are best arranged in a matricial way, so that one has a sum $\sum\_{1\leq i\leq n,\ 1\leq j\leq n}a\_{ij} x\_ix\_j$. The coefficients $a\_{ij}$ will be related to the second partials of $f$ at $0$ in a particular way established in the proof of the general theorem. Going into the details one obtains $$j^2(x)=f(0)+\nabla f(0)\cdot x+{1\over2}\sum\_{1\leq i\leq n,\ 1\leq j\leq n}\left({\partial^2 f\over\partial x\_i\partial x\_j}\right)\_0 x\_ix\_j\ ,$$ and one can prove that $$f(x)=j^2(x)+ r(x),\quad \lim\_{x\to0} {|r(x)|\over |x|^2}=0\ .$$ The formula you displayed is a systematic and condensed way to write this all up. E.g., in degree $3$ we shall obtain a triple sum of $n^3$ monomials $x\_i x\_j x\_k$, each of them multiplied with the appropriate third partial derivative of $f$ at the origin.
For 2 variables I believe the following expression to be correct. If it is incorrect then I should like to know! $$f(x,y) = \sum\_{m=0}^{\infty} \sum\_{n=0}^{\infty} \beta\_{m,n} (x-x\_0)^m (y-y\_0)^n$$ $$\beta\_{m,n} = \frac{1}{n! m!} \left[ \frac{\partial^{m+n}}{\partial x^m \partial y^n} \ f(x,y) \right]\_{(x=x\_0,y=y\_0)}$$ Where the square bracket notation with coordinate subscript means evaluate at. I previously derived the following formula, however I now suspect that it is not correct. Perhaps someone better than myself at proof by induction could verify this? $$f(x,y) = \sum\_{k=0}^{\infty} \frac{1}{k!} \sum\_{j=0}^{k} \alpha\_{k,j} (x-x\_0)^{j} (y-y\_0)^{k-j}$$ $$\alpha\_{k,j} = \,^{k}C\_{j} \left[ \frac{\partial^{k}}{\partial x^j \partial y^{k-j}} \ f(x,y) \right]\_{(x=x\_0,y=y\_0)}$$ In order to prove the first form, I did the following: $$\left[ f(x,y) \right]\_{(x0,y0)} = \sum\_{m=0}^{\infty} \sum\_{n=0}^{\infty} \beta\_{m,n} \cdot 0^m \cdot 0^n = \beta\_{0,0}$$ Differentiating partially with respect to x we find $$\left[ \frac{\partial f(x,y)}{\partial x} \right]\_{(x0,y0)} = \sum\_{m=0}^{\infty} \sum\_{n=0}^{\infty} \left( \beta\_{m,n} \cdot m \cdot 0^{m-1} \cdot 0^n + \left(\frac{\partial \beta\_{m,n}}{\partial x} \right) \cdot0^m\cdot0^n\right) = \beta\_{1,0} $$ where $\tfrac{\partial \beta\_{m,n}}{\partial x} = 0$. Continuing this process for all combinations of partial derivatives with respect to both x and y, we find that in general $$\beta\_{m,n}=\frac{1}{m!n!}\cdot \left[ \frac{\partial f(x,y)}{\partial x} \right]\_{(x=x0,y=y0)}$$ Unless I have made a mistake that is. (In which case please add a comment so I can correct my answer.)
331,337
I am in confidence with Taylor expansion of function $f\colon R \to R$, but I when my professor started to use higher order derivatives and multivariate Taylor expansion of $f\colon R^n \to R$ and $f\colon R^n \to R^m$ I felt lost. *Can somean explain to me from scratch multivariate Taylor?* In particular I don't understand the notation $$ f(x+h) = \sum\_{k=0}^p \frac{1}{k!} f^{(k)}(x)[h,...,h] + O(h^{p+1}) $$ Why we need the k-linear form $ \frac{1}{k!} f^{(k)}(x)[h,...,h]$? This k-linear form is the derivative or the derivative is only $f^{(k)}(x)$? I'm quite lost. Thank you.
2013/03/15
[ "https://math.stackexchange.com/questions/331337", "https://math.stackexchange.com", "https://math.stackexchange.com/users/66897/" ]
One can think about Taylor's theorem in calculus as applying in the following cases: 1. Scalar-valued functions of a scalar variable, i.e. $f : \mathbb{R} \rightarrow \mathbb{R}$ 2. Vector-valued functions of a scalar variable, i.e. $f : \mathbb{R} \rightarrow \mathbb{R}^n$ 3. Scalar-valued functions of a vector variable, i.e. $f : \mathbb{R}^n \rightarrow \mathbb{R}$ 4. Vector-valued functions of a vector variable, i.e. $f : \mathbb{R}^n \rightarrow \mathbb{R}^m$ All of these can be derived & proven based on nothing more than [integration by parts](http://books.google.ie/books?id=XUjod_RjjX8C&dq=Lang+Calculus+taylor%27s+theorem&q=Taylor%27s+theorem#v=snippet&q=Taylor%27s%20theorem&f=false) (the last one needs to be developed in a banach space & the third one is more commonly reduced to the first one which is just a shorthand for re-proving it via integration by parts) if you set things up correctly (as is done in Lang's Undergraduate, Real & Functional Analysis books) & so your main obstacle here is formalism - this is no small obstacle as we'll see below. Now I'm not sure if your expression for Taylor's formula is map 3 or map 4, one would think it is map 3 since you used the word "linear form" which is standard parlance for maps from vector spaces into a field but you did ask about maps of the form $f : \mathbb{R}^n \rightarrow \mathbb{R}^m$ - are you sure you are differentiating these kinds of maps because they add a whole world of complexity compared to the first 3? If you're asking about maps of the form in 3 then some intuition is given in [this](http://www.youtube.com/watch?v=Z7yTsoMTjnM) video & some examples & a proof are given in [this](http://www.youtube.com/watch?v=D8AjFhLhFvA) video. After these you should have enough of a grasp of what's going on & if you focus on developing the formalism properly you should be able to prove it yourself in more general spaces. If you're actually asking about map 4 then you may be used to the definition of the derivative of the last map as $f : \mathbb{R}^n \rightarrow \mathbb{R}^m$ as something like $\mathcal{f'} : \mathbb{R}^n \rightarrow \mathcal{L}(\mathbb{R}^n,\mathbb{R}^m)$ satisfying [all the conditions](http://en.wikipedia.org/wiki/Frechet_derivative#Definition) a differentiable map does, well it's second derivative is defined similarly using a map of the form $f'': \mathbb{R}^n \rightarrow \mathcal{L}(\mathbb{R}^n,\mathcal{L}(\mathbb{R}^n,\mathbb{R}^m))$ & so on, however you see no such entity as a "k-linear form" in any of this & that's because [there is a theorem](http://books.google.ie/books?id=VfxGB5nYv1MC&pg=PA5&dq=banach+isomorphism+multilinear&hl=en&sa=X&ei=Z2BDUY7dOZON7AbRg4GICA&ved=0CDAQuwUwAA#v=onepage&q=banach%20isomorphism%20multilinear&f=false) which allows one to think of maps like the second derivative above in terms of multilinear maps & so one can re-cast the theory using multilinear maps which eases the development & allows for nice proofs etc... but without this being explained it might appear odd to randomly start pulling out multilinear maps. In any case the derivative is a linear map by definition & so that is why you're coming across the word linear, but since you didn't put subscripts on the $[h,...,h]$ I'm not sure how deep I can go, because I see two possibilities here so if the above isn't enough of an explanation as it stands just let me know.
You need to understand gradient vector to understand this article, although it is quite useful and can direct you to formulate the taylor series formula more concisely: <http://www.math.ucdenver.edu/~esulliva/Calculus3/Taylor.pdf>.
3,652,331
So let me start by saying that the weird thing about this error is that the application is running, and the error bubbles to the event log, but it's intermittent. Sometimes it's 2 hours between it happening, sometimes a few minutes, sometimes half an hour. Does not appear to be tied directly to requests (and requests don't seem to be failing because of it, though nearly all requests should be hitting NHibernate right now). I've ensured that the dll is in the bin, it's unblocked (and if either of those weren't the case, I would expect it to fail always, not just sometimes). For the app, I'm using Nhibernate 2.1.2, castle activerecord 2, ASP.NET MVC 2, and the app is deployed on IIS 7.5 with SQL Server 2005 for the db. I saw a similar error on Stack but no answers there, hoping someone has insight on this error. ``` Message: Unable to find assembly 'NHibernate, Version=2.1.2.4000, Culture=neutral, PublicKeyToken=aa95f207798dfdb4'. StackTrace: at System.Runtime.Serialization.Formatters.Binary.BinaryAssemblyInfo.GetAssembly() at System.Runtime.Serialization.Formatters.Binary.ObjectReader.GetType(BinaryAssemblyInfo assemblyInfo, String name) at System.Runtime.Serialization.Formatters.Binary.ObjectMap..ctor(String objectName, String[] memberNames, BinaryTypeEnum[] binaryTypeEnumA, Object[] typeInformationA, Int32[] memberAssemIds, ObjectReader objectReader, Int32 objectId, BinaryAssemblyInfo assemblyInfo, SizedArray assemIdToAssemblyTable) at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadObjectWithMapTyped(BinaryObjectWithMapTyped record) at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadObjectWithMapTyped(BinaryHeaderEnum binaryHeaderEnum) at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.Run() at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage) at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage) at System.Runtime.Remoting.Channels.CrossAppDomainSerializer.DeserializeObject(MemoryStream stm) at System.AppDomain.Deserialize(Byte[] blob) at System.AppDomain.UnmarshalObject(Byte[] blob) ```
2010/09/06
[ "https://Stackoverflow.com/questions/3652331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53788/" ]
Does this also happen on Application start up or is it always at some time in the future after the application has started? Check [Unhandled IIS Exception - How can I track it down](https://stackoverflow.com/questions/1799376/unhandled-iis-exception-how-can-i-track-it-down) (which has a **very** similar stack trace) which leads to <http://unhandledexception.codeplex.com/sourcecontrol/latest>
I have gotten similar errors and found that the real problem is not being reported. The accepted answer here is specific to ASP.NET (which is fine since that is what the question was about), but I was having the issue with a WPF browser application (which doesn't have a web.config file) and I found another way to see what my real problem was. I thought I should post it in case other people will find it helpful. If you are getting these while debugging in Visual Studio, it can help to go to Debug > Exceptions and select the "Thrown" checkboxes (I am using VS 2008). For me, this allowed the error to be reported in Visual Studio instead of my web browser, and provided more detailed and accurate error information. If you do this, realize that some of these exceptions may have been previously handled but now will disrupt your workflow by breaking at those points. If this happens, you can just turn off the exceptions that you don't need to break on.
45,325,039
In the following program, When I click on Add button in the options menu a dialog is opened wherein the user enters the data which is then shown in the ListView. There are a number of problems with his code. 1) age.setText in the Custom Adapter causes the app to crash.Commenting out the age.settext line, it works well for the other two TextViews. 2) When i add data in the list using the dialog the second time, the list gets overwritten and no updation is done. I want the list to be automatically updated when new data is entered rather than over writing it. 3) The data vanishes away when i restart the app. I want the data to be saved permanently. Code for Custom Adapter is: ``` package com.example.sakshi.dialogsandmenus; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import org.w3c.dom.Text; import java.util.ArrayList; public class CustomAdapter extends BaseAdapter { private Context context; private ArrayList<Data> list; private LayoutInflater mLayoutInflator; public CustomAdapter(Context context, ArrayList list){ this.context=context; this.list=list; mLayoutInflator = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { convertView = mLayoutInflator.inflate(R.layout.row,null); TextView name = (TextView)convertView.findViewById(R.id.name); TextView age = (TextView)convertView.findViewById(R.id.agedata); TextView dob = (TextView)convertView.findViewById(R.id.dob); name.setText(list.get(position).getName()); //age.setText(list.get(position).getAge()); dob.setText(list.get(position).getDate()); return convertView; } } ``` Code for Main Activity is: ``` package com.example.sakshi.dialogsandmenus; import android.app.Dialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ListView; import java.util.ArrayList; import static android.R.id.list; import static com.example.sakshi.dialogsandmenus.R.id.date; public class MainActivity extends AppCompatActivity{ ListView listview; ArrayList<Data> arrayList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listview = (ListView)findViewById(R.id.list_item); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.menu,menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id= item.getItemId(); if(id==R.id.add){ filldialog(); } return super.onOptionsItemSelected(item); } public void filldialog(){ final Dialog dialog = new Dialog(MainActivity.this); dialog.setCanceledOnTouchOutside(false); dialog.setContentView(R.layout.dialog_layout); dialog.show(); Button add = (Button)dialog.findViewById(R.id.additem); final EditText getnamedata = (EditText)dialog.findViewById(R.id.name); final EditText getagedata = (EditText)dialog.findViewById(R.id.age); final DatePicker datePicker = (DatePicker)dialog.findViewById(date); add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String getname = getnamedata.getText().toString(); int getage = Integer.parseInt(getagedata.getText().toString()); int mm,y,d; mm=datePicker.getMonth(); y=datePicker.getYear(); d=datePicker.getDayOfMonth(); String getdate = d+"/"+mm+"/"+y; arrayList = new ArrayList<>(); Data data = new Data(); data.setName(getname); data.setAge(getage); data.setDate(getdate); arrayList.add(data); CustomAdapter customAdapter = new CustomAdapter(MainActivity.this,arrayList); listview.setAdapter(customAdapter); //customAdapter.notifyDataSetChanged(); dialog.dismiss(); } }); } ``` }
2017/07/26
[ "https://Stackoverflow.com/questions/45325039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7885436/" ]
You can use the `Range` object to insert text at a specific position. [msdn](https://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.range.aspx) ``` doc1.Range(0, 0).Text = "Hello World"; ``` If you have a template and the position to insert the text is always at the same location, you could also use `Bookmark`. [msdn](https://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.bookmark.aspx) **[Update]** Here is a complete example to add text to a word document by a bookmark: ``` Application app = new Microsoft.Office.Interop.Word.Application(); Document doc = app.Documents.Open(@"your file"); string bookmark = "BookmarkName"; Bookmark bm = doc.Bookmarks[bookmark]; Range range = bm.Range; range.Text = "Hello World"; doc.Bookmarks.Add(bookmark, range); ``` With this solution, the bookmark will not be deleted and you can add/modify it later again with the same piece of code.
You can use the following to insert a string into another string in a specific position. ``` doc1.Content.Text = doc1.Content.Text.Insert(10, "Merge?"); ``` Source: <https://msdn.microsoft.com/en-us/library/system.string.insert(v=vs.110).aspx>
45,325,039
In the following program, When I click on Add button in the options menu a dialog is opened wherein the user enters the data which is then shown in the ListView. There are a number of problems with his code. 1) age.setText in the Custom Adapter causes the app to crash.Commenting out the age.settext line, it works well for the other two TextViews. 2) When i add data in the list using the dialog the second time, the list gets overwritten and no updation is done. I want the list to be automatically updated when new data is entered rather than over writing it. 3) The data vanishes away when i restart the app. I want the data to be saved permanently. Code for Custom Adapter is: ``` package com.example.sakshi.dialogsandmenus; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import org.w3c.dom.Text; import java.util.ArrayList; public class CustomAdapter extends BaseAdapter { private Context context; private ArrayList<Data> list; private LayoutInflater mLayoutInflator; public CustomAdapter(Context context, ArrayList list){ this.context=context; this.list=list; mLayoutInflator = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { convertView = mLayoutInflator.inflate(R.layout.row,null); TextView name = (TextView)convertView.findViewById(R.id.name); TextView age = (TextView)convertView.findViewById(R.id.agedata); TextView dob = (TextView)convertView.findViewById(R.id.dob); name.setText(list.get(position).getName()); //age.setText(list.get(position).getAge()); dob.setText(list.get(position).getDate()); return convertView; } } ``` Code for Main Activity is: ``` package com.example.sakshi.dialogsandmenus; import android.app.Dialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ListView; import java.util.ArrayList; import static android.R.id.list; import static com.example.sakshi.dialogsandmenus.R.id.date; public class MainActivity extends AppCompatActivity{ ListView listview; ArrayList<Data> arrayList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listview = (ListView)findViewById(R.id.list_item); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.menu,menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id= item.getItemId(); if(id==R.id.add){ filldialog(); } return super.onOptionsItemSelected(item); } public void filldialog(){ final Dialog dialog = new Dialog(MainActivity.this); dialog.setCanceledOnTouchOutside(false); dialog.setContentView(R.layout.dialog_layout); dialog.show(); Button add = (Button)dialog.findViewById(R.id.additem); final EditText getnamedata = (EditText)dialog.findViewById(R.id.name); final EditText getagedata = (EditText)dialog.findViewById(R.id.age); final DatePicker datePicker = (DatePicker)dialog.findViewById(date); add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String getname = getnamedata.getText().toString(); int getage = Integer.parseInt(getagedata.getText().toString()); int mm,y,d; mm=datePicker.getMonth(); y=datePicker.getYear(); d=datePicker.getDayOfMonth(); String getdate = d+"/"+mm+"/"+y; arrayList = new ArrayList<>(); Data data = new Data(); data.setName(getname); data.setAge(getage); data.setDate(getdate); arrayList.add(data); CustomAdapter customAdapter = new CustomAdapter(MainActivity.this,arrayList); listview.setAdapter(customAdapter); //customAdapter.notifyDataSetChanged(); dialog.dismiss(); } }); } ``` }
2017/07/26
[ "https://Stackoverflow.com/questions/45325039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7885436/" ]
For sake of simplicity, first add the bookmark in MS Word as follow: Select the region where you want to add the text, Then go to Insert > Bookmark in Word. [![enter image description here](https://i.stack.imgur.com/3eGzV.png)](https://i.stack.imgur.com/3eGzV.png) Then give the name to the bookmark as follow: [![enter image description here](https://i.stack.imgur.com/7N5Kn.png)](https://i.stack.imgur.com/7N5Kn.png) [![enter image description here](https://i.stack.imgur.com/G9jaZ.png)](https://i.stack.imgur.com/G9jaZ.png) Then use the follow modified version of Ben: ``` Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application(); Document doc = app.Documents.Open(Path.Combine(Environment.CurrentDirectory, "Report.doc")); Dictionary<string, string> bookmarks = new Dictionary<string, string> { { "DateOfIssue", "23-06-2018"}, { "TotalNumOfPages", "20" } }; foreach (var bookmark in bookmarks) { Bookmark bm = doc.Bookmarks[bookmark.Key]; Range range = bm.Range; range.Text = bookmark.Value; doc.Bookmarks.Add(bookmark.Key, range); } ``` Finally the output is as follow: [![enter image description here](https://i.stack.imgur.com/dMTPq.png)](https://i.stack.imgur.com/dMTPq.png)
You can use the following to insert a string into another string in a specific position. ``` doc1.Content.Text = doc1.Content.Text.Insert(10, "Merge?"); ``` Source: <https://msdn.microsoft.com/en-us/library/system.string.insert(v=vs.110).aspx>
426,700
I have a very strange problem with a NFS mount. I have a Synology NAS serving the home directories for a set of linux machines (Archlinux for the moment). The used protocol is NFS V3. When I log into the machines using my main user, I can see that I have write permission to my home folder: ``` $ ls -ld ~ drwx------ 28 cwolf cwolf 4096 26. Feb 15:10 /home/cwolf ``` I can create and remove files. So the folder is in fact writable. Now I see a strange behavior. Issuing ``` $ test -w ~; echo $? 1 ``` indicates that I do not have write permission on my home folder.... This makes KDE to reject from running as it thinks it cannot write to the home folder. Trying the same with a local user (whose home folder lies completely on the local hard disk), everything is consistent. So the test returns `0`. Can anyone tell me where I can look to solve the problem and make test return the correct value? Also the question is if this is more likly a problem on the NFS server or on the NFS client. --- Additional information: The problem is not related to `root_squash` as in the exact same session I can do `touch foo`/`rm foo` to create and remove a file `foo` successfully. So the server accepts my commands as user. Most of the information in the internet is related the other way around: The user is shown to have write access but gets remapped on the server to `nobody` due to squashing. My problem is that my rights are accepted but shown falsely as read-only rendering tests to fail. --- As requested by the comments here the export options on the server: ``` /volume1/cloud 134.96.8.160/27(rw,async,no_wdelay,no_root_squash,insecure_locks,sec=sys,anonuid=1025,anongid=100) ``` The mount options (corresponding line from the output of `mount`) are: ``` ds2.lsr.uni-saarland.de:/volume1/cloud on /home type nfs (rw,relatime,vers=3,rsize=131072,wsize=131072,namlen=255,hard,proto=tcp,timeo=600,retrans=2,sec=sys,mountaddr=134.96.8.162,mountvers=3,mountport=892,mountproto=tcp,local_lock=none,addr=134.96.8.162) ```
2018/02/26
[ "https://unix.stackexchange.com/questions/426700", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/40241/" ]
You are root when you run this test. Depending on the server settings, this will forbid you to write to that folder. A normal user will not have that problem.
I recently had the same issue. I am using a Synology NAS, and the problem has been resolved after updating the DSM (operating system) to the latest. Hope it helps the ones struggling with the same problem.
46,010,819
In my project, I want to display battery information in details. With `UIDevice` I can get battery level easily, but my demand is much more that just that. I want to obtain such battery health ,cycle count, voltage and even more details about the battery. (the more the better!! ). I really need some advice, thanks!
2017/09/02
[ "https://Stackoverflow.com/questions/46010819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7775634/" ]
You should use the `@Table` annotation. The problem is that you register two entities with the same name instead to bind them to same tables. ``` @Entity @Table(name = "user") public class Human ``` And then: ``` @Entity @Table(name = "user") public class Robot ```
You are using same table for two different classes, it will get mixed up. How hibernate knows that user table is of human or robot. Also both classes can have different properties. Either create two different table or create a super class of `User` and extend `Human` and `Robot` classes from it. Put common attributes in User class.
33,900,253
For improving the performance of my android app i decided to re write calculation parts in c++ and use JNI. here is the problem : My c++ method generates very large amount of objects (2k to 10k) in a multiple level loop. An object is being created in the deepest level and stored in a vector of jobject's for the later return. My implementation of the last part is as below: ``` jobject genObj = env->NewObject(jclass,jmethodId,...); Vector.push_back(genObj); env->DeleteLocalRef(genObj); ``` this code gives me: ***JNI ERROR (app bug): accessed stale local reference*** Which means im trying to access a deleted block of memory. This is unexpected because push\_back should copy the argument not its pointer. What should i do ? Ps: not deleting the local ref will lead to localref table overflow
2015/11/24
[ "https://Stackoverflow.com/questions/33900253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2975750/" ]
You could create global references of your objects using `NewGlobalRef` put those in the vector, then delete the local references. This way you can keep your objects in a vector as long as you don't run out of memory. Make sure you don't forget to delete those global references with `DeleteGlobalRef` once you don't need them anymore, because the garbage collector doesn't collect objects held in native memory. Here's the [documentation](http://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/design.html#referencing_java_objects)
OYou're saving the local reference in `Vector,` deleting it, but then using it out of `Vector` later on. You can't do that. You can't delete it until you're really finished with it. Maybe you should look into `PushLocalFrame()` and friends if you're running out of local references. Or use a Java collection instead of the C++ `Vector`.
12,207,656
I'm currently almost at the end of a long journey into rails testing, but I'm banging my head on how to get request specs working with subdomains. In development, I'm using pow with urls such as: `http://teddanson.myapp.dev/account` which is all fine and dandy. In testing, I let capybara do it's thing which returns localhost `http://127.0.0.1:50568/account` which obviously doesn't play nice with the whole subdomain thing. It works fine for the public part of the app that doesn't require subdomains, but how to access a given user's subdomain account is beyond me. The relevant routes are accessed via these methods: ``` class Public def self.matches?(request) request.subdomain.blank? || request.subdomain == 'www' end end class Accounts def self.matches?(request) request.subdomain.present? && request.subdomain != 'www' end end ``` I feel like I'm taking crazy pills, so if anyone has any advice or suggestions to help me out that'd be very, very awesome. Thanks for your help!
2012/08/31
[ "https://Stackoverflow.com/questions/12207656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/472259/" ]
You can use xip.io to test subdomains in Capybara/RSpec, as described here: <https://web.archive.org/web/20171222062651/http://chrisaitchison.com/2013/03/17/testing-subdomains-in-rails/>
Unfortunately you cannot use subdomain in capybara's test but I have a workaround for this problem. I have helper class for resolving a subdomain from the request, see: ``` class SubdomainResolver class << self # Returns the current subdomain def current_subdomain_from(request) if Rails.env.test? and request.params[:_subdomain].present? request.params[:_subdomain] else request.subdomain end end end end ``` As you see, when the app is running in `test` mode and a special `_subdomain` request param is set the subdomain is taken from the request param called `_subdomain` otherwise `request.subdomain` (normal subdomain) is used. To make this workaround work you have to also override url builders, in `app/helpers` create the following module: ``` module UrlHelper def url_for(options = nil) if cannot_use_subdomain? if options.kind_of?(Hash) && options.has_key?(:subdomain) options[:_subdomain] = options[:subdomain] end end super(options) end # Simple workaround for integration tests. # On test environment (host: 127.0.0.1) store current subdomain in the request param :_subdomain. def default_url_options(options = {}) if cannot_use_subdomain? { _subdomain: current_subdomain } else {} end end private # Returns true when subdomains cannot be used. # For example when the application is running in selenium/webkit test mode. def cannot_use_subdomain? (Rails.env.test? or Rails.env.development?) and request.host == '127.0.0.1' end end ``` `SubdomainResolver.current_subdomain_from` can be also used as constraint in `config/routes.rb` I hope it will help you.
4,534,513
Let $x\_n$ be a sequence of positive real numbers, which is not convergent. ($x\_n$ does not converge to a finite number, nor to infinity). Define $$ A\_n = \frac{x\_1 + x\_2 + \cdots + x\_n}{n} \quad \text{ and }\quad G\_n = \sqrt[n]{x\_1x\_2...x\_n}.$$ > > Does the convergence of $A\_n$ imply the convergence of $G\_n$ or vice versa? > > > I know that if $x\_n \to L \in \mathbb{R}\cup\{\infty\}$, then both $A\_n,G\_n$ converge to $L$. But here I assume $x\_n$ is not convergent. I also wonder if adding a boundedness assumption on $x\_n$ changes anything.
2022/09/19
[ "https://math.stackexchange.com/questions/4534513", "https://math.stackexchange.com", "https://math.stackexchange.com/users/104576/" ]
You did the steps wrongly at "... then $0.3 = r^3$ ..." It does not matter whether the variable is on the left or on the right. It is just a convention to have the variable on the left so that it is easier to read. Observe how I do it with both cases where the variables on the left / on the right: 1. Variable on the left $60 = \frac{200}{r^3}$ $60r^3 = 200$ *(Multiply $r^3$ on both sides)* $r^3 = \frac{200}{60}= \frac{10}{3}$ *(Divide $60$ on both sides and simplify $\frac {200}{3}\space to\space \frac{10}{3}$)* $r = \sqrt[3]{\frac{10}{3}} = 1.49 \space(3sf)$ *(Cube root both sides)* 2. Variable on the right $60 = \frac{200}{r^3}$ $\frac{60}{200} = \frac{1}{r^3}$ \*(This is the part where you get confused. Notice that it is like so because if you bring $200$ over to the right side, we are essentially doing this: $$60 \cdot \frac{1}{200}= \frac{200}{r^3} \cdot \frac{1}{200}$$ Which will give you: $$\frac{60}{200}=\frac{1}{r^3}$$ If we take the reciprocal on both sides, we will get: $$\frac{200}{60}=r^3$$ which will give you the same answer. Observe that it is less confusing when the variable is on the left, so I suggest that you follow the convention! Hope this helps!
If you multiply both sides by $1/200$ you get $$ \frac{60}{200}=\frac{1}{r^3}\tag{1} $$ Think to $$ 4=\frac{8}{2} $$ which is a true equality; if you multiply both sides by $1/8$, you get $$ \frac{4}{8}=\frac{1}{2} $$ which is still true, not $$ \frac{4}{8}=2 $$ which is clearly false. Now our ($1$) becomes $$ \frac{10}{3}=r^3 $$ by taking reciprocals and this ends up in $$ r=\sqrt[3]{10/3} $$
71,119,053
#Write a function named add\_one\_to\_all that takes in a list of numbers and adds one to each of the original numbers ``` assert add_one_to_all([0, 0, 0]) == [1, 1, 1] assert add_one_to_all([1, 2, 3]) == [2, 3, 4] assert add_one_to_all([6, 7, 8]) == [7, 8, 9] ``` I've tried this ``` def my_list ([x,y,z]): new_list = [x+1 for x in my_list] ```
2022/02/14
[ "https://Stackoverflow.com/questions/71119053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18207593/" ]
``` def add_one_to_all(my_list): return [x+1 for x in my_list] ```
You can use `map` ``` l = [1, 2, 3] print(list(map(lambda x:x+1, l))) ``` result ``` [2, 3, 4] ```
71,119,053
#Write a function named add\_one\_to\_all that takes in a list of numbers and adds one to each of the original numbers ``` assert add_one_to_all([0, 0, 0]) == [1, 1, 1] assert add_one_to_all([1, 2, 3]) == [2, 3, 4] assert add_one_to_all([6, 7, 8]) == [7, 8, 9] ``` I've tried this ``` def my_list ([x,y,z]): new_list = [x+1 for x in my_list] ```
2022/02/14
[ "https://Stackoverflow.com/questions/71119053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18207593/" ]
``` def add_one_to_all(my_list): return [x+1 for x in my_list] ```
``` def add_one_to_all(integer): return integer+1 int_list = [1, 2, 3, 4, 5] # Adding one on each integer # using list comprehension. output_list = [add_one_to_all(i) for i in int_list] print(output_list) ``` > > The output will be **[2,3,4,5,6]** > > >
7,608,694
here is my code : this is my application class >>> ``` import org.restlet.Application; import org.restlet.Restlet; import org.restlet.routing.Router; import firstSteps.UserResource; public class FirstStepsApplication extends Application { @Override public synchronized Restlet createRoot() { Router router = new Router(getContext()); router.attach("/hello", UserResource.class); router.attach("/isuserloggedin",UserResource.class); return router; } } ``` this is resource class >>> ``` import org.restlet.resource.Get; import org.restlet.resource.ServerResource; /** * Resource which has only one representation. * */ public class UserResource extends ServerResource { @Get public String userLogin() { return "This is userLogin method"; } @Get public boolean isUserLoggedIn(){ return false; } } ``` `/hello` & `/isuserloggedin` are mapped to same to resource class but what i want is : when there is `/hello` then `userLogin` method should be called and when there is `/isuserloggedin` then `isUserLoggedIn` must be called . is this possible ?? or am i going wrong? if this is not possible then any one can tell me any other alternative ?
2011/09/30
[ "https://Stackoverflow.com/questions/7608694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/824774/" ]
In Restlet 2.1 (try M7 or above), it is possible to dispatch two HTTP GET calls to two Java methods in the same resource class. This is done by leveraging query parameters like this: ``` import org.restlet.resource.Get; import org.restlet.resource.ServerResource; /** * Resource which has only one representation. * */ public class UserResource extends ServerResource { @Get public String userLogin() { return "This is userLogin method"; } @Get("?loggedIn") public boolean isUserLoggedIn(){ return false; } } ``` However, as pointed already, you would be better off using a separate resource class.
Some time has passed since my last experience with Restlet, anyway, if you are implementing a fully REST API, I would expect the two to be separate resources if they really need to be. Otherwise, a resource should be mapped to exactly one representation, IMHO. What is the benefit of having two URIs mapped to one resource class, instead of having two, each implementing the GET method? It seems to add a bit of ambiguity there, with no benefit. I would return the status (logged or not) information in the user representation. Now, for sake of completeness, I find a bit difficult to understand your API semantics: can I ask for the logged status of any user, or just mine? It's not very clear, but I understand that it was not the main point. Just as a nice reading, you may want to have a look at some popular REST api to see how they manage issues similar to yours, ie. I like [Github Users' API](http://develop.github.com/p/users.html) particularly. Hope it helps.
25,093,239
I have this JSON file: ``` {"__v":4,"_id":"53dbeedb1a6550ee08c55c05","name":"Quatro formaggi","ingredients":["53c791b6e4b04af47f662f98","53c791b6e4b04af47f662f98","53c791b6e4b04af47f662f98","53c791b6e4b04af47f662f98"]} ``` I want get every ingredients. If I write: ``` {{pizza.ingredients}} ``` I get: ``` ["53c791b6e4b04af47f662f98","53c791b6e4b04af47f662f98","53c791b6e4b04af47f662f98","53c791b6e4b04af47f662f98"] ``` If I write this: ``` {{pizza.ingredients.1}} ``` I get this: ``` 53c791b6e4b04af47f662f98 ``` but I want a loop that I can get every ingredient like this result: ``` 1- 53c791b6e4b04af47f662f98 2- 53c79214e4b04af47f662f9d 3- 53c7925ae4b04af47f662fa0 ``` how can I do that with AngularJS?
2014/08/02
[ "https://Stackoverflow.com/questions/25093239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3405595/" ]
Your (1) has nothing to do with (2) and (3). And there are other places where you can bind controllers (e.g. a directive's `controller` property). Each way is serves a different purpose, so go with the one that suits your situation. * If you have a directive and want to give it a specific controller, use the Directive Definition Object's `controller` property. * If you use `ngView` and want to give each view a specific controller (as is usually the case) use the `$routeProvider`s `controller`. * If you want to assign a controller to some part of your view (in the main file or in a view or partial) use `ngController`. All the above are methods for "binding" a controller to some part of the view (be it a single element or the whole HTML page or anything in between).
Im quite new too but Ill try to explain in a more layman way. 1 For each .js file you have (which may contain one or more controller defined), you need a corresponding entry into the script for #1 there. Its not the controller itself, more like to allow script to recognise that this .js file is part of the set of files to run. 2 is more like specify a state or route, which may or may not use a controller. Its much like saying how one event should lead to another. The controller may be involved in the transitions of the states/routes (ie. responsible from one state, to another) or within a view itself. 3 is for using a controller's functions within a view itself.
25,093,239
I have this JSON file: ``` {"__v":4,"_id":"53dbeedb1a6550ee08c55c05","name":"Quatro formaggi","ingredients":["53c791b6e4b04af47f662f98","53c791b6e4b04af47f662f98","53c791b6e4b04af47f662f98","53c791b6e4b04af47f662f98"]} ``` I want get every ingredients. If I write: ``` {{pizza.ingredients}} ``` I get: ``` ["53c791b6e4b04af47f662f98","53c791b6e4b04af47f662f98","53c791b6e4b04af47f662f98","53c791b6e4b04af47f662f98"] ``` If I write this: ``` {{pizza.ingredients.1}} ``` I get this: ``` 53c791b6e4b04af47f662f98 ``` but I want a loop that I can get every ingredient like this result: ``` 1- 53c791b6e4b04af47f662f98 2- 53c79214e4b04af47f662f9d 3- 53c7925ae4b04af47f662fa0 ``` how can I do that with AngularJS?
2014/08/02
[ "https://Stackoverflow.com/questions/25093239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3405595/" ]
Your (1) has nothing to do with (2) and (3). And there are other places where you can bind controllers (e.g. a directive's `controller` property). Each way is serves a different purpose, so go with the one that suits your situation. * If you have a directive and want to give it a specific controller, use the Directive Definition Object's `controller` property. * If you use `ngView` and want to give each view a specific controller (as is usually the case) use the `$routeProvider`s `controller`. * If you want to assign a controller to some part of your view (in the main file or in a view or partial) use `ngController`. All the above are methods for "binding" a controller to some part of the view (be it a single element or the whole HTML page or anything in between).
I've added comments to one of the answers, but aside from syntax this may is more of a design question. Here is my *opinion* Firstly, (1) is irrelevant to the conversation. (2) is the preferred approach when specifying the controller for the view as it decouples the controller from the view itself. This can be useful when you want to re-use the same view by providing a different controller. If you find yourself using (3),consider making that area into a directive, since by specifying a controller you are indicating that it requires its own logic.
5,002,429
Revisiting MySQL, and trying to change the structure of the table. I want to change two rows from a varchar(30) to higher. I have googled it, and tried what appears to be the correct statement but I'm getting a syntax error: ``` ALTER TABLE 'compdetails' CHANGE 'compName' varchar(60) not null; ``` This statement however gives me a syntax error. I have also tried without the '' around the table/column names without any luck. > > "Error 2064 (42000): You have an error > in your SQL Syntax...." > > > Can anyone jog my memory?
2011/02/15
[ "https://Stackoverflow.com/questions/5002429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/376083/" ]
For those interested in an answer from the Doug Lea on this topic, he recently explained the reason for `readValueUnderLock` This is in response to someone who had the question: > > In the ConcurrentHashMap the get > method does not require > "readValueUnderLock" because a racing > remove does not make the value null. > The value never becomes null on the > from the removing thread. this means > it is possible for get to return a > value for key even if the removing > thread (on the same key) has > progressed till the point of cloning > the preceding parts of the list. This > is fine so long as it is the desired > effect. > > > But this means "readValueUnderLock" is > not required for NEW memory model. > > > However for the OLD memory model a put > may see the value null due to > reordering(Rare but possible). > > > Is my understanding correct. > > > Response: > > Not quite. You are right that it > should never be called. However, the > JLS/JMM can be read as not absolutely > forbidding it from being called > because of weaknesses in required > ordering relationships among finals vs > volatiles set in constructors (key is > final, value is volatile), wrt the > reads by threads using the entry > objects. (In JMM-ese, ordering > constraints for finals fall outside of > the synchronizes-with relation.) > That's the issue the doc comment > (pasted below) refers to. No one has > ever thought of any practical loophole > that a processor/compiler might find > to produce a null value read, and it > may be provable that none exist (and > perhaps someday a JLS/JMM revision > will fill in gaps to clarify this), > but Bill Pugh once suggested we put > this in anyway just for the sake of > being conservatively pedantically > correct. In retrospect, I'm not so > sure this was a good idea, since it > leads people to come up with exotic > theories. > > > It can all be viewed [here](http://old.nabble.com/Numa-and-ReentrantLock-td29549241.html)
As far as I understand Memory Model, write to volatile variable is guaranteed to be visible by all subsequent (as defined by *synchronization order*) reads of that variable. However, nothing guarantees that read of `e.value` in `get()` is subsequent to write of `value` in the constructor (since there are no *synchronized-with* relations between these actions), so that Memory Model allows this kind of reorder, and explicit synchronization in the case of `null` value is necessary to ensure that we read the correct value. **UPDATE:** The new memory model guarantees that any write to non-volatile variable prior to write to the volatile variable can be seen by other threads after the subsequent read of that volatile variable, **but not vice versa**. Here is the related excerpt from [The Java Memory Model by Jeremy Manson, William Pugh and Sarita Adve](http://unladen-swallow.googlecode.com/files/journal.pdf): > > *5.1.1 Lock Coarsening.* > > ... > > All of this is simply a roundabout way of saying that **accesses to normal variables > can be reordered with** a following volatile read or lock acquisition, or **a preceding > volatile write** or lock release. This implies that normal accesses can be moved > inside locking regions, but (for the most part) not out of them; > > > Therefore assignment of the constructed object can be reordered with the write to volatile variable inside a constructor, so that the check in question is required.
5,002,429
Revisiting MySQL, and trying to change the structure of the table. I want to change two rows from a varchar(30) to higher. I have googled it, and tried what appears to be the correct statement but I'm getting a syntax error: ``` ALTER TABLE 'compdetails' CHANGE 'compName' varchar(60) not null; ``` This statement however gives me a syntax error. I have also tried without the '' around the table/column names without any luck. > > "Error 2064 (42000): You have an error > in your SQL Syntax...." > > > Can anyone jog my memory?
2011/02/15
[ "https://Stackoverflow.com/questions/5002429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/376083/" ]
For those interested in an answer from the Doug Lea on this topic, he recently explained the reason for `readValueUnderLock` This is in response to someone who had the question: > > In the ConcurrentHashMap the get > method does not require > "readValueUnderLock" because a racing > remove does not make the value null. > The value never becomes null on the > from the removing thread. this means > it is possible for get to return a > value for key even if the removing > thread (on the same key) has > progressed till the point of cloning > the preceding parts of the list. This > is fine so long as it is the desired > effect. > > > But this means "readValueUnderLock" is > not required for NEW memory model. > > > However for the OLD memory model a put > may see the value null due to > reordering(Rare but possible). > > > Is my understanding correct. > > > Response: > > Not quite. You are right that it > should never be called. However, the > JLS/JMM can be read as not absolutely > forbidding it from being called > because of weaknesses in required > ordering relationships among finals vs > volatiles set in constructors (key is > final, value is volatile), wrt the > reads by threads using the entry > objects. (In JMM-ese, ordering > constraints for finals fall outside of > the synchronizes-with relation.) > That's the issue the doc comment > (pasted below) refers to. No one has > ever thought of any practical loophole > that a processor/compiler might find > to produce a null value read, and it > may be provable that none exist (and > perhaps someday a JLS/JMM revision > will fill in gaps to clarify this), > but Bill Pugh once suggested we put > this in anyway just for the sake of > being conservatively pedantically > correct. In retrospect, I'm not so > sure this was a good idea, since it > leads people to come up with exotic > theories. > > > It can all be viewed [here](http://old.nabble.com/Numa-and-ReentrantLock-td29549241.html)
> > I confused at HashEntry comment, as > JSR-133, once HashEntry is > constructed, all final fields will be > visible to all other threads, value > field is volatile, so I think it > visible to other threads too??? . > > > Other threads will see value as well but... The assigment of the entry (into the Object[]) is done after the initialization AND *under lock*. So if any thread sees `null` it will try to read the value under the lock. > > Other point, is the reorder he said > is: HashEntry object reference can be > assigned to tab[...] before it is full > constructed (so result is other > threads can see this entry but e.value > can be null) ? > > > No, it cannot b/c there is a volatile assignment (`value`) and than means all other operations must be set before hand (i.e. not reordered). Also keep in mind that java object creation is 2 phase, creating an empty object w/ zero/null fields (like using the default c-tor) and then calling `<init>` method (which is the constructor). The object cannot be assigned to anything before completing the constructor call and its last assignment of `value` (to ensure proper ordering also known as happens-before)
1,379,167
i have a .txt file, where i have numbers such as- ``` 99.69599 100.7113 101.7196 123.93 ``` but whenever i am exporting them to excel, they become like this- ``` 9.969.599 1.007.113 1.017.196 123.93 ``` please note that the numbers in the .txt file in the US English format but the excel is in German format. so in the excel (German format) decimal point and comma are opposite meaning it uses "." to mean "," and "," to mean ".". * US / English thousands and decimal separators: `1,234.56` * European thousands and decimal separators: `1.234,56` and the main problem is excel is for some reason shifting the decimal point when the numbers are being exported. can anyone please help me with this problem?
2018/11/28
[ "https://superuser.com/questions/1379167", "https://superuser.com", "https://superuser.com/users/968038/" ]
OK, I found the problem. I was using an `https://` url for the origin instead of an ssh url (`[email protected]:...`). After switching to an ssh url the ssh key was used. To view current remotes: `git remote -v` To switch a remote: `git remote set-url origin [email protected]:XXXXX`
Use this command: ``` ssh-copy-id [email protected] ``` Change the user to your username, and target to your destination, so it will copy your ssh key to the target system.
1,518,974
Let $A\subset X$ be connected. Then I want to conclude that $\bar A$ is connected. So I was trying to do the same thing as in the question of this post [The closure of a connected set is connected](https://math.stackexchange.com/questions/678032/the-closure-of-a-connected-set-is-connected#) The thing is that I don't follow the answer, and in fact I think there is something wrong with it. So Can someone explain me why that answer is right? or provide a detail answer for this fact please? In fact I don't follow because of @dunstin's comment, since I think he is right. Thanks a lot in advance.
2015/11/08
[ "https://math.stackexchange.com/questions/1518974", "https://math.stackexchange.com", "https://math.stackexchange.com/users/162343/" ]
Your transfer function is incorrect. Assuming that $y(n)$ is the output sequence and $x(n)$ is the input sequence, the transfer function is given by $$H(z)=\frac{Y(z)}{X(z)}=0.634\frac{1-z^{-2}}{1-0.268z^{-2}}\tag{1}$$ The poles are the values of $z$ for which $(1)$ becomes infinity, or, equivalently, for which the denominator of $(1)$ becomes zero. I'm sure you can take it from here.
Apply Z-transform to the equation, gives: $Y(z)=0.634X(z)-0.634z^{-2}X(z)+0.268z^{-2}Y(z)$ or: $Y(z)\left(1-0.268z^{-2} \right)=0.634X(z)\left(1-z^{-2} \right)$ Now computing $H(z)=\frac{Y(z)}{X(z)}$, $H(z)=\frac{Y(z)}{X(z)}=\frac{0.634\left(1-z^{-2}\right)}{1-0.268z^{-2}}$ For finding the poles, you simply need to solve $1-0.268z^{-2}=0$, $z=\pm 0.5177$.
24,210,992
I’m trying to set up a website using Spring. I already managed to read data from a database I've set up, but now encountered a problem when trying to update rows in it. I'm using the `merge()` function of the `EntityManager`. I don't get any errors or exceptions, it just wont update the data on the DB. I'll try to give all relevant code. The entity class I want to change: I already managed to fill it with data from the DB, so I think it should be alright. Benutzer.java ``` @Entity @Table(name = "BENUTZER") @NamedQueries({ @NamedQuery(name = "Benutzer.findAll", query = "SELECT tt FROM Benutzer tt"), @NamedQuery(name = "Benutzer.findByKennung", query = "SELECT tt FROM Benutzer tt WHERE tt.kennung = :kennung"), public class Benutzer { @Id @GeneratedValue private BigInteger oid; @Size(min = 2, max = 20) @Pattern(regexp = "[A-Za-z ]*", message = "Titel darf nur Buchstaben und Leerzeichen beinhalten") private String titel; @NotNull @Size(min = 2, max = 25) @Pattern(regexp = "[A-Za-z ]*", message = "Anrede darf nur Buchstaben und Leerzeichen beinhalten") private String anrede; @NotNull @Size(min = 2, max = 45) @Pattern(regexp = "[A-Za-z ]*", message = "Name darf nur Buchstaben und Leerzeichen beinhalten") private String name; @NotNull @Size(min = 2, max = 45) @Pattern(regexp = "[A-Za-z ]*", message = "Vorname darf nur Buchstaben und Leerzeichen beinhalten") private String vorname; @NotNull @Size(min = 6, max = 16) @Pattern(regexp = "[0-9]*", message = "Telefonnummer darf nur aus Zahlen bestehen") private String telefonnummer; @Size(max = 25, message = "Fax darf maximal 25 Zahlen beinhalten") @Pattern(regexp = "[0-9]*", message = "Fax darf nur aus Zahlen bestehen") private String fax; @NotNull @Size(min = 2, max = 45) @Pattern(regexp = "[A-Za-z0-9 ]*", message = "Straße darf nur Buchstaben, Leerzeichen und Hausnummer beinhalten") private String strasse; @NotNull @Size(min = 2, max = 45) @Pattern(regexp = "[A-Za-z0-9 ]*", message = "Ort darf nur Buchstaben, Leerzeichen und PLZ beinhalten") private String ort; @NotNull @Size(min = 2, max = 45, message = "E-mail muss zwischen 2 und 45 Zeichen beinhalten") private String email; private boolean freigeschaltet; @Temporal(TemporalType.TIMESTAMP) private Date sperrbeginn; @NotNull(message = "Kennung darf nicht leer sein") private String kennung; @NotNull private String passwort; @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "BENUTZER_has_KUNDE", joinColumns = { @JoinColumn(name = "BENUTZER_oid") }, inverseJoinColumns = { @JoinColumn(name = "KUNDE_oid") }) private List<Kunde> kundenListe; public Benutzer() { }; +getter and setter } } ``` The DAO : Im using the `update(Benutzer benutzer)` method in it to try updating the apropriate collumn in the DB. BenutzerDaoImpl.java ``` @Transactional @Repository("benutzerDao") public class BenutzerDaoImpl implements BenutzerDao{ private EntityManager em; public EntityManager getEm() { return em; } @PersistenceContext (type = PersistenceContextType.TRANSACTION) public void setEm(EntityManager em) { this.em = em; } public Benutzer findById(BigInteger id) { return em.find(Benutzer.class, id); } public Benutzer findByKennung(String kennung) { Query benutzerByKennung = em.createNamedQuery("Benutzer.findByKennung"); benutzerByKennung.setParameter("kennung", kennung); return (Benutzer) benutzerByKennung.getSingleResult(); } public List<Benutzer> findAll() { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Benutzer> criteria = cb.createQuery(Benutzer.class); Root<Benutzer> benutzer = criteria.from(Benutzer.class); criteria.select(benutzer).orderBy(cb.asc(benutzer.get("name"))); return em.createQuery(criteria).getResultList(); } public void register(Benutzer benutzer) { em.persist(benutzer); return; } public void delete(BigInteger id) { Benutzer benutzerTemp = findById(id); em.remove(benutzerTemp); } public void update(Benutzer benutzer) { Benutzer benutzerTemp = findById(benutzer.getOid()); benutzerTemp.setTelefon_vorwahl(benutzer.getTelefon_vorwahl()); benutzerTemp.setTelefon_nummer(benutzer.getTelefon_nummer()); benutzerTemp.setFax_vorwahl(benutzer.getFax_vorwahl()); benutzerTemp.setFax_nummer(benutzer.getFax_nummer()); benutzerTemp.setStrasse(benutzer.getStrasse()); benutzerTemp.setStrasse_nummer(benutzer.getStrasse_nummer()); benutzerTemp.setOrt(benutzer.getOrt()); benutzerTemp.setEmail(benutzer.getEmail()); benutzerTemp.setKennung(benutzer.getKennung()); em.merge(benutzerTemp); return; } } ``` And the Controller class that calles the `update(Benutzer benutzer)` function in `saveBenutzerdaten()` right at the bottom of the code: BenutzerdatenController.java ``` @Controller @SessionAttributes("activeUser") public class LoginController { private BenutzerDao benutzerDao; private KundeDao kundeDao; private AnlageDao anlageDao; @Autowired public LoginController(BenutzerDao benutzerDao, KundeDao kundeDao, AnlageDao anlageDao){ this.benutzerDao = benutzerDao; this.kundeDao = kundeDao; this.anlageDao = anlageDao; } @ModelAttribute("activeUser") public Benutzer populateActiveUser() { return new Benutzer(); // Füllt activeUser beim ersten mall wenn es null ist. } @RequestMapping(value = "/login" ,method = RequestMethod.GET) public String login(Model model, SessionStatus status) { status.setComplete(); model.addAttribute("benutzerLoginDaten", new Login()); return "login"; } @RequestMapping(value = "/login" ,method = RequestMethod.POST) public String requestLogin( @Valid @ModelAttribute("benutzerLoginDaten") Login logindaten, BindingResult result, Model model, final RedirectAttributes redirectAttributes) { if (!result.hasErrors()) { if (logindaten == null) { String error = "Fehler beim login"; model.addAttribute("error", error); return "login"; } Benutzer user = null; try{ user = benutzerDao.findByKennung(logindaten.getKennung()); }catch(Exception e){ String error = "Unbekannter Benutzer"; model.addAttribute("error", error); return "login"; } if (user == null) { String error = "Unbekannter Benutzer"; model.addAttribute("error", error); return "login"; } String pw = user.getPasswort(); if (pw.equals(logindaten.getPasswort())) { redirectAttributes.addFlashAttribute("activeUser", user); return "redirect:/home.html"; } else { String error = "Passwort falsch"; model.addAttribute("error", error); return "login"; } } return "login"; } @RequestMapping(value = "/home",method = RequestMethod.GET) public String home(@ModelAttribute("activeUser") Benutzer activeUser ,Model model, final RedirectAttributes redirectAttributes){ if(activeUser == null){ return "redirect:/login.html"; } if(activeUser.getKennung()==null){ //falls activeUser == null, hat sich kein Benutzer eingelogt //und wird damit auf die loginseite weitergeleitet. return "redirect:/login.html"; } //erstellen der Anlagenliste mit dazugehörigem Kunden: //i und j werden zum mitzählen der schleifendurchläufe verwenden //sum zählt die benotigte größe für die Anlagenliste. (summe der anlagen aller kunden zu denen der benutzer zugriff hat) int i=0, j = 0, sum = 0; List<Kunde> kunden = activeUser.getKundenListe(); for(i = 0 ; i< kunden.size(); i++){ List<Anlage> anlagen = kundeDao.getAllAnlagen(kunden.get(i)); sum += anlagen.size(); } //auffüllen der attribute für select anlagenListe (beschreibung: anlagenbeschreibung, ids: anlagenids): String[] beschreibung = new String[sum]; BigInteger[] ids = new BigInteger[sum]; Select anlagenListe = new Select(); sum = 0; for(i = 0 ; i < kunden.size(); i++){ List<Anlage> anlagen = kundeDao.getAllAnlagen(kunden.get(i)); for(j = 0; j <anlagen.size(); j++){ //beschreibung format : Anlagenbezeichnung (kunde) beschreibung[sum] = ""+anlagen.get(j).getBezeichnung() + " (" + ((kunden.get(i).isFirma())? kunden.get(i).getFirmenname() : kunden.get(i).getPrivatperson_nachname() + " " + kunden.get(i).getPrivatperson_vorname()) + ")"; ids[sum++]= anlagen.get(j).getOid(); } } anlagenListe.setSelectOptions(beschreibung); anlagenListe.setIds(ids); model.addAttribute("activeUser", activeUser); model.addAttribute("selection", anlagenListe); return "home"; } @RequestMapping(value = "/home", method = RequestMethod.POST) public String selectAnlage(@Valid @ModelAttribute("selection") Select selection, BindingResult result, Model model) { if(!result.hasErrors()) { Anlage anlage = anlageDao.findById(selection.getSelectionOid()); System.out.println("anlage-- id: " + anlage.getOid() + " Bezeichnung: " + anlage.getBezeichnung()); return "home"; } return "home"; } @RequestMapping(value = "/benutzerdaten", method = RequestMethod.GET) public String benutzerdaten(@ModelAttribute("activeUser") Benutzer benutzer,Model model){ return "benutzerdaten"; } @RequestMapping(value = "/benutzerdaten", method = RequestMethod.POST) public String saveBenutzerdaten( @ModelAttribute("activeUser") Benutzer benutzer, Model model) { benutzerDao.update(benutzer); return "benutzerdaten"; } } ``` I've been looking for a solution for quite a long time now, and I've also found quite a lot of people having simular problems, but none of their solutions worked for me. I really hope someone finds the problem. Starting to get quite frustrated. Just ask If you need to see some more code or relevant data. Also, If you notice anything I should change, please tell me. I'm new to Spring and not sure I'm doing everything right. Especially with the way I handle the logged in User (probably not a good solution to save him in the DAO object?). --- I've found a solution. It worked fine after I added a service class and added to my mvc-dispatcher-servlet.xml. (sopro.mvc.swm.service is the package where I have my service classes).
2014/06/13
[ "https://Stackoverflow.com/questions/24210992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3723355/" ]
Windows Azure Storage supports geo-replication for Blobs, Tables and Queues. Data in the storage account is made durable by replicating transactions across different storage nodes in the same region (LRS) or a secondary region (GRS). GRS is the default redundancy option when creating a storage account. Refer to <http://blogs.msdn.com/b/windowsazurestorage/archive/2013/12/11/introducing-read-access-geo-replicated-storage-ra-grs-for-windows-azure-storage.aspx> for more details. If you want to build a custom backup solution then you could use the techniques suggested in the below 2 blogs 1) <http://blogs.msdn.com/b/windowsazurestorage/archive/2010/04/30/protecting-your-blobs-against-application-errors.aspx> 2) <http://blogs.msdn.com/b/windowsazurestorage/archive/2010/05/03/protecting-your-tables-against-application-errors.aspx>
I am not sure of the exact use case of why you need to backup azure table and blob. You can backup All the above services without downtime; might be there would be slight glitch or bottleneck performance with SQL database durning back. The single shot answer is to write a custom script which would read the data from azure table ( or SQL database, or the required service ) make a archive (packaging) and store it back. The important thing to note here is where would storage backups, broadly speaking generally store the archives in blob. In this case you have thing where you would be storing, if you are storing on-premises you need calculate upon the storage locally, out bandwidth cost and latency of the data transfer from azure. PS : cloud storage by itself has good leave of availability and durability, you further improve these factors by enabling geo-replication
17,603,701
I have some items that I want to show to the user in a WPF window, but I want to hide the details of each item until the user selects/expands the item. I'd like to achieve Windows-Explorer-esque functionality, where the item Header is always displayed, and the item Details (as an `ItemsControl`) are displayed when the user clicks on the item's arrow. *Is there an obvious way to do this?* Or am I going to have to whip out a custom control?
2013/07/11
[ "https://Stackoverflow.com/questions/17603701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1964319/" ]
It can be done using `System.XML.Linq;` ``` var xmlDoc = xDocument.Load("text.xml"); var items = xmlDoc.Element("values").Elements("Item").Select(i => new { ID = i.Attribute("ID").Value, Type = i.Attribute("Type").Value, Value = i.Attribute("Value").Value }); foreach(var _item in items) { //write your logic } ```
``` var doc = XDocument.Parse("<xml . ../>"); foreach (var item in doc.Element("Values").Elements("Item").OrderBy(x=>x.Attribute("ID").Value)) { var type = item.Attribute("Type").Value; if (type=="Notification") { // processing code here } } ```
66,545,950
I am trying to label the outliers in my boxplot using the text function so I can find out from which class the outliers are coming from. I've stored the rownames of my data in variable "rownames" using names(vehData) to get the row names. When I apply this however, I get an error. ERROR: **Error in which(removeOutliers1 == bxpdat$out, arr.ind = TRUE) : 'list' object cannot be coerced to type 'double'** Completely new to R programming. Completely not sure how to fix this or what I am doing wrong Thanks in advance for any help! ``` library(reshape2) vehData <- structure( list( Samples = 1:6, Comp = c(95L, 91L, 104L, 93L, 85L, 107L), Circ = c(48L, 41L, 50L, 41L, 44L, 57L), D.Circ = c(83L, 84L, 106L, 82L, 70L, 106L), Rad.Ra = c(178L, 141L, 209L, 159L, 205L, 172L), Pr.Axis.Ra = c(72L, 57L, 66L, 63L, 103L, 50L), Max.L.Ra = c(10L, 9L, 10L, 9L, 52L, 6L), Scat.Ra = c(162L, 149L, 207L, 144L, 149L, 255L), Elong = c(42L, 45L, 32L, 46L, 45L, 26L), Pr.Axis.Rect = c(20L, 19L, 23L, 19L, 19L, 28L), Max.L.Rect = c(159L, 143L, 158L, 143L, 144L, 169L), Sc.Var.Maxis = c(176L, 170L, 223L, 160L, 241L, 280L), Sc.Var.maxis = c(379L, 330L, 635L, 309L, 325L, 957L), Ra.Gyr = c(184L, 158L, 220L, 127L, 188L, 264L), Skew.Maxis = c(70L, 72L, 73L, 63L, 127L, 85L), Skew.maxis = c(6L, 9L, 14L, 6L, 9L, 5L), Kurt.maxis = c(16L, 14L, 9L, 10L, 11L, 9L), Kurt.Maxis = c(187L, 189L, 188L, 199L, 180L, 181L), Holl.Ra = c(197L, 199L, 196L, 207L, 183L, 183L), Class = c("van", "van", "saab", "van", "bus", "bus") ), row.names = c(NA, 6L), class = "data.frame") #Remove outliers removeOutliers <- function(data) { OutVals <- boxplot(data)$out remOutliers <- sapply(data, function(x) x[!x %in% OutVals]) return (remOutliers) } vehDataRemove1 <- vehData[, -1] vehDataRemove2 <- vehDataRemove1[,-19] vehData <- vehDataRemove2 vehClass <- vehData$Class rownames <- names(vehData) #column names #Begin removing outliers removeOutliers1 <- removeOutliers(vehData) bxpdat <- boxplot(removeOutliers1) #Also tried using vehicles$Class instead of rownames but get the same error text(bxpdat$group, bxpdat$out, rownames[which(removeOutliers1 == bxpdat$out, arr.ind = TRUE)[,1]], pos = 4) ``` The boxplot looks like this. I am trying to label the outliers based on the x axis e.g. "Comp", "Circ", "D.Circ", "Rad.Ra", "Max.L.Ra" etc.. & by vehicle class "Van", "Bus" .. [![enter image description here](https://i.stack.imgur.com/AtAMe.png)](https://i.stack.imgur.com/AtAMe.png) Crammed text issue when identifying class [![enter image description here](https://i.stack.imgur.com/hB6ks.png)](https://i.stack.imgur.com/hB6ks.png)
2021/03/09
[ "https://Stackoverflow.com/questions/66545950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14723580/" ]
If it is the outliers in the 2nd boxplot, it would be: ``` bxpdat <- boxplot(removeOutliers1) text(bxpdat$group, bxpdat$out, bxpdat$names[bxpdat$group], pos = 4) ``` [![enter image description here](https://i.stack.imgur.com/m4bor.png)](https://i.stack.imgur.com/m4bor.png) Maybe looks better like this, if you adjust the margin and flip the labels: ``` par(mar=c(8,3.5,3.5,3.5)) bxpdat = boxplot(removeOutliers1,las=2,cex=0.5) text(bxpdat$group, bxpdat$out, bxpdat$names[bxpdat$group], pos = 4,cex=0.5) ``` [![enter image description here](https://i.stack.imgur.com/j1yWf.png)](https://i.stack.imgur.com/j1yWf.png)
I understood the question differently to @StupidWolf. I thought the goal was to replace points indicating outliers with the text of the vehicle class (bus, van or saab). If you simply print the variable name (e.g. Skew.maxis), then you might as well have simply plotted the outliers as points. Unless I'm missing something. Here is code to answer the question as I understood it, for what it's worth (beginning after defining `removeOutliers`): ``` # CHANGE: Create vehClass vector before removing Class from the dataframe vehClass <- vehData$Class vehDataRemove1 <- vehData[, -1] vehDataRemove2 <- vehDataRemove1[,-19] vehData <- vehDataRemove2 #Begin removing outliers removeOutliers1 <- removeOutliers(vehData) bxpdat <- boxplot(removeOutliers1) # use boxplot(vehData) if you plot all the outliers as points # loop over columns n_plot <- 1; set.seed(123) # only plot n_plot randomly-chosen outliers for(i in 1:ncol(vehData)){ # find out which row indices were removed as outliers diffInd <- which(vehData[[i]] %in% setdiff(vehData[[i]], removeOutliers1[[i]])) # if none were, then don't add any outlier text if(length(diffInd) == 0) next print(i) print(paste0("l:", length(diffInd))) if(length(diffInd) > n_plot){ diffIndPlot <- sample(diffInd, n_plot, replace = FALSE) } else diffIndPlot <- diffInd text(x = i, y = vehData[[i]][diffIndPlot], labels = paste0(vehClass[diffIndPlot], ": ", vehData[[i]][diffIndPlot])) } ```
26,663,208
I have an image database. With an image table with two `bytea` columns. I would like to query the table and see these columns to be able to see whether or not these entries are storing images or not. As they are nullable columns. Currently when I query the DB using psql command line, my whole command line screen goes blank trying to display the bytea. I've googled around for a while now and can't find a way to display the table suitably. Ideally the first 'x' characters would display. I can confirm that the bytea will print if small enough by uploading a tiny tiny picture. This is what I see when I do: `SELECT * FROM Image;` ![my view when querying this table](https://i.stack.imgur.com/xUknR.png)
2014/10/30
[ "https://Stackoverflow.com/questions/26663208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2743131/" ]
you can use the `encode` function: ``` select encode(bytea_column, 'hex') from image; ``` If you only want to see the first bytes, just use the `left()` function on that: ``` select left(encode(bytea_column, 'hex'), 40) from image; ``` More details in the manual: <http://www.postgresql.org/docs/current/static/functions-binarystring.html>
You can toggle expanded formatting mode with the following command ``` \x ```
26,663,208
I have an image database. With an image table with two `bytea` columns. I would like to query the table and see these columns to be able to see whether or not these entries are storing images or not. As they are nullable columns. Currently when I query the DB using psql command line, my whole command line screen goes blank trying to display the bytea. I've googled around for a while now and can't find a way to display the table suitably. Ideally the first 'x' characters would display. I can confirm that the bytea will print if small enough by uploading a tiny tiny picture. This is what I see when I do: `SELECT * FROM Image;` ![my view when querying this table](https://i.stack.imgur.com/xUknR.png)
2014/10/30
[ "https://Stackoverflow.com/questions/26663208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2743131/" ]
you can use the `encode` function: ``` select encode(bytea_column, 'hex') from image; ``` If you only want to see the first bytes, just use the `left()` function on that: ``` select left(encode(bytea_column, 'hex'), 40) from image; ``` More details in the manual: <http://www.postgresql.org/docs/current/static/functions-binarystring.html>
If you are not trying to interpret binary data yourself, why not just do: ``` select length(img1), length(img2) from Image ``` or ``` select img1 is null, img2 is null from Image ```
58,440,839
I want to recreate the same design as the second image below using CSS grid. I got a problem with the alignment, of course because of the two spans the inputs are not aligned like they should be. I am almost there with CSS grid but i can't figure it out. Is there a way to do it with grid or is there another solution for this? [![Render in react](https://i.stack.imgur.com/fVANo.png)](https://i.stack.imgur.com/fVANo.png) [![Adobe xd design](https://i.stack.imgur.com/WCJM0.png)](https://i.stack.imgur.com/WCJM0.png) ``` <div className="grade-card"> <div className="grade-card-header"> <span className="title">{this.props.title}</span> </div> <div className="grade-card-body"> <div className="grade-input"> <span>I</span> <input type="text"/> <span>1x</span> </div> <div className="grade-input"> <span>I</span> <input type="text"/> <span>Min</span> </div> <div className="grade-input"> <span>I</span> <input type="text"/> <span>1x</span> </div> <div className="grade-input"> <span>I</span> <input type="text"/> </div> <div className="grade-input"> <span>I</span> <input type="text"/> </div> <div className="grade-input"> <input type="text"/> </div> </div> </div> ``` ``` .grade-card{ width: 349px; height: 384px; background-color: white; border-radius: 28px; .grade-card-header{ display: flex; align-items: center; justify-content: center; height: 20%; border-radius: 28px 28px 0 0; background-color: #1089FF; .title{ color: white; font-size: 1.5em; } } .grade-card-body{ height: 80%; cursor: pointer; display: grid; grid-template-columns: repeat(2, 174.5px); grid-template-rows: repeat(3, 102.4px); justify-items: center;//horizontally align-items: center;//vertically input{ outline: none; width: 74px; height: 51px; border: 1px solid #707070; border-radius: 6px; font-size: 1.3em; text-align: center; } .grade-input:last-child{ input{ width: 117px; height: 69px; } } } } ```
2019/10/17
[ "https://Stackoverflow.com/questions/58440839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9043877/" ]
This is a little of a variation on @Brice's answer, because in his version: 1. you need to adjust for each variation of the label text 2. if the font is rendered different, it will break (zoom, differences between platforms, etc). This version solves it, but the idea to use absolute positioning to escape the flow is the same. ```css /*********** begin changes **********/ .grade-input { position: relative; } .label { position: absolute; top: 50%; } .label-left { transform: translate(calc(-100% - 6px), -50%); } .label-right { transform: translate(6px, -50%); } /*********** end changes **********/ .grade-card { width: 349px; height: 384px; background-color: white; border-radius: 28px; } .grade-card .grade-card-header { display: flex; align-items: center; justify-content: center; height: 20%; border-radius: 28px 28px 0 0; background-color: #1089ff; } .grade-card .grade-card-header .title { color: white; font-size: 1.5em; } .grade-card .grade-card-body { height: 80%; cursor: pointer; display: grid; grid-template-columns: repeat(2, 174.5px); grid-template-rows: repeat(3, 102.4px); justify-items: center; align-items: center; } .grade-card .grade-card-body input { outline: none; width: 74px; height: 51px; border: 1px solid #707070; border-radius: 6px; font-size: 1.3em; text-align: center; } .grade-card .grade-card-body .grade-input:last-child input { width: 117px; height: 69px; } ``` ```html <div class="grade-card"> <div class="grade-card-header"> <span class="title">{this.props.title}</span> </div> <div class="grade-card-body"> <div class="grade-input"> <span class="label label-left">I</span> <input type="text"/> <span class="label label-right">1x</span> </div> <div class="grade-input"> <span class="label label-left">I</span> <input type="text"/> <span class="label label-right">Min</span> </div> <div class="grade-input"> <span class="label label-left">I</span> <input type="text"/> <span class="label label-right">1x</span> </div> <div class="grade-input"> <span class="label label-left">I</span> <input type="text"/> </div> <div class="grade-input"> <span class="label label-left">I</span> <input type="text"/> </div> <div class="grade-input"> <input type="text"/> </div> </div> </div> ```
Because the spans are different values, your `.grade-input` divs are becoming different widths and that is throwing off your alignment. EDITED to get inputs aligned exactly centered: If you make the spans `position: absolute;`, then you would be able to just align the inputs. Try below HTML: ``` <div className="grade-card"> <div className="grade-card-header"> <span className="title">{this.props.title}</span> </div> <div className="grade-card-body"> <div className="grade-input"> <span className="left-absolute">I</span> <input type="text"/> <span className="right-absolute oneX">1x</span> </div> <div className="grade-input"> <span className="left-absolute">I</span> <input type="text"/> <span className="right-absolute min">Min</span> </div> <div className="grade-input"> <span className="left-absolute">I</span> <input type="text"/> <span className="right-absolute oneX">1x</span> </div> <div className="grade-input"> <span className="left-absolute">I</span> <input type="text"/> </div> <div className="grade-input"> <span className="left-absolute">I</span> <input type="text"/> </div> <div className="grade-input"> <input type="text"/> </div> </div> </div> ``` Add below to your css file: ``` .grade-input { position: relative; } .left-absolute { position: absolute; left: -7px; top: 20px; } .right-absolute.oneX { position: absolute; right: -15px; top: 20px; } .right-absolute.min { position: absolute; right: -27px; top: 20px; } ```
71,755,708
How can I do something like `select * from T1 inner join T2 on (T1.ID=T2.ID OR T1.ID2=T2.ID)` When I execute this code, it seems to fall in a infinity loop so I guess I'm wrong. In other words, how can I match one of two columns from T1 to one column from T2 T1 ``` ID ID2 1 10 2 20 ``` T2 ``` ID value 1 dummy10 20 dummy20 ``` Result ``` ID ID2 value 1 10 dummy10 2 20 dummy20 ```
2022/04/05
[ "https://Stackoverflow.com/questions/71755708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13346068/" ]
You ***cannot*** reference an Object *parent* that way (Object(value) ← Array ← Object), and not even from an Object's parent Object. What you can do instead is: * Create two **Classes**, one for the parent and one for the child. * When adding a child to the parent, just make a *"linked list"*, by referencing the parent's `this` to the created child item `parent` property ```js class Child { constructor(data) { Object.assign(this, data); } get url() { return this.parent.urlParent + this.section } } class Parent { constructor(data) { Object.assign(this, data); this.subItems = []; } addChild(item) { this.subItems.push(new Child({...item, parent: this})); } } // Example: const parent = new Parent({id:1, name:"Home", urlParent:"/home"}); parent.addChild({subId:1, name:"Project 1", section:"#project1"}); console.log(parent.subItems[0].url) // /home#project1; ``` ### But hey! Nodes and trees Your original idea and the above use too much complexity. What I'd suggest is to treat all parent, child, whatever, as **Page Nodes**. ```js class Page { constructor(data) { Object.assign(this, data); this.children = {}; } addChild(page) { page.parent = this; // Linked to parent! this.children[page.id] = page; } get url() { // Generate full URI by recursing the parents tree return this.parent ? `${this.parent.url}/${this.slug}` : this.slug; } } // Example: // 1. Create pages: const pageRoot = new Page({id:1, name:"Home page", slug:""}); const pageProj = new Page({id:3, name:"All projects", slug:"projects"}); const pageWebs = new Page({id:4, name:"Websites", slug:"websites"}); const pageStOv = new Page({id:6, name:"Stack Overflow", slug:"so"}); const pageSpec = new Page({id:9, name:"Stack Overflow Specs", slug:"specs"}); // 2. Create Tree: pageRoot.addChild(pageProj); pageProj.addChild(pageWebs); pageWebs.addChild(pageStOv); pageStOv.addChild(pageSpec); // 3. Test console.log(pageRoot.url); // ""; console.log(pageProj.url); // "/projects"; console.log(pageSpec.url); // "/projects/websites/so/specs"; console.log(pageRoot); ```
``` const linkItems = [ { id: 1, name: 'Home Page', urlParent: '/home', get subItems(){ console.log(this.name); return ([ (() => { console.log(this); return { subId: 1, name: 'Project 1', section: '#project1', urlParentFromOuterScope: () => { return this.urlParent; }, sectionString(){ return this.section; }, url(){ console.log('url', this); return this.urlParentFromOuterScope() + this.sectionString(); } } })() ]) } } ]; const subItems = linkItems[0].subitems; console.log(linkItems[0].subItems[0].url()); ``` Please feel free to remove the unnecessary 'console.log's after you understand the approach. I took the liberty of adding a few methods. This is a tricky one and has to do with the scope of this in array functions. P.S.: I guess this can be simplified.
2,927,194
I have following query: ``` var result = ( from role in db.Roles join user in db.Users on role.RoleID equals user.RoleID where user.CreatedByUserID == userID orderby user.FirstName ascending select new UserViewModel { UserID = user.UserID, PhotoID = user.PhotoID.ToString(), FirstName = user.FirstName, LastName = user.LastName, FullName = user.FirstName + " " + user.LastName, Email = user.Email, PhoneNumber = user.Phone, AccessLevel = role.Name }); ``` Now, I need to modify this query... Other table I have is table Deals. I would like to count how many deals user created last month and last year. I tried something like this: ``` var result = ( from role in db.Roles join user in db.Users on role.RoleID equals user.RoleID //join dealsYear in db.Deals on date.Year equals dealsYear.DateCreated.Year join dealsYear in ( from deal in db.Deals group deal by deal.DateCreated into d select new { DateCreated = d.Key, dealsCount = d.Count() } ) on date.Year equals dealsYear.DateCreated.Year into dYear join dealsMonth in ( from deal in db.Deals group deal by deal.DateCreated into d select new { DateCreated = d.Key, dealsCount = d.Count() } ) on date.Month equals dealsMonth.DateCreated.Month into dMonth where user.CreatedByUserID == userID orderby user.FirstName ascending select new UserViewModel { UserID = user.UserID, PhotoID = user.PhotoID.ToString(), FirstName = user.FirstName, LastName = user.LastName, FullName = user.FirstName + " " + user.LastName, Email = user.Email, PhoneNumber = user.Phone, AccessLevel = role.Name, DealsThisYear = dYear, DealsThisMonth = dMonth }); ``` but here is even syntax not correct. Any idea? Btw, is there any good book of LINQ to SQL with examples?
2010/05/28
[ "https://Stackoverflow.com/questions/2927194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/168535/" ]
I think found solution [here](https://stackoverflow.com/questions/2767143/linq-join-with-count): ``` var result = ( from role in db.Roles join user in db.Users on role.RoleID equals user.RoleID join deal in db.Deals on user.UserID equals deal.SalesAgentID into deals where user.CreatedByUserID == userID orderby user.FirstName ascending select new UserViewModel { UserID = user.UserID, PhotoID = user.PhotoID.ToString(), FirstName = user.FirstName, LastName = user.LastName, FullName = user.FirstName + " " + user.LastName, Email = user.Email, PhoneNumber = user.Phone, AccessLevel = role.Name, DealsThisYear = deals.Where(deal => deal.DateCreated.Year == date.Year).Count() }); ```
If you would [create an association](http://msdn.microsoft.com/en-us/library/bb629295.aspx), you could write the query as ``` IQueryable<UserViewModel> result = from user in db.Users where user.CreatedByUserID == userID orderby user.FirstName ascending select new UserViewModel { UserID = user.UserID, PhotoID = user.PhotoID.ToString(), FirstName = user.FirstName, LastName = user.LastName, FullName = user.FirstName + " " + user.LastName, Email = user.Email, PhoneNumber = user.Phone, AccessLevel = user.Role.Name, DealsThisYear = user.Deals .Where(deal => deal.DateCreated.Year == date.Year).Count() }); ```
46,197,841
I have a little problem using findAll in my component. It concerns the value it returns at the end. ``` users: Ember.computed(function() { return this.get('store').findAll('user'); }), ``` In my case, I want to get the name of the first object. So in my handlebar: ``` users.firstObject.name ``` 'users' is a class in this case. But I'm trying to return directly the first object in the property, like this: ``` user: Ember.computed(function() { return this.get('store').findAll('user') .then(function(user){ return user.get('firstObject'); }); }), ``` But in this case, in my handlebar, user.name is undefined and user is a promise. There is something I can't understand with promises, how they work ... Can somebody help me to get the correct user without using 'firstObject' on my users ? Thanks in advance !
2017/09/13
[ "https://Stackoverflow.com/questions/46197841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6358270/" ]
`this.customer` is an array not an object. access the `customer_delivery_city_address` property by index. ``` this.cus_city = this.customer[0].customer_delivery_city_address; console.log("City Address: " +this.cus_city) ```
I would do it in this way. ``` customer: any; getCustomer() { return this.http.get('url').map((res: Response) => res.json()); } loadCustomer(){ this.customer = []; this.getCustomer().subscribe(d => { for (var i = 0; i < d.length; i++) { this.customer.push(d[i]); } }, err => {console.log(err)}) } ``` //in view ``` <div *ngFor="let c of customer"> {{c.customer_delivery_city_address}} </div> ``` You are tring to do **this.customer.customer\_delivery\_city\_address** when **this.customer** is an array, if you want the first element out you can do **this.customer = data.customer[0]**. ``` <div> {{customer.customer_delivery_city_address}} </div> ```
46,197,841
I have a little problem using findAll in my component. It concerns the value it returns at the end. ``` users: Ember.computed(function() { return this.get('store').findAll('user'); }), ``` In my case, I want to get the name of the first object. So in my handlebar: ``` users.firstObject.name ``` 'users' is a class in this case. But I'm trying to return directly the first object in the property, like this: ``` user: Ember.computed(function() { return this.get('store').findAll('user') .then(function(user){ return user.get('firstObject'); }); }), ``` But in this case, in my handlebar, user.name is undefined and user is a promise. There is something I can't understand with promises, how they work ... Can somebody help me to get the correct user without using 'firstObject' on my users ? Thanks in advance !
2017/09/13
[ "https://Stackoverflow.com/questions/46197841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6358270/" ]
I think the response which is coming is an array. You should try this: ``` this.customer[0].customer_delivery_city_address ```
I would do it in this way. ``` customer: any; getCustomer() { return this.http.get('url').map((res: Response) => res.json()); } loadCustomer(){ this.customer = []; this.getCustomer().subscribe(d => { for (var i = 0; i < d.length; i++) { this.customer.push(d[i]); } }, err => {console.log(err)}) } ``` //in view ``` <div *ngFor="let c of customer"> {{c.customer_delivery_city_address}} </div> ``` You are tring to do **this.customer.customer\_delivery\_city\_address** when **this.customer** is an array, if you want the first element out you can do **this.customer = data.customer[0]**. ``` <div> {{customer.customer_delivery_city_address}} </div> ```
45,086,903
I have the following code block that basically checks for the existance of a entity in the DB and loads it to context for updating or in case it does not exist adds the new entity. ``` using (var db = new Entities.DB.DConn()) { //... foreach (Account account in accounts) { bool isNewRecord = false; Entities.DB.Account dlAccount = new Entities.DB.Account(); Entities.DB.Account exisitngAcct = db.Accounts.Where(x => x.GId == dlG.Id).FirstOrDefault(); //x.GId is NOT ad primary key if (exisitngAcct != null) { dlAccount = exisitngAcct; isNewRecord = true; } dlAccount.GId = dlG.Id; dlAccount.AccountName = account.NameAtFI; dlAccount.AccountNumber = account.AcctNumber; dlAccount.AcctType = account.AcctType; dlAccount.AsOfDate = account.DateCreated; dlAccount.IsDeleted = false; dlAccount.DateModified = DateTime.UtcNow.ToUniversalTime(); if (isNewRecord) { dldb.Accounts.Add(dlAccount); } db.SaveChanges(); } } ``` I have been doing loads of research on attaching entities to context and using EntityState, but i'm just not getting how that code would be written in my example. Is there any way someone can help to show me a better more efficient way to perform the same operation as above? I'm fairly new to EF and want to make sure that i am working with it properly. Thanks for any help you can provide.
2017/07/13
[ "https://Stackoverflow.com/questions/45086903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1034022/" ]
Working with disconnected entities has been left by the designers of the EF for the developers using it. Thus there is no "proper" way - everything depends on the usage case and the entity model. Since you seem to be forcing update of the existing records (by setting the `DateModified` to DateTime.UtcNow), there is no need to load the existing data into context. It would be sufficient to get the existing entity PKs with single database trip and use it as criteria for add or update: ``` using (var db = new Entities.DB.DConn()) { //... var accountIds = accounts.Select(x => x.GId); // variable required by EF6 Contains translation var existingAccountIds = new HashSet<GId_Type>( db.Accounts.Where(x => accountIds.Contains(x.GId).Select(x => x.GId)); foreach (Account account in accounts) { var dlAccount = new Entities.DB.Account(); dlAccount.GId = account.GId; dlAccount.AccountName = account.NameAtFI; dlAccount.AccountNumber = account.AcctNumber; dlAccount.AcctType = account.AcctType; dlAccount.AsOfDate = account.DateCreated; dlAccount.IsDeleted = false; dlAccount.DateModified = DateTime.UtcNow.ToUniversalTime(); if (existingAccountIds.Contains(dlAccount.GId)) db.Entry(dlAccount).State = EntityState.Modified; // update else db.Accounts.Add(dlAccount); // insert } db.SaveChanges(); } ``` (replace the `GId_Type` with the type of the `GId`, e.g. `int`, `Guid` etc.) This, along with moving the `SaveChanges` outside the loop should give you the best performance for this scenario.
There is some way to improve performance. By example, using @Ivan solution to retrieve more than one account at a time to reduce the number of database round-trip However, the SaveChanges methods will still make one database round-trip for every entity you need to Add or Update which is **INSANELY** slow. --- **Disclaimer**: I'm the owner of the project [Entity Framework Extensions](http://entityframework-extensions.net/) This library is not free. But it is the most efficient way to perform a upsert operation. In addition of Bulk Merge (Upsert), this library allows you to perform all bulk operations: * BulkSaveChanges * BulkInsert * BulkUpdate * BulkDelete * BulkMerge * BulkSynchronize Example: ``` // Easy to use context.BulkSaveChanges(); // Easy to customize context.BulkSaveChanges(bulk => bulk.BatchSize = 100); // Perform Bulk Operations context.BulkDelete(customers); context.BulkInsert(customers); context.BulkUpdate(customers); // Customize Primary Key context.BulkMerge(customers, operation => { operation.ColumnPrimaryKeyExpression = customer => customer.Code; }); ```
45,086,903
I have the following code block that basically checks for the existance of a entity in the DB and loads it to context for updating or in case it does not exist adds the new entity. ``` using (var db = new Entities.DB.DConn()) { //... foreach (Account account in accounts) { bool isNewRecord = false; Entities.DB.Account dlAccount = new Entities.DB.Account(); Entities.DB.Account exisitngAcct = db.Accounts.Where(x => x.GId == dlG.Id).FirstOrDefault(); //x.GId is NOT ad primary key if (exisitngAcct != null) { dlAccount = exisitngAcct; isNewRecord = true; } dlAccount.GId = dlG.Id; dlAccount.AccountName = account.NameAtFI; dlAccount.AccountNumber = account.AcctNumber; dlAccount.AcctType = account.AcctType; dlAccount.AsOfDate = account.DateCreated; dlAccount.IsDeleted = false; dlAccount.DateModified = DateTime.UtcNow.ToUniversalTime(); if (isNewRecord) { dldb.Accounts.Add(dlAccount); } db.SaveChanges(); } } ``` I have been doing loads of research on attaching entities to context and using EntityState, but i'm just not getting how that code would be written in my example. Is there any way someone can help to show me a better more efficient way to perform the same operation as above? I'm fairly new to EF and want to make sure that i am working with it properly. Thanks for any help you can provide.
2017/07/13
[ "https://Stackoverflow.com/questions/45086903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1034022/" ]
Working with disconnected entities has been left by the designers of the EF for the developers using it. Thus there is no "proper" way - everything depends on the usage case and the entity model. Since you seem to be forcing update of the existing records (by setting the `DateModified` to DateTime.UtcNow), there is no need to load the existing data into context. It would be sufficient to get the existing entity PKs with single database trip and use it as criteria for add or update: ``` using (var db = new Entities.DB.DConn()) { //... var accountIds = accounts.Select(x => x.GId); // variable required by EF6 Contains translation var existingAccountIds = new HashSet<GId_Type>( db.Accounts.Where(x => accountIds.Contains(x.GId).Select(x => x.GId)); foreach (Account account in accounts) { var dlAccount = new Entities.DB.Account(); dlAccount.GId = account.GId; dlAccount.AccountName = account.NameAtFI; dlAccount.AccountNumber = account.AcctNumber; dlAccount.AcctType = account.AcctType; dlAccount.AsOfDate = account.DateCreated; dlAccount.IsDeleted = false; dlAccount.DateModified = DateTime.UtcNow.ToUniversalTime(); if (existingAccountIds.Contains(dlAccount.GId)) db.Entry(dlAccount).State = EntityState.Modified; // update else db.Accounts.Add(dlAccount); // insert } db.SaveChanges(); } ``` (replace the `GId_Type` with the type of the `GId`, e.g. `int`, `Guid` etc.) This, along with moving the `SaveChanges` outside the loop should give you the best performance for this scenario.
We can make Ivan's answer even better performing using upserting (updating or inserting) all the accounts in one call. I'm using Free package named EFCore.BulkExtensions that includes BulkInsertOrUpdate(list) method: <https://github.com/borisdj/EFCore.BulkExtensions> (This package is listed in Microsoft ef extensions page: <https://learn.microsoft.com/en-us/ef/core/extensions/>) Ivans code with ONE upsert call for all accounts: ``` using (var db = new Entities.DB.DConn()) { //... var accountIds = accounts.Select(x => x.GId); // variable required by EF6 Contains translation var existingAccountIds = new HashSet<GId_Type>( db.Accouns.Where(x => accountIds.Contains(x.GId).Select(x => x.GId)); var dlAccounts = new List<Entities.DB.Account>(); foreach (Account account in accounts) { var dlAccount = new Entities.DB.Account(); dlAccount.GId = account.GId; dlAccount.AccountName = account.NameAtFI; dlAccount.AccountNumber = account.AcctNumber; dlAccount.AcctType = account.AcctType; dlAccount.AsOfDate = account.DateCreated; dlAccount.IsDeleted = false; dlAccount.DateModified = DateTime.UtcNow.ToUniversalTime(); //Add the updated account to a list dlAccounts.Add(dlAccount); } //upsert dlAccounts in ONE call db.BulkInsertOrUpdate(dlAccounts); db.SaveChanges(); } ``` Note: BulkInsertOrUpdate assuming that the account has a primary key set. in the above example it is probably AccountNumber.
45,086,903
I have the following code block that basically checks for the existance of a entity in the DB and loads it to context for updating or in case it does not exist adds the new entity. ``` using (var db = new Entities.DB.DConn()) { //... foreach (Account account in accounts) { bool isNewRecord = false; Entities.DB.Account dlAccount = new Entities.DB.Account(); Entities.DB.Account exisitngAcct = db.Accounts.Where(x => x.GId == dlG.Id).FirstOrDefault(); //x.GId is NOT ad primary key if (exisitngAcct != null) { dlAccount = exisitngAcct; isNewRecord = true; } dlAccount.GId = dlG.Id; dlAccount.AccountName = account.NameAtFI; dlAccount.AccountNumber = account.AcctNumber; dlAccount.AcctType = account.AcctType; dlAccount.AsOfDate = account.DateCreated; dlAccount.IsDeleted = false; dlAccount.DateModified = DateTime.UtcNow.ToUniversalTime(); if (isNewRecord) { dldb.Accounts.Add(dlAccount); } db.SaveChanges(); } } ``` I have been doing loads of research on attaching entities to context and using EntityState, but i'm just not getting how that code would be written in my example. Is there any way someone can help to show me a better more efficient way to perform the same operation as above? I'm fairly new to EF and want to make sure that i am working with it properly. Thanks for any help you can provide.
2017/07/13
[ "https://Stackoverflow.com/questions/45086903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1034022/" ]
We can make Ivan's answer even better performing using upserting (updating or inserting) all the accounts in one call. I'm using Free package named EFCore.BulkExtensions that includes BulkInsertOrUpdate(list) method: <https://github.com/borisdj/EFCore.BulkExtensions> (This package is listed in Microsoft ef extensions page: <https://learn.microsoft.com/en-us/ef/core/extensions/>) Ivans code with ONE upsert call for all accounts: ``` using (var db = new Entities.DB.DConn()) { //... var accountIds = accounts.Select(x => x.GId); // variable required by EF6 Contains translation var existingAccountIds = new HashSet<GId_Type>( db.Accouns.Where(x => accountIds.Contains(x.GId).Select(x => x.GId)); var dlAccounts = new List<Entities.DB.Account>(); foreach (Account account in accounts) { var dlAccount = new Entities.DB.Account(); dlAccount.GId = account.GId; dlAccount.AccountName = account.NameAtFI; dlAccount.AccountNumber = account.AcctNumber; dlAccount.AcctType = account.AcctType; dlAccount.AsOfDate = account.DateCreated; dlAccount.IsDeleted = false; dlAccount.DateModified = DateTime.UtcNow.ToUniversalTime(); //Add the updated account to a list dlAccounts.Add(dlAccount); } //upsert dlAccounts in ONE call db.BulkInsertOrUpdate(dlAccounts); db.SaveChanges(); } ``` Note: BulkInsertOrUpdate assuming that the account has a primary key set. in the above example it is probably AccountNumber.
There is some way to improve performance. By example, using @Ivan solution to retrieve more than one account at a time to reduce the number of database round-trip However, the SaveChanges methods will still make one database round-trip for every entity you need to Add or Update which is **INSANELY** slow. --- **Disclaimer**: I'm the owner of the project [Entity Framework Extensions](http://entityframework-extensions.net/) This library is not free. But it is the most efficient way to perform a upsert operation. In addition of Bulk Merge (Upsert), this library allows you to perform all bulk operations: * BulkSaveChanges * BulkInsert * BulkUpdate * BulkDelete * BulkMerge * BulkSynchronize Example: ``` // Easy to use context.BulkSaveChanges(); // Easy to customize context.BulkSaveChanges(bulk => bulk.BatchSize = 100); // Perform Bulk Operations context.BulkDelete(customers); context.BulkInsert(customers); context.BulkUpdate(customers); // Customize Primary Key context.BulkMerge(customers, operation => { operation.ColumnPrimaryKeyExpression = customer => customer.Code; }); ```
59,996,448
I run Google Ads on my Google-App-Engine-hosted website (www.bigriddles.com), and they tell me I need to have an "ads.txt" file served from the root domain (i.e. <http://bigriddles.com/ads.txt>, as opposed to <http://www.bigriddles.com/ads.txt>). My DNS is hosted on Gandi, and I created their "ALIAS" record (which I think just does CNAME flattening or something similar) to alias "bigriddles.com" to "ghs.googlehosted.com." I chose "ghs.googlehosted.com" because that's what I CNAMEd "www.bigriddles.com" to (many years back), and that CNAME has been working fine. However, now when I visit "bigriddles.com", I get an "HTTP 301 Moved" to "www.bigriddles.com", and as far as I can tell, this response isn't coming from any code I wrote (I've looked through my code and don't see anything that would redirect this). Furthermore, there is a "Server: ghs" header in the response from "bigriddles.com", whereas if I visit "www.bigriddles.com", which works fine, the response includes the header "Server: Google Frontend". I'm not sure if there is some hint of my problem in the difference between those two Server headers. Anyway, I'm not sure exactly what's going wrong. It could be a DNS issue. I say this because "dig www.bigriddles.com" comes back with the IP 172.217.14.115, whereas "dig bigriddles.com" comes back with "172.217.168.211", so maybe one of these really is a "ghs" server and the other is a "Google Frontend" server (I'm not sure the difference) and this "ALIAS" DNS solution just isn't going to work. More likely though I feel like maybe there is just some settings problem with my App itself where it's not set up to allow the apex domain "bigriddles.com", and if I change that setting it will start working? I have gone through the steps on <https://cloud.google.com/appengine/docs/standard/python/mapping-custom-domains>. When I view the "Custom Domains" for my project, I see "www.bigriddles.com" and "m.bigriddles.com", but I don't see the naked domain "bigriddles.com". However, when I try to add it on that page, it tells me that "bigriddles.com" is already mapped to a project, so I'm not sure what to make of that. Any help would be appreciated, thank you!
2020/01/31
[ "https://Stackoverflow.com/questions/59996448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12816973/" ]
`Object.keys` returns an array. You can iterate the array to build a new string, or simply join it: `categories += options.join('<br>')` **EDIT:** There are a few errors in your code that are preventing this from working: 1. Only have one onclick attribute on your button: `onclick="showCategories()"` 2. The option value for Desserts needs to match your if statement in showCategories. So either change the if condition to `userPicked === 'one'`, or change the Desserts option value to `<option value="dessert">Desserts</option>`
You can add an event listener to your dropdown options and filter your menu options with the selected value. Then, it's just a matter of building up your elements and appending them to the list. ```js const dessert = { store: "Baskin Robbins", inventory: { "Ice cream": { 0: { flavor: "Chocolate", cost: 15 }, 1: { flavor: "Vanilla", cost: 10 } }, "Cake": { 2: { flavor: "Oreo", cost: 30 } } } }; const ddl = document.getElementById('ddl'); ddl.addEventListener('change', e => { const itemsList = document.getElementById('items'); itemsList.innerHTML = ''; const options = dessert.inventory[e.target.value]; for (const key in options) { const flavor = options[key].flavor; const div = document.createElement('div'); div.innerText = flavor; itemsList.append(div); } }); ``` ```html <select id="ddl"> <option>Select...</option> <option value="Ice cream">Ice Cream</option> <option value="Cake">Cake</option> </select> <div id="items"></div> ```
55,599,741
I'm creating a stored procedure that uses two multi-value parameters: ``` @Class AS VARCHAR(5), @Service AS VARCHAR(5) (…) WHERE B.UTRCLS IN (@Class) AND B.UTSVC IN (@Service) ``` The procedure works fine when both parameters only contain one value. However, when either or both use multiple values, it throws an error. In report builder the error is the following: > > Cannot read the next data row for the dataset DataSet1 (rsErrorReadingNextDataRow) > > > In SQL Server, the error appears as the following (truncated for length): > > Cannot execute the query "SELECT > Col1009,Col1010,Col1008,Expr1003,Expr1004 FROM (SELECT > Col1009,Tbl1001.UTCSNM Col1008,Col1010,SUM(Col1016) > Expr1003,SUM(Col1014) Expr1004 FROM (…) > > > I don't think I'm doing anything wrong with declaring the parameters. Is this an issue with multi-value parameters in stored procedures?
2019/04/09
[ "https://Stackoverflow.com/questions/55599741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11063543/" ]
If you only have one location to redirect to, check out Andrew1325's answer. If there are multiple route-to-redirect match-ups, [this thread](https://github.com/nuxt/nuxt.js/issues/112) has some ideas. The way I do it is with "anonymous" middleware, like so: In /pages/browse/index.js ```js <script> export default { middleware: [ function({ redirect }) { redirect('/browse/songs/new'); }, ], }; </script> ```
To redirect automatically or under certain conditions you need to use **middleware**. This can be setup like this: ``` //browse/index.js <template> //no need for content as redirecting </template> <script> export default { middleware: 'redirect' } </script> ``` and your middleware file... ``` //middleware/redirect.js export default function ({ store, redirect }) { // automatic redirect return redirect('/browse/songs/new') } ``` Read about middleware [here](https://nuxtjs.org/api/pages-middleware/) Your pages structure is set up in the **pages** folder and you name folders and pages as you would like your routes to be. Read about it [here](https://nuxtjs.org/guide/routing/) To use a common theme you can use **layouts**. These will have a `<nuxt-child/>` section which will display the individual page content. You can read about them [here](https://nuxtjs.org/guide/views/#layouts) All of this is pretty basic nuxt stuff, you should take some time to read the documantation or look at some tutorials listed [here](https://github.com/nuxt-community/awesome-nuxt#tutorials).
55,599,741
I'm creating a stored procedure that uses two multi-value parameters: ``` @Class AS VARCHAR(5), @Service AS VARCHAR(5) (…) WHERE B.UTRCLS IN (@Class) AND B.UTSVC IN (@Service) ``` The procedure works fine when both parameters only contain one value. However, when either or both use multiple values, it throws an error. In report builder the error is the following: > > Cannot read the next data row for the dataset DataSet1 (rsErrorReadingNextDataRow) > > > In SQL Server, the error appears as the following (truncated for length): > > Cannot execute the query "SELECT > Col1009,Col1010,Col1008,Expr1003,Expr1004 FROM (SELECT > Col1009,Tbl1001.UTCSNM Col1008,Col1010,SUM(Col1016) > Expr1003,SUM(Col1014) Expr1004 FROM (…) > > > I don't think I'm doing anything wrong with declaring the parameters. Is this an issue with multi-value parameters in stored procedures?
2019/04/09
[ "https://Stackoverflow.com/questions/55599741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11063543/" ]
To redirect automatically or under certain conditions you need to use **middleware**. This can be setup like this: ``` //browse/index.js <template> //no need for content as redirecting </template> <script> export default { middleware: 'redirect' } </script> ``` and your middleware file... ``` //middleware/redirect.js export default function ({ store, redirect }) { // automatic redirect return redirect('/browse/songs/new') } ``` Read about middleware [here](https://nuxtjs.org/api/pages-middleware/) Your pages structure is set up in the **pages** folder and you name folders and pages as you would like your routes to be. Read about it [here](https://nuxtjs.org/guide/routing/) To use a common theme you can use **layouts**. These will have a `<nuxt-child/>` section which will display the individual page content. You can read about them [here](https://nuxtjs.org/guide/views/#layouts) All of this is pretty basic nuxt stuff, you should take some time to read the documantation or look at some tutorials listed [here](https://github.com/nuxt-community/awesome-nuxt#tutorials).
Big ups to [@parker\_codes](https://stackoverflow.com/questions/55599694/how-to-redirect-to-child-route-in-nuxt#answer-55601274), there is a little deficiency is his implementation which is **circular redirection** a.k.a forever redirect loop. To solve this, add some checks in the parent component. This is because `Nuxt Js` calls the middleware of a parent route anytime a child route is visited. ```html //browse/index.js <template> //no need for content as redirecting <NuxtChild /> </template> <script> export default { middleware({ route, redirect, from }) { if(route.path == "/browse" || route.path == "/browse/"){ return redirect("/browse/songs/new") } } } </script> ```
55,599,741
I'm creating a stored procedure that uses two multi-value parameters: ``` @Class AS VARCHAR(5), @Service AS VARCHAR(5) (…) WHERE B.UTRCLS IN (@Class) AND B.UTSVC IN (@Service) ``` The procedure works fine when both parameters only contain one value. However, when either or both use multiple values, it throws an error. In report builder the error is the following: > > Cannot read the next data row for the dataset DataSet1 (rsErrorReadingNextDataRow) > > > In SQL Server, the error appears as the following (truncated for length): > > Cannot execute the query "SELECT > Col1009,Col1010,Col1008,Expr1003,Expr1004 FROM (SELECT > Col1009,Tbl1001.UTCSNM Col1008,Col1010,SUM(Col1016) > Expr1003,SUM(Col1014) Expr1004 FROM (…) > > > I don't think I'm doing anything wrong with declaring the parameters. Is this an issue with multi-value parameters in stored procedures?
2019/04/09
[ "https://Stackoverflow.com/questions/55599741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11063543/" ]
If you only have one location to redirect to, check out Andrew1325's answer. If there are multiple route-to-redirect match-ups, [this thread](https://github.com/nuxt/nuxt.js/issues/112) has some ideas. The way I do it is with "anonymous" middleware, like so: In /pages/browse/index.js ```js <script> export default { middleware: [ function({ redirect }) { redirect('/browse/songs/new'); }, ], }; </script> ```
Big ups to [@parker\_codes](https://stackoverflow.com/questions/55599694/how-to-redirect-to-child-route-in-nuxt#answer-55601274), there is a little deficiency is his implementation which is **circular redirection** a.k.a forever redirect loop. To solve this, add some checks in the parent component. This is because `Nuxt Js` calls the middleware of a parent route anytime a child route is visited. ```html //browse/index.js <template> //no need for content as redirecting <NuxtChild /> </template> <script> export default { middleware({ route, redirect, from }) { if(route.path == "/browse" || route.path == "/browse/"){ return redirect("/browse/songs/new") } } } </script> ```
371,464
I need to get the names of files which are starting with a string testfile. Also i want to create a XML file in the same location and write these file names into the XML. ``` <path> <dir> <file>testfile1</file> </dir> <dir> <file>testfile2</file> </dir> <path> ```
2011/12/25
[ "https://superuser.com/questions/371464", "https://superuser.com", "https://superuser.com/users/109580/" ]
As @slhck said, the shell isn't really the right tool for writing XML (although it's not as bad as trying to parse XML in the shell...), but it's not too hard to do a quick&dirty script: ``` targetdir="/path/to/dir/of/files" prefix="testfile" outfile="$targetdir/out.xml" # Write the opening tag(s): echo "<path>" >"$outfile" # Loop through the matching files, writing entries for each one: for f in "$targetdir/$prefix"*; do cat <<END_INSERT >>"$outfile" <dir> <file>$(basename "$f")</file> </dir> END_INSERT done # Write the closing tag(s): echo "</path>" >>"$outfile" ``` So what's wrong with the above, that you'd want to use something with a real XML library instead? Well, consider what'd happen with the above if any filenames happen to contain "<" or ">" (which are perfectly legal characters in unix filenames)? Doing this right involves encoding the filenames with HTML entities, and (AFAIK) the shell doesn't have good tools for this; a good XML library will just handle this sort of thing for you automatically. A couple of notes on the script: first, note that the first `echo` redirects with ">", while all the subsequent writes to outfile use ">>" -- that's because ">" empties the file before writing, so you want this only on the first write. Second, I use `echo` for the first and last writes, but `cat` with a here-document in the loop -- this is just a matter of convenience, because `echo` is easiest for single-line writes, but here-docs are easier to do multi-line writes in. You could easily use `echo` everywhere, or `cat <<` everywhere if you wanted to be consistent. Third, I tend to double-quote everything that contains a variable. This is a way of avoiding trouble with special characters (like spaces) in things like filenames. In general, I follow the principle that you should quote everything unless there's a specific reason not to. It's bad enough the XML will have trouble with special characters, I don't want trouble at the shell level as well.
It is possible for the bash shell to create an XML file containing the names of files matching a pattern (in this case `testfile*`): ``` #!/bin/bash XML_LIST="$HOME/xml.list" touch $XML_LIST #find files matching the regex find /home/ -name "testfile*" -print0 | xargs -n1 -0 >> /tmp/temp_filelist echo "<path>" > $XML_LIST #read list of files from TMP_FILE #declare array declare -a FILE_NAMES #open file for reading to array exec 10</tmp/temp_filelist while read LINE <&10; do FILE_NAMES[$count]=$LINE if [ "$LINE" != "" ]; then echo " <dir>" >> $XML_LIST echo " <file>$LINE</file>" >> $XML_LIST echo " </dir>" >> $XML_LIST fi done #close temp read file exec 10>&- echo "</path>" >> $XML_LIST echo "done" ``` Reading this into the shell is going to be more complicated, but still entirely possible. For this kind of scripting I would recommend another Linux native language, Python, which is easy to learn and has a specialized XML library to make possible the above write process, as well as reading the XML file, in less lines of code!
18,888,756
i need to implement some intersting behavior for menu on my website. on a mainpage menu div must be pinned to bottom of the window and when user scrolls down - menu goes up and stays pinned to top of the window. and when user scrolls back to top - menu goes down and stays pinned bottom. and unfortunately i don't have any idea how to do so. can anyone help me?
2013/09/19
[ "https://Stackoverflow.com/questions/18888756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/978119/" ]
**DEMO: <http://jsfiddle.net/M3KLB/1/>** HTML ---- ``` <ul id="menu" class="bottom"> <li>a</li> <li>b</li> <li>c</li> <li>d</li> </ul> ``` CSS --- ``` #menu { left: 0; background-color: red; width: 100px; } #menu.bottom { position: absolute; bottom: 0; } #menu.top { position: fixed; top: 0; } ``` JQuery ------ ``` var menu = $('#menu'); $(document).scroll(function () { if ($(this).scrollTop() >= $(window).height() - menu.height()) { menu.removeClass('bottom').addClass('top'); } else { menu.removeClass('top').addClass('bottom'); } }); ``` The idea here is that originally we want to position the menu relatively to the window. Once we would have "scrolled past" it, we should set the position to fixed. Because we can't *remove* a specific style using JS - e.g. `top` can't be removed - it is best for us to implement this using two different classes. That way the property can be removed and not interfere with our new styling. The JS calculates the where the top of the menu would have originally sat and compares this with the current scroll position. The reason we don't just calculate the menus position once and store it is because the menu could grow (menu items expanding, perhaps) but more importantly the window size can be changed.
Basically, position 'fixed' on the menu - fixed to the bottom. Then put in a handler that detects when the window is scrolled ``` $(window).scroll(function(){ do stuff . . . }); ``` You can work out the page position ``` if( pagePosVar != 0){ do animate . . . (menu to top) }else{ do animate . . . (menu to bottom) } ``` i.e. when the page isn't right at the top, move the menu to the top otherwise, move the menu back to the bottom. When the menu is at the top, make sure it's still 'fixed', this time to the top and the rest of the content will scroll behind it.
67,395,982
My Spring boot application has REST endpoints and has scheduled tasks. Which AWS service should I use? I was considering beanstalk, but there I have to choose a web or worker environment. Similar selection is required in Heroku also. My application can withstand crashes, if it can spin up automatically. Can you suggest an appropriate AWS service?
2021/05/05
[ "https://Stackoverflow.com/questions/67395982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077917/" ]
When I used other endpoints, The issue was fixed. You can try the below endpoints. **BSC RPC Endpoints:** ``` https://data-seed-prebsc-1-s1.binance.org:8545/ https://data-seed-prebsc-2-s1.binance.org:8545/ https://data-seed-prebsc-1-s2.binance.org:8545/ https://data-seed-prebsc-2-s2.binance.org:8545/ https://data-seed-prebsc-1-s3.binance.org:8545/ https://data-seed-prebsc-2-s3.binance.org:8545/ ```
```js bsc: { networkCheckTimeout: 999999, provider: () => new HDWalletProvider(mnemonic, `https://data-seed-prebsc-1-s1.binance.org:8545`), network_id: 97, // Ropsten's id gas: 5500000, // Ropsten has a lower block limit than mainnet confirmations: 10, // # of confs to wait between deployments. (default: 0) timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50) skipDryRun: true // Skip dry run before migrations? (default: false for public nets ) }, ``` adding network timeout should help
67,395,982
My Spring boot application has REST endpoints and has scheduled tasks. Which AWS service should I use? I was considering beanstalk, but there I have to choose a web or worker environment. Similar selection is required in Heroku also. My application can withstand crashes, if it can spin up automatically. Can you suggest an appropriate AWS service?
2021/05/05
[ "https://Stackoverflow.com/questions/67395982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077917/" ]
I searched for more than a week. Finally, I found the answer [here](https://www.cnblogs.com/softfair/p/Truffle-migirate-deploy-contract-ESOCKETTIMEDOUT.html), Not only change the `pollingInterval`, but also do this: in the module `web3-provider-engine`, modify the `timeout` a bigger number. Remember that, the module maybe imported more than one times, so change the value everywhere in your projects. ``` xhr({ uri: targetUrl, method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(newPayload), rejectUnauthorized: false, timeout: 2000, // change the value bigger ``` The `timeout` value is hardcoded, maybe nowadays most people have very good Internet connection and only a few techs suffering, I tried very hard to find out the answer. After I change this configuration, I never suffer timeout!
```js bsc: { networkCheckTimeout: 999999, provider: () => new HDWalletProvider(mnemonic, `https://data-seed-prebsc-1-s1.binance.org:8545`), network_id: 97, // Ropsten's id gas: 5500000, // Ropsten has a lower block limit than mainnet confirmations: 10, // # of confs to wait between deployments. (default: 0) timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50) skipDryRun: true // Skip dry run before migrations? (default: false for public nets ) }, ``` adding network timeout should help
67,395,982
My Spring boot application has REST endpoints and has scheduled tasks. Which AWS service should I use? I was considering beanstalk, but there I have to choose a web or worker environment. Similar selection is required in Heroku also. My application can withstand crashes, if it can spin up automatically. Can you suggest an appropriate AWS service?
2021/05/05
[ "https://Stackoverflow.com/questions/67395982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077917/" ]
When I used other endpoints, The issue was fixed. You can try the below endpoints. **BSC RPC Endpoints:** ``` https://data-seed-prebsc-1-s1.binance.org:8545/ https://data-seed-prebsc-2-s1.binance.org:8545/ https://data-seed-prebsc-1-s2.binance.org:8545/ https://data-seed-prebsc-2-s2.binance.org:8545/ https://data-seed-prebsc-1-s3.binance.org:8545/ https://data-seed-prebsc-2-s3.binance.org:8545/ ```
The problem is that BSC produces blocks so quickly that it exceeds the default number of blocks Truffle is configured to wait for. You can solve this by adding the `networkCheckTimeout` and `timeoutBlocks` fields in your network config: ```json bsc: { networkCheckTimeout: 1000000, timeoutBlocks: 200 } ```
67,395,982
My Spring boot application has REST endpoints and has scheduled tasks. Which AWS service should I use? I was considering beanstalk, but there I have to choose a web or worker environment. Similar selection is required in Heroku also. My application can withstand crashes, if it can spin up automatically. Can you suggest an appropriate AWS service?
2021/05/05
[ "https://Stackoverflow.com/questions/67395982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077917/" ]
I searched for more than a week. Finally, I found the answer [here](https://www.cnblogs.com/softfair/p/Truffle-migirate-deploy-contract-ESOCKETTIMEDOUT.html), Not only change the `pollingInterval`, but also do this: in the module `web3-provider-engine`, modify the `timeout` a bigger number. Remember that, the module maybe imported more than one times, so change the value everywhere in your projects. ``` xhr({ uri: targetUrl, method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(newPayload), rejectUnauthorized: false, timeout: 2000, // change the value bigger ``` The `timeout` value is hardcoded, maybe nowadays most people have very good Internet connection and only a few techs suffering, I tried very hard to find out the answer. After I change this configuration, I never suffer timeout!
The problem is that BSC produces blocks so quickly that it exceeds the default number of blocks Truffle is configured to wait for. You can solve this by adding the `networkCheckTimeout` and `timeoutBlocks` fields in your network config: ```json bsc: { networkCheckTimeout: 1000000, timeoutBlocks: 200 } ```
67,395,982
My Spring boot application has REST endpoints and has scheduled tasks. Which AWS service should I use? I was considering beanstalk, but there I have to choose a web or worker environment. Similar selection is required in Heroku also. My application can withstand crashes, if it can spin up automatically. Can you suggest an appropriate AWS service?
2021/05/05
[ "https://Stackoverflow.com/questions/67395982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077917/" ]
When I used other endpoints, The issue was fixed. You can try the below endpoints. **BSC RPC Endpoints:** ``` https://data-seed-prebsc-1-s1.binance.org:8545/ https://data-seed-prebsc-2-s1.binance.org:8545/ https://data-seed-prebsc-1-s2.binance.org:8545/ https://data-seed-prebsc-2-s2.binance.org:8545/ https://data-seed-prebsc-1-s3.binance.org:8545/ https://data-seed-prebsc-2-s3.binance.org:8545/ ```
I searched for more than a week. Finally, I found the answer [here](https://www.cnblogs.com/softfair/p/Truffle-migirate-deploy-contract-ESOCKETTIMEDOUT.html), Not only change the `pollingInterval`, but also do this: in the module `web3-provider-engine`, modify the `timeout` a bigger number. Remember that, the module maybe imported more than one times, so change the value everywhere in your projects. ``` xhr({ uri: targetUrl, method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(newPayload), rejectUnauthorized: false, timeout: 2000, // change the value bigger ``` The `timeout` value is hardcoded, maybe nowadays most people have very good Internet connection and only a few techs suffering, I tried very hard to find out the answer. After I change this configuration, I never suffer timeout!
67,395,982
My Spring boot application has REST endpoints and has scheduled tasks. Which AWS service should I use? I was considering beanstalk, but there I have to choose a web or worker environment. Similar selection is required in Heroku also. My application can withstand crashes, if it can spin up automatically. Can you suggest an appropriate AWS service?
2021/05/05
[ "https://Stackoverflow.com/questions/67395982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077917/" ]
When I used other endpoints, The issue was fixed. You can try the below endpoints. **BSC RPC Endpoints:** ``` https://data-seed-prebsc-1-s1.binance.org:8545/ https://data-seed-prebsc-2-s1.binance.org:8545/ https://data-seed-prebsc-1-s2.binance.org:8545/ https://data-seed-prebsc-2-s2.binance.org:8545/ https://data-seed-prebsc-1-s3.binance.org:8545/ https://data-seed-prebsc-2-s3.binance.org:8545/ ```
Best way I found to avoid this error is to ``` truffle compile ``` manually before migration. Then, when migrate, to add the --compile-none option. ``` truffle migrate --network xxx --compile-none ```
67,395,982
My Spring boot application has REST endpoints and has scheduled tasks. Which AWS service should I use? I was considering beanstalk, but there I have to choose a web or worker environment. Similar selection is required in Heroku also. My application can withstand crashes, if it can spin up automatically. Can you suggest an appropriate AWS service?
2021/05/05
[ "https://Stackoverflow.com/questions/67395982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077917/" ]
I searched for more than a week. Finally, I found the answer [here](https://www.cnblogs.com/softfair/p/Truffle-migirate-deploy-contract-ESOCKETTIMEDOUT.html), Not only change the `pollingInterval`, but also do this: in the module `web3-provider-engine`, modify the `timeout` a bigger number. Remember that, the module maybe imported more than one times, so change the value everywhere in your projects. ``` xhr({ uri: targetUrl, method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(newPayload), rejectUnauthorized: false, timeout: 2000, // change the value bigger ``` The `timeout` value is hardcoded, maybe nowadays most people have very good Internet connection and only a few techs suffering, I tried very hard to find out the answer. After I change this configuration, I never suffer timeout!
Best way I found to avoid this error is to ``` truffle compile ``` manually before migration. Then, when migrate, to add the --compile-none option. ``` truffle migrate --network xxx --compile-none ```
17,750,340
I have some very complex XSD schemas to work with. By complex I mean that each of these XSD would correspont to about 20 classes / tables in a database, with each table having approximately 40 fields. And I have 18 different XSD like that to program. What I'm trying to achieve is: Get a XML file defined by the XSD and save all the data in a PostgreSQL database using SQLAlchemy. Basically I need a CRUD application that will persist a XML file in the database following the model of the XSD schema, and also be able to retrieve an object from the database and create a XML file. I want to avoid having to manually create the python classes, the sqlalchemy table definitions, the CRUD code. This would be a monumental job, subject to a lot of small mistakes, given the complexity of the XSD files. I can generate python classes from XSD in many ways like GenerateDS, PyXB, etc... I need to save those objects in the database. I'm open to any suggestions, even if the suggestion is conceptually different that what I'm describing. Thank you very much
2013/07/19
[ "https://Stackoverflow.com/questions/17750340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/447387/" ]
You can use generateDS to create django models from your XSD. You do this using the gends\_run\_gen\_django script, which is located under the django directory in the generateDS source. Here is some [documentation](http://www.rexx.com/~dkuhlman/generateDS.html#django-generating-models-and-forms) on that functionality. Relevant quote: > > Here is an overview of the process: > > > > ``` > Step 1. Generate bindings -- Run generateDS.py. > Step 2. Extract simpleType definitions from schema -- Run > gends_extract_simple_types.py. > Step 3. Generate models.py and forms.py -- Run gends_generate_django.py. > > ``` > > The script gends\_run\_gen\_django.py performs these three steps. > > > I believe django should give you most of the functionality of sqlalchemy. However, if you decide to use sqlalchemy instead then generateDS' django functionality might be a good model on which to base a similar sqlalchemy solution.
Not sure if there is a way directly, but you could indirectly go from XSD to a SQL Server DB, and then import the DB from SQLAlchemy
35,120,688
I have a long Excel spreadsheet with names in 2 columns and I am trying to be able to count the number of times a name appears in column A with a particular name appearing in the same row in column B but I am getting caught up with formulas. For example, if I have: ``` Col A, Col B Wilson, Ted Wilson, Alice Poole, Frank Wilson, Ted Poole, Alice Frank, Ted ``` I would like to be able to construct a formula that would tell me that Wilson, Ted appears two times. I've tried COUNTIFS in the following configuration but it returns 0 as an answer: ``` COUNTIFS(A1:B6,"Wilson",A1:B6,"Ted") ``` Am I missing something completely or is Excel just not built for this?
2016/01/31
[ "https://Stackoverflow.com/questions/35120688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4670655/" ]
I don't know the details of your code but it sounds like a job for condition variables: [cs.nmsu.edu/~jcook/Tools/pthreads/pthread\_cond.html](http://www.cs.nmsu.edu/~jcook/Tools/pthreads/pthread_cond.html) – Galik I've just implemented the solution based upon the `pthread_cond_signal` and `pthread_cond_timedwait` and I confirm that if works!!! – Dare Devil
In sending a signal, you're doing the right thing. The only thing that is missing is catching that signal. You have to replace the signal action with your own one. In the signal handler you can set a variable and check for it after sleep returns. Look into `sigaction`
31,097,716
So I'm using the NavigationView provided by [Android Design Support Library](http://android-developers.blogspot.in/2015/05/android-design-support-library.html) ![enter image description here](https://i.stack.imgur.com/1OK71.png) I can't seem to find examples on how to style it. So far I have: ``` <android.support.design.widget.NavigationView android:id="@+id/navigation_view" android:layout_height="match_parent" android:layout_width="wrap_content" android:layout_gravity="start" app:headerLayout="@layout/header" app:menu="@menu/drawer" app:itemTextColor="@color/black" app:itemIconTint="@color/black"/> ``` Styling the header is easy as its under its own xml layout but the body is a menu resource file and not a layout. * `app:itemTextColor` changes the text color * `app:itemIconTint` changes the icon color * `app:itemBackground` changes the item background color So how to set * selected item background * selected item text color * selected item icon tint
2015/06/28
[ "https://Stackoverflow.com/questions/31097716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2251156/" ]
I have answered to a similar question [Here](https://stackoverflow.com/a/31074133/23195420). Basically what you need do is , use a `Color State List Resource`. For that , first create a new `xml` (e.g drawer\_item.xml) inside `color` directory (which should be inside `res` directory.) If you don't have a directory named color already , create one. Now inside `drawer_item.xml` do something like this ``` <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:color="checked state color" android:state_checked= "true" /> <item android:color="your default color" /> </selector> ``` For `itemBackground`, a separate drawable needs to be placed inside drawable folder too. The name is same `drawer_item`. `android:drawable` property needs to be set instead of `android:color` for `itemBackground`: ``` <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/shape_rectangle_checked" android:state_checked= "true" /> <item android:drawable="@drawable/shape_rectangle" /> </selector> ``` File `shape_rectangle`: ``` <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="#ffffff" /> <!--white color --> </shape> ``` File `shape_rectangle_checked`: ``` <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="#25aaf1" /> <!--blue color --> </shape> ``` and then set in your navigationview like this ``` app:itemIconTint="@color/drawer_item" //notice here app:itemTextColor="@color/drawer_item" //and here app:itemBackground="@drawable/drawer_item"//and here for changing the background color of the item which is checked ```
To expand on @Sash\_KP's answer, for the `xml` in the `drawable` folder, you dont need the `@drawable/shape_rectangle` and `@drawable/shape_rectangle_check`. You can just use `@color/your_color`. Also for `API >= 21`, I've noticed that the navigation menu items by default have a preset selector. You'll notice if you touch and hold down the menu item a ripple will appear. Using a custom `itemBackground` will not override the default ripple. Therefore if you use a `ripple drawable` it will create two ripples! Also menu items with `ripple drawables` do not allow you to have a pressed state for some reason (the default ripple will only appear if you HOLD down). So for `API >= 21` I would not recommend using a `ripple drawable`. Just use a regular `selector drawable` with no custom ripples.
33,790,401
I want to create a program that removes space between characters in a string. Here is my code: ``` #include<string.h> #include<stdlib.h> #include<stdio.h> int main(){ char str[10]="I love you",temp[20]; int i,j; for(i=0;str[i];i++){ if(str[i] ==" "){ } else{ temp[j]=str[i]; j++; } } temp[j]='\0'; strcpy(str,temp); printf("%s",str); } ```
2015/11/18
[ "https://Stackoverflow.com/questions/33790401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5578530/" ]
There are several problems with your program. Though this initialization of a character array is valid in C ``` char str[10]="I love you",temp[20]; ^^^^ ``` nevertheless the array `str` will not contain the terminating zero of the string literal `"I love you"` because the string literal contains 11 characters including the terminating zero. This makes some difficulties in processing of the array. It is better to declare the array either like ``` char str[11]="I love you",temp[20]; ^^^^ ``` or like ``` char str[]="I love you",temp[20]; ^^^^ ``` In this case the array will contain the terminating zero. In this statement ``` if(str[i] ==" ") { ^^^^ ``` there is compared a character with a pointer because the string literal `" "` is implicitly converted to pointer to its first character. I think you mean a character constant instead of the string literal ``` if(str[i] == ' ') { ^^^^ ``` Take into account that variable `j` was not initialized. So the program has undefined behavior. At least you should write ``` int i,j = 0; ^^^^^ ``` And the program can be written without using an auxiliary array. It could look for example the following way ``` #include <stdio.h> int main( void ) { char str[] = "I love you"; size_t i = 0; while ( str[i] && str[i] != ' ' ) i++; size_t j = i; while ( str[i] ) { if ( str[++i] != ' ' ) str[j++] = str[i]; } puts( str ); } ``` Its output is ``` Iloveyou ```
You're using double quotes to reference a single character - comparing it to a single char[] element in your string, you should use single quotes: ``` if (str[i] == ' ') ``` Also, not 100% here so maybe someone can confirm - the inactive/empty if condition may throw up at least a warning, try changing it to: ``` if (str[i] != ' ') { temp[j]=str[i]; j++; } ``` Hope that helps. ETA - I just want to add so that you don't end up back here again :p You're packing a string byte by byte, when we assign strings to buffers in c using double quotes like: ``` char str[10] = "I love you"; ``` We create a string that is terminated with a NUL byte or \0: ``` temp[0] = '\0'; ``` For example - using single-quotes to refer to a single character - when you pack your string: ``` temp[j]=str[i]; ``` You should add the \0 byte at the end so functions like strcpy() and printf() know when the string ends So when you copy temp to str, strcpy won't know where your string ends, you need to add that \0 byte. This also means that you are overwriting str...because str has 10 elements, "I love you" including spaces is 10 bytes...but it's really 11, because when youa ssign the string the \0 is automatically added at the end for you...you are packing your temp string by hand so you need to add the \0 yourself: ``` if (str[i] != ' ') { temp[j]=str[i]; temp[++j] = '\0'; } ``` I'd change the entire loop to: ``` for(i=0; str[i] != '\0'; i++) { if(str[i] != ' ') { temp[j++] = str[i]; temp[j] = '\0'; } } ``` Oughtta do it, hope that helps.
33,790,401
I want to create a program that removes space between characters in a string. Here is my code: ``` #include<string.h> #include<stdlib.h> #include<stdio.h> int main(){ char str[10]="I love you",temp[20]; int i,j; for(i=0;str[i];i++){ if(str[i] ==" "){ } else{ temp[j]=str[i]; j++; } } temp[j]='\0'; strcpy(str,temp); printf("%s",str); } ```
2015/11/18
[ "https://Stackoverflow.com/questions/33790401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5578530/" ]
There are several problems with your program. Though this initialization of a character array is valid in C ``` char str[10]="I love you",temp[20]; ^^^^ ``` nevertheless the array `str` will not contain the terminating zero of the string literal `"I love you"` because the string literal contains 11 characters including the terminating zero. This makes some difficulties in processing of the array. It is better to declare the array either like ``` char str[11]="I love you",temp[20]; ^^^^ ``` or like ``` char str[]="I love you",temp[20]; ^^^^ ``` In this case the array will contain the terminating zero. In this statement ``` if(str[i] ==" ") { ^^^^ ``` there is compared a character with a pointer because the string literal `" "` is implicitly converted to pointer to its first character. I think you mean a character constant instead of the string literal ``` if(str[i] == ' ') { ^^^^ ``` Take into account that variable `j` was not initialized. So the program has undefined behavior. At least you should write ``` int i,j = 0; ^^^^^ ``` And the program can be written without using an auxiliary array. It could look for example the following way ``` #include <stdio.h> int main( void ) { char str[] = "I love you"; size_t i = 0; while ( str[i] && str[i] != ' ' ) i++; size_t j = i; while ( str[i] ) { if ( str[++i] != ' ' ) str[j++] = str[i]; } puts( str ); } ``` Its output is ``` Iloveyou ```
Welp this worked for me i just searched up a bit. ``` #include<string.h> #include<stdlib.h> #include<stdio.h> #include"stdafx.h" int main(void) { char str[11] = "I love you", str2; char *src, *dst; for (src = dst = str; *src != '\0'; src++) { *dst = *src; if (*dst != ' ') dst++; } *dst = '\0'; printf("%s", str); return 0; } ``` (It returns Iloveyou)
25,386,296
I am saving MapTiles to my internal cache which I retrieve using `getCacheDir()`. I have a few questions regarding the handling of the cache size. 1. How should I go about setting a maximum size for my cache directory before I start handling the deletion of files? With the newer devices a large cache isn't so much of a problem as there is quite a bit of space (not limitless but a fair amount), however the older devices have quite small internal memory and therefore cache sizes are going to be more important... 2. At the moment, I store a tile's use count and last used timestamp so I know which tiles I can delete and which not to delete. This way I can see which are used and which aren't, allowing me to remove the less used tiles. What happens when the Android OS decides it needs space and delete my cache? Is there an Intent I can listen for that tells me which files in my application's cache were deleted?
2014/08/19
[ "https://Stackoverflow.com/questions/25386296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/507313/" ]
1. for how to handle the size, I guess the best approach is to check how much are you using: * here it shows how to get free space [Get free space on internal memory](https://stackoverflow.com/questions/4595334/get-free-space-on-internal-memory) * the class shown on this link `StatFs` can also tell you what is the total size * So based on those values you can set to take a max of 2% of the total memory for as long as you have at least 10% free (for example) 2. no, there's really nothing you can do about it. Your software should be able to check for deleted tiles and re-download them if necessary. and as an alternative to your apprach, I suggest you to use a LruDiskCache from JakeWharton (<https://github.com/JakeWharton/DiskLruCache>) I believe that re-inventing the wheel is bad and unnecessary, so if there's a library that is already doing all of most of the heavy lift, why will I bother code it again?
Regarding 1) In my applications I often use disc based image caches. I have always used a fixed cache size, which has worked fine so far. I don't know about your size requirements, but you could determine the total available disc size and calculate some ratio of that (see: [Getting all the total and available space on Android](https://stackoverflow.com/questions/4799643/getting-all-the-total-and-available-space-on-android)). You probably want to set some max upper limit though, users won't be happy if your app eats up all their free disc space ;) Regarding 2) Android won't secretly delete your persisted files. The only thing that might happen is that the user decides to delete application data or all cached files of your app. In such a case, all data will be gone, and you will have to re-initialize your cache.
9,924,453
I am developing a mobile social TV application on Android.I want to integrate Facebook with my application so that I can: 1. Share things on Facebook 2. Send request to friends on Facebook to join the application
2012/03/29
[ "https://Stackoverflow.com/questions/9924453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1249713/" ]
You may use this. [Facebook Android SDK](http://developers.facebook.com/docs/reference/androidsdk/) But carefull about handling activity result. If you test integration in simulator you haven't installed facebook app. and sdk will show you a dialog with webview. But on a real phone if facebook app. is installed, authorization will go via app.
you need to install an extension, similar to the core Android SDK, but no, here is what you need to do: 1.) go to <https://github.com/facebook/facebook-android-sdk> 2.) download the facebook directory ONLY! The other directories are only examples. 3.) Put the files from the src (you can copy the drawables too, if you want to) in the package, you are currently working with 4.) You are good to go, you can use the facebook "SDK" see also these examples <https://github.com/facebook/facebook-android-sdk/tree/master/samples> , it is working example provided by facebook
26,165,211
I am building an interactive educational small app, where I help kids discover the different parts of body. <http://www.easypacelearning.com/images/TheWholeBody.jpg> Technically, I want to know how can I select some parts in the image, to let users click on a portion of an image and link to a new more specific image. Example: I am putting the body of human as a background, and I would like to click on an eye, it would pop-up and say it's an eye. How can I get points so I can hover using the mouse to recognize the part .. ``` function getData() { return { 'Head': { color: ... points: .. }, 'body': { color: ... points: .. }, 'leg': { color: ... points: .. } } } ``` Link that I use to experiment : <http://jsfiddle.net/ozgsvc61/1/>
2014/10/02
[ "https://Stackoverflow.com/questions/26165211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3378649/" ]
You can achieve this with an "[Image Map](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/map)". This is a long forgotten feature of HTML. To create linkable areas in your image, you use the `<map/>` element along with [`<area/>` elements](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/area). The `<area/>` elements, like the name suggests, define clickable areas in an image, and you can give them a 'polygon' shape, which sounds like what you're looking for. A simple example: ``` <map name="body-parts"> <area shape="poly" coords="..." href="#eyes" /> </map> ``` **EDIT**: I don't think you can listen to `click` events with this, but you can definitely use [`hashchange`](https://developer.mozilla.org/en-US/docs/Web/Events/hashchange) event.
You can add elements to you image and position them absolute like this: ``` #eye { position: absolute; height: 10px; // size of area width: 10px; top: 20px; // position left: 20px; cursor: pointer; // make it "feel" clickable // maybe you want to make a circle instead of a rectangle, you can do this with // border-radius (thanks to J148) border-radius: 10px; } ``` Now you can use JS to get the click and display anything you want, in JQuery e.g.: ``` $('#eye').click(function(){ // this is an eye !!! }); ``` Its maybe easier to use a data attribute to get the content easier. ``` <div class="area" data-content="This is an eye"></div> ``` In JQuery: ``` $('.area').click(function(){ content = $(this).data("content"); // show content in any way }); ```
35,577,965
Having this html: ``` <div class="images_portfolio panel-widget-style"> <a href="imagelink"><img src="x.jpg" alt="" /></a> <a href="imagelink"><img src="x.jpg" alt="" /></a> <a href="imagelink"><img src="x.jpg" alt="" /></a> <a href="imagelink"><img src="x.jpg" alt="" /></a> <a href="imagelink"><img src="x.jpg" alt="" /></a> <a href="imagelink"><img src="x.jpg" alt="" /></a> <a href="imagelink"><img src="x.jpg" alt="" /></a> <a href="imagelink"><img src="x.jpg" alt="" /></a> <a href="imagelink"><img src="x.jpg" alt="" /></a> <a href="imagelink"><img src="x.jpg" alt="" /></a> <a href="imagelink"><img src="x.jpg" alt="" /></a> <a href="imagelink"><img src="x.jpg" alt="" /></a> </div> ``` and this css: ``` .images_portfolio.panel-widget-style a img { width:100%; height:auto; } .images_portfolio.panel-widget-style a { position:relative; display:block;width:32%;margin-right:1%; float:left; margin-bottom:1%; } ``` it I can get 32%+32%+32% = 96% + margin right (1%\*3) = 99% in total of parent element. How can i get 100% of parent element so it works in all major browsers? Number of links can vary so I never know if it's 5 or 18 etc... (I want the the images to be aligned to an element down below that is 100%. Hope you understand what I mean).
2016/02/23
[ "https://Stackoverflow.com/questions/35577965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2188778/" ]
Try using `width: 33,33333333%` and instead of `margin-right` use `padding-right`. Padding is offset inside the element that counts towards elements width.
You can achieve it with javascript for example <https://jsfiddle.net/fx1azr4q/> ``` (function() { var elements = document.getElementsByTagName('a'); [].forEach.call(elements, function (el) { el.style.width = (100-elements.length)/elements.length + '%'; }); })(); ```
73,112,252
I've created a mat-form-field within an formArray, which allows me to display an image inside the option tag of the select box.[![Like this, Multiple select boxex](https://i.stack.imgur.com/erRFe.png)](https://i.stack.imgur.com/erRFe.png) Now I want to display to the left side of the filled inputfields the an image of the actor. Meaning the following: This is the component ts to update/edit a show information and it's episodes. I'm already showing a small preview of the image of the actor in the option field. What I'm trying to accomplish is once the actor is selected, to show a bigger image on the side of the input fields Actor/Char Name. Since a Show can have multiple actors "imgBig" is overwritten with the last selected actor for the Show. I somehow need to create duplicatable variable which I can access in the templates FormGroup. That way I can say imgBig+i (i being the FormGroup index number) and it should show me the correct image the html looks like this ``` <mat-form-field style="width: 100%;"> <mat-select formControlName="cast" class="form-control"> <mat-option *ngFor="let c of actorList;let i=index;" value="{{c.imdbId}}" class="form-control" style="height:60px;" > {{c.combinedname}} || {{c.imdbId}} </mat-option> </mat-select> </mat-form-field> <img src="{{imgBig}}" style="border-radius: 100%;"/> ``` The data I'm gettig from a json looks like this [![Array_Data](https://i.stack.imgur.com/NoG3L.png)](https://i.stack.imgur.com/NoG3L.png) I tried this within my typescript ``` export class EditShowComponent implements OnInit { imgBig :any; showForm: any showList:any = {} selectedShow_ = ''; actorInfo:any; info:any; actorList:any = {}; prevSelA :any = 0; prevSelEP :any = 0; epNr :any; epiIndex:number=0; ... setTitleValues(r:any){ //console.log('valuesset start'); console.log(r); //console.log('valuesset end'); this.showForm.get('name_en').setValue(r[0].name_en); this.showForm.get('name_kr').setValue(r[0].name_kr); this.showForm.get('imdbId').setValue(this.selectedShow_); this.showForm.get('asianwiki').setValue(r[0].asianwiki); this.showForm.get('releasedate').setValue(r[0].releasedate); this.showForm.get('baseImg').setValue(r[0].baseImg); this.imgBig = r[0].imgBase; this.epiIndex = -1; if(this.prevSelA==0) { //console.log('if'); this.prevSelA = this.sd.setActorCount(r[0][0].length); this.casts.removeAt(0); } else{ //console.log ('else'); this.prevSelA = this.sd.getActorCount(); while (this.casts.length !== 0) { this.casts.removeAt(0); } if(this.prevSelEP==0) { this.prevSelEP= this.sd.setEpisodeCount(r[0].episodenZahl); //this.casts.removeAt(0); } else{ this.prevSelEP = this.sd.getEpisodeCount(); } this.epNr = r[0].episodenZahl; while (this.episoden().length !== 0) { this.episoden().removeAt(0) } if(r[0][1]) { for(let tt of r[0][1]){ //console.log('E:::'+tt.episode); this.addEpisode(); var tIndex = tt.episode; tIndex = tIndex-1; this.createEpisodenDescDBdata(tIndex,tt) //this.descs(tt.episode).push(this.newEpisodeDecription()); } } console.log('cast daten begin'); console.log(r[0]); console.log('cast daten ende'); //console.log(r[0]); for( let tt of r[0][0]) { this.casts.push(this.buildExistingActor(tt.imdbCid,tt.alias,tt.imgBig)); } //this.casts.removeAt(0); } ... buildExistingActor(n:any, a:any,bild:any):UntypedFormGroup { this.imgBig = bild; console.log("actor name "+n); console.log("actor alias "+a); return this.fb.group({ cast:[n], alias:[a], bigImg:[bild] }) } } ``` The image get's displayed next to the field but it's always the same image because it basically always overwrites the older img saved in the variable "imgBig" Any idea how I could solve this?
2022/07/25
[ "https://Stackoverflow.com/questions/73112252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15996575/" ]
There is a much simpler approach: 1. create a new sheet with no filters present. 2. double click longitude and latitude fields, one after the other 3. After the Map is **AUTO GENERATED**, use your Business name field as a second layer of the Map 4. you can find more info here : <https://help.tableau.com/current/pro/desktop/en-us/maps_howto_simple.htm>
For maps, longitude goes on columns as the run vertically in a map. Likewise latitude goes on rows as those run horizontally. Then set the mark type to Map. [![enter image description here](https://i.stack.imgur.com/cl6AS.png)](https://i.stack.imgur.com/cl6AS.png) Now place your Business Name and Rating Value on the map layers.
31,700,665
I have been searching high and low for an answer on this and I am completly dumbfounded. I am implementing simple click and page tracking in my Android app using GA, running this through GTM. All my "Screens" are visible in realtime in GA but I can't get "Events" to appear at all. Well actually I can but the behaviour seems very bizarre. If I do not include a "Label" and a "Value" I can see the events appear. However if I add them (either as just a constant or a data layer variable) all events stop. I have confirmed the variables I want in "Label" and "Value" are coming through as I made a container with those values as "Category" and "Action" and could see them as expected in real time. This leads me to think the app side implementation is perfectly fine but there is an issue with my tag in GTM. (Obviously not the Trigger as that too works when expected). Ideally I would like to do something like this (the variables are data layer variables): [![Ideal look](https://i.stack.imgur.com/yIFLM.png)](https://i.stack.imgur.com/yIFLM.png) But this doesn't work. I see no Events.
2015/07/29
[ "https://Stackoverflow.com/questions/31700665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1659009/" ]
The Event Value should be a number, not a string. Shuffle the fields, for example - Action - Click on: {{GTM - Click Target}}, Label - {{GTM - Click Value}}, and leave the value empty, this will fix your problem.
Make sure, you have correctly setted up Click listener. Enable when defines when is listener available and where is applied to the all DOM elements. Fire ON defines conditions, so in your case it could be **{{event}} equals gtm.click** or **{{event}} equals gtm.linkClick** . This is the most common pitfall when setting listeners
70,060,775
I'm trying to reverse this linked-list but after giving input it gives output **Segmentation fault (core dumped)** while printing the list. This only happened when I declare 4th pointer before that it was working fine when there were only three pointers head, newcode, temp. ``` #include <stdio.h> #include <stdlib.h> int main() { struct node { int data; struct node *next; }; struct node *head, *newnode, *temp; int choice = 1; // Creating a linked-list while (choice) { newnode = (struct node *)malloc(sizeof(struct node)); printf("Enter the data: "); scanf("%d", &newnode->data); newnode->next = 0; if (head == 0) { head = temp = newnode; } else { temp->next = newnode; temp = newnode; } printf("Do you want to continue: "); scanf("%d", &choice); } temp = head; // Reversing the LL struct node *prevnode, *currentnode, *nextnode; prevnode = 0; currentnode = nextnode = head; while (nextnode != 0) { nextnode = nextnode->next; currentnode->next = prevnode; prevnode = currentnode; currentnode = nextnode; } head = prevnode; // Printing the Linked-list while (prevnode != 0) { printf("%d ", prevnode->data); prevnode = prevnode->next; } return 0; } ``` I understand segmentation fault error still can't figure which part is actually causing the error.
2021/11/22
[ "https://Stackoverflow.com/questions/70060775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17021070/" ]
So I figured out how to to upgrade to the latest version of node js. First you need to remove the older version of node with this syntax: ``` sudo apt-get purge --auto-remove nodejs ``` Install `npm` with: ``` sudo apt install npm ``` For me it already installed the latest version of node js, however if it did not work for you continue by installing node with these syntaxes: ``` npm install n -g n stable sudo n latest ``` Then check your node version by running `node -v`
Consider using [nvm](https://github.com/nvm-sh/nvm) and specifying the version you would like to use: ``` curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash nvm install 13.10.1 ``` You can try clearing you cache if you want to edit your global node [version](https://stackoverflow.com/questions/11284634/upgrade-node-js-to-the-latest-version-on-mac-os?rq=1): `sudo npm cache clean -f`
70,060,775
I'm trying to reverse this linked-list but after giving input it gives output **Segmentation fault (core dumped)** while printing the list. This only happened when I declare 4th pointer before that it was working fine when there were only three pointers head, newcode, temp. ``` #include <stdio.h> #include <stdlib.h> int main() { struct node { int data; struct node *next; }; struct node *head, *newnode, *temp; int choice = 1; // Creating a linked-list while (choice) { newnode = (struct node *)malloc(sizeof(struct node)); printf("Enter the data: "); scanf("%d", &newnode->data); newnode->next = 0; if (head == 0) { head = temp = newnode; } else { temp->next = newnode; temp = newnode; } printf("Do you want to continue: "); scanf("%d", &choice); } temp = head; // Reversing the LL struct node *prevnode, *currentnode, *nextnode; prevnode = 0; currentnode = nextnode = head; while (nextnode != 0) { nextnode = nextnode->next; currentnode->next = prevnode; prevnode = currentnode; currentnode = nextnode; } head = prevnode; // Printing the Linked-list while (prevnode != 0) { printf("%d ", prevnode->data); prevnode = prevnode->next; } return 0; } ``` I understand segmentation fault error still can't figure which part is actually causing the error.
2021/11/22
[ "https://Stackoverflow.com/questions/70060775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17021070/" ]
--- The `Node.js v10.19.0` Conundrum ================================ --- > > "I am going to answer this question in reference to Ubuntu, because I know about the `apt` package maintainer, and I feel that even if you don't use Ubuntu as your distro, so long as your a Linux user, you have still used `apt`/`apt-get`." > > > ##### This question demonstrates the method used by NVM for installing Node on a platform like Linux. --- NVM makes it extremely easy to install node. Not to long ago everyone had to use curl/wget & npm... Honestly I can't remember all the steps, but it seemed very involved for an open source language that is extreamly popular, and heavily used on all platforms, henceforth; NVM came about, and grew fast in popularity. The Problem with **`NVM`** -------------------------- --- The problem with NVM is the same thing that makes it so damn useful — *"to be clear I do really love the Node Version Manager"* — NVM uses environment variables, and local installation folders to isntall node, and to configure the environment to use the NVM and NODE commands. The problem is you already have the `apt` package-maintainer's version. \_**Apt software** is always behind the most current released version, and this is true for almost all software that we could discuss in relation to `apt`. Your Debian Linux "Out-of-the-Box" install, comes with the latest `apt` version of node, which is (at the time of authoring this answer): ### `Node.js v(10.19.00)` ...and It gets installed, and assigned to the path variables in the system root binary directory @... #### ***`/usr/bin`*** --- If you are experiencing this issue, you should do a couple things to gather some info. First, go to your console, and type in the command `which node`. ###### Here's a snippet that shows the commands you want to type that'll help you troubleshoot the issue: ``` # First type the command like this: ~$> which node ``` --- ``` # Then do it like this: ~$> which -a node ``` Your Output should look somewhat like this: ------------------------------------------- [![enter image description here](https://i.stack.imgur.com/C7575.png)](https://i.stack.imgur.com/C7575.png) #### !IMPORTANT!: Also use the command `node --version` or `node -v` so you know what your shell thinks your current version is. Its important to know what your shell is doing. The first `which` command shows what node installation is being used when you use the command `~$> node`, the second `which -a` command, shows you all of the executable node programs you have throughout your system. You will see multiple, and this is why when you try using `npm` or other software with nod version is used when you use the command the next thing you want to do is type the following command ``` ~$> nvm which current ``` [![nvm which current (NVM Command for view Node version)](https://i.stack.imgur.com/DUHhn.png)](https://i.stack.imgur.com/DUHhn.png) Most every thing should be pointing to a node install located on your path, with a pathname that looks close to something like this: #### `/home/<your-user-name>/.nvm/versions/node/<current-node-version>` The problem is if you try to do something, like install `vsce` the extension packager for VSCode with npm, it wont install, even though node seems to be working fine. So what you have to do is remove the other version of node you have, that you probably seen while executing the commands above. Currently `/usr/bin/` has `nodejs` which is node, and it is the version of node we talked about which is: `node v10.19.00. ### Removing the unwanted Node Package & Fixing NPN: > > *The last thing we will do before removing the unwanted nodejs package is doctor up `npm`. Use the two commands below, but just read what the output says. It will likely show unpleasant errors, and may not work at all, but just type them in, so we can use them in a bit to fix npm w/ the new node.js version, and you can see the difference. This will help demonstrate, under the hood, everything your doing, and how it is affecting the software on your machine.* > > > ##### okay go ahead and execute away: --- ``` ~$> npm doctor ``` then use ``` ~$> sudo npm doctor ``` --- ### Now We Will Remove the Un-wanted package: `"Node v10.19.00"` ##### First, lets look at your packages. To do that use the command below to view your packages. Look and confirm that nodejs is in the list ``` ~$> dpkg --list ``` #### then use.. ``` sudo apt-get --purge remove nodejs; sudo apt-get autoremove; # OR alternatively you could do it in two commands: sudo apt --purge remove nodejs sudo apt --purge autoremove ``` #### Now use... ``` ~$> dpkg --list ``` ##### ...to confirm that nodejs is indeed gone. --- #### With the unwanted node package out of the way, lets run the following again: ###### You will likely get unhappy results again, but thats okay, you should notice a bit of a change in behavior from the `npm doctor` though. ``` ~$> npm doctor ``` then use ``` ~$> sudo npm doctor ``` --- ###### The output probably looks like this: [![enter image description here](https://i.stack.imgur.com/T5q2O.png)](https://i.stack.imgur.com/T5q2O.png) Now you need to copy your NVM version of Node.js (currently I am using `Node v17.1.0` but by the time you read this, you will likley be using another version. ##### To copy your \_**NVM Node.js Executable** to the correct directory, you must do the following: 1. Use the `nvm which current` command again, and if you remember, it will print the name of a `Node executable` that looks like this: #### `/home/<your-user-name>/.nvm/versions/node/<current-node-version>` 2. Copy & Paste the **`<NODE-PATHNAME>`** the Node executable that was logged into your console. 3. Execute the following command: ``` ~$> sudo copy -v <NODE-PATHNAME> /usr/bin ``` --- Now if you don't have the following directories create them: ``` ~$> mkdir ~/node_modules ~$> mkdir ~/node_modules/.bin ``` > > ### !NOTE: > > > ###### Now upgrade npm. Unlike Node, we won't use an installed package from NPM, and copy it to the places where we want it. We will just makesure both locations have the same npm version > > > ###### Just FYI, NPM is having the same issue as node.js, but you may have figured that out already. > > > ##### Use the following commands: The first npm install will be executed as seen in the snippet ``` ~$> nvm install-latest-npm ``` --- The second npm install (the one just below this text) needs a little adjustment, after `npm@` you have to replace the word `latest` with the most recent version of npm. ``` ~$> npm install -g npm@latest ``` #### Now lastly you need to use the npm doctor to make sure every thing is working: ``` ~$> npm doctor ``` ``` ~$> sudo npm doctor ``` You should get a result that looks like this: [![enter image description here](https://i.stack.imgur.com/SBCUE.png)](https://i.stack.imgur.com/SBCUE.png)
Consider using [nvm](https://github.com/nvm-sh/nvm) and specifying the version you would like to use: ``` curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash nvm install 13.10.1 ``` You can try clearing you cache if you want to edit your global node [version](https://stackoverflow.com/questions/11284634/upgrade-node-js-to-the-latest-version-on-mac-os?rq=1): `sudo npm cache clean -f`
70,060,775
I'm trying to reverse this linked-list but after giving input it gives output **Segmentation fault (core dumped)** while printing the list. This only happened when I declare 4th pointer before that it was working fine when there were only three pointers head, newcode, temp. ``` #include <stdio.h> #include <stdlib.h> int main() { struct node { int data; struct node *next; }; struct node *head, *newnode, *temp; int choice = 1; // Creating a linked-list while (choice) { newnode = (struct node *)malloc(sizeof(struct node)); printf("Enter the data: "); scanf("%d", &newnode->data); newnode->next = 0; if (head == 0) { head = temp = newnode; } else { temp->next = newnode; temp = newnode; } printf("Do you want to continue: "); scanf("%d", &choice); } temp = head; // Reversing the LL struct node *prevnode, *currentnode, *nextnode; prevnode = 0; currentnode = nextnode = head; while (nextnode != 0) { nextnode = nextnode->next; currentnode->next = prevnode; prevnode = currentnode; currentnode = nextnode; } head = prevnode; // Printing the Linked-list while (prevnode != 0) { printf("%d ", prevnode->data); prevnode = prevnode->next; } return 0; } ``` I understand segmentation fault error still can't figure which part is actually causing the error.
2021/11/22
[ "https://Stackoverflow.com/questions/70060775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17021070/" ]
I also updated node js to 16.5.1 version but still showing 10.19.0 version. A simple command worked for me: ``` curl -fsSL https://deb.nodesource.com/setup_12.x | sudo -E bash - sudo apt-get install -y nodejs ``` Here, 12.x with version.For 16th version installation: ``` curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash - sudo apt-get install -y nodejs ``` Then, run following command: ``` sudo apt-get install -y nodejs ``` Now check version with `node -v` Hope it help.
Consider using [nvm](https://github.com/nvm-sh/nvm) and specifying the version you would like to use: ``` curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash nvm install 13.10.1 ``` You can try clearing you cache if you want to edit your global node [version](https://stackoverflow.com/questions/11284634/upgrade-node-js-to-the-latest-version-on-mac-os?rq=1): `sudo npm cache clean -f`
70,060,775
I'm trying to reverse this linked-list but after giving input it gives output **Segmentation fault (core dumped)** while printing the list. This only happened when I declare 4th pointer before that it was working fine when there were only three pointers head, newcode, temp. ``` #include <stdio.h> #include <stdlib.h> int main() { struct node { int data; struct node *next; }; struct node *head, *newnode, *temp; int choice = 1; // Creating a linked-list while (choice) { newnode = (struct node *)malloc(sizeof(struct node)); printf("Enter the data: "); scanf("%d", &newnode->data); newnode->next = 0; if (head == 0) { head = temp = newnode; } else { temp->next = newnode; temp = newnode; } printf("Do you want to continue: "); scanf("%d", &choice); } temp = head; // Reversing the LL struct node *prevnode, *currentnode, *nextnode; prevnode = 0; currentnode = nextnode = head; while (nextnode != 0) { nextnode = nextnode->next; currentnode->next = prevnode; prevnode = currentnode; currentnode = nextnode; } head = prevnode; // Printing the Linked-list while (prevnode != 0) { printf("%d ", prevnode->data); prevnode = prevnode->next; } return 0; } ``` I understand segmentation fault error still can't figure which part is actually causing the error.
2021/11/22
[ "https://Stackoverflow.com/questions/70060775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17021070/" ]
So I figured out how to to upgrade to the latest version of node js. First you need to remove the older version of node with this syntax: ``` sudo apt-get purge --auto-remove nodejs ``` Install `npm` with: ``` sudo apt install npm ``` For me it already installed the latest version of node js, however if it did not work for you continue by installing node with these syntaxes: ``` npm install n -g n stable sudo n latest ``` Then check your node version by running `node -v`
I also updated node js to 16.5.1 version but still showing 10.19.0 version. A simple command worked for me: ``` curl -fsSL https://deb.nodesource.com/setup_12.x | sudo -E bash - sudo apt-get install -y nodejs ``` Here, 12.x with version.For 16th version installation: ``` curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash - sudo apt-get install -y nodejs ``` Then, run following command: ``` sudo apt-get install -y nodejs ``` Now check version with `node -v` Hope it help.
70,060,775
I'm trying to reverse this linked-list but after giving input it gives output **Segmentation fault (core dumped)** while printing the list. This only happened when I declare 4th pointer before that it was working fine when there were only three pointers head, newcode, temp. ``` #include <stdio.h> #include <stdlib.h> int main() { struct node { int data; struct node *next; }; struct node *head, *newnode, *temp; int choice = 1; // Creating a linked-list while (choice) { newnode = (struct node *)malloc(sizeof(struct node)); printf("Enter the data: "); scanf("%d", &newnode->data); newnode->next = 0; if (head == 0) { head = temp = newnode; } else { temp->next = newnode; temp = newnode; } printf("Do you want to continue: "); scanf("%d", &choice); } temp = head; // Reversing the LL struct node *prevnode, *currentnode, *nextnode; prevnode = 0; currentnode = nextnode = head; while (nextnode != 0) { nextnode = nextnode->next; currentnode->next = prevnode; prevnode = currentnode; currentnode = nextnode; } head = prevnode; // Printing the Linked-list while (prevnode != 0) { printf("%d ", prevnode->data); prevnode = prevnode->next; } return 0; } ``` I understand segmentation fault error still can't figure which part is actually causing the error.
2021/11/22
[ "https://Stackoverflow.com/questions/70060775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17021070/" ]
--- The `Node.js v10.19.0` Conundrum ================================ --- > > "I am going to answer this question in reference to Ubuntu, because I know about the `apt` package maintainer, and I feel that even if you don't use Ubuntu as your distro, so long as your a Linux user, you have still used `apt`/`apt-get`." > > > ##### This question demonstrates the method used by NVM for installing Node on a platform like Linux. --- NVM makes it extremely easy to install node. Not to long ago everyone had to use curl/wget & npm... Honestly I can't remember all the steps, but it seemed very involved for an open source language that is extreamly popular, and heavily used on all platforms, henceforth; NVM came about, and grew fast in popularity. The Problem with **`NVM`** -------------------------- --- The problem with NVM is the same thing that makes it so damn useful — *"to be clear I do really love the Node Version Manager"* — NVM uses environment variables, and local installation folders to isntall node, and to configure the environment to use the NVM and NODE commands. The problem is you already have the `apt` package-maintainer's version. \_**Apt software** is always behind the most current released version, and this is true for almost all software that we could discuss in relation to `apt`. Your Debian Linux "Out-of-the-Box" install, comes with the latest `apt` version of node, which is (at the time of authoring this answer): ### `Node.js v(10.19.00)` ...and It gets installed, and assigned to the path variables in the system root binary directory @... #### ***`/usr/bin`*** --- If you are experiencing this issue, you should do a couple things to gather some info. First, go to your console, and type in the command `which node`. ###### Here's a snippet that shows the commands you want to type that'll help you troubleshoot the issue: ``` # First type the command like this: ~$> which node ``` --- ``` # Then do it like this: ~$> which -a node ``` Your Output should look somewhat like this: ------------------------------------------- [![enter image description here](https://i.stack.imgur.com/C7575.png)](https://i.stack.imgur.com/C7575.png) #### !IMPORTANT!: Also use the command `node --version` or `node -v` so you know what your shell thinks your current version is. Its important to know what your shell is doing. The first `which` command shows what node installation is being used when you use the command `~$> node`, the second `which -a` command, shows you all of the executable node programs you have throughout your system. You will see multiple, and this is why when you try using `npm` or other software with nod version is used when you use the command the next thing you want to do is type the following command ``` ~$> nvm which current ``` [![nvm which current (NVM Command for view Node version)](https://i.stack.imgur.com/DUHhn.png)](https://i.stack.imgur.com/DUHhn.png) Most every thing should be pointing to a node install located on your path, with a pathname that looks close to something like this: #### `/home/<your-user-name>/.nvm/versions/node/<current-node-version>` The problem is if you try to do something, like install `vsce` the extension packager for VSCode with npm, it wont install, even though node seems to be working fine. So what you have to do is remove the other version of node you have, that you probably seen while executing the commands above. Currently `/usr/bin/` has `nodejs` which is node, and it is the version of node we talked about which is: `node v10.19.00. ### Removing the unwanted Node Package & Fixing NPN: > > *The last thing we will do before removing the unwanted nodejs package is doctor up `npm`. Use the two commands below, but just read what the output says. It will likely show unpleasant errors, and may not work at all, but just type them in, so we can use them in a bit to fix npm w/ the new node.js version, and you can see the difference. This will help demonstrate, under the hood, everything your doing, and how it is affecting the software on your machine.* > > > ##### okay go ahead and execute away: --- ``` ~$> npm doctor ``` then use ``` ~$> sudo npm doctor ``` --- ### Now We Will Remove the Un-wanted package: `"Node v10.19.00"` ##### First, lets look at your packages. To do that use the command below to view your packages. Look and confirm that nodejs is in the list ``` ~$> dpkg --list ``` #### then use.. ``` sudo apt-get --purge remove nodejs; sudo apt-get autoremove; # OR alternatively you could do it in two commands: sudo apt --purge remove nodejs sudo apt --purge autoremove ``` #### Now use... ``` ~$> dpkg --list ``` ##### ...to confirm that nodejs is indeed gone. --- #### With the unwanted node package out of the way, lets run the following again: ###### You will likely get unhappy results again, but thats okay, you should notice a bit of a change in behavior from the `npm doctor` though. ``` ~$> npm doctor ``` then use ``` ~$> sudo npm doctor ``` --- ###### The output probably looks like this: [![enter image description here](https://i.stack.imgur.com/T5q2O.png)](https://i.stack.imgur.com/T5q2O.png) Now you need to copy your NVM version of Node.js (currently I am using `Node v17.1.0` but by the time you read this, you will likley be using another version. ##### To copy your \_**NVM Node.js Executable** to the correct directory, you must do the following: 1. Use the `nvm which current` command again, and if you remember, it will print the name of a `Node executable` that looks like this: #### `/home/<your-user-name>/.nvm/versions/node/<current-node-version>` 2. Copy & Paste the **`<NODE-PATHNAME>`** the Node executable that was logged into your console. 3. Execute the following command: ``` ~$> sudo copy -v <NODE-PATHNAME> /usr/bin ``` --- Now if you don't have the following directories create them: ``` ~$> mkdir ~/node_modules ~$> mkdir ~/node_modules/.bin ``` > > ### !NOTE: > > > ###### Now upgrade npm. Unlike Node, we won't use an installed package from NPM, and copy it to the places where we want it. We will just makesure both locations have the same npm version > > > ###### Just FYI, NPM is having the same issue as node.js, but you may have figured that out already. > > > ##### Use the following commands: The first npm install will be executed as seen in the snippet ``` ~$> nvm install-latest-npm ``` --- The second npm install (the one just below this text) needs a little adjustment, after `npm@` you have to replace the word `latest` with the most recent version of npm. ``` ~$> npm install -g npm@latest ``` #### Now lastly you need to use the npm doctor to make sure every thing is working: ``` ~$> npm doctor ``` ``` ~$> sudo npm doctor ``` You should get a result that looks like this: [![enter image description here](https://i.stack.imgur.com/SBCUE.png)](https://i.stack.imgur.com/SBCUE.png)
I also updated node js to 16.5.1 version but still showing 10.19.0 version. A simple command worked for me: ``` curl -fsSL https://deb.nodesource.com/setup_12.x | sudo -E bash - sudo apt-get install -y nodejs ``` Here, 12.x with version.For 16th version installation: ``` curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash - sudo apt-get install -y nodejs ``` Then, run following command: ``` sudo apt-get install -y nodejs ``` Now check version with `node -v` Hope it help.
8,617,794
I'm trying to reference two primary keys from two different tables, but the problem is that they don't match due to its character length. For an example , `person.personid = '1234'` and `department.personid = '12345'`. Is there an SQL statement in which I can use to match the first 4 or 5 characters of the primary keys or is there any other methods that I can use. --- UPDATE : My sincere apologies. I am dealing with two tables. `"dyndomrun.ddid"` is with a Primary key and `"domainregion.domainid"` is without any primary key nor foreign key. "dyndomrun" table DDL is set to `"character varying"` and has 8 characters, whereas "domainregion" table DDL is also set to "character varying" but has 10 characters. Problem : There are some fields in `domainregion` table that needs to be joined together with the primary key in `dyndomrun` table. I can't seem to do this with a simple SQL statement such as below ``` SELECT domainregion.domainid, dyndomrun.ddid FROM domainregion, dyndomrun WHERE domainregion.domainid = dyndomrun.ddid ORDER BY domainregion.domainid, dyndomrun.ddid; ``` I have tried JOINS, INNER JOINS, LIKE, none of them seems to work. The database that I am dealing with is purely SQL based stored using PostgreSQL. Please advise.
2011/12/23
[ "https://Stackoverflow.com/questions/8617794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1113616/" ]
You shouldn't exit after exploring the first child. You don't need the `if` statement in front of the `for` loop. ``` private nNode recursiveSearch(data gi,nNode node){ if (node.getdata()==gi) return node; nNode[] children = node.getChildren(); nNode res = null; for (int i = 0; res == null && i < children.length; i++) { res = recursiveSearch(gi, children[i]); } return res; } ```
In your code if recursiveSearch(gi, children[i]) returned null then i+1 not searched, modify: ``` private nNode recursiveSearch(data gi,nNode node){ if (node.getdata()==gi) return node; nNode[] children = node.getChildren(); nNode temp; if (children.length>0) for (int i = 0; i < children.length; i++) { temp = recursiveSearch(gi, children[i]); if(temp!=null) return temp; } return null; } ```
19,639,764
I just need some clarification. I need to get my PHP page to move from one page to another once the 'submit' button is clicked. I presumed it was ``` $_SESSION['ID'] = $row['ID']; header("location:newpage.php"); } ``` Any help/advice is greatly appreciated to these newbie!!
2013/10/28
[ "https://Stackoverflow.com/questions/19639764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2729578/" ]
If you want to move to other page after clicking the submit button. It will be better to add action tag to your form. Example: ``` <form method="GET" action="newpage.php"> <input type="submit" value="Send me to new page" /> </form> ```
`header()` only works prior to any output. You can't use it in an interactive way like this. Try [zaynetro's suggestion](https://stackoverflow.com/a/19639953/2057919) and see if that helps.
19,639,764
I just need some clarification. I need to get my PHP page to move from one page to another once the 'submit' button is clicked. I presumed it was ``` $_SESSION['ID'] = $row['ID']; header("location:newpage.php"); } ``` Any help/advice is greatly appreciated to these newbie!!
2013/10/28
[ "https://Stackoverflow.com/questions/19639764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2729578/" ]
If you want to move to other page after clicking the submit button. It will be better to add action tag to your form. Example: ``` <form method="GET" action="newpage.php"> <input type="submit" value="Send me to new page" /> </form> ```
You could output an redirect from javascript once your php is done (assuming your form processor is on the same page with the html) . For example: ``` $_SESSION['ID'] = $row['ID']; if($_SESSION['ID']){ ?> <script type="text/javascript"> window.location = 'newpage.php'; </script> <?php } ?> ```
11,548,387
Here is a piece of code i am trying to write. Here i want to retrieve data from the database, store that into an array and then json\_ecode it and set is as output. But i keep on getting this error "Trying to get property of non-object". Here is the code ``` $data['query'] = $this->db->get('forms'); foreach($data['query'] as $row) { $forms_array[] = array( $row->id ); } $return=json_encode($forms_array); $this->output->set_output($return); ```
2012/07/18
[ "https://Stackoverflow.com/questions/11548387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1212207/" ]
Make a shortcut. I don't know the browser you are targeting, but here's a link for IE <http://support.microsoft.com/kb/168124>
Well it depends on which platform your website is built upon. Assuming you're using `ASP.NET`. You will find that the file "making the server go live" is some executable in the `IIS` folder (Assuming your friends have `IIS` installed...). Using a batch file, you can make it automatically start the server according to your files and launch the browser. That is if I understood you correctly. Anyway, this isn't a very good thing to do...
52,941,226
I have an application that all the radiologists generates their reports by logging into the application. But I does not want user to login with their user id and password. when a user enters url it should not open a login page . I tried returning true when a user enters an URL like below. ``` <?php if($app->isLoggedIn()) { $title="Temlate post data"; include 'pages/post-data.php'; //This is keep on opening if i disable this showing showing blank page. $url = $app->current_url(); $app->log('visit',$title,$url,$b); exit(); } public function isLoggedIn() { if(empty($_SESSION['login'])) { return true; } else { return false; } } ``` But above code is allowing user to show only `post-data.php` page. I want him to access all other pages. How do I do default authentication. Any help would appreciated thanks.
2018/10/23
[ "https://Stackoverflow.com/questions/52941226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Although Nova does not provide a `->height()` method, when you generate a Nova card it creates `resources/js/components/Card.vue` automatically ([see Nova card documentation](https://nova.laravel.com/docs/1.0/customization/cards.html#assets)) The Card.vue file allows you to modify the Vue template for the card element. Since [Nova uses the Tailwind CSS framework](https://nova.laravel.com/docs/1.0/customization/frontend.html#css), you should be able to use the [Height classes of Tailwind CSS](https://tailwindcss.com/docs/height/) inside Card.vue.
As of now you can only adjust the width of the Card from the Card's php file using the `->width()` method. When you set the card width to `1/2` contents from the card seems to overflow. I solved the issue by adding the class `h-auto` to the `<card>` inside the `Card.vue`.
52,941,226
I have an application that all the radiologists generates their reports by logging into the application. But I does not want user to login with their user id and password. when a user enters url it should not open a login page . I tried returning true when a user enters an URL like below. ``` <?php if($app->isLoggedIn()) { $title="Temlate post data"; include 'pages/post-data.php'; //This is keep on opening if i disable this showing showing blank page. $url = $app->current_url(); $app->log('visit',$title,$url,$b); exit(); } public function isLoggedIn() { if(empty($_SESSION['login'])) { return true; } else { return false; } } ``` But above code is allowing user to show only `post-data.php` page. I want him to access all other pages. How do I do default authentication. Any help would appreciated thanks.
2018/10/23
[ "https://Stackoverflow.com/questions/52941226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Although Nova does not provide a `->height()` method, when you generate a Nova card it creates `resources/js/components/Card.vue` automatically ([see Nova card documentation](https://nova.laravel.com/docs/1.0/customization/cards.html#assets)) The Card.vue file allows you to modify the Vue template for the card element. Since [Nova uses the Tailwind CSS framework](https://nova.laravel.com/docs/1.0/customization/frontend.html#css), you should be able to use the [Height classes of Tailwind CSS](https://tailwindcss.com/docs/height/) inside Card.vue.
I solved this by adding this to my nova theme: ``` .card-panel { height: auto !important; min-height: 150px; } ``` Solution originally posted here: <https://github.com/laravel/nova-issues/issues/1014#issuecomment-451355417>
52,941,226
I have an application that all the radiologists generates their reports by logging into the application. But I does not want user to login with their user id and password. when a user enters url it should not open a login page . I tried returning true when a user enters an URL like below. ``` <?php if($app->isLoggedIn()) { $title="Temlate post data"; include 'pages/post-data.php'; //This is keep on opening if i disable this showing showing blank page. $url = $app->current_url(); $app->log('visit',$title,$url,$b); exit(); } public function isLoggedIn() { if(empty($_SESSION['login'])) { return true; } else { return false; } } ``` But above code is allowing user to show only `post-data.php` page. I want him to access all other pages. How do I do default authentication. Any help would appreciated thanks.
2018/10/23
[ "https://Stackoverflow.com/questions/52941226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
As of now you can only adjust the width of the Card from the Card's php file using the `->width()` method. When you set the card width to `1/2` contents from the card seems to overflow. I solved the issue by adding the class `h-auto` to the `<card>` inside the `Card.vue`.
I solved this by adding this to my nova theme: ``` .card-panel { height: auto !important; min-height: 150px; } ``` Solution originally posted here: <https://github.com/laravel/nova-issues/issues/1014#issuecomment-451355417>
20,474,321
I have a simple todolist app I'm creating whereby new todo items are added via an EditText View. So I'm trying to have it **submit the new item** to the list **when I press the enter key**. For some reason though **it just enters a new line instead**. I have also noticed that it **works fine** when I use the enter key **via an AVD** through eclipse but the **problem only occurs when I'm running it through my Nexus 4.** Here is my code: ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.todo_main); //Create reference to the ListView in the main layout ListView myListView = (ListView)findViewById(R.id.myListView); //Create a reference to the EditText view in the main layout for adding new items final EditText editText = (EditText)findViewById(R.id.myEditText); //Create a an arraylist to hold all the todo items final ArrayList<String> todoList = new ArrayList<String>(); //Create an ArrayAdaptor object to be able to bind ArrayLists to ListViews final ArrayAdapter<String> arrayAdaptor = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoList); myListView.setAdapter(arrayAdaptor); //Listens for certain keys to be pushed, particular the dpad center key or enter key editText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if(event.getAction() == KeyEvent.ACTION_DOWN) { if((keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER)) { //add item in the EditText to the todo list todoList.add(0, editText.getText().toString()); //Update the view by notifying the ArrayAdapter of the data changes arrayAdaptor.notifyDataSetChanged(); editText.setText(""); return true; } return false; } return false; } }); } ``` And XML: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ToDoListActivity"> <EditText android:id="@+id/myEditText" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/addItemHint" android:imeOptions="actionDone" /> <ListView android:id="@+id/myListView" android:layout_width="match_parent" android:layout_height="wrap_content" /> ``` **Please note that I have found similar questions on stack overflow but none seem to solve my problem.** I've tried!
2013/12/09
[ "https://Stackoverflow.com/questions/20474321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1129647/" ]
Set the singleLine property on your EditText widget to true: ``` <EditText android:singleLine="true" android:id="@+id/myEditText" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/addItemHint" android:imeOptions="actionDone" /> ```
``` android:inputType="textMultiLine" ``` adding this property in edittext will solve the problem
20,474,321
I have a simple todolist app I'm creating whereby new todo items are added via an EditText View. So I'm trying to have it **submit the new item** to the list **when I press the enter key**. For some reason though **it just enters a new line instead**. I have also noticed that it **works fine** when I use the enter key **via an AVD** through eclipse but the **problem only occurs when I'm running it through my Nexus 4.** Here is my code: ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.todo_main); //Create reference to the ListView in the main layout ListView myListView = (ListView)findViewById(R.id.myListView); //Create a reference to the EditText view in the main layout for adding new items final EditText editText = (EditText)findViewById(R.id.myEditText); //Create a an arraylist to hold all the todo items final ArrayList<String> todoList = new ArrayList<String>(); //Create an ArrayAdaptor object to be able to bind ArrayLists to ListViews final ArrayAdapter<String> arrayAdaptor = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoList); myListView.setAdapter(arrayAdaptor); //Listens for certain keys to be pushed, particular the dpad center key or enter key editText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if(event.getAction() == KeyEvent.ACTION_DOWN) { if((keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER)) { //add item in the EditText to the todo list todoList.add(0, editText.getText().toString()); //Update the view by notifying the ArrayAdapter of the data changes arrayAdaptor.notifyDataSetChanged(); editText.setText(""); return true; } return false; } return false; } }); } ``` And XML: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ToDoListActivity"> <EditText android:id="@+id/myEditText" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/addItemHint" android:imeOptions="actionDone" /> <ListView android:id="@+id/myListView" android:layout_width="match_parent" android:layout_height="wrap_content" /> ``` **Please note that I have found similar questions on stack overflow but none seem to solve my problem.** I've tried!
2013/12/09
[ "https://Stackoverflow.com/questions/20474321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1129647/" ]
Set the singleLine property on your EditText widget to true: ``` <EditText android:singleLine="true" android:id="@+id/myEditText" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/addItemHint" android:imeOptions="actionDone" /> ```
``` android:inputType="textImeMultiLine" ``` In my case this have solved the problem!
20,474,321
I have a simple todolist app I'm creating whereby new todo items are added via an EditText View. So I'm trying to have it **submit the new item** to the list **when I press the enter key**. For some reason though **it just enters a new line instead**. I have also noticed that it **works fine** when I use the enter key **via an AVD** through eclipse but the **problem only occurs when I'm running it through my Nexus 4.** Here is my code: ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.todo_main); //Create reference to the ListView in the main layout ListView myListView = (ListView)findViewById(R.id.myListView); //Create a reference to the EditText view in the main layout for adding new items final EditText editText = (EditText)findViewById(R.id.myEditText); //Create a an arraylist to hold all the todo items final ArrayList<String> todoList = new ArrayList<String>(); //Create an ArrayAdaptor object to be able to bind ArrayLists to ListViews final ArrayAdapter<String> arrayAdaptor = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoList); myListView.setAdapter(arrayAdaptor); //Listens for certain keys to be pushed, particular the dpad center key or enter key editText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if(event.getAction() == KeyEvent.ACTION_DOWN) { if((keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER)) { //add item in the EditText to the todo list todoList.add(0, editText.getText().toString()); //Update the view by notifying the ArrayAdapter of the data changes arrayAdaptor.notifyDataSetChanged(); editText.setText(""); return true; } return false; } return false; } }); } ``` And XML: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ToDoListActivity"> <EditText android:id="@+id/myEditText" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/addItemHint" android:imeOptions="actionDone" /> <ListView android:id="@+id/myListView" android:layout_width="match_parent" android:layout_height="wrap_content" /> ``` **Please note that I have found similar questions on stack overflow but none seem to solve my problem.** I've tried!
2013/12/09
[ "https://Stackoverflow.com/questions/20474321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1129647/" ]
Set the singleLine property on your EditText widget to true: ``` <EditText android:singleLine="true" android:id="@+id/myEditText" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/addItemHint" android:imeOptions="actionDone" /> ```
`android:singleLine="true"` is depricated, use ``` android:maxLines="1" android:inputType="text" android:imeOptions="actionNext" ```
20,474,321
I have a simple todolist app I'm creating whereby new todo items are added via an EditText View. So I'm trying to have it **submit the new item** to the list **when I press the enter key**. For some reason though **it just enters a new line instead**. I have also noticed that it **works fine** when I use the enter key **via an AVD** through eclipse but the **problem only occurs when I'm running it through my Nexus 4.** Here is my code: ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.todo_main); //Create reference to the ListView in the main layout ListView myListView = (ListView)findViewById(R.id.myListView); //Create a reference to the EditText view in the main layout for adding new items final EditText editText = (EditText)findViewById(R.id.myEditText); //Create a an arraylist to hold all the todo items final ArrayList<String> todoList = new ArrayList<String>(); //Create an ArrayAdaptor object to be able to bind ArrayLists to ListViews final ArrayAdapter<String> arrayAdaptor = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoList); myListView.setAdapter(arrayAdaptor); //Listens for certain keys to be pushed, particular the dpad center key or enter key editText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if(event.getAction() == KeyEvent.ACTION_DOWN) { if((keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER)) { //add item in the EditText to the todo list todoList.add(0, editText.getText().toString()); //Update the view by notifying the ArrayAdapter of the data changes arrayAdaptor.notifyDataSetChanged(); editText.setText(""); return true; } return false; } return false; } }); } ``` And XML: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ToDoListActivity"> <EditText android:id="@+id/myEditText" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/addItemHint" android:imeOptions="actionDone" /> <ListView android:id="@+id/myListView" android:layout_width="match_parent" android:layout_height="wrap_content" /> ``` **Please note that I have found similar questions on stack overflow but none seem to solve my problem.** I've tried!
2013/12/09
[ "https://Stackoverflow.com/questions/20474321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1129647/" ]
Set the singleLine property on your EditText widget to true: ``` <EditText android:singleLine="true" android:id="@+id/myEditText" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/addItemHint" android:imeOptions="actionDone" /> ```
If you want to single line The easy way is `android:inputType="text"` Or you can use `android:MaxLine="1"` If you want to Multiline don't insert those codes.
20,474,321
I have a simple todolist app I'm creating whereby new todo items are added via an EditText View. So I'm trying to have it **submit the new item** to the list **when I press the enter key**. For some reason though **it just enters a new line instead**. I have also noticed that it **works fine** when I use the enter key **via an AVD** through eclipse but the **problem only occurs when I'm running it through my Nexus 4.** Here is my code: ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.todo_main); //Create reference to the ListView in the main layout ListView myListView = (ListView)findViewById(R.id.myListView); //Create a reference to the EditText view in the main layout for adding new items final EditText editText = (EditText)findViewById(R.id.myEditText); //Create a an arraylist to hold all the todo items final ArrayList<String> todoList = new ArrayList<String>(); //Create an ArrayAdaptor object to be able to bind ArrayLists to ListViews final ArrayAdapter<String> arrayAdaptor = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoList); myListView.setAdapter(arrayAdaptor); //Listens for certain keys to be pushed, particular the dpad center key or enter key editText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if(event.getAction() == KeyEvent.ACTION_DOWN) { if((keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER)) { //add item in the EditText to the todo list todoList.add(0, editText.getText().toString()); //Update the view by notifying the ArrayAdapter of the data changes arrayAdaptor.notifyDataSetChanged(); editText.setText(""); return true; } return false; } return false; } }); } ``` And XML: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ToDoListActivity"> <EditText android:id="@+id/myEditText" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/addItemHint" android:imeOptions="actionDone" /> <ListView android:id="@+id/myListView" android:layout_width="match_parent" android:layout_height="wrap_content" /> ``` **Please note that I have found similar questions on stack overflow but none seem to solve my problem.** I've tried!
2013/12/09
[ "https://Stackoverflow.com/questions/20474321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1129647/" ]
``` android:inputType="textMultiLine" ``` adding this property in edittext will solve the problem
``` android:inputType="textImeMultiLine" ``` In my case this have solved the problem!
20,474,321
I have a simple todolist app I'm creating whereby new todo items are added via an EditText View. So I'm trying to have it **submit the new item** to the list **when I press the enter key**. For some reason though **it just enters a new line instead**. I have also noticed that it **works fine** when I use the enter key **via an AVD** through eclipse but the **problem only occurs when I'm running it through my Nexus 4.** Here is my code: ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.todo_main); //Create reference to the ListView in the main layout ListView myListView = (ListView)findViewById(R.id.myListView); //Create a reference to the EditText view in the main layout for adding new items final EditText editText = (EditText)findViewById(R.id.myEditText); //Create a an arraylist to hold all the todo items final ArrayList<String> todoList = new ArrayList<String>(); //Create an ArrayAdaptor object to be able to bind ArrayLists to ListViews final ArrayAdapter<String> arrayAdaptor = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoList); myListView.setAdapter(arrayAdaptor); //Listens for certain keys to be pushed, particular the dpad center key or enter key editText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if(event.getAction() == KeyEvent.ACTION_DOWN) { if((keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER)) { //add item in the EditText to the todo list todoList.add(0, editText.getText().toString()); //Update the view by notifying the ArrayAdapter of the data changes arrayAdaptor.notifyDataSetChanged(); editText.setText(""); return true; } return false; } return false; } }); } ``` And XML: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ToDoListActivity"> <EditText android:id="@+id/myEditText" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/addItemHint" android:imeOptions="actionDone" /> <ListView android:id="@+id/myListView" android:layout_width="match_parent" android:layout_height="wrap_content" /> ``` **Please note that I have found similar questions on stack overflow but none seem to solve my problem.** I've tried!
2013/12/09
[ "https://Stackoverflow.com/questions/20474321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1129647/" ]
``` android:inputType="textMultiLine" ``` adding this property in edittext will solve the problem
`android:singleLine="true"` is depricated, use ``` android:maxLines="1" android:inputType="text" android:imeOptions="actionNext" ```
20,474,321
I have a simple todolist app I'm creating whereby new todo items are added via an EditText View. So I'm trying to have it **submit the new item** to the list **when I press the enter key**. For some reason though **it just enters a new line instead**. I have also noticed that it **works fine** when I use the enter key **via an AVD** through eclipse but the **problem only occurs when I'm running it through my Nexus 4.** Here is my code: ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.todo_main); //Create reference to the ListView in the main layout ListView myListView = (ListView)findViewById(R.id.myListView); //Create a reference to the EditText view in the main layout for adding new items final EditText editText = (EditText)findViewById(R.id.myEditText); //Create a an arraylist to hold all the todo items final ArrayList<String> todoList = new ArrayList<String>(); //Create an ArrayAdaptor object to be able to bind ArrayLists to ListViews final ArrayAdapter<String> arrayAdaptor = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoList); myListView.setAdapter(arrayAdaptor); //Listens for certain keys to be pushed, particular the dpad center key or enter key editText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if(event.getAction() == KeyEvent.ACTION_DOWN) { if((keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER)) { //add item in the EditText to the todo list todoList.add(0, editText.getText().toString()); //Update the view by notifying the ArrayAdapter of the data changes arrayAdaptor.notifyDataSetChanged(); editText.setText(""); return true; } return false; } return false; } }); } ``` And XML: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ToDoListActivity"> <EditText android:id="@+id/myEditText" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/addItemHint" android:imeOptions="actionDone" /> <ListView android:id="@+id/myListView" android:layout_width="match_parent" android:layout_height="wrap_content" /> ``` **Please note that I have found similar questions on stack overflow but none seem to solve my problem.** I've tried!
2013/12/09
[ "https://Stackoverflow.com/questions/20474321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1129647/" ]
``` android:inputType="textMultiLine" ``` adding this property in edittext will solve the problem
If you want to single line The easy way is `android:inputType="text"` Or you can use `android:MaxLine="1"` If you want to Multiline don't insert those codes.
20,474,321
I have a simple todolist app I'm creating whereby new todo items are added via an EditText View. So I'm trying to have it **submit the new item** to the list **when I press the enter key**. For some reason though **it just enters a new line instead**. I have also noticed that it **works fine** when I use the enter key **via an AVD** through eclipse but the **problem only occurs when I'm running it through my Nexus 4.** Here is my code: ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.todo_main); //Create reference to the ListView in the main layout ListView myListView = (ListView)findViewById(R.id.myListView); //Create a reference to the EditText view in the main layout for adding new items final EditText editText = (EditText)findViewById(R.id.myEditText); //Create a an arraylist to hold all the todo items final ArrayList<String> todoList = new ArrayList<String>(); //Create an ArrayAdaptor object to be able to bind ArrayLists to ListViews final ArrayAdapter<String> arrayAdaptor = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoList); myListView.setAdapter(arrayAdaptor); //Listens for certain keys to be pushed, particular the dpad center key or enter key editText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if(event.getAction() == KeyEvent.ACTION_DOWN) { if((keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER)) { //add item in the EditText to the todo list todoList.add(0, editText.getText().toString()); //Update the view by notifying the ArrayAdapter of the data changes arrayAdaptor.notifyDataSetChanged(); editText.setText(""); return true; } return false; } return false; } }); } ``` And XML: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ToDoListActivity"> <EditText android:id="@+id/myEditText" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/addItemHint" android:imeOptions="actionDone" /> <ListView android:id="@+id/myListView" android:layout_width="match_parent" android:layout_height="wrap_content" /> ``` **Please note that I have found similar questions on stack overflow but none seem to solve my problem.** I've tried!
2013/12/09
[ "https://Stackoverflow.com/questions/20474321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1129647/" ]
`android:singleLine="true"` is depricated, use ``` android:maxLines="1" android:inputType="text" android:imeOptions="actionNext" ```
``` android:inputType="textImeMultiLine" ``` In my case this have solved the problem!
20,474,321
I have a simple todolist app I'm creating whereby new todo items are added via an EditText View. So I'm trying to have it **submit the new item** to the list **when I press the enter key**. For some reason though **it just enters a new line instead**. I have also noticed that it **works fine** when I use the enter key **via an AVD** through eclipse but the **problem only occurs when I'm running it through my Nexus 4.** Here is my code: ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.todo_main); //Create reference to the ListView in the main layout ListView myListView = (ListView)findViewById(R.id.myListView); //Create a reference to the EditText view in the main layout for adding new items final EditText editText = (EditText)findViewById(R.id.myEditText); //Create a an arraylist to hold all the todo items final ArrayList<String> todoList = new ArrayList<String>(); //Create an ArrayAdaptor object to be able to bind ArrayLists to ListViews final ArrayAdapter<String> arrayAdaptor = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoList); myListView.setAdapter(arrayAdaptor); //Listens for certain keys to be pushed, particular the dpad center key or enter key editText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if(event.getAction() == KeyEvent.ACTION_DOWN) { if((keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER)) { //add item in the EditText to the todo list todoList.add(0, editText.getText().toString()); //Update the view by notifying the ArrayAdapter of the data changes arrayAdaptor.notifyDataSetChanged(); editText.setText(""); return true; } return false; } return false; } }); } ``` And XML: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ToDoListActivity"> <EditText android:id="@+id/myEditText" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/addItemHint" android:imeOptions="actionDone" /> <ListView android:id="@+id/myListView" android:layout_width="match_parent" android:layout_height="wrap_content" /> ``` **Please note that I have found similar questions on stack overflow but none seem to solve my problem.** I've tried!
2013/12/09
[ "https://Stackoverflow.com/questions/20474321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1129647/" ]
`android:singleLine="true"` is depricated, use ``` android:maxLines="1" android:inputType="text" android:imeOptions="actionNext" ```
If you want to single line The easy way is `android:inputType="text"` Or you can use `android:MaxLine="1"` If you want to Multiline don't insert those codes.
32,396,826
In application, I need to find out current (maximum) bandwidth of current network connection (WLAN/3G/4G). How can this be done? Uploading small file, like 20kb or so would not be an option, since, I might get network speed that is not the same for 5MB, 20MB or 50MB files since effective network upload/download speed depends on file size. Uploading a large file is another option, but how big would it need to be and how often do I need to do the check for the current maximum bandwidth? I am guessing this is not something already available somewhere about current connection from the system (android). My idea is to have this information available for the app while it is being used, which can run in the background too.
2015/09/04
[ "https://Stackoverflow.com/questions/32396826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755422/" ]
The `dateFormat` of the `NSDateFormatter` (`yyyy-MM-dd'T'HH:mm:ss.SSS`) doesn't match string you get `1995-01-01T00:00:00`. You need to remove the extra `.SSS` => `yyyy-MM-dd'T'HH:mm:ss` to have a match.
Wouldn't the if statement expression always return false? ``` object["json"]["dateOfBirth"].stringValue as? NSDate ``` You are specifically getting a string and then try to cast it to an NSDate. Pretty sure that will always fail. In your other example you are specifically parsing the string to a date when you set it
11,857,819
``` private void LoadImageList() { string filepath = Application.StartupPath + @"\Content\Textures\Tiles\PlatformTiles.png"; Bitmap tileSheet = new Bitmap(filepath); int tilecount = 0; for (int y = 0; y < tileSheet.Height / TileGrid.TileHeight; y++) { for (int x = 0; x < tileSheet.Width / TileGrid.TileWidth; x++) { Bitmap newBitmap = tileSheet.Clone( new System.Drawing.Rectangle( x * TileGrid.TileWidth, y * TileGrid.TileHeight, TileGrid.TileWidth, TileGrid.TileHeight), System.Drawing.Imaging.PixelFormat.DontCare); imgListTiles.Images.Add(newBitmap); string itemName = ""; if (tilecount == 0) { itemName = "Empty"; } if (tilecount == 1) { itemName = "White"; } listTiles.Items.Add(new ListViewItem(itemName, tilecount++)); } } } ``` All I did was update PlatformTiles.png with a newer one and the next time I ran the program it doesn't load. I placed a breakpoint at *int tilecount = 0;* and it doesn't ever reach it. Every thing after it doesn't load either. Any ideas?
2012/08/08
[ "https://Stackoverflow.com/questions/11857819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/950949/" ]
I solved the issue by implementing the instructions exactly what is told here... <http://libmailcore.com/>... no need to build framework... just include the files in your project as told by the link I've mentioned and you are done...
I can only speak to that "config.h" error: Turns out you have to have MailCore in a folder with no spaces in the directory path. See: <https://github.com/mronge/MailCore/issues/35> I moved the folder to `/Users/bill/Documents/dev/lib/MailCore` and was able to build the project there. Leaving MailCore at that location, I dragged the MailCore.xcodeproj file into my project (located elsewhere on the hard drive) and was able to compile my project. Would be nice if someone would add this as a warning to to the directions [here](http://libmailcore.com/#iosadding)
28,130,711
this is probably an easy answer and having to do something to do with global variables maybe? how can i get a user inputted data from one function and have it able to be called and outputted with other functions in the same program. For example: ``` hydro = False def main(): medium = input("soil or hydro") def second(): if medium == "hydro": hydro = True main() second() ```
2015/01/24
[ "https://Stackoverflow.com/questions/28130711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490565/" ]
vCard files have mimetypes of ``` text/vcard ``` You'd need to add that as one of the accepted\_file\_mime\_types. If it's not that, it could be any of the following mimetypes which are now [deprecated](http://en.wikipedia.org/wiki/VCard). ``` text/x-vcard text/directory;profile=vCard text/directory ``` *Edit* - if it still does not work, you will need to output the mimetype when you upload the file to see what needs to be accepted.
Try a MIME type of `text/vcard`. `text/x-vcard` is deprecated.
4,776,130
What is difference between: ``` SELECT * FROM news WHERE cat_id IN (1, 2, 6, 8); ``` and create a loop: ``` foreach($cat as $key => $value){ $sql = "SELECT * FROM news WHERE cat_id = $value['id']; } ```
2011/01/23
[ "https://Stackoverflow.com/questions/4776130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/361635/" ]
The first example is far more efficient because only 1 sql query is run. The second example has x amount of queries, and is far slower. I would say that you should **never** do it the second way and always the first way.
The first example runs only 1 query, while the second runs N queries. Oh yeah, **never** do it the second way.
4,776,130
What is difference between: ``` SELECT * FROM news WHERE cat_id IN (1, 2, 6, 8); ``` and create a loop: ``` foreach($cat as $key => $value){ $sql = "SELECT * FROM news WHERE cat_id = $value['id']; } ```
2011/01/23
[ "https://Stackoverflow.com/questions/4776130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/361635/" ]
The first example runs only 1 query, while the second runs N queries. Oh yeah, **never** do it the second way.
I think just for some circumstances, when you want to extract data from DB in **exact order** of input ids, you might want to use the second statement. In this case, when you use the first query, the result might not in the order of input ids (1,2,6,8) if these ids are not in this order in DB. The first id that matches the DB will return result.
4,776,130
What is difference between: ``` SELECT * FROM news WHERE cat_id IN (1, 2, 6, 8); ``` and create a loop: ``` foreach($cat as $key => $value){ $sql = "SELECT * FROM news WHERE cat_id = $value['id']; } ```
2011/01/23
[ "https://Stackoverflow.com/questions/4776130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/361635/" ]
The first example is far more efficient because only 1 sql query is run. The second example has x amount of queries, and is far slower. I would say that you should **never** do it the second way and always the first way.
I think just for some circumstances, when you want to extract data from DB in **exact order** of input ids, you might want to use the second statement. In this case, when you use the first query, the result might not in the order of input ids (1,2,6,8) if these ids are not in this order in DB. The first id that matches the DB will return result.
47,181,312
Is it a array or object we creating in this line? I want to know the meaning of this line used in Javascript ? ``` document.getElementById("status").options[1]=new Option("OPEN","open"); ``` I am using this for my Dynamic dropdown list
2017/11/08
[ "https://Stackoverflow.com/questions/47181312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7911326/" ]
The first problem is determining priority. In this case, you could use the largest `TypeId`, but that does not seem like a great idea. You could add another column to serve as a priority ordinal instead. From there, it is a top 1 per group query: using [**`top with ties`**](http://sqlmag.com/t-sql/use-top-filter-with-ties-option) and [**`row_number()`**](https://msdn.microsoft.com/en-us/library/ms186734.aspx): ``` select top 1 with ties t1.UserId, t1.TypeId, t2.TypeDescription from #Tab1 t1 left join #Tab2 t2 on t1.TypeId = t2.TypeId order by row_number() over ( partition by t1.UserId order by t2.Ordinal --order by t1.TypeId desc ) ``` using [common table expression](https://msdn.microsoft.com/en-us/library/ms175972.aspx) and [**`row_number()`**](https://msdn.microsoft.com/en-us/library/ms186734.aspx): ``` ;with cte as ( select t1.UserId, t1.TypeId, t2.TypeDescription , rn = row_number() over ( partition by t1.UserId order by t2.Ordinal --order by t1.TypeId desc ) from #Tab1 t1 left join #Tab2 t2 on t1.TypeId = t2.TypeId ) select UserId, TypeId, TypeDescription from cte where rn = 1 ``` --- rextester demo for both: <http://rextester.com/KQAV36173> both return: ``` +--------+--------+-----------------+ | UserId | TypeId | TypeDescription | +--------+--------+-----------------+ | 1 | 2 | Admin | +--------+--------+-----------------+ ```
Actually I don't think you don't need a join at all. But you have to take the max TypeID without respect to the TypeDescription, since these differences can defeat a Group By. So a workaround is to take the Max without TypeDescription initially, then subquery the result to get the TypeDescription. ``` SELECT dT.* ,(SELECT TypeDescription FROM #Tab2 T2 WHERE T2.TypeId = dT.TypeId) [Role] --2. Subqueries TypeDescription using the Max TypeID FROM ( select t1.UserId ,MAX(T1.TypeId) [TypeId] --, T1.TypeDescription AS [Role] --1. differences will defeat group by. Subquery for value later in receiving query. from #Tab1 t1 GROUP BY t1.UserId ) AS dT ``` Produces Output: ``` UserId TypeId Role 1 2 Admin ```
11,304,985
I am working on one android application,in which paid videos are contain, user will able to download that videos. But I am not sure where I am going to save it after downloaded. Since these are paid videos, So user can not copy and paste it.
2012/07/03
[ "https://Stackoverflow.com/questions/11304985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/833290/" ]
To use the retrievePeripheral API, you need to save the CBPeripheral UUID somewhere (I use CoreData). The retrievePeripheral call takes an NSArray of UUIDs as a parameter. Looks like you're not providing the saved UUID to your retrievePeripheral call. When your didRetrievePeripherals callback is called, you will get an array of CBPeripheral objects. You can then reconnect to these peripherals. You don't need to scan for these and you also won't need to pair with the peripherals.
I have the same problem and I think one solution: when connection is lost, masterhave to scan for peripherials in the same way that we scan and connect, and slave have to pass to advertisin state and both have to recognice caractheristics services uuid's and caracteristics for the services again. This is the way I going to try to reconnect. Of course I thing we have to refresh on your own way with some more functions
11,304,985
I am working on one android application,in which paid videos are contain, user will able to download that videos. But I am not sure where I am going to save it after downloaded. Since these are paid videos, So user can not copy and paste it.
2012/07/03
[ "https://Stackoverflow.com/questions/11304985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/833290/" ]
To use the retrievePeripheral API, you need to save the CBPeripheral UUID somewhere (I use CoreData). The retrievePeripheral call takes an NSArray of UUIDs as a parameter. Looks like you're not providing the saved UUID to your retrievePeripheral call. When your didRetrievePeripherals callback is called, you will get an array of CBPeripheral objects. You can then reconnect to these peripherals. You don't need to scan for these and you also won't need to pair with the peripherals.
You should save the peripheral UUID (peripheral.identifier.UUIDString) when you successfully connect to the device. I am using NSUserDefaults to save the UUID. When you want to connect to the device use the following method from CBCentralManager *retrievePeripheralsWithIdentifiers:* and pass as parameter the UUID. This will return an array of CBPeripherals, find yours and connect to it. Don't try to save the CBPeripheral object anywhere. It is a very bad idea. Just use its UUID. If your device is already connected to the phone you could retrieve the CBPeripheral object using the method *retrieveConnectedPeripheralsWithServices* from CBCentralManager. You need to pass the services that the peripheral is using as parameters.
74,577,324
I have a DataFrame with a column that contains a dictionary as follows: ``` df: date dictionary 0 2021-01-01 00:00:00 + 00:00 'Total':{'USD':100, 'size':20}, 'country':{'USA': {'income': 20000}, 'fees': {'total': 55}} 1 2021-01-01 00:00:00 + 00:00 'Total':{'EUR':200, 'size':40}, 'country':{'France': {'income': 10000}, 'fees': {'total': 30}} 1 2021-01-02 00:00:00 + 00:00 'Total':{'GBP':100, 'size':30}, 'country':{'UK': {'income': 23000}, 'fees': {'total': 24}} ``` What I want is to set `USA` as a column name and take the value of `total` from the `fees` and set that as the value, to get the following: ``` df_final: date USA France UK 0 2021-01-01 00:00:00 + 00:00 55 30 NaN 1 2021-01-02 00:00:00 + 00:00 NaN NaN 24 ``` My DataFrame has hundreds of columns. I have tried the following: ``` df_list = [] for idx, row in df.iterrows(): for dct in row['dictionary']: dct['date'] = row['date'] df_list.append(dct) ``` But I get the following error: `TypeError: 'str' object does not support item assignment`. This happened specifically at `dct['date']`. How can this be done? EDIT: I added a few more rows to my DataFrame to better represent my problem.
2022/11/25
[ "https://Stackoverflow.com/questions/74577324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12244355/" ]
**1)** The first possibility I see, is if your dataframe contains valid json strings like so: ``` df = pd.DataFrame({ 'date': [ '2021-01-01 00:00:00', '2021-01-01 00:00:00', '2021-01-02 00:00:00', ], 'dictionary': [ '{"Total":{"USD":100, "size":20}, "country":{"USA": {"income": 20000}, "fees": {"total": 55}}}', '{"Total":{"EUR":200, "size":40}, "country":{"France": {"income": 10000}, "fees": {"total": 30}}}', '{"Total":{"GBP":100, "size":30}, "country":{"UK": {"income": 23000}, "fees": {"total": 24}}}', ] }) df.date = pd.to_datetime(df.date) df ``` [![enter image description here](https://i.stack.imgur.com/LWMtA.png)](https://i.stack.imgur.com/LWMtA.png) Then you could do: ``` import json for idx, row in df.iterrows(): dict = json.loads(row.dictionary) dict_keys = list(dict["country"].keys()) df.loc[idx, dict_keys[0]] = dict["country"]["fees"]["total"] df_final = df.groupby(df.date.dt.date) \ .agg('first') \ .drop(columns=['date', 'dictionary']) \ .reset_index() df_final ``` [![enter image description here](https://i.stack.imgur.com/KiSaz.png)](https://i.stack.imgur.com/KiSaz.png) **2)** The second is if your df contained valid dictionaries like so: ``` df = pd.DataFrame({ 'date': [ '2021-01-01 00:00:00', '2021-01-01 00:00:00', '2021-01-02 00:00:00', ], 'dictionary': [ {"Total":{"USD":100, "size":20}, "country":{"USA": {"income": 20000}, "fees": {"total": 55}}}, {"Total":{"EUR":200, "size":40}, "country":{"France": {"income": 10000}, "fees": {"total": 30}}}, {"Total":{"GBP":100, "size":30}, "country":{"UK": {"income": 23000}, "fees": {"total": 24}}}, ] }) df.date = pd.to_datetime(df.date) df ``` [![enter image description here](https://i.stack.imgur.com/uGP95.png)](https://i.stack.imgur.com/uGP95.png) Then you would: ``` import json for idx, row in df.iterrows(): dict = row.dictionary dict_keys = list(dict["country"].keys()) df.loc[idx, dict_keys[0]] = dict["country"]["fees"]["total"] # df.loc[index, row] df_final = df.groupby(df.date.dt.date) \ .agg('first') \ .drop(columns=['date', 'dictionary']) \ .reset_index() df_final ``` [![enter image description here](https://i.stack.imgur.com/uFM65.png)](https://i.stack.imgur.com/uFM65.png)
A possible solution: ``` aux = pd.json_normalize(df.dictionary, sep='_') (aux.filter(like='income').loc[0] .index.str.extract(r'.*_(.*)_.*').join(aux['country_fees_total']).join(df) .pivot(index='date', columns=0, values='country_fees_total').reset_index() .rename_axis(None, axis=1)) ``` Output: ``` date France UK USA 0 2021-01-01 00:00:00 + 00:00 30.0 NaN 55.0 1 2021-01-02 00:00:00 + 00:00 NaN 24.0 NaN ```
14,538,255
Today, I got a compiler error when trying to use a lazy pattern when matching on an existential GADT constructor: > > An existential or GADT data constructor cannot be used inside a lazy (~) pattern > > > Why is that limitation? What "bad" stuff could happen, if it were allowed?
2013/01/26
[ "https://Stackoverflow.com/questions/14538255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1333025/" ]
Consider ``` data EQ a b where Refl :: EQ a a ``` If we could define ``` transport :: Eq a b -> a -> b transport ~Refl a = a ``` then we could have ``` transport undefined :: a -> b ``` and thus acquire ``` transport undefined True = True :: Int -> Int ``` and then a crash, rather than the more graceful failure you get when trying to head-normalise the `undefined`. GADT data represent evidence *about* types, so bogus GADT data threaten type safety. It is necessary to be strict with them to validate that evidence: you can't trust unevaluated computations in the presence of bottom.
With "normal" data, you can skip checking the constructor during pattern-matching, on the understanding that when you try to use the data from the pattern, it might turn out to not exist, thus throwing an exception at you. With a GADT, the *type signature* potentially changes depending on which constructor is present. We need to know about types at *compile-time*; it's no good not checking the constructor until you need the values. If you do, you might have a type mismatch error. And that, potentially, means your program crashing with a segmentation fault (or worse). Haskell programs should *never* segfault.
351,085
I know of [How to remove an uninstalled package's dependencies?](https://askubuntu.com/questions/443/how-to-remove-an-uninstalled-packages-dependencies) and I tried ``` apt-get autoremove ``` but that does not remove dependencies that are recommended/suggested by other packages. That is, if I install a package X that recommends Y, but I do not install Y, and then I install package Z that depends on Y. and later I do ``` apt-get remove --auto-remove Z ``` then Y is not automatically removed even though nothing depends on it. (X "picked up" Y, even though it does not depend on it).
2013/09/28
[ "https://askubuntu.com/questions/351085", "https://askubuntu.com", "https://askubuntu.com/users/195582/" ]
Actually the command is: ``` sudo apt-get autoremove <Z> ``` But this has a trick! If any of the dependencies has some other previously installed packages that recommend/suggest them then apt would not remove them. You didn't specified what package was but for example, if I were to install the IcedTea plugin, it would install Java/OpenJRE by dependencies. If I uninstall them using `sudo apt-get autoremove icedtea-7-plugin` you would notice that it won't remove Java/OpenJRE, since LibreOffice also suggests the packages. So, to remove them you has to be overly specific about the package you wants to uninstall that normal `autoremove` won't: ``` sudo apt-get autoremove <Z> <dependency of Z> ``` This way you could be sure your package get removed. You can also use deborphan to remove some dependencies.
Right, if you want to remove package `<Z>` with dependances just type: ``` sudo apt-get autoremove --purge <Z> ```
351,085
I know of [How to remove an uninstalled package's dependencies?](https://askubuntu.com/questions/443/how-to-remove-an-uninstalled-packages-dependencies) and I tried ``` apt-get autoremove ``` but that does not remove dependencies that are recommended/suggested by other packages. That is, if I install a package X that recommends Y, but I do not install Y, and then I install package Z that depends on Y. and later I do ``` apt-get remove --auto-remove Z ``` then Y is not automatically removed even though nothing depends on it. (X "picked up" Y, even though it does not depend on it).
2013/09/28
[ "https://askubuntu.com/questions/351085", "https://askubuntu.com", "https://askubuntu.com/users/195582/" ]
If you want to remove recommended packages from your system, even if there are still some installed packages recommending (or suggesting) them, put the following in the file `/etc/apt/apt.conf.d/99_norecommends` (create it): ``` APT::Install-Recommends "false"; APT::AutoRemove::RecommendsImportant "false"; APT::AutoRemove::SuggestsImportant "false"; ``` The documentation for these options [is here](https://www.debian.org/doc/manuals/aptitude/ch02s05s05.en.html). Then, the next apt run (try `apt-get autoremove`) should remove them all. If it doesn't, launch `aptitude`, and type `g` and `g` again. This configuration also disables the automatic installation of recommended packages when using `apt-get`. For `aptitude` it can be done from the console GUI, menu Options > Preferences > "Install recommended packages automatically" (uncheck it).
Right, if you want to remove package `<Z>` with dependances just type: ``` sudo apt-get autoremove --purge <Z> ```
351,085
I know of [How to remove an uninstalled package's dependencies?](https://askubuntu.com/questions/443/how-to-remove-an-uninstalled-packages-dependencies) and I tried ``` apt-get autoremove ``` but that does not remove dependencies that are recommended/suggested by other packages. That is, if I install a package X that recommends Y, but I do not install Y, and then I install package Z that depends on Y. and later I do ``` apt-get remove --auto-remove Z ``` then Y is not automatically removed even though nothing depends on it. (X "picked up" Y, even though it does not depend on it).
2013/09/28
[ "https://askubuntu.com/questions/351085", "https://askubuntu.com", "https://askubuntu.com/users/195582/" ]
### Overriding APT options Unlike dependencies, automatically installed "recommended" or "suggested" packages may be ignored by `apt-get autoremove`. As described elsewhere, this behavior of APT can be changed in the configuration. Likewise, the configuration of the `apt-get` command can be temporarily changed through the `-o` command line option. This is, how you would force autoremove to remove left-over "recommended" and "suggested" packages, in addition to unused dependencies. ``` sudo apt-get autoremove -o APT::Autoremove::RecommendsImportant=0 -o APT::Autoremove::SuggestsImportant=0 ``` ### Caution! Some functionality may be lost. Be prepared to investigate and reinstall things. It may be easier to leave these packages alone. ### Other options To uninstall the 'recommended' and 'suggested' packages solely for a particular package, have a look at the apt history log.
Right, if you want to remove package `<Z>` with dependances just type: ``` sudo apt-get autoremove --purge <Z> ```
351,085
I know of [How to remove an uninstalled package's dependencies?](https://askubuntu.com/questions/443/how-to-remove-an-uninstalled-packages-dependencies) and I tried ``` apt-get autoremove ``` but that does not remove dependencies that are recommended/suggested by other packages. That is, if I install a package X that recommends Y, but I do not install Y, and then I install package Z that depends on Y. and later I do ``` apt-get remove --auto-remove Z ``` then Y is not automatically removed even though nothing depends on it. (X "picked up" Y, even though it does not depend on it).
2013/09/28
[ "https://askubuntu.com/questions/351085", "https://askubuntu.com", "https://askubuntu.com/users/195582/" ]
If you want to remove recommended packages from your system, even if there are still some installed packages recommending (or suggesting) them, put the following in the file `/etc/apt/apt.conf.d/99_norecommends` (create it): ``` APT::Install-Recommends "false"; APT::AutoRemove::RecommendsImportant "false"; APT::AutoRemove::SuggestsImportant "false"; ``` The documentation for these options [is here](https://www.debian.org/doc/manuals/aptitude/ch02s05s05.en.html). Then, the next apt run (try `apt-get autoremove`) should remove them all. If it doesn't, launch `aptitude`, and type `g` and `g` again. This configuration also disables the automatic installation of recommended packages when using `apt-get`. For `aptitude` it can be done from the console GUI, menu Options > Preferences > "Install recommended packages automatically" (uncheck it).
Actually the command is: ``` sudo apt-get autoremove <Z> ``` But this has a trick! If any of the dependencies has some other previously installed packages that recommend/suggest them then apt would not remove them. You didn't specified what package was but for example, if I were to install the IcedTea plugin, it would install Java/OpenJRE by dependencies. If I uninstall them using `sudo apt-get autoremove icedtea-7-plugin` you would notice that it won't remove Java/OpenJRE, since LibreOffice also suggests the packages. So, to remove them you has to be overly specific about the package you wants to uninstall that normal `autoremove` won't: ``` sudo apt-get autoremove <Z> <dependency of Z> ``` This way you could be sure your package get removed. You can also use deborphan to remove some dependencies.