getUserMedia() not supported in chrome

Question: I am trying to access my webcam using the getUserMedia() using my own website that run using my own ip address.
it was working fine until i tried my website again. i had tried the other demo site and the error given was getUserMedia is not supported.
Chrome version v47.0.2526.80m 32bits

I am able to access the webcam if i enter localhost instead of my ipadress. it also work in firefox.
Comment: problem solve i am able to create a local SSL file to test my site using this http://www.mytechblog.in/wp-content/uploads/2015/09/Commands-Procedure.txt
Comment: it work previously without using SSL..
Comment: Yes, it did. On Monday I had to change my site to be all SSL for it work.
Comment: how do i add SSL? i google and most certificate require purchase..
Comment: Startssl has free certs.. on my phone but you can find tutorials on Google for startssl
Comment: i read/watch a few tuts on setting up SSL using starssl but it need a valid domain? this is a sch project and i am testing the website in a intranet environment.
Comment: Does it have to be chrome? Or can you just use Firefox?
Comment: certain features i code only work in chrome..
Comment: Can you downgrade to an earlier version of chrome? Pre 47
Comment: You can provide your IP address as an exception in Chrome. Follow these steps here: https://stackoverflow.com/a/58090783/293280
Answer: Chrome is requiring secure origins (HTTPS) for getUserMedia.

Starting with Chrome 47, getUserMedia() requests are only allowed from secure origins: HTTPS or localhost.

https://developers.google.com/web/updates/2015/10/chrome-47-webrtc?hl=en
Comment: Is this strictly on mobile?
Answer: I am not sure if this exactly solves your problem. However, it might be helpful to someone who is struggling to have getUserMedia() in a working state.
I came across a medium link that helped me solve this issue.
Go to : chrome://flags/#unsafely-treat-insecure-origin-as-secure
Enable the option.
Also, there will be a checkbox provided below. Use that to provide the link to your HTTP server.
Referr to this image for better clarity
Provide the port number too. (In my case it is 8000)
Source: https://medium.com/@Carmichaelize/enabling-the-microphone-camera-in-chrome-for-local-unsecure-origins-9c90c3149339
Comment: Perfect answer, worked for me. one thing is we should add the http host origin in the same otherwise it wont work.
Answer: Chrome finally implemented the new navigator.mediaDevices.getUserMedia() method, but they added a security that will prevent the calls from unsecure address (non https or non localhost servers)
You will call it like this :
var video = document.querySelector('video');
navigator.mediaDevices.getUserMedia({video:true}).then(function(mediaStream){
    window.stream = mediaStream;
    video.src = URL.createObjectURL(mediaStream);
    video.play();
});

Or you can use the official webRTC polyfill adpater.js library.
var constraints = { video: true, audio: true };

navigator.mediaDevices.getUserMedia(constraints)
  .then(stream => video.srcObject = stream)
  .catch(e => console.error(e));

getUserMedia() not supported in chrome


A strange (!) behaviour of differentiability

Question: I see by drawing diagram that $y=\max (0,\sin x)$ is not differentiable at some points. But $y=(\max (0,\sin x)) ^ 2$ is . How to explain/prove it ? Am I missing something easy ?
If $f$ is not differentiable at $x$ and $g$ is differentiable then $g\circ f$ differentiable at $x$ ?
Comment: For a simpler example of the same phenomenon, notice that $y=|x|$ is not differentiable at $0$, but $y=|x|^2$ is...
Comment: @Micah: yes, but how to prove it. What is the general theorem we have to use ?
Comment: There is no general theorem. Non-differentiability of a function $f$ has nothing to do with the differentiability properties of $f^2$. However, if $f$ is differentiable then so is $f^2$ - this might be what is confusing you.
Comment: It's similar to the fact that $y = |x|$ is not differentiable at $x=0$ but $y = |x|^2$ (which is the same as $y = x^2)$ is differentiable at $x=0.$ Or perhaps better, it's like what happens when you square the function $f(x)$ defined to be $x$ when $x \geq 0$ and defined to be $0$ when $x < 0.$ Note that near $x=0$ the graph of $y = \max\{0, \, \sin {x} \}$ looks like the graph of the function I just defined (think about linearizations to the right and left of $x = 0).$
Comment: One "general theorem" is that if the values of the function approach $0$ at least as fast as $|x-a|^a$ (where $a$ is some real number greater than $1),$ then the function will have a zero derivative at $x=a.$
Answer: The derivative is a limit.  Check the two one-sided limits for the two functions.
For example, with the first function,
$$\lim_{x\to 0-}\frac{f(x)-f(0)}{x-0}=\lim_{x\to 0-}\frac{0}{x}=0\\
\lim_{x\to 0+}\frac{f(x)-f(0)}{x-0}-\lim_{x\to0+}\frac{\sin x}{x}=1$$
The two limits are different, so the limit doesn't exist; so the derivative does not exist.
Answer: When a function is defined piecewise, as
$$
f(x)=\begin{cases}g(x) & & {\text{if }} x\ge0 \\
h(x) & & {\text{if }}x<0,
\end{cases}
$$
where $g$ and $h$ are differentiable, its derivative exists at the join point if and only if its pieces have the same derivative there (i.e., $g'(0)=h'(0)$).  That is, the join must be smooth.  In your example, the derivative of $\sin x$ where it crosses $0$ is $\cos x=\pm\sqrt{1-\sin^2 x}=\pm 1$, so the joins are not smooth.  The derivative of $\sin^2 x$ at the same locations is $2\sin x \cos x=0$, so the joins are smooth.
Comment: is this true that  for any $f$ non-differentiable at $x$, $g$ differentiable and $g \circ f$ being differentiable ? if not which conditions are sufficient ?
Comment: @user148951 There is a chain rule for left- and right- derivatives. That is, if $L$ is the left derivative operator and $R$ is the right derivative operator then $L(g \circ f)(x) = L(g)(f(x)) L(f)(x)$ and $R(g \circ f)(x) = R(g)(f(x)) R(f(x))$. Thus if $f$ is left- and right-differentiable at $x$ and $g'(f(x))=0$ then $g \circ f$ is differentiable at $x$ with derivative 0.
Comment: @mjqxxxx The derivative of $\sin(x)$ is $1$ at $0$. This is the right derivative of the piecewise function. The left derivative is $0$, from the constant piece. There's no $-1$ anywhere.
Comment: @Ian: The function he named was $\max(0, \sin x)$.  This has multiple join points (at each position where $\sin x=0$).  The derivative of $\sin x$ is $+1$ at some of those points and $-1$ at the rest.
Comment: Ah, my mistake, I assumed it was looking at a small neighborhood of zero for some reason.
Answer: One little picture says more than a long speech!
On the blue curve there is an angular point at $y=0$. Of course, the corresponding function is not derivable at this point.
At the same point, the red curve is tangent to the x-axe. So, the corresponding function is derivable because the derivatives have the same limit $=0$ on the left and right sides.
It is the same if the angular point is anywhere on the x-axe. On can understand that it is a general property for any angular point located on the x-axe.


The sum of $n$ terms in $1 \cdot 2+2 \cdot 3+3 \cdot 4+\ldots$

Question: I am just confused, considering we can take $1 \cdot 2$ as the first term then we get the $n$th term as $n(n+1)$ so the sum of $n$ terms would be $\frac{n(n+1)(2n+1)}{6}$ + $\frac{n(n+1)}{2}$ but let's assume $0 \cdot 1$ as the first term then the $n$th term becomes $(n-1) \cdot n$ and so it's summation becomes $\frac{n(n+1) (2n+1)}{6} - \frac{n(n+1)}{2}$ but it's the same summation as above but the results are different what am I doing wrong?
Comment: You may also be interested in the so called *hockey stick identity*. Apart from a factor of two, the summands are binomial coefficients $\binom{n+1}2$. Staring at the Pascal triangle (moving $\binom22$ to $\binom 33$) gives you a binomial coefficient on the third diagonal as the sum :-)
Comment: You sum up until $(n-1)\cdot n$  in the second case, not until $n(n+1)$
Comment: In the second case, you have to sum up to $n(n+1)$ and in the second case you sum up to $(n-1)n$. You need to add the missing term $n(n+1)$ in the second case, which resolves the apparent contradiction.
Answer: The results are same.
The first $n$ terms of first series is different from first $n$ terms of second series. Thus, You'll get different answers if you plug in same $n$ . In fact, you'll have to plug $n+1$ terms in second to get same as that of $n$ terms of first.
Answer: This reduces the problem to the evaluation of a second derivative.
$$
   1\cdot 2 + 2\cdot 3+ 3\cdot 4+ \cdots + n\cdot (n+1)
   = \sum_{k=1}^{n} k(k+1) \\
   = \left.\frac{d^2}{dx^2}(1+x+x^2+x^3+\cdots+x^{n+1})\right|_{x=1} \\
   = \left.\frac{d^2}{dx^2}\frac{x^{n+2}-1}{x-1}\right|_{x=1}
$$
Answer: $S_1=1⋅2+2⋅3+3⋅4+\dots$
$T_n=n(n+1)$
$S_1=\frac{n(n+1)(2n+1)}{6}\bf+\frac{n(n+1)}{2}$
$S_2=1⋅2+2⋅3+3⋅4+\dots$
$T_n=(n-1)n$
$S_2=\frac{n(n+1)(2n+1)}{6}\bf-\frac{n(n+1)}{2}$
As the bold part indicates, the summation isn't the same.
Let's put $\bf n=1$:
$S_1=1⋅2=2$
$S_1=\frac{1(2)(3)}{6}\bf+\frac{1(2)}{2}=1+1=2$
$S_2=0⋅1=0$
$S_2=\frac{1(2)(3)}{6}\bf-\frac{1(2)}{2}=1-1=0$
Let's put $\bf n=1$:
$S_1=1⋅2+2⋅3=8$
$S_1=\frac{2(3)(5)}{6}\bf+\frac{2(3)}{2}=5+3=8$
$S_2=0⋅1+1⋅2=2$
$S_2=\frac{2(3)(5)}{6}\bf-\frac{2(3)}{2}=5-3=2$
So, what you have done is totally correct and verifies.
Whenever there is confusion like such that you have, working out for small values of $n$ which we can ourselves calculate helps to make things clearer.
Comment: This answers highlights that the two summations are different, but not what the difference is. Also, your chosen notation adds to the confusion. You gave the same name to two different definitions of $T_n$, and didn't make the dependence of $S_1$ and $S_2$ on $n$ explicit. This makes it hard to highlight the difference. The difference is just that one of the two sequences is shifted by one term., and $S_2(n+1) = S_1(n)$, or alternatively $S_2(n) = S_1(n) + T_n$.
Answer: In first case. ${\color{green}S_n}=\frac{n(n+1)(n+2)}{6}+\frac{n(n+1)}{2}={\color{red}{\frac{n(n+1)(n+2)}{3}}}$
In second case, $S'_{n+1}=\frac{(n+1)(n+2)(2n+3)}{6}-\frac{(n+1)(n+2)}{2}={\color{red}{\frac{n(n+1)(n+2)}{3}}}={\color{green}S_n}$


How to define PyCharm-friendly value object in Python?

