Moving image in circle with touch move

Question: I want to move an image within a circle with my touch on move. I've been confused how to determine the coordinates circle boundaries when the finger moved.
For example I want to move this image like lock screen on android tabs.
http://cdn.alltouchtablet.com/wp-content/uploads/2012/03/samsung-galaxy-tab-7-plus-lock-screen.jpg
EDIT :
Now After learn the answer below, I managed to draw an circle image and moving this image around the screen.
And now, I want to restrict the image movement so that it only can moved in a circle, just like in the image above. Any ideas?
I hope you can help me. Thank you!
Answer: so I've actually not done anything like this but i know this tutorial : and the guy does something similar to what you want,
this video is one right in the middle of an entire playlist of tutorial videos if you dont get what he's doing check the previous few... as for moving the image in a circle i'm sure there'll be some way to set boundries :)
http://www.youtube.com/watch?v=9d4Wua-cxZs&list=PLB03EA9545DD188C3&index=32&feature=plpp_video
hope it was helpful!
Comment: Thank you for your fast reply and I appreciate it! One problem : moving image solved at least. Now I confused how to set the boundaries :).
Comment: hmm, let me try out the program and check it out.. do click on the gray tick mark next to my answer if you found it useful :)
Comment: when you set the canvas set it to a circle go through all the tutorials from this one onwards : http://www.youtube.com/watch?v=vOY2AxbnRyc&feature=BFa&list=PLB03EA9545DD188C3  and in the tutorial where he draws a rectangle on the canvas (tutorial 26) draw a circle using `canvas.drawCircle(canvas.getWidth()/2, canvas.getHeight()/2, canvas.getWidth()/5, blue)` where `blue` is the Paint variable that is set up... again, do click on the tick mark to the left of my answer if you have found it useful

Moving image in circle with touch move


Can VMWARE Workstation read beyond 4GB memory in 32bit Windows host?

Question: Windows 32bit can only make use of ~3.2GB when 4GB is installed.
Some software such as Superspeed's Ramdisk can use the unused memory, that is, I can use the remaining wasted 768MB for ramdisk purpose.
Does VMWARE workstation have this feature? I would like to use the wasted memory for guest OSes in VMWARE, example I have 8GB installed, HOST Windows only sees 3.2GB, remaining 4.7GB used for VMs.
Reason I'm asking this is that I don't want switch to 64bit windows yet.
Anyone can help?
Answer: I would say no since the OS you are running it on cant adress more then 3.x gb memory in a 32bit enviroment and the system need to be able to adress it in order to let applications use it.
Havnt tried it tho.
Answer: The hardware feature you need to address anything over 4GB in any way from a system running 32bit Mode is called PAE. If this is not emulated by the virtual environment, then: No.
Answer: On 32 bit win machine, the only one thing you may use the "upper" memory for - ram drive.
Answer: http://www.vmware.com/files/pdf/server2_beta2_faq.pdf
Page 2, under "64-bit guest operating system support..."


What regression/estimation is not a MLE?

Question: I just rigorously learned that OLS is a special case of MLE. It surprises me because the popular and "reliable" sources such as researchgate and this do not mention this most important connection between MLE and OLS!
I am not sure if there are any simple regression or estimation method that does not belong to MLE.
Comment: From what I've seen Q&A researchgate is not particularly reliable. I've never heard of "differencebetween". Beware what you read on the internet (or for that matter, in some textbooks, though the frequency of good sources is better then)
Comment: ... And yes, I fully recognize my statement included this site. So it should -- you should definitely be a skeptical consumer of information and advice in every instance. But at least StackExchange makes it easier to find and fix errors over time, for example by encouraging ongoing curation of answers, and consolidating questions into canonical threads. It doesn't eliminate problems, but it does improve the average quality noticeably.
Answer: Least squares is indeed maximum likelihood if the errors are iid normal, but if they aren't iid normal, least squares is not maximum likelihood. For example if my errors were logistic, least squares wouldn't be a terrible idea but it wouldn't be maximum likelihood.
Lots of estimators are not maximum likelihood estimators; while maximum likelihood estimators typically have a number of useful and attractive properties they're not the only game in town (and indeed not even always a great idea).
A few examples of other estimation methods would include

