Java Custom Event Handling

Question: Good Day,
I am writing a custom event handler in Java.  I have a class called BoogieCarMain.java that instantiates three instances of a type called BoogieCar.  Whenever any of the three instances exceeds a certain speed limit, then an event should be fired off.  The code I currently have is working, so here is what I have:
<code>// BoogieCar.java
import java.util.ArrayList;

public class BoogieCar {

    private boolean isSpeeding = false;

    private int maxSpeed;
    private int currentSpeed;
    private String color;
    BoogieSpeedListener defaultListener;

    public BoogieCar(int max, int cur, String color) {
        this.maxSpeed = max;
        this.currentSpeed = cur;
        this.color = color;
    }

    public synchronized void addSpeedListener(BoogieSpeedListener listener) {
        defaultListener = listener;
    }

    public void speedUp(int increment) {
        currentSpeed += increment;
        if (currentSpeed > maxSpeed) {
            processSpeedEvent(new BoogieSpeedEvent(maxSpeed, currentSpeed, color));
            isSpeeding = true;
        } else {
            isSpeeding = false;
        }
    }

    public boolean getSpeedingStatus() {
        return isSpeeding;
    }

    private void processSpeedEvent(BoogieSpeedEvent speedEvent) {
        defaultListener.speedExceeded(speedEvent);
    }
}

// BoogieCarMain.java
import java.util.ArrayList;

public class BoogieCarMain {

    public static void main(String[] args) {
        BoogieCar myCar = new BoogieCar(60, 50, "green");
        BoogieCar myCar2 = new BoogieCar(75, 60, "blue");
        BoogieCar myCar3 = new BoogieCar(65, 25, "pink");

        BoogieSpeedListener listener = new MySpeedListener();

        myCar.addSpeedListener(listener);
        myCar2.addSpeedListener(listener);
        myCar3.addSpeedListener(listener);

        myCar.speedUp(50); // fires SpeedEvent
        System.out.println(myCar.getSpeedingStatus());

        myCar2.speedUp(20);
        System.out.println(myCar2.getSpeedingStatus());

        myCar3.speedUp(39);
        System.out.println(myCar3.getSpeedingStatus());
    }
}

// BoogieSpeedListener.java
public interface BoogieSpeedListener { // extends java.util.EventListener
    public void speedExceeded(BoogieSpeedEvent e);
}

// MySpeedListener.java
public class MySpeedListener implements BoogieSpeedListener {
    @Override
    public void speedExceeded(BoogieSpeedEvent e) {
        if (e.getCurrentSpeed() > e.getMaxSpeed()) {
        System.out.println("Alert!  The " + e.getColor() + " car exceeded the max speed: " + e.getMaxSpeed() + " MPH.");
        }
    }
}

// BoogieSpeedEvent.java
public class BoogieSpeedEvent { // extends java.util.EventObject

    private int maxSpeed;
    private int currentSpeed;
    private String color;

    public BoogieSpeedEvent(int maxSpeed, int currentSpeed, String color) {
        // public SpeedEvent(Object source, int maxSpeed, int minSpeed, int currentSpeed) {
        // super(source);
        this.maxSpeed = maxSpeed;
        this.currentSpeed = currentSpeed;
        this.color = color;
    }

    public int getMaxSpeed() {
        return maxSpeed;
    }

    public int getCurrentSpeed() {
        return currentSpeed;
    }

    public String getColor() {
        return color;
    }
}
</code>
My question is:  While this code works, I would like the BoogieCar type to notify BoogieCarMain directly without me have to "poll" the BoogieCar type by having to invoke the getSpeedingStatus() method.
In other words, perhaps defining a variable in BoogieCarMain.java that changes whenever one of the three cars exceeds its predefined speed limit.  Is it possible to have the BoogieCar type set the variable?
Is there a cleaner way to do this?
TIA,
coson
Answer: Callbacks are ideal for this scenario.
<code>// BoogieCarMain provides a sink for event-related information
public void handleSpeeding(BoogieCar car) {
  System.out.println(car.getSpeedingStatus());
}

// MySpeedListener knows about an object that wants event-related information.
// I've used the constructor but an addEventSink method or similar is probably better.
public MySpeedListener(BoogieCarMain eventSink) {
  this.eventSink = eventSink;
}

// MySpeedListener handles events, including informing objects that want related information.
// You decide if the event is an appropriate type for the sink to know about.
// Often it isn't, and instead your listener should pull the relevant info out of the event and pass it to the sink.
public void speedExceeded(BoogieSpeedEvent e) {
  if (e.getCurrentSpeed() > e.getMaxSpeed()) {
    // I've taken the liberty of adding the event source as a member of the event.
    eventSink.handleSpeeding(e.getCar());
  }
}
</code>

Java Custom Event Handling


Multi-site Drupal install with sites on different ports using Apache ip-based hosting?

Question: In the past we've used name-based virtual hosting in Apache.  We recently converted websites to SSL and had to go the ip-based route.  As a result, we currently have an instance that is set up as follows:

www.domain.com using port 80
dev.domain.com using port 8080

Both use the same IP.  Is this scenario possible using Drupal multi-site functionality?  While we find that dev.domain.com works and reads the correct "dev" database (using the dev settings), it reads theme files from the "www" site instead which is not what we want.
Is the culprit the dev's htaccess file?  Apache is listening on 8080 and does use the proper DB settings, but just not the correct theme files.  One other note: browsing dev.domain.com:8080 gives an error: "The page isn't redirecting properly".  Should we just purchase a new IP address for the dev website, or would this still not help?
Any advice would be appreciated.  Thanks.
Answer: Have you tried specifying a port with your ServerName directive for each VirtualHost stanza?
Comment: I have not as I hadn't seen that in the examples Apache provides.  I suppose it couldn't hurt to try.
Answer: There might be a better solution if you want to pay for it.. Buy a wild card cert for *.domain.com
I think the prices are around 150-200 for a year.. That will clear up your issues..
If you don't want to do that.. you can edit your htaccess to be more generic to handle ports
Comment: Thanks.  I don't believe a wildcard cert is an option at the moment.  So you believe it's an .htaccess issue?
Answer: Turns out dev.domain.com was only looking at www.domain.com all along and reading the correct DB config file from there rather than dev.domain.com.  This ended up being an issue of .conf file order where dev.domain.com was being read after www.domain.com due to .conf naming scheme.  I renamed domain1-dev.conf to dev-domain1.com and all works great now as dev.domain.com is being read prior to www.domain.com which is like a catchall.
This had nothing to do with ports or anything outside of Apache's VirtualHost settings.  Here's what I used to help determine order read:
<code>$PATH_TO_APACHE_DIR/bin/httpd -S
</code>
Comment: More info here:

http://serverfault.com/questions/230271/virtualhost-not-directing-properly-based-on-domain-name


Anaconda doesnt launch since PyQt5

Question: I'm truly desperated...
Yesterday I installed PyQt5 to start working on spyder... but today when I wanted to start working again... spyder didn't open... then i tried to open anaconda with no sucess... I'd tried every "solution" I found on google to solve the problem without any sucess...
Can you help me throught the process?
I actually don't know that much about comands, I'm a begginer, I hope someone could help to fix this
I have tried to unistall the packege, re-install it, i update the conda... I uninstalled also anaconda and re-installed
Answer: I just had the same problem with my Anaconda Navigator not starting.  Finally traced the problem to pyqt5.  Of which I had version 5.15.9.  I uninstalled it entirely by putting this  in the Anaconda Powershell Prompt:
pip uninstall pyqt5

That got Anaconda Navigator running again for me.  Tho it's not  really a happy ending for me because I tried all the available prior versions and they broke Anaconda-Navigator. I like Jupyter Lab so I guess I'll have to open it direct or something if I want to use pyqt5.
BUT for YOU installing a prior version should work because when I run the tests it showed me a warning that Spyder doesn't work unless you're using the lowest version.  So try this code and see if it works:
pip install --upgrade pyqt5==5.12.3 --user

Well I hope that works for you.  Good luck!

Anaconda doesnt launch since PyQt5


Controller interceptor that process endpoint annotation in WebFlux

Question: My team is in the middle of migrating our Spring MVC extensions to WebFlux.
We've got a feature that lets our clients customize metric of controller method. To do that we've created our annotation that is processed by HandlerInterceptorAdapter.
The problem is that I can't see any equivalent of this in Spring WebFlux. I can't use WebFilter because Spring does not know yet which endpoint will be called. How can I implement that?
The closest workaround I found is to use RequestMappingHandlerMapping and somehow build a map of Map<String(path), HandlerMethod>, but this is cumbersome and error prone in my opinion.
Is there any better way to solve this?
Edit:
It goes like this
public class MeteredHandlerInterceptor extends HandlerInterceptorAdapter {

public MeteredHandlerInterceptor() {
}

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    // I save start time of method
    return true;
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    // I read endpoint method from the HandlerMethod, I apply any customisation by our custom @MeteredEndpoint annotation (for example custom name) and I save it in MeterRegistry
}
}

I haven't coded workaround yet because I didn't want to invest time in it, but I see that I could obtain HandlerMethod for path, but I'm not sure I will receive same HandlerMethod as I normally would when the controller is called.
Comment: Do you mind posting a little summary of the code for the original implementation so we can get an idea about what you were doing there? Please also post the workaround you're using
Answer: Maybe little bit late, but it can still be useful for someone...
I have not found an easy way to do that, the best I was able to create is a HandlerAdapter bean that intercepts handling in the following way:
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public HandlerAdapter handlerAdapter(RequestMappingHandlerAdapter requestMappingHandlerAdapter) {
    return new HandlerAdapter() {

        @Override
        public boolean supports(Object handler) {
            return handler instanceof HandlerMethod;
        }

        @Override
        public Mono<HandlerResult> handle(ServerWebExchange exchange, Object handler) {
            // your stuff here...
            // e.g. ((HandlerMethod) handler).getMethod().getAnnotations()...
            return requestMappingHandlerAdapter.handle(exchange, handler);
        }
    };
}