Question: I'm curious about good way to define value object in Python. Per Wikipedia: "value object is a small object that represents a simple entity whose equality isn't based on identity: i.e. two value objects are equal when they have the same value, not necessarily being the same object". In Python that essentially means redefined __eq__ and __hash__ methods, as well as immutability.
Standard namedtuple seems like almost perfect solution with exception that they don't play well with modern Python IDE like PyCharm. I mean that IDE will not really provide any helpful insights about class defined as namedtuple. While it's possible to attach docstring to such class using trick like this:
class Point2D(namedtuple("Point2D", "x y")):
    """Class for immutable value objects"""
    pass

there's simply no place where to put description of constructor arguments and specify their types. PyCharm is smart enough to guess arguments for Point2D "constructor", but type-wise it's blind.
This code have some type information pushed in, but it's not very useful:
class Point2D(namedtuple("Point2D", "x y")):
    """Class for immutable value objects"""
    def __new__(cls, x, y):
        """
        :param x: X coordinate
        :type x: float

        :param y: Y coordinate
        :type y: float

        :rtype: Point2D
        """
        return super(Point2D, cls).__new__(cls, x, y)

point = Point2D(1.0, 2.0)

PyCharm will see types when constructing new objects, but will not grasp that point.x and point.y are floats, so would not not help to detect their misuse. And I also dislike the idea of redefining "magic" methods on routine basis.
So I'm looking for something that will be:

just as easy to define as normal Python class or namedtuple
provide value semantics (equality, hashes, immutability)
easy to document in a way that will play nicely with IDE

Ideal solution could look like this:
class Point2D(ValueObject):
    """Class for immutable value objects"""
    def __init__(self, x, y):
        """
        :param x: X coordinate
        :type x: float

        :param y: Y coordinate
        :type y: float
        """
        super(Point2D, self).__init__(cls, x, y)

Or that:
class Point2D(object):
    """Class for immutable value objects"""

    __metaclass__ = ValueObject

    def __init__(self, x, y):
        """
        :param x: X coordinate
        :type x: float

        :param y: Y coordinate
        :type y: float
        """
        pass

I tried to find something like this but without success. I thought that it will be wise to ask for help before implementing it by myself.
UPDATE:
With help of user4815162342 I managed to come up with something that works. Here's the code:
class ValueObject(object):
    __slots__ = ()

    def __repr__(self):
        attrs = ' '.join('%s=%r' % (slot, getattr(self, slot)) for slot in self.__slots__)
        return '<%s %s>' % (type(self).__name__, attrs)

    def _vals(self):
        return tuple(getattr(self, slot) for slot in self.__slots__)

    def __eq__(self, other):
        if not isinstance(other, ValueObject):
            return NotImplemented
        return self.__slots__ == other.__slots__ and self._vals() == other._vals()

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        return hash(self._vals())

    def __getstate__(self):
        """
        Required to pickle classes with __slots__
        Must be consistent with __setstate__
        """
        return self._vals()

    def __setstate__(self, state):
        """
        Required to unpickle classes with __slots__
        Must be consistent with __getstate__
        """
        for slot, value in zip(self.__slots__, state):
            setattr(self, slot, value)

It's very far from an ideal solution. Class declaration looks like this:
class X(ValueObject):
    __slots__ = "a", "b", "c"

    def __init__(self, a, b, c):
        """
        :param a:
        :type a: int
        :param b:
        :type b: str
        :param c:
        :type c: unicode
        """
        self.a = a
        self.b = b
        self.c = c

It's total FOUR times to list all attributes: in __slots__, in ctor arguments, in docstring and in ctor body. So far I have no idea how to make it less awkward.
Comment: Note that `namedtuple` has a primary purpose of providing both the tuple interface (indexing, unpacking), and attribute access. It was invented for backward-compatibility of functions that used to return tuples, such as `os.stat` or `time.gmtime`. It is likely not the optimal choice for a simple value type.
Comment: Regarding types: *PyCharm is smart enough to guess arguments for Point2D "constructor", but type-wise it's blind* Maybe you should be using a statically typed language? In Python it shouldn't be such a big deal that an IDE is blind about types.
Comment: Well, `namedtuple` almost do the right job for me. It's definitely more then simple value object, but I can live with it.

As for using statically typed language, I wish I could. But I have a Python project on hands and looking for a way to make development more comfortable. And PyCharm already does very good job for inferring type of variables using docstrings.
Answer: New in version 3.5: The typing module and NamedTuple
In version 3.5, the typing module has been added, in it, you will find a class that perfectly fits your needs.
The new NamedTuple
It works just as you'd expect:

Simple type definition:
from typing import NamedTuple
class DownloadableFile(NamedTuple):
    file_path: str
    download_url: str

Recognized in PyCharm:

Note:
As of today, the API is still in a provisional stage. It means it isn't guaranteed to be backwards compatible when new version is released. Changes to the interface though are not expected. My personal take on it is: given the simplicity of the design, if change there is, I am sure it will be an easy refactor ;)
Answer: Your requirements, although carefully expressed, are not quite clear to me, partly because I don't use the PyCharm GUI. But here is an attempt:
class ValueObject(object):
    __slots__ = ()

    def __init__(self, *vals):
        if len(vals) != len(self.__slots__):
            raise TypeError, "%s.__init__ accepts %d arguments, got %d" \
                % (type(self).__name__, len(self.__slots__), len(vals))
        for slot, val in zip(self.__slots__, vals):
            super(ValueObject, self).__setattr__(slot, val)

    def __repr__(self):
        return ('<%s[0x%x] %s>'
                % (type(self).__name__, id(self),
                   ' '.join('%s=%r' % (slot, getattr(self, slot))
                            for slot in self.__slots__)))

    def _vals(self):
        return tuple(getattr(self, slot) for slot in self.__slots__)

    def __eq__(self, other):
        if not isinstance(other, ValueObject):
            return NotImplemented
        return self.__slots__ == other.__slots__ and self._vals() == other._vals()

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        return hash(self._vals())

    def __setattr__(self, attr, val):
        if attr in self.__slots__:
            raise AttributeError, "%s slot '%s' is read-only" % (type(self).__name__, attr)
        super(ValueObject, self).__setattr__(attr, val)

Usage is like this:
class X(ValueObject):
  __slots__ = 'a', 'b'

This gets you a concrete value class with two read-only slots and an autogenerated constructor, __eq__, and __hash__. For example:
>>> x = X(1.0, 2.0, 3.0)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 5, in __init__
TypeError: X.__init__ accepts 2 arguments, got 3
>>> x = X(1.0, 2.0)
>>> x
<X[0x4440a50] a=1.0 b=2.0>
>>> x.a
1.0
>>> x.b
2.0
>>> x.a = 10
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 32, in __setattr__
AttributeError: X slot 'a' is read-only
>>> x.c = 10
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 33, in __setattr__
AttributeError: 'X' object has no attribute 'c'
>>> dir(x)
['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', '_vals', 'a', 'b']
>>> x == X(1.0, 2.0)
True
>>> x == X(1.0, 3.0)
False
>>> hash(x)
3713081631934410656
>>> hash(X(1.0, 2.0))
3713081631934410656
>>> hash(X(1.0, 3.0))
3713081631933328131

If you want, you can define your own __init__ with the docstring that (presumably) provides your IDE with type annotation hints.
Comment: I played with this solution for some time. It grasps semantics of value object precisely, but has same troubles with type inference as `namedtuple`. Adding `__init__` doesn't really help: without "magical" string like `self.a = a` PyCharm has no idea that it should link type declaration of an argument to an object attribute. I used your code to build something that will work for me, but it's far from perfect. I'm attaching it as update to original question now.
Answer: An update solution:
Since python 3.7 there is a new built in module called dataclasses which has the dataclass class in it.
Pycharm supports it and knows how to work with it.
It is a perfect fit for a value object, since it already defines a lot of what you would define for a value object and the syntax is really short:

repr
eq
making the class immutable by passing Frozen=True

example:
from dataclasses import dataclass
@dataclass(frozen=True)
class Point2D:
    x: float
    y: float

There are differences between NamedTuple and Dataclasses which most notably one is based on a tuple and the other one on a dict.
In my opinion, the dataclass is the best code generator ATM to create a value object.
For more info, continue with python's docs about how to use a dataclass.


Which statistical method should I use to prove significant difference for my picture?

Question: I would like to confirm my biological hypothesis with statistical approach.
Red line on picture represents average frequency of some biological phenomenom for whole chromosome. Chromosome consists of milions of bases, which can be understood as positions. So that we have milions of positions total. Then I, using certain rule, pick up 100 positions. For these 100 positions I determine frequency of the same biological phenomenon (so that I have 100 isolated points, for every x there is y and they are connected by lines, as seen on picture). Because picture shows just these positions, red line does not represent average of picture (it represents average of whole chromosome).
I want to show that freguency at my certain positions is significantly higher than average (so that the biological process I observe is really there).
My data are from database,so my output is what I calculated using this database-there are no more measurements or data of this kind.
y-axis represent counts, not ratios. Adjacent points on graph are neighbours on the chromosome, so one could expect that two neighbours on the chromosomes do experience same/similiar biological process.
I am a computer scientist (with one course of statistics so I have an idea) - detailed howto would be appreciated. However, advice about which method to use may be fair enough :-)
Comment: Hi whuber, thanks for your comment. x-axis represents certain positions at chromosome, y-axis frequency of some biological phenomenom. Red line is average frequency for whole chromosome. I want to show that freguency at my certain positions is significantly higher than average. (so that the biological process I observe is really there)
Comment: Will try to do my best-red line is average for the whole chromosome, which consist of milions of bases, which can be understood as positions. So that we have milions of positions total. I pick up 100 positions and determine frequency of certain biological process. Because picture shows just these positions,red line does not represent average of pic. My data are from database,so my output is what I calculated using this database-there are no more measurements or data of this kind. Because I have 100 positions, data are isolated points, which were connected for better illustration of phenomenon.
Comment: Good! Just a few more followup questions. (1) What are these "point" frequencies? Are they counts or are they proportions? (2) What is the basis for selecting these particular 100 points: are they randomly selected? Were they chosen because some of them exhibited high frequencies? Something else? (3) Is there any relationship to be expected among the frequencies for adjacent points in the graph? (There appears to be strong serial correlation, as evidenced by the smoothness of the line.) (4) Does the *sequence* of points have any meaning?
Comment: Thank you a lot! (1) counts (2) something else, they were chosen because they lie next to the elements on chromosomes called transposons, so that the positions were chosen using certain rule (3) adjacent points are neighbours on the chromosome, so yes, one could expect that two neighbours on the chromosomes do experience same/similiar biological process (4) not really, we are just showing that next to transposons there exists certain biological process, thats all what we want to show
Comment: It might make sense to restructure your analysis so it analyzes data from adjacent pairs of points on the chromosome: the positions you chose by your rule and the positions near those points.  Your null hypothesis would then reflect no difference between the pairs. (Nice questions by whuber!)
Comment: Could you explain--with some detail--what it means to you for one line to be "significantly higher" than another?  Also, lines by themselves cannot be assessed statistically: the focus of analysis is the *data*.  What are the *data* from which these graphs are generated?
Comment: Thanks--but we really need more information. To begin with, the red line clearly does not represent the average height of the blue line, so some crucial information is missing. Second, in order to determine *significance* of differences, it is essential to know how the data are measured and how they vary: the graphs don't show us that, either.
Comment: (+1) I have upvoted the comments that add information so that they will not disappear below the bottom of the page.  If you get a chance, it would help to provide the same information within the body of your question so that readers will not overlook it.
Comment: ok, will do when I come home:)
Comment: Hi whuber, I reformulated my question as you proposed.
Answer: Based on experience with timeline (from one other diploma and my bachelor thesis) analysis I would suggest comparing coefficients of linear regression and test for autocorrelation, maybe check for breakpoints.
Comment: What would be regressed against what? How would tests of autocorrelation and breakpoints answer the question?


