What are the use cases of class member functions marked &&?

Question: I don't know which C++ standard presented this feature, but I cannot think of any use cases of this.

A member functions with && modifier will only be considered by overload resolution if the object is rvalue

struct Foo
{
    auto func() && {...}
};

auto a = Foo{};
a.func();            // Does not compile, 'a' is not an rvalue
std::move(a).func(); // Compiles
Foo{}.func();        // Compiles

Can someone please explain the use case for this?
Why we ever want some routine to be performed only for rvalues?
Comment: The are many use cases - not just "the use case" - but in general, a member function that's only considered for rvalues does not need to preserve the state of the object.
Comment: It might be performed *differently* for rvalues, like give away resources instead of creating a copy.
Answer: Ref-qualification was added in c++11. In general, propagation of the value-category is incredibly useful for generic programming!
Semantically, ref-qualifications on functions help to convey the intent; acting on lvalue references or rvalues -- which is analogous to const or volatile qualifications of functions. These also parallel the behavior of struct members, which propagate the qualifiers and categories.
A great example of this in practice is std::optional, which provides the std::optional::value() function, which propagates the value-category to the reference on extraction:
auto x = std::move(opt).value(); // retrieves a T&&

This is analogous to member-access with structs, where the value-category is propagated on access:
struct Data {
    std::string value;
};

auto data = Data{};

auto string = std::move(data).value; // expression yields a std::string&&

In terms of generic composition, this massively simplifies cases where the input may be an lvalue or an rvalue. For example, consider the case of using forwarding references:
// Gets the internal value from 'optional'
template <typename Optional>
auto call(Optional&& opt) {
    // will be lvalue or rvalue depending on what 'opt' resolves as
    return std::forward<Optional>(opt).value();
}

Without ref-qualification, the only way to accomplish the above code would be to create two static branches -- either with if constexpr or tag-dispatch, or some other means. Something like:
template <typename Optional>
auto call(Optional&& opt) {
    if constexpr (std::is_lvalue_reference_v<Optional>) {
        return opt.value();
    } else {
        return std::move(opt.value());
    }
}

On a technical level, rvalue-qualifications on functions provides the opportunity to optimize code with move-constructions and avoid copies in a semantically clear way.
Much like when you see a std::move(x) on a value, you are to expect that x is expiring; it's not unreasonable to expect that std::move(x).get_something() will cause x to do the same.
If you combine && overloads with const & overloads, then you can represent both immutable copying, and mutating movements in an API. Take, for example, the humble "Builder" pattern. Often, Builder pattern objects hold onto pieces of data that will be fed into the object on construction. This necessitates copies, whether shallow or deep, during construction. For large objects, this can be quite costly:
class Builder {
private:

    // Will be copied during construction
    expensive_data m_expensive_state;
    ...

public:

    auto add_expensive_data(...) -> Builder&;
    auto add_other_data(...) -> Builder&;
    ...

    auto build() && -> ExpensiveObject {
        // Move the expensive-state, which is cheaper.
        return ExpensiveObject{std::move(m_expensive_state), ...}
    }
    auto build() const & -> ExpensiveObject
        // Copies the expensive-state, whcih is costly
        return ExpensiveObject{m_expensive_state, ...}
    }
    ...
};

Without rvalue-qualifications, you are forced to make a choice on the implementation:

Do destructive actions like moves in a non-const function, and just document the safety (and hope the API isn't called wrong), or
Just copy everything, to be safe

With rvalue-qualifications, it becomes an optional feature of the caller, and it is clear from the authored code what the intent is -- without requiring documentation:
// Uses the data from 'builder'. May be costly and involves copies
auto inefficient = builder.build();

// Consumes the data from 'builder', but makes 'efficient's construction
// more efficient.
auto efficient = std::move(builder).build();

As an added benefit, static-analysis can often detect use-after-move cases, and so an accidental use of builder after the std::move can be better caught than simple documentation could.
Answer:
What are the use cases of class member functions marked &&?

A use case are "getter" style functions. They traditionally return references to sub objects or owned objects whose lifetime is tied to the super object.
That is however sometimes problematic, since calling the getter on an rvalue will result in a reference to an object that will be destroyed at the end of the expression. That is unsafe:
struct demo {
    int& get_mem() { return mem; }
private:
    int mem;
};

demo get_demo();

int& ref = get_demo().get_mem();
std::cout << ref; // bug

An lvalue ref qualifier prevents such bugs:
int& get_mem() & { return mem; }
int& ref = get_demo().get_mem(); // safely ill-formed

But it also prevents working previously correct code such as:
std::cout << get_demo().get_mem(); // used to be OK; now ill-formed

A solution is to provide two overloads, each with different qualifier:
int& get_mem() &  { return mem; }
int  get_mem() && { return mem; }

It is commonly used with types that wrap other types, with a full set of overloads that simulate all constess and value categories:
const int&  get_mem() const& ;
      int&  get_mem()      & ;
const int&& get_mem() const&&;
      int&& get_mem()      &&;


Is the approximation $\cos\frac23x \approx \frac12(1 + \cos x)$, for $x$ a first-quadrant angle, well known?

Question: Please comment on whether the following approximation is well known
$$\cos\frac23x \approx \frac12(1 + \cos x)$$
in the first quadrant, with a maximum error of $0.016$.
Comment: If you look at the series expansion, $\cos\left(\frac 23 x \right) \approx 1 - \frac 29 x^2$ and $\frac 12 (1 + \cos x) \approx 1 - \frac 14 x^2$ .  You can make lots of approximations like this by adjusting the constants.
Comment: @Chris Lewis   Nice geometric interpretation: using this formula, you can (approximately) trisect an acute angle!
Comment: No, it isn't a known approximation. I thought at first that the explanation was to be found on the side of Fourier series but this doesn't appear to be the case...
Comment: @Jean Marie  Please see edited question with plots
Comment: I wonder if there's a nice geometric argument to support this?
Comment: @DanielV I don't see how that is useful, since we want the approximation to be good for $1<x\le\frac\pi2$ and the terms of degree $2$ don't match.
Comment: I have NOT seen this one before. Inspired by this I came up with $$ \cos( \tfrac{2}{3}x) \approx \tfrac{125}{243} + \tfrac{128}{243} \cos(x) - \tfrac{10}{243} \cos^2(x)$$ which has even less error overall since it is a higher order approximation.
Comment: The error can be greater than 0.016. For example, x=1.09 gives an error of 0.0161. According to [Wolfram](https://www.wolframalpha.com/input?i=extrema+%7Ccos%282x%2F3%29-cos%28x%29%2F2-1%2F2%7C%2C+0%3C%3Dx%3C%3Dpi%2F2),  the maximum error is $\frac{13\sqrt{13} - 46}{54}$.
Comment: Obviously, you found the best simple approximation. Bravo !
Answer: Suppose that you look for the best $a$ such that $\cos(ax)$ is as close as possible to $\frac{1}{2} (1+\cos (x))$.
Consider the norm
$$\Phi(a)=\int_0^{\frac \pi 2} \left(\cos(ax)-\frac{1}{2} (1+\cos (x)) \right)^2\,dx$$ which is
$$\Phi(a)=\frac{1}{4} \left(\frac{4 \cos \left(\frac{\pi
   a}{2}\right)}{a^2-1}+\frac{\sin (\pi  a)-4 \sin \left(\frac{\pi
   a}{2}\right)}{a}+\frac{7 \pi }{4}+2\right)$$ Computing the derivative, we then need to solve for $a$ the equation
$$\left(a^2-1\right) \left(\pi  a \left(a^2-1\right) \cos (\pi  a)-2
   \sin \left(\frac{\pi  a}{2}\right) \left((\pi -2)
   a^2+\left(a^2-1\right) \cos \left(\frac{\pi
   a}{2}\right)+2\right)\right)-2 a \left(\pi  a^4-2 (\pi -2)
   a^2+\pi \right) \cos \left(\frac{\pi  a}{2}\right)=0$$ Using any root-finder, the solution is $a=0.6797$.
Considering $\Phi_{\text{min}}=5.59\times 10^{-5}$ while, for $a=\frac 23$, $\Phi=\frac{35 \pi-32-45 \sqrt{3}}{80}=1.68\times 10^{-4} $ which is only three times larger.
Using simple numbers
$$\cos \left(\frac{17 }{25}x\right)\approx \frac{1}{2} (1+\cos (x))$$
If you want to minimize the maximum error, consider the less pleasant norm
$$\Psi(a)=\int_0^{\frac{\pi }{2}} \left| \cos (a x)-\frac{1}{2} (1+\cos
   (x))\right|  \, dx$$ which is minimum for $a \sim 0.6834$ (maximum error of $0.0073$).
To summarize : "congratulations for your approximation !"
Comment: This is interesting, however it's unclear to me why the $1$-norm should minimize the maximum error, rather than the natural choice of the $\infty$-norm.
Comment: Or you could just say "best" means the $x^2$ coefficients match viz. $a=1/\sqrt{2}$.
Comment: @J.G. Actually, in terms of sup norm on $[0,\pi/2]$, $\cos(x/\sqrt2)$ is a worse approximation of $\frac{1+\cos x}2$ than $\cos(2x/3)$, because $$\sup_{0\le x\le \pi/2}\left\lvert\cos\frac x{\sqrt2}-\frac{1+\cos x}2\right\rvert\approx 0.056\\ \sup_{0\le x\le \pi/2}\left\lvert\cos\frac {2x}3-\frac{1+\cos x}2\right\rvert\approx 0.016$$ https://www.wolframalpha.com/input?i=maximize+%7Ccos%282%5E%28-1%2F2%29x%29-%281%2Bcos+x%29%2F2%7C+subject+to+0%3C%3Dx%3C%3Dpi%2F2
Comment: @SassatelliGiulio Agreed: there are all sorts of definitions of what makes one $a$ better than another. One could, for example, seek to minimize the supremum, arithmetic mean etc. of the $L^p$ norm for any $p$.
Answer: Here is a graphical representation that can be considered as a "Proof without words" ; strictly speaking, it isn't a proof of equality but a way to see the "plausability" of the good approximation :

(Added by @Blue)

I've animated @JeanMarie's visualization to show that OP's construction always puts the "upper trisection point" of the blue arc almost onto the perpendicular bisector of the red segment. (We get exactness when the blue arc has measure $90^\circ$ or $0^\circ$.)
If we were to reflect the blue arc in the horizontal radius, the red segment would be the sagitta of the doubled arc, so one might call this construction "approximate arc trisection via sagitta bisection".
Comment: I hope you don't mind that I've taken the liberty of adding an animation. :)
Comment: @Blue Very nice... Thank you very much !
Comment: +1. ... It's always been awfully *convenient* that (in the case of $x=\pi/2$ of your diagram) the "upper trisection point" of the right angle lies on the perpendicular bisector of the (horizontal) radius. Your visualization shows that OP's approximation roughly extends this convenience to arbitrary acute angles, using the perpendicular bisector of an appropriate sub-segment of the radius. ... This makes me wonder if the construction is "known" somewhere as a not-unreasonable strategy for approximating trisectors (and/or whether someone has erroneously claimed that the trisection is *exact*).
Comment: @Blue. Nice contribution ! Thanks
Comment: @Blue I hadn't thought to angle trisection...
Comment: This is a very nice problem ! By the way, how are you ? Cheers
Comment: @Claude Leibovici Hi, Claude ! Fine, thank you, and you ? I was just re-working on the very nice book "Spirals from Theodorus to Chaos" by Philip Davis that I mention in an old question of mine that could interest you [here](https://math.stackexchange.com/q/3006165/305862)
Answer: This approximation is a special case of a general approximation formula of the form
$$\cos \alpha x \approx A + B \cos x$$
for $x$ in $J := [-\frac{\pi}{2}, \frac{\pi}{2}]$ good for, say, $|\alpha|$ not too much larger than $1$.
Matching values at $x = 0, \pm \frac{\pi}{2}$ gives $A = \cos \frac{\pi \alpha}{2}, B = 1 - \cos \frac{\pi \alpha}{2}$, hence an approximation
$$\boxed{\cos \alpha x \approx \cos \frac{\pi \alpha}{2} + \left(1 - \cos \frac{\pi \alpha}{2}\right) \cos x}.$$
(In fact, a short calculus argument shows that (for $|\alpha| \leq 4$) our approxmation is an inequality (on $J$): $$\cos \alpha x \geq \cos \frac{\pi \alpha}{2} + \left(1 - \cos \frac{\pi \alpha}{2}\right) \cos x .$$ Moreover, provided that $|\alpha| < 1$, equality holds in $J$ only at $0, \pm \frac\pi2$.)
Examples

Taking $\alpha = \frac{2}{3}$ recovers the identity
$$\cos \frac{2}{3} x = \frac{1}{2} \left(1 + \cos x\right)$$
in the question statement, which has a maximum absolute error of $\frac{-46 + 13 \sqrt{13}}{54} \approx \frac{1}{62}$ on $J$. This special case is characterized by $A = B$.

Instead taking $\alpha = \frac{1}{2}$, for example, gives
$$\cos \frac{x}{2} \approx \frac{1}{\sqrt{2}} + \left(1 - \frac{1}{\sqrt{2}}\right) \cos x,$$
which has a maximum absolute error of $\frac{10 - 7 \sqrt{2}}{8} \approx \frac{1}{80}$ on $J$.

Taking $\alpha = \frac{2}{5}$ gives
$$\cos \frac{2 x}{5} \approx \frac{\phi}{2} + \left(1 - \frac{\phi}{2}\right) \cos x,$$ where $\phi := \frac{1 + \sqrt{5}}{2}$ is the Golden Ratio, and this approximation has maximum absolute error $\approx \frac{1}{110}$ on $J$.

For $\alpha \approx 0$, $\cos \alpha x \approx 1 - \frac{1}{2} \alpha^2 x^2$, so the error in the original approximation is maximized near $\pm x_0$, where $x_0 \approx 1.09882$ is the unique solution of $8 x = \pi^2 \sin x$ in $(0, \frac{\pi}{2})$, and the maximum absolute error is $O(\alpha^2)$.
Comment: Once more, you have been inspiring me. Thanks & cheers
Comment: @ClaudeLeibovici Cheers!
Answer: I prefer to add a separate answer since this one is more than much inspired by @Travis Willse's answer.
If we want the best approximation for
$$\cos(\alpha x) \approx A + B \cos( x)$$ consider again the infinite norm
$$\Phi(\alpha,A,B)=\int_0^{\frac \pi 2}\Big( A + B \cos( x)-\cos(\alpha x)  \Big)^2\,dx$$ which is
$$\frac{1}{4} \left(\frac{\sin (\pi  \alpha )}{\alpha }+2 \pi
   A^2-\frac{8 A \sin \left(\frac{\pi  \alpha }{2}\right)}{\alpha
   }+8 B \left(\frac{\cos \left(\frac{\pi  \alpha
   }{2}\right)}{\alpha ^2-1}+A\right)+\pi  B^2+\pi \right)$$ Computing the partial derivatives, we have
$$\frac{\partial \Phi(\alpha,A,B)}{\partial A}=-\frac{2 \sin \left(\frac{\pi  \alpha }{2}\right)}{\alpha }+\pi
   A+2 B$$
$$\frac{\partial \Phi(\alpha,A,B)}{\partial B}=\frac{2 \cos \left(\frac{\pi  \alpha }{2}\right)}{\alpha ^2-1}+2
   A+\frac{\pi  B}{2}$$
Solving
$$A=\frac{2 \pi  \left(\alpha ^2-1\right) \sin \left(\frac{\pi
   \alpha }{2}\right)+8 \alpha  \cos \left(\frac{\pi  \alpha
   }{2}\right)}{\left(\pi ^2-8\right) \alpha  \left(\alpha
   ^2-1\right)}$$
$$B=\frac{-8 \left(\alpha ^2-1\right) \sin \left(\frac{\pi  \alpha
   }{2}\right)-4 \pi  \alpha  \cos \left(\frac{\pi  \alpha
   }{2}\right)}{\left(\pi ^2-8\right) \alpha  \left(\alpha
   ^2-1\right)}$$
Computing
$$f(x)= A + B \cos( x)-\cos(\alpha x)$$ and assuming $\alpha$ close to $\frac 23$
$$f(0) =\frac{1}{188}-\frac{1}{393}\left(\alpha -\frac{2}{3}\right)+O\left(\left(\alpha -\frac{2}{3}\right)^2\right)$$
$$f\left(\frac{\pi }{2}\right)=\frac{2}{137}+\frac{1}{163}\left(\alpha -\frac{2}{3}\right)+O\left(\left(\alpha -\frac{2}{3}\right)^2\right)$$
$$\Phi(.)=\frac{1}{27087}-\frac{1}{30047}\left(\alpha -\frac{2}{3}\right)+O\left(\left(\alpha -\frac{2}{3}\right)^2\right)$$
None of these values can be very large.
So, for any value of $\alpha$, we have the corresponding $A$ and $B$.
For example, if $ \alpha=\frac 23$
$$ A=\frac{3 \left(5 \sqrt{3} \pi -24\right)}{10 \left(\pi^2-8\right)}=0.514599\qquad B=\frac{6 \left(3 \pi -5 \sqrt{3}\right)}{5 \left(\pi ^2-8\right)}=0.490707$$ For these values
$$\Phi(.)=\frac{3 \sqrt{3}}{16}+\frac{\pi }{4}+\frac{27 \left(80
   \sqrt{3}-49 \pi \right)}{200 \left(\pi ^2-8\right)}=3.69\times 10^{-5}$$ which is not much better than your $1.68\times 10^{-4}$
If, as in your post, you want $A=B$ regardless of their values,
$$\alpha=0.675440 \sim \frac{25}{37}=\frac 23+\frac{1}{111} \quad \implies \quad A=B\sim \frac{69}{137}=\frac 12+\frac{1}{274}  $$
Now, if we want the best combination, we need to solve for $\alpha$ the equation
$$\frac{\partial \Phi(\alpha,A,B)}{\partial \alpha}=0$$ which is too long to type here but which does not make any problem. The solution is
$$\alpha=0.697144\sim \frac 23+\frac 1{32}$$ which, in turn, gives
$$A\sim \frac 12-\frac 1{36}\quad\quad \text{and}\quad\quad B\sim \frac 12+\frac 1{30}$$
Answer: By using Maclaurin series
$$\cos(\frac{2}{3}\arccos x)=\frac12+\frac1{\sqrt3}x-\frac19 x^2+\frac{5}{54\sqrt3}x^3...$$
we have
$$\cos\frac23 x\approx\frac12+\frac1a\cos x\left(\frac a{\sqrt3}-\frac a9\cos x \right).$$
Minimizing $||
\frac a{\sqrt3}-\frac a9\cos x-1||_2$ we get $a=\frac{108\sqrt3\pi-72}{110\pi-48\sqrt3}\approx 1.9649.$


How to add range for combobox in c#?

Question: I have a combo box in table layout panel .I want to add the existing serial ports to it.But it doesn't show my ports in the items.It shows nothing.(I have to mention that when the combo box wasn't in table layout panel it worked, but now it doesn't).
private void Form1_Load(object sender, EventArgs e)
        {
            string[] ports = SerialPort.GetPortNames();
            cBoxComPort.Items.AddRange(ports);
        }

Comment: are you using Winforms?
Comment: @MongZhu yes.Can you help me with this?
Answer: You need InitializeComponent(); without it you should get a runtime exception.
public Form1()
{
    InitializeComponent();

    string[] ports = SerialPort.GetPortNames();
    cBoxComPort.Items.AddRange(ports);
}

How to add range for combobox in c#?


IserviceCollection does not contain defination of "AddDefaultIdentity"

Question: AddDefaultIdentity throwing error
'IServiceCollection' does not contain a definition for 'AddDefaultIdentity' and

no accessible extension method 'AddDefaultIdentity' accepting a first argument

of type 'IServiceCollection' could be found (are you missing a using directive or an assembly reference?)

WebApiDotNet.AddDefaultIdentity does not exist in IServiceCollection

Comment: What's your Identity configuration code in Startup.cs?
Answer:
'IServiceCollection' does not contain a definition for 'AddDefaultIdentity' and no accessible extension method 'AddDefaultIdentity' accepting a first argument of type 'IServiceCollection' could be found (are you missing a using directive or an assembly reference?)

I reproduced the issue when I installed Microsoft.AspNetCore.Identity.UI package higher than version 3.0 in a 3.0 project.  Note: AddDefaultIdentity extension method is used to add the default UI service for Razor Pages and MVC.
You could use AddIdentity instead of AddDefaultIdentity like below:
services.AddIdentity<ApplicationUser,IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

If you want to use AddDefaultIdentity, you should update the version of Microsoft.AspNetCore.Identity.UI to 3.0.
For the difference between AddDefaultIdentity and AddIdentity , refer to https://medium.com/@xsoheilalizadeh/asp-net-core-identity-deep-dive-stores-e0e54291b51d


Eigenvalues of a matrix product

Question: it is a well know result that for two $n\times n$ matrices $A$ and $B$ the eigenvalues of the product $AB$ are equal to those of the product $BA$.
Are there similar results for a product of $m>2$ matrices? E.g. does the product of four $n\times n$ matrices $ABCD$ have the same eigenvalues as $ACBD$?
Thanks for your help!
Comment: The only thing that can be said is what can be deduced from the first result, which is that eigenvalues are invariant under cyclic permutations, so $ABCD$ has the same eigenvalues as $DABC, CDAB$, and $BCDA$, and that's it.
Answer: Let check this on orthogonal matrices (e.g. rotations dim. $3 \times 3$).
We have for example $R_1R_1^TR_2R_2^T=I$ with $1$ as eigenvalues. If we change the order of rotations for example $R_1R_2(R_2R_1)^T=R_1R_2R_1^TR_2^T$ certainly if $R_1$ and $R_2$ are not commutative we would not obtain identity matrix and consequently the  eigenvalues are different.
Answer: In fact, $AB$ and $BA$ have the same characteristic polynomial.
The problem with expecting switches in between various other matrices to preserve eigenvalues, is that the characteristic polynomial does not behave well with multiplication of matrices from left/right.
In other words, if $A$ and $B$ have the same characteristic polynomial, then this may not be true of $CA$ and $CB$, where $C$ is some other matrix. This is because the trace(sum of eigenvalues) is not multiplicative in general, and we can use this to produce counterexamples.
To give an example, take $A = \begin{bmatrix}1 \ 0 \\ 0 \ 2 \end{bmatrix}$ and $B  = \begin{bmatrix} 1 \ 1 \\ 0 \ 2\end{bmatrix}$. These matrices have the same characteristic polynomial. For yourself, find a $C$ such that $CA$ and $CB$ have different trace, and therefore different eigenvalues. Find a  $D$ such that $AD$ and $BD$  have different trace. It follows that $CA,CB$ and $AD,BD$ don't have the same characteristic polynomials.
The stumbling block in trying to prove, say , that $CBA$  and $CAB$ have the same eigenvalues, is the inability to assure that multiplying by $C$, after knowing that the eigenvalues of $AB$ and $BA$ are the same, retains the equality of eigenvalues. This is why you can use the $C,A,B,D$ above to find counterexamples of the assertions you were making.
However, cyclic permutations retain eigenvalues, because we are just applying the "two-matrix" case to deduce this. For example, $ABCD = (AB)(CD)$ has the same eigenvalues as $(CD)(AB) = CDAB$ and so on. So while this is a generalization, it may not feel satisfactory.

Eigenvalues of a matrix product


computing weighted average over numpy.ndarray

Question: There two numpy.ndarray A and B; and both of which have shapes (3,20,5). C is a pandas.core.series.Series with length 20
I would like to compute a weighted average array D based on A, B and C, based on the formula
D[:,x,:] = A[:,x,:]*C[x]+B[:,x,:]*(1-C[x])

What's the right way to implement this based on the best practice in Numpy, without iterating over the related 3-dimension array
Answer: You can try this:
c = C.to_numpy().reshape(-1, 1)
D = A*c + B*(1-c)

Comment: thanks, I have a question regarding the answer, so the c will be automatically broadcasted into the second dimension of both A and B. if A and B have shapes (3,20,20), how should we solve this?
Comment: If you still want to broadcast `c` over the second dimension then the same code will work (the last dimension of `c` is 1, so it will be broadcast over the last dimension of `A` and `B`). [Here](https://jakevdp.github.io/PythonDataScienceHandbook/02.05-computation-on-arrays-broadcasting.html#Rules-of-Broadcasting) is a nice summary of numpy broadcasting rules.


How to remove bathtub drain plug?

Question:
Any tips on how to remove drain plug?
Comment: look for a screw on the side
Answer: While holding the bottom part, unscrew the top part and it will come out

How to remove bathtub drain plug?


Kubuntu: Broken Plasma Desktop after accidentally removing packages

Question: While trying to install unofficial radeon drivers from padoka, I've ended up with broken package (some intel-related file has been modified by both ubuntu ppa and padoka one). Apt suggested running apt-get with --fix-broken parameter, so I did. As a result of this, half of my DE had been uninstalled - file manager, utilities, etc.
I've reinstalled kubuntu-full package and got most of it back, but something must be still missing, as my desktop (after reboot) looks like this:

I've tried:

logging in as another user - same situation.
switching DE to xfce - xfce is unnafected and works OK.
reinstalling all packages - no difference.
observing auto-removable packages - list contains 100 entries, these may be dependencies of some packages I've failed to reinstall after the "fix broken". Possibly notable examples: gir1.2-*, kde-wallpapers-default, libvulkan1, libwayland-bin, many python libraries.

So, my actual questions:

which packages are responsible for rendering the missing elements?
which log files could contain info regarding this?

Thanks for any help; I would love to keep my current installation and avoid full system reinstall...
Edit, Additional info:

Kubuntu 17.04
Kde Plasma 5.94
Kernel 4.10.0-19-g

Everything else - graphics related or not - seems to work as expected.
Answer: Sorry for the previous comment.
After some tests I managed to recover my KDE desktop by installing all the libqt5* packages.
apt-cache search libqt5 | awk '{print $1}'| grep -v "\-dev" | grep -v "\-dbg"

I was not able to detect the exact missing packages so this solution is a little a "brute force" one.
After the install you need to logoff / logon and the KDE desktop should be  right in place.
Comment: Thank you, thank you, thank you, kind person on the internet :)
I had to do minor tweak to get it working: I had to remove -gles packages from the list; also, somehow kwin-x11 package was missing too. But after installing all this, my KDE is back in all its glory!


Google Analytics - dynamic segment with conditions api

Question: I have a segment in GA that does the following....
It is a conditional segment
Filter Sessions
Exclude

Network Domain - exactly Matched - unknown.unknown
AND
medium - exactly matches - (none)
AND
Country/Territory - matches regex - united\ states|ireland
AND
Transactions - Per Session = 0

This works as I want in the user interface
(I know this is a little bit over the top, but we are getting hit by non identifiable traffic at the moment and until i can filter it out this is what i need to use)
I also have a number of rpeorts that run off the api that I would like to add this segment to.
I have written the following dynamic segment but it doesnt properly work
sessions::condition::ga:networkdomain!~unknown\.unknown;ga:medium!~\(none\);ga:country!~united states|ireland|australia;perSession::ga:transactions>0

It seems to be excluding each one individually and not as a condition
Has anyone had anyluck with an exclusion segment over the api with conditions, could you give me some pointers
Cheers
Answer: It seems this is a missing feature in GA API: https://code.google.com/p/analytics-issues/issues/detail?id=414


Basement Bathroom Venting Help

Question: Our basement has been roughed in for a bathroom. My layout has a three floor PVC pipes coming out of the ground. The left most pipe has a tipped over bucket cemented onto the floor. There is a middle pipe at 2.5 inches and a 1.5 inch all the way to the right.
I'm GUESSING the toilet is the left most, not sure what is under the bucket, but maybe preventing the smell? There is a a plastic capped PVC pip coming down from the ceiling labeled 'BATH VENT' between the middle and right most PVC pipe.
If I would like a shower/toilet/sink in this space, does only the sink need to be attached to that overhead vent, or do all 3?
Comment: Hello, and welcome to Home Improvement. The diagram helps, but  pictures would  be even more helpful.
Answer: I'm going to venture a guess here (at least until photos come). 2.5" isn't a pipe size so I'm going to go out on a limb and call it 3 inch that will be for your toilet. Regarding the bucket I'm going to guess that only a bottom half of the bucket is showing which means that there is a space in there to put a trap for a shower or tub. If the previous statements are correct then the one and a half inch pipe is really a 2"  which is a wet vent for your sink.
In the floor it would look somewhat like thiswww.doityourself.com
Answer: Agree with Daniel, pictures and measurements of distance between fixtures would help. If they are all aligned like this, yes you could tie all three into the common vent and be good to go.  The toilet will need a vent, most commonly wet vented to the nearest fixture by at least a 3" vent. Add some pics and more details.

Basement Bathroom Venting Help


Orderby dictionary like data structure by value angular

Question: I'm trying to order an object data structure by the value.
{apple: 1, pear: 85, orange: 24, blueberry: 18}
I want to achieve a reorder by value in DESC order. I don't think there is a a method to do so, even if this object was wrapped in an Array, but wanted to check.
My other thought process was to separate the key value pair into 2 separate arrays. Then loop the value array, search for the max vale and capture the index at that point and that particular index should match at the key array. Then i can move the key/value pair into a third/separate array keeping order by max value. Then based on the index number captured, pop from both the key and value array.
If there is a better method please feel free to share?
Comment: Dictionaries (hashtables, maps, etc) are generally not ordered - it's inherent in the way hashtables are implemented (either by key or by value). What you'll want to do is copy the values into an array (which does have order) and then sort it using a custom comparator if your values are non-scalar.
Answer: An Object's keys are not sorted, so you will not be able to achieve what you want with just an Object.
If you use an Array, however, you can use Array.sort():

const myArray = [{apple: 1}, {pear: 85}, {orange: 24}, {blueberry: 18}]
myArray.sort((e1, e2) => Object.values(e2)[0] - Object.values(e1)[0])
console.log(myArray)
Comment: I edited my answer to correct the comparaison function. The problem was that Array.sort expects `(x, y) => number` and not `(x, y) => boolean`.
Comment: I get this error: Argument of type '(e1: any, e2: any) => boolean' is not assignable to parameter of type '(a: any, b: any) => number'.
  Type 'boolean' is not assignable to type 'number'.
Comment: this is an example of the array with objects:::: [{assailing: 1},{haters: 1},{trump: 10}]
Comment: Could this error be caused by a number in the key position? For example, i have some values (not mentioned in my example) like [{2018: 10}, { 2: 14}, {men: 3}] and so on..
Comment: so does that loop the array and each time value to the right is larger than to the left it places it above ?


Points A, B and C have position vectors a = i + 2 j, b = 2i + j and c = 2i − 3 j. Find the shortest distance from B to line AC

Question: Points A, B and C have position vectors a = i + 2 j, b = 2i + j and c = 2i − 3 j. Find:

The shortest distance from B to line AC
The area of triangle ABC

What I have done so far:
Found AB and AC and hence, the vector resolute of AB in the direction of AC.
According to my working out this is 3/13 (i - 5j).
From here onwards, I'm not sure how to construct a diagram/show the working out to get the shortest distance from B to line AC. The answer key shows the shortest distance is obtained by:
AB - 3/13 (i - 5j)
^^How does this come about though? From here, I can work out the area of the triangle formed by A, B & C.
Any tips/help would be appreciated!
Comment: $\mathbf {AB}$ can be resolved into perpendicular components:  one is along $\mathbf{AC}$ and one is perpendicular to that; the length of the one perpendicular to that is the shortest distance from $B$ to line $AC$
Answer: We can  find the length of AB and then project it onto the line AC and then applying Pythagoras' theorem find the third side of the triangle which is the shortest distance of B from AC
$ |{\bf AB}|=|{\bf i-  j}| =\sqrt{2}\\
\frac{{\bf AB}.{\bf AC}}{|{\bf AC}|}=\frac{6}{\sqrt{26}}$
Thus the shortest distance is $\sqrt{2-\frac{36}{26}} =\frac{4}{\sqrt{26}}$
Answer:
The area of $\triangle ABC$ given $2D$ coordinates
of the vertices $(A_x,A_y),\ (B_x,B_y),\ (C_x,C_y)$
is given by
\begin{align}
S_{ABC}
&=
\tfrac12\,|(B_x-A_x)(C_y-A_y)-(C_x-A_x)(B_y-A_y)|
\\
&=
\tfrac12\,|(2-1)(-3-2)-(2-1)(1-2)|
=2
.
\end{align}
The shortest distance from the point $B$ to the line $AC$
is the altitude $|BD|$ of $\triangle ABC$,
so given that the area $S_{ABC}$ of $\triangle ABC$,
can be also expressed as
\begin{align}
S_{ABC}&=\tfrac12\cdot|AC|\cdot|BD|
\end{align}
we can find it as
\begin{align}
|BD|&=
\frac{2\,S_{ABC}}{|AC|}
=\frac{2\cdot2}{\sqrt{26}}
=\tfrac2{13}\,\sqrt{26}
\approx 0.78446454
.
\end{align}
Note that we don't actually need to find the coordinates of the point $D$,
if we just need the distance $|BD|$.


network login vs. network cable

Question: I disconnected network cable to .... move it. when I reconnect it the whole system had problem with it. I was not able to execute console or log in(on ctrl+shift+fx consoles). after some time 20 consoles (gnome-terminal) did open. however I still have no internet.
P.S. I do not have root account
how can I restart network card? do I need to restart system?
Answer: I am not sure why you were not able to connect to other tty's, but it sounds like your network needs to reestablish an IP address from your router or modem. If your using Network Manager, you should just be able to click the Wired connection, however, (this may not work without root permissions) you could run the command dhcpcd eth0 (or the approperate wired interface) and it'll get you connected again. Simple restart should do the trick if all else fails.

network login vs. network cable


Should I use placeholders in just some of the form fields?

Question: Suppose we've got a form with a number of input supported with labels and placeholder.
Label helps to identify the whole input idea (whether it's for First name or Salary).
The purpose of placeholder is to provide an example of input data.

Is it fine to place first/last name examples in placeholder (that just seem a little weird for me, because label's already provided some info), isn't this too verbose?
Won't leaving some placeholders blank somehow mislead users?
Answer: Placeholder values are typically used as a means of prompting input-appropriate formatting (such as firstname.lastname@example.com).  If you do use them, they shouldn't be the only means of describing the input being requested (Does the content of the HTML5 placeholder attribute affect usability?).
They're also often used to help the user identify which fields are necessary (marked as required within placeholder) and which are not.  In this sense, appropriate use and absence of placeholders actually works to reduce user confusion.
Answer: This depends on how simple or complicated the format is that your fields require. If the input is required in a special/not-so-intuit form you can use spaceholders but i would not use it only on some fields.
Think about adding tooltips or a label in smaller font under the textfield with more information. E.g. under a textfield for a email-address you can write "* required. Must be valid. No spam from us."
At 2) i don't think it will mislead the user but is not so good looking. if you add placeholders you can maybe do that with a light grey font instead of black (if user input is displayed black).
Comment: Currently I'm thinking about a small-font tooltip right below label, but there's no need in placeholders. I think instead of placeholders it's better to use some sort of on-focus tooltip.


Oracle alphanumeric sequence

Question: I need to create an alphanumeric sequence in oracle but can't figure that out. Already checked the existing questions, but not fully understand it (my sql knowledge is not that great).
The number 00001 will increase up to 00009 then new series will start with 00000A and will increase up to 00000Z.
Then the new series will start with 0000A1 and will increase up to 0000A9, after this number the new number will start with 0000AA and go up to 0000AZ.
Then comes the number 0000B1 which goes upto 0000B9 then new series start with 0000BA till 0000BZ and so on.
As well the sequence should have a  prefix, for example CNT00000Z, CNT0000A1
I've tried to test different setups using a wrapper function with different oracle converting functions like substr, mod, to_char, etc. but with no success.
If you have any ideas I would be grateful.
Cheers,
Alexandru
Comment: Will converting a numeric sequence to [base 36](https://www.unitconverters.net/numbers/decimal-to-base-36.htm) do it? It's not exactly what you described though, as the number after `Z` will be `10`, not `A1`.
Comment: There's another option: You could have a normal numeric sequence and *render* the id as base36 and/or *parse* as base36 if a client sends it as the entity key. This transformation would be easiest to perform in the app layer, but could happen in SQL albeit ugly.
Comment: In this Case, better idea would be to write a "Before Insert" Trigger
Comment: how important is it that it starts with 1 and not A ? In oracle apex there is a function called compress_int that transforms an integer in to a similar string. But it starts with AAAB, AAAC, ... AAA1,AAA2,... . You could easily replace the leading 'A' with '0'. The code for that function is available. If the requirement is to generate a unique string based on an integer this will satisfy your requirement. If the requirement is to produce a string *exactly* like yours then it won't.
Comment: @WilliamRobertson I'm afraid I will need the sequence in base 10 (decimal).
Comment: @Bohemian same as I've told to William, I will need the sequence in base 10
Comment: @KoenLostrie it's a requirement to start the sequence with 1
Comment: I'm not sure what you mean. `0000A1` is not decimal. What you are describing is more or less base 36 (you just want to go straight from `00000Z` to `0000A1` skipping `000010` - `0000A0` or whatever it is - typing this on my phone so can't check). It shouldn't be hard to take a normally generated sequence and convert it to base 36.
Comment: Hi @WilliamRobertson, my bad, misunderstood your answer. I think that will work, but I will have to tweak a custom convert function because I'll have to exclude the letters 'I' and 'O' (so it would be a custom base 34?)
Answer: Well...without a zero and I and O, then it would be custom base33 not base34.  To do a "legitimate" version where the digits/letters ascend in the normal fashion no matter what decimal position you are at, you can do this
SQL> create or replace
  2  function int_to_seq(n in integer ) return varchar2    as
  3     ret       varchar2(30);
  4     quotient  integer;
  5     digit     char(1);
  6     chars varchar2(100) := '123456789ABCDEFGHJKLMNPQRSTUVWXYZ';
  7     len int := length(chars)+1;
  8  begin
  9     quotient := n;
 10     while quotient > 0
 11     loop
 12         ret := substr(chars,mod(quotient,len),1) || ret;
 13         quotient := floor(quotient/len);
 14     end loop ;
 15     return 'CNT'||lpad(ret, 10, '0');
 16  end ;
 17  /

Function created.

SQL>
SQL> select rownum, int_to_seq(rownum) x
  2  from dual
  3  connect by level <= 36
  4  /

    ROWNUM X
---------- ----------------------------------------
         1 CNT0000000001
         2 CNT0000000002
         3 CNT0000000003
         4 CNT0000000004
         5 CNT0000000005
         6 CNT0000000006
         7 CNT0000000007
         8 CNT0000000008
         9 CNT0000000009
        10 CNT000000000A
        11 CNT000000000B
        12 CNT000000000C
        13 CNT000000000D
        14 CNT000000000E
        15 CNT000000000F
        16 CNT000000000G
        17 CNT000000000H
        18 CNT000000000J
        19 CNT000000000K
        20 CNT000000000L
        21 CNT000000000M
        22 CNT000000000N
        23 CNT000000000P
        24 CNT000000000Q
        25 CNT000000000R
        26 CNT000000000S
        27 CNT000000000T
        28 CNT000000000U
        29 CNT000000000V
        30 CNT000000000W
        31 CNT000000000X
        32 CNT000000000Y
        33 CNT000000000Z
        34 CNT0000000011
        35 CNT0000000011
        36 CNT0000000012

36 rows selected.

But if you really want the 2nd power onwards to start with "A", but the final place going through all 33 characters, then you can do this
SQL> create or replace
  2  function int_to_seq2(n in integer ) return varchar2    as
  3     ret       varchar2(30);
  4     quotient  integer;
  5     digit     char(1);
  6     chars varchar2(100) := '123456789ABCDEFGHJKLMNPQRSTUVWXYZ';
  7     chars2 varchar2(100) := 'ABCDEFGHJKLMNPQRSTUVWXYZ';
  8     len int := length(chars)+1;
  9  begin
 10     quotient := n;
 11     ret := substr(chars,mod(quotient,len),1) || ret;
 12     quotient := floor(quotient/len);
 13     len := length(chars2)+1;
 14     while quotient > 0
 15     loop
 16         ret := substr(chars2,mod(quotient,len),1) || ret;
 17         quotient := floor(quotient/len);
 18     end loop ;
 19     return 'CNT'||lpad(ret, 10, '0');
 20  end ;
 21  /

Function created.

SQL>
SQL> select rownum, int_to_seq2(rownum) x
  2  from dual
  3  connect by level <= 100
  4  /

    ROWNUM X
---------- ----------------------------------------
         1 CNT0000000001
         2 CNT0000000002
         3 CNT0000000003
         4 CNT0000000004
         5 CNT0000000005
         6 CNT0000000006
         7 CNT0000000007
         8 CNT0000000008
         9 CNT0000000009
        10 CNT000000000A
        11 CNT000000000B
        12 CNT000000000C
        13 CNT000000000D
        14 CNT000000000E
        15 CNT000000000F
        16 CNT000000000G
        17 CNT000000000H
        18 CNT000000000J
        19 CNT000000000K
        20 CNT000000000L
        21 CNT000000000M
        22 CNT000000000N
        23 CNT000000000P
        24 CNT000000000Q
        25 CNT000000000R
        26 CNT000000000S
        27 CNT000000000T
        28 CNT000000000U
        29 CNT000000000V
        30 CNT000000000W
        31 CNT000000000X
        32 CNT000000000Y
        33 CNT000000000Z
        34 CNT00000000A1
        35 CNT00000000A1
        36 CNT00000000A2
        37 CNT00000000A3
        38 CNT00000000A4
        39 CNT00000000A5
        40 CNT00000000A6
        41 CNT00000000A7
        42 CNT00000000A8
        43 CNT00000000A9
        44 CNT00000000AA
        45 CNT00000000AB
        46 CNT00000000AC
        47 CNT00000000AD
        48 CNT00000000AE
        49 CNT00000000AF
        50 CNT00000000AG
        51 CNT00000000AH
        52 CNT00000000AJ
        53 CNT00000000AK
        54 CNT00000000AL
        55 CNT00000000AM
        56 CNT00000000AN
        57 CNT00000000AP
        58 CNT00000000AQ
        59 CNT00000000AR
        60 CNT00000000AS
        61 CNT00000000AT
        62 CNT00000000AU
        63 CNT00000000AV
        64 CNT00000000AW
        65 CNT00000000AX
        66 CNT00000000AY
        67 CNT00000000AZ
        68 CNT00000000B1
        69 CNT00000000B1
        70 CNT00000000B2
        71 CNT00000000B3
        72 CNT00000000B4
        73 CNT00000000B5
        74 CNT00000000B6
        75 CNT00000000B7
        76 CNT00000000B8
        77 CNT00000000B9
        78 CNT00000000BA
        79 CNT00000000BB
        80 CNT00000000BC
        81 CNT00000000BD
        82 CNT00000000BE
        83 CNT00000000BF
        84 CNT00000000BG
        85 CNT00000000BH
        86 CNT00000000BJ
        87 CNT00000000BK
        88 CNT00000000BL
        89 CNT00000000BM
        90 CNT00000000BN
        91 CNT00000000BP
        92 CNT00000000BQ
        93 CNT00000000BR
        94 CNT00000000BS
        95 CNT00000000BT
        96 CNT00000000BU
        97 CNT00000000BV
        98 CNT00000000BW
        99 CNT00000000BX
       100 CNT00000000BY

100 rows selected.

SQL>
SQL>
SQL>

Comment: Thanks @Connor McDonald. That's exactly what I need.

Oracle alphanumeric sequence


What is the distribution of $X+Y$ if $X$ and $Y$ come from a bivariate normal distribution?

Question: Further assume that the conditional distribution of $X$ given $Y=y$ is $N(y,1)$ and that the distribution of $Y$ is $N(0,\sigma^2)$. What is the distribution of $X+Y$?
One technique that seems applicable is to note that $X+Y= X-Y+2Y$. If we show that $X-Y$ and $Y$ are independent and determine their parameters (where both must have normal distributions) then we can determine the distribution of $X+Y$ which is normal.
Comment: Characteristic functions are the easiest way (and I guess that X and Y are independent ?).
Comment: Saying "conditional distribution of $X$ given $Y=y$ is $N(y,1)$" looks equivalent to saying "$X-Y\sim N(0,1)$ for each possible value of $Y$ and so is independent of $Y$"
Answer: $$E(X|Y)=Y,\  E(X^2|Y)=1+Y^2,\  E(X^2)=1+\sigma^2.$$
$$E(XY)=E(E(XY|Y))=E(YE(X|Y))=E(Y^2)=\sigma^2.$$
$$E((X+Y)^2)=1+4\sigma^2\Rightarrow X+Y\sim N(0,1+4\sigma^2).$$
Comment: How does does it follow from Var$(X+Y)=1+4\sigma^2$ that $X+Y$ is normally distributed? I think characteristic functions are a safer bet here...
Comment: I think that is because $X$ and $Y$ have a joint bivariate normal distribution.
Comment: Ah I overlooked that. Technically you do not need that assumption about the distribution of $(X,Y)$ though. The result also holds only with the assumptions in your question


Make Ionic Native Camera Plugin only take pictures from FRONT camera

Question: My current options for taking photos from an iPad camera in my Ionic/Cordova application are as follows:
<code>const options: CameraOptions = {
        quality: 70,
        destinationType: this.camera.DestinationType.DATA_URL,
        encodingType: this.camera.EncodingType.JPEG,
        mediaType: this.camera.MediaType.PICTURE,
        correctOrientation: true,
        cameraDirection: this.camera.Direction.FRONT
    };
</code>
I read on the Cordova documentation that setting the property cameraDirection tells which camera you want to use when you take a picture on a device using your app. I set the direction to front, hoping this would mean that only front facing pictures would be accepted. Unfortunately, I am still able to switch to my back camera once the camera app is opened.
Is there a way to limit the camera to only being used by the front facing camera?
Answer: Short answer: Not with Cordova, because the Camera plugin uses a native camera from the device that always includes the rotation button. You can however create a custom camera plugin (in Java) to get rid of all buttons but this requires plenty of Java knowledge.


Can I change apache web server user and group?

Question: I'm not too familiar with file ownership etc. in Linux but here's my problem. I log into my ubuntu (dev machine) which is local as let's say user abc group xyz.
Now files that reside under /var/www/vhosts/abc.com/htdocs when created are owned by abc:xyz. In order for web server to run them I have to do sudo chown -R www-data:www-data . which works like a charm. Problem is that I can't edit these files with my text editor since these files are not owned by abc:xyz.
Ideally I want my web server group to be replaced with abc and group to be replaced with xyz (if possible) so that files are both editable through IDE and executable by the web server user. I don't like the idea of symlinking files/directories from elsewhere.
Any advice on this will be greatly appreciated.
Answer: You can change the user apache runs as - from www-data to whatever fits you best. However, I wouldn't advise you to do that. Or at least you should select a dedicated user for apache - user that won't be used for anything else.
The better option is to make www-data user a member of xyz group. That way apache will be able to read/execute whatever needed (just don't forget that your directories in /var/www/ must have +x for the group, all scripts and files will be fine with +r for group).


UWP / Visual Studio: How to make different builds variants?

Question: I need to have three different build variants (flavors) of my UWP app that can be installed parallel: one for production, one for testing and one for development. They obviously need to share the same code base but have different constants like backend URLs and API keys.
In Android Studio this can be done using "build variants" and in Xcode this can be done using "schemes". What's the Visual Studio equivalent of those?
Maybe "build configurations" using the Configuration Manager as in https://msdn.microsoft.com/en-us/library/kwybya3w.aspx is the way to go. By default I have a Debug and a Release configuration. Would it be correct to rename those to Production-Debug and Production-Release and then create Testing-Debug, Testing-Release, Development-Debug and Development-Release? What I don't understand though:

Will that allow me to install Production, Testing and Development parallel on the same device?
How do I know which flavor I'm running in code (in order to get different properties, constants)?

EDIT: This is about UWP apps, not about web apps.
Comment: I would be very glad if you can show me where is Web.Debug.Config within the scope of UWP app
Comment: @Tony_KiloPapaMikeGolf I think web.config is not relevant here, I'm talking about UWP apps.
Comment: You are right , [read this](http://amadeusw.com/iot/custom-resource-files-in-uwp-windows-10) On UWP, there is no access to System.Configuration.ConfigurationManager
Comment: Possible duplicate of [Web.Debug.config vs. Web.Release.config running web app in localhost](http://stackoverflow.com/questions/40921566/web-debug-config-vs-web-release-config-running-web-app-in-localhost)
Comment: @Tony_KiloPapaMikeGolf Thanks. But that is not what I'm looking for. I need a configuration that allows me to have "three different build variants (flavors) of my UWP app that can be installed parallel".
Answer: You can just use conditionals like this:
<code><AppxManifest Include="Manifest.Debug.xml"
              Condition="'$(Configuration)'=='Debug'">
  <SubType>Designer</SubType>
</AppxManifest>
<AppxManifest Include="Package.appxmanifest"
              Condition="'$(Configuration)'=='Release'">
  <SubType>Designer</SubType>
</AppxManifest>
</code>
Comment: @Allstar, no, you make a debug variant of `Package.appxmanifest`, and name it `Manifest.Debug.xml`. The code above goes into the `.csproj` (UWP) or `.wapproj` (packaged desktop app).
Comment: where does the code go exactly, within `Package.appxmanifest` ?
Comment: thanks @LOST, it works. I just had to change the Name under `Identity` in the new manifest file.
Answer: Double click on Package.appxmanifest file in your project.
Select Packaging label and enter different Package names for different cases.
Store each of variants.
Your PC gonna think these are different UWP apps.
Comment: But how can I assign the different appxmanifest files to the build configurations?
Comment: Seems like you can't or I didn't dig that far. It was like an alternative variant. Also you may try make branches of your project and merge code among them.
Comment: Then let me try to dig that far... :)
Answer: I've found a solution using this guide: http://grogansoft.com/blog/?p=1087
I basically ended up having an appxmanifest (renamed to appxmanifest2 since you can only have one appxmanifest per project) per build configuration and then in the build events "pre-build event command line" I'm copying the one I need into the project root.
For the constants I'm using pre-processor conditional compilation symbols.
Comment: You need not rename the other appxmanifest. Simply change the 'Build Action' property of it to 'None'. Since you are copying it to the project root in pre-build events, finally you would have only one appxmanifest in your project folder.


how to store Tmail object in resque

Question: I know we cant keep objects directly in redis queue. I converted it to string using Marsal.dump(tmail_object)
while fetching i am using
Marshal.load(tmail_object)
but the object is changing i guess. I get empty email when i send email using that object.
What is the best way to store tmail object in redis queue. I am actually sending email using scheduled job used resque scheduler.
please advice.
Answer: The better way is pass params needed to generate your Tmail object in resque and generate this Tmail object in your job.
You limit your size of data save on your redis and save time to generate this tmail object before push it on your resque job.

how to store Tmail object in resque


fit_generator trains with 0 accuracy

Question: I'm trying to make a model from scratch using TensorFlow, Keras and ImageDataGenerator, but it does not go as expected. I use the generator just for loading the images, so no data augmentation is used. There are two folders with train and test data, each folder has 36 subfolders filled with images. I get the following output:
Using TensorFlow backend.
Found 13268 images belonging to 36 classes.
Found 3345 images belonging to 36 classes.
Epoch 1/2
1/3 [=========>....................] - ETA: 0s - loss: 15.2706 - acc: 0.0000e+00
3/3 [==============================] - 1s 180ms/step - loss: 14.7610 - acc: 0.0667 - val_loss: 15.6144 - val_acc: 0.0312
Epoch 2/2
1/3 [=========>....................] - ETA: 0s - loss: 14.5063 - acc: 0.1000
3/3 [==============================] - 0s 32ms/step - loss: 15.5808 - acc: 0.0333 - val_loss: 15.6144 - val_acc: 0.0312

Even though it seems OK, apparently it does not train at all. I've tried using different amount of epochs, steps and larger datasets - almost nothing changes. It takes around half a second to train each epoch even with over 60k images! The weird thing is that when I tried saving images to respective folders, it saves only around 500-600 of them and most likely stops.
from tensorflow.python.keras.applications import ResNet50
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Dense, Flatten, GlobalAveragePooling2D, Conv2D, Dropout
from tensorflow.python.keras.applications.resnet50 import preprocess_input
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator
import keras
import os

if __name__ == '__main__':
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

    image_size = 28
    img_rows = 28
    img_cols = 28
    num_classes = 36

    data_generator = ImageDataGenerator()

    train_generator = data_generator.flow_from_directory(
        directory="/final train 1 of 5/",
        save_to_dir="/image generator output/train/",
        target_size=(image_size, image_size),
        color_mode="grayscale",
        batch_size=10,
        class_mode='categorical')

    validation_generator = data_generator.flow_from_directory(
        directory="/final test 1 of 5/",
        save_to_dir="/image generator output/test/",
        target_size=(image_size, image_size),
        color_mode="grayscale",
        class_mode='categorical')

    model = Sequential()
    model.add(Conv2D(20, kernel_size=(3, 3),
                     activation='relu',
                     input_shape=(img_rows, img_cols, 1)))
    model.add(Conv2D(20, kernel_size=(3, 3), activation='relu'))
    model.add(Flatten())
    model.add(Dense(100, activation='relu'))
    model.add(Dense(num_classes, activation='softmax'))

    model.compile(loss=keras.losses.categorical_crossentropy,
                  optimizer='adam',  # adam/sgd
                  metrics=['accuracy'])

    model.fit_generator(train_generator,
                        steps_per_epoch=3,
                        epochs=2,
                        validation_data=validation_generator,
                        validation_steps=1)

Seems like something silently fails and cripples the training process.
Answer: The problem is that you are misunderstanding the steps_per_epoch argument of fit_generator. Let's take a look at the documentation:

steps_per_epoch: Integer. Total number of steps (batches of samples) to yield from generator before declaring one epoch finished and starting the next epoch. It should typically be equal to the number of samples of your dataset divided by the batch size. Optional for Sequence: if unspecified, will use the len(generator) as a number of steps.

So basically, it determines how many batches would be generated in each epoch. Since, by definition, an epoch means to go over the whole training data therefore we must set this argument to the total number of samples divided by batch size. So in your example it would be steps_per_epoch = 13268 // 10. Of course, as mentioned in the docs, you can leave it unspecified and it would automatically infer that.
Further, the same thing applies to validation_steps argument as well.
Comment: Thank you for the response, but apparently the problem is in something different. I just copy-pasted those values from a tutorial on Kaggle. After I removed them, it calculated 1327 steps, but the training was still very quick and not fruitful, resulting in `1327/1327 [==============================] - 26s 20ms/step - loss: 15.6347 - acc: 0.0300 - val_loss: 15.9109 - val_acc: 0.0129` Why the accuracy could be that low? It was around 40% with Apple's CreateML tool on exact same data (afaik they use transfer learning though)
Comment: @ethamine I don't know about the specific task and dataset you are working on. One reason might be that you are not normalizing the images. Pass `rescale=1/255.` as an argument to `ImageDataGenerator` and see if it helps. Further, depending on the number of images and complexity of the task, your network might be too small and therefore underfit.
Answer: As @today suggested the problem was in not normalized images.
Passing rescale=1/255 to ImageDataGenerator solved it.

fit_generator trains with 0 accuracy


Merge two array of objects using lodash

Question: I have two arrays of objects called movies and movieDetails:
const movies = [{
        movieID: 0,
        movieDetailsID: 9,
        movieName: "Dragonball Z",
        cost: 10
    },
    {
        movieID: 1,
        movieDetailsID: 10,
        movieName: "Spider Man",
        cost: 15
    },
    {
        movieID: 2,
        movieDetailsID: 11,
        movieName: "John Wick",
        cost: 20
    }
];

const movieDetails = [{
        movieDetailsID: 10,
        actor: "John Doe",
        fee: 100
    },
    {
        movieDetailsID: 10,
        actor: "Harry Styles",
        fee: 120
    },
    {
        movieDetailsID: 11,
        actor: "John Bane",
        fee: 200
    }
];

I would like to some how merge these two array of objects and add details only if there is a matching movieDetailsID. I was thinking of using low dash for this?
I would like to choose each objects (column names) I want to see from movies and movies details in my output i.e, for movies: movie name and cost. and movie details: actor and cost.

Expected Output:
 {
    movieID: 0,
    movieDetailsID: 9,
    movieName: "Dragonball Z",
    cost: 10
}, {
    movieID: 1,
    movieDetailsID: 10,
    movieName: "Spider Man",
    cost: 15,
    details: [{
            movieDetailsID: 10,
            actor: "John Doe",
            fee: 100
        },
        {
            movieDetailsID: 10,
            actor: "Harry Styles",
            fee: 120
        }
    ]
}, {
    movieID: 2,
    movieDetailsID: 11,
    movieName: "John Wick",
    cost: 20,
    details: [{
        movieDetailsID: 11,
        actor: "John Bane",
        fee: 200
    }]
}

What I have tried . However this seems to merge it in and doesnt create a seperate ovject details to add in those matching movie details ids.
var mergedList = _.map(movies, function(item){
        return _.extend(item, _.findWhere(movieDetailsID, { movieDetailsID: item.movieDetailsID }));
      });

Answer: There you are, lodash solution, extremely simple
import groupBy from "lodash/groupBy";
import reduce from "lodash/reduce";

const result = reduce(movies, ([movieDetailsIndex, res], movie) => [
  movieDetailsIndex,
  [...res, {...movie, ...(movieDetailsIndex[movie.movieDetailsID] ?
    {details: movieDetailsIndex[movie.movieDetailsID]} : {}
  )}]
], [groupBy(movieDetails, "movieDetailsID"), []])[1];

Answer: If I understood everything, here's a solution in pure JS:

const movies = [
  {
    movieID: 0,
    movieDetailsID: 9,
    movieName: "Dragonball Z",
    cost: 10
  },
  {
    movieID: 1,
    movieDetailsID: 10,
    movieName: "Spider Man",
    cost: 15
  },
  {
    movieID: 2,
    movieDetailsID: 11,
    movieName: "John Wick",
    cost: 20
  }
];

const movieDetails = [
  {
    movieDetailsID: 10,
    actor: "John Doe",
    fee: 100
  },
  {
    movieDetailsID: 10,
    actor: "Harry Styles",
    fee: 120
  },
  {
    movieDetailsID: 11,
    actor: "John Bane",
    fee: 200
  }
];

const result = movies.map(movie => {
  const details = movieDetails.filter(md => md.movieDetailsID === movie.movieDetailsID);

  const { movieID, movieDetailsID, ...movieKeys } = movie;

  const filteredMovie = { ...movieKeys };

  if (details.length) {
    const filteredDetails = details.map(({
      movieDetailsID,
      ...keys
    }) => keys);

    return ({
        ...filteredMovie,
        details: filteredDetails,
    });
  }

  return filteredMovie;
});

console.log(result);

Merge two array of objects using lodash


How do I get a TIFF bytestream from an OpenCV image, rather than a numpy array?

Question: In python, I want to convert an image that has been processed using OpenCV for transmission in a certain image format (TIFF in this case, but could be: BMP, JPEG, PNG, .....).
For this purpose it will suffice to encode the OpenCV image into a memory buffer. The problem is that when I use cv2.imencode() to do this the returned object still looks like a numpy array:
import cv2
img_cv2_aka_nparr = cv2.imread('test.jpg')
my_format = '.tiff'
retval, im_buffer = cv2.imencode(my_format, img_cv2_aka_nparr)
print type(im_buffer)

im_buffer is just another numpy array - it is not at all a TIFF-encoded bytestream! As far as I can tell, OpenCV images in python always behave like numpy arrays, and even look like numpy arrays via type().
In fact, if you want to create a dummy "OpenCV image", you have to use numpy - see e.g. https://stackoverflow.com/a/22921648/1021819
Why is this, and how do I fix it? That is, how do I obtain an actual TIFF-encoded bytestream rather than another numpy array?
Now I love numpy, but in this case I need the image to be readable by non-python services, so it needs to be in a commonly-available (preferably lossless) format (see list above).
(I've gone round the houses of embedding numpy within JSON and decided against it.)
I could use PIL/pillow, scipy, and some, but I am trying to minimize dependencies (i.e. so far only cv2, numpy and intrinsics).
Thanks!
Comment: "it is not at all a TIFF-encoded bytestream" -- Sure it is, contained in a single row numpy array.
Comment: @DanMašek Interesting... So if I return this over a RESTful interface I can just open it as a TIFF client-side?
Comment: Ya. You will want to call [`tostring()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tostring.html) or `tobytes()` first.
Comment: @DanMašek Thanks - that does it - please could you post an answer that I can accept? I do feel this falls in the cracks of the OpenCV/numpy/SO literature to date. (Also: Why..?!)
Comment: @DanMašek I've posted an answer but you deserve the credit so I will leave it open for a bit to see if you want to post an answer. Thanks for all help! :)
Comment: That's cool, feel free to accept your self-answer. Glad I could help you solve the problem :)
Comment: @DanMašek Thanks so much - I do feel bad but extremely grateful for you helping me get there! Seems so simple now... :)
Answer: Following https://stackoverflow.com/a/50630390/1021819 and building (but not very much) on the comment by Dan Masek, the required extra step is simply to use im_buffer.tobytes(), which returns a bytestring that can be sent through a stream.
Python OpenCV images do seem to be represented as pure numpy arrays. As pointed out by Dan Masek, the arrays can be transformed using cv2.imencode() into TIFF, PNG, BMP, JPG etc.
There is obviously some debate around choice of formats and compression. In the case above there was a preference for lossless compression, implying TIFF, BMP or PNG (still there will be debate). The python bindings to OpenCV have no tunable parameters for TIFF compression (unlike(?) the C++ bindings?), so it's not very easy to discover what is being done there. The compression level could apparently be better using other libraries but my aim was to minimize dependencies (see above).
A BMP-encoded image was no smaller than a TIFF one. PNG compression is tunable in python OpenCV, and setting
cv2.imencode('.png', nparr, [int(cv2.IMWRITE_PNG_COMPRESSION),1])

has given the best size-speed trade-off so far. Thanks.


Django nonrel error "No Module name models"

Question: Guys,
I Started playing with django-nonrel, and am trying to run my old django app on it.
My app was done on django 1.2.1 & python 2.6.
When i fire up the local server, there are a couple of warnings but the server starts well.
But when i try to run the main page from the browser, django throws the following error
ImportError at /bytex
No module named bytexpro.bytex.models
Request Method: GET
Request URL:    http://127.0.0.1:8000/bytex
Django Version: 1.3 beta 1
Exception Type: ImportError
Exception Value:
No module named  bytexpro.bytex.models
Exception Location: E:\home\web\bytex\bytexpro\bytex\admin.py in <module>, line 1
Python Executable:  C:\python26\python.exe
...

My admin.py looks like this
from bytexpro.bytex.models import ItemGroup
from bytexpro.bytex.models import Item
from bytexpro.bytex.models import Supplier
....

Anything i i have forgotten to include?
Gath
Comment: have you tried `from bytex.models import ItemGroup` etc.
Answer: try
from bytex.models import ....


Lipschitz constant of $f' f$

Question: I have a question about the following statement. I saw this in this paper but the proof in this paper seems somewhat unreasonable to me. So I tried to give more rigorous proof, but I have no idea to prove this statement.
The paper is:
A.A. Zevin, Minimal periods of solutions of Lipschitizian differential equations in a vector space with an arbitrary norm
In this paper, there is a lemma which says:
Suppose $f: \mathbb{R}^n \rightarrow \mathbb{R}^m$ is Lipschitz continuous with constant $L$. Let $F(x) = Df(x) f(x)$. (The author assumes that $f$ is differentiable, without loss of generality. He mentioned that Lipschitz continuous is differentiable almost everywhere, but I can't understand why this assumption is still valid.) Then $F$ is Lipschitz continuous with constant $L^2$.
edited: $f$ is a differentiable function.
I tried to use the fact that the norm of $Df(x)$ is bounded by $L$. (I think that the proof of Rademacher's theorem verifies this.)
Can anyone give me a hint about the proof or help me understand the proof of this lemma given in the paper?
This is my first question in this community, so any suggestions about the format of my question are also welcome.
Thank you.
Comment: Remark: $Df(x)$ is a linear map $\mathbb R^n\to\mathbb R^m$, $f(x)$ is an element of $\mathbb R^m$, so $Df(x)\cdot f(x)$ a priori makes no sense. They probably mean $Df(x)^T f(x)$. The proof in the paper certainly is very suspect!
Comment: If $n=m=1$ and $f (x) = |x|+1$, then $F = f' f $ is not even continuous.
Comment: @JohnMa I think the differentiability of $f$ should be assumed. The author assumes it before he states the lemma, although I can't understand about it. Thank you for your comment.
Answer: The Theorem is false.
Start with $g(x)=1+x^{4/3}$ and let $G:\Bbb R\to \Bbb R$ be a smooth function so that $G$ is constant $1$ on $[-1,1]$ and $0$ outside of $[-2,2]$. Our function $f$ will be
$$f=g\cdot G$$
$f$ is Lipschitz continuous. This follows from it being a continuously differentiable function $\Bbb R\to\Bbb R$ with bounded derivative (boundedness of the derivative follows from compactness of the support). But the construction $F=f' f$ gives for $x\in(-1,1)$:
$$F(x)=\frac43 x^{1/3}(1+x^{4/3})$$
for which there exists no Lipschitz constant in any neighbourhood of $0$. Suppose you have a Lipschitz constant $L$, then for $x>0$, $x<1$ you get:
$$Lx≥F(x)-F(0)=\frac43 x^{1/3}(1+x^{4/3})≥\frac43x^{1/3}$$
and it follows
$$L≥\frac43 x^{-2/3}$$
for all such $x$, which is impossible since the expression on the right is unbounded.
Comment: Thanks for your answer. Should I throw the paper away..? .............
Comment: Some comments: I read parts of the paper, the author is interested in maps $f$ $\Bbb R^n\to \Bbb R^n$, so the previous comment about needing to take a transpose is not relevant. The author is also only interested in such functions that result in periodic solutions to the equation $\dot x= f(x)$ so one dimensional examples are certainly out. I think the example I gave can be modified in a suitable way to also find a counterexample to the lemma with these conditions.
Comment: As to what to do with the paper, that depends on why you were interested in it. If you need the results you should ask your advisor whether you should try to prove it yourself/find counter-examples to the main result of the paper @user381027.
Comment: Well, I want to introduce some results to people in my academic club (I'm an undergraduate student) about the problem regarding the minimal period of Lipschitzian DEs. I think I should look for other papers first. Thanks for your help.

Lipschitz constant of $f' f$


Angular: Re-render asynchronous data in image tag

Question: I am using Angular to fetch user profile picture from backend(Node.js/Express). Everything is working perfectly except for one thing. The Angular does not re-render the HTML that displays the profile picture incase, the user has updated his picture or if no picture is present and user uploads his first image. As expected, the Angular is rendering the HTML only once and isn't re-rendering again. I don't know how can I wait for asynchronous data in HTML as I am directly targeting an endpoint in HTML instead of TS.
Here's my code:

userProfile.component.html

     //angular is sending request to the above endpoint to fetch the image only once at the time
       application starts or user logs in. How can I send a request again?

<button type="button" name="button" (click) = "selectImage()" class = "btn
       btn-outline-primary">   </button>

      <input type="file" id="imgUpload" (change) = "handleImageInput($event.target.files)">

userProfile.component.ts

selectImage()
{
  document.getElementById('imgUpload').click();
}

handleImageInput(files: FileList)
{
  this.imageUpload = files.item(0);
  this.uploadImage();
}

uploadImage()
{
  const formData = new FormData();
  const params = new HttpParams().set('id', sessionStorage.getItem('cookie'));

  formData.append("file", this.imageUpload, this.imageUpload.name);

  this.http.post('http://localhost:3000/api/updateImage', formData, {params, responseType: "text"})
  .subscribe(responseData => {

   this.imageChanged = true;  //I have tried using this as *ngIf in HTML but it is not working either
 }
  ,error => {
   console.log("Image uploading failed" + error.message);
 })
}

Does anybody know how can I send the request to an endpoint in HTML once user changes/uploads his first picture?
Answer: You need to trigger the image fetch request for each update/upload requests. Or you could adjust the backend to return the image data from the update/upload requests.
Option 1: manually fetch image for each update/upload requests
Use RxJS switchMap operator to switch to image fetch request after the uploading has completed. It'll not be fetched if the uploading failed.
profileImage: any;

selectImage() {
  document.getElementById('imgUpload').click();
}

handleImageInput(files: FileList) {
  this.imageUpload = files.item(0);
  this.uploadImage();
}

uploadImage() {
  const formData = new FormData();
  const params = new HttpParams().set('id', sessionStorage.getItem('cookie'));
  formData.append("file", this.imageUpload, this.imageUpload.name);

  this.http.post('http://localhost:3000/api/updateImage', formData, {
    params,
    responseType: "text"
  }).pipe(
    tap(null, error => console.log("Image uploading failed" + error.message)),
    switchMap(_ => this.http.get(`http://localhost:3000/api/getProfilePhoto?id${this.cookieData}`))
  ).subscribe(
    image => {
      this.profileImage = image;
    },
    error => {
      console.log("Image fetching failed" + error.message);
    }
  );
}

Option 2: Return the image from upload/update request
Adjust the backend to return the image data from the Upload POST request.
profileImage: any;

uploadImage() {
  const formData = new FormData();
  const params = new HttpParams().set('id', sessionStorage.getItem('cookie'));
  formData.append("file", this.imageUpload, this.imageUpload.name);

  this.http.post('http://localhost:3000/api/updateImage', formData, {
    params,
    responseType: "text"
  }).subscribe(
    image => {
      this.profileImage = image;
    },
    error => {
      console.log("Image uploading failed" + error.message);
    }
  );
}

As a sidenote, using document.getElementById() in Angular will search the whole DOM, not just the individual component. In relatively complex apps, it might lead to performance issues. Instead try to use an event handler or if it's not possible, use Angular ViewChild with a template reference parameter to get an element from the current component's DOM.
Comment: I assumed the image would be fetched elsewhere at the app start (like `ngOnInit`) once as the question was only targeting image change behavior. In any case, you need to fetch the image the beginning of the app once (like in `ngOnInit`) to display it.
Comment: Option 2 has a drawback, it's going to display the image ONLY AFTER user uploads an image. It's not going to display if the user has already uploaded an image before and is logging in again since, there's no http client targeting the get image endpoint.
Answer: if the webservice resolving the image url returns an Observable, you  can make the call from typescript like below
imageData$: Observable<number>;
    getImage(id): Observable<string> {
        this.imageData$=http.get(url?id=<some_id>);
        return this.imageData$
    }

and the adding async pipe on it

Basically The async pipe subscribes to an Observable or Promise and
returns the latest value it has emitted. When a new value is emitted,
the async pipe marks the component to be checked for changes. When the
component gets destroyed, the async pipe unsubscribes automatically to
avoid potential memory leaks.
Comment: This will trigger the request for each change detection cycle in default CD strategy. As a general rule, it is not a good idea to bind to functions to attributes and directives.


jQuery Hover question

Question: here:
http://www.jsfiddle.net/JEXru/1/
i don't know how to make it so if you hover over the slide it stays active ... help?
Comment: I'd first fix your markup so your  only contains  elements as immediate children.
Answer: Change your javascript to this:
<code>$(function() {
$('.slide').hide();
$('.title:first').css({
    'margin-left': '1px #333 solid'
});
$('ul#horzAccordion ul').hover(
    function() {
         var slideLink = $(this).children('a').attr('name');
         $(slideLink).animate({
             'width': '320px'
         }).show();
    }, function() {
         var slideLink = $(this).children('a').attr('name');
         $(slideLink).animate({
             'width': '0px'
    }, 300).hide();
});
});
</code>
What you were doing is setting the hover event on just the link which only encompasses the first LI (the link surrounding the list item is invalid html by the way you will want to move that to inside the LI).  So when your mouse moved away from the link it closed.  The updated javascript sets the hover on the interior UL so that you can interact with the shown contents.
Let me know if you have any questions on the above.
edit: code formatting.
Answer: For what you want, you don't need any Javascript. Add these to your CSS:
<code>#horzAccordion ul li.slide { display: none; }
#horzAccordion ul:hover li.slide { display: block; }
</code>
Then remove your hover jQuery function and $('.slide').hide();.
Comment: He might want that smooth animation of it opening since he is setting the easing in his jquery call
Comment: Yea... in that case then JS is the only way... Using just CSS is faster though.
Comment: One thing to watch for when using :hover on non  elements is it can cause performance issues in IE.  But generally I like pure css solutions when they fit the design. http://stackoverflow.com/questions/4204527/css-does-every-class-support-hover-state
Comment: I actually had this, but as antonlavey said, I do want the smooth animation.

jQuery Hover question


Android Studio - add .jar library

Question: This seems an old answered question, but I'm still having some issues.
I created a Web Server that shares some classes as .jar. This is an example of a shared POJO class
@JsonInclude(Include.NON_NULL)
@Entity
@Table(name = "user", uniqueConstraints =
{ @UniqueConstraint(columnNames = "email"),
    @UniqueConstraint(columnNames = "nick") })
public class User implements java.io.Serializable, RecognizedServerEntities
{
  @Id
  @GeneratedValue(strategy = IDENTITY)
  @Column(name = "id", unique = true, nullable = false)
  private Integer userId;

  @OneToMany(fetch = FetchType.LAZY, mappedBy = "threadAuthor",
      orphanRemoval = false)
  @Cascade({ CascadeType.SAVE_UPDATE })
  private Set<Thread> userThreads = new HashSet<Thread>(0);
}

Now, I'm trying to create an android app that simply use these shared classes: the app doesn't need to know anything about hibernate or javax.persistence (at least, is what I think).
However, when I create a new project in Android Studio, it seems to require some additional libraries. Indeed, the gradle build process generates a lot of warnings like
warning: unknown enum constant CascadeType.REMOVE
  reason: class file for org.hibernate.annotations.CascadeType not found
warning: unknown enum constant FetchType.EAGER
  reason: class file for javax.persistence.FetchType not found

and at runtime the app crashes with this log message
java.lang.NoClassDefFoundError: org/hibernate/annotations/Cascade

So, do I have to import these .jars as library and add a compile files() to build.gradle?
I've yet developed another client-side application using Java (Swing) and there is no need to import those libraries: the shared.jar was enough. Why do Android require them?
Comment: You may try to add, and see what happened.
Comment: @bjiang  know, but there are a lot of libraries to add and it seems
an unnecessary waste of space. However, I just tried to add javax.persistence and hibernate-core to the list of jars: while the build process runs without warnings, runtime errors occurs anyway. Is it strictly necessary to add these jars?
Answer: CascadeType and FetchType are part of Java EE.
Try use findjar to download jar(s) which contains these classes.
Even if you will add downloaded jars to classpath, RuntimeExceptions still migt happen because these libs can use part of Java that isn't part of Android Java.
Just try and give us a feedback :)
Comment: Thanks for your time.
Can you take a look at the comment below the original question? Is it strictly necessary to add these jars?
Comment: @tigerjack89 java.lang.NoClassDefFoundError: org/hibernate/annotations/Cascade - I'd try add jars :)
Comment: Yet tried: I haven't compile warnings anymore, but the app still crashes with runtime errors.
Comment: @tigerjack89 runtime still says that not found CascadeType?
Comment: WTF restarted Android Studio and now it works without errors :S
Comment: Well, your tips and the ones from @CommonsWare helped me in many ways and both deserve an up vote, but it's difficult to say that they are the final answer.
Answer:
Now, I'm trying to create an android app that simply use these shared classes: the app doesn't need to know anything about hibernate or javax.persistence (at least, is what I think).

Apparently, it does. Some of those annotations may be runtime annotations, in which case, you would need the JARs. Some of those that are compile-time annotations may expand into references to things in those JARs, and that is my interpretation of your error messages.

So, do I have to import these .jars as library and add a compile files() to build.gradle?

You are certainly welcome to try using Hibernate on Android, whether through JARs or artifacts up at someplace like Maven Central. Whether there is a port of Hibernate that works on Android, I cannot say. Last I checked, Hibernate was designed for server-side use with direct access to a database, whereas Android apps are designed for client-side use without direct access to a database (e.g., using a Web service).
Comment: Well, is what I've done so far. I've implemented the server-side project using POJO classes and now I'd like to use an Android app only to access this server. However, I've shared some of those POJOs so, for example, I can easily create a new User from the Client and send it to the Server, which in turns save it to the database.
Also, I've yet developed another client-side application using Java (Swing) and there is no need to import those libraries: the shared.jar was enough.
However, I tried to include the jars in the Android project, but the runtime errors are still there.
Comment: @tigerjack89: Well, in terms of `javax.persistence`, that simply isn't on Android and is unlikely to be something that you can add, as Android's build tools usually reject classes in an app (or library) that are in the `java` or `javax` namespaces. However, those are not runtime errors; they are warnings. The Dalvik (and presumably ART) runtimes will post warnings about missing stuff. If you really need the stuff, you will crash with a `VerifyError` at the point of executing the code.
Comment: The warnings aren't the real problem. Problem is that at runtime, even after adding those libraries, the app crashes and the logcat says `java.lang.NoClassDefFoundError: org/hibernate/annotations/Cascade` (however, no build errors)
Comment: @tigerjack89: And so you need a JAR that contains that class in your APK at runtime. The fact that on a largely unrelated runtime (whatever Java SE version you used for your Swing client) happens to not need this class is not especially relevant. "Why do Android require them?" -- because you are using them. Depending on the specific trigger behind the error, you may have a stack trace that shows what specific part of your code is going through a path that happens to require this class. In this case, it would appear to be a runtime annotation.
Comment: I tried to add many jars; indeed, compile time warnings are gone, but it still has runtime errors: aren't the two things related? I mean, the fact that I don't have compile warnings anymore doesn't imply that I shouldn't have runtime errors?
Comment: @tigerjack89: "I tried to add many jars" -- if you are still getting the runtime errors, there would appear to be some issue in how you added the JARs. That's unusual with Android Studio; I am more used to that sort of problem in Eclipse. What JARs did you add, and how did you add them? Also, if there is a full stack trace associated with your `NoClassDefFoundError`, could you post it?
Comment: Just restarted Android Studio and now it works great. So, is this the final solution?
Comment: @tigerjack89: Well, I certainly can't explain why restarting the IDE would have an impact on your app running in your device/emulator. I mean, stranger things have happened, but I can't say "oh, yes, by restarting the IDE you caused X to happen, which impacted Y, etc.".

Android Studio - add .jar library


Trying to add an option to a select list

Question: The code below removes all options in my edit form. But after the options are removed I want to add a default option. I've tried the code below, but also .add and .prepend I just can't find the right code for this. What am I doing wrong?
$("#editform").find("select").each(function(){
                alert(this.id);
                this.options.length = 0;
                this.append($('<option/>', { value: '', text : 'Selecteer' }));
            });

Comment: Replace `this` by `$(this)`.
Answer: If you checked the console.log, you'd likely see an error that says something like Uncaught TypeError: this.append is not a function. Append is a jQuery function, and therefore you need to use the jQuery constructor function. Change this to $(this). ie:
$("#editform").find("select").each(function(){
   alert(this.id);
   this.options.length = 0;
   $(this).append($('<option/>', { value: '', text : 'Selecteer' }));
});

Comment: Is the this.options.length = 0; also incorrect then?
Comment: No. In that case, `this` refers to the object found (in this case, a select element). You're fine using just `this` within the scope of each. If you were to use `$(this)` it would be using jQuery to try and execute an `.options()` method, which does not exist.
Answer: append is jquery function:
$("#editform").find("select").each(function(){
            alert(this.id);
            this.options.length = 0;
            $(this).append($('<option/>', { value: '', text : 'Selecteer' }));
        });

Comment: A code-only answer will never be as good as an answer with, if not some accompanying text to explain, comments. — [During review](http://stackoverflow.com/review/low-quality-posts/10297448).
Comment: append is jquery function, when using [this] means using javascript and not jquery, and in this case [this] has no function called append


An Exercise from Theory of Plane Curves

Question: It was an exercise given in the class:

For every integer $n\geq 0$, there is a function (curve) $f\colon \mathbb{R}\rightarrow \mathbb{R}^2$ such that $f$ is $n$-times differentiable with $n$-th derivative continuous, and $f(\mathbb{R})$ is the V-shaped graph in $\mathbb{R}^2$:
  $$f(\mathbb{R})=\{ x,|x|\}.$$

I initially was saying, this is wrong, but Teacher's said, Think over it; its elementary but interesting problem.
I tried this, but couldn't solve. It may be very elementary, but I was comparing with function $x\mapsto |x|$, and hence may getting confused.
Any Hint for it?
Comment: so stupid! I was thinking, "by taking $f(x)=(x^n, |x|^n)$, it will not be a straight line; but thats not the case. Now its clear.
Comment: Sorry! This will work only when $n$ is odd. What about $n$ even?
Answer: The map $f(x) = (x^3, |x|^3)$ will work for $n=2$.
Comment: sorry! This will work when $n$ is odd. If $n$ is even, then $f(t)=(t^n, |t|^n)$ will not work, since the image is only in first quadrant. How to proceed for $n$ even?

An Exercise from Theory of Plane Curves


How to get the X value from a known Y value for a line chart in C#?

Question: I'm creating a graph in C# which plots an X value (distance) against Y (time).
The graph has two lines: A line to compare to (we can call IdealDistance) and a line generated from an external input (RealDistance).
I was wanting to compare the RealDistance X value to the IdealDistance X value at the time it is added but can't work out how to return the IdealDistance X value at known times (or IdealDistance Y values).
The IdealDistance line is formed by a number of datapoints spaced out every second, the desired check is done every 100ms so can't simply use the IdealDistance set of datapoints unfortunately.

How can I get the X axis value of one of my series at a given Y axis value?
Answer: If you take two data points (a and b) you can use the equation of a line to get Y for any X point (or X for any Y point) between them:
<code>public static int GetX(int y, Point a, Point b)
{
    var m = CalculateSlope(a, b);

    // Horizontal line (x-values are always the same)
    if (m == 0.0)
        return a.X;

    var c = a.Y - a.X * m;

    return Convert.ToInt32((y - c) / m);
}

public static int GetY(int x, Point a, Point b)
{
    var m = CalculateSlope(a, b);

    // Vertical line (y-values are always the same)
    if (double.IsPositiveInfinity(m))
        return a.Y;

    var c = a.Y - a.X * m;

    return Convert.ToInt32(m * x + c);
 }

public static double CalculateSlope(Point a, Point b)
{
    if (b.Y == a.Y)
        return double.PositiveInfinity;

    if (b.X == a.X)
        return 0.0;

    return (Convert.ToDouble(b.Y) - Convert.ToDouble(a.Y)) / (Convert.ToDouble(b.X) - Convert.ToDouble(a.X));
}
</code>
Comment: this is a good way to do it for lines. However was there a way to account for if there was a spline type with soft corners?
Comment: I think you're talking about calculating equation of irregular curve? The maths would get a bit complex if so.
Comment: Yes that would be required to do it this way. It is alright I will stick with the line graph for now. Would be easier to implement the pixel method to determine position for the curved graph. I will mark your answer as correct if you change it to correctly implement for GetX rather than GetY, or I can update with how I implemented the code which is based off yours but mildly different.
Comment: @Luke I added the GetX method.


On the Wii Virtual Console version of The Legend of Zelda, how can you save a game in progress?

Question: In the original Legend of Zelda for the NES, there was a trick where you could (if I remember correctly) press ↑ and select simultaneously on the 2nd controller to bring up the Save dialog.
After buying the Wii Virtual Console version, I tried this trick and it didn't work.
Is there a way to save your game in-progress on the Wii version? (maybe I'm missing something obvious, like generic save state functionality)
Comment: If you pushed reset & the power button at the same time, that would  prevent losing your progress.
Comment: "In the original *Legend of Zelda* for the NES, there was a trick where you could" hold the A button and press up.  (Not the Select button.)
Answer: Figured it out. It was actually in the manual. (who would have thought to look there?) ;-)
You hit + (start) to bring up your inventory, then ↑ and - (select) at the same time. All on the first controller. Done!
Comment: @SevenSidedDie — At the time, many considered it a point of pride to complete the game with their death counter still at 0.  Thus, a *significant* difference between "save while alive" and "save after dying".  ;-)
Comment: You also have the opportunity to save when you die. Since you always start in the same place when you load a game, there's no difference between the two ways of saving except convenience.
Comment: @Ben A fair point. :)
Answer: Commonly with virtual console games, you can hit the center button (Wii menu?), and exit the game.  This will automatically save the state of the game.  Next time the game loads you'll begin at that spot; however, after reloading once the save state is no longer available -- resetting the system won't allow you to resume from that state again.
Comment: +1. This is true of all of the virtual console games, as far as I know. This is possible because they're all emulated, and so it's easy to just write the state of the simulator to disk.
Comment: +1, great to know. This will be useful if I'm in the depths of a dungeon and don't want to completely reset. I'll probably use a combination of my approach and yours.
Comment: There is a problem with using this method in Legend of Zelda. Sure you save the game in the spot-but you miss the warp back to the start of a dungeon or the starting screen on the overworld. CyberSkull's method is better for the original style save.


Traffic light program. Java. Loops

Question: My code is getting complicated and it doesn't seem to be getting resolved, please, have a look and give me advice.
Please, make sure you do not share a solution as I'd rather fix it by me, instead of leaving it unclear.
Here we go:
TASK:
The pedestrian traffic light is programmed as follows:
at the beginning of each hour, the green signal is on for three minutes,
then the signal is yellow for one minute,
and then it is red for one minute.
Then the light is green again for three minutes, etc.
Use the keyboard to enter a real number t that represents the number of minutes that have elapsed since the beginning of the hour.
Determine what color the traffic light is at the specified time.
Display the result as follows:
"green" if the light is green,
"yellow" if the light is yellow, and
"red" if the light is red.
EXAMPLE:
For 2.5 - Green.
For 3 - Yellow.
For 5 - Green.
and so on, within 60 minutes loop.
MY CODE:
<code>     public static void main(String[] args) throws NumberFormatException, IOException {

     BufferedReader sum = new BufferedReader(new InputStreamReader(System.in));
     double a;

    a = Double.parseDouble(sum.readLine());

    while(true) {
     calcYellow(a, a); break;}
    while(true) {
     calcRed(a, a); break;}
    while(true) {
     calcGreen(a, a, a, a); break;}

    }

    static void calcYellow(double a, double b) {
      double a1 = 3.0;
      double b1 = 3.5;
    for (a=a1+4; a<60; a++);
    for (b=b1+4; b<60; b++);
      if ((a%3.0==0) || (a%3.5==0));
      if ((b%3.0==0) || (b%3.5==0));

    System.out.println("Yellow");
      }

    static void calcRed(double a, double b) {
      double a1 = 4.0;
      double b1 = 4.5;
    for (a=a1+4; a<60; a++);
    for (b=b1+4; b<60; b++);
    if ((a%4.0==0) && (a%4.5==0));
    if ((b%4.0==0) && (b%4.5==0));

    System.out.println("Red");
    }

    static void calcGreen(double a, double b, double c, double d) {
    double a1 = 1.0;
    double b1 = 1.5;
    double c1 = 2.0;
    double d1 = 2.5;
    for (a=a1+4; a<60; a++);
    for (b=b1+4; b<60; b++);
    for (c=c1+4; c<60; c++);
    for (d=d1+4; d<60; d++);

    System.out.println("Green");
}
    }
</code>
Any advice will be highly appreciated.
TY in Advance!
Comment: An obvious logic flaw is having 3 while loops each calling `calcSomeColor`. There should be a method that converts the input (time) into one of the three possible outputs. Not three methods converting the input always to the output (which can't happen for all inputs).
Comment: Is it a special requirement to calculate the color using loops?  You can do the same by calculating a remainder after division by 5 and checking the range of the result.
Comment: The biggest immediate problem: use meaningful variable names. Using single char variable names like you do renders your code totally unreadable.
Comment: What is the point of `while(true) { calcYellow(a, a); break; }`? It's a forever loop that always exits after the first iteration, i.e. it's not looping at all. It's exactly the same as not having the loop: `calcYellow(a, a);`
Comment: What is the point of `for (a=a1+4; a<60; a++);`? It's a loop that iterates some times, but doesn't do anything in the loop, and it will run so fast it's not even a delay. --- What is the point of `if ((a%3.0==0) || (a%3.5==0));`? It's an `if` statement, the it doesn't control anything. --- In both cases, you probably meant to do those with the `;` at the end.
Comment: You're right Andreas, I should have left the comments. sorry, I'll update it very soon. Kayaman, thank you for your advice - I'll try to take it into consideration.
Comment: Thank you @GhostCat, your advice made full sense. As far as the solution has already been posted, the question is closed and next time I won't ask the question posting the code like that one.                                                                                Actually, thank's to all of you guys, really appreciated!
Answer: Solution could be as easy as this:
<code> public static void main(String[] args) throws IOException {
        BufferedReader sum = new BufferedReader(new InputStreamReader(System.in));
        double enteredTime;
        enteredTime = Double.parseDouble(sum.readLine());

        double colorTime = enteredTime % 5;

        if (colorTime >= 0 && colorTime < 3) {
            System.out.println("Green");
        } else if (colorTime >= 3 && colorTime < 4) {
            System.out.println("Yellow");
        } else if (colorTime >= 4 && colorTime < 5) {
            System.out.println("Red");
        }

    }
</code>
You could expand this with the 60 minutes loop.
Answer: You could create an array of colors imitating their sequence and calculate the index in the array using remainder operation.
Also, an edge case may need to be handled when the timestamp is negative, that is, you need to define the traffic light color in the past: from 1 minute "ago" it was red, from 2 till 1 minutes it was yellow and so on.
<code>private static final String[] COLORS_BY_MINUTE = {"Green", "Green", "Green", "Yellow", "Red"};

public static String getColor(double minute) {
    double colorIndex = minute % COLORS_BY_MINUTE.length;
    // handle "backward"/negative timestamp
    if (colorIndex < 0) {
        colorIndex += COLORS_BY_MINUTE.length;
    }
    return COLORS_BY_MINUTE[(int) colorIndex];
}

// tests
double[] tests = { -3.5, -2.5, -1.5, -1, 0, 1.5, 2.5, 3, 3.8, 4.5, 5.5, 62.5 };
Arrays.stream(tests)
      .forEach(t -> System.out.printf("%4.1f -> %s%n", t, getColor(t)));
</code>
Output:
<code>-3.5 -> Green
-2.5 -> Green
-1.5 -> Yellow
-1.0 -> Red
 0.0 -> Green
 1.5 -> Green
 2.5 -> Green
 3.0 -> Yellow
 3.8 -> Yellow
 4.5 -> Red
 5.5 -> Green
62.5 -> Green
</code>
Comment: That's an amazing one, @Alex Rudenko. I'll try this solution as well, thank you!

Traffic light program. Java. Loops


Unity animation setting bool true but doesnt set false after setting true?

Question: Everything matches at unity like controller name , parameter name vs. but my animation after i set it true, doesnt set false.Here is code:
<code>    public Animator anim;

void Start()
{
    anim = gameObject.GetComponent<Animator>();

}

void Update()
{

    if (this.GetComponent<cube2>().enabled)
    {

        if (Input.GetMouseButtonDown(0))
        {
            anim.SetBool("tikk", false);

        }
        else
        {
            anim.SetBool("tikk", true);
        }
    }

}
</code>
Comment: Maybe you want to use `Input.GetMouseButton(0)` instead of `Input.GetMouseButtonDown(0)` (the first is true while the mouse button is down, the second one only for the first frame)
Answer: Try adding a check if not input.getmousebuttondown and switching the booleans.


How to round a decimal to the nearest 1/n

Question: I want to round a number to the nearest 1/4. For example, if I have 3.21, I'd round it to 3.25, or if I have 3.46, I'd round to 3.50. I'd like to write a method for this, but I am not sure how.
Answer: Try this: (number / 0.25).round * 0.25