The idea is that this adapter is used for all HandlerMethod handlers (those are the ones created by collecting annotated methods from @Controllers) and delegates the handling to the RequestMappingHandlerAdapter (that would be used directly for HandlerMethod handlers in normal case, notice the @Order annotation here).
The point is you can put your code before/after the invocation of the handle method and you are aware of the method being invoked at this point.
Comment: Can you elaborate on this please? How is this supposed to be used with the webfilter? Thank you
Comment: Which WebFilter do you mean? The code snippet does not require any explicit WebFilter registration.
Comment: Oh okay. I thought this was somehow supposed to be used with a webflux webfilter (like the one in the answer below from Ivan.
Answer: Solution:
     @Component
 class AuditWebFilter(
      private val requestMapping: RequestMappingHandlerMapping
 ): WebFilter {

      override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {
           // if not to call - then exchange.attributes will be empty
           // so little early initialize exchange.attributes by calling next line
           requestMapping.getHandler(exchange)

           val handlerFunction = exchange.attributes.get(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE) as HandlerMethod
           val annotationMethod = handlerFunction.method.getAnnotation(MyAnnotation::class.java)

           // annotationMethod  proccesing here
      }
 }


Forecasting with holiday dummy variables

Question: I have an example of call center data for 2013. There are 261 days of data (excluding weekends).
For 2013, I have included a holiday dummy variable (holiday) for the days where there were no stats.
For 2014, I have also included a future holiday dummy variable (holidayf).
My objective is to assess how accurate this code is in making predictions for 2014.
I tried this code below but when looking at fc$fitted, the forecasts don't seem to be correct. For the first 8 days of January 2014, it forecasts the exact number of calls that were received in the first 8 days of January 2013, which seems wrong. Also, where there is a public holiday in 2014, the future forecast for that day predicts a normal to high volume of calls, so it seems that the forecast is using the holiday variable and not the holidayf variable.
library(forecast)
y <- ts(calls,frequency=5)
z <- fourier(ts(calls,frequency=261),K=12)
zf <- fourier(ts(calls,frequency=261),K=12,h=261)
fit <- auto.arima(y,xreg=cbind(z,holiday))
fc <- forecast(fit,xreg=cbind(zf,holidayf),h=261)
plot(fc)

Data:
calls <-
  c(0,145,175,129,266,219,156,184,167,241,218,194,192,162,236,219,212,191,162,216,
  235, 218,180,150,245,209,210,211,151,236,197,217,140,164,200,156,152,153,141,224,178,
  159,153,137,207,173,197,213,206,305,284,248,289,269,359,333,257,0,244,325,292,267,
  206,0,0,360,261,327,284,385,377,317,327,271,372,191,320,268,261,376,320,280,251,200,
  200,200,0,236,161,259,200,190,166,174,225,228,202,201,155,241,207,199,179,178,249,
  243,230,177,181,264,250,219,204,178,244,249,185,184,164,0,253,216,217,165,170,185,
  175,160,148,231,223,196,162,149,228,213,190,177,139,212,205,221,190,170,196,210,
  198,192,131,220,185,199,153,166,240,176,200,145,0,255,202,220,220,181,250,171,164,
  142,118,179,197,167,130,124,180,214,203,153,140,161,200,191,159,141,227,170,166,
  166,106,131,0,176,156,109,196,175,175,174,161,230,191,159,150,91,180,188,173,157,
  107,193,172,172,172,116,195,183,169,146,125,208,160,160,177,128,191,176,149,175,
  136,217,162,178,130,99,158,154,135,146,106,155,148,119,137,96,161,106,114,139,84,
  0,97,95,82,65,59,23,0,0,48,83,48)

holiday <- c(1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
             0,0,0,0,0,0,0,0,0,0,0,0 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
             0,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
             0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
             0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
             0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,
             0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,
             0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
             0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,
             0,0,0,1,1,1,0,0,0)

 holidayf <- c(1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
             0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
             0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,
             0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
             0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
             0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
             0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,
             0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
             0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,
             0,0,0,0,1,1,0,0,0)

Answer: Read ?forecast.Arima closely. fc$fitted does not give the forecast, it gives the in-sample fits. These are identical to the history at the beginning, because the rather complex ARIMA(2,0,2)(1,0,2)[5] model that auto.arima() finds needs an amount of differencing to fit the seasonality.
Use fc$mean to extract the point forecasts. Note that the graph also shows forecasts that are appreciably different from the history. Notably, you get negative values. Given that all historical values are nonnegative, you may want to think about constraining your forecasts in some way.
Comment: `auto.arima()` handles missing values seamlessly. The estimation is done in state space so that missing values are handled via the Kalman filter algorithm.
Comment: Hi Stephan, thanks for such a quick response. Thank you for the clarity on fc$fitted. How would I go about constraining it? I thought the negative values were a consequence of the public holiday.
Comment: Yes, the negative values are due to the holiday effect. But do negative values make sense for the call center data you are forecasting? You can simply truncate forecasts at zero if they are negative. In principle, you could work on the log scale, but the zeros in your history make that problematic (unless you first add a small number and subtract it out afterwards).
Comment: I agree with you on all those points. I think your suggestion to truncate to zero is the easiest. Lastly, what would I do if there was no stats for a day, like an NA. How would the code change? I think putting a zero is not advisable?
Comment: ARIMA has major conceptual difficulties with missing data. I actually don't know whether and how `auto.arima()` deals with that. You have so much data here that perhaps you can deal with (few) missings very simply, by taking the average of seasonally neighboring points (i.e., points +/- 5 steps away) before modeling.
Comment: Thanks Stephan, you have been tremendously helpful. Really appreciate it. The feedback has been excellent. Kind regards,
Comment: @user43207: feel free to *accept* my answer if you feel it sufficiently answers your question, by clicking on the little check mark underneath the vote count for the answer. You get rep and I get rep from accepted answers. Everyone wins ;-)


Construction of a pentagon in which an angle bisector at a certain vertex is also a perpendicular bisector of a side opposite to that vertex

Question: Construct a pentagon $ABCDE$ if  lengths of its sides are $a,b,c,d$ and $e$ ($|AB|=a,|BC|=b,...$), and the bisector of the angle at vertex $D$ is also the perpendicular bisector of $AB$.
I know that $D\in f$, $C\in c_1=c(B,b)$ and $E\in c_2=c(A,e)$.

How do I find the exact position of point $D$?
Answer: Let $x=AD=BD$. By the triangular inequality we have the constraints:
$$
|b-c|<x<b+c
\quad\text{and}\quad
|d-e|<x<d+e.
$$
For the perpendicular bisector of $AB$ to be also the bisector of $\angle CDE$ we must have $\angle ADE=\angle BDC$. By the cosine rule this implies:
$$
{d^2+x^2-e^2\over 2dx}=
{c^2+x^2-b^2\over 2cx},
$$
that is:
$$
x^2={d(c^2-b^2)-c(d^2-e^2)\over c-d}.
$$
Of course this gives a solution only if $x>a/2$ and if the above constraints are satisfied.
Example. Setting
$$
a=4,\quad
b=7,\quad
c=4,\quad
d=6,\quad
e=4
$$
we get $x=\sqrt{139}$, which is larger than $b+c$. Hence no solution exists.
Comment: @kaykay You are right: I did'n notice it had to be an angle bisector. I'll delete my answer.
Comment: @kaykay If you don't understand the answer, you should not give it the green check mark.
Comment: @kaykay Instead of deleting I edited my answer, to take into account the second request.
Comment: @Intelligentipauca Sir, it is my pleasure to inform you that I have successfully passed the  Construction methods in geometry course. I am extremely grateful for each and every one of your comments over the past few months. They helped me a lot and gave me hope when it was the most difficult. I often couldn't see the solution to the problem, even when it was literally trivial. You still took the time out of your day to kindly answer all of my questions. The most important thing is that I went from a total beginner to a lover of Euclidean geometry and now I see its true merits.Thank you!!❤
Comment: Sir, I am very sorry to bother you but I just have to ask this.
In order to construct $ABCDE$ I chose the following lengths:
$a=4$,
$b=7$,
$c=4$,
$d=6$,
$e=4$.

Now $|b-c|<AD<b+c=3<AD<11$ and
$|d-e|<AD<d+e=2<AD<10$. So I chose $|AD|$ to be 5.  I do end up with a pentagon with its sides being of required lengths and $D$ lying on line $f$, but the obtained pentagon doesn't satisfy the condition that $f$ has to also bisect $\angle EDC$. I added the picture of all this to my original post. I suppose I misunderstood your instructions. Can you please tell me what I'm doing wrong?
Comment: Does this answer consider the bisector of angle $D$?
Comment: @DavidK Or maybe...just maybe.. I can give the green check mark to whomever I please? I appreciate every single answer I get even if it's not fully correct/clear to me. Besides, nothing intelligenti pauca stated is mathematically incorrect. already had a bad experience with some guy named David on here. Are all Davids on this forum nosy or it's just me having bad luck?
Comment: @Intelligentipauca Awesome!! Thanks for solving it in a way even us newbies can understand, means a lot
Answer: Let $E_{1}$ be the projection of $E$ onto $f$, and define $C_{1}$ similarly. Because $f$ bisects $\angle CDE$, $\triangle DC_{1}C\sim\triangle DE_{1}E$.
Let $\angle CDE = 2\theta$. Then, $DE_{1} = d\cos(\theta)$ and $DC_{1} = c\cos(\theta)$. Also, $EE_{1}=d\sin(\theta)$ and $CC_{1}=c\sin(\theta)$.
Let $A_{1}$ be the projection of $A$ onto $EE_{1}$ and let $B_{1}$ be the projection of $B$ onto $CC_{1}$. We have $EA_{1} = d\sin(\theta)-\frac{a}{2}$, so $AA_{1} = \sqrt{e^{2}-\left(d\sin(\theta)-\frac{a}{2}\right)^{2}}$ by the Pythagorean Theorem. Similarly, $BB_{1}=\sqrt{b^{2}-\left(c\sin(\theta)-\frac{a}{2}\right)^{2}}$.
Letting $M$ be the midpoint of $AB$, note that $ME_{1} = AA_{1}$ and $MC_{1} + BB_{1}$. However, we must have $ME_{1}+DE_{1} = MC_{1}+DC_{1}$. Thus:
$$d\cos(\theta)+\sqrt{e^{2}-\left(d\sin(\theta)-\frac{a}{2}\right)^{2}} = c\cos(\theta)+\sqrt{b^{2}-\left(c\sin(\theta)-\frac{a}{2}\right)^{2}}$$
This equation can be numerically solved for $\theta$ (possible analytically as well, although it may be too messy to be worth it). Then, $MD = d\cos(\theta)+\sqrt{e^{2}-\left(d\sin(\theta)-\frac{a}{2}\right)^{2}}$.
Answer:
Defining $\alpha$ and $\beta$ as the exterior angles at $A$ and $B$, and $\theta$ as the complement of the half-angle at $D$, and $a_2:=a/2$ for convenience, "all we have to do" is solve the system
$$\begin{align}
d \cos\theta &= a_2 + e \cos\alpha \tag1\\
c \cos\theta &= a_2 + b \cos\beta \tag2\\
d \sin\theta + e \sin\alpha &= c \sin\theta + b \sin\beta \tag3
\end{align}$$
The special case of $c=d$ clearly implies $b=e$ and $\alpha=\beta$, making the pentagon symmetric about the angle/perpendicular bisector, although its shape is not uniquely determined.
Otherwise ... A couple of rounds of squaring of $(3)$ will give us even powers of $\sin\alpha$ and $\sin\beta$, which we can replace with powers of $1-\cos^2\alpha$ and $1-\cos^2\beta$; substituting $\cos\alpha$ and $\cos\beta$ from $(1)$ and $(2)$, and simplifying, gives this quadratic in $\cos\theta$:
$$\begin{align}
0 &=\phantom{-}\;4\cos^2\theta\;(c - d) (d (b^2 - c^2) - c (e^2 - d^2)) \\
&\quad-4 \cos\theta\;a_2 (c - d) ((b^2 - c^2) - (e^2 - d^2))\\
&\quad-4 a_2^2 (c - d)^2 - (b + c - d - e) (b - c + d - e) (b + c - d + e) (b - c + d + e)
\end{align}$$
Solving gives
$$\begin{align}
\cos\theta &= \frac{a_2 (c - d) (b^2 - c^2 + d^2 - e^2)\pm \sigma}{2p (c - d)} \\[8pt]
\sigma &:= \sqrt{ q(c - d)   \left(a_2^2(c-d) + p\right)} \\[2pt]
p &:= d(b^2-c^2)-c(e^2-d^2) \\[4pt]
q &:= (b + c - d - e)(b + c - d + e)(b - c + d + e)  (b - c + d - e)
\end{align}$$
And then, from $(1)$ and $(2)$,
$$\begin{align}
\cos\alpha &= \frac{a_2(c-d)((c-d)(e^2-d^2)-p)\pm d\sigma}{2ep(c-d)} \\[4pt]
\cos\beta  &= \frac{a_2(c-d)((c-d)(b^2-c^2)-p)\pm c\sigma}{2bp(c-d)}
\end{align}$$
where the $\pm$ represents the same sign throughout.
Of course, $\sigma$ must be real for a solution to exist. Whether one or the other (or both, or neither) states of the "$\pm$" leads to an extraneous solution is left as an exercise to the reader. $\square$