java.lang.ClassNotFoundException for my app

Question: I recently just received a bug report from device "Desire HD (ace)" which I cannot recreate for the life of me.  I looked over Here1 and Here2 but it didn't seem like it would help me with my problem or I am just not understanding this enough to know if this is the fix to my problem.
My LogCat :
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{joseph.lubonty.librarysmite11/joseph.lubonty.librarysmite11.Splash}: java.lang.ClassNotFoundException: joseph.lubonty.librarysmite11.Splash in loader dalvik.system.PathClassLoader[/mnt/asec/joseph.lubonty.librarysmite11-2/pkg.apk]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1738)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1837)
at android.app.ActivityThread.access$1500(ActivityThread.java:132)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1033)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:143)
at android.app.ActivityThread.main(ActivityThread.java:4196)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: joseph.lubonty.librarysmite11.Splash in loader dalvik.system.PathClassLoader[/mnt/asec/joseph.lubonty.librarysmite11-2/pkg.apk]
at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1730)
... 11 more

My Manifest :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="joseph.lubonty.librarysmite11"
android:installLocation="preferExternal"
android:versionCode="19"
android:versionName="2.7" >

<compatible-screens>

    <screen
        android:screenDensity="mdpi"
        android:screenSize="normal" />
    <screen
        android:screenDensity="hdpi"
        android:screenSize="normal" />
    <screen
        android:screenDensity="xhdpi"
        android:screenSize="normal" />

    <screen
        android:screenDensity="mdpi"
        android:screenSize="large" />
    <screen
        android:screenDensity="hdpi"
        android:screenSize="large" />
    <screen
        android:screenDensity="xhdpi"
        android:screenSize="large" />

    <screen
        android:screenDensity="mdpi"
        android:screenSize="xlarge" />
    <screen
        android:screenDensity="hdpi"
        android:screenSize="xlarge" />
    <screen
        android:screenDensity="xhdpi"
        android:screenSize="xlarge" />

    <screen
        android:screenDensity="213"
        android:screenSize="large" />

    <screen
        android:screenDensity="480"
        android:screenSize="large" />

    <screen
        android:screenDensity="480"
        android:screenSize="normal" />
</compatible-screens>

<uses-sdk
    android:minSdkVersion="10"
    android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/b_promo"
    android:label="@string/app_name"
    android:logo="@drawable/i_topbarimage1"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".Splash"
        android:label="@string/title_activity_main"
        android:noHistory="true"
        android:screenOrientation="landscape" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >
    </activity>
    <activity
        android:name=".GodStatComparison"
        android:label="@string/app_name"
        android:screenOrientation="landscape" >
    </activity>
    <activity
        android:name=".JungleTimers"
        android:label="@string/app_name"
        android:screenOrientation="portrait" >
    </activity>
    <activity
        android:name=".JungleInfoTablet"
        android:label="@string/app_name"
        android:screenOrientation="landscape" >
    </activity>
    <activity
        android:name=".JungleTimersTablet"
        android:label="@string/app_name"
        android:screenOrientation="landscape" >
    </activity>
    <activity
        android:name=".TopPlayers"
        android:label="@string/app_name"
        android:screenOrientation="landscape" >
    </activity>
</application>
</manifest>

Here are images of my "Properties" > "Java Build Path" if this may help solve this problem :

("Projects" tab is empty)

Please let me know if there is any other sort of information you need.
Edit :
package joseph.lubonty.librarysmite11;

public class Splash extends FragmentActivity {

}

Comment: Post the declaration (including package statement) for the class? This usually indicates that you have a mismatch between your config file and the fully-qualified class name.
Comment: @chrylis I am a bit of a noob here, really sorry. Do you want me to post basically the top of my Splash class?
Comment: The whole Splash class is probably easiest. The most important things I'm looking for are the `package` line and the `public class` line.
Comment: @chrylis added the package line and public class line
Answer: Just installed it on my Desire HD fine. Installed itself to SD card by default. So probably what @Jon said.
Answer: It's possible their device is fubar'd, but I also just noticed your project is setup for JDK builds instead of ADT. You'll want to make sure everything is set up using Properties -> Android instead of Properties -> Java Build, as explained here.
Managing Projects from Eclipse with ADT | Android Developers
It appears others are also having similar issues after upgrading to ADT version 22, so there may be a bug in the SDK. I just checked to see what version I have and found an update to Ver. 22.2.1 available.
Libraries do not get added to APK after update to ADK 22
Comment: To be completely honest, I'm not really sure why that setup wouldn't work for you. I just checked my projects and even the the android samples are setup like that. Have you tried updating the ADK again and doing a clean build?
Comment: I guess this is where I am really confused.  So I guess I did it "The Wrong Way" as described in your link "here".  So would I have to undo this? (If I do which Screenshot or tab should I do my removal in?).

So for me to do this the right way I should be going to Properties -> Android and in "Project Build Target" and Select my Target (which is 17) and in "Library" select the check box "isLibrary"?  Also I cannot add anything when I click the "Add" feature in the Library section, it is all just blank.
Comment: I have not had an error since that user has reported it (or multiple users with the same device).  I did though have in my Properties > Android that the Project Build Target didn't match the one in my Manifest file so I went ahead and fixed that.  So I think it was their device being foobar or my small mistake there.  I will be putting out another update on it in 2 days that I hope to never see that error again or at least once in a blue moon.  Thanks again Jon for the follow up, I really appreciate it.


filling out NA values using clustering analysis

Question: I have a data frame with a large number of NA values. I do not wish to leave out all these rows as that would reduce the size of my training set drastically.
I filled out these missing values in a couple of ways, such as

Filling the NA values in a column with the majority value in that
column
Filling the NA values with a random label from that column.

However, I would like to try out something which uses cluster analysis. Is there an R package which allows this? Two things which I can implement are as follows

Finding the k nearest neighbour and filling up the missing/NA value
as the majority of the k neighbours. However, this could be
difficult because running the knn itself required that the rows
don't have NA values, in the first place.
Finding the jaccard similarity based on other columns in the row,
and filling up the missing/NA value with the corresponding value
from the jaccard similar row.

Finding jaccard match
<code>library(stringdist) df[which.min(Reduce(`+`,Map(stringdist,df, newdata, method='jaccard'))),]
</code>
Please suggest me a package/library in R which will help me fill out the missing/NA values using cluster analysis.
Comment: I use the mice package in these cases.
Answer: You can also use the k nearest by jaccard?
It's not as if you are bound to use Euclidean.
Either way, kNN is not clustering. I'd use kNN.
If you look at clustering algorithms, you'll notice that most cannot deal with NA values well either...


Transformar diversas colunas em apenas uma

Question: Olá, não programo VBA e não estou conseguindo fazer um código que fizesse o seguinte:

<code>|A |B |C |
----------
|1 |6 |11|
|2 |7 |12|
|3 |8 |13|
|4 |9 |14|
|5 |10|15|
</code>

Minha tabela tem diversas colunas como essas ali em cima, gostaria que me ajudassem com uma rotina que iria ler a partir da coluna B e colocar sempre embaixo da coluna A, neste caso ficaria em sequência do 1 ao 15 na coluna A, isso é possível?
Resultado:

<code>|A  |
-
|1  |
|2  |
|3  |
|4  |
|5  |
|6  |
|7  |
|...|
|14 |
|15 |
</code>
Comment: Quando voce diz tabela quer dizer uma planilha excel, vetores (arrays) ou é uma tabela do banco de dados access?
Comment: Uma tabela excel, gostaria de fazer uma macro para ela...
Answer: Resposta do autor em comentário.
<code>Sub macro()
    'Step 1:  Declare your variables.
        Dim MyRange As Range
        Dim MyCell As Range
        Dim i As Double
        i = 6000
    'Step 2:  Define the target Range.
        Set MyRange = Range("A1:T5917")
    'Step 3:  Start looping through the range.
        For Each MyCell In MyRange
    'Step 4:  Do something with each cell.
        MyCell.Cut
        Cells(i, 1).Select
        ActiveSheet.Paste
    'Step 5: Get the next cell in the range
        i = i + 1
        Next MyCell
End Sub
</code>
Coloquei no GitHub para referência futura.


vista clients can't connect to default sbs 2008 share

Question: One of my vista sp2 clients can no longer see the default share on my sbs 2008 sp2 box.
The server has no av and i've unsintalled anti virus stuff from the client and rebooted it. The client was fine until today. I don't think anything has changed since it was working on Friday.
I've tried to access the share as the user that first reported the problem and as the domain admin. Both users can see all the other computers/shares on the network but can't get to the default share on the server. All the shares for the server (eg public and users) are listed when you browse it from the network and all work except the main one.
Clicking on the main share causes it to hang for a while and then either report it offline or access denied. Occasioanlly only printers and the one share that doesn't work are listed and the others aren't. It generally takes a long time before anything is listed.
It isn't a permissions things since i have changed the permissions to everyone with no effect.
What's weird is that it occasionally works fine for a few mins and then seems to cut out.
Other networking is fine (email,rdp) and no other clients have the issue.
edit ----
Seems to be spreading. on some other vista machines I'm getting related issues like not able to connect to mapped drives to this share at login and log login times.
Only vista clients?
I had a similar problem before which effected all clients (osx, xp, vista) and turned out to be the symantec av on the server which i have uninstalled. This is subtly different.
Why can't it just work! I'm not doing anything complicated!
Answer: Make sure the time/date on the Vista machine matches the server. Make sure the DNS server entry on the Vista machine's network properties point to only the SBS server
Comment: the dns is set to the server and the date/time is the same.
Answer: I disabled all tcp offloading on the server both in windows and on the NIC. I also disabled Receive Side Scaling and tcp tuning and rebooted the server and it seems to have solved it.
the commands i ran were
<code>netsh interface tcp set global rss=disabled
netsh interface tcp set global autotuninglevel=disabled
netsh interface tcp set global chimney=disabled
</code>
Looking around this seems to be a problem with win2003sp2 but it seems to effect my sbs 2008 too.
This is related to an earlier server fault post i made:
slow unc resolution on a win 2008 share
which i had tracked down to the A/V. It seems it's the A/V and the all the neworking stuff above.


Interpreting intercept for the log model in linear regression in R for small predictor

Question: I have a dataset. Assume that y is the dependent variable and x is the independent variable. My goals for this analysis is mainly on the following hypothesis:

Expecting x=0 to imply y=0
Expecting a significant relationship between x and y

To achieve this, I am trying to determine the best transformation of x and y to fit the best linear model in R. So, the final model I got is $\sqrt y$ against ln(x). When I fit the model in R, I obtain the following for the coefficients:
<code>  Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.319615   0.028743   11.12 2.93e-10 ***
x           0.150139   0.009959   15.08 9.76e-13 ***
---
</code>
Questions:

I am trying to interpret the Intercept term. Since the p-value is much less than 5% significance level, can I say that the intercept is significantly different from 0? However, this model is undefined for x=0, hence I'm not sure if this interpretation is valid. I was thinking of will it be OK if I were to refit the linear model for smaller x. < Solved >
To address the above question, the problem as seen from this model is that I can't test for hypothesis 1. Would be very thankful if anyone could provide some help.
Comment: What I meant was click the [ASK QUESTION](http://stats.stackexchange.com/questions/ask) at the top, & ask a totally new question, not edit this one. It will also help to say what x & y are (eg, blood pressure, stock prices, etc), why you need a model of them, & why the model should show y=0 when x=0.
Comment: If you can say -- what does $y$ represent?
Comment: @Glen_b y is a ratio of two numbers, each is a count on the number of objects.
Comment: Question continues in a new question thread. http://stats.stackexchange.com/questions/116106/performing-a-linear-regression-on-small-dataset-and-trouble-with-modeling-small
Comment: The denominator of $y$ can occasionally be smaller than the numerator? It seems to behave like there's an upper boundary near 1 (as you'd see with a count divided by a total count - like "proportion of people with brown eyes"), but at least one of the observations exceeds 1. Trying to understand why it's nearly limited to 1 but not quite.
Comment: @Glen_b it is one of the limitation during the data collection process, which is not done by me as the total count is reported by the person but the numerator is reported by the organization. Can just take it as 1.
Comment: @user106113 It would be nice to be able to do so, since that would allow treating $y$ properly - as a binomial count out of a total. However, there's several issues to worry about.
Answer: The intercept term does not refer to when x=0, since your x is actually ln(x).  Instead, the intercept refers to when ln(x)=0, which occurs when the old x=1.  At that point (in the new space), $\hat y$ (i.e., $\widehat{\sqrt{y}}$) differs significantly from 0.
It may help you to read this excellent CV thread: Interpretation of log transformed predictor.
Comment: Why not try regressing y on x & x^2? Non-normal residuals usually aren't that big a deal. How far from normal are they & how much data do you have?
Comment: Thanks for the clarification, I totally missed it. If this is the case, how should I test whether at x=0, y is not significantly different from 0?
Comment: Is the point of your analysis to determine if y=0 when x=0? If so, using transformations (eg ln & sqrt) may not be the way to go. Is x=0 within, or close to, the range of x's you have in your dataset?
Comment: It is one of the reality check of the model, that when x=0, y should be close to zero. This transformation seems to be the only one that satisfy the model assumptions on residuals. And for the second question, my x ranges from 0.2 to 200.
Comment: What's wrong with the residuals? Are they non-normal? Is the variance not constant? Is there a curvilinear relationship that isn't being picked up? Bear in mind that when x=0, ln(x)=-infty.
Comment: When i try to fit sqrt(x) or even cube root(x), the residuals have a downward parabolic trend which implies that it is not independent.
Comment: The shape of the residual distribution has nothing to do w/ independence. Why not just regress y on x? What's wrong w/ that?
Comment: Because there is an obvious curve, something that looks like y = sqrt(x) in the original model. Also, regress y on x will end up with non-normal residuals.
Comment: when i perform a shapiro-wilk test on the residuals for y on x, i get a p value of 0.004. Besides, referring to the previous comment, doesn't the downward parabolic trend in the residuals vs fitted plot implies non-independence?
Comment: No, nothing about the shape of the residual distribution has to do w/ independence. Re S-W test, you may want to read [this](http://stats.stackexchange.com/q/2492/7290). What is your N?
Comment: Ok, I am confused. What I learnt from uni is that the shape of the residual distribution related to the independence. If this is not true, how do we test independence?
Comment: That would be best as a new question, not buried in comments. What is your N?
Comment: I'm not sure what do u mean by N. I got the following when i run the shapiro-wilk test in R.

"W = 0.8622, p-value = 0.004572". Not sure if this is also one of the reason, my dataset has only 23 points.
Comment: Hmmm, 23 points is pretty tough. It may be hard to determine if the value of y at x=0 is 0. Can you paste your data into your question above?
Comment: I have added the data in the question. Would be grateful for any form of opinions.
Comment: Hmm, not really sure & I don't have a lot of time to explore right now. Why not ask as a new question? Say a little bit about what the data are & what your goals are, etc. then post the data, etc.
Comment: Sorry to take up your time. Thank you so much for the help
Comment: No problem, sorry I wasn't more help.


KB2667402 update fails to install with 0x80004005. Yet it's also showing as installed

Question: I've got 15 Windows 2008 R2 x64 servers that I manage with SCCM2012. I've noticed during my Windows updates reporting that there's two boxes that are showing as 'error' for total updates installed. Digging around, it looks like the update that is failing to install is KB2667402.
The Software Centre on the server itself shows the following:
The software change returned error code 0x80004005(-2147467259).

So SCCM thinks it hasn't installed the update. However, if I go to the Programs and Features application and select 'Windows Updates', I can see an entry for KB2667402:

If I try and uninstall this, I get an error:
An error occurred. Not all of the updates were successfully uninstalled

If I try and download the patch from Microsoft directly, I get the same error installing as displayed in Software Centre.
The only odd thing about this setup that I can think would affect this is that I run the RDP service on a non-standard port. However, I do this across all the servers, so it seems odd that it would fail on just 2 out of 15.
The tail of the WindowsUpdate.log file is below:
2012-06-26  15:33:53:184    3924    1608    COMAPI  -------------
2012-06-26  15:33:53:190    3924    1608    COMAPI  -- START --  COMAPI: Install [ClientId = CcmExec]
2012-06-26  15:33:53:190    3924    1608    COMAPI  ---------
2012-06-26  15:33:53:190    3924    1608    COMAPI    - Allow source prompts: No; Forced: No; Force quiet: Yes
2012-06-26  15:33:53:190    3924    1608    COMAPI    - Updates in request: 1
2012-06-26  15:33:53:190    3924    1608    COMAPI    - ServiceID = {3DA21691-E39D-4DA6-8A4B-B43877BCB1B7} Managed
2012-06-26  15:33:53:199     860    1198    Agent   *************
2012-06-26  15:33:53:199     860    1198    Agent   ** START **  Agent: Installing updates [CallerId = CcmExec]
2012-06-26  15:33:53:199     860    1198    Agent   *********
2012-06-26  15:33:53:199     860    1198    Agent     * Updates to install = 1
2012-06-26  15:33:53:201     860    1198    Agent     *   Title = Security Update for Windows Server 2008 R2 x64 Edition (KB2667402)
2012-06-26  15:33:53:201     860    1198    Agent     *   UpdateId = {48859BE4-1331-4CD2-8E70-3B537180A0D0}.103
2012-06-26  15:33:53:201     860    1198    Agent     *     Bundles 1 updates:
2012-06-26  15:33:53:201     860    1198    Agent     *       {D854ECF1-99A7-4D67-B435-2D041BF79565}.103
2012-06-26  15:33:53:204    3924    1608    COMAPI    - Updates to install = 1
2012-06-26  15:33:53:204    3924    1608    COMAPI  <<-- SUBMITTED -- COMAPI: Install [ClientId = CcmExec]
2012-06-26  15:33:53:221     860    1198    Agent   WARNING: failed to calculate prior restore point time with error 0x80070002; setting restore point
2012-06-26  15:33:53:222     860    1198    Agent   WARNING: LoadLibrary failed for srclient.dll with hr:8007007e
2012-06-26  15:33:53:322     860    1198    DnldMgr Preparing update for install, updateId = {D854ECF1-99A7-4D67-B435-2D041BF79565}.103.
2012-06-26  15:33:53:325    5700    117c    Misc    ===========  Logging initialized (build: 7.5.7601.17514, tz: +0100)  ===========
2012-06-26  15:33:53:325    5700    117c    Misc      = Process: C:\Windows\system32\wuauclt.exe
2012-06-26  15:33:53:325    5700    117c    Misc      = Module: C:\Windows\system32\wuaueng.dll
2012-06-26  15:33:53:324    5700    117c    Handler :::::::::::::
2012-06-26  15:33:53:325    5700    117c    Handler :: START ::  Handler: CBS Install
2012-06-26  15:33:53:325    5700    117c    Handler :::::::::
2012-06-26  15:33:53:330    5700    117c    Handler Starting install of CBS update D854ECF1-99A7-4D67-B435-2D041BF79565
2012-06-26  15:33:53:342    5700    117c    Handler CBS package identity: Package_for_KB2667402~31bf3856ad364e35~amd64~~188.8.131.52
2012-06-26  15:33:53:366    5700    117c    Handler Installing self-contained with source=C:\Windows\SoftwareDistribution\Download\44059e0415033d6f699a50ef69dd5ff2\windows6.1-kb2667402-v2-x64.cab, workingdir=C:\Windows\SoftwareDistribution\Download\44059e0415033d6f699a50ef69dd5ff2\inst
2012-06-26  15:33:56:270    5700    3b8 Handler FATAL: CBS called Error with 0x80004005,
2012-06-26  15:33:56:402    5700    117c    Handler FATAL: Completed install of CBS update with type=0, requiresReboot=0, installerError=1, hr=0x80004005
2012-06-26  15:33:56:405    5700    117c    Handler :::::::::
2012-06-26  15:33:56:406    5700    117c    Handler ::  END  ::  Handler: CBS Install
2012-06-26  15:33:56:406    5700    117c    Handler :::::::::::::
2012-06-26  15:33:56:433     860    1198    Agent   *********
2012-06-26  15:33:56:433     860    1198    Agent   **  END  **  Agent: Installing updates     [CallerId = CcmExec]
2012-06-26  15:33:56:433     860    1198    Agent   *************
2012-06-26  15:33:56:433     860    d14 AU  Can not perform non-interactive scan    if AU is interactive-only
2012-06-26  15:33:56:450    3924    e40 COMAPI  >>--  RESUMED  -- COMAPI: Install   [ClientId = CcmExec]
2012-06-26  15:33:56:450    3924    e40 COMAPI    - Install call complete (succeeded = 0, succeeded with errors = 0, failed = 1, unaccounted = 0)
2012-06-26  15:33:56:450    3924    e40 COMAPI    - Reboot required = No
2012-06-26  15:33:56:450    3924    e40 COMAPI    - WARNING: Exit code = 0x00000000;     Call error code = 0x80240022
2012-06-26  15:33:56:451    3924    e40 COMAPI  ---------
2012-06-26  15:33:56:451    3924    e40 COMAPI  --  END  --  COMAPI: Install [ClientId = CcmExec]
2012-06-26  15:33:56:451    3924    e40 COMAPI  -------------
2012-06-26  15:33:56:536     860    13a4    AU  Triggering Offline detection (non-interactive)
2012-06-26  15:33:56:536     860    d14 AU  #############
2012-06-26  15:33:56:536     860    d14 AU  ## START ##  AU: Search for updates
2012-06-26  15:33:56:536     860    d14 AU  #########
2012-06-26  15:33:56:539     860    d14 AU  <<## SUBMITTED ## AU: Search for updates [CallId = {2DBB046C-2265-421B-A37B-93BDECC6C261}]
2012-06-26  15:33:56:539     860    1788    Agent   *************
2012-06-26  15:33:56:539     860    1788    Agent   ** START **  Agent: Finding updates [CallerId = AutomaticUpdates]
2012-06-26  15:33:56:539     860    1788    Agent   *********
2012-06-26  15:33:56:539     860    1788    Agent     * Online = No; Ignore download priority = No
2012-06-26  15:33:56:539     860    1788    Agent     * Criteria = "IsInstalled=0 and DeploymentAction='Installation' or IsPresent=1 and DeploymentAction='Uninstallation' or IsInstalled=1 and DeploymentAction='Installation' and RebootRequired=1 or IsInstalled=0 and DeploymentAction='Uninstallation' and RebootRequired=1"
2012-06-26  15:33:56:539     860    1788    Agent     * ServiceID = {3DA21691-E39D-4DA6-8A4B-B43877BCB1B7} Managed
2012-06-26  15:33:56:539     860    1788    Agent     * Search Scope = {Machine}
2012-06-26  15:33:58:562     860    1788    Agent     * Found 0 updates and 70 categories in search; evaluated appl. rules of 180 out of 1072 deployed entities
2012-06-26  15:33:58:565     860    1788    Agent   *********
2012-06-26  15:33:58:565     860    1788    Agent   **  END  **  Agent: Finding updates [CallerId = AutomaticUpdates]
2012-06-26  15:33:58:565     860    1788    Agent   *************
2012-06-26  15:33:58:650     860    f2c AU  >>##  RESUMED  ## AU: Search for updates [CallId = {2DBB046C-2265-421B-A37B-93BDECC6C261}]
2012-06-26  15:33:58:650     860    f2c AU    # 0 updates detected
2012-06-26  15:33:58:650     860    f2c AU  #########
2012-06-26  15:33:58:650     860    f2c AU  ##  END  ##  AU: Search for updates [CallId = {2DBB046C-2265-421B-A37B-93BDECC6C261}]
2012-06-26  15:33:58:650     860    f2c AU  #############
2012-06-26  15:33:58:650     860    f2c AU  Featured notifications is disabled.
2012-06-26  15:33:58:651     860    f2c AU  Successfully wrote event for AU health state:0
2012-06-26  15:33:58:652     860    f2c AU  Successfully wrote event for AU health state:0

Answer: This thread looks to have a solution that worked for people.
KB2667402 fails with a 8024200D error in Win 2008R2 x64

Had same problem. The update already exists in the list of installed updates. Removed the update and installed it again
Comment: I can't remove the update. That's the whole point.


Como posso aplicar Unpivot em uma select simples, quero deixar na vertical uma consulta

Question: Conforme o código abaixo:
SELECT
1 DADO1
,2 DADO2
FROM   DUAL
Gostaria de deixar o resultado da pesquisa na vertical, sou iniciante em Oracle, vi que da pra fazer com o unpivot mas não encontrei um exemplo simples demonstrando a inversão de colunas na vertical e seus resultados ao lado de cada campo.
Comment: Que eu saiba, no Oracle é igual no SQL. http://pt.stackoverflow.com/questions/189841/12-colunas-de-meses-1-coluna-de-valores-1-coluna-de-m%C3%AAs/189863#189863
Answer: Conforme consulta utilizada, segue abaixo como ficaria. Para adequar ao seu cenário, recomendo consultar a Documentação - Pivot and Unpivot EN.
SELECT valor
  FROM ((SELECT '1' dado1
               ,'2' dado2
               ,'3' dado3
               ,'4' dado4
               ,'5' dado5
           FROM dual)
        unpivot(valor FOR tipo_de_valor IN (dado1
                                 ,dado2
                                 ,dado3
                                 ,dado4
                                 ,dado5)))

Comment: Obrigado pelo exemplo David, vou implementar aqui na consulta.


Enable Aspect proxy based on runtime condition, Spring AOP?

Question: I am using Spring AOP to reduce my debug log of my existing application.
What I tried to do is log every method invocation based on log level.
I know Spring will construct a proxy for every class of mine if I using below aspect,which will introduce some overhead if it is not in debug level:
package com.basepackage.aop;

import....

@Aspect
@Component
public class LogAspect {

    private Logger logger=Logger.getLogger(LogAspect.class.getName());

    @Pointcut("execution(* com.basepackage..*.*(..))")//all the method in my app
    private void debug_log(){};

    @Around("debug_log()")//here, I hope I can introduce something like && logger.isDebugeEnable()
    public Object aroundLog(ProceedingJoinPoint joinPoint) throws Throwable{
        String signature=joinPoint.getSignature().toString();
        String paramList = null;
        Object[] args=joinPoint.getArgs();
        for (int i = 0; i < args.length; i++) {
            paramList+=args[i]+" ";
        }

        String debugMsg="----------enter "+signature;
        if(paramList!=null){
            debugMsg+="\nparam: "+paramList;
        }

        LogUtil.debug(debugMsg);//will delegate to log4j
        try{
            Object returnObject= joinPoint.proceed();
            LogUtil.debug("--------return form"+signature);//will delegate to log4j
            return returnObject;
        }
        catch(Throwable t){
            LogUtil.error("--------error from "+signature, t);//will delegate to log4j
            throw t;
        }
    }
}

What I hope is that only when log4j level <=debug level will Spring AOP construct a proxy for every class.
Or any more suggestion on how to make the log clean will be highly appreciated.
Thank you!
Answer: You can add an activation condition to your pointcut via if(), see AspectJ documentation. The pointcut then returns boolean instead of void and contains a body dynamically evaluating the condition and returning the result:
@Pointcut("execution(* com.basepackage..*.*(..)) && if()")
public boolean debug_log() {
    return logger.isdebugEnabled();
};

Because it is dynamic, I guess the proxies are still being created, but the advice body will not be executed. In order to get rid of the proxies, switch from Spring AOP to AspectJ which does not use proxies and is more efficient. AspectJ can be easily integrated into Apring applications via LTW (load-time weaving).
Update:
Spring AOP is just a proxy-based "AOP lite" approach for method interception, not a full-fledged framework like AspectJ. Thus, it does not support the if() pointcut primitive, see here. Having said that, I suggest you switch to full AspectJ. It can be applied to Spring applications easily via LTW (load-time weaving) as described here.
Comment: Thank you! I will try ! But I have one more thing to ask, does the `logger` have something need to pay attention to? For example: does it has to be non-static, or where does it has to be created from(injected , constructor or something else)?
Comment: I got some error when I run the application in tomcat, the nested exception is org.aspectj.weaver.tools.UnsupportedPointcutPrimitiveException: Pointcut expression 'execution(* wodinow.weixin.jaskey..*.*(..)) && if()' contains unsupported pointcut primitive 'if'
Comment: The logger can be static if you wish. This question is unrelated to the AOP problem.
Comment: So dou you mean there is no other way to maje a point cut based on run time cindition using spring aop?
Comment: Correct. If I had known one, I would have told you.


Swift - SKSprite Kit - Change Gamescene Variables from FileBrowser Closure

Question: I am working on an application that uses the 'FileBrowser' CocoaPod to load files in a simulator (using the SKSprites Physics Engine)
I have a function in my GameViewController that creates a 'FileBrowser' instance, then allows the user to set it's 'didSelectFile' closure like so:
let file = FileBrowser()
    present(file, animated: true, completion: nil)

fileBrowser.didSelectFile = { (file: FBFile) -> Void in
print(file.displayName)}

This enables me to trigger that small bit of code in the closure once a file has been selected from the popup browser, and to print the name of the file clicked, but I can't figure out how to get the value of 'file.displayName' back to my GameScene (I need it to be passed to that class instance to load the file and change the level, etc).
I've tried adding a 'String' return to the closure, which I cannot do. I've also tried to pass my GameScene to the Closure but that doesn't work.
So how do I get the data that is retrievable within that closure back to my GameScene if I cannot edit the closures inputs / outputs? (they are defined by the library).
Thanks
Answer: I solved my problem:
What I had to do was give the GameViewController class a property 'scene', and then add inside of the "viewDidLoad()" function:
self.scene = gameScene

then inside the closure, I had to add the code
let gameScene = self.scene as! GameScene

Then I could edit variables in my GameScene (ex: gameScene.numberofpoints = 100)
So in short, I guess giving the GameViewController class a 'scene' variable to store the gamescene, then allowed me to change attributes of this gameScene from within the closure.


Problema com APK

Question: Estou com um problema com o arquivo APK gerado pelo android studio, quando eu instalo o app via AVD Manager o App funciona normalmente, porem se eu pegar o apk de debug e instalar no mesmo dispositivo, ao tentar abrir o App ele fecha automátiamente. Alguém já passou por isso?
Comment: abre o logcat no Android Studio com o celular plugado e vê qual o erro apareceu
Comment: se e o apk de debug voce consegue o pegar o erro no android studio
Comment: Deu um erro,  android.view.InflateException: Binary XML file line #8: Binary XML file line #8: Error inflating class androidx.constraintlayout.widget.ConstraintLayout. Resolvi recriando o Layout. Muito obrigado!
Answer: No Android Studio tem uma função de gerar o arquivo apk para ser instalador e tem outra função para compilar e executar, são duas rotinas separadas mas as duas geram um apk, e a de compilar gera um apk incompleto.
Vá em Build\Builds APK, essa rotina sim gera o instalador. As Rotinas Run, Make, Debug geram os apk incompleto, uma versão para ser executada direto no emulador ou do cabo USB.
Comment: Oi eu já tinha testado dessa forma acabei por seguir a orientação do Paulo e do Neuber, deu o erro:  android.view.InflateException: Binary XML file line #8: Binary XML file line #8: Error inflating class androidx.constraintlayout.widget.ConstraintLayout. Resolvi refazendo o Layout

Problema com APK


Comunicação entre Fragment e Activity

Question: Estou fazendo um aplicativo em Android que utiliza seletores de tempo e de data (DatePicker e TimePicker), que são exibidos na forma de fragments. Quando o usuário define o tempo desejado, preciso que o mesmo seja passado do fragment do seletor para a janela principal. Tenho os seguintes códigos:
Fragment de seletor de tempo:
package pickers;

import java.util.Calendar;

import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.text.format.DateFormat;

import compromissos.Tela_Cadastro;

public class TimePicker extends DialogFragment implements
        TimePickerDialog.OnTimeSetListener {

    public TimePicker() {
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        // Create a new instance of TimePickerDialog and return it
        return new TimePickerDialog(getActivity(), this, hour, minute,
                DateFormat.is24HourFormat(getActivity()));
    }

    @Override
    public void onTimeSet(android.widget.TimePicker view, int hourOfDay,
            int minute) {
        // aqui que eu preciso que a hora selecionada seja enviada para a classe
        // princpal

    }

}

E o da classe que chama o fragment de tempo:
package compromissos;

import pickers.TimePicker;
import android.app.ActionBar;
import android.app.Activity;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import classes.BancoDeDados;
import classes.Evento;

import com.bravosix.compromissos.R;

public class Tela_Cadastro extends Activity {

    BancoDeDados bd = new BancoDeDados(this);
    private EditText nome, data, local, telefone;

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

        nome = (EditText) findViewById(R.id.cadastro_input_evento);
        local = (EditText) findViewById(R.id.cadastro_input_local);
        data = (EditText) findViewById(R.id.cadastro_input_data);
        telefone = (EditText) findViewById(R.id.cadastro_input_telefone);

        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_cadastro, menu);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {

        switch (item.getItemId()) {

        case R.id.cadastrar:
            salvarEvento();
            return true;

        case R.id.cancelar:
            finish();
            return true;

        default:
            return super.onMenuItemSelected(featureId, item);
        }
    }

    public void mostrarDatePicker(View view) {
        DialogFragment newFragment = new TimePicker();
        newFragment.show(getFragmentManager(), "timePicker");
    }

    public void salvarEvento() {

        String evento_nome, evento_local, evento_data, evento_telefone;

        evento_nome = nome.getText().toString();
        evento_local = local.getText().toString();
        evento_data = data.getText().toString();
        evento_telefone = telefone.getText().toString();

        bd.adicionarEvento(new Evento(evento_nome, evento_local, evento_data,
                evento_telefone));

        Toast.makeText(this, "Evento criado com sucesso.", Toast.LENGTH_SHORT)
                .show();
        finish();
    }
}