method of moments (this involves equating enough sample and population moments to solve for parameter estimates; sometimes this turns out to be maximum likelihood but usually it doesn't)
For example, equating first and second moments to estimate the parameters of a gamma distribution or a uniform distribution; not maximum likelihood in either case.

method of quantiles (equating sufficient sample and population quantiles to solve for parameter estimates; occasionally this is maximum likelihood but usually it isn't),

minimizing some other measure of lack of fit than $-\log\mathcal{L}$ (e.g. minimum chi-square, minimum K-S distance).

With fitting linear regression type models, you could for example look at robust regression (some of which do correspond to ML methods for some particular error distribution but many of which do not).
In the case of simple linear regression, I show an example of two methods of fitting lines that are not maximum likelihood here - there estimating slope by setting to 0 some other measure of correlation (i.e. other than the usual Pearson) between residuals and the predictor.
Another example would be the Tukey's resistant line/Tukey's three group line (e.g. see <code>?line</code> in R). There are many other possibilities, though many of them don't generalize readily to the multiple regression situation.
Comment: *If* you have a distributional model (e.g. for the conditional distribution in a regression-like situation) and the data, you can calculate a likelihood function, without reference to any specific estimates. You can then use that function calculate a likelihood *value* for the fitted parameter values you obtained (however you happened to obtain them), just as you can with any specific set of values for the parameters -- but to what end?
Comment: Thank you very much for this detailed answer! I wonder if all regression method has some sort of likelihood functions, loosely speaking, even if it is not a max likelihood procedure.
Comment: I really don't know what you're asking there, sorry. Parameters in otherwise-fully-specified distributions have likelihood functions.
Comment: "For example if my errors were logistic, least squares wouldn't be a terrible idea but it wouldn't be maximum likelihood."  — Maybe I'm misunderstanding what you mean by logistic error, but if it's what I think you mean, then logistic error is maximum likelihood Bernoulli estimation.  Most of the GLMs can be viewed as MLE for some exponential family distribution.
Comment: Sorry for being unclear. I would just like to confirm that, even if a regression method (e.g. OLS) is not MLE, we can still calculate the likelihood function from the model we obtained. Is it true? Thank you for helping and I hope this is clearer
Comment: I believe you may hve misunderstood the situation being described in that part. In the situation where the error distribution is a [logistic distribution](https://en.wikipedia.org/wiki/Logistic_distribution) but the estimation is OLS (as per the estimator mentioned in the question), you don't have MLE but it (OLS) is nonetheless a perfectly reasonable estimator -- just suboptimal, since it's sensitive to the more extreme points that will crop up more often than it's best at dealing with.
Answer: Bayesian approaches do not involve maximizing a likelihood function, but rather integrating over a posterior distribution. Note that the underlying model may be exactly identical (i.e., linear regression, generalized linear regression), but we also need to provide a prior distribution which captures our uncertainty in the parameters before seeing the data. The posterior distribution is simply the normalized distribution of the prior times the likelihood.
I believe that most statisticians these days generally agree that a Bayesian approach is generally superior to an MLE approach for parameter estimation. However, when one has a lot of data, it may not be so much better that it's both the extra computational costs (integrating is harder than optimizing!) and extra effort of coming up with a prior distribution. In fact, one can show that asymptotically, the MLE + normal approximation approaches the posterior distribution under certain conditions.
Answer: All MLE is minimax but not all minimax is MLE. Some examples of minimax estimators that do not maximize a likelihood are ROC regression, conditional logistic regression, Cox proportional hazards models, nearest neighbor, quasilikelihood, the list goes on and on. Hodge's "superefficient" estimator  beats maximum likelihood as a more efficient UMVUE (unbiased minimum variance) estimator of the mean in a normal sample but it is NOT minimax
Comment: I'm not sure I'd say that Cox PH models are not an MLE; the Cox PH solution is the optimal parameter values for the partial likelihood function.
Comment: @CliffAB Stigler's "Epic History of Maximum Likelihood" gives an excellent historical account of the dialogue on this matter. The truth is when we exclude ancillary parameters from estimation (like dispersion in QuasiMLE or for Cox the event times conditional on risk-set order statistics), we cannot be guaranteed of the same optimality or regularity criteria that MLEs have. Asymptotic efficiency of the MLE is based on a Taylor expansion using the information matrix. When we knock out a few dimensions of ancillary parameters weird things happen.
Comment: Oh interesting, I didn't realize there have been huge discussions about whether to consider the Cox PH model an MLE!
Answer: $$
Y_i = \alpha + \beta x_i + \varepsilon_i
$$

$\alpha,\beta$ are non-random and not observable.
$\varepsilon_i$ are random and not observable.
$x_i$ are non-random and are observable.
$Y_i$ are consequently random, and are observable.

Suppose you have the Gauss–Markov assumptions:

The errors $\varepsilon_i$ have expected value zero.
The errors all have the same (finite) variance but not necessarily the same distribution (in particular, they are not assumed to be normal).
The errors are uncorrelated but not necessarily independent.

One cannot do MLE because there's no parametrized family of distributions. But one can still do ordinary least squares.
And among all linear combinations of the $y$-values with non-random observable coefficients, that are unbaised estimators of $\alpha$ and $\beta,$ the least-squares estimators have the smallest variance.
Answer: An answer to the question "What regression/estimation is not a MLE?", a simple and robust alternative to Least-Squares (LS) is reportedly Least-Absolute Deviation (LAD).
To quote a source:
"The least absolute deviations method (LAD) is one of the principal alternatives to the least-squares method when one seeks to estimate regression parameters. The goal of the LAD regression is to provide a robust estimator."
Interestingly, per a reference, to quote "The least absolute deviations estimate also arises as the maximum likelihood estimate if the errors have a Laplace distribution." Here is a link that discusses some interesting applications of the Laplace (like as a Bayesian prior, and for extreme events).
Historically, the LAD procedure was introduced 50 years before the least-squares method (1757) by Roger Joseph Boscovich, who employed it to reconcile incoherent measures relating to the shape of the earth.
An illustrative difference is in the very simple case of Y = Constant, where the LS returns the sample mean, while the LAD selects the sample median! So in contexts with one or two extreme values, which for whatever reason (like heteroscedasticity), that may arise, LS could display a major shift in the true slope estimate, especially when there is one very low and/or a high observation, as a noted weakness. Wikipedia on robust regression makes a supporting comment:
"In particular, least squares estimates for regression models are highly sensitive to outliers."
With respect to applications, this can be particularly important, for example, in chemistry-based data analysis to predict a so-called reaction's Rate Law (which is based on the slope estimate).
Comment: LAD is the MLE for conditional responses with Laplace distributions.


How to create a macro for creating a symbol in Julia

Question: I am trying to create a string literal macro in Julia to create a symbol, so that s"x" is the same as :x. It does not work:
julia> macro s_str(p)
           symbol(p)
       end

julia> s'x'
ERROR: s not defined

julia> s"x"
ERROR: x not defined

Answer: The reason is macro hygiene. You can do either
macro s_str(p)
  quote
    symbol($p)
  end
end

which is easy to read, or do the more complicated but equivalent.
macro s_str(p)
  esc(:(symbol($p)))
end

Comment: Ah, so the `esc` is actually not needed at all.
Comment: Isn't the second and more complicated example equivalent to `quot`?
Answer: I would recommend
macro s_str(p)
    Meta.quot(Symbol(p))
end

which avoids a runtime call to Symbol. See below for more information on quoting symbols in macros.

There are three ways to quote something using a Julia function:
julia> QuoteNode(:x)
:(:x)

julia> Meta.quot(:x)
:(:x)

julia> Expr(:quote, :x)
:(:x)

What does "quoting" mean, and what is it good for? Quoting allows us to protect expressions from being interpreted as special forms by Julia. A common use case is when we generate expressions that should contain things that evaluate to symbols. (For example, this macro needs to return a expression that evaluates to a symbol.) It doesn't work simply to return the symbol:
julia> macro mysym(); :x; end
@mysym (macro with 1 method)

julia> @mysym
ERROR: UndefVarError: x not defined

julia> macroexpand(:(@mysym))
:x

What's going on here? @mysym expands to :x, which as an expression becomes interpreted as the variable x. But nothing has been assigned to x yet, so we get an x not defined error.
To get around this, we must quote the result of our macro:
julia> macro mysym2(); Meta.quot(:x); end
@mysym2 (macro with 1 method)

julia> @mysym2
:x

julia> macroexpand(:(@mysym2))
:(:x)

Here, we have used the Meta.quot function to turn our symbol into a quoted symbol, which is the result we want.
What is the difference between Meta.quot and QuoteNode, and which should I use? In almost all cases, the difference does not really matter. It is perhaps a little safer sometimes to use QuoteNode instead of Meta.quot. Exploring the difference is informative into how Julia expressions and macros work, however.
The difference between Meta.quot and QuoteNode, explained
Here's a rule of thumb:

If you need or want to support interpolation, use Meta.quot;
If you can't or don't want to allow interpolation, use QuoteNode.

In short, the difference is that Meta.quot allows interpolation within the quoted thing, while QuoteNode protects its argument from any interpolation. To understand interpolation, it is important to mention the $ expression. There is a kind of expression in Julia called a $ expression. These expressions allow for escaping. For instance, consider the following expression:
julia> ex = :( x = 1; :($x + $x) )
quote
    x = 1
    $(Expr(:quote, :($(Expr(:$, :x)) + $(Expr(:$, :x)))))
end

When evaluated, this expression will evaluate 1 and assign it to x, then construct an expression of the form _ + _ where the _ will be replaced by the value of x. Thus, the result of this should be the expression 1 + 1 (which is not yet evaluated, and so distinct from the value 2). Indeed, this is the case:
julia> eval(ex)
:(1 + 1)

Let's say now that we're writing a macro to build these kinds of expressions. Our macro will take an argument, which will replace the 1 in the ex above. This argument can be any expression, of course. Here is something that is not quite what we want:
julia> macro makeex(arg)
           quote
               :( x = $(esc($arg)); :($x + $x) )
           end
       end
@makeex (macro with 1 method)

julia> @makeex 1
quote
    x = $(Expr(:escape, 1))
    $(Expr(:quote, :($(Expr(:$, :x)) + $(Expr(:$, :x)))))
end

julia> @makeex 1 + 1
quote
    x = $(Expr(:escape, 2))
    $(Expr(:quote, :($(Expr(:$, :x)) + $(Expr(:$, :x)))))
end

The second case is incorrect, because we ought to keep 1 + 1 unevaluated. We fix that by quoting the argument with Meta.quot:
julia> macro makeex2(arg)
           quote
               :( x = $$(Meta.quot(arg)); :($x + $x) )
           end
       end
@makeex2 (macro with 1 method)

julia> @makeex2 1 + 1
quote
    x = 1 + 1
    $(Expr(:quote, :($(Expr(:$, :x)) + $(Expr(:$, :x)))))
end

Macro hygiene does not apply to the contents of a quote, so escaping is not necessary in this case (and in fact not legal) in this case.
As mentioned earlier, Meta.quot allows interpolation. So let's try that out:
julia> @makeex2 1 + $(sin(1))
quote
    x = 1 + 0.8414709848078965
    $(Expr(:quote, :($(Expr(:$, :x)) + $(Expr(:$, :x)))))
end

julia> let q = 0.5
           @makeex2 1 + $q
       end
quote
    x = 1 + 0.5
    $(Expr(:quote, :($(Expr(:$, :x)) + $(Expr(:$, :x)))))
end

From the first example, we see that interpolation allows us to inline the sin(1), instead of having the expression be a literal sin(1). The second example shows that this interpolation is done in the macro invocation scope, not the macro's own scope. That's because our macro hasn't actually evaluated any code; all it's doing is generating code. The evaluation of the code (which makes its way into the expression) is done when the expression the macro generates is actually run.
What if we had used QuoteNode instead? As you may guess, since QuoteNode prevents interpolation from happening at all, this means it won't work.
julia> macro makeex3(arg)
           quote
               :( x = $$(QuoteNode(arg)); :($x + $x) )
           end
       end
@makeex3 (macro with 1 method)

julia> @makeex3 1 + $(sin(1))
quote
    x = 1 + $(Expr(:$, :(sin(1))))
    $(Expr(:quote, :($(Expr(:$, :x)) + $(Expr(:$, :x)))))
end

julia> let q = 0.5
           @makeex3 1 + $q
       end
quote
    x = 1 + $(Expr(:$, :q))
    $(Expr(:quote, :($(Expr(:$, :x)) + $(Expr(:$, :x)))))
end

julia> eval(@makeex3 $(sin(1)))
ERROR: unsupported or misplaced expression $
 in eval(::Module, ::Any) at ./boot.jl:234
 in eval(::Any) at ./boot.jl:233

In this example, we might agree that Meta.quot gives greater flexibility, as it allows interpolation. So why might we ever consider using QuoteNode? In some cases, we may not actually desire interpolation, and actually want the literal $ expression. When would that be desirable? Let's consider a generalization of @makeex where we can pass additional arguments determining what comes to the left and right of the + sign:
julia> macro makeex4(expr, left, right)
           quote
               quote
                   $$(Meta.quot(expr))
                   :($$$(Meta.quot(left)) + $$$(Meta.quot(right)))
               end
           end
       end
@makeex4 (macro with 1 method)

julia> @makeex4 x=1 x x
quote  # REPL[110], line 4:
    x = 1 # REPL[110], line 5:
    $(Expr(:quote, :($(Expr(:$, :x)) + $(Expr(:$, :x)))))
end

julia> eval(ans)
:(1 + 1)

A limitation of our implementation of @makeex4 is that we can't use expressions as either the left and right sides of the expression directly, because they get interpolated. In other words, the expressions may get evaluated for interpolation, but we might want them preserved. (Since there are many levels of quoting and evaluation here, let us clarify: our macro generates code that constructs an expression that when evaluated produces another expression. Phew!)
julia> @makeex4 x=1 x/2 x
quote  # REPL[110], line 4:
    x = 1 # REPL[110], line 5:
    $(Expr(:quote, :($(Expr(:$, :(x / 2))) + $(Expr(:$, :x)))))
end

julia> eval(ans)
:(0.5 + 1)

We ought to allow the user to specify when interpolation is to happen, and when it shouldn't. Theoretically, that's an easy fix: we can just remove one of the $ signs in our application, and let the user contribute their own. What this means is that we interpolate a quoted version of the expression entered by the user (which we've already quoted and interpolated once). This leads to the following code, which can be a little confusing at first, due to the multiple nested levels of quoting and unquoting. Try to read and understand what each escape is for.
julia> macro makeex5(expr, left, right)
           quote
               quote
                   $$(Meta.quot(expr))
                   :($$(Meta.quot($(Meta.quot(left)))) + $$(Meta.quot($(Meta.quot(right)))))
               end
           end
       end
@makeex5 (macro with 1 method)

julia> @makeex5 x=1 1/2 1/4
quote  # REPL[121], line 4:
    x = 1 # REPL[121], line 5:
    $(Expr(:quote, :($(Expr(:$, :($(Expr(:quote, :(1 / 2)))))) + $(Expr(:$, :($(Expr(:quote, :(1 / 4)))))))))
end

julia> eval(ans)
:(1 / 2 + 1 / 4)

julia> @makeex5 y=1 $y $y
ERROR: UndefVarError: y not defined

Things started well, but something has gone wrong. The macro's generated code is trying to interpolate the copy of y in the macro invocation scope; but there is no copy of y in the macro invocation scope. Our error is allowing interpolation with the second and third arguments in the macro. To fix this error, we must use QuoteNode.
julia> macro makeex6(expr, left, right)
           quote
               quote
                   $$(Meta.quot(expr))
                   :($$(Meta.quot($(QuoteNode(left)))) + $$(Meta.quot($(QuoteNode(right)))))
               end
           end
       end
@makeex6 (macro with 1 method)

julia> @makeex6 y=1 1/2 1/4
quote  # REPL[129], line 4:
    y = 1 # REPL[129], line 5:
    $(Expr(:quote, :($(Expr(:$, :($(Expr(:quote, :(1 / 2)))))) + $(Expr(:$, :($(Expr(:quote, :(1 / 4)))))))))
end

julia> eval(ans)
:(1 / 2 + 1 / 4)

julia> @makeex6 y=1 $y $y
quote  # REPL[129], line 4:
    y = 1 # REPL[129], line 5:
    $(Expr(:quote, :($(Expr(:$, :($(Expr(:quote, :($(Expr(:$, :y)))))))) + $(Expr(:$, :($(Expr(:quote, :($(Expr(:$, :y)))))))))))
end

julia> eval(ans)
:(1 + 1)

julia> @makeex6 y=1 1+$y $y
quote  # REPL[129], line 4:
    y = 1 # REPL[129], line 5:
    $(Expr(:quote, :($(Expr(:$, :($(Expr(:quote, :(1 + $(Expr(:$, :y)))))))) + $(Expr(:$, :($(Expr(:quote, :($(Expr(:$, :y)))))))))))
end

julia> @makeex6 y=1 $y/2 $y
quote  # REPL[129], line 4:
    y = 1 # REPL[129], line 5:
    $(Expr(:quote, :($(Expr(:$, :($(Expr(:quote, :($(Expr(:$, :y)) / 2)))))) + $(Expr(:$, :($(Expr(:quote, :($(Expr(:$, :y)))))))))))
end

julia> eval(ans)
:(1 / 2 + 1)

By using QuoteNode, we have protected our arguments from interpolation. Since QuoteNode only has the effect of additional protections, it is never harmful to use QuoteNode, unless you desire interpolation. However, understanding the difference makes it possible to understand where and why Meta.quot could be a better choice.
This long exercise is with an example that is plainly too complex to show up in any reasonable application. Therefore, we have justified the following rule of thumb, mentioned earlier:

If you need or want to support interpolation, use Meta.quot;
If you can't or don't want to allow interpolation, use QuoteNode.

What about Expr(:quote)?
Expr(:quote, x) is equivalent to Meta.quot(x). However, the latter is more idiomatic and is preferred. For code that heavily uses metaprogramming, a using Base.Meta line is often used, which allows Meta.quot to be referred to as simply quot.
Answer: First, be careful to use " and not ' for strings in Julia. ' represents characters, but also transpose, which, with implicit multiplication, means that s'x' is translated as transpose(s)*transpose(x). s"x" is correct and is actually calling the s_str macro.
The problem is that due to macro hygiene, the quoted symbol is evaluated when the macro is evaluated. esc will create a specially quoted expression that stays quoted after an evaluation:
julia> esc(:x)
:($(Expr(:escape, :x)))

Note that I still quote x here so that it remains unevaluated (otherwise you would end up with whatever x is instead of :x in the final expression.
Here, you need to escape the full symbol(p). You need to use parentheses with the :. Finally, use $p to evaluate p (otherwise p will just end up being escaped as a symbol).
julia> macro s_str(p)
           esc(:(symbol($p)))
       end

julia> s"x"
:x


Numerical computation series

Question: In a numerical series following data is given:
    $$u_1 = 3, v=2\text{ and }s_n=120$$
They ask to find the value of $n$.
First I used the formula:
$$u_n= u_1 + (n-1) \cdot v
   \implies u_n= 3 + (n-1) \cdot 2$$
Then I tried to put this formula inside the formula for $s_n$
$$    s_n= n \cdot {u_1 + u_n\over2}$$
When I try to work further with it and insert the data $s_n=120$
I eventually find that
$$n^2+ 7/2\cdot n -120=0$$
Then I tried to calculate
$$D =b^2-4ac$$
 and find a very weird answer $1969/4$.
Who can explain where I made a mistake?
Comment: You don't need to put a dollar sign for every single symbol in MathJax. Also, \implies is better than \Rightarrow, as it is longer.
Comment: I am still learning to write like this and also English isn't my native language so thanks for the improvements :)
Answer: You get $2$ there, not $7/2$.
$n^2 + 2n - 120 = 0$
Comment: Thanks, I was able to trace back where in wich step i made the mistake!

Numerical computation series


Python Arcsin Arccos radian and degree

Question: I am working on wind power and speed
u and vare zonal and meridional wind. (I have the values of these 2 vectors)
The wind speed is calculated by V = np.sqrt(u2*v2)
Wind direction is given by α between 0 and 360 degree
I know this relation holds - u / V = sin( abs(α)) and - v / V = cos( abs(α))
In python I am using np.arccos and np.arcsin to try to find α between 0 and 360 with the 2 equation above. For the first one, it returns the radian so I convert with np.rad2deg(...) but it gives me a value between 0 and 180 degree for the second one, I also try to convert but it returns me a valus between 0 and 90.
Anyone knows how to code it? I am lost :(
Answer: The underlying problem is mathematics: cos(-x) == cos(x), so the function acos has only values in the [0,pi] interval. And for equivalent reasons asin has values in [-pi/2,pi/2] one.
But trigonometric library designers know about that, and provide a special function (atan2) which uses both coordinates (and not a ratio) to give a value in the [-pi, pi] interval.
That being said, be careful when processing wind values. A 360 wind is a wind coming from the North, and 90 is a wind coming from the East. Which is not the way mathematicians count angles...
Comment: Thank you for your explanation, can you explain me what do you mean by => That being said, be careful when processing wind values. A 360 wind is a wind coming from the North, and 90 is a wind coming from the East. Which is not the way mathematicians count angles...
Comment: @chantaldem: the 0 angle (in math) is x=1, y=0. This is an horizontal vector going to the right. On a standard map, the North is the up of the map. So a 360 (or 0) wind will be a vertical vector going downside. I still remember my first dynamic meteorology courses...

Python Arcsin Arccos radian and degree


npm semantic versioning in package.json - does it work only from version 1.0.0 and up?

Question: I noticed that even though I have specified version ^0.5.5 of v-calendar library, and as of today version 0.6.3 is available, when I run npm update, the package is not updated.
When I test the version ^0.5.5 in npmsemver calculator, only version 0.5.5 is in green, meaning that npm ignores versions 0.6.x and up.
Am I correct in assuming that semantic versioning with npm works only if the package is on version 1.0.0 and up?
npm docs specify that:

If a project is going to be shared with others, it should start at 1.0.0, (though some projects on npm don't follow this rule).

but I couldn't find anything there saying that semantic versioning won't work if you release a package starting at version 0.x.x.
Answer: See https://docs.npmjs.com/misc/semver#caret-ranges-123-025-004
The caret range is keyed on the left most non-zero value. This conforms with the common practice of shifting the SemVer rules one field to the right for experimental versions (0.y.z) such that the Y field is incremented for known breaking changes and the Z field is used for new features and bug fixes.  It is an historical artifact that should be eliminated from the standard in my opinion.


how to send json data by $http.Post from Angular to webAPI POST method?

Question: I am trying to pass data as JSON object by $http.Post to webAPI method. In WebAPI method, the parameter of the method is a class object.
It works fine when I test the webAPI method by Postman.But I am not able to pass the JSON object by angular $http.post method-I get null values in the webAPI parameter(in the class object).
Can someone please advise how to fix the issue.i am new to AngularJS.Kindly help.
AngularJS Code
angular.module('Test.Employer')
    .controller('EmployerController', ['$scope','headerValue', '$http',
        function ($scope, headerValue, $http) {
            var ipEmployerDetls = {
                EmployerName: "cherokee",
                Company: "ABC"
            };

            $http({
                url: "http://localhost:212122/api/Values/PostEmployeeData",
                dataType: 'json',
                method: 'POST',
                data: JSON.stringify(ipEmployerDetls),
                headers: {
                    "Content-Type": "application/json"
                }
            }).success(function (response) {
                $scope.object = response.data;
            })
                .error(function (error) {
                    alert(error.Message);
                });
})();

WebAPI
using System.Web.Http;
using AttributeRouting.Web.Http;

namespace webAPITestProject.Controllers
{
    [Route("api/Values")]
    public class ValuesController : ApiController
    {
        retrieveEmployeeData empData = new retrieveEmployeeData();
        retrieveProductDetails prodDetls = new retrieveProductDetails();

        [Route("PostEmployeeData")]
        [HttpPost]
        public DataTable PostEmployeeData([FromBody] Employer empDetails)
        {
            DataTable dataTable = new DataTable { TableName = "MyTableName" };
            dataTable = empData.getEmployeeData(empDetails);
            return dataTable;
        }
    }
}

NOTE: I get NULL value in empDetails in webAPI method,but when I test the method in Postman,it has value.
Answer: Your routing attributes don't look right for how you've specified your $http API call.
Looks like you want the class-level attribute to be:
[RoutePrefix("api/Values")]
public class ValuesController : ApiController

Which will mean that PostEmployeeData has a route of api/Values/PostEmployeeData.
You'll also need to ensure that your properties in ipEmployerDetls directly map to your Employer class (which you haven't shown), so that model binding works correctly.
Comment: Thanks for your advice.I updated the routing attributes as mentioned.The Employer class is as below-namespace employeeDetails

{

    public class Employer

    {

        public string Company { get; set; }

        public string EmployerName { get; set; }

    }

} But still it is not working.Please let me know any advice.
Comment: The only other unusual things I notice are that you specify dataType, which shouldn't be required. You also specify the Content-Type header, but that is the default value. I would remove both of those things. I also tend to use the shortcut methods, e.g. $http.post(...) in preference to the syntax you've used but it shouldn't matter. I also find it's usually not necessary to stringify your objects.
Comment: I have implemented as per your suggestion.But still I am not able to hit the webAPI method.Anyways appreciate your advice.Thank You !!
Comment: I just noticed one thing-it looks $http.Post never works(never hit controller,it hits webAPi if I use attribute 'params' instead of 'data',but I checked we cannot use 'params' in Post) only &http.Get works.Do I need to add anything any in Config file to make &http.post work.Can anyone advise me please.
Comment: Hi The issue is fixed ! I added data:$.param(empDetails) inside post and Content-Type changed to application/x-www-form-urlencoded.It worked !! Thanks.
Comment: That's very odd that you needed to do that - it's not the usual way of making AJAX calls to Web API.  application/json is normally the way to go, and the use of $.param shouldn't be necessary. I hadn't realised you weren't hitting the method; I thought you were just getting a null value. Glad you've moved forwards with it though!
Comment: That is true.Even I am also surprised how come application/json is not working but this guy and param are working.May be all Open source languages are like this only, sometimes behave weired..thats my experience.Thanks for all your help !!


frechet differentiable implies uniformly continuous/ absolutely continuous?

Question: I knew if $f$ is Frechet differentiable at $x$ then $f$ is continuous at $x$.
My question is: Can we imply that $f$ is uniformly continuous or absolutely continuous if if $f$ is Frechet differentiable at $x$?.
Answer: We have that $f: \mathbb{R} \rightarrow \mathbb{R}$ given by $f(x)=x^2$ is not absolutely continuous (not even uniformly continuous), yet $f$ is Fréchet differentiable with its Fréchet derivative given by the map $h \mapsto 2xh$.


Related Rates (Cones)

Question: The question reads:  A water tank has the shape of a cone with height $2 m$ and radius $\frac{2}{3}$ m. If water is pumped into the tank at a rate of $3 m^3/hr$ how fast is the water level rising at the instant when the tank begins to overflow?
The question asks to use similar triangles (r is $\frac{1}{3}$ of h), and thus solves the answer to be dy/dt equals $\frac{27}{4}π$.
However, shouldn't it also be possible to solve this through the product rule. If $V = \frac{π}{3}(r^2)(y)\frac{dv}{dt}\frac{π}{3}[2ry(\frac{dr}{dt}+ r^2\frac{dy}{dt}$.
However, plugging in 3 for $dv/dt$ and $\frac{27}{4}π$ for $dy/dt$, which should mean that $dr/dt$ equals a third of that or $\frac{9}{4}π$, the numbers don't equal. Why does it not work with the product rule?
Answer: Here you are considering $r$ as variable. Which isnt the case here its constant . So $V=\frac{1}{3}πr^2h$ thus $\frac{dV}{dt}=\frac{π}{3}r^2\frac{dy}{dt}=3$ . So $dy/dt=\frac{81}{4π}$.
Answer: Yes, the last answer is correct. And i would like to say sth else about the "r" which is basically a constant, and why is it a constant?
-When the conical tank has been filled, of course when it is filled, its radius is not affected, but only the height of it is affected by water building up!. That's why when you write your time-derivative equation; you derive and when comes to dr/dt you cancel its term out. And the rest, as mentioned by the first comment, is only the dh/dt which is the rate of change of length that you are required to get.
I hope i make it much clearer.

Related Rates (Cones)


Apache 2.4 Config Troubles

Question: If I go to example.com/index.php or www.example.com the site loads correctly.  If I just go to http://example.com it redirects me to https://example.com which gives an invalid cert error, and brings me to what is supposed to be shown when going to mail.example.com
Here is my config:
Listen 80
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/c1/example/example.com
</VirtualHost>

<VirtualHost *:80>
ServerName www.example.com
DocumentRoot /var/www/c1/example/example.com
</VirtualHost>

<VirtualHost *:80>
ServerName pass.example.com
DocumentRoot /var/www/c1/example/pass.example.com
</VirtualHost>

<VirtualHost *:80>
ServerName ticket.example.com
ProxyRequests Off
    <Proxy *>
    Require all granted
    </Proxy>
ProxyPass / ajp://127.0.0.1:8009/
ProxyPassReverse / ajp://127.0.0.1:8009/
</VirtualHost>

Listen 443
<VirtualHost *:80>
ServerName mail.example.com
Redirect / https://mail.example.com
</VirtualHost>

<VirtualHost *:443>
ServerName mail.example.com
ServerAlias mail.example.com
DocumentRoot /var/www/c1/example/mail.example.com

ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

SSLEngine on

SSLCertificateFile /home/user/SSL/mail.example.com.crt
SSLCertificateKeyFile /home/user/SSL/mail.example.com.key
SSLCACertificateFile /home/user/SSL/intermediate.crt

</VirtualHost>

Comment: Do you have a `.htaccess` file in  `/var/www/c1/example/example.com`?
Comment: No .htaccess file.
Answer: Are you using Google Chrome to test? I've noticed that Chrome likes to redirect you to https on it's own. Make a cross check with another browser (IE / Firefox / etc.)
Also I don't see a https configuration for example.com or www.example.com which might also be an issue.
And if you don't want two entries for example.com you can use
<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/c1/example/example.com
</VirtualHost>

Comment: I don't want https for example.com or www.example.com  (www.example.com works)  I'm using firefox.  It works on chrome.  Lol this might be a browser cache issue.

Apache 2.4 Config Troubles


Missing required parameters for [Route]

Question: Estou tendo dificuldades para apontar a rota por causa dos dois parametros que ela possui.
Route::prefix('auction')->namespace('Auction')->name('auction.')->group(function() {
    Route::get('delegations/{auction}/view/{lot}', 'AuctionDelegatorsController@delegation')->name('delegations');

e a url que estou tentando apontar é:
@slot('url') {{route('auction.delegations', $auction, $lot)}} @endslot

O erro que ele retorna é o seguinte
Missing required parameters for [Route: auction.delegations] [URI: auction/delegations/{auction}/view/{lot}]

Não estou conseguindo fazer funcionar, alguem poderia me ajudar a ver onde estou errando?
Answer: Consegui concertar utilizando uma array associativa para os parametros.
{{route('auction.delegations',['auction'=> $auction,'lot' => $lot])}}

dessa maneira ele entendeu o caminho da rota com os dois parametros que eu enviava na minha rota: {auction} {lot} devem ser passados para a route como ['auction'=> $auction,'lot' => $lot]

Missing required parameters for [Route]


Is $\left(\dfrac{3299}{2663}\right) = 1$?

Question: Is $\left(\dfrac{3299}{2663}\right) = 1$?
The solution from the book was $-1$ :(.
My attempt was:
$$\left(\dfrac{3299}{2663}\right) = \left(\dfrac{636}{2663}\right) = \left(\dfrac{2^2}{2663}\right) \cdot \left(\dfrac{159}{2663}\right)$$
$$ = 1 \cdot \left(\dfrac{2663}{159}\right) = \left(\dfrac{119}{159}\right) = \left(\dfrac{159}{119}\right) = \left(\dfrac{40}{119}\right) = \left(\dfrac{2^3}{119}\right) \cdot \left(\dfrac{5}{119}\right)$$
And $\dfrac{119^2 - 1}{8} = 1770$. Hence,
$$ = \left(\dfrac{5}{119}\right) = \left(\dfrac{119}{5}\right) = \left(\dfrac{2^2}{5}\right) = 1$$.
Any idea?
Comment: [Wolfram Alpha](http://www.wolframalpha.com/input/?i=JacobiSymbol%5B3299%2C2663%5D) says that the answer is 1.
Comment: @Tsuyoshi Ito: Many thanks for your answer and the link ;)
Comment: Can someone explain the notation? I would like to know what the question is about.
Comment: @picakhu See [Jacobi symbol](http://en.wikipedia.org/wiki/Jacobi_symbol).
Answer: In fact $1$ is correct. Indeed $\rm\ 173^2\ \equiv\ 636\ \equiv\ 3299\ \ (mod\ 2663)\:.\ $ But your proof is wrong since you incorrectly flipped with no sign change in two spots (but the errors cancelled out). $\:$ Namely $\rm\ (159|2663)\ $ and $\rm\ (119|159)\:.$
For testing your program, you might find it helpful to compare to the following unified GCD and Jacobi symbol algorithm. I devised this program not for efficiency but, rather, in response to a challenge problem to show that such a unified program schema exists.
<code>Assumptions: m,n > 0, n odd  (Jacobi (m|n) is defined only for n odd)

BOUNDARY CONDITIONS  (m|n) where 0 ≤ m ≤ 2

GCD:     (0|n) = n,  (1|n) = 1,  (2|n) = 1
Jacobi:  (0|n) = 0,  (1|n) = 1,  (2|n) = 1 if n=1,7 (mod 8) else -1

RECURSION

(m|n) =
 m odd:
       m=n=3 (mod 4):   ( m-(n mod m) | m ) except (0|m) if n = m
       else:            (    n mod m  | m )
 m even:
       n = 5 (mod 8):   ( n-m   | n )
       n = 3 (mod 8):   ( n-m/2 | n ) except (0|n-m) if n-m/2 = m
       else:            (   m/2 | n )
</code>
Comment: Sometimes two wrongs do make a right.
Comment: Sometimes I call such erroneous proofs *involuted* (vs. convoluted).
Comment: @Bill Dubuque: So when I flip, I need to change the sign? Thank you.
Comment: @Chan: The sign changes iff both odd arguments are $\rm\: \equiv\ 3\ \ (mod\ 4)\:.$
Comment: @Bill Dubuque: I see it now. I'm writing a program to calculate Jacobi Symbol. I read the book example and thought I got it, but it turned out to be "big" NO. I really need to read the theorem again. Thanks a lot.
Comment: @Bill Dubuque: Wow! Many thanks for the program ;)! Love it.


OwnCloud error deploying to AWS: The username is already being used (not WebDAV related)

Question: I have an instance of Owncloud running on AWS Elastic Beanstalk
I'm just deploying it from the docker, so I have a very simple Dockerrun.aws.json
{
  "AWSEBDockerrunVersion": "1",
  "Image": {
    "Name": "owncloud/server:latest",
    "Update": "true"
  },
  "Ports": [
    {
      "ContainerPort": "8080",
      "hostPort": "80"
    }
  ],
  "Volumes": []
}

I first setup it running with SQLite, and it was running fine for a couple days
Now I'm trying to setup it using a MariaDB backedn instead.
For that I just add environment variables to my Elastic Beanstalk environment:
OWNCLOUD_ADMIN_PASSWORD=<admin-password>
OWNCLOUD_ADMIN_USERNAME=admin
OWNCLOUD_DB_HOST=<my-db-host-endpoint>
OWNCLOUD_DB_NAME=owncloud
OWNCLOUD_DB_PASSWORD=<db-password>
OWNCLOUD_DB_TYPE=mysql
OWNCLOUD_DB_USERNAME=owncloud
OWNCLOUD_DOMAIN=cloud.mydomain.com
OWNCLOUD_MYSQL_UTF8MB4=true
OWNCLOUD_REDIS_ENABLED=false

Then I just deployed this, and I got this log:
Docker container quit unexpectedly after launch: moving config folder…
Linking config folder…
Writing config file…
Fixing base perms…
Fixing data perms…
Fixing hook perms…
Installing server database…
The username is already being used. Check snapshot logs for details.

I checked the database and the username is not there.
I have tried using different OWNCLOUD_ADMIN_USERNAME, no success.
If I run the docker locally it runs fine and I can access it normally, I got this error message only once while running locally, but I just had to change the username and it worked.
However, the EB version is not accessible, and the instance keeps in "SEVERE/FAILURE" state.
I also have tried restarting the app server and even rebuilding the environment…
I saw similar issues, but they were always related to using WebDAV as an authentication backend, which is not my case. And in all the cases I saw this error was happening while creating a new user from the admin interface, which is not my case, as the admin UI is not even accessible to me.
Any idea what else can I do?
Expected behaviour
Owncloud should be running and connected to the correct database
Actual behaviour
Elastic Beanstalk keep failing the deployment with the error above
Server configuration
Mostly of the configuration is the default coming from the Docker image: owncloud/server:latest
Answer: I'm still not pretty sure why the error was happening, but after several attempts, the error was finally gone.
What seems to have solved it was those steps:

Drop the database created previously.
Remove the environment variables related to Owncloud admin user: OWNCLOUD_ADMIN_PASSWORD and OWNCLOUD_ADMIN_USERNAME.

Then the instance was created with a default user admin/admin, you just need to change the password in the web UI.


Loading a file into a vector

Question: I would like to load the contents of a text file into a vector<char> (or into any char input iterator, if that is possible). Currently my code looks like this:
std::vector<char> vec;
std::ifstream file("test.txt");
assert(file.is_open());
while (!(file.eof() || file.fail())) {
    char buffer[100];
    file.read(buffer, 100);
    vec.insert(vec.end(), buffer, buffer + file.gcount());
}

I do not like the manual use of a buffer (Why 100 chars? Why not 200, or 25 or whatever?), or the large number of lines that this took. The code just seems very ugly and non-C++. Is there a more direct way of doing this?
Comment: Look at this response: http://stackoverflow.com/questions/132358/how-to-read-file-content-into-istringstream/138645#138645 . It does exactly what you want in an intermediate state, and even vinally it builds an stream from the string (or `vector`).
Comment: @Diego - Write this up as an answer and I will accept it. This is just what I was looking for.
Comment: Done, although then it *may* be considered a duplicate question?
Comment: Re `assert(file.is_open());` : Don't do that! `assert` is a macro that can expand into nothing (e.g., release mode) and even if the `assert` does generate code, it doesn't help. A missing file is a user error, not a programmer error. General guideline: Use `assert` to detect programmer errors. Use something else, *anything else*, for user errors.
Comment: @David Hammen - I know... this is not exactly production code at the moment. I will fix the code in the question though.
Comment: @David Hammen - Or, to put it differently, the assert is to stand in for the programmer error that errors in reading the file are not properly accounted for.
Comment: @Mankarse: maybe `#define TODO_ITEM_SHOULD_NOT_ASSUME assert`, then `TODO_ITEM_SHOULD_NOT_ASSUME(file.is_open())` ;-)
Comment: @Steve Jessop - Hehehe, maybe. In the actual code that this was ripped from, it was an `assert(false)` inside an `if` block, with a comment saying `"Not yet implemented"`. I find the Input/Output library to be one of the most confusing part of C++, so I sometimes just give up on trying to write correct I/O code in places where it doesn't matter much.
Comment: possible duplicate of [Efficient way of reading a file into an std::vector?](http://stackoverflow.com/questions/4761529/efficient-way-of-reading-a-file-into-an-stdvectorchar)
Comment: Please consider posting your final solution as an _answer_; it should not be in the question. BTW I've just used it for some production code and wish I could upvote it!
Comment: @LightnessRacesinOrbit: Done. Thanks for the prod. :)
Comment: All answers can be found in  [this article](http://cpp.indi.frih.net/blog/2014/09/how-to-read-an-entire-file-into-memory-in-cpp/). Unfortunately, they are in section: Bad idea #1 or Bad idea #2. The accepted answer causes UB.
Answer: If you want to avoid reading char by char:
if (!file.eof() && !file.fail())
{
    file.seekg(0, std::ios_base::end);
    std::streampos fileSize = file.tellg();
    vec.resize(fileSize);

    file.seekg(0, std::ios_base::beg);
    file.read(&vec[0], fileSize);
}

Comment: Actually, after googling, I found [this article](http://cpp.indi.frih.net/blog/2014/09/how-to-read-an-entire-file-into-memory-in-cpp/). The answer is in the section Bad idea #2.Basically, it causes undefined behavior.
Comment: Neat solution, but is this safe?
Comment: And for the standard sticklers, it's important to remember that nobody actually writes *fully standard compliant code*. Like I doubt much code would work if `char` was 9 bits. So it is ok to rely on de facto standards sometimes.
Comment: @doron: "Safe" in what sense?
Comment: If the word 'safe' is about not crash the app and copy the value correctly to the vector, I think it is. But after the function `file.read(&vec[0], fileSIZe)` executed. The vector size `vec.size()` will still be zero, vec.empty() is true. Not sure that is safe in your app or not.
Comment: It's not *unsafe* in the sense of memory errors. Here's [the article r0ng linked (now dead)](https://web.archive.org/web/20180314195042/http://cpp.indi.frih.net/blog/2014/09/how-to-read-an-entire-file-into-memory-in-cpp/). TL;DR: 1. Make sure you open the file in binary mode, or `tellg()` might not be correct. 2. *According to the C standard*, `seekg(0, end)` might seek beyond the end of files opened in binary mode. However I would be absolutely amazed if any modern system actually does that because then loads and loads of code like this would break. It's fine as long as you use binary mode.
Answer: I think it's something like this, but have no environment to test it:
std::copy(std::istream_iterator<char>(file), std::istream_iterator<char>(), std::back_inserter(vec));

Could be you have to play with io manipulators for things like linebreaks/whitespace.
Edit: as noted in comments, could be a performance hit.
Comment: Hang on, I tell a lie, you're right that an io manipulator is needed to deal with whitespace. The required iterator pair is `std::istream_iterator(file>>std::noskipws), std::istream_iterator()`.
Comment: Note further that if performance requirements aren't too tight for this, and if the questioner really just needs "any char input iterator", then there's no need for a container. `std::istream_iterator(file), std::istream_iterator()` already is the requested InputIterator pair.
Comment: You streams will be buffered so the overhead of kernel calls should be low. The istream iterator could well use a memcpy under the hood as well. It will be interested to see the performance difference between this and Eugene's solution but I don't think the difference will be really big.
Comment: @Diego: probably, I don't know the implementation details of std and couldn't test it. Also, that's not necessarily an issue, but good note indeed.
Answer: Another approach, using rdbuf() to read the whole file to a std::stringstream first:
#include <fstream>
#include <sstream>
#include <vector>
#include <string>

// for check:
#include <algorithm>
#include <iterator>
#include <iostream>

int main() {
   std::ifstream file("test.cc");
   std::ostringstream ss;
   ss << file.rdbuf();
   const std::string& s = ss.str();
   std::vector<char> vec(s.begin(), s.end());

   // check:
   std::copy(vec.begin(), vec.end(), std::ostream_iterator<char>(std::cout));
}

Answer: There were lots of good responses. Thanks all! The code that I have decided on using is this:
std::vector<char> vec;
std::ifstream file;
file.exceptions(
    std::ifstream::badbit
  | std::ifstream::failbit
  | std::ifstream::eofbit);
//Need to use binary mode; otherwise CRLF line endings count as 2 for
//`length` calculation but only 1 for `file.read` (on some platforms),
//and we get undefined  behaviour when trying to read `length` characters.
file.open("test.txt", std::ifstream::in | std::ifstream::binary);
file.seekg(0, std::ios::end);
std::streampos length(file.tellg());
if (length) {
    file.seekg(0, std::ios::beg);
    vec.resize(static_cast<std::size_t>(length));
    file.read(&vec.front(), static_cast<std::size_t>(length));
}

Obviously, this is not suitable for extremely large files or performance-critical code, but it is good enough for general purpose use.
Answer: use an iterator:
#include <iterator>

istream_iterator<char> data( file );
istream_iterator<char> end;
vec.insert( std::back_inserter(vec), data, end );

Comment: Isn't this going to read a character at a time **and** skip over whitespace?

Loading a file into a vector


Interpreting intercept in logistic regression when there is more than one categorical variable

Question: mydata <- read.csv("https://stats.idre.ucla.edu/stat/data/binary.csv")
#create a binary variable just for the purpose of experimentation
mydata$bin = rbinom(nrow(mydata), p = 0.7, size = 1)
mydata$rank <- factor(mydata$rank)
mydata$bin <- factor(mydata$bin)
#Run the model with just bin
my.mod <- glm(admit ~ bin, data = mydata, family = "binomial")
summary(my.mod)

Coefficients:
              Estimate Std. Error  z value    Pr(>|z|)
(Intercept) -0.8434294  0.1966085 -4.28989 0.000017876
bin1         0.1121304  0.2347628  0.47763     0.63291
The intercept is simply logodds of admit == 1 when bin1 = 0
Check:
x = subset(mydata, bin == "0")
mean(x$admit)
log(0.3008130081/(1-0.3008130081))

Result:
-0.843429383
Tallied
Next, do the same with rank variable alone in the model
my.mod <- glm(admit ~ rank, data = mydata, family = "binomial")
summary(my.mod)

Coefficients:
              Estimate Std. Error  z value    Pr(>|z|)
(Intercept)  0.1643031  0.2569384  0.63946    0.522521
rank2       -0.7500300  0.3079693 -2.43540    0.014875
rank3       -1.3646980  0.3353867 -4.06903 0.000047210
rank4       -1.6867296  0.4093073 -4.12094 0.000037733
The intercept is simply logodds of admit == 1 when rank2 = 0 & rank3 = 0 & rank4 = 0; in other words rank == 1
Check:
x = subset(mydata, rank == "1" )
mean(x$admit)
log(0.5409836066/(1-0.5409836066))

Result:
0.1643030515 Tallied
Next, I add both the categorical variables in the model
my.mod <- glm(admit ~ rank + bin, data = mydata, family = "binomial")
summary(my.mod)

Coefficients:
               Estimate  Std. Error  z value    Pr(>|z|)
(Intercept)  0.23245129  0.32715773  0.71052    0.477383
rank2       -0.75673758  0.30869909 -2.45138    0.014231
rank3       -1.38523274  0.34119770 -4.05991 0.000049091
rank4       -1.69956417  0.41127752 -4.13240 0.000035899
bin1        -0.08308446  0.24667503 -0.33682    0.736255
Question: How to make sense of this intercept like above 2 examples? I don't think in this case intercept equals logodds of admit == 1 when (bin = 0 and rank = 1).
Check:
 x = subset(mydata, rank == "1" & bin == "0" )
 mean(x$admit)
 log(0.6363636364/(1-0.6363636364))

Result:
     0.5596157881 Not tallied!
Answer: So, you have two binary predictors, say $X$ and $Z$, and the logistic model
$$\DeclareMathOperator{\P}{\mathbb{P}}
\P(Y=1 \mid X=x) = \frac{e^{\beta_0 + \beta_1 x}}{1+e^{\beta_0 + \beta_1 x}}
$$
setting $X=0$ you can see that $\beta_0$ is the log odds of probability that $Y=1$ given $X=0$.  Now adding the second predictor in the model:
$$
\P(Y=1 \mid X=x,Z=z) = \frac{e^{\beta_0 + \beta_1 x+\beta_2 z}}{1+e^{\beta_0 + \beta_1 x + \beta_2 z}}
$$
and you can see that in this model $\beta_0$ is the log odds of the probability that $Y=1$ given both $X=0$ and $Z=0$ (in your code example you look at the conditioning $X=0, Z=1$).
Comment: dummy variables for the categorical variable with rank = 1 as the baseline are all zero. bin1 is also zero for binary predictor for bin = 0. This will wipe out all the terms in the linear predictor except for the intercept - β0. Ex - > model.matrix(my.mod)[13,]
(Intercept)        bin1       rank2       rank3       rank4
          1           0           0           0           0                                                            ..I still cannot see the answer, some elaboration would surely help.
Comment: > mydata[13,]
   ADMIT GRE GPA RANK bin rank
13     1 760   4    1   0    1


Jasper não abre fora da IDE

Question: Dentro da IDE NetBeans o código funciona e o relatório é apresentado.
Mas ao gerar o executável, não é possivel abrir o relatório, recebendo a mensagem de nulo.
É como se ele não conseguisse localizar o relatório.
public ClienteREL() {
    this.path = this.getClass().getClassLoader().getResource("").getPath();
    this.pathToReportPackage = this.path + "br/com/prologica/report/";

            System.out.println(this.pathToReportPackage);

}

//Imprime/gera uma lista de Clientes
public void imprimir(List<Cliente> clientes) throws Exception
{
    JasperReport report = JasperCompileManager.compileReport(this.getPathToReportPackage() + "imprimir.jrxml");

            JasperPrint print = JasperFillManager.fillReport(report, null, new JRBeanCollectionDataSource(clientes));

            JasperPrintManager jasperPrintManager = null;
            jasperPrintManager.printReport(print, false);

}

Comment: você está gerando um jar? Se sim, tente executa-lo direto do prompt e veja se estoura algum erro.
Comment: pois amigo, ao executar no console é como se ele não conseguisse encontrar o relatório.
Comment: Executar o jar no console não exibe nada também?
Comment: nada... mas dentro da ide roda direitinho
Answer: Isso claramente é algum problema de Classpath. O NetBeans por debaixo dos panos executa o JAR também por linha de comando. Então teria que ver como ele faz.
Recomendo você começar tentando rodar manualmente o JAR gerado pelo NetBeans dentro da pasta "dist" do seu projeto. Se isso der certo, copie a pasta "dist" com tudo o que há lá dentro (inclusive a pasta "dist/libs") para um outro lugar e tente executá-lo.
Se isto der errado, por favor, tente criar um exemplo mínimo, completo e verificável do seu problema.

Jasper não abre fora da IDE


Is there away to wrap to the left an element that's positioned to the right using flexbox?

Question: So I have 2 elements on the same line where one is to the far left and the other the far right using justify-content: space-between;
For responsive purposes though I need to wrap the element on the right to the next line if it's about to overlap the element on the left.
I'm using flex-wrap: wrap; but when it wraps the "right" element is on a new line but it is still pushed to the right whereas I need it to be pushed to the left as otherwise there's just whitespace to it's left.
Comment: Unfortunately there is no way to select a wrapped flex child through a CSS rule. This would probably be better handled with a media query.
Comment: Post the code you use, so we can see how to help
Answer: Why isn't flex-wrap working for you? Look at this simple example with justify-content: space-between; and where the right element wraps to the next line and they are both pushed to the left:

.wrapper {
 display: flex;
 flex-wrap: wrap;
 justify-content: space-between;
 max-width: 500px;
 width: 100%;
 margin: 0 auto;
}

.wrapper div {
 display: block;
 width: 220px;
 height: 220px;
    margin-bottom: 10px;
 background-color: red;
}

Comment: As it now turned out, there was nothing wrong with OP's code, hence this can now be closed as _a problem that can no longer be reproduced_
Comment: I guess if OP's code would be like this there wouldn't be an issue, right? ... so if we wait until we get the actual code we would be able to answer properly ... and having a proper written question :)
Comment: You're right, it should have worked and it does now. Turns out the element was inheriting a `margin-left: auto` from somewhere else in the app. I just presumed it was the `justify-content` that was pushing it to the right. Thanks.
Comment: You're welcome. @LGSon I can see the future. Yea i know it's not proper SO guidelines. Downvote me. I still helped the OP that's what matters to me. Not the future of SO. Pretty sure they'll be fine


Reading complicated format string with fscanf

Question: I have a kindof complicated file format:
<code>{
      "color": [
        45,
        200,
        34
      ],
      "docnum": 5183,
      "form": "avoir",
      "graph": "jdm.N.flat",
      "id": 0,
      "lang": "fr",
      "neighbors": 17,
      "pos": "N",
      "pzero": true,
      "rank": 1,
      "score": 0.0028284271,
      "type": 1
    },
    {
      "color": [
        45,
        200,
        34
      ],
      "docnum": 22809,
      "form": "argent",
      "graph": "jdm.N.flat",
      "id": 1,
      "lang": "fr",
      "neighbors": 65,
      "pos": "N",
      "pzero": false,
      "rank": 2,
      "score": 0.0028284271,
      "type": 1
    },
</code>
This kind of list goes on, for hundreds of entries. I would like to read in the variable numbers, and a string (docnum, form, id, neighbors, rank, score) so i created a format string for this kind of input:
<code>     main(){

     FILE* in=fopen("fr.N.bien2","r");
     int maxwords=100;
     int maxstringlen=100;

     char* nodes=malloc(sizeof(char)*maxstringlen*maxwords);
     if(!nodes){printf("Nodes couldn't be allocated!\n");}

     int i=0;

     int* IDs=malloc(sizeof(int)*3*maxwords);
     int docnum,nei,rank;
     float score;
     char* pzero;
     while(fscanf(in," { \"color\": [ 45, 200, 34 ], \"docnum\": %i,      \"form\": %s \"graph\": \"jdm.N.flat\", \"id\": %i , \"lang\": \"fr\",  \"neighbors\": %i , \"pos\": \"N\", \"pzero\": false, \"rank\": %i , \"score\": %f , \"type\" :1  },",&docnum,&nodes[i],&IDs[i],&nei,pzero,&rank,&score))
    {
         printf("node:%s,ID=%i\n",&nodes[i],IDs[i]);
         i++;
   }
   }
</code>
It looks complicated, but it seems to be working, because I get the first instance right. The output is:
<code>>>node:"avoir",,ID=0
</code>
However, output stops at that, even though the format is exactly repeating in the file (as you can see in the sample).
Am I missing something important here?
Is there an easier way to read in this kind of data from such a file?
Comment: That's JSON. Grab your favorite json library and use that.
Comment: That looks like a [JSON](https://en.wikipedia.org/wiki/JSON) object, and that you can't really parse easily with only `scanf` and family. Instead search for a JSON library.
Comment: " it seems to be working, because I get the first instance right" - Famous last words of a software developer who did not properly test.
Answer: And this complicated format is JSON
As the comments suggest, look for a library instead (they can be found following the previous link) there's many libraries and for different languages as well.
In fact, your question might be already answered here


What happens when you choose a default country during installation?

Question: In the last step when you install Drupal 8 under "Configure site" you can choose a "default country":

However no clues are provided about the option...

What happens when you choose a default country for the site?
And what happens when you just leaves it as "none"?
Answer: In drupal core this is only used for date and time formats. If you leave it empty you can set it later in the admin menu:
/admin/config/regional/settings
Comment: It looks like that, and even the date/time formatting is not fully implemented in core. So the only purpose seems to be, that contrib/custom modules can use this setting and the country list and don't need to define it on their own.
Comment: Thanks for feedback. Okay - so does it **only** effect those two formates? At the path you directed me to there is also "First day of week" selection, maybe that is also effected? Are there any other things that might be effected by this choice?
Comment: Hmm, okay - so in that case the correct answer is that choosing a default country doesn't have any effect?


How to add Open Graph Tags in Custom Module detail page?

Question: For Node I already used https://www.drupal.org/project/metatag
For my custom module's detail page would like to add Open Graph tags for FB share.
So in my_test.module
function template_preprocess_my_detail_page(&$variables) {

  $items = $variables['item'];

  $title =  $items->title;

  $og_title = [
        '#tag' => 'meta',
        '#attributes' => [
          'property' => 'og:title',
          'content' => $title,
        ],
      ];

  $variables['page']['#attached']['html_head'][] = [$og_title, 'og_title'];
}

Above one suppose to work but NOT WORKING.
function MY_MODULE_page_attachments_alter(array &$page) {

  $og_title = [
        '#tag' => 'meta',
        '#attributes' => [
          'property' => 'og:title',
          'content' => '',
        ],
      ];

  $page['#attached']['html_head'][] = [$og_title, 'og_title'];
}

Above one is working, But I'm not able to get Page Variables. How will I get $variables in above function?
This one called in all pages of module, but I want to call only on detail page as mentioned in proprocess function
Answer: I think that you need this.
    /**
 * Alter the metatags for pages that are not of content entities.
 *
 * @param array $metatags
 *   The special metatags to be added to the page.
 * @param array $context
 *   The context, containing the entity used for token replacements.
 */
function hook_metatags_alter(array &$metatags, array $context) {
  // Exclude metatags on frontpage.
  if (\Drupal::service('path.matcher')->isFrontPage()) {
    $metatags = NULL;
  }
}

Comment: I need to get current post details as well. Can i get that then on basis of that need to set meta tags
Comment: Julia what kind of page do you have?
Comment: We are getting data from API & on basis of URL Say `/test/111` will get Id & get data from API
Answer: Got the solution
So in my_test.module
function template_preprocess_my_detail_page(&$variables) {

  $items = $variables['item'];

  $title =  $items->title;

  $og_title = [
        '#tag' => 'meta',
        '#attributes' => [
          'property' => 'og:title',
          'content' => $title,
        ],
      ];

  $variables['#attached']['html_head'][] = [$og_title, 'og_title'];
}

Change from
$variables['page']['#attached']['html_head'][] = [$og_title, 'og_title'];

to
$variables['#attached']['html_head'][] = [$og_title, 'og_title'];


How to calculate the transalation and/or rotation of two images using fourier transaform?

Question: I need find the translation and/or rotation of an image and himself translated and/or rotated (x0, y0) px and/or J degrees. Given the two images I need to find N.
Answer: The classic reference for this problem is Reddy et al., An FFT-Based Technique for Translation,
Rotation, and Scale-Invariant Image Registration. The basic idea builds on the well-known properties of the FFT, that a displacement is reflected in a phase shift of the same magnitude, so that you just need to recover the phase shift to estimate the displacement.
Concretely, if the FFT of an image $f(x, y)$ is $F(\xi, \eta)$, then the FFT of $f^{'}(x, y) = f(x-x_0, y-y_0)$ is $e^{-j2\pi (x_0 \xi + y_0 \eta)}F(\xi, \eta)$, so that
$$
e^{-j2\pi (x_0 \xi + y_0 \eta)} = \frac{F(\xi, \eta)\bar F^{'}(\xi, \eta)}{F(\xi, \eta)F^{'}(\xi, \eta)}
$$
where $\bar F$ is the conjugate. In the paper, this approach is extended to get estimates of rotations and scaling along the x,y axis.
Comment: Thank. That's excelente. Is there a clear definition for the rotatation? Do you have a Python code?
Comment: I do not fully understand your question. The idea is that you have a reference image, and translations and rotations are relative to that reference image. Please go through the paper, and do not hesitate to ask if there are unclear issues. OpenCV provides an implementation. See cv::phaseCorrelate (https://docs.opencv.org/4.6.0/d7/df3/group__imgproc__motion.html#ga552420a2ace9ef3fb053cd630fdb4952)
Answer: OpenCV (and Scikit-Image) only implement phase correlation (aka just the translation part). I couldn't find an implementation of translation + rotation in any library from the Reddy et al. paper @jpmuc mentioned, so I implemented it here: https://gist.github.com/kwsp/8c660f7636c64f3f6ceaac900517f842
<code>"""
B. S. Reddy and B. N. Chatterji, "An FFT-based technique for translation, rotation, and scale-invariant image registration," IEEE Transactions on Image Processing, vol. 5, no. 8, pp. 1266–1271, Aug. 1996, doi: 10.1109/83.506761.

Implemented in Numpy/OpenCV and Numpy/Scikit-Image

The OpenCV version is about 4 times faster than the Scikit-Image version.
"""
# Numpy/OpenCV implementation
import cv2
from scipy import signal
import scipy.fft as sfft
import numpy as np

# OpenCV implementation
def find_rotation_cv(img_ref: np.ndarray, img_moved: np.ndarray) -> float:
    h, w = img_ref.shape[:2]
    hamming_w = signal.windows.hamming(w)
    hamming_h = signal.windows.hamming(h)
    hamming = np.outer(hamming_h, hamming_w)

    F_ref = np.log(np.abs(sfft.fftshift(sfft.fft2(img_ref * hamming))))
    F_moved = np.log(np.abs(sfft.fftshift(sfft.fft2(img_moved * hamming))))

    center_x = w // 2
    center_y = h // 2
    radius = min(center_x, center_y)

    # Define the desired size of the output polar image
    polar_width = radius
    polar_height = int(np.ceil(radius * np.pi / 2))

    # Perform the polar transformation
    F_ref_warpped = cv2.warpPolar(
        F_ref,
        (polar_width, polar_height),
        (center_x, center_y),
        radius,
        cv2.WARP_POLAR_LOG + cv2.INTER_CUBIC + cv2.WARP_FILL_OUTLIERS
    )
    F_moved_warpped = cv2.warpPolar(
        F_moved,
        (polar_width, polar_height),
        (center_x, center_y),
        radius,
        cv2.WARP_POLAR_LOG + cv2.INTER_CUBIC + cv2.WARP_FILL_OUTLIERS
    )

    ret = cv2.phaseCorrelate(F_ref_warpped[:180], F_moved_warpped[:180])
    theta_shift = 360 / polar_height * -ret[0][1]
    return theta_shift

from skimage.transform import warp_polar
from skimage.registration import phase_cross_correlation

# scikit-image implementation
def find_rotation(img_ref: np.ndarray, img_moved: np.ndarray) -> float:
    h, w = img_ref.shape[:2]
    hamming_w = signal.windows.hamming(w)
    hamming_h = signal.windows.hamming(h)
    hamming = np.outer(hamming_h, hamming_w)

    F_ref = np.log(np.abs(sfft.fftshift(sfft.fft2(img_ref * hamming))))
    F_moved = np.log(np.abs(sfft.fftshift(sfft.fft2(img_moved * hamming))))

    F_ref_warpped = warp_polar(F_ref, scaling="log")
    F_moved_warpped = warp_polar(F_moved, scaling="log")

    ret = phase_cross_correlation(F_ref_warpped[:180, ], F_moved_warpped[:180, ])
    return ret[0][0]
```
</code>


Maven: zip resources and save into specific folder

Question: For a project I need to zip a number of resource files and put this archive inside the project source (src/main/resources). The idea is that this archive then ends up in the EAR and goes to the deployment server, where it is picked up by a script for further processing. Convoluted, I know, but those are the constraints we are working with.
I've created an Assembly plugin configuration file that creates the zip, but this zip is placed by default in a target/ folder.
The assembly plugin has an outputDirectory option, but this only changes the filestructure of the contents of the zip, not the location where the zip is saved.
Is there a way to specify where the assembly plugin saves the created zip? Or is there a better way altogether to zip resources?
Answer: there are two outputDirectory configuration, one represents the file path inside your assembled package,
another one represents directory where your assembled package would be output
you are looking for second one
Comment: The link "you are looking for second one" is not working .
Answer: Please add the following code in pom.xml , provide the path in outputDirectory tag  :
     <execution>
             <id>assembly-execution</id>
            <phase>package</phase>
            <goals>
            <goal>single</goal>
            </goals>
            <configuration>
            <finalName>zipFileName</finalName>
            <appendAssemblyId>false</appendAssemblyId>
            <descriptors>
                <descriptor>${project.basedir}/zip.xml</descriptor>
            </descriptors>
 <outputDirectory>${project.basedir}/src/main/resources</outputDirectory>
            </configuration>
     </execution>


LINQ groupby question

Question: I have a collection called navigationList. This list holds customer objects.
A customer has a property called Town.
The list holds 5 customers: 2 with town "New York", and 5 with town "Madrid".
I want the list to only hold only 2 customers. 1 with town "New York" and one with "Madrid". If 2 are from "New York", I want the last one. Same for "Madrid".
What would the LINQ statement look like?
var newList = navigationList.GroupBy(c => c.Town) // ?

Answer: You would want something like
var newList = navigationList.GroupBy(c => c.Town).Select(g => g.Last()).ToList();

However, you would probably want to OrderBy first, so that the Last is meaningful:
var newList = navigationList.
              GroupBy(c => c.Town).
              Select(g => g.OrderBy(c => c.Id).Last()).
              ToList();

In this case the ordering is done by customer Id.

LINQ groupby question


k nearest neighbor with decision tree

Question: A dataset has a few attributes. One of the attributes(attribute X) represents a distance with values expressed in meters.  I use cross-validation to estimate the performance of Decision tree and k nearest neighbor classifiers.
My questions:

Why will the performance of k-nn change if I change the
representation of attribute  X to cm instead of m?
Why will the
performance of k-nn and decision tree not change if I multiply all
the attributes with 20?
Answer:
1) Why will the performance of k-nn change if I change the representation of attribute X to cm instead of m ?

k nearest neighbor classifiers use a distance measure , usually Euclid distance, to decide classification. Suppose you have this data set.
10m 10kg
11m 11kg

 >> sqrt((11-10)^2 + (11-10)^2)
 ans =
 1.4142

if you change m to cm. you have following data set.
1000cm 10kg
1100cm 11kg

Here your distances changed.
 >> sqrt((1100-1000)^2 + (11-10)^2)
 ans =
 100.0050

If you do not want this behavior, you need to normalize your data.

2) Why will the performance of k-nn and decision tree not change if I multiply all the attributes with 20?

here you scale your data but you scale ALL of them. Since both k-nn and decision trees use distance measures to classify your data, classifications does not change.
Comment: Thank you for taking the time to answer the question complete with the examples.

k nearest neighbor with decision tree


Curved Path Constant Speed and End Points

Question: I'm trying to move at a constant speed over a curved path in a given amount of time. I calculated the average speed needed to travel the curve by taking the derivative at various points along the curve and averaging them. Then I multiply the path's position (t) by a ratio of the average derivative and the derivative at the current location of the curve. This method for setting constant speed works great.
The problem I'm having occurs when multiple control points (3 or more) are put in the same location. Then the speed (or derivative) at this point is 0 and dividing the average speed by a speed of 0 obviously causes problems in the calculations.
BSpline requires three control points to be placed at the ends in order to have the curve actually reach the start and end at the end points. If I only put 1 or 2 control points at the ends the path starts after the first control point and ends before the last control point. For my application it is important that the motion reaches the end points because I will be linking together multiple BSplines and it's important for them to line up correctly and to not have any time gaps between them either.
I've tried a few different attempts at fixing it, but none of them were successful.
Here is my sample code and I've included comments to indicate where the problem is.
NOTE: I used CatmullRomSpline in my example instead of BSpline only because I found a bug in the BSpline's derivative method, which has been fixed but is not yet in the stable version of LibGDX.
Test.java
public class Test extends Game {
    private Stage stage;
    private MyPath path;

    @Override
    public void create () {
        Gdx.graphics.setDisplayMode(1000, 1000, false);
        stage = new Stage();
        stage.setViewport(new ScreenViewport(stage.getViewport().getCamera()));
        Gdx.input.setInputProcessor(stage);
        path = new MyPath(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        stage.addActor(path);
    }
    @Override
    public void render () {
        Gdx.gl.glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();
    }
    @Override
    public void dispose(){
        path.dispose();
        stage.dispose();
        super.dispose();
    }
}

MyPath.java
public class MyPath extends WidgetGroup implements Disposable {
    private Path<Vector2> path;
    private Vector2 result=new Vector2(), derivative=new Vector2();
    private float time, t, tPrev, dt, tConst, tConstPrev, derivativeAverage;
    private Array<Texture> textures = new Array<Texture>(Texture.class);
    private Array<Image> points = new Array<Image>(Image.class);
    private Image dot;

    private final float CYCLE = 4;  // path cycle time (in seconds)

    private Vector2[] pointsData = {
            new Vector2(100, 100),
            new Vector2(100, 100),
//          new Vector2(100, 100),  // << UN-COMMENT TO PRODUCE BUG

            new Vector2(350, 800),
            new Vector2(550, 200),
            new Vector2(650, 400),
            new Vector2(900, 100),
            new Vector2(900, 100)
    };

    public MyPath(int width, int height){
        this.setSize(width, height);
        path = new CatmullRomSpline<Vector2>(pointsData, false);
        // create and add images
        createImages();
        for (int i=0; i<points.size; i++){
            points.items[i].setPosition(pointsData[i].x - points.items[i].getWidth()/2, pointsData[i].y - points.items[i].getHeight()/2);
            addActor(points.items[i]);
        }
        addActor(dot);

        // calculate derivative average
        derivativeAverage();
    }

    @Override
    public void act(float delta){
        result = getValue(delta);
        dot.setPosition(result.x - dot.getWidth()/2, result.y - dot.getHeight()/2);
    }
    private Vector2 getValue(float delta){
        // set t in the range [0,1] for path
        time += delta;
        if (time > CYCLE){
            time = tPrev = dt = tConst = tConstPrev = 0;
        }
        t = time / CYCLE;
        dt = t - tPrev;
        tPrev = t;

        // constant speed (tConst)
        path.derivativeAt(derivative, tConstPrev);
        tConst += dt * (derivativeAverage / derivative.len());  // << ERROR when derivative.len() is 0
        tConstPrev = tConst;

        path.valueAt(result, tConst);

        return result;
    }

    private void derivativeAverage(){
        float segmentCount = 20000;
        derivativeAverage = 0;
        for (float i=0; i<=1; i+=1.0/segmentCount) {
            path.derivativeAt(result, i);
            derivativeAverage += result.len();
        }
        derivativeAverage /= segmentCount;
        if (derivativeAverage==0){ throw new GdxRuntimeException("ERROR: derivative average is zero"); }
    }

    private void createImages(){
        dot = getImage(Color.GREEN, true);
        for (int i=0; i<pointsData.length; i++){
            points.add(getImage(Color.WHITE, false));
        }
    }
    private Image getImage(Color color, boolean fillCircle){
        Pixmap pixmap = new Pixmap(50, 50, Pixmap.Format.RGBA8888);
        pixmap.setColor(color);
        if (fillCircle){
            pixmap.fillCircle(pixmap.getWidth()/2, pixmap.getHeight()/2, pixmap.getWidth()/2-1);
        } else {
            pixmap.drawCircle(pixmap.getWidth()/2, pixmap.getHeight()/2, pixmap.getWidth()/2-1);
        }
        textures.add(new Texture(pixmap));
        pixmap.dispose();
        return new Image(textures.peek());
    }
    @Override
    public void dispose(){
        while (textures.size > 0){
            textures.pop().dispose();
        }
    }
}

===================================================================
EDIT
===================================================================
Here is my latest attempt at increasing t until the dot is moving.
This method does occasionally work on some frames (moving smoothly past the zero derivative). But other times the dot does weird things lie starting over at the beginning of the curve when it hits the zero derivative or extending beyond the end of the curve moving a different direction or disappearing completely (because the position gets set to negative values).
So it seems like this method is really close as it does occasionally work on some frames, but it glitches and does weird things on other frames.
Vector2 lastPoint = new Vector2();
float minSpeed = 1;
float minDerivative = 1;
float temp;

...

private Vector2 getValue(float delta){
    // set t in the range [0,1] for path
    time += delta;
    if (time > CYCLE){
        time = tPrev = dt = tConst = tConstPrev = 0;
    }
    t = time / CYCLE;

    // CONSTANT SPEED
    dt = t - tPrev;
    path.derivativeAt(derivative, tConstPrev);
    temp = dt * (derivativeAverage / derivative.len());
    path.valueAt(result, tConst + temp);

    //**************************************
    //  FIX FOR ZERO SPEED
    //  increase t in loop until speed > 0
    //**************************************
    while (result.dst(lastPoint)<minSpeed || derivative.len()<minDerivative){
        // set t in the range [0,1] for path
        time += delta;
        if (time > CYCLE){
            time = tPrev = dt = tConst = tConstPrev = 0;
            lastPoint.set(0,0);
        }
        t = time / CYCLE;

        // CONSTANT SPEED
        dt = t - tPrev;
        // new derivative
        path.valueAt(derivative, t);
        derivative.sub(lastPoint);

        temp = dt * (speedAverage / derivative.len());
        path.valueAt(result, tConst + temp);
    }

    tConst += temp;

    lastPoint.set(result);
    tPrev = t;
    tConstPrev = tConst;

    return result;
}

I also do a similar thing when calculating the average speed to keep the zero derivatives from affecting it. I also tried using the commented out sections with the "addedSegmentCount" variable when calculating the average, but that actually caused more glitches for some reason...even though theoretically this seems like the "correct" way to calculate the average since some segments don't get added if the distance is too small.
private void pathLength_SpeedAverage(){
    float segmentCount = 20000;
//  float addedSegmentCount = 0;
    pathLength = 0;

    path.valueAt(lastPoint, 0);
    for (float i=0; i<=1; i+=1.0/segmentCount){
        path.valueAt(result, i);
        if (result.dst(lastPoint) >= minSpeed){
            path.derivativeAt(result, i);
            if (result.len() >= minDerivative){
                pathLength += result.len();

                lastPoint.set(result);
//              ++addedSegmentCount;
            }
        }
    }
    speedAverage = pathLength / segmentCount;
//  speedAverage = pathLength / addedSegmentCount;
    lastPoint.set(0,0);
}

Comment: B-spline does not require you to add multiple control points at the ends so as for the curve to reach the start and end points unless you are using non-clamped knot sequence such as [0, 0.1, 0.2, ...., 0.9, 1.0]. If you uses clamped knot sequence such as [0, 0, 0, 0, 0.1, 0.2,...., 0.9, 1, 1, 1, 1], then the curve will start and ends at the first and last control points. Having said this, if you had switched to Catmull-Rom spline, do you still have the same problem (encountering zero derivative)?
Comment: Yes, I do have the same zero (or near zero) derivative problem with CatmullRom if I set 3 (or more) control points in the same location. Regarding BSpline, I looked at the LibGDX source code and it doesn't appear that the knots are used in the valueAt() or derivativeAt() methods. I tested it by clearing the knot array and assigning my own values to it and the path remained the same. So how would I go about setting different knot sequences? Thanks.
Comment: Well, if you duplicated consecutive points, you will get zero derivatives. But this happens regardless which kind of interpolation you used. I am not familiar with LibGDX. I was just commenting from the perspective of B-spline theory. Sorry.
Comment: Do you know if there is a way to smoothly step over these areas with multiple control points and get back into the path where the derivatives are no longer zero (or close to zero)? I've tried a few different methods like increasing the time interval by the normal amount (instead of the derivative ratio) until the derivative is greater than 1. But I always end up causing glitches and it doesn't smoothly move past the multiple control points. Also, LibGDX is open source and here is the source for BSpline: https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/math/BSpline.java
Comment: For cubic B-spline, you need to have 4 consecutive control points for the corresponding Bezier segment to become a point. Let's say you have 6 control points P0,P1,P2,...P5 with P1,P2,P3 and P4 being at the same location and a knot sequence [0.0, 0.3, 0.7, 1.0], then the derivative evaluation within (0.3,0.7) will be zero and you just need to skip this range for derivative evaluation.
Comment: I made a copy of the BSpline class so I could put some print statements in to see what it was doing at each frame. I also removed the constant speed derivative ratio code for these tests and used 7 control points where the first 3 are the same. During knot span 1 the derivative ranges from 0 to 346.3167 and the position on the curve changes from the starting control point (100, 100) to (137.47958, 204.94284). I posted my print statements to textuploader. http://textuploader.com/5wg7h So it doesn't appear I can skip the first curve entirely as there is quite a bit of movement during it. Thanks.
Comment: Having 4 consecutive identical control points will certainly make a cubic Bezier segment become a point, which leads to zero first derivative. But this is not the "only" way that will lead to zero first derivative. For example, if you have the first two control points the same, you will have zero first derivative at t=0.0. Even for a single cubic Bezier curve with all 4 distinct control points, you still could encounter zero first derivative at certain parameter value. So, if you really want to skip zero first derivatives, the best way is simply not to include them when computing the average.
Comment: I think you can also get the average speed by dividing the overall length of the path by the parameter range.  To compute the overall length of the path, you can sample sufficient points along the path and compute the cumulative chord length as accuracy is not really important here. This way, you don't really care about zero first derivatives at all.
Comment: The BSpline class has an approxLength method that I can use to get the length of the curve. But what can I do about having to get current speed? At each frame I'm evening out the speed by multiplying t by (averageSpeed / currentSpeed) and the currentSpeed is what is causing the problems. In order to get the current speed at a particular point in the curve I have to get the derivative at that point. Is there another way to offset "t" at a particular point to keep constant speed without dealing with the derivative at that point? Thanks.
Comment: You cannot completely avoid zero first derivatives if control points could be coincident. So, what I suggest is to not use the zero first derivatives at all. Your purpose is to traverse the path at a constant speed, which is equivalent to sample points along the path with equal arc length, You should be able to find many examples in SO on this topic.
Comment: I have looked into arc length parameterization and it seems to be very, very complicated. For example, this pdf pops up in most threads on this topic. https://www.geometrictools.com/Documentation/MovingAlongCurveSpecifiedSpeed.pdf And I've read some other stuff on arc lengths but I still do not understand how to calculate the curve parameter t that corresponds to a specific arc length. If I could get that part, then I could definitely go the arc length route instead. But it's been a while since I've had to do calculus in college and actually grasping this stuff so I can code it is difficult.
Comment: The theoretical approach involves calculus indeed, but you can go with the approximation approach, which I will post as an answer (as it takes a couple steps).
Comment: Great thanks! And since you clearly understand this stuff really well, would it be possible to also explain the calculus version of calculating t in plain english? It seems like some of the documents trying to explain it way over-complicate things. lol But to see it presented in the step-by-step approach like you did would probably make it much clearer. Thanks again for all your help! :)
Comment: It is not easy to explain math and complex numeric methods in plain English and within limited character counts. All I can tell you is that the  equation(5) and (6) in the pdf file you reference above actually correspond to the lookup table (step 3) and linear interpolation (step 4) in my answer. It is just that the approach in my answer is an approximation to the real solution but is much easier to understand implement.
Comment: If you wanted to post another answer (or edit your answer to include the advanced calculus method) then you wouldn't be constrained to the character limit. But I'll take a look at the document again and compare to your approximation example. Your example was easy to intuitively understand so maybe that will help make the long mathematical document more digestible. Thanks again. :)
Comment: Also, I've still been working on a less math intensive solution, because everything works except for the one special case where the dot is not moving (derivative=0 or small enough that the dot's position doesn't change by even 1 pixel). So my idea is: IF dot is moving THEN make speed constant. IF dot is not moving THEN move to a frame where the dot is moving THEN make that speed constant. Basically just increasing the curve parameter in a loop until the dot moves and then use my constant speed derivative ratio on it. Does this seem plausible? I can edit my post to show what I have so far.
Comment: I just edited my original post to include my latest method to transition over the zero speed/derivative. Do you think something like that would be a viable solution or am I wasting my efforts trying to fix the problem like that? Thanks.
Answer: You cannot completely avoid zero first derivatives if control points could be coincident. So, what I suggest is to not use the first derivatives at all. Your purpose is to traverse the path at a constant speed, which is equivalent to sample points along the path with equal arc length. The theoretical approach to solve this involves calculus to compute arc length numerically, but we can go with an approximation approach as in the following:
Suppose you would like to traverse the path in N steps,
1) Sample M points along the path uniformly in parameter domain (i.e., t=0.0, 0.1, 0.2, 0.3, ....) where M is preferred to be greater than N. Denoting these points as P0, P1, P2,....
2) Compute the distance between P0P1, P1P2, P2P3,....
3) Compile a look-up table that maps from parameter t(i) to the cumulative chord length |P0P1|+|P1P2|+.....+|P(i-1)P(i)|. At the end, you will also obtain the overall length of the path, denoted as L.
4) Now, for each value of kL/N (where k=0 to N), you can compute the corresponding t value from the look-up table by linear interpolating the two parameter values in which the kL/N falls on.
Comment: Suppose you have a lookup table that maps parameters [0, 0.1, 0.2, 0.3,0.4,....1.0] to arc length [0, 8, 15, 23, 32, .....100] and you want to find the parameter at which the arc length is 28, you will loop thru the arc length array to find out the two bounding values 23 and 32, then linear interpolate the corresponding parameters 0.3 and 0.4 to find the parameter.  Hope this clearly enough.
Comment: @camillo: if invLerp gives you a value = 5/9 and lerp gives you a value = 0.3555555, then it is correct.
Comment: Woohoo! I got this method working. :) I was worried initially that I was going to need to store thousands and thousands of values in the lookup table in order for it to be precise and I only need about 100 and it looks to be about perfect. Wow, this really is a great method. It currently freezes for a split second right at the very beginning, but I hopefully I'll be able to figure that out. Thanks again for all you're help. :)
Comment: Hello @fang, I know this is old, but is it possible to add some more details to this answer, mainly on point 4 which is too difficult to understand for me?
Comment: @fangThank you! I used an array of lengths instead of a lookup table; then used an invLerp to find "t" for "28" between "23" and "32" and then I used a lerp between samples[0.3] and samples[0.4] with the "t" param... is it correct?