Mysql determine if update found row even if not changed

Question: I want to be able to return the number of rows found after an update even if the row did not change.  I would have thought that I  can use row_count(), however, that returns the number of rows that actually changed. So for example if I do an update on one row and the row exists but does  not change  then  row_count()  returns 0. It also can return 0 if the row does not exist. I am  particularly interested in the  case where the update uses a unique key and hence either  updates  0 rows or 1 row.
Is there  an easy  way to get the found row count after an update?
Some of the answers below describe how to do this in using php or  java, but how can it be done in a stored procedure itself (in other words if java and php is  not used)
Comment: Why not run a query before the update and count the number of rows that match the condition?
Comment: Running a query before should work in mysql, but I wanted to avoid running an additional query.  Also if autocommit is true then the row  could be deleted before the update, so a transaction would need to be started, then the query would block subsequent updates.
Answer: It is available in the mysqli_real_connect options
MYSQLI_CLIENT_FOUND_ROWS  return number of matched rows, not the number of affected rows
For java,
Statement.executeUpdate() or execute() followed by getUpdateCount() will return the number of rows matched, not updated, according to the JDBC spec.
For Stored Procedure call in Java you can use like,
public static void executeUpdateStoredProcedure(Connection con) {
    try {
          CallableStatement cstmt = con.prepareCall("{calldbo.UpdateTestTable(?, ?)}");
          cstmt.setString(1, "A");
          cstmt.setInt(2, 100);
          cstmt.execute();
          int count = cstmt.getUpdateCount();
          cstmt.close();

          System.out.println("ROWS AFFECTED: " + count);
    }
    catch (Exception e) {
          e.printStackTrace();
    }
}

Comment: I am not using Php. Want  to do this either in a stored procedure or using java jdbc.  I wonder what that does under the covers?
Comment: Yes you are correct about the java. I just tested it.  Still wondering how to do this in a stored procedure.
Comment: I upticked it, but I  am still waiting to find out how to  do it in the  stored procedure itself.  In other words  calling select row_count() after doing the update in the  stored procedure
Answer: I'm pretty sure the following would return a variable with the value:
update t
    set col = if(@rn := coalesce(@rn, 0) + 1, newval, newval)
    where . . .;

The if() function needs to be evaluated before the update, regardless of whether the value is changing.
Comment: As far as I know MySQL will not physically change anything if the old and new value of a column are identical. I don't think that "hiding" the value behind an expression will work around that.


How can I reverse an animation in SceneKit?

Question: I'm learning how to use the animation functions in SceneKit using the Fox 2 example (you can find it here https://developer.apple.com/videos/play/wwdc2017/604/ and here https://developer.apple.com/library/content/samplecode/scenekit-2017/Introduction/Intro.html) and I have a question:
How can I reverse an animation?
I searched in the official documentation (that is very very poor) and online but it seems that there isn't a built-in function that can reverse an animation.
I found three interesting parameters:

.autoreverses: "when true, the object plays backwards after playing forwards. Defaults to NO"
.fillsBackward: "when true, the animation is active before its active duration and evaluates to its start value. Defaults to NO"
.fillsForward: "when true, the animation remains active after its active duration and evaluates to its end value. Defaults to NO"

The problem is that the first parameter doesn't do what I want and when I use the other two parameters, nothing happens: S
This is how I use these parameters:

Where I load the animation in the character model
let spinAnimation = Character.loadAnimation(fromSceneNamed: "Art.scnassets/character/max_spin.scn")
spinAnimation.animation.isRemovedOnCompletion = false
spinAnimation.speed = 1.5
spinAnimation.stop()
model!.addAnimationPlayer(spinAnimation, forKey: "spin")

Where I create the character and start the animation
character2 = Character.init(scene: scnScene!)
character2?.model.position = SCNVector3(x: 0.15, y: -0.3, z: 0)
scnScene!.rootNode.addChildNode(character2!.node!)
character2?.model.animationPlayer(forKey: "spin")?.animation.fillsForward = true //or fillsBackward or autoreverses
character2?.model.animationPlayer(forKey: "spin")?.play()

Did I misunderstand .fillsBackward and .fillsForward? Is there an exhaustive and updated documentation of SceneKit?
Comment: "Is there an exhaustive and updated documentation of SceneKit?", no. Unfortunately. Try making the animation speed a negative number.
Comment: Please post the code that you're having a problem with.  We can't help you debug something if we don't know what you're doing.
Comment: It works! So...what's the meaning of fillsBackward and fillsForward?
Answer: I don't know how to close this question since the problem is solved so:
To reverse an animation in SceneKit, simply set the speed to a negative value (ex: -1)
Comment: Works flawlessly. Apple could have really mentioned that in a short sentence.
Comment: I was searching for this solution an I thought the same but I did not dare to try it, thanx to you, it works like magic :)


Making new variable for a theme function shows an error notice

Question: I am trying to make a new variable for a theme whose name is ntheme. I have defined the following function in template.php.
function ntheme_gnu_preprocess(&$variables) {
  $variables['disclaimer'] = t('Comments are unaythorized. The views expressed are those of the comment author.');
}

I used $disclaimer in the comment-wrapper.tpl.php template file.
<div id="comments" class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if ($content['comments'] && $node->type != 'forum'): ?>
    <?php print render($title_prefix); ?>

<?php print t('Comments'); ?>

    <?php print render($title_suffix); ?>
  <?php endif; ?>
  <?php print render($content['comments']); ?>
  <?php if ($content['comment_form']): ?>

<?php print t('Add new comment'); ?>

    <?php print render($content['comment_form']); ?>
  <?php endif; ?>

<?php print $disclaimer; ?>

I get the following warning.

Notice: Undefined variable: disclaimer in include() (line 39 of C:\wamp\www\drupal\sites\all\themes\ntheme\templates\comment-wrapper.tpl.php).

What am I doing wrong?
Comment: your theme is is `ntheme` then use `ntheme_preprocess`
Comment: Try out `ntheme_preprocess_page`
Answer: You should use THEME_preprocess_comment_wrapper(&$variables) to alter comment wrapper variables.
Answer: Each template file has its own preprocess/process functions. If <theme> is the theme identifier for the theme function, then <module_name>_preprocess_<theme>(), <theme_name>_preprocess_<theme>(), <module_name>_process_<theme>(), and <theme_name>_process_<theme>() are the function names for the preprocess/process functions.
In this case, ntheme_gnu_preprocess() would not be a preprocess function, since it doesn't follow the schema Drupal adoptes for preprocess/process functions: ntheme_gnu is not the short name of the theme.
ntheme_preprocess(&$variables, $hook) would be invoked, but for every theme function / theme template used from Drupal; if you need to use the preprocess function just for the comment-wrapper.tpl.php template file, then you should use ntheme_preprocess_comment_wrapper().


Which is correct note?

Question: On measure 22 at 1:30-1:31, she hit an F instead of a D as in the score.  So, which is correct?
It is in this YouTube video of an arrangement of "Chi Mai" from Le Professionel by Ennio Morricone.
Answer: Both and neither is correct, but D is the best choice.
This is the YouTuber's own arrangement of the original piece. The original piece is a half-step lower, doesn't include arpeggios at this point in the music, and uses a different inversion of the chord (here, D would be the lowest note instead of G). So in that sense, the whole thing is wrong — if the goal were to most accurately reproduce the original.
This being an arrangement, however, it's clear the arranger's goal was to give the sense of the original without being slavish to it. At that level, both D and F are fine to play, because both are part of the underlying chord. So at that level, the arranger can play either one — it's not at all unusual for a performer of their own arrangement to make changes on the fly.
But since she wrote D and played F, clearly one is what was intended and one is not, but short of writing to the arranger to ask, there's no way to know which is "correct".
The best choice, however, is to play the D. The F is already in the melody, so the D fills out the chord and avoids doubling a dissonant pitch. The D is also a prominent pitch in the original (the bass note), so there's a good case to be made there as well that it should be present in the arpeggio.

Which is correct note?


Why L'hopital's rule only proved for indetermined forms?