Eu pesquisei um pouco mas não cheguei a nenhuma maneira que me permitisse fazer isso de forma simples. Li que poderia chamar um método estático na classe principal, mas preciso fazer um toast, que requer o contexto, que não consegui obter dentro de um método estático. O que me sugerem?
Answer: Esta é a forma como eu costumo fazer.
Na classe do DialogFragment declaro uma interface que define os métodos que a Activity, a que chama o Fragment, deve implementar para ser notificada daquilo que se passa no Fragment.
public interface TimeSetListener {
      public void onTimeSet(int hora, int minuto);
}

Declaro um campo no DialogFragment para guardar a referência da Activity que chama o Fragment.
TimeSetListener mListener;

No evento onAttachdo DialogFragment guardo a referência da Activity, ela tem de implementar a interface.
@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (TimeSetListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
            + " deve implementar TimeSetListener");
        }
    }

Quando quero informar a Activity chamo o respectivo método da interface.
@Override
public void onTimeSet(android.widget.TimePicker view, int hourOfDay,
        int minute) {
    mListener.onTimeSet(hourOfDay, minute);
}

Comment: Se você quer utilizar o formato 24h independentemente de como está definido nas preferências do *device* passe `true` em vez de `DateFormat.is24HourFormat(getActivity())` no construtor do `TimePickerDialog`. A função `DateFormat.is24HourFormat` retorna `true` ou `false` de acordo com o que está definido nas preferências.
Comment: Obrigado, funcionou perfeitamente! Talvez você possa me tirar a seguinte dúvida: como faço para que o formato 24h seja usado? (não achei onde declarar o is24HourView)

Comunicação entre Fragment e Activity


Variable value not kept in while loop

Question: I'm facing a weird issue and I can't really understand what I'm doing wrong... There must be something!
I'll explain it shortly...
I'm developing for the Arduino platform (As far as I know it's heavily based on C++) and in a section of my actual code I have a while loop...
So where's the issue?
If I set a variable (a flag in my case) inside the while loop it gets resetted every time, this code is in a function... (may be useful)
Here it is:
void waitResponse(char* text) {
    static bool flag = false;
    count = 0;
    digitalWrite(GREEN_PIN, HIGH); //Turn OFF Green LED
    while (!espSerial.available()) { //Wait until we get some data in...
        Serial.println("No data");
        notBlockingBlink();
    }
    while (!flag) { //We got sth
        Serial.print("Flag value 1: ");
        Serial.println(flag);
        while (espSerial.available()) {
            Serial.println("In");
            if (search(text)) {
                flag = true;
                Serial.println("Found");
                Serial.print("Flag value 2: ");
                Serial.println(flag);
                break;
            } else {
                notBlockingBlink();
            }
        }
        Serial.print("Flag value 3: ");
        Serial.println(flag);
        notBlockingBlink();
    }
}

I've tried to debug my issue...
After entering the if block where there is "Found", flag gets set to true, indeed "Flag value 2:" is true just like "Flag value 3:", but
at the next iteration "Flag value 1:" is actually false...
What's wrong? Please enlighten me! Thanks
Comment: _"I've tried to debug my issue..."_ Obviously not seriously enough.
Comment: What does `notBlockingBlink();` do?
Comment: @NathanOliver It makes an LED blink, but I guess It's irrelevant...
Comment: @πάνταῥεῖ Why? I can't find the error I made...Help?
Comment: Since the outer `while` statement's condition is `!flag` (`while (!flag)`, it is impossible for `flag` to be true at the next statement. So the "next iteration" must be later, after `flag` has somehow gotten changed. (Although I don't know how that happens, since `flag` is static and local to the function.)
Comment: Looks like your waitResponse is being called many times and that is where the flag is set to `false`.  When the flag is set to `true`, your function exits.
Comment: @ingamedeo Well, step through your code line by line, and keep watching state values changing.
Comment: Debugging may be difficult since this is an embedded system.  Print statements may prove easier if the OP doesn't have a JTAG debugger or remote debugging capabilities.
Comment: @rici as far as I know !flag is only supposed to check if the opposite of the value of flag is true, is it wrong? Does it actually invert the value?
Comment: @ThomasMatthews The code runs only one time... That's for sure ;)
Comment: @ingamedeo: No, it doesn't change the value. So if `flag` is true, the loop does not execute. Consequently, if the loop (and thus the `Serial.print` call) executes, `flag` *must be false*.
Comment: @rici Indeed! But I set it to true... So it should exit
Comment: @ingamedeo: yes, so there are two possibilities. (1) NotBlockingBlink corrupts memory. (2) The function is called a second time, after something else corrupted memory.
Comment: @rici You have been very helpful, thanks a lot really, I'll look into that code now
Answer: Since your condition for the while loop is !flag, logically there is no possibility of having an iteration where flag is true. Therefore the behavior you believe should happen can not happen.
Comment: Your function is called a second time. The variable is in fact local to the function, so it's not reset, it's just declared a second time (and initialised false).
Comment: @rainbowgoblin: Except that it's declared `static`.
Comment: Okay... I thought so and so and I got really confused when it did... The variable seems to be resetting itself
Comment: I believe it should exit the loop... But it doesn't...That's the issue
Comment: You might want to update your question with what the problem actually was... Ignacio Vazquez-Abrams is completely right, the fact that it's static means that some line OTHER THAN THE DECLARATION must be making the value of `flag` false.

Variable value not kept in while loop


Can't use (self-signed wildcard) SSL Certificate in Windows Azure Website (WAWS)

Question: I want to secure an azure website with a custom domain via SSL.
The website is in the "Standard" Tier, as required.
I've been able to upload my self-signed wildcard certificate, but when I want to bind it to the custom domain name, it is not appearing in the "choose a certificate" dropdown.

Does anybody know why this is?
EDIT
For completeness sake, here's how I generated the self-signed certificate:

Generate a root-certificate
makecert -pe -n "CN=Mydomain Root" -ss my -a sha1 -sky exchange -r -len 2048 root.mydomain.com.cer
I imported the root-certificate (right-click -> Install Certificate) after which it ended up in the "Personal" certificate store
Generate a wildcard certificate from the root certificate:
makecert -pe -n "CN=*.mydomain.com" -a sha1 -sky exchange -eku 126.96.36.199.184.108.40.206.1 -is my -in "Mydomain Root" -sp
"Microsoft RSA SChannel Cryptographic Provider" -sy 12 -ss Personal wildcard.mydomain.com.cer
I exported the pfx file of this wildcard certificate with these settings
I uploaded the exported pfx to azure and tried to bind that to my website's custom domain name.
Answer: I haven't found a current link for that, but this post on SO suggests that wildcard certificates are not possible (yet) with Azure Websites.
According to this post on Azure Feedback, it should be available on end of april 2014.

Wildcard domain support is live. You can assign a wildcard certificate
  to your wildcard domain with an SNI SSL binding. Look for IP SSL
  support at the end of April.
Comment: I've followed [this](http://blogs.msdn.com/b/windowsazure/archive/2013/12/13/securing-your-windows-azure-web-sites-waws-with-https-and-ssl.aspx) blog post and according to it, it should work. Please note that in my case I do have a wildcard certificate, but I'm not trying to bind it to a wildcard domain, but rather to a 'normal' domain. Also I'm using SNI SSL binding, not IP.
Comment: In my specific case, I've got three domains: dev.mydomain.com, qa.mydomain.com and prod.mydomain.com and I'm trying to bind all three of them to a *.mydomain.com certificate.
Comment: Interesting. Have you uploaded a correct certificate including it's private key?
Comment: I think so, I exported it like [this](http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-13-25/3482.WAWS4.png)
Comment: Then unfortunately I'm lost... hope someone else can chime in :)
Comment: I edited my question to include the way in which I generated the certificate. Maybe this will give you another clue?
Answer: It appears that the azure websites management console only accepts one level of wildcarding.
So:
web.mydomain.com and db.mydomain.com can both be certified with *.mydomain.com,
but for example web.qa.mydomain.com can't, because "web.qa" isn't valid according to the azure websites management console!
Solution? None at the moment, you have to make sure that your website's domain name only needs one part to be wildcarded.
Reference: http://social.msdn.microsoft.com/Forums/windowsazure/en-US/eeeadc3c-2b71-4c31-87aa-780d7c00f20d/cant-use-selfsigned-wildcard-ssl-certificate-in-windows-azure-website-waws?forum=windowsazurewebsitespreview


Copy days report to weekly

Question: I have a problem.
I have two workbooks. The first one is Workbook A, which contain information about days in a month.
The second one is Weekly Summary workbook, where I need to do weekly reports from Workbook A. There I would like to have VBA code, that copies the information about week days and paste the range from each day into Sheet1 of the Weekly Summary Workbook.
Can someone help me?
Here is an example...
Information about Days:

Week summary:
Comment: Could you post an example of how your two tables look like? It'd be best to edit it into your question.
Comment: We can easily help you with this, but we need to have see your sheet, post a in image of the sheets and also post the marco you wrote until now. You can actually even record the marco on one of the weeks, which will get you started.
Answer: Here is a code that was not tested, but should give you a good idea to start writing your macro:
Dim wkBookLog As WorkBook
Dim wkBookWeekly As WorkBook
Dim datestring As String
Dim LastRow As Long
Dim rowCount As Long
Dim CountDays As Integer

Set wkBookLog = Workbooks("Workbook A")
Set wkBookWeekly = Workbooks("Weekly Summary")
rowCount=0

For each s in wkBookLog.Sheets
    datestring = s.Range("C2").Text
    LastRow = Range("A4").SpecialCells(xlLastCell).Row
    s.Range("A4:A" & Cstr(LastRow)).Copy wsBookWeekly.ActiveSheet.Range("C" & Cstr(4+rowCount))
    s.Range("C2").Copy wsBookWeekly.ActiveSheet.Range("B" & Cstr(4+rowCount) & _
        ":B" & Cstr(4+rowCount+LastRow))
    rowCount=rowCount+LastRow+1
    CountDays=CountDays+1
    If CountDays=7 Then
        CountDays=0
        rowCount=0
        wsBookWeekly.ActiveSheet.Next.Select
    End If

Next s

Hope this helps.
Comment: Thank you very much ... :)
I will try it, and i believe, that this code help me to solve the problem...