Question: In this proof of L'hopital's rule, $\lim\limits_{x\to a}\, f(x)=0$ and $g(x)=0$ seems have no role to paly.
So what goes wrong when the limits mentioned before are not equal to $0$?
(My guess is that you can't assume that "f(a)=g(a)=$0$" without making the functions discontinuous when those limit are not equal to $0$. Is that right?)
thanks!
Comment: your guess is correct!
Answer: The proof requires an application of  Rolle's theorem to
$$h(x) = f(x) - \frac{f(b)}{g(b)}g(x).$$
Since $h(b) = 0$, this requires $h(a) = 0$ for all $b >a$.  This is satisfied if $f(a) = g(a) = 0$ either outright or by continuous extension using $f(x),g(x) \to 0$ as $x \to a+$.


How to combine different node in single views

Question: I'm currently doing recruitment system by using drupal 7..
First..
In my system, applicant need to fill up the "Applicant Profile" (node) before they can apply for the job.
Second..
i am using flag module..if applicant want to apply the job, they must flag the job..after that, they need to fill up their "name" and make some "pitch" (Flagging form)..
Third..
In my views, i add "flag" at relationship so i can add the flagging form details in the fields.At filter criteria, i add the "content:type (Applicant Profile)"
My question..
how i want to combine the details in flagging form and applicant profile in single views?
because currently the views fields only can display the flagging form details..
i already add two different "content:type" at filter criteria. but it does't work..it only show the details on one content type only..
Thank You in advance..
Answer: For Applicant Profile use Profile 2 module instead of node. Then when you create the View of Job List, add relation to Flags, Content: Author and User:Profile, in that way you will get all the fields you need.
Answer: Click the Filter for Content Type and checkbox the other content type you need.
Comment: i already done that..but still cannot..because the details is from flagging form. i want to get the applicant profile details. the nid for this views is referring to the job that applicant flag..
Comment: try an or filter group and add has field


$f(z)=\sum_{k=0}^\infty a_kz^{k}$ with $\sum |a_k|<\infty$ is of bounded variation on circle $|z|=1$

Question: Let $f(z)=\sum_{k=0}^\infty a_kz^{k}$ be a power series. Show that if $\sum |a_k|<\infty$, then $f(z)$ is of bounded variation on every radius of the circle $|z|=1$. (If, e.g., the radius is $0\leq x\leq 1$ and the $a_k$ are real, then $f(x)=\sum a_k^+x^k-\sum a_k^-x^k$).  Problem copied from Wheeden & Zygmund Measure and Integral.
For example working in general with $a_k\in \mathbb{C}$, for all $k$, I was able to prove that $$S_\Gamma=\sum_{j=1}^m\left|f(z_j)-f(z_{j-1})\right|<M$$ for any partition $\Gamma=\{z_0,\cdots,z_m\}$ of the following radius: line joining $0$ and $1$, line joining $-1$ and $0$, line joining $0$ and $i$, line joining $-i$ and $0$. The interesting part, occurs when the radius is a line joining $0$ and other point in the circle $|z|=1$, let $z_m=x_m+iy_m$ be such point. Consider a partition $\Gamma=\{z_0,\cdots,z_m\}$ of this radius, where $z_j=x_j+iy_j$ and $z_0=0+i0$. If we can make $S_\Gamma<\infty$, we are done
$$S_\Gamma=\sum_{j=1}^m|f(z_j)-f(z_{j-1})| = \sum_{j=1}^m\left|\sum_{k=0}^\infty a_k\left((x_j+iy_j)^k-(x_{j-1}+iy_{j-1})^k\right)\right| = \sum_{j=1}^m\left|\sum_{k=0}^\infty a_k\sum_{l=0}^k \binom{k}{l}\left( (x_j)^{k-l}(iy_j)^k-(x_{j-1})^{k-l}(iy_{j-1})^k \right)\right|\leq $$
$$ \leq \sum_{j=1}^m \sum_{k=0}^\infty |a_k|\sum_{l=0}^k \binom{k}{l}\left| x_j^{k-l}y_j^k-x_{j-1}^{k-l}y_{j-1}^k \right|$$ since $|i^k|=1$.
Interchanging the order of summation we have $$S_\Gamma \leq  \sum_{k=0}^\infty |a_k|\sum_{l=0}^k \binom{k}{l}\sum_{j=1}^m\left| x_j^{k-l}y_j^k-x_{j-1}^{k-l}y_{j-1}^k \right| = \sum_{k=0}^\infty |a_k|\sum_{l=0}^k \binom{k}{l}x_m^{k-l}y_m^k =$$ $$= \sum_{k=0}^\infty |a_k|(x_m+y_m)^k  $$ in order to get convergence is enough that $|x_m+y_m|^k\leq 1$, since the initial condition is $|z_m|=1$ we have $x_m^2+y_m^2=1$. Replacing we get $|x_m+y_m|=|x_m+\sqrt{1-x_m^2}|$, but the function $|x+\sqrt{1-x^2}|>1$ on $0<x<1$. For this reason I cannot verify the convergence of the serie, so I can't conclude if it's of bounded variation.
Is my bounding approach too excessive? so that loses its property of convergence?
I think the problem could be the last two equalities, since I'm assuming $\left| x_j^{k-l}y_j^k-x_{j-1}^{k-l}y_{j-1}^k \right| = x_j^{k-l}y_j^k-x_{j-1}^{k-l}y_{j-1}^k $ which could be something that is not true all the time. Any comment will be appreciated.
Answer: Your approach is too complicated. It suffices to consider the case of a ray joining $z=0$ and $z=1$:
Let $\Gamma=\{z_0,\cdots,z_m\}$ be a partition of the ray joining $z=0$ and $z=e^{i \alpha}$ on the unit circle. Then $z_j = x_j e^{i \alpha}$ with real numbers
$$
 0 = x_0 < x_2 < \cdots < x_m = 1 \, .
$$
Also
$$
\sum_{j=1}^m\left|f(z_j)-f(z_{j-1})\right| = \sum_{j=1}^m\left|F(x_j)-F(x_{j-1})\right|
$$
where $F$ is defined as $F(z) = \sum_{n=0}^\infty a_n e^{i n\alpha} z^n$.
The coefficients of $F$ satisfy the same condition: $ \sum_{n=0}^\infty |a_n e^{i n\alpha}| =  \sum_{n=0}^\infty |a_n| < \infty$. This shows that it suffices to show that $f$ is of bounded variation on the interval $[0, 1]$.
For a proof of that case, see for example Show that $\,f(x) = \sum_{n=0}^\infty a_nx^n$, for $x \in [0,1]$, is of bounded variation.
Comment: could you explain why doing $e^{i\alpha}$ we have all cases? Is it like an angle?
Comment: @Valerin: Yes, every point on the unit circle can be written as $e^{i \alpha}  = \cos(\alpha) + i \sin(\alpha)$ with some real $\alpha$ between $0$ and $2 \pi$. – You can also write $z_j = x_j \cdot z$ with $|z|=1$ if you prefer.


Why cloning carousel-item not working perfectly?

Question: I was trying to make a carousel that has multiple image in 1 slide. The thing is, when the image reached at 4, all 3 other image going to hide forcely. Special credit to this owner Bootstrap Codply, I found this open source here Stackoverflow.
This is the code I mixed up so far:

let items = document.querySelectorAll('.multiple-carousel .items')

items.forEach((el) => {
    const minPerSlide = 4
    let next = el.nextElementSibling
    for (var i = 1; i < minPerSlide; i++) {
        if (!next) {
            // wrap carousel by using first child
            next = items[0]
        }
        let cloneChild = next.cloneNode(true)
        el.appendChild(cloneChild.children[0])
        next = next.nextElementSibling
    }
})
@media (max-width: 767px) {
    .multiple-carousel .carousel-inner .carousel-item > div {
        display: none;
    }
    .multiple-carousel .carousel-inner .carousel-item > div:first-child {
        display: block;
    }
}

.multiple-carousel .carousel-inner .carousel-item.active,
.multiple-carousel .carousel-inner .carousel-item-next,
.multiple-carousel .carousel-inner .carousel-item-prev {
    display: flex;
}

/* medium and up screens */
@media (min-width: 768px) {

    .multiple-carousel .carousel-inner .carousel-item-end.active,
    .multiple-carousel .carousel-inner .carousel-item-next {
        transform: translateX(25%);
    }

    .multiple-carousel .carousel-inner .carousel-item-start.active,
    .multiple-carousel .carousel-inner .carousel-item-prev {
        transform: translateX(-25%);
    }
}

.multiple-carousel .carousel-inner .carousel-item-end,
.multiple-carousel .carousel-inner .carousel-item-start {
    transform: translateX(0);
}

picture 1

picture 2

picture 3

picture 4

When I tried to edit the transform it makes more mess, same with const minPerslide where should I edit it?
Comment: Can u share a screenshot what exactly is happening? I have already answered but i will delete it if the code doesn't work!
Answer: I think this code works:

let items = document.querySelectorAll('.carousel .carousel-item')

items.forEach((el) => {
    const minPerSlide = 4
    let next = el.nextElementSibling
    for (var i=1; i<minPerSlide; i++) {
        if (!next) {
            // wrap carousel by using first child
            next = items[0]
        }
        let cloneChild = next.cloneNode(true)
        el.appendChild(cloneChild.children[0])
        next = next.nextElementSibling
    }
})
    @media (max-width: 767px) {
    .carousel-inner .carousel-item > div {
        display: none;
    }
    .carousel-inner .carousel-item > div:first-child {
        display: block;
    }
}

.carousel-inner .carousel-item.active,
.carousel-inner .carousel-item-next,
.carousel-inner .carousel-item-prev {
    display: flex;
}

/* medium and up screens */
@media (min-width: 768px) {

    .carousel-inner .carousel-item-end.active,
    .carousel-inner .carousel-item-next {
      transform: translateX(25%);
    }

    .carousel-inner .carousel-item-start.active,
    .carousel-inner .carousel-item-prev {
      transform: translateX(-25%);
    }
}

.carousel-inner .carousel-item-end,
.carousel-inner .carousel-item-start {
  transform: translateX(0);
}
<!DOCTYPE html>

<title>Page Title</title>
<link href="https://email@example.com/dist/css/bootstrap.min.css" rel="stylesheet">

Bootstrap Multi Slide Carousel

Slide 1

Slide 2

Slide 3

Slide 4

Slide 5

Slide 6

advances one slide at a time

Good Luck :)


Calculating the annualized return of the VIX

Question: I need to calculate the annualized return of the VIX and it's Futures by using daily data from six and a half years.
I tried to use the R-function Return.annualized from the PerformanceAnalytics-package:
 Return.annualized(vix,scale=252,geometric=TRUE)

But all R shows is "INF" as a result. Am I wrong by just letting the daily index values run through this?
Thanks for your help!
Answer: Your data must be corrupted. Can you run summary or hist on them to see whether there are NAs or prices that are not plausible?
The problem is that you work on prices. You should work on the returns of VIX:
What about this:
library(PerformanceAnalytics)
library(xts)
data = read.table("clipboard",header=TRUE)

vix = xts(data$VIX, order.by = as.Date(data$Date,"%d.%M.%Y")  )
vix.ret = Return.calculate(vix, method = "discrete")
Return.annualized(vix.ret,scale=252,geometric=TRUE)

Comment: There are no missing values and the index ranges from 10.32 to 52.65.
Comment: Can you post your data? e.g. upload it to gdrive and share the link?
Comment: https://drive.google.com/file/d/0B-j4esZ-O8IbSHNiV3gxSWo0NEU/view?usp=sharing
Comment: I got the data. Please post more code. You have to construct an xts object. How do you do that?
Comment: I just put the VIX and Date into an xts object:
    vix <- xts(vixts, order.by=datevix)
Comment: There is no column name "vixts" ... please post your code.
Comment: Sorry, I converted the VIX column into a time series and from this one if have made the xts object:
vixts <- ts(vixdata$VIX)
vix <- xts(vixts, order.by=datevix)
Return.annualized(vix,scale=252,geometric=TRUE)
Comment: I edited my answer. Please have a look


Cannot interrupt running operation in vba when command button is being pressed

Question: I researched net, but I haven`t found a solution yet and I am still grappling with the following problem:
In vba UserForm I have two command buttons:

1st one ('Run Operation') runs an operation that could take around 30 minutes.
2nd one ('Cancel') was created to interrupt the operation that was triggered off by 'Run Operation'

When I press 'Run Operation' button I cannot press neither 'Cancel' nor 'x' to stop the running operation and I have to wait until the operation finishes, thus the userform is freezed for around 30 minutes.

Code looks more or less like this:
private Sub Cancel_Click()
   Cancel = True
End Sub

private Sub RunOperation_Click()
   RunOperation.Enabled = False
   Call Macro()
End Sub

private Sub Macro()
   For i = 1 to 100
   'do stuff here
      If Cancel = True Then
      RunOperation.Enabled = True
      Exit Sub
   Exit If
   Next i
End Sub

What`s more both buttons have TakeFocusOnClick set to False.
I`d be grateful for any ideas.
Thanks in advance !
Comment: Where it says `'do stuff here`, insert the command `DoEvents` (all one word).
Answer: The DoEvents method is your friend here.
What's happening is that since VBA is single-threaded (i.e. only one macro can be running at a time) it's not possible for events (in your case Cancel_Click()) to trigger. The DoEvents method essentially pauses the code wherever it appears to see if any other events have been triggered and resolves them before code execution is resumed.
Try this, it should work:
Private Sub Macro()
    For i = 1 To 100
       'do stuff here
       DoEvents '<~~ Insert this line here
       If Cancel = True Then
           RunOperation.Enabled = True
           Exit Sub
       End If
    Next i