Copy days report to weekly


Criando um bot em JS

Question: Estou desenvolvendo um bot em javascript onde ele irá inserir um valor em um campo de um site e clicar em 'enviar'.
window.onload = function() {
    window.open('http://www.google.com', '_self');
    document.getElementById('gbqfq').value = 'javascript';
    document.getElementById('gbqfb').click();
}

Porém encontrei um código semelhante a esse na internet, ele abre a página porem não insere no campo de busca o valor e clica em 'ir'. Alguém teria uma ideia semelhante a essa 'não solução'?
Comment: Só dá para fazer isso na forma de uma extensão de browser ou bookmarklet, ou se você achar uma maneira de injetar scripts no site desejado (alguma vulnerabilidade que permita XSS).
Comment: Em alguma outra programação é possível fazer esse acesso e enviar uma informação simulando um usuário digitando no campo?
Comment: Um bookmarklet não resolve?
Comment: @ralfting qualquer linguagem que tenha comunicação TCP/IP teoricamente permite, com maior ou menor complexidade. Seria melhor você explicar o que está tentando fazer, pra poder indicar o melhor caminho.
Comment: cara talvez vc consiga executar pelo console do navegador. O google chrome permite
Answer: Através do javascript executando dentro do contexto de uma página (e limitado pelo sandbox do navegador) não é possível manipular documentos vindos de outro domínio, seja em uma nova janela ou em um iframe. Isso é por motivos de segurança.

Se você quer uma resposta visual para isso: ver a janela do browser abrindo e os comandos sendo executados (talvez para repassar o controle para o usuário depois que chegar em algum dado estado, como depois de clicar em pesquisar), tem basicamente duas soluções:

Uma extensão ao navegador:
Extensões podem injetar código em uma página específica (como inserir um botão a mais na página do google), ou adicionar um botão direto na barra do navegador, ou teclas de atalho. Qualquer um desses pode ser gatilho para iniciar a ação: manipular o DOM da página.
O ponto negativo é que terá que fazer uma extensão para cada navegador que queira suportar, possivelmente usando APIs completamente diferentes.
Biblioteca de automação:
Usar um programa externo que vai lançar um novo processo do navegador e vai "controlar" ele. Isso é suportado por todos os grandes navegadores e é relativamente simples de programar. Duas boas bibliotecas: Selenium e Watir.

Por último, talvez você não queira um navegador visível ou a iteração com o usuário. Queira fazer tudo as escuras e apenas obter o resultado depois (um array dos títulos dos resultados da pesquisa, por exemplo). Para isso você precisa de um navegador headless.

PhantomJS:
Como já mencionado em outras respostas. É uma interface ao WebKit, mas sem criar uma janela ou visual de nenhum tipo. Você fica no controle de tudo.
Implementar o seu HTTP Client:
Aqui pode usar qualquer linguagem que queira. Basta abrir um socket TCP e se comunicar com o servidor do site usando o protocolo HTTP. O grande problema aqui é que o javascript da página não será executado e terá que processar o HTML manualmente, você estará muito limitado. Por outro lado é a forma mais rápida e eficiente de obter dados. Você pode fazer uma única request ao http://www.google.com/search?q=teste por exemplo.
Answer: Você pode usar o PhantomJs para simular o browser, usando scripts feitos usando javascript.
O que é possível fazer com o PhantomJs:

automação de navegação (provavelmente é isso que você quer)
testes de websites
tirar screenshots
converter página para PDF

O projeto usa o código do webkit, e permite fazer várias coisas usando scripts em javascript. Não é necessário ter nenhum navegador instalado na máquina em que o PhantomJs for instalado.
Ideia para fazer funcionar no Browser
Apesar de poder fazer o robô usando javascript como linguagem, esse robô não vai rodar a partir de uma página web, mas sim, a partir de um programa executável desktop.
Entretanto, seria possível, criar um web-service que chame o PhantomJs, fazendo isso ser possível através do navegador, que chamaria o web-service.
Você pode fazer o web service usando o C# por exemplo, que tem suporte ao PhantonJs através de uma biblioteca.
Answer: O navegador NÃO irá permitir isso, devido à caixa de areia - é uma restrição de segurança de qualquer browser.
Usar o http://phantomjs.org para poder manipular páginas nativas é uma alternativa.
Answer: Eu recentemente tive a oportunidade de trabalhar com esta biblioteca/solução: http://www.gebish.org/ que recorre a drivers do Selenium, suportando automatização pelo Firefox, Chrome, Internet Explorer, Opera, htmlUnit, PhantomJS e outros.
A linguagem utilizada para a automatização dos testes é Groovy (baseada em java), recorrendo a uma biblioteca de navegação que suporta selectores semelhantes aos conhecidos selectores JQuery.
Recomendo começar por aqui como exemplo: https://github.com/geb/geb-example-gradle

Criando um bot em JS


Search engine friend search string using htaccess

Question: Is it possible to alter my search result url say from this:
/search.php?query=Currys

To something more search engine friendly and also add to it so that it becomes something like this:
/search-results-for-Currys-Voucher-Codes

By using htaccess?
Thanks.
Comment: Oh look, a question on the basic use of mod_rewrite – that's totally new and has never been asked before …
Answer: You can probably do something like this by placing this code in your DOCUMENT_ROOT/.htaccess file:
RewriteEngine On

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+search\.php\?query=([^\s&]+) [NC]
RewriteRule ^ /search-results-for-%1? [R=301,L,NE]

# internal forward from pretty URL to actual one
RewriteRule ^search-results-for-(.+?)/?$ /search.php?query=$1 [L,QSA,NC,NE]

Then inside search.php get your parameters as $_GET['query']
Comment: Wasn't sure where to place the slug part in the search file so I removed everything between the ) and /$ and also &slug=$2 just to see if it would do anything but nothing seemed to happen.
Comment: Ok edited to remove slug part. Can you try it now.
Comment: Stil not getting anything.  Test site is here: http://testingstuff.tk/search.php?query=currys
Comment: Oh looks like you want rewrite other way also. Check edited code now.
Comment: Brilliant stuff - working!  Thanks.  Will help a lot.
Comment: There is one more thing.  The spaces in the merchant names are being replaced by this in the url %2520 .  Can htaccess be used to make the url appear with dashes instead?
Comment: Just edited with `NE` flag. Now spaces (`%20`) won't be encoded. For replacing all spaces with hyphen you'll need further rules and that will cause your query to fail since you will need to replace all hyphens with spaces again.
Comment: That looks perfect to me as it is.  Thanks again.
Comment: Great to know. Can you please now upvote and mark the answer as accepted.
Comment: I have spotted a problem.  This works /search.php?query=Pro-10 and it finds the Pro-10 company but with the htaccess code in place /search-results-for-Pro-10 doesn't work as it cuts off at the dash and ends up as /search-results-for-Pro .  This works for all search terms with a dash in it.  Any fix for this plz?
Comment: Yup that did it.  Cheers.  Can update this now as accepted - if I can figure out how ;) .


Unique up to unique isomorphism

Question: If an object $X$ has a non-trivial automorphism $g$, for any isomorphism $f$ with an object $Y$ there is another isomorphism $f \circ g$ between $X$ and $Y$, so there is not a unique isomorphism between $X$ and $Y$.

Does the second "unique" in "unique up
  to unique isomorphism" mean nothing
  else than that the object in question
  has no automorphism than the identity?

If the answer is positive: Why is this second - and somehow independent - fact so strongly interwoven (terminologically) with the fact of being unique up to isomorphism?
Comment: I would say that the locution "unique up to unique isomorphism" is slightly jargony.  Of course it does not mean unique in the literal sense: it means there is a unique isomorphism **such that X holds**, where $X$ is generally some universal mapping property.  When I learned this material, the turn of phrase I heard was "unique up to *canonical* isomorphism", which I think is more accurate.
Comment: It is vary rare that the expression is used in such a context: it is usually used in a context such as the statement of the uniqueness up to unique isomprphism of a product in a category, in which "up to isomorphism" involves more structure than the object itself.
Comment: I'm not really sure how this is [set-theory], could you explain?
Comment: In particular, it is true, in the usual sense of the word, that a product of two objects in a category is, when it exists, unique up to unique isomorphism, but this statement makes absolutely no assertion about the existence of automorphisms of the product object. Indeed, the product of two objects usually has lots of automorphisms!
Answer: When people say, for example, that the product $X \times Y$ of two objects $X, Y$ is unique up to unique isomorphism, that doesn't mean that $X \times Y$, as an object of the category, has no non-trivial automorphisms; it's easy to find examples where this is blatantly false. It means that if you have two objects $A, B$ which are both products of $X$ and $Y$ in the sense that they come with distinguished projection maps to $X$ and $Y$ satisfying the universal property, then there is a unique isomorphism $A \to B$ compatible with the projection maps. The projection maps are part of the data that defines a product, and in particular it is possible for the same object to be a product of $A$ and $B$ in two different ways (in the sense that the projection maps are different): those different ways are then related by an automorphism of the object.
Another way to say this is to say that a product is a terminal object in a certain category of cones, and as an object of this category, it follows that the product has no non-trivial automorphisms because, for any terminal object $1$, there is a unique map $1 \to 1$, which must be the identity.

Unique up to unique isomorphism


Is it possible to Overblow in Hohner Silverstar Harmonica?

Question: I am trying to overblow in silverstar. Almost worked in 6blow. Is is possiblie in 4blow overblow in Silverstar harmonica?
Answer: It's quite possible that a harp like that may well have 1 or 2 overblows out of the box, if you're not unlucky (probably on hole 6 or 5).  However, to get them to come out cleanly (or sometimes to come out at all), you'll need to do some reed gapping and other setup tweaks, which aren't tasks to be taken lightly, especially by someone who isn't already and experienced overblow player.
Most experienced players would not recommend anyone who cannot already reliably produce overblows to go playing around with harp setups because 1. you can ruin your harp and 2. you don't really know what you're looking for so you won't be able to identify success.
(My qualifier to this would be, if you have a "junk" harmonica that you don't mind risking breaking, there's no harm in having some fun.  You very likely won't improve the harmonica but you might well enjoy yourself, and learn something.)
My advice to you regarding overblows would be this: before you can know if your harp is overblowing, you need to be able to overblow.  This may seem like a catch-22, but to really get the feeling for what an overblow feels like, you can "force" even a harmonica that won't usually overblow to do it.  And make it a whole lot easier even for a harp that overblows well.
When you overblow, the blow reed "chokes" and the draw reed sounds.  To get the harmonica to do this more easily, you can cover the blow reed yourself.  There are harmonicas designed specifically with this in mind (for example the suzuki overdrive with holes for the individual chambers), but that's a lot of money for essentially a teaching tool.  Instead, take the cover plates off so the reeds are exposed.  Then you can just use your fingers to cover reed slots.  Be gentle (with your hands and your airflow) and you won't do any damage.
You should notice a few things on holes 1-6

covering the draw reed whilst blowing, or covering the blow reed while drawing gives you a warmer, fuller sound.  This is what a valved harp feels like!  You'll also be able to bend the blow reeds slighty, with 1-reed valved bends.  It's not the same as a full bend, but it's a lot of fun!
if you cover the blow reed and try to blow, the usual note won't sound.  But, with some practice, you will be able to overblow, and a lot more easily than usually at that!  Hold the note you want in your head, and try and sort of "bend" up to it.  I recommend starting on hole 6 (or hole 5 sometimes). you'll be shooting for that minor third up.  There are a lot of tutorials out there and opinions about how to achieve that first overblow, and how it "feels".  I'll leave that up to you to find what works, but the key is, you'll be able to reach it a lot easier by artificially choking the blow reed.

The advantage real advantage of this is that you can ONLY overblow while the blow is choked, so you can move your mouth around until you manage to make a sound, and that sound will be an overblow.  Then you can remember what that feels like and try and make it without the blow reed covered.
Once you can successfully overblow, you'll be able to tell me which holes on your stock silverstar can overblow!  And maybe even look into setting it up so they overblow flawlessly.


calculate $\lim_{x\rightarrow\frac{\pi}{4}}\frac{\cos2x}{\cos x-\sin x}$

Question: $$\lim_{x\rightarrow\frac{\pi}{4}}\frac{\cos(2x)}{\cos(x)-\sin(x)}=\lim_{x\rightarrow\frac{\pi}{4}}\frac{2\cos^{2}(x)-1}{\cos(x)-\sqrt{1-\cos^{2}(x)}}$$
$$t=\cos(x)$$
$$\lim_{x\rightarrow\frac{\pi}{4}}\frac{2t^{2}-1}{t-\sqrt{1-t^{2}}}=\lim_{x\rightarrow\frac{\pi}{4}}\frac{(2t^{2}-1)(t+\sqrt{t^{2}-1})}{2t^{2}-1}$$
$$\lim_{x\rightarrow\frac{\pi}{4}}(2t^{2}-1)(t-\sqrt{t^{2}-1})=3(\sqrt{2}-1)$$
Please help me to find an error. Correct answer is $\sqrt{2}$. Thanks
Comment: If $t=\cos x$, then you want the limit as $t\rightarrow \sqrt2/2$.
Comment: Thank You all for quick answers!. I didn't know that many ways to solve this easy task.
Answer: $$ \lim_{x\to\frac{\pi}{4}}\frac{\cos2x}{\cos x-\sin x}=
  \lim_{x\to\frac{\pi}{4}}\frac{\cos^2 x-\sin^2 x}{\cos x-\sin x}=$$
 $$ \lim_{x\rightarrow\frac{\pi}{4}}\frac{(\cos x- \sin x)(\cos x+\sin x)}{\cos x-\sin x}=$$
$$= \lim_{x\rightarrow\frac{\pi}{4}}{\cos x+\sin x}=\frac{1}{\sqrt{2}}+\frac{1}{\sqrt{2}}=\sqrt2$$
Answer: writing $\cos 2x = \cos^2 x - \sin^2x $ and expanding $a^2-b^2$ and cancelling $\cos x - \sin x$ you get $\cos x + \sin x$. Putting value $x \to \frac{\pi}{4}$ we get $ \frac{1}{\sqrt 2} + \frac{1}{\sqrt 2} = \sqrt 2$.
EDIT::
Looks like you've been writing $\sqrt{t^2-1}$ for $\sqrt{1 -t^2}$ and also there is substitution so you must be putting $ t \to \frac{1}{\sqrt 2}$
$\underset{x\rightarrow\frac{\Pi}{4}}{\lim}\frac{2t^{2}-1}{t-\sqrt{1-t^{2}}}=\underset{x\rightarrow\frac{\Pi}{4}}{\lim}\frac{(2t^{2}-1)(t+\sqrt{t^{2}-1})}{2t^{2}-1}$
After this you should get
$\lim_{t \to \frac{1}{\sqrt 2}} t + \sqrt{1-t^2}$
this is essentially same as multiplying by $\cos x + \sin x $ and cancelling the $\cos 2x$ up there, so substitution quite unnecessary though.
Comment: Ok, thanks. But where is an error in my solution?
Comment: I believe he's asking where he made a mistake and not looking for another way to solve the problem.
Comment: Since the asker did effectively reduce to $\cos x + \sin x$ I think it's appropriate to point out a much simpler way of doing the same thing.
Answer: The third line is in error: you forgot to cancel the factor of $2 t^2 - 1$ and you switched the sign of $\sqrt{1-t^2}$.  If you correct, you'll see that
$$ \lim_{x \rightarrow \frac{\pi}{4}} \frac{\cos{2 x}}{\cos{x} - \sin{x}} = \lim_{t \rightarrow \frac{1}{\sqrt{2}}} \left [ t + \sqrt{1-t^2} \right ] = \sqrt{2} $$
Answer: A few observations about your "move" from your second to third line, where you obtain
$$\lim_{x\rightarrow\large\frac{\pi}{4}}\frac{(2t^{2}-1)(t+\sqrt{t^{2}-1})}{2t^{2}-1}$$

you forgot to cancel the common factor of $(2 t^2 - 1)$;
By writing $\;\sqrt{t^2-1}\;$ instead of $\;\sqrt{1-t^2}\;$ in the numerator, the sign needs to switch.
After substituting $\;t = \cos x\;$ in the limit, you need to change the point for which you are taking the limit. That is: $$x \to \frac{\pi}{4}\;\; \iff \;\;t \to \cos\left({\frac{\pi}{4}}\right) = \dfrac{1}{\sqrt{2}}.$$

Correcting for these errors, you'll find that
$$ \lim_{x \rightarrow \large\frac{\pi}{4}} \frac{\cos{2 x}}{\cos{x} - \sin{x}} = \lim_{t \rightarrow \large \frac{1}{\sqrt{2}}} \left (t + \sqrt{1-t^2} \right ) = \sqrt{2} $$
Comment: It's not only wise to change the limit point, but also required. Not changing it is just wrong...
Comment: Your very welcome, Steve!
Answer: Plugging in $\frac{\pi}{4}$ for $x$, we see that it is of the form $0/0$, thus we can apply l'Hopital's rule. This gives us:
\begin{align}
\lim_{x\to\frac{\pi}{4}}\frac{\cos(2x)}{\cos(x)-\sin(x)}&=\lim_{x\to\pi/4}\frac{-2\sin(2x)}{-\sin(x)-\cos(x)}\\&=\lim_{x\to\pi/4}\frac{2\sin(2x)}{\cos(x)+\sin(x)}\\&=\frac{2}{\sqrt{2}}\\&=\sqrt{2}.
\end{align}
Comment: Why was this one downvoted while other similar solutions upvoted?
Comment: I down voted all answers which didn't specify where his mistake was (because that's what he asked).
Furthermore, this one in particular uses l'Hopital which is too strong to solve this. I believe that's NOT what's intended with this exercise. But that's just me.
Comment: +1 from me. Also it's nice to see another way how to solve this


In a given set of numbers can there be more than half above mean, median or mode?

Question: Suppose I have a set of numbers, for example - exam scores of 20 students.
Can there be more than half of students scoring above the mean ? similarly, can more than half the class score above the median and mode ?
Comment: Yes and no. You can't  have more than half above the median; at most in the presence of ties more than half can be equal to or above the median. (Trivial example: all students get the same mark.) Otherwise imagine 9 at 0, 6 at 50 and 5 at 100. Then the mode is 0 and 11 are above. The mean is 40 and 11 are above. Many such examples.
Comment: @NickCox You should post that as an answer rather than a comment.
Comment: thanks @NickCox, can you share some more insights into this ? any study material ? similarly, what will be the case with mode and mean ?
Comment: Any good introductory statistics text should discuss the possibilities. @A.G. has now provided a very good analysis.
Comment: Note that "above" can be replaced by "below" simply by negating all values.  Thus, if there is *any* statistic whatsoever where the answer is always "no," then *by definition* that statistic is a median.
Answer: It is not possible for over half of the students to score above the median:

If there is an even number of students $n$, the median is the mean of the 2 scores in the "middle" of the sorted set of scores, meaning that at most half ($\frac{n}{2}$) of the students will score above or below the median.
If there is an odd number of students $n$, the median is the number in the "middle" of the sorted set of scores. In this case, at most less than half ($\frac{n-1}{2}$, to be precise) students may score above the median.

Notice that I said "at most" above: when multiple students score at the median, the number of students scoring over the median must be even less than the $\frac{n}{2}$ or $\frac{n-1}{2}$ figures I gave above.
But is is possible for more than half the students to score above the mean: this may happen when the distribution is negatively-skewed, like in image (a) below, and the mean is below the median.
And it is possible for more than half the students to score above the mode: this may happen when the distribution is positively-skewed, like in image (c) below, and the mode is below the median.

(For the avoidance of doubt, the perfectly symmetrical distribution in image (b) above is actually a bit of a special case, where the mean exists (unlike the Cauchy distribution) and there is a single mode. If those conditions do not hold, we cannot state that the mean, median & mode coincide, so being perfectly symmetrical is neither necessary nor sufficient to do so. One famous example of such a symmetric distribution where those conditions do hold is the Normal/Gaussian ("bell curve") distribution.)
Comment: Good (+1). Some readers might appreciate notes that the normal is just an example of a perfectly symmetrical distribution; and that distributions being symmetrical is neither necessary nor sufficient for mode to coincide with median and mean.
Comment: @NickCox - In other words, "normal" is completely abnormal.
Comment: Edwin Jaynes suggested that we call it the central distribution, but I've never seen that quoted. There is always Gaussian....
Comment: Thanks for the feedback. I've edited it to add that info.


selenium webdriver BrokenPipeError (timeout issue)

Question: I've boiled my code down to the following:
from selenium import webdriver
from time import sleep
b = webdriver.Firefox()
sleep(10)
b.get('http://www.google.com')

This causes a BrokenPipeError on the b.get call. Is this an error with my environment? Something I'm doing wrong, or a bug?
ENV:

Fedora 27 (64bit)
Firefox Quantum 59.0.2 (64bit)
Python 3.6.5
selenium 3.13.0 (via pip)
geckodriver v0.21.0 from github

Update:
I upgraded my workstation and along with that moved to Fedora 28 with a brand new install of Firefox 61, Python 3.6.5, Selenium 3.13.0, and geckodriver 0.21.0 and I have the same problem with the provided script.
Comment: I think `geckodriver` works on FF 47+ and not below. Your FF is very old.
Comment: @demouser123 I forgot to include my firefox version. I've added it above. I using version 59.0.2
Comment: Also please update Selenium. Version `3.1.3` is very old.
Comment: it's Selenium version 3.13.0 (the latest according to https://pypi.org/project/selenium/)
Answer: You need to specify the path of the webdriver.exe file
first specify path ='path of your webdriver.exe'
path ='path of your webdriver.exe'
and then b = webdriver.Firefox(path)

Comment: Not necessarily. If you have added the webdriver's location to your system/user path, you do not need to specify it when you invoke the browser.
Comment: It's in the in the path and opens. It's just that if there is a delay in commands being sent the pipe breaks. If commands are executed as soon as possible the pipe won't break. My original code loaded several pages before asking for input, if there was any delay in a response, the pipe would break. In testing, I boiled it down to the code I included in the question
Answer: I use this method to fix this problem and I call it every time there is a risk for timeout. I hope there is a better solution, but this works for me right now.
def refresh(b):
    try:
        b.refresh()
    except BrokenPipeError:
        pass