End Sub


Meaning of CsvProvider error "The given key was not present in the dictionary" when trying to load sample file?

Question: I am having trouble loading the csv files with FSharp.Data csv provider provided by fslab, including the sample adwords.csv file.
What does this error below mean? Also, when I hover over the code in the Visual studio editor it mentions that "The given key was not present in the dictionary"
Problem example:
#load "packages/FsLab/FsLab.fsx"

open System.IO
open FSharp.Data

"adwords.csv"
|> File.ReadAllLines

let test = CsvProvider<"adwords.csv">.GetSample()

The output:
>
val it : string [] =
 [|"Criteria ID,Name,Canonical Name,Parent ID,Country Code,Target Type,Status";
    "1000010,Abu Dhabi,"Abu Dhabi,Abu Dhabi,United Arab Emirates",9041082,AE,City,Active";
"1000011,Ajman,"Ajman,Ajman,United Arab Emirates",9047096,AE,City,Active";
"1000012,Al Ain,"Al Ain,Abu Dhabi,United Arab Emirates",9041082,AE,City,Active";
"1000013,Dubai,"Dubai,Dubai,United Arab Emirates",9041083,AE,City,Active";
"2004,Afghanistan,Afghanistan,,AF,Country,Active"|]
>
>System.MethodAccessException: Attempt by method '<StartupCode$FSI_0007>.$FSI_0007.main@()' to access method 'FSharp.Data.Runtime.CsvFile`1<System.__Canon>.Create(System.Func`3<System.Object,System.String[],System.__Canon>,
at <StartupCode$FSI_0007>.$FSI_0007.main@() in C:\test.fsx:line 11
Stopped due to error

I ran into this problem with my own files, so I grabbed this sample file from here: https://raw.githubusercontent.com/fsharp/FSharp.Data/master/tests/FSharp.Data.Tests/Data/Adwords.csv
Debug info:

If I delete the FSharp.Data library folder (v 2.3.0) and replace with version 2.2.5 it works correctly with no error.
If I don't use the FsLab.fsx script and instead use
#I "packages/FSharp.Data/lib/net40
 #r "FSharp.Data.dll"

then everything works.
The path to the FsLab.fsx script is correct, it runs when I send the line to fsi.
The F# version is 14.0.23413.0.
The version of FSharp.Data downloaded by FSlab is FSharp.Data.2.3.0.
I have no other references in the .fsx script.
I am using Visual Studio Community edition 14.0.24720.00 Update 1.
.NET version 4.6.01038
I am realizing now that I am not getting the popup asking if I want to allow the .dll like I think I used to get when I used this before.
Comment: The important issue is FSharp.Data.2.2.5 vs. 2.3.0. Switching these out fixes my problems.
Comment: Have you tried to declare a type for the CSV content?

`type MyRecords = CsvProvider<"adwords.csv">`
 `let test = MyRecords.GetSample()`
Comment: Yes. It gives a similar error.
Comment: Canonical Name column seems to be displayed strangely by FSI. Maybe it is the cause. Afghanistan doesn't provide any value for Parent ID.  If you will place there 0 is there any better?
Comment: Doesn't fix on my end. The file is one of the test files from the github repository.
Comment: Is it possible the quotes around Canonical Name are throwing it off?  It may be reading each line as 3 separate lines.
Comment: It shouldn't because this is specifically a test file from the repository's test suites. Regardless, if I change the values of this column to "a" I still get an error.
Comment: you could investigate what is being referenced in the FsLab.fsx file.
Comment: As far as I can tell the references are the same. In `FsLab.fsx` `#I "../FSharp.Data/lib/net40"` goes up to the packages folder and then into FSharp.Data just like the hand-coded version that works. I'm updating to VS now to see if that helps.
Comment: I'll download a new FsLab and see if it behaves differently but these path or version related issues can be difficult to troubleshoot...maybe someone else seen this issue.
Comment: it's a shot in the dark but 32-bit FSI or 64-bit FSI behaves the same?
Comment: I just grabbed an old version I had on my computer: FsLab.0.3.10 and FSharp.Data 2.2.5. When I copied over the new libraries with the old versions, everything works correctly.
Comment: great. you can add that as the correct answer.
Answer: There is nothing wrong with the file. This for example works:
#load @"..\..\FSLAB\packages\FsLab\FsLab.fsx"

open System.IO
open FSharp.Data

[<Literal>]
let csvFile = @"C:\tmp\adwords.csv"
File.Exists csvFile

type Csv = CsvProvider<csvFile>
let csv = Csv.Load(csvFile)
csv.Rows

There is something wrong with your FsLab of FSharp.Data installation or type providers security maybe. Try the following, specify the path to the file directly. If it still doesn't work just nuget FSharp.Data and try using the csv  type provider directly in a new project.
Other info is also helpful. VS version, FSLab version, wha other references you have. etc.
EDIT: Thanks for the debug info. That's actually quite helpful. VS2015 Update 1 broke two things, the Binding Redirect for Fsharp and the type providers (that might have been FSharp Tools, I forgot). I would upgrade to Update 2. If that's not possible please check if your FSharp.Data.TypeProviders.dll is in C:\Program Files (x86)\Reference Assemblies\Microsoft\FSharp\.NETFramework\v4.0\18.104.22.168\Type Providers.
As referencing the dlls directly works, it's probably a version mismatch issue. My FsLab install predates VS2015 Update 1 and 2, so will see if it behaves differently with a new download.
Comment: Yes, I agree the file is fine (why I chose it). I added some debug info to the bottom of the question.
Comment: @nh2 see my comment in the Edit.
Comment: I've upgraded Visual Studio Community edition to Update 2. I still have the same problems. I also confirmed that the typeProviders.dll is in the right spot.
Answer: There is some issue with the installation of FSharp.Data currently bundled with FsLab (as of June 2016). This issue is with version 2.3.0. If you instead use FSharp.Data 2.2.5 the code works as expected.
Delete the packages/FSharp.Data folder and replace with version 2.2.5. I did it from an old installation but you could do it from Nuget


Newbie: Slow Apache2 Response Time, CPU 100%?

Question: As the title says I'm a newbie with this stuff but I'm willing to learn what I need to know. I'm simply ignorant atm. This is a Rackspace server with Ubuntu 15.10 running Apache2 using MySQL.
I have a PHP web app that runs with (not yet optimized) good load times on my local machine but stalls for about 2-4 seconds on page load/reload on the server. This seems to be an accumulating stall. The more time that passes the slower it seems to get.
Things I've tried to troubleshoot and other information:

I've checked both Chrome network tools and pingdom.com and both reveal that the first initial request is where the longest wait, not local or external resources.
Restarting apache helps a little but running the stop then start command seem to temporarily increase load speeds. One thing I noticed here is that I start to get quite a few entries under "CGroup: /system.slice/apache2.service" when I run the command "systemctl status apache2.service". I'm not sure if this should indicate anything to me or not. Should I have 10-20+ CGroup entries?
I'm peaking at around 250m memory and 100% CPU. No idea why CPU is so high with so few users.
Also, if it is pertinent, I am using nodejs, forever and socketio along side Laravel 5 though I don't think that any of this is the culprit for the long wait on the initial response.

What other reports or logs do I need to generate or look at to determine what might be the cause? I've heard some people having an issue with "resource leeching" and others with DDOS. How might I rule something like this out?
Here is a pingdom result of a faster load but still non-optimal. (I know, I need to bundle my scripts and styles ;) )
http://tools.pingdom.com/fpt/#!/jl6bX/http://barkerbot.com/
Thank you in advance!
Answer: Your page generation time is high. You need to:

Optimize your application, or increase CPU resources
Page caching could reduce the need for optimization, but only for anonymous users. Regenerating pages still takes time. On a busy site caching for even a small number of seconds can reduce server load.
Set up a CDN (content distribution network) like Cloudflare (which has a free plan). This will reduce the download time for your static resources
Change your headers to indicate that static resources should be cached, ideally for a week or more.

You may find this webpagetest.org test useful. It shows 11 - 15 second page load times - at that level people will be abandoning your website.
We'd need more information about your application and server to help much more.


What advantage is there for a baseball player to be selected with a higher draft slot if he signs for "below slot" money?

Question: The Pittsburgh Pirates selected catcher Henry Davis with the first pick of the 2021 draft. One consideration is that Davis is reportedly willing to sign for a below-slot amount of money, allowing the Pirates to spend more money in the later rounds of the draft.
Assuming that this information is correct, what advantages are there for a player to agree to something like this? Might a player reasonably think, "if I am signed number 1 "below-slot," I'll still sign for more than if I signed for number 2 or number 3 "at slot?" Or is it more like that the number 1 pedigree will follow him years later when he becomes a free agent and signs for "real" money, so it is worth sacrificing some up-front money to get the number 1 draft slot?
Answer: Draft slots are essentially irrelevant in baseball except for the limited purpose of setting an opening salary (which is by convention).  After the initial contract, it will make absolutely no difference.  There is no advantage in free agency due to draft position.  Any future contracts after the first will be based on his production, not the perception of him when he was drafted.
As a sport baseball has one of the worst drafts.  Good players frequently are taken in later rounds and early choices frequently don't pan out.  For example, previous Pirates first overall choice Jeff King was an average starter, with a best of 30 home runs in a year at a time when McGwire and Bonds were chasing the Ruth/Maris records (60/61).  The best of the four previous Pirates' first overall picks was Gerrit Cole, followed by King, Kris Benson (below average but an eleven year career), and Bryan Bullington (ten decisions in five years; left the MLB for Japan).  None of the four finished their career with the Pirates.  Cole is the only serious Hall of Fame contender.
None of the four 2020 Hall of Fame inductees were first overall choices, although Derek Jeter and Ted Simmons were first round picks.  Larry Walker was an undrafted free agent.  Marvin Miller was inducted for his front office contributions, not playing.
Between college and the minor leagues, draft picks are risky.  The best players may be in high school, while lesser players are finishing college.  And regardless, most players spend at least a year or two in the minors before they make it to the major league.  Basketball and football players start in the NBA (although that's changing) and NFL respectively, and drafting out of high school is much rarer.
It is quite possible that the Pirates would be better off signing all their late round choices than a first overall.
Assuming your source is correct, Davis presumably expressed a willingness to sign a "below-slot" contract because he still expects to make more money that way than if he had waited until his natural position in the draft.  One draft prediction put him fourth.  The slot values:
<code>1.  $8,415,300
4.  $6,664,000
-   $1,751,300
</code>
However, for all we know, he might have fallen farther.  His agent would know more but might not be sharing.  Note that that difference would be almost enough to sign the Pirates' second round pick at slot value ($1,999,300).  Of course, he might not have signed at that level.  We don't know what they have discussed.  Perhaps he will get paid the $7,789,900 for being drafted second overall or something else.  That would be enough savings for their fourth round choice.
CBS Sports also had him as the fourth best player.
It's also worth noting that the other top prospects that the Pirates were considering might not have signed at all.  As high school players, Marcelo Mayer and Jordan Lawlar could refuse to sign, go to college, and then go through the draft again.
It's also conceivable that he preferred the Pirates to other teams who expressed interest in him.  He's from New York, which is adjacent to Pennsylvania (where Pittsburgh is).  He had previous discussions with the Pirates when he graduated from high school.  They did not draft him then because they weren't willing to pay him what he wanted to forgo college.
It also may be that other teams that were interested in him also wanted to pay below-slot.  In general, the top drafting teams need to fill a lot of positions.  If he were insisting on slot value, he might have fallen below fourth.
Comment: Welcome to the site! Let's say the final contract is for $7-something million. That represents a savings for the Pirates from $8.4 million, and Davis would certainly prefer $7-something million for sure than $6.6 million for the fourth slot. A good (upvoted) answer.


Using Multiple Patterns in Form Field

Question: I'm attempting to create an email form field that requires a user to enter an email in the email@example.com format but also only allowing business emails to come through (no gmail, yahoo, hotmail, ect.)
I've created 2 field patterns that work independently, but I can't seem to get them to work together.
Requires a email@example.com format
pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$"

Does not allow these free email domains. Business emails only.
pattern="^(?!.*@(?:live|gmx|yahoo|outlook|msn|icloud|facebook|aol|zoho|yandex|lycox|inbox|myway|aim|goowy|juno|(?:hot|[gy]|google|short|at|proton|hush|lycos|fast)?mail)\.\w+$).*$"

Here is my form code:
    <form  method="POST" action="#">

    <input type=hidden name="oid" value="00D70000000KCoG">
    <input type=hidden name="retURL"
    value="#">

    Email<input id="email" maxlength="80"
    name="email" size="30" type="email"
    oninvalid="setCustomValidity('Please enter your business email here.')"
    onchange="try{setCustomValidity('')}catch(e){}" pattern="[a-z0-
    9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" required />

    <input type="submit" name="submit" value="Submit">
    </form>

Comment: type="email" allows one to enter the email a@b, but pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" only allows emails in the firstname.lastname@example.com format.
Comment: I ask out of curiosity - is there a difference between specifying `pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$"` and specifying `type="email"`?
Comment: @Felicia Please check my answer below, and let know if it  works fine for you or you need more help.
Comment: Good to know, @FeliciaSantos - thank you for clarification.
Answer: Here are the two patterns combined:
pattern="[a-z0-9._%+-]+@(?!(?:live|gmx|yahoo|outlook|msn|icloud|facebook|aol|zoho|yandex|lycox|inbox|myway|aim|goowy|juno|(?:hot|[gy]|google|short|at|proton|hush|lycos|fast)?mail)\.\w+$)[a-z0-9.-]+\.[a-z]{2,4}"

Note that the ^ at the start and $ at the end are not necessary as they are implicit there: pattern value is wrapped with ^(?: and )$ to match the entire input value.
See the regex demo.
Details

^  - implicit - start of string
[a-z0-9._%+-]+ - one or more letters, digits, ., _, %, + or -
@ - a @
(?!(?:live|gmx|yahoo|outlook|msn|icloud|facebook|aol|zoho|yandex|lycox|inbox|myway|aim|goowy|juno|(?:hot|[gy]|google|short|at|proton|hush|lycos|fast)?mail)\.\w+$) - a negative lookahead the fails the match if the pattern matches immediately to the right of the current location (that is, after @)
[a-z0-9.-]+ - 1+ lowercase ASCII letters, digits, . or/and -
\. - a dot
[a-z]{2,4} - 2 to 4 lowercase ASCII letters.

NOTE: you might want to add A-Z to the character classes: [a-z0-9._%+-]+ => [\w.%+-]+ and [a-z0-9.-]+ => [a-z0-9A-Z.-]+.

Using Multiple Patterns in Form Field


easier to use ratio test than comparison on this problem

Question: Im trying to show $\sum_{k=1}^{\infty} \mathrm{e}^{-k^2} $
First, I was trying to bound $e^{-n^2}$ by using $e^x \geq x + 1$ so $$e^{x^2} \geq x^2 + 1 > x^2 \implies e^{-x^2} < \frac{1}{x^2} $$
and the convergence follows easily. I also tried the ratio test:
$$ \frac{ e^{-(k+1)^2} }{e^{-k^2}} = \frac{e^{-k^2-2k-1}  }{e^{-k^2}} = e^{-2k-1} \to 0 <1 $$
and thus the ratio test gives us convergence. Do you think it is easier using ratio than comparison?
Comment: I think they're both pretty easy. What is the point of your question? Just to gather opinions?
Comment: In general, comparison is easier than ratio test since there is a lot of stuff on the denominator in some cases.
Comment: @T.Bongers, "What is the point of your question? Just to gather opinions?"
Also to give some participants an easy way to self-assert.
Comment: @avs Sorry, what? I don't understand your last.
Comment: @T.Bongers, just a bit of friendly sarcasm.  Disregard, since you've shown understanding for the Asker.
Answer: I would still use the comparison test:
$$
e^{-k^2} \leq 3^{-k^2} \leq 3^{-k}.
$$
Comment: I see, fair enough.
Comment: Why even bother with messing around with the base? $e^{-k^2} \le e^{-k}$.
Comment: Purely psychological: on the possibility that the Asker may be new to the constant $e$ and not as fluent in estimating it.  (And, yes, I have seen such situations arise when I taught.)


Dask dataframe: Can `set_index` put a single index into multiple partitions?

Question: Empirically it seems that whenever you set_index on a Dask dataframe, Dask will always put rows with equal indexes into a single partition, even if it results in wildly imbalanced partitions.
Here is a demonstration:
import pandas as pd
import dask.dataframe as dd

users = [1]*1000 + [2]*1000 + [3]*1000

df = pd.DataFrame({'user': users})
ddf = dd.from_pandas(df, npartitions=1000)

ddf = ddf.set_index('user')

counts = ddf.map_partitions(lambda x: len(x)).compute()
counts.loc[counts > 0]
# 500    1000
# 999    2000
# dtype: int64

However, I found no guarantee of this behaviour anywhere.
I have tried to sift through the code myself but gave up. I believe one of these inter-related functions probably holds the answer:

set_index
set_partitions
rearrange_by_column
rearrange_by_column_tasks
SimpleShuffleLayer

When you set_index, is it the case that a single index can never be in two different partitions? If not, then under what conditions does this property hold?

Bounty: I will award the bounty to an answer that draws from a reputable source. For example, referring to the implementation to show that this property has to hold.
Answer:
is it the case that a single index can never be in two different partitions?

No, it's certainly allowed. Dask will even intend for this to happen. However, because of a bug in set_index, all the data will still end up in one partition.
An extreme example (every row is the same value except one):
In [1]: import dask.dataframe as dd
In [2]: import pandas as pd
In [3]: df = pd.DataFrame({"A": [0] + [1] * 20})
In [4]: ddf = dd.from_pandas(df, npartitions=10)
In [5]: s = ddf.set_index("A")
In [6]: s.divisions
Out[6]: (0, 0, 0, 0, 0, 0, 0, 1)

As you can see, Dask intends for the 0s to be split up between multiple partitions. Yet when the shuffle actually happens, all the 0s still end up in one partition:
In [7]: import dask
In [8]: dask.compute(s.to_delayed())  # easy way to see the partitions separately
Out[8]:
([Empty DataFrame
  Columns: []
  Index: [],
  Empty DataFrame
  Columns: []
  Index: [],
  Empty DataFrame
  Columns: []
  Index: [],
  Empty DataFrame
  Columns: []
  Index: [],
  Empty DataFrame
  Columns: []
  Index: [],
  Empty DataFrame
  Columns: []
  Index: [],
  Empty DataFrame
  Columns: []
  Index: [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]],)

This is because the code deciding which output partition a row belongs doesn't consider duplicates in divisions. Treating divisions as a Series, it uses searchsorted with side="right", hence why all the data always ends up in the last partition.
I'll update this answer when the issue is fixed.
Answer:
Is it the case that a single index can never be in two different partitions?

IIUC, the answer for practical purposes is yes.
A dask dataframe will in general have multiple partitions and dask may or may not know about the index values associated with each partition (see Partitions). If dask does know which partition contains which index range, then this will be reflected in df.divisions output (if not, the result of this call will be None).
When running .set_index, dask will compute divisions and it seems that in determining the divisions it will require that divisions are sequential and unique (except for the last element). The relevant code is here.
So two potential follow-up questions: why not allow any non-sequential indexing, and as a specific case of the previous, why not allow duplicate indexes in partitions.
With regards to the first question: for smallish data it might be feasible to think about a design that allows non-sorted indexing, but you can imagine that a general non-sorted indexing won't scale well, since dask will need to store indexes for each partition somehow.
With regards to the second question: it seems that this should be possible, but it also seems that right now it's not implemented correctly. See the snippet below:
# use this to generate 10 indexed partitions
import pandas as pd

for user in range(10):

    df = pd.DataFrame({'user_col': [user//3]*100})
    df['user'] = df['user_col']
    df = df.set_index('user')
    df.index.name = 'user_index'

    df.to_parquet(f'test_{user}.parquet', index=True)

# now load them into a dask dataframe
import dask.dataframe as dd

ddf = dd.read_parquet('test_*.parquet')

# dask will know about the divisions
print(ddf.known_divisions) # True

# further evidence
print(ddf.divisions) # (0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3)

# this should show three partitions, but will show only one
print(ddf.loc[0].npartitions) # 1

Comment: Thanks for the answer. I think my question could've been clearer about the fact that I'm specifically interested in the behaviour of Dask's `set_index`. This answer is quite relevant and interesting, but doesn't address that.
Comment: Btw, for me, in your example, the divisions are actually unknown (`known_divisions` is `False)`. I'm using Dask `2021.08.01`, Pandas `1.3.1` and PyArrow `5.0.0`
Comment: No worries, I'm not confident in dask internals.
Answer: I have just noticed that Dask's documentation for shuffle says

After this operation, rows with the same value of on will be in the same partition.

This seems to confirm my empirical observation.


Can runs be scored by a boundary in the same legal ball as an Out - Hit wicket?

Question: Suppose a batsman plays the ball, gets out Hit wicket and the ball crosses the boundary. Will the runs be considered or not?
What changes if the batsman misses the ball, is out Hit wicket, and the ball carries to the boundary? Are four byes awarded in this case?
Answer: Section 9 of Law 18 covers this situation - in both cases no runs are scored. Once the batsman is dismissed no runs can be credited to the batting side.
Answer: Hit wicket is out so no runs will be considered and also bye is also not considered if the batsman is out.
Comment: Can you provide a resource(s) supporting your answer?


Twitter widget android

Question: Is there anyone now how to make widget like twitter?
They have 2 layout and user can user one of them after they see the layout.
Thank u very much..
Answer: Here's a tutorial to do the sending part. It uses OAuth for the Twitter authentication: http://www.androidacademy.com/3-tutorials/43-hands-on/249-twitterwidget-how-to-write-an-android-widget-which-tweets

Twitter widget android


Exchange 2007 to 2010 public folder replication error 1129

Question: I currently upgrading from an Exchange server 2007 to 2010. I have moved all mailboxes and OAB. I am having issues replicating the public folders. This is the error I'm getting in the event log on the 2007 box:
<code>Error 1129 occurred while processing a replication event.

Folder: (6-11ED8367F0C) IPM_SUBTREE\Marketing\Marketing
</code>
I have looked online and everything about these errors seems to relate from an old 2003 server. Well, we never had a 2003 server.
I'm really not sure what to do at this point. Any help?
Comment: How big is the Pubic Folders store? Have you tried permissions reset on the Public Folders?
Comment: A little over 1GB. I'm not exactly sure how to reset the permissions.
Comment: Try this:
http://technet.microsoft.com/en-us/library/bb125099(v=exchg.65).aspx
I would also suggest running ISINTEG on the database.
Comment: Those instructions seems to be for Exchange 2003. I have ran ISINTEG to repair the public store. It fixed a few things but overall it's still not working.
Comment: ok, here's the second link:
http://social.technet.microsoft.com/Forums/en-us/exchangesvradmin/thread/00ac473a-e0b5-4e0f-87cc-682eba0aeaec
Make sure to run the repair until there will be zero errors.
Answer: In case anyone else is having this issue, we finally found that the Mail Queue was holding the replication emails for the Public Folders. It was easily fixed by checking "Exchange Server authentication" on the Authentication tab in the Default Receive Connector.


Changing songs' chords to Arpeggios

Question: I want to know how I change chords to Arpeggios in a song? For example how do you change (Somebody's me) by Enrique from chords to Arpeggios or single notes? Can you show me this or another example as you want?
Answer: I'll borrow the arpeggio definition from wikipedia:

An arpeggio (Italian: [arˈpeddʒo]) is a musical technique where notes in a chord are played or sung in sequence, one after the other, rather than ringing out simultaneously.

So, let's say you have the C major chord, which consists of the notes C-E-G. If you play these 3 notes together, they will form the chord. If you play them one after the other, they will form an arpeggio.
In an arpeggio, you can also repeat these notes, like C E G C E G C E G.
So, in the song you mentioned, just take all the chords and play the notes one after the other.
Answer: Strictly speaking an arpeggio is played in strict note order like a scale, but more informally people use it to describe playing a chord in a broken order rather than all at once. With guitar you can hold a chord and play the notes(strings) in any order and it should sound reasonably ok. All the notes will harmonise.
You want to allow the strings to carry on ringing out rather than ending a note when you play the next one as you would normally do when playing a melody line
As mentioned elsewhere there are countless number of patterns you can play. Generally speaking, the placement of the bass note has a big effect on the overall sound, the higher notes less so. Mostly you will want to establish your chord with the root note in the bass (ie first note played of that chord). Below are 3 example of 8th note picking patterns that you can play with pick or fingers. Hold the chord shape throughout as if you were strumming it but pick the individual strings. These examples use just G D and C chords, but you could apply the same patterns to the chords for any song in 4/4.
<code>Example 1
 G                 D                  C       G
|-------1-------1-|-------2-------2-|-------0-------1-|
|-----0-------0---|-----3-------3---|-----1-------0---|
|---0-------0-----|---2-------2-----|---0-------0-----|
|-----------------|-0-------0-------|-----------------|
|-----------------|-----------------|-3---------------|
|-3-------3-------|-----------------|---------3-------|

Example 2 - alternating bass
 G                 D                 C        G
|-------1-------1-|-------2-------2-|-------0-------1-|
|-----0-------0---|-----3-------3---|-----1-------0---|
|---0-------0-----|---2-------2-----|---0-------0-----|
|-----------------|-0---------------|-----------------|
|---------2-------|---------0-------|-3---------------|
|-3---------------|-----------------|---------3-------|

Example 2 - alternating bass on beat 1 and 4
 G                 D                 C        G
|-------1---------|-------2---------|-------0-------1-|
|-----0---0-------|-----3---3-------|-----1-------0---|
|---0-------0---0-|---2-------2---2-|---0-------0-----|
|-----------------|-0---------------|-----------------|
|-------------2---|-------------0---|-3---------------|
|-3---------------|-----------------|---------3-------|
</code>
Answer: Check out this link for a good resource on arpeggios.
There are literally thousands of picking patterns for arpeggios. As a general rule though instead of strumming or playing the notes of a chord together. (Like this)

You pick the notes one at a time in some sort of pattern. (Like this)

(OR this)

SOURCE:

Changing songs' chords to Arpeggios


Inequality $\ln(x)x^2+x^4-x^5<1$

Question: I'm trying to prove this inequality but am unable to do so. Derivatives and graphing not permitted. Any hint?
Comment: Do you mean $x^2\ln{x}+x^4-x^5<1$?
Comment: it seems that is $$x^2\ln(x)+x^4-x^5<0$$
Comment: @Dr.SonnhardGraubner Strict inequality does not hold at $x=1$.
Answer: Assuming $x > 0$ so that $\ln(x)$ is defined (without complex numbers) and using the fact* that $\ln(x) \le x-1$,
\begin{eqnarray}
\ln(x) x^2 + x^4 - x^5 &\le& (x-1) x^2 + x^4(1-x)\\
 &=& (1-x)(x^2 - 1)x^2\\
\end{eqnarray}
For $0 < x < 1$, this product is negative. At $1$, it's $0$. Finally, for $x > 1$ it's negative again.
Thus $\ln(x) x^2 + x^4 - x^5 \le (1-x)(x^2-1)x^2 \le 0 < 1$ for all $x > 0$.

*This fact will have to be shown separately. E.g. see here.
Answer: Let $f(x)=\frac{x^5-x^4+1}{x^2}-\ln{x}$.
Hence, $$f'(x)=3x^2-2x-\frac{2}{x^3}-\frac{1}{x}=\frac{3x^5-2x^4-x^2-2}{x^3},$$
which by Descartes has unique positive root $x_1$.
Thus, $x_1=x_{min}$ and $x_1=1.208...$ and since $f(x_1)>0$, we are done!
By the same way we can prove that $\ln{x}\leq x^3-x^2$

Inequality $\ln(x)x^2+x^4-x^5<1$


Cumcount with reset in Python

Question: I have a following problem. I need to compute a cumcount but I would like to reset the counter always when the series is interupted.
See example:
data = { 'col_1': ['a', 'a', 'b', 'b', 'a'], 'col_2': [3, 2, 1, 0, -3]}
df = pd.DataFrame.from_dict(data)

I tried this but it gives me a wrong output:
df["seq"] = df.groupby(["col_1"]).cumcount()

What I want is:
data = { 'col_1': ['a', 'a', 'b', 'b', 'a'], 'col_2': [3, 2, 1, 0, -3], 'seq': [0, 1, 0, 1, 0]}

How can I do it, please?
Comment: What do you mean by the series is interrupted?
Comment: @DaniMesejo interrupted means that I have `a` in the first and second row but then in the last row. I would like to check this when doing `cumcount()`.
Answer: Try:
df["seq"] = df.groupby((df["col_1"] != df["col_1"].shift()).cumsum())["col_1"].cumcount()
print(df)

Output
  col_1  col_2  seq
0     a      3    0
1     a      2    1
2     b      1    0
3     b      0    1
4     a     -3    0

Answer: Note that as you are interested in runs (like in run-length encoding) itertools.groupby might be better suited for this task, consider following example
import pandas as pd
df = pd.DataFrame({'col1':['a','a','b','b','a']})
df['seq'] = [i for k, g in itertools.groupby(col1) for i in range(len(list(g)))]
print(df)

output
  col1  seq
0    a    0
1    a    1
2    b    0
3    b    1
4    a    0

Comment: Elegant way, thanks!

Cumcount with reset in Python


How do I find a function based on given function values?

Question: Let us suppose I have an unknown function $f(x)$.
I have the information that $f(2)=6$ and $f'(2)=-1$.
What would the actual function be? Are there unlimited possibilities? How do I make an expression that satisfies this information?
Comment: You cannot tell what the whole function is by the information you are providing. The simplest way to find one(!) function is to chose $a,b$ properly such that $f(x)=ax+b$ satisfies your conditions.
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or closed. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognise and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: There are multiple fonctions that satisfy this. The "easiest" way is to consider a polynomial function as
$$
f\left(x\right)=ax+b
$$
You have
$$
f\left(2\right)=2a+b=6
$$
and
$$
f'\left(2\right)=a=-1
$$
Hence an example is
$$
f\left(x\right)=8-x
$$
Answer: Yes: there are unlimited options. One of the simplest would be the affine function
$$f(x)=-x+8$$
which goes through the point $(2,6)$ and whose slope is $-1$ (actually everywhere), as requested.
Answer: As it was mentioned in other answers, there are countless possibilities. To obtain a relatively large selection of such functions, you can draw inspiration from Taylor's series, where
$$
f(x) = \sum_{n=0}^{+\infty}\frac{f^{(n)}(a)}{n!} (x-a)^n, \quad x \in D.
$$
Any function of the form
$$
f(x) = 6 - (x-2) + \sum_{n=2}^{+\infty} c_n (x-2)^n
$$
is a good fit, as long as the series is convergent. In particular, taking $c_n = 0$, you get $f(x)=6-(x-2)$.


File reader encapsulation in a table reader

Question: I have a file reader object that i need to read a file with tables in it. I want to create an object called Table to hold the row and column data from the read file. The trouble is, to read the whole page, i need to have a list of tables (there are more than one in the file). WHat is the best structure of my classes so that i am not exposing the data reader too much and passing it around too much?
My current line of thinking is this:

Create a class that instantiates a list of tables and pass this class the reader.
Run the reader and for each new table found, instantiate a new table object and pass along the reference to the reader so it can get row/column info.

Is this the best way to do this kind of task? Or is there a more efficient design to restrict the reader being passed too much? I have to use the using statement and it just doesnt feel right to use it in this nested design
Thanks
Comment: Does the table structure change at all or is it fixed?  Could also provide a small sample of the input?
Comment: the number of rows and columns differ between each table. the info is a bit sensitive so i cant provide a sample. but just think of it as tables in a word doc with headers/columns/rows
Comment: Is the information at least delimited in the same fashion?  Comma/pipe/tilde separated or something like that?
Answer: I personally would go with the idea of encapsulating the Table collection in your own class that controls the reader.  I would also not allow public instantiation of either object if hiding those details is a concern.  Something like this.
public class TableCollection : List

{
   private TableCollection() { }

   public static TableCollection FromFile(string filePath)
   {
       using (StreamReader reader = new StreamReader(filePath))
       {
           //populate all tables here before disposing
       }
   }
}

public class Table
{
   //whatever other properties/methods

   //keep it internal to hide the implementation from the user
   internal Table(StreamReader reader)
   {
      //do what you need to do here
   }
}

Answer: You could potentially use the already available DataTable.  There is a little bit of overhead in using them, but it sounds like it would be something easy to work with.
You did say that the tables contain different structures.  Is there anything in the file that identifies the table changing?  This could make it more difficult if there are many 'tables' in the same file.
You can simply use a collection of type DataTable if you want to have a list of them around.  I suppose you could create your own class for this if your design warrants that.
List<DataTable> tables = new List<DataTable>();

and a sample method of how it may be used:
private IList<DataTable> GetTables()
{
    IList<DataTable> tables = new List<DataTable>();
    using (StreamReader reader = new StreamReader(pathAndFile))
    {
        //pseudo-code below
        //Iterate through tables in the file: foreach(DiscoveredTable table in file)
        //parse from csv: table = GetTableFromCsv(table.DataFromTheFile);
        //add to tables collection: tables.Add(table);
    }

    return tables;
}

Here is a link to a CSV parser if you are interested in going that route, since you said it is comma-separated.


Empty $order variable on WooCommerce plugin PHP hook

Question: I have an issue trying to make a hook on the WooCommerce plugin for WordPress.
The problem is that I need to conditionally change the recipient email of the order depending on the local pickup shipping option they choose. My code was working properly for months, but suddenly; it stopped working.
This is what I have on my functions.php file:
<code>    add_filter( 'woocommerce_email_recipient_new_order', 'diff_recipients_email_notifications', 10, 2 );
function diff_recipients_email_notifications( $recipient, $order ) {

    $shippingOptionOne = 'firstname.lastname@example.com';
    $shippingOptionTwo = 'firstname.lastname@example.com';
    $shippingOptionThree = 'firstname.lastname@example.com';

    $order_shipping = $order->get_items('shipping');
    $key = key($order_shipping);
    $shipping_method_id = $order_shipping[$key]['item_meta']['method_id'][0];

    if($shipping_method_id == 'local_pickup:6' )
    {
        $recipient = $shippingOptionOne;
    }
    elseif($shipping_method_id == 'local_pickup:4'){
        $recipient = $shippingOptionTwo;
    }
    elseif($shipping_method_id == 'local_pickup:7'){
        $recipient = $shippingOptionThree;
    }
    return $recipient;
}
</code>
I've made some testing and research and after debugging a little bit, I've came to the conclusion that the variable $order which is coming as the second parameter of my function is printing an empty value, so I can't get the $order_shipping = $order->get_items('shipping');
($order is printing an empty space).
Thanks in advance.
P.S: This is the link I used to make my code in first place: WooCommerce email notifications: different email recipient for different cities
Answer: My team and I spent some time debugging and we came to the solution.
For some reason, the var_dump wasn't printing the order but it was there, we just changed this line:
<code>$order_shipping = $order->get_items('shipping');
    $key = key($order_shipping);
    $shipping_method_id = $order_shipping[$key]['item_meta']['method_id'][0];
</code>
and replaced it with this one:
<code>$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
    $chosen_shipping = $chosen_methods[0];
</code>
Of course we also changed
<code>$shipping_method_id
</code>
with:
<code>$chosen_shipping
</code>
And it works as a charm!


Verificar se e-mail possui brecha através do site have I been Pwned (Selenium/Python)

Question: Boa tarde!
Estou utilizando o Selenium para teste automatizado. O objetivo é verificar, através de uma lista de e-mails institucionais, se o e-mail está em alguma brecha e enviar um e-mail padrão solicitando atualização da senha;
O problema surgiu quando busquei por um e-mail com brecha e o corpo do site é exatamente igual para um e-mail que não está em nenhuma brecha;
Tentei class name, id, page source e nada parece funcionar nesse caso.
Como podem ver no trecho abaixo.. O primeiro e-mail está num site vazado e o segundo e-mail não caiu em nenhum vazamento de dados, mas ambos caem na primeira condição.

Alguma sugestão?
Comment: Não seria melhor usar a [API](https://haveibeenpwned.com/API/v3) que eles fornecem?
Answer: Você está verificando se o conteúdo Oh no - pwned está no código fonte da página, não se está na tela.
Se você olhar o código fonte da página (como sempre é bom fazer se está desenvolvendo com selenium), vai que essa string sempre está lá  - está lá assim como  a contraparte Good news — no pwnage found!.
Em outras palavras: o texto para as duas respostas - se o email vazou ou não vazou, está presente na página - é o Javascript da página que faz um, ou o outro, ser visível.
Mais ainda, a página tem uma API, e uma API normalmente é algo mais propíciod e se usar do que uma consulta por selenium - por vários motivos, mas o principal dele é que uma API sempre vai ser bem documentada e vai te trazer respostas trafegando bem menos dados e usando menos recursos do lado do servidor - e do lado do cliente, você tem a garantia que a resposta não vai mudar por conta de uma reformulação estética da página.
Os úncos casos em que você iria preferir usar o Selenium pra fazer uma consulta, se há uma API são: (1) a app já faz várias outras coisas com selenium, e essa consulta seria só uma coisa a mais e simples de de fazer, sem precisar multiplicar a lógica da aplicação para incluir a consulta a API, além do Selenium já usado para outras páginas; (2) o acesso da API é restrito por login e/ou conta paga, e você quer usar o Selenium para tentar uma consulta gratuita.
Bom - no caso dessa questão, parece que você cai exatamente nos dois casos acima  - tanto já tem parte da app usando selenium pronta, como o uso da API requer uma assinatura.
O problema é que - se a API requer uma assinatura, isso quer dizer que por vários motivos os autores do site não querem ou não podem fornecer a informação a uma aplicação automatizada de forma gratuita  - então insistir em usar o Selenium para fazer a consulta contornando a api é se apropriar indevidamente do serviço do portal.
Aqui está a página do haveibeenpwned explicand por que ele teve que fechar o serviço e passar a cobrar pelo uso da API (é barato, de repente você pode comprar uma chave de API para seu projeto: https://www.troyhunt.com/authentication-and-the-have-i-been-pwned-api/
Se quiser insistir em tentar usar o serviço sem ter um token de API, e com o selenium, claro que ninguém vai quebrar por conta disso, e muita das coisas que fazemos no dia a dia, mesmo em trabalho corporativo, as vezes tem alguns contornos desses=- mas tecnicamente vai ser desafiador: você vai ter que usar algo que identifica qual das duas mensagens está visível na página, não apenas presente no codigo fonte da página nesse caso.
Vejo três maneiras de fazer isso, e por questão de tempo e recursos não tenho como te dar uma resposta inteira: Verificar no CSS ativo da página (com as ferramentas de desenvolvedor), que propriedades estão ativas/inativas para aparecer uma ou outra resposta na tela, e verificar essas propriedades pelo Selenium - talvez seja a visibilidade das div
 e a div com id noPwnage - mas você vai ter que checar isso você mesma.
Se pela checagem das propriedades de CSS para os elementos visíveis você não conseguir localizar, vai ter que usar alguma API do Selenium para ver se um elemento está visível na página, e não simplesmente "presente" - parece que a chamada ".isDisplayed" do Selenium, nas classes acima, pode ser o suficiente - de qualquer forma, você vai ter que olhar a documentação - https://developers.perfectomobile.com/display/TT/isDisplayed%28%29+and+NoSuchElementError+exception

Por fim, mas não menos importante: bem-vinda ao stackoverflow em português.
Por favor, ao fazer perguntas, não use imagens para colar seu código, mensagens de erros ou representações de dados.  Sempre cole o seu código, as mensagens de erro impressas, e os seus dados como texto (formate o código usando os botões da interface ou a marcação markdown) -- Imagens não permite uma busca, não permitem indexação de trechos do seu código pelos bancos do stackoverflow, não permitem que pessoas respondendo sua pergunta copiem e colem trechos do seu código para dar exemplos - -nesse caso mesmo, eu tive que ficar indo e voltando para reproduzier a mensagem que você espera na tela "Yo've been pwned", quando teria sido muito mais confortável pra mim copiar e colar esse trechinho


Como descobrir a porta da JVM em linux?

Question: Tenho servidor linux rodando uma JRE 1.7 e preciso usar o VisualVM para monitorar o desempenho das aplicações rodando na mesma.
O VisualVM usa JMX para conectar no host linux porem ele espera algo como
<hostname>:<port>

A principio achei que fosse a porta ssh 22, porém pesquisando li que se trata da porta da JVM no servidor.
Como descubro a porta que a JVM esta rodando?
Comment: @FlávioGranato, estava aguardando gerando a imagem para mostrar a saída do comando.
Comment: Em ambiente Windows é utilizado o PID, não seria o mesmo para ambiente  Linux ?
Comment: Execute o comando netstat -tlnp, verá a lista de portas abertas
Comment: @BrunoRigolon você não acha que esta pode ser uma resposta em vez de um comentário?
Answer: Execute o comando netstat -tlnp, veja o resultado:
Temos o protocolo, como TCP/UPD, o IP de escuta e a porta. No final temos o PID e também qual programa está executando.
Comment: Obrigado era isso que precisa

Como descobrir a porta da JVM em linux?


Search nodes with paragraph

Question: I have the following query:
$query = \Drupal::entityQuery('node')
            ->condition('type', 'case_study')
            ->condition('status', '1')
            ->sort('changed', 'DESC')
            ->pager(4);

$query->condition('title', "%QUERY%", "LIKE");

$nids = $query->execute();

This works fine, however it obviously only searches on the title of the node. My case study nodes' fields are structured like this
- Case Study
    - title
    - field_page_banner
    - ...
    - field_rows <-- this is my paragraphs field

The paragraphs can contain multiple types and are chosen by the user when creating the content.
I want to be able to alter my query so that it searches the content of the paragraphs. For example, if the user adds a 'Rich Text' paragraph type, it will search the text.
This works fine for the built in search functionality, I just want to create a page of case studies with search functionality.
I am using Drupal 8.2.4 and Paragraphs 8.x-1.0.
Answer: The \Drupal::entityQuery object doesnt support JOINs I believe:
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Query%21QueryInterface.php/interface/QueryInterface/8.2.x
If it did you could Join onto the Paragraph bundle and LIKE across that all you want.
I recommend the following approach with Views, a small chance exists it may not work:

Create a View of your case study Nodes
add a relationship to the Paragraph bundle (if needed)
assure the field list for the View includes title and field_rows (you can Exclude field_rows from showing in your view if you want).
add a Grouped Filter and Expose it and select it to use your title and field_rows values.

That should do the trick...
Comment: This sounds like it might be exactly what I want, however I'm stuck at the `Grouped Filter`, is this the same thing as the normal `Filter Criteria` or `Contextual Filters` options? Or is this something different?
Comment: A `Group Filter` is an option when adding a `Filter Criteria`. You must have already added the fields you want to group upon to your View.
Comment: Ah I see, I'm not getting a `Group Filter` option, could it have been renamed to `Combine fields filter`? Or am I missing a module?
Answer: After keep on testing and write the query i found out it do support join for paragraph. Below is my query
$query = \Drupal::entityQuery('node');
$query->condition('field_content_type_paragraph_name.entity.field_paragraph_field_machine_name.target_id',"NODE ID HERE");
$entity_ids = $query->execute();
Here is the generated query
[node__field_content_type_paragraph_name] => Array
                    (
                        [join type] => INNER
                        [table] => node__field_content_type_paragraph_name
                        [alias] => node__field_content_type_paragraph_name
                        [condition] => node__field_content_type_paragraph_name.entity_id = base_table.nid
                        [arguments] => Array
                            (
                            )
                    )

                [paragraphs_item] => Array
                    (
                        [join type] => LEFT OUTER
                        [table] => paragraphs_item
                        [alias] => paragraphs_item
                        [condition] => paragraphs_item.id = node__field_content_type_paragraph_name.field_content_type_paragraph_name_target_id
                        [arguments] => Array
                            (
                            )
                    )

                [paragraph__field_paragraph_field_machine_name] => Array
                    (
                        [join type] => INNER
                        [table] => paragraph__field_paragraph_field_machine_name
                        [alias] => paragraph__field_paragraph_field_machine_name
                        [condition] => paragraph__field_paragraph_field_machine_name.entity_id = paragraphs_item.id
                        [arguments] => Array
                            (
                            )

                    )

Search nodes with paragraph