Servidor MySql com Xampp para ser acessado por outra máquina?

Question: eu sou um completo iniciante em mexer com programação Web e servidores locais e remotos, a minha noção sobre estes assuntos é bem parcial. Bom, eu tenho um sistema que precisará acessar um banco de dados Mysql. Porém este servidor com o banco de dados deverá estar em outra máquina, ou seja, preciso acessar remotamente a rede local de onde está o mysql com o xampp.
Pesquisei sobre o assunto em vários lugares, vários mesmo, e por saber realmente pouco sobre o assunto, acabei que me confundi cada vez mais. A minha dúvida é como eu posso criar e/ou configurar um servidor mysql com xampp para que eu possa acessa-lo remotamente? eu precisaria de uma outra rede isolada para as duas máquinas? Ou liberar o acesso online?
Desde já, agradeço a atenção de vocês.
Obs: Eu consigo acessar o banco via rede local da propria maquina utilizando o xampp, mas a intenção era prove o acesso via Ip para que eu possa acessa-lo via outra maquina.
Comment: XAMPP (Apache, MySQL, PHP e Perl, e o X é "cross platform") é uma coleção de programas. O MySQL que vem com ele é o mesmo que vem "solto" se baixar da página original. Se vai usar só o DB remotamente, não faz sentido instalar o XAMPP todo. Pegue só o MySQL, ou melhor ainda, o MariaDB, que é compatível, mas com um ciclo evolutivo melhor e mais aberto. Na verdade o XAMPP é uma maneira prática de montar um ambiente de testes, mas pra coisa séria, acho mais sensato instalar separadamente o MariaDB, o Apache e o PHP (e o Perl se precisar).
Comment: Primeiramente obrigado pela resposta. Bom eu tenho instalado também o mysql da oracle com Workbench, com ele consegui acessar via rede local também. Porém no meu projeto o banco de dados será um intermediário entre o sistema e uma aplicação web. Achei que precisaria do xampp pra criar um servidor pra estes fins. Para tal, você não recomendaria o xampp?
Comment: Pela sua pergunta, da pra ver que você tá bem confuso sobre o que de fato é o tal XAMPP, mas vamos tentar ir direto ao ponto. Esse servidor onde ficará o MySQL, tem uma razão pra ele ser Windows? Você quer que seu sistema acesse o MySQL remotamente, portanto, a máquina onde ficará o MySQL precisa ter um IP fixo dentro da rede local e isso nos leva a segunda pergunta. Sua rede local possui algum roteador?
Comment: Os testes do sistema com o banco e a aplicação web serão para fins de apresentação mesmo, no caso o projeto seria meu tcc Por isso estou usando no windows mesmo. Possui roteador sim, é um Tp-link wr941nd, preciso liberar o acesso à porta 80 por ele?
Answer: Se eu entendi bem a tua pergunta, você quer que sua base de dados seja disponibilizada em outras maquinas. Sendo assim em uma rede local basta colocar o IP da maquina onde se encontra o xammp instalado.
Exemplo
192.168.1.100 <- IP da máquina onde esta instalado o xammp
192.168.1.100/phpmyadmin
Espero que seja isso que queria, qualquer coisa e só avisar !
Comment: Consegui conectar remotamente via rede local, porém consigo apenas o acesso pelo browser de outro dispositivo, ao acessar pelo ip na minha aplicação a conexao nao é estabelecida, mas sua resposta nao deixa de estar correta em relação a minha pergunta. Obrigado pela resposta.


Error Accessing Data in Message Element

Question: I have an issue trying to process a ReferenceDataRequest. Here is all the code I am using to fill in a session.
global options
options = parseCmdLine()
sessionOptions = blpapi.SessionOptions()
sessionOptions.setServerHost(options.host)
sessionOptions.setServerPort(options.port)
session = blpapi.Session(sessionOptions)

if not session.start():
    print ("Failed to start session.")
    return False

if not session.openService("//blp/refdata"):
    print ("Failed to open //blp/refdata")
    return False

refDataService = session.getService("//blp/refdata")
request = refDataService.createRequest("ReferenceDataRequest")
request.getElement("securities").appendValue("UX1 Index")
request.getElement("fields").appendValue("FUT_DAYS_EXPIRE")
cid = session.sendRequest(request)

while(True):
    ev = session.nextEvent(500)
    for msg in ev:
        if cid in msg.correlationIds():
            # print(msg)
            data = msg.getElement("securityData").getElement("fieldData")

    if ev.eventType() == blpapi.Event.RESPONSE:
            break

print(data)
session.stop()

I am getting this error. blpapi.exception.UnknownErrorException: Attempt access name 'fieldData' on array element 'securityData' (0x00000003).
This is what the msg received looks like.
ReferenceDataResponse = {
    securityData[] = {
        securityData = {
            security = "UX1 Index"
            eidData[] = {
            }
            fieldExceptions[] = {
            }
            sequenceNumber = 0
            fieldData = {
                FUT_DAYS_EXPIRE = 27
            }
        }
    }
}

Is there anyway to fix this issue?
Answer: The solution is to just narrow down the msg elements and values. Took a lot of testing but this is the solution to my specific problem.
refDataService = session.getService("//blp/refdata")
request = refDataService.createRequest("ReferenceDataRequest")
request.getElement("securities").appendValue("UX1 Index")
request.getElement("fields").appendValue("FUT_DAYS_EXPIRE")
cid = session.sendRequest(request)
while(True):
    ev = session.nextEvent(500)
    for msg in ev:
        if cid in msg.correlationIds():
            data = msg.getElement("securityData").getValue().getElement("fieldData").getElement("FUT_DAYS_EXPIRE").getValue()

    if ev.eventType() == blpapi.Event.RESPONSE:
            break

print(data)
session.stop()

Looking at the provided examples in the DAPI blpapi directory helped me.
Answer: You could also do
data = msg.getElement("securityData").getElement("securityData").getElement("fieldData").getElement("FUT_DAYS_EXPIRE").getValue().
I believe getValue() worked because there was only one value in the securityData[] array.

Error Accessing Data in Message Element


Drupal commerce - what page/function should i call after an off site payment

Question: I'm creating a module to integrate 'xpay - carta sì' payments inside Drupal commerce.
I don't have any documentation on xpay apart for the module developed for ubercart.
Anyway i managed to code the part where the payment method is added and i succesfully dealt with going from my site to the bank page sending the correct data. I'm stuck with where to go after the payment is completed.
When i send the data to the bank i set some url to call according to the outcome of the transaction
<code>'RESULT_URL' => $site_url.'/cart/xpay/complete',
'NOTIFICATION_URL' => $site_url.'/cart/xpay/server',
'ERROR_URL' => $site_url.'/cart/xpay/error',
'ANNULMENT_URL' => $site_url.'/cart/xpay/error',
</code>
I've defined those menu_callbacks, but i'm not sure that Drupal Commerce works like this, maybe i should do something totally different like returning to <code>$site_url.'/checkout/%order_id/payment'</code>
Has anybody of you tackled something similar?
Answer: i used those two
<code>// Return to the previous page when payment is canceled
'cancel_return' => url('checkout/' . $order->order_id . '/payment/back/' . $order->data['payment_redirect_key'], array('absolute' => TRUE)),

// Return to the payment redirect page for processing successful payments
'return' => url('checkout/' . $order->order_id . '/payment/return/' . $order->data['payment_redirect_key'], array('absolute' => TRUE)),
</code>
but also have an IPN. (your NOTIFICATION_URL)
don't forget to create a commerce transaction with the feedback from the carrier !
maybe have a look at another module, like postfinance (by me),
or paypal (by Ryan - the commerce god ;))
Comment: Thanks, those works, the notification url is the url that is notified as soon as the transaction is completed, the url thatis responsible for creating the transaction inside drupal, is this correct?
Comment: yep - correct :D
Comment: When I use this , sometimes where comeback form bank  show 404 page not found !!!
Comment: what case is 'sometimes', what url is there in the browser causing 404 ?


Wordpress com CF7 gravando em MySql externo

Question: Dentro de um WP tenho um formulário CF7 e preciso que os campos (normalmente estão [desta forma] como padrão de variável no CF7) sejam enviados para uma página externa PHP que vai receber estes valores através do link e gravar no banco em outro local. Algo mais ou menos assim:

Form CF7 com dados [nome] [email] [endereco]
Usar o campo de script ou de redirecionamento do CF7 para capturar estas variaveis CF7 [nome] [email] [endereco]
Criar o link http://meusite.com/recebedados.php?nome=[nome]&email=[email]&endereco=[endereco]
Concluir operação com o envio do form e o envio deste link para página externa PHP que vai gravar em outro MySql

--> pontos importantes:
- Não quero usar o banco de dados do plugin local;
- Preciso gravar em BD externo (outra hospedagem);
- Pode ser utilizado o campo de script quanto o de direcionamento que já vem no CF7, porém precisa passar estas [variaveis] no link;
Muito obrigado pelas indicações ;)
Answer: Resolvido
Utilizei o recurso do CF7 de pegar suas variáveis e enviar para um redirecionamento através do link.
Na página destino resgatei-as e usei no banco como precisava.


How do I make the entire width of a menu item change background color when hovered over?

Question: I want it to be like this:

Currently, it is like this:

So, as shown most of the background is highlighted in white but there is a small left and right section which is purple.
The code I have so far which correspond to the menu items is:
<code>.collapsible-menu ul
li:hover:not(:last-child) {
background-color:white;
width:100%;
color: #4C27B3;
text-decoration: none;
 outline:none;
}
</code>
It is probably a quick fix but I need a second pair of eyes to pinpoint the issue. Many thanks in advance.
All code can be seen here:
https://codepen.io/JoyFulCoding/pen/EzXowL
Answer: in Css
<code>.menu-content{
overflow: hidden;
font-family: 'Raleway', sans-serif;
font-weight: bold;
padding: 0 0 0 50px;

/* add this margin left & right to make hover white full screen*/
margin-left: -79px;
margin-right: -30px;
}
</code>
Answer: in Css
<code>.collapsible-menu {
    background-color: #4C27B3;
    border: none;
    box-shadow: 1px 2px 3px rgba(0,0,0,0.2);
}
</code>
Remove Padding from this class in code


How should I save the Jenkins pipeline result?

Question: I'm learning Jenkins,
I want to save Jenkins pipeline result, and then visit the result by Jenkins REST API.
Can this be achieved?
For example:
pipeline {
    agent  any
    stages {
        stage("calculate 1+1") {
               script{
                  def result = 0
                  result = 1+1
               }
         }
}

How should I save result and then visit it? (I can use Jenkins python package: Jenkins.get_build_info)
Comment: Thank you @zett42
Here is a similar question: [link]https://stackoverflow.com/questions/59551174/jenkins-pipeline-to-return-results-file-after-build
Comment: According Document in Jenkins, Can I custormize `currentBuild.result`? Is `currentBuild.result` is only a enum of  `SUCCESS` `UNSTABLE` `FAILURE`?
Comment: Seems I can not save the result in `currentBuild.result`
Comment: `currentBuild.result` is enum. I suggest to use `writeFile` to write result to workspace, then use `archiveArtifacts` to store it as artifact. You can use REST API to get artifacts.
Answer: The result of a pipeline usually is a build somewhere in $WORKSPACE.
You can make Jenkins archive such file(s) using archiveArtifacts and later retrieve them like Downloading artifacts from Jenkins using wget or curl
If instead you intend to store more metadata about the build (which would reside in build.xml) this is another story. Usually you need plugins that perform such work for you - I am not aware of generic pipeline steps that would do that.


Append multiple list in a list comprehension

Question: Is it possible to append multiple list during list comprehension?
For example: Below works fine:
X = []
Y = []
[X.append(i) for i in range(100000)]

But, this won't even run:
[X.append(i), Y.append(i**2 + 3*i) for i in range(100000)]

How to make above work?
Comment: Why would you use a list comprehension here? It doesn't make sense. Don't use list comprehensions for side effects.
Comment: **Do not use a list comprhensions for side-effects**. Never do `[X.append(i) for i in range(100000)]
`
Comment: ```[(X.append(i), Y.append(i**2 + 3*i)) for i in range(100000)]```
?
Answer: You should never write the code you've written above.
[X.append(i) for i in range(...)] generates the result [None, None, None, ......] where there are 100,000 Nones in that list, and then throws it away.  It just so happens that X.append(i) has a side affect that you're taking advantage of.
You're looking for
X.extend(i for i in range(100000))
And as for the code you're trying to write.  Just make it two lines of code.  Your readers will thank you.
Or alternatively, just X = [i for i in range(100000)] and likewise for Y.
Comment: `X = list(range(100000))` is sufficient ;)
Answer: Direcly define your list with comprehension:
Y = [i**2 + 3*i for i in range(1000)]

Answer: You can use zip(*...) (transposing operation) to assign to different variables:
X, Y = map(list, zip(*((i, i ** 2 + 3 * i) for i in range(10))))

print(X)
print(Y)

Prints:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 4, 10, 18, 28, 40, 54, 70, 88, 108]

Answer: To answer your question, you need to wrap your two parameters in brackets to be able to do that from within list comprehension:
[(X.append(i), Y.append(i**2 + 3*i)) for i in range(100000)]

However, doing it this way is unpythonic as it will result in a list filled with None of length 10_000 which immediately gets discarded. Just use a for loop:
for i in range(10_000):
  X.append(i)
  Y.append(i**2 + 3*i)

or, two list comprehensions:
X = list(range(10_000))
Y = [i**2 for i in range(10_000)]


Bigquery Internal Error triggered by FULL OUTER JOIN

Question: I am getting a Bigquery internal error when attempting to perform a full outer join. The query succeeds if I use an inner join.
The job statistics can be seen in:
GET https://www.googleapis.com/bigquery/v2/projects/quantum-gearbox-90015/jobs/job_AQtc0zMEkDHkk-OmCXCGRk6zycs?key={YOUR_API_KEY}
The query is as follows:
SELECT
  CASE WHEN t1.userId           IS NOT NULL THEN t1.userId           ELSE t2.userId           END AS userId,
  CASE WHEN t1.jobId            IS NOT NULL THEN t1.jobId            ELSE t2.jobId            END AS jobId,
  CASE WHEN t1.result_duration  IS NOT NULL THEN t1.result_duration  ELSE t2.result_duration  END AS result_duration,
  CASE WHEN t1.job_submitted_ts IS NOT NULL THEN t1.job_submitted_ts ELSE t2.job_submitted_ts END AS job_submitted_ts,
  CASE WHEN t1.job_running_ts   IS NOT NULL THEN t1.job_running_ts   ELSE t2.job_running_ts   END AS job_running_ts,
  CASE WHEN t1.job_complete_ts  IS NOT NULL THEN t1.job_complete_ts  ELSE t2.job_complete_ts  END AS job_complete_ts,
  CASE WHEN t1.userId           IS NULL AND t2.userId            IS NOT NULL THEN t2.last_updated_ts
       WHEN t1.jobId            IS NULL AND t2.jobId             IS NOT NULL THEN t2.last_updated_ts
       WHEN t1.result_duration  IS NULL AND t2.result_duration   IS NOT NULL THEN t2.last_updated_ts
       WHEN t1.job_submitted_ts IS NULL AND t2.job_submitted_ts  IS NOT NULL THEN t2.last_updated_ts
       WHEN t1.job_running_ts   IS NULL AND t2.job_running_ts    IS NOT NULL THEN t2.last_updated_ts
       WHEN t1.job_complete_ts  IS NULL AND t2.job_complete_ts   IS NOT NULL THEN t2.last_updated_ts
       ELSE t1.last_updated_ts END AS last_updated_ts
FROM (
  SELECT
    userId,
    jobId,
    result_duration,
    job_submitted_ts,
    job_running_ts,
    job_complete_ts,
    last_updated_ts
  FROM
    [activeJobs.jobScoreboard] )t1
FULL OUTER JOIN EACH (
  SELECT
    userId,
    jobId,
    result_duration,
    job_submitted_ts,
    job_running_ts,
    job_complete_ts,
    INTEGER(ROUND(NOW()/1000,0)) AS last_updated_ts
  FROM (
    SELECT
      userId,
      jobId,
      MAX(CASE WHEN eventType = 'WORKITEM_COMPLETE' THEN data.result.data.duration END) AS result_duration,
      MIN(CASE WHEN eventType = 'JOB_SUBMITTED' THEN timestamp END) AS job_submitted_ts,
      MIN(CASE WHEN eventType = 'JOB_RUNNING' THEN timestamp END) AS job_running_ts,
      MAX(CASE WHEN eventType = 'JOB_COMPLETE' THEN timestamp END) AS job_complete_ts,
    FROM
      [trebekProd.JobActivity_20151125T000000Z_20151126T000000Z@1448472935436-]
    GROUP BY
      userId,
      jobId))t2
ON
  t1.jobId = t2.jobId
Comment: The job query returns in part the following response:
 "status": {
  "state": "DONE",
  "errorResult": {
   "reason": "internalError",
   "message": "An internal error occurred and the request could not be completed."
  },
  "errors": [
   {
    "reason": "internalError",
    "message": "An internal error occurred and the request could not be completed."
   }
  ]
 },
 "statistics": {
  "creationTime": "1448477868181",
  "startTime": "1448477868667",
  "endTime": "1448477872929"
 },
 "user_email": "email@example.com"
}
Comment: Can you please give me your jobid so I can debug more efficiently? (Whoops. Sorry. Just found it in your link above...)
Answer: The root cause of your error was a temporary overload of our streaming ingestion service. It was unable to serve the data for your table at the time you ran your query because of the aggregate load on the system. We will investigate this further and fix the underlying issue. For now, if you run your query again it should succeed.


Create a path transition with absolute coordinates for a StackPane object

Question: OrangeBlock is an orange block with text inside. It is implemented as a StackPane that contains text on top of a rectangle. (This approach is demonstrated in the documentation for StackPane.)
I've placed an OrangeBlock at coordinates (100, 80) and am now trying to make it travel smoothly to some target coordinates. Unfortunately I get a nasty bump in my path:

For some reason the coordinates in the PathElements are interpreted relative to the orange block.
Why is this? And how can I make my OrangeBlock travel along a path with absolute coordinates? Minimal working example below.
import javafx.animation.PathTransition;
import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.*;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;

public class PathTransitionExample extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {
        Group root = new Group();

        OrangeBlock block = new OrangeBlock(60, 40);
        block.relocate(100, 80);
        root.getChildren().add(block);

        PathTransition transition = newPathTransitionTo(block, 460, 320);

        primaryStage.setScene(new Scene(root, 600, 400));
        primaryStage.show();
        transition.play();
    }

    private static PathTransition newPathTransitionTo(OrangeBlock block,
            double toX, double toY) {
        double fromX = block.getLayoutX();
        double fromY = block.getLayoutY();

        Path path = new Path();
        path.getElements().add(new MoveTo(fromX, fromY));
        path.getElements().add(new LineTo(toX, toY));

        PathTransition transition = new PathTransition();
        transition.setPath(path);
        transition.setNode(block);
        transition.setDelay(Duration.seconds(1));
        transition.setDuration(Duration.seconds(2));

        return transition;
    }

    public static void main(String[] args) {
        launch(args);
    }

    private static class OrangeBlock extends StackPane {
        public OrangeBlock(int width, int height) {
            Rectangle rectangle = new Rectangle(width, height, Color.ORANGE);
            Text text = new Text("Block");
            getChildren().addAll(rectangle, text);
        }
    }
}

Answer: I debugged the JavaFX code out of curiosity. Seems like you are out of luck with a proper solution. Here's what happens:
The PathTransition code has a method interpolate(double frac) which includes:
cachedNode.setTranslateX(x - cachedNode.impl_getPivotX());
cachedNode.setTranslateY(y - cachedNode.impl_getPivotY());

The impl_getPivotX() and impl_getPivotY() methods contain this:
public final double impl_getPivotX() {
    final Bounds bounds = getLayoutBounds();
    return bounds.getMinX() + bounds.getWidth()/2;
}

public final double impl_getPivotY() {
    final Bounds bounds = getLayoutBounds();
    return bounds.getMinY() + bounds.getHeight()/2;
}

So the PathTransition always uses the center of your node for the calculation. In other words this works with e. g. a Circle node, but not with e. g. a Rectangle node. Moreover you need the layoutBounds, so the PathTransition must be created after the bounds were made available.
You can see in the PathTransition code that the calculations are all relative and already involve the layout position. So in your lineTo you have to consider this.
Worth noting is that the LineTo class has a method setAbsolut(boolean). However it doesn't solve your problem.
So my solution to your problem would be

creating the PathTransition after the primary stage was made visible
modification of the moveTo and lineTo parameters

This works for me (I added a Rectangle shape to identify the proper bounds visually):
public class PathTransitionExampleWorking2 extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {

        Group root = new Group();

        Rectangle rect = new  Rectangle( 100, 80, 460-100+60, 320-80+40);
        root.getChildren().add(rect);

        OrangeBlock block = new OrangeBlock(60, 40);
        block.relocate( 100, 80);

        root.getChildren().add(block);

        primaryStage.setScene(new Scene(root, 600, 400));
        primaryStage.show();

        // layout bounds are used in path transition => PathTransition creation must happen when they are available
        PathTransition transition = newPathTransitionTo(block, 460, 320);
        transition.play();
    }

    private static PathTransition newPathTransitionTo(OrangeBlock block, double toX, double toY) {

        double fromX = block.getLayoutBounds().getWidth() / 2;
        double fromY = block.getLayoutBounds().getHeight() / 2;

        toX -= block.getLayoutX() - block.getLayoutBounds().getWidth() / 2;
        toY -= block.getLayoutY() - block.getLayoutBounds().getHeight() / 2;

        Path path = new Path();
        path.getElements().add(new MoveTo(fromX, fromY));
        path.getElements().add(new LineTo(toX, toY));

        PathTransition transition = new PathTransition();
        transition.setPath(path);
        transition.setNode(block);
        transition.setDelay(Duration.seconds(1));
        transition.setDuration(Duration.seconds(2));

        return transition;
    }

    public static void main(String[] args) {
        launch(args);
    }

    private static class OrangeBlock extends StackPane {
        public OrangeBlock(int width, int height) {
            Rectangle rectangle = new Rectangle(width, height, Color.ORANGE);
            Text text = new Text("Block");
            getChildren().addAll(rectangle, text);
        }
    }
}

edit: another solution would be to use this instead of MoveTo and LineTo:
public static class MoveToAbs extends MoveTo {

    public MoveToAbs( Node node) {
        super( node.getLayoutBounds().getWidth() / 2, node.getLayoutBounds().getHeight() / 2);
    }

}

public static class LineToAbs extends LineTo {

    public LineToAbs( Node node, double x, double y) {
        super( x - node.getLayoutX() + node.getLayoutBounds().getWidth() / 2, y - node.getLayoutY() + node.getLayoutBounds().getHeight() / 2);
    }

}

Note: You still have to create the PathTransition after the primaryStage was created.
edit: here's another example with the block moving to the position of the mouse-click:
public class PathTransitionExample extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {

        Group root = new Group();

        OrangeBlock block = new OrangeBlock(60, 40);
        block.relocate(100, 80);
        root.getChildren().add(block);

        Label label = new Label( "Click on scene to set destination");
        label.relocate(0, 0);
        root.getChildren().add(label);

        Scene scene = new Scene(root, 600, 400);

        scene.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<Event>() {

            PathTransition transition;

            {
                transition = new PathTransition();
                transition.setNode(block);
                transition.setDuration(Duration.seconds(2));

            }

            @Override
            public void handle(Event event) {

                transition.stop();

                setPositionFixed(block.getLayoutX() + block.getTranslateX(), block.getLayoutY() + block.getTranslateY());

                double x = ((MouseEvent) event).getX();
                double y = ((MouseEvent) event).getY();

                Path path = new Path();
                path.getElements().add(new MoveToAbs( block));
                path.getElements().add(new LineToAbs( block, x, y));

                transition.setPath(path);
                transition.play();

            }

            private void setPositionFixed( double x, double y) {
                block.relocate(x, y);
                block.setTranslateX(0);
                block.setTranslateY(0);
            }

        });

        primaryStage.setScene( scene);
        primaryStage.show();

        PathTransition transition = newPathTransitionTo(block, 460, 320);
        transition.play();

    }

    private static PathTransition newPathTransitionTo(OrangeBlock block, double toX, double toY) {

        Path path = new Path();
        path.getElements().add(new MoveToAbs( block));
        path.getElements().add(new LineToAbs( block, toX, toY));

        PathTransition transition = new PathTransition();
        transition.setPath(path);
        transition.setNode(block);
        transition.setDelay(Duration.seconds(1));
        transition.setDuration(Duration.seconds(2));

        return transition;
    }

    public static void main(String[] args) {
        launch(args);
    }

    private static class OrangeBlock extends StackPane {
        public OrangeBlock(int width, int height) {
            Rectangle rectangle = new Rectangle(width, height, Color.ORANGE);
            Text text = new Text("Block");
            getChildren().addAll(rectangle, text);
        }
    }

    public static class MoveToAbs extends MoveTo {

        public MoveToAbs( Node node) {
            super( node.getLayoutBounds().getWidth() / 2, node.getLayoutBounds().getHeight() / 2);
        }

    }

    public static class LineToAbs extends LineTo {

        public LineToAbs( Node node, double x, double y) {
            super( x - node.getLayoutX() + node.getLayoutBounds().getWidth() / 2, y - node.getLayoutY() + node.getLayoutBounds().getHeight() / 2);
        }

    }
}

Comment: I believe those impl_getPivot**() methods are used for the PathTransition.OrientationType .. ?? .. This way if set to OrthogonalToTangent, it uses the center of node to rotate it appropriately. I could be wrong though...
Answer: The solution I'm using now is to simply offset layoutX and layoutY of the Path in the opposite direction.
private static void offsetPathForAbsoluteCoords(Path path, OrangeBlock block) {
    Node rectangle = block.getChildren().iterator().next();
    double width = rectangle.getLayoutBounds().getWidth();
    double height = rectangle.getLayoutBounds().getHeight();

    path.setLayoutX(-block.getLayoutX() + width / 2);
    path.setLayoutY(-block.getLayoutY() + height / 2);
}

Inserting a call to this method immediately after the Path instantiation fixes the problem.

I'm not really satisfied with this solution. I don't understand why layoutX and layoutY need to be involved at all. Is there a neater way?
Answer: So Basically,
the relocate(x,y) method sets the layout x/y values...
the Transition uses the translateX/Y values...
I could be wrong but I believe that when either value gets invalidated the scene runs a "layout" pass on the nodes in scene.
When this happens it tries to set the node to it's known layoutX/Y values, which are set when you call relocate(x,y) (layout values are 0,0 by default).
This causes the node to be drawn in "layoutPosition" then "pathPosition" within the transition at each step, causing jitters and the node to be offset from where it should be.
@Override
public void start(Stage primaryStage) throws Exception {
    Group root = new Group();

    OrangeBlock block = new OrangeBlock(60, 40);
    System.out.println(block.getLayoutX() + " : " + block.getLayoutY());
    block.relocate(100, 80);
    //block.setTranslateX(100);
    //block.setTranslateY(80);
    System.out.println(block.getLayoutX() + " : " + block.getLayoutY());
    root.getChildren().add(block);

    PathTransition transition = newPathTransitionTo(block, 460, 320);
    transition.currentTimeProperty().addListener(e->{
        System.out.println("\nLayout Values: " + block.getLayoutX() + " : " + block.getLayoutY()
                +"\nTranslate Values:" + block.getTranslateX() + " : " + block.getTranslateY()
    );});
    primaryStage.setScene(new Scene(root, 600, 400));
    primaryStage.show();
    transition.play();

}

private static PathTransition newPathTransitionTo(OrangeBlock block,
        double toX, double toY) {
    double fromX = block.getLayoutX();//getTranslateX();
    double fromY = block.getLayoutY();//getTranslateY();

    Path path = new Path();
    path.getElements().add(new MoveTo(fromX, fromY));
    path.getElements().add(new LineTo(toX, toY));

    PathTransition transition = new PathTransition();
    transition.setPath(path);
    transition.setNode(block);
    transition.setDelay(Duration.seconds(1));
    transition.setDuration(Duration.seconds(2));

    return transition;
}

public static void main(String[] args) {
    launch(args);
}

private static class OrangeBlock extends StackPane {
    public OrangeBlock(int width, int height) {
        Rectangle rectangle = new Rectangle(width, height, Color.ORANGE);
        Text text = new Text("Block");
        getChildren().addAll(rectangle, text);
    }
}

Not going to post pics, But my first result was like your first post, changing it to the above code gave me the second post result.
Usually it is always best to avoid "layout" values on a dynamic (moving) object for these reasons. If you like the convenience of the relocate method, I'd implement your own setting the translate values instead.
Cheers :)
EDIT:
I edited some code to print what happens as the transition is running so you can see what happens in your original version..
Answer: Both @jdub1581 and @Lorand have given valid points:

Transition is applied modifying block's translateXProperty() and translateYProperty().
Transition is applied on the center of the block.

I'll add one more thing:

We are mixing two different things: the global path we want the block to follow, and the local path we have to apply to the transition, so the block follows the first one.

Let's add a pathScene to the group:
Path pathScene = new Path();
pathScene.getElements().add(new MoveTo( block.getLayoutX(),  block.getLayoutY()));
pathScene.getElements().add(new LineTo(460, 320));
root.getChildren().add(pathScene);

This will be our scene now (I've added two labels with the coordinates of the origin and end of the path for clarity):

Now we need to determine the local path, so we'll change pathScene elements to local coordinates of the block, and translate it to its center:
Path pathLocal = new Path();
pathScene.getElements().forEach(elem->{
    if(elem instanceof MoveTo){
        Point2D m = block.sceneToLocal(((MoveTo)elem).getX(),((MoveTo)elem).getY());
        Point2D mc = new Point2D(m.getX()+block.getWidth()/2d,m.getY()+block.getHeight()/2d);
        pathLocal.getElements().add(new MoveTo(mc.getX(),mc.getY()));
    } else if(elem instanceof LineTo){
        Point2D l = block.sceneToLocal(((LineTo)elem).getX(),((LineTo)elem).getY());
        Point2D lc = new Point2D(l.getX()+block.getWidth()/2d,l.getY()+block.getHeight()/2d);
        pathLocal.getElements().add(new LineTo(lc.getX(),lc.getY()));
    }
});

As @Lorand also mentioned, this should be done after the stage is shown to compute the size of the block.
Now we can create the transition and play it.
PathTransition transition = new PathTransition();
transition.setPath(pathLocal);
transition.setNode(block);
transition.setDelay(Duration.seconds(1));
transition.setDuration(Duration.seconds(2));

transition.play();

Finally, this is all the code we need to make the block follow the desired path:
@Override
public void start(Stage primaryStage) throws Exception {
    Group root = new Group();

    OrangeBlock block = new OrangeBlock(60, 40);
    block.relocate(100, 80);
    root.getChildren().add(block);

    // Path in scene coordinates, added to group
    // in order to visualize the transition path for the block to follow
    Path pathScene = new Path();
    pathScene.getElements().add(new MoveTo(block.getLayoutX(), block.getLayoutY()));
    pathScene.getElements().add(new LineTo(460, 320));
    root.getChildren().add(pathScene);

    primaryStage.setScene(new Scene(root, 600, 400));
    primaryStage.show();

    PathTransition transition = newPathTransitionTo(pathScene, block);
    transition.play();
}

private PathTransition newPathTransitionTo(Path pathScene, OrangeBlock block) {
    // Calculate the path in local coordinates of the block
    // so transition is applied to the block without bumps
    Path pathLocal = new Path();
    pathScene.getElements().forEach(elem->{
        if(elem instanceof MoveTo){
            Point2D m = block.sceneToLocal(((MoveTo)elem).getX(),((MoveTo)elem).getY());
            Point2D mc = new Point2D(m.getX()+block.getWidth()/2d,m.getY()+block.getHeight()/2d);
            pathLocal.getElements().add(new MoveTo(mc.getX(),mc.getY()));
        } else if(elem instanceof LineTo){
            Point2D l = block.sceneToLocal(((LineTo)elem).getX(),((LineTo)elem).getY());
            Point2D lc = new Point2D(l.getX()+block.getWidth()/2d,l.getY()+block.getHeight()/2d);
            pathLocal.getElements().add(new LineTo(lc.getX(),lc.getY()));
        }
    });
    PathTransition transition = new PathTransition();
    transition.setPath(pathLocal);
    transition.setNode(block);
    transition.setDelay(Duration.seconds(1));
    transition.setDuration(Duration.seconds(2));

    return transition;
}

public static void main(String[] args) {
    launch(args);
}

private static class OrangeBlock extends StackPane {
    public OrangeBlock(int width, int height) {
        Rectangle rectangle = new Rectangle(width, height, Color.ORANGE);
        Text text = new Text("Block");
        getChildren().addAll(rectangle, text);
    }
}

Note that this solution is equivalent to the one given by @Lorand.
If we monitorize the X, Y translate properties of the block, these go from (0,0) to (360,240), which are just the relative ones on the global path.
Answer: You're using relocate function to locate your Block. relocate function makes computation on x and y for locating your object. If you used setLayoutX to locate Block and then use getLayoutX, this problem might not be happened. Same explanations is valid for y property.
You can find some informations about your problem in here: http://docs.oracle.com/javase/8/javafx/api/javafx/scene/Node.html#layoutXProperty


archive all messages account on exchange 2003 receiving multiple copies

Question: I am using microsoft exchange 2003 on windows 2003 small business server.
For the past month or so, the archiver account has been receiving multiple copies (about 15 or so) of each and every email. edit: All copies share the same Message ID.
The machine that hosts exchange is updated religiously and an antivirus scan is run on a daily basis.
So would anyone please have any ideas about how to deal with this
and furthermore, how i would be able to delete the multiple copies of emails from outlook 2003 inbox.
I will edit the entry, answering any questions or updating on my efforts
Thanks in advance
Comment: Are you sure the messages are exact duplicates, and not a separate message because some user had their mail account set to forward messages to somewhere else?
Comment: sender, recipient, subject and time are consistent among all duplicate copies. is there something i should check in the headers?
Answer: Look at the actual message ID, this will tell you if they're duplicate copies of the same message or not. If there's a unique message ID for each message, then they're unique messages and not copies of the same message.
Comment: i'm afraid the message ID is identical, thanks
edited the question accordingly
Comment: Are you exluding the Exchange directories and processes from your AV software?

http://support.microsoft.com/kb/823166
Comment: there are some viruses in the exchange directory, the items are quarantined, I'd have to dismount the mail server to clean them up and I haven't had the chance yet.
Answer: I don't know what caused this, but it is now solved:
I created a new user to receive all email that goes through the Exchange server. As soon as the previous user was deselected, he started to receive single copies of the emails that hadn't yet been downloaded.
I tried using a vba script to delete the multiple copies of received emails, that failed. Finally got around to doing it using one of the various shareware "duplicate delete" programs out there.
Thanks for all the replies.


Geometric interpretation of the maximum likelihood estimation

Question: I was reading the book The Identification Problem In Econometrics by Franklin M. Fisher, and was confused by the part that he demonstrates the identification by visualizing the likelihood function.
The problem could be simplified as:

For a regression $Y=a+Xb+u$, where $u \sim i.i.d. N(0,\sigma^2I)$,
  $a$ and $b$ are the parameters. Suppose $Y$ has a coefficient $c$ which
  equals to unity. Then the likelihood function in the space of $c, a,b$
  would have a ridge along the ray corresponding to the vector of true
  parameters and its scalar multiples. When considering only the place
  given by $c=1$, the likelihood function would have a unique maximum at
  the point where the ray intersected that plane.

My questions are:

How should one understand and reason about the ridge and the ray mentioned in the demonstration.
Since the ray are the true parameters and scalars, why is the ray not on the plane given by $c=1$ since the true value of parameter $c$ is 1.
Answer: Out of context this passage is a bit vague but here is how I interpreted it.
Suppose I wanted to perform a linear regression on $cY$.  I would write $cY = a' +Xb' + u$ where $u \sim N(0, c^2 \sigma^2)$.  If $Y=a_0+Xb_0$ are the true parameters then clearly $cY = c a_0 + Xcb_0$ are the true parameters of $cY$.
For fixed $c$ the likelihood function for this regression on $cY$ has a unique maximum at the point $a'=ca_0$ and $b' = cb_0$.  Thus, for general $c$ the ray of scalar multiplies of the true parameter forms the ridge of the likelihood function as a function of three variables. Now take $c=1$ to intersect with the $c=1$ plane.


Why does $|x|^2$ not equal $x^2$

Question: A friend told me that the two are unequal. I had a though that maybe one has two solutions on the same point, but from what I can tell that's not the case.
Edit: LaTeX is hard :).
Comment: for real numbers $x$, they are equal. If you allow for complex numbers, then not necessarily (look at $x=i$).
Comment: Interesting. Thank you!
Answer: Consider the case when $x$ is a complex number.
Let's express $x$ in the form $x=a+b\mathrm{i}$, where $a\ne 0$ and $b\ne 0$. Then, we have $|x|^2=a^2+b^2$, but $x^2=a^2-b^2+2ab\mathrm{i}\ne a^2+b^2$. This demonstrates that $|x|^2$ and $x^2$ are not equal.
Answer: The fundamental problem of your question is that you haven't defined what $x$ is. If $x$ is a real number, $|x|^2$ and $x^2$ are equal.

Why does $|x|^2$ not equal $x^2$


how to change h2 tag for div in block_view

Question: I've created a block like this
function mymodule_block_view($delta = '') {
    if($delta == 'myblock') {
        $block['subject'] = 'mytitle';
        $block['content'] = myfunction();
    }
    return $block;
}

but the output is like this:

mytitle

I need change h2 to div

mytitle

I've tried with _preprocess_block hook but i cant change that tag
could you please help me?
Comment: this may help https://drupal.stackexchange.com/questions/236069/why-the-content-of-a-block-created-in-an-external-module-does-not-appear/236078#236078
Comment: Override the default block template. Try: "How to theme a custom block" https://drupal.stackexchange.com/a/39270/28700
Comment: hi, thanks @pinueve but that add a div tag inside h2, title
Comment: You could use a theme hook with a template thus have complete control of your html output. Take a look here: https://drupal.stackexchange.com/questions/39023/how-to-theme-a-custom-block
Comment: just built $content in yourfuction($args);
Comment: @seroton thanks but that add a div tag inside h2, title
Answer: try with the following:

Implement hook_theme_registry_alter to take the templates from your module.

/**
 *  Implements hook_theme_registry_alter().
 */
function mymodule_theme_registry_alter(&$theme_registry) {
  // Defined path to the current module.
  $module_path = drupal_get_path('module', 'mymodule') . "/templates";
  // Find all .tpl.php files in this module's folder recursively.
  $template_file_objects = drupal_find_theme_templates($theme_registry, '.tpl.php', $module_path);
  // Iterate through all found template file objects.
  //test if this page isn't in BO page
  if (!path_is_admin(current_path())) {
    foreach ($template_file_objects as $key => $template_file_object) {
      // If the template has not already been overridden by a theme.
      if (!isset($theme_registry[$key]['theme path']) || !preg_match('#/themes/#', $theme_registry[$key]['theme path'])) {
        // Alter the theme path and template elements.
        $theme_registry[$key]['theme path'] = $module_path;
        $theme_registry[$key] = array_merge($theme_registry[$key], $template_file_object);
        $theme_registry[$key]['type'] = 'module';
      }
    }
  }
}

Copy modules/block/block.tpl.php and past it in templates folder of your module.
Rename it from block.tpl.php to block--mymodule--myblock.tpl.php to change only for your block.
Change the line from <h2<?php print $title_attributes; ?>><?php print $block->subject ?>
 to <div<?php print $title_attributes; ?>><?php print $block->subject ?>

Clear cache.


react-hook-form Is it possible to validate onTouched and when last field is being filled?

Question: I have my mode set to onTouched to validate the fields on blur.  I also have my Submit form button to be disabled unless the form isValid.  The problem is that when the user is in the last field and typing AND it's valid, and all other fields are valid, the submit button is still disabled.  I would like it to be enabled at that point and the field to be validated.
Essentially, I would need to have the mode change to all or onChange once the user is in the last field, and all other fields a filled.
Edit: duplicate of Enable/disable submit button with react-hook-form in onBlur mode
Comment: `isValid` should just update when the fields become valid. There shouldn't be a need to `blur` or leave the input first. So there might be something else causing this issue. Where is your useForm defined, in the same component as the fields or somewhere higher up the chain?
Comment: Sharing some code might be helpful in this case
Comment: @Y.Gherbi it's in the same component.  `isInvalid` becomes true `onBlur` of the last field that is valid, but not when still focused inside the field even though it's valid.  So it appears `isValid` is working.
Comment: You are right! I looked up a project and posted how we did it. Let me know if this worked for you, they change quite a lot with their version upgrades
Comment: Could you accept an answer for this question if it helped you or if it didn't help you please comment with your problem or the fix if you have found one yourself. This way, we can help the next person with the same problem :) @avocodoo
Answer: You can change the default behavior by passing options to your useForm.
Depending on your version, this should work. (I tested this on V6)
const defaultValues = {
  name: '...'
}

const form = useForm({
  mode: 'onChange',
  reValidateMode: 'onChange',
  defaultValues,
});
const { isValid } = form.formState;

This will revalidate on onChange instead of on onBlur. You can also use this interchangeably with other events.
Comment: Could you accept this as an answer if it helped you or if it didn't help you please comment with your problem or the fix if you have found one yourself? This way, we can help the next person with the same problem :) @avocodoo


Injecting one service in another service angular js

Question: Can i use one service into another angular service? Else what will be the best approach to accomplish the below?
First Service:
var app = angular.module("MyApp", []);
app.service('Service1', function () {
    return {
        FirstFunction: function () {
            return "something";
        }
    }
});

Second service:
app.service('Service2', function () {
    return {
        SecondFunction: function () {
           //How to use FirstFunction of Service1 ???
        }
    }
});

Thanks
Answer: app.service('Service2', function (Service1) {
    return {
        SecondFunction: function () {
           Service1.FistFunction
        }
    }
});

As long as service2 doesnt depend on service1 there is no problem.
Answer: app.service('Service2', function (Service1) {
    return {
        SecondFunction: function () {
           Service1.FirstFunction();
        }
    }
});

Comment: Thanks alot.Works great. I just tried the below which didnt work. What is the reason.                                                     app.service('Service2',["Service1", function (Service1) {
    return {
        SecondFunction: function () {
           Service1.FirstFunction();
        }
    }
}]);


Retornar data de hoje em C# em formato específico

Question: Minha saída tem que ser "2015-02-01"
Tentei por DateTime.Now.ToString("yyyy-m-d"), mas ela não poem os 0 entre os dias e os meses.
Answer: Se quer dois dígitos, precisa especificar dois dígitos:
DateTime.Now.ToString("yyyy'-'MM'-'dd");
DateTime.Now.ToString("yyyy-MM-dd");

Atenção com as maiúsculas. m é minuto, M é mês.
Veja funcionando no IDEONE.
Não está na pergunta, mas tem duas coisas importantes que podem ser úteis:

além do Now, existe o UtcNow.
para converter UTC para tempo local, você tem o ToLocalTime(). Pode usar vinculado a um TimeZone específico, se preferir.

Seguem os campos mais comuns:
   d   dia do mês,  1-31
  dd   dia do mês, 01-31
 ddd   dia da semana ( Dom, Seg ... )
dddd   dia da semana ( Domingo ... )
   h   hora  1-12
  hh   hora 01-12
   H   hora  0-23
  HH   hora 00-23
   m   minuto  0-59
  mm   minuto 00-59
   M   mês     1-12
  MM   mês    01-12
 MMM   mês (Jan, Fev ... )
MMMM   mês (Janeiro ... )
   s   segundo  0-59
  ss   segundo 00-59
   t   A/P
  tt   AM/PM
   y   ano     0-99
  yy   ano    00-00
 yyy   ano   000-999
yyyy   ano  0000-9999
   :   separador de tempo
   /   separador de data
"string" / 'string' valor literal

Documentação oficial:
https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
Answer: Já existe resposta que atende ao solicitado, mas há um padrão que pode ser mais adequado, dependendo do que se está fazendo. Claro que a necessidade específica pode ser usar um formato definido pelo programador ali mesmo, mas na maioria dos casos o melhor é é usar uma padrão conhecido ao invés de "inventar" um padrão. Então na maior parte dos casos o código mais correto pra isto é usar a cultura.
DateTime.Now.ToString(new CultureInfo("pt-BR", false).DateTimeFormat.ShortDatePattern)

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Dei uma opção usando a cultura corrente que deve ser a mais adequada na maioria dos casos, afinal é comum a aplicação deixar as configurações gerais do usuário determinar isto e não o que o programador quer que o usuário veja. Note que o dotNetFiddle usa o padrão americano por padrão, por isso fica fora do esperado. Fiz também com cultura invariante. O assunto é extenso e não cabe aqui.
Obviamente é possível usar outras culturas, incluindo uma que usar o padrão ano-mês-dia, por exemplo: ko, pl, sv, lt, mn, km, si, ko-KR, pl-PL, sv-SE, lt-LT, mn-MN, km-KH, si-LK, se-SE, fr-CA, en-CA, smj-SE, en-ZA, sma-SE, sma, mn-Cyrl, smj.


$p$ and $\neg\,q$ implies not $q$

Question: I need help showing the equivalence of $(p \wedge \neg q) \implies ¬q$. I know I have to use the equation $p \implies q = \neg\,p \lor q$, but I don't know how to begin changing the propositions around. Any help would be appreciated.
Comment: You are talking about equivalence, but I do not see any. Do you mean that the term is always true, that it is a tautology?
Comment: Yes, but I have to show it is a tautology by establishing a sequence of equivalences.
Answer: $$\begin{array}{lcl}(p \wedge \neg q)\rightarrow \neg q & \Leftrightarrow & \neg (p\wedge \neg q) \vee \neg q \\ & \Leftrightarrow & \neg[(p\wedge \neg q)\wedge q] \\ &\Leftrightarrow & \neg [p\wedge (\neg q\wedge q)] \\ & \Leftrightarrow & \neg (p\wedge 0) \\ & \Leftrightarrow & \neg 0 \\ &\Leftrightarrow & 1 \end{array}$$
Answer: Hint
$$A\implies B \equiv \neg A \lor B$$
If you apply this to your expression, you get
$$\neg(p\land \neg q)\lor \neg q$$
Now, use DeMorgan's law $\neg(A\lor B)\equiv \neg A\land \neg B$ and use the distributivity of $\land$ and $\lor$, i.e.
$$A\lor(B\land C)\equiv (A\lor B)\land (A\lor C)$$
What do you get?
Comment: The OP already stated that, in their question.
Answer: It is easier to use the equivalence
$$(A\implies B)\iff (\lnot B\implies \lnot A) $$

$p$ and $\neg\,q$ implies not $q$


django-rest-framework speed-up endpoint with http requests

Question: I have an application on DRF and there is an endpoint inside which sends an http requests in the loop for each item.
Endpoint is very slow because of this, any ideas how to speed it up?
example of code
class MyView(APIView):
    def get(self, request: Request) -> Response:
        for cat in Cats.objects.all():
            data = CatsInfoService.get_info(cat) # send http request
        return Response({"message": "ok"})

Comment: You might consider using a task scheduler for sending the HTTP requests. Something using celery will do the work.
Answer: Have you tried using an iterator like this?
class MyView(APIView):
    def get(self, request: Request) -> Response:
        for cat in Cats.objects.all().iterator():
            data = CatsInfoService.get_info(cat)
        return Response({"message": "ok"})

Also, I think this article could help as well Optimize Django Queryset for loop


finding the average of the largest numbers input out of 3 by the user in c++

Question: So the design problem is:
Input 3 numbers and display the largest. Keep inputting sets of 3 numbers until the user wants to quit. Find the average of all of the largest numbers.
So entering the numbers works fine but when I try to plug in the SENTINEL value to stop the loop I need to type it in for all 3 numbers and it doesn't give me a correct average for the past numbers entered.
Any help is greatly appreciated thank you for your time!
 #include <iostream>
 using namespace std;

int main()
{

    const int SENTINEL = -1;
    int num1;
    int num2 = 0;
    int num3 = 0;
    int largest;
    int sum;
    int count;
    float average;

    // initialize the count and sum
    count = 0;
    sum = 0;

    while (num1 != SENTINEL)
    {

        // Prompt user for the first number or to quit
        cout << "If you want to quit enter " << SENTINEL << " to stop\n " << endl;
        cout << "Enter first number  ";
        cin >> num1;

        // Prompt the user for the second number
        cout << "please enter second number                  ";
        cin >> num2;

        // Prompt the user for a third number
        cout << "please enter the third number               ";
        cin >> num3;

        // Compare numbers 1 and 2 for the largest number
        if (num1 > num2)
        {
            largest = num1;
        }
        else
        {
            largest = num2;
        }

        // Compare largest to last number input
        if (num3 > largest)
        {
            largest = num3;
        }

        // Display the largest number
        cout << "largest number is: " << largest << endl;

        // Increment the count
        count++;

    }

    if (count > 0)
    {
        average = sum / count;
        cout << "Average of the numbers is " << average;
    }

    return 0;
}

Comment: You don't initialize `num1` before you use it, which leads to [*undefined behavior*](http://en.wikipedia.org/wiki/Undefined_behavior). You also don't increase the sum.
Comment: I will change it to initialize num1 thanks I realize I haven't added to increase the sum yet but the code is not complete the problem I am doing it in pieces and testing it and was stuck at this part..
Answer: Using a break; instruction is a possibility, but often considered unelegant and hard to maintain.
The reason is that you break the flow of the code, and the reader of your program (that may not be you in big programs or if you share it) expect the code of your loop to be continued to the end of it. If your function has one or several break;instructions, it may be hard to understand the intent of the function, because you have to remember in which cases the loop will have already ended.
The basic principle to solve your problem is to start your loop at the right place, just after getting a value for num1. Then your loop also has to end with it. That way, you will always check your exit condition right after the user keyed in num1.
// initialize the count and sum
count = 0;
sum = 0;

// Prompt user for the first number or to quit
cout << "If you want to quit enter " << SENTINEL << " to stop\n " << endl;
cout << "Enter first number  ";
cin >> num1;

while (num1 != SENTINEL)
{

    // Prompt the user for the second number
    cout << "please enter second number                  ";
    cin >> num2;

    // Prompt the user for a third number
    cout << "please enter the third number               ";
    cin >> num3;

    // Compare numbers 1 and 2 for the largest number
    if (num1 > num2)
    {
        largest = num1;
    }
    else
    {
        largest = num2;
    }

    // Compare largest to last number input
    if (num3 > largest)
    {
        largest = num3;
    }

    // Display the largest number
    cout << "largest number is: " << largest << endl;

    // Increment the count
    count++;

    // Prompt user for the first number or to quit
    cout << "If you want to quit enter " << SENTINEL << " to stop\n " << endl;
    cout << "Enter first number  ";
    cin >> num1;
}

if (count > 0)
{
    average = sum / count;
    cout << "Average of the numbers is " << average;
}

return 0;

Note: I did not solve the code mistakes here, as mentioned in the comments (variables not being declared, the sum not being updated, etc.).
Comment: 1. You're replicating code (those 3 lines that appear before the loop and at the end of each iteration), which is even less elegant than a `break` (what's not elegant about a `break` anyway?). 2. You forgot one small thing required for this program to actually work (hint: `sum` has something to do with it).
Comment: Replicating code is indeed not elegant either, but I would not say less than `break`. The problem with the break instruction is that it breaks the flow of the code. In one small program, it may not be very important, but you expect a loop to be continued from the start to the end. Having to look for other possible termination of the loop makes the code harder to read, and is forbidden or really not appreciated in a lot of companies.
Answer: Conditionally break your loop immediately after input of num1.
cin >> num1;
if (SENTINEL == num1)
{
  break;
}

Comment: I can't use a break unless its a switch statement per the instructor I tried it lol
Comment: Then use `continue;` instead :) it jumps to the next iteration which then checks the SENTINEL
Answer: After
cin >> num1;

You can check, if its SENTIEL number and break from the loop:
if (num1 == SENTIEL)
    break

so that it will not execute another cin's.


android ContactsContract.CommonDataKinds.GroupMembership and ICS

Question: I need to find out if a particular contact is a member of a given group.  I have been working with the code below and have proved that it works using a handset running Gingerbread.  However I have been trying to run it on my HTC One S running Android version 4.0.3 and it is failing.  Has the API spec changed?  My code is below.
public boolean checkGroupMembership(String groupID, String contactID, Context ctx) {
            ContentResolver groupContentResolver = ctx.getContentResolver();
                        String select = "contact_id=" + contactID +
                    " AND " + GroupMembership.GROUP_ROW_ID + " = " + groupID +
                    " AND mimetype='vnd.android.cursor.item/group_membership'";

            Cursor contactGroupCursor =
                    groupContentResolver.query(
                        Data.CONTENT_URI,
                        new String[] { GroupMembership.CONTACT_ID,  GroupMembership.GROUP_ROW_ID, GroupMembership.IN_VISIBLE_GROUP },
                        select,
                        null,
                        null);
            int records = contactGroupCursor.getCount();
            try {
            while(contactGroupCursor.moveToNext()){
                String ContactID = contactGroupCursor.getString(contactGroupCursor.getColumnIndexOrThrow(GroupMembership.CONTACT_ID));
                String groupRowId = contactGroupCursor.getString(contactGroupCursor.getColumnIndexOrThrow(GroupMembership.GROUP_ROW_ID));
                String InVisiblegroup = contactGroupCursor.getString(contactGroupCursor.getColumnIndexOrThrow(GroupMembership.IN_VISIBLE_GROUP));

                Log.d("DEBUG", "groupSourceId in checkGroupMembership: " + groupRowId + "  InVisiblegroup = " + InVisiblegroup);
                Log.d("DEBUG", "ContactID in checkGroupMembership: " + ContactID);

                }
            }
            finally
            {
                contactGroupCursor.close();
            }

            // see if the contact is in this group
            if (records > 0) {
                return true;
            }
            else {

            return false;
            }
        }

    }

In addition changing the query to purely find out what groups the contact is a member of:
String select = "contact_id=" + contactID;

results in the following debug output. In some cases groupRowID looks like a group ID, in others it is the contact number or the name of the contact.  Note that I am using my home landline to call test and this is appearing.  Also - I only have 10 groups defined on the handset and an id of 11, 12 and 13 is printed in the output... It could be that I'm missing something?  I definitely know that the contact_id I'm passing in is a member of the Coworkers group (group_ID 5 on my phone) but this is never returned in ICS.  I have independently verified the group membership for HOME using contact manager apps on both handsets.

11-04 11:48:21.980: D/DEBUG(10145): select in checkGroupMembership :
  contact_id=133 11-04 11:48:21.990: D/DEBUG(10145): count of records in
  checkGroupMembership: 13 11-04 11:48:22.000: D/DEBUG(10145):
  groupRowId in checkGroupMembership: null  InVisiblegroup = 1 11-04
  11:48:22.000: D/DEBUG(10145): ContactID in checkGroupMembership: 133
  11-04 11:48:22.000: D/DEBUG(10145): groupRowId in
  checkGroupMembership:   InVisiblegroup = 1 11-04 11:48:22.000:
  D/DEBUG(10145): ContactID in checkGroupMembership: 133 11-04
  11:48:22.000: D/DEBUG(10145): groupRowId in checkGroupMembership:
  004-414-83326995  InVisiblegroup = 1 11-04 11:48:22.000:
  D/DEBUG(10145): ContactID in checkGroupMembership: 133 11-04
  11:48:22.000: D/DEBUG(10145): groupRowId in checkGroupMembership:
  014-833-26995  InVisiblegroup = 1 11-04 11:48:22.000: D/MYOB(10145):
  ContactID in checkGroupMembership: 133 11-04 11:48:22.030:
  D/MYOB(10145): groupRowId in checkGroupMembership: 01483326995
  InVisiblegroup = 1 11-04 11:48:22.030: D/DEBUG(10145): ContactID in
  checkGroupMembership: 133 11-04 11:48:22.030: D/DEBUG(10145):
  groupRowId in checkGroupMembership: 10  InVisiblegroup = 1 11-04
  11:48:22.030: D/DEBUG(10145): ContactID in checkGroupMembership: 133
  11-04 11:48:22.030: D/DEBUG(10145): groupRowId in
  checkGroupMembership: 11  InVisiblegroup = 1 11-04 11:48:22.030:
  D/DEBUG(10145): ContactID in checkGroupMembership: 133 11-04
  11:48:22.030: D/DEBUG(10145): groupRowId in checkGroupMembership: 12
  InVisiblegroup = 1 11-04 11:48:22.030: D/DEBUG(10145): ContactID in
  checkGroupMembership: 133 11-04 11:48:22.030: D/DEBUG(10145):
  groupRowId in checkGroupMembership: 13  InVisiblegroup = 1 11-04
  11:48:22.030: D/DEBUG(10145): ContactID in checkGroupMembership: 133
  11-04 11:48:22.030: D/DEBUG(10145): groupRowId in
  checkGroupMembership: 7  InVisiblegroup = 1 11-04 11:48:22.030:
  D/DEBUG(10145): ContactID in checkGroupMembership: 133 11-04
  11:48:22.030: D/DEBUG(10145): groupRowId in checkGroupMembership: 8
  InVisiblegroup = 1 11-04 11:48:22.030: D/DEBUG(10145): ContactID in
  checkGroupMembership: 133 11-04 11:48:22.030: D/DEBUG(10145):
  groupRowId in checkGroupMembership: 9  InVisiblegroup = 1 11-04
  11:48:22.030: D/DEBUG(10145): ContactID in checkGroupMembership: 133
  11-04 11:48:22.030: D/DEBUG(10145): groupRowId in
  checkGroupMembership: HOME  InVisiblegroup = 1 11-04 11:48:22.030:
  D/DEBUG(10145): ContactID in checkGroupMembership: 133

P.S. please could someone with sufficient privileges please add "GroupMembership" as a tag to the site.
Comment: I have updated the code (runs in a separate application) that I've been using to list the groups on the device to also return groups.SYSTEM_ID and this is now bringing back group _IDs of 11, 12 and 13.  So now I'll have to figure out how to pick based on system_id which is a little tricky because some of the entries appear 2 or 3 times for the same group (based on Groups.TITLE). The code is:  final Cursor cursor = contentResolver.query(Uri.parse("content://com.android.contacts/groups"),
    (new String[] { Groups._ID, Groups.SYSTEM_ID, Groups.TITLE}), null, null, null);
Answer: Nothing's changed in group membership between Honeycomb and 4.0.3.
It would be easier to read all this if you used LogCat or even did a ListView and screenshot or something. It's hard to understand what your problem is. You can do a dump of
ContactsContract.Groups to see what groups are defined for the database. Unless you're absolutely certain that both handsets have exactly the same data, you're gonna find differences. The only way to ensure they have exactly the same data is to wipe the contacts data off them and sync them both to a small test dataset.
Comment: Please see the image below which has a photo of what is returned as a dump of the groups - from Gingerbread and ICS.  As you can see it's very different...
Answer: The image below shows a dump of the groups from Gingerbread (Cyanogen) and ICS (HTC) produced using exactly the same code.  As you can see they are quite different in terms of how the data is presented.  For some reason the groups are duplicated to some extent in ICS.  So the question is how do I manage this across different versions if I'm planning to use the group _ID to perform lookups. Note that in the contacts app on ICS each group appears only once so how do I know which ID this refers to?
Comment: I guess the answer is to use the group name as the key data to perform lookups, which isn't what I'd call ideal, but it will work for both provided I de-dupe along the way.  If anyone is able to uncover why these are so different or how the differences can be addressed another way I'd be pleased to here from you.
Comment: I did figure this out ages ago, but haven't found time to update until now.  The query returns Phone Groups AND Google Groups and using the Group Name as the key works as it will pick up the correct membership regardless of where the user's contact entry is tagged - i.e. on the handset or in Google.


Get date of last update for a view

Question: Is there an easy way to check when I last made changes to a particular view or views display?
Answer: No, unfortunately there isn't.  If you look at the views_view and views_display tables in the Drupal database, that information simply isn't stored.
I even checked whether you can get to info like that if you're using the Features module with views, but even that only lets you know if a view has been updated since your last created feature, but gives no information about the date of any changes...

Get date of last update for a view


Digital piano: adjacent notes make wavering "wobble" sound when played together

Question: I played an acoustic piano for years, long ago. I just purchased my first digital piano to get back into it, a Yamaha P-35. I immediately started playing one of my old favorite songs. It sounds great for the most part, but something sounded off to me. The song has a lot of steps down from F# to F (just above middle C), and I eventually realized that when these two notes are played together there is a weird wobbling/wavering/vibrating sound effect. It sounds like something that could happen with an acoustic device (interference between sound frequencies?) and I know these digital pianos are designed to emulate real acoustics as much as possible, but this vibrating for some reason is really grating on my ears, and I just don't remember ever hearing it before when I played this song on an acoustic piano years ago.
I don't have access to an acoustic piano (or any other piano) right now, so I have no way to figure out if this is normal or not. I've recorded a short audio file which is hosted here. In the recording I hit in series:

F# alone
F alone
F step into F# while continuing to hold both

Listen to the 3rd sound, specifically as it starts to fade out turn the volume up very high and you should here the wobbling I'm talking about. In the recording I don't notice it nearly as much as when I'm playing and have headphones on or using the keyboard's speakers.
Can any experts or acoustic piano owners let me know if this is normal, or some kind of issue?
(I also just noticed that even looking at the pulsing circle graphic on the file host where I uploaded the mp3, the vibrations in the 3rd sound are visible)
Answer: It sounds like you are noticing the beat frequency, which is completely normal and something you ought to hear on a proper piano as well. A lot of old/upright pianos will have a somewhat muddy sound (compared to the concert grand emulated by most digital pianos) which could make it less noticeable, though. A minor second is quite a dissonant interval so I would think that's the reason it bothers you.
Comment: You are listening very closely and analytically, with the volume right up.  If you did that to an acoustic piano you'd hear all sorts of stuff too!
Comment: Thank you! I wouldn't be surprised if this piano does indeed have better sound than the cheap upright I played growing up. That's probably why I never noticed it before. Other than that one issue I am loving the sound on this!


Stop autopostback on keyboard input for dropdownlist

Question: Is there any way do delay the autopostback on a dropdownlist until the list actually loses focus?  I want to accept input from the keyboard without the page posting back after every keystroke.  For example, take this code:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true">
<asp:ListItem >Test1</asp:ListItem>
<asp:ListItem >Tst1</asp:ListItem>
<asp:ListItem >twotest</asp:ListItem>
</asp:DropDownList>

Say I want to select twotest.  I tab to the ddl and input 'tw' into my keyboard.  However, as soon as the 't' is entered, the page automatically posts back, while the 'w' input is lost.  Resetting focus doesn't really help any as then the ddl thinks that 'w' is the first input.  Any help would be appreciated.
Answer: It seems impossible. You must remove AutoPostBack="true" and try another way to perform postback. Consider below solution:
when dropdown ddlCountry changed, the function ddlCountry_changed is called that trigger btnLoad click to perform postback. The button btnLoad is put inside an update panel so the page is not reload and you still have focus on the dropdown.

Country:
<asp:DropDownList ID="ddlCountry" runat="server" onchange="ddlCountry_changed();">
    <asp:ListItem Text="Vietnam" Value="1"></asp:ListItem>
    <asp:ListItem Text="United State" Value="2"></asp:ListItem>
</asp:DropDownList>

<asp:UpdatePanel ID="updatePanel" runat="server">
    <ContentTemplate>
        <asp:Button ID="btnLoad" style="display: none" runat="server" OnClick="btnLoad_OnClick" />
    </ContentTemplate>
</asp:UpdatePanel>

Comment: I was hoping to stay way from more chunks of javascript, as the application is already a mess.  Updatepanels all around too, so I can't exactly use them as you have here.  OnBlur would probably work instead of onchange though.
Answer: It's a little more complicated than just handling the blur. You need to remove the onchange attribute (AutoPostBack="false") so keyboard navigation is possible and attach event handlers that submit the form when the value has changed via clicking, blur, or the enter key is pressed.
I ran into this same issue and created a plugin for handling this.  Check out https://github.com/bstruthers/AutoPostBack-Fix.


Backup solution (includes tape backup)

Question: What would be the best Linux based solution for backup (later maybe tape backup too). There are Bacula, Amanda, and others.
Any suggestions which to learn ?
(Now I use compressed tarballs simply)
Answer: I highly recommend looking into bacula. It does take quite a bit of work to get it up and running, however once up it is rock solid. If you need any assisstance let me know.
Answer: I would also recommend Bacula. We are using it for backing up sensitive information for several clients with between 2 and 15TB of data. Bacula also helped detect subtle data corruption caused by a faulty LTO4 tape drive.
Answer: The "best" is the one that fully suits your needs and provides reliable restore capabilities. Just don't forget to factor off-site into the equation.
Answer: I was recently was facing same decision and I went with Amanda. It was hard choice because both are good and both have weaknesses. So, my decision boiled down to personal preferences, i.e. GUI vs. command line, dependency on database or no database, etc. My advice go with one that fits you better - they are both good.
Comment: unfortunately its hard to explain to a non-technical client about how zmanda is a rock solid service with a command line tool. They just say, oooh isnt the the web-bacula web interface all clicky clicky nice. So bacula wins the "client sell" test.
Comment: And are you satisfied with Amanda ? It seems to me, it's GUI is only in the commercial version.
Comment: I completely satisfied with Amanda's functionality and I prefer command line interface for setting thing up. As with any backup system, you just need to set it up once and then it should work with little human interaction. So, it may take less time to set it up through the GUI but CLI gives more control. But again, this is just personal preference and both systems are good. And yes, they have commercial version that offers even more, so it keeps some extra options open.
Answer: I have eared about rdiff-backup which is simple to use, and does the job well.

Backup solution (includes tape backup)


Combination of a standard random variable and a standard uniform random variable

Question: Edited: Let $X$ be a Gamma distributed r.v., $X \sim\Gamma(\alpha,\beta)$ and $Y$ be a standard uniformly distributed r.v., $Y \sim U(0,1)$. Then what is the distribution of a r.v. $Z=XY$?
Comment: What is the _joint_ distribution of $X$ and $Y$? Also, regarding your hypothesized distribution for $XY$, what happens when $X < 0$?
Comment: @Dilip Sarwate that's a very good point. I have made adjustments to the question.
Answer: Assuming that $X$ (the Gamma rv) and $Y$ (uniform rv) are independent, indicating with  $f_Z(z)$ the probability density function of the r.v. $Z$ for $z>0$, this is
$$
{f_Z}\left( z \right) = \frac{{\Gamma \left( {\alpha  - 1,\frac{z}{\beta }} \right)}}{{\beta \,\, \Gamma \left( \alpha  \right)}}
$$
where $\Gamma \left( {\alpha  - 1,\frac{z}{\beta }}\right)$ is the incomplete Gamma function.
To find this result you need to apply the theory of Mellin transform. The probability density of the product of two independent random variables is given, in particular by the Mellin convolution of their densities expressed as
$$
{f_Z}(z) = \int_0^\infty  {\frac{1}{s}{f_X}\left( {\frac{z}{s}} \right){f_Y}\left( s \right)ds}.
$$


Assumption to apply the delta method

Question: When proving the delta method of distributions in my textbook we make the following assumption:
Let $X_{n}$ be a sequence of random variables.
and:
${\sqrt{n}[X_n- c]\,\xrightarrow{D}\,\mathcal{N}(0,1)}$
Bearing this in mind it can be shown that:
${\sqrt{n}[g(X_n)-g(c)]\,\xrightarrow{D}\,\mathcal{N}(0,[g'(c)]^2)}$
What I'm struggling to understand why in this case the assumption to implement the delta method is:
${\sqrt{n}[X_n- c]\,\xrightarrow{D}\,\mathcal{N}(0,1)}$
and not
${\sqrt{n}[X_n- c]\,\xrightarrow{D}\,\mathcal{N}(0,\sigma^{2})}$?
Usually $X_{n}$ is an estimator of a population parameter and $c$ the actual parameter being estimated. If the estimator is a consistent asymptotically normal estimator we can conclude that:
${\frac{\sqrt{n}[X_n- c]}{\sigma}\,\xrightarrow{D}\,\mathcal{N}(0,1)}$
Would it be safe to assume that here $\sigma^{2} = 1$ is assumed here?
Comment: Don't mix asymptotics with ability to apply the delta method in a given non-huge dataset.  You may find that the transformed statistic has a very asymmetric distribution, something ignored by the delta method.
Comment: What is your reference?  I'm used to the [Taylor Series derivation](https://cran.r-project.org/web/packages/modmarg/vignettes/delta-method.html), which assumes higher order terms can be neglected.  The [wikipedia entry](https://en.wikipedia.org/wiki/Delta_method#Univariate_delta_method) (terrible reference) has the $N(0,\sigma^2)$
Comment: In this context (nondegenerate Normal distributions) you can *always* take $\sigma^2=1$ because the value of $\sigma$ merely establishes what your unit of measurement is.
Answer: The two statements :
$$\left(\sqrt{n}(X_n - c) \overset{D}{\to}\mathcal{N}(0, 1)\right) \Longrightarrow \left(\sqrt{n}(g(X_n) - g(c)) \overset{D}{\to}\mathcal{N}(0, g'(c)^2)\right) $$
and
$$\left(\sqrt{n}(X_n - c) \overset{D}{\to}\mathcal{N}(0, \sigma^2)\right) \Longrightarrow \left(\sqrt{n}(g(X_n) - g(c)) \overset{D}{\to}\mathcal{N}(0, g'(c)^2\sigma^2)\right) $$
are equivalent.
The second one clearly implies the first one (take $\sigma = 1$).
Now, assume the first one is true, and suppose that
$$\sqrt{n}(X_n - c) \overset{D}{\to}\mathcal{N}(0, \sigma^2). $$
Define $Y_n = \frac{X_n}{\sigma}$, $c' = \frac{c}{\sigma}$ and $g_1 : t \mapsto g(\sigma t)$.
Then you have
$$\sqrt{n}(Y_n - c') \overset{D}{\to}\mathcal{N}(0, 1),$$
and thus
$$\sqrt{n}\left(g_1(Y_n) - g_1(c')\right) \overset{D}{\to}\mathcal{N}(0, g_1'(c')^2)$$
which gives
$$\sqrt{n}(g(X_n) - g(c)) \overset{D}{\to}\mathcal{N}(0, g'(c)^2 \sigma^2).$$

Assumption to apply the delta method


Find values of $a$ such that $\frac{x^2-x}{1-ax}$ attains all real values

Question:
Find values of $a$ such that
  $$\frac{x^2-x}{1-ax}$$
  attains all real values.

I first tried to find the range of the above by equating the above to some $y$. Solving I get $x^2+x(ay-1)-y=0$. How do I proceed?
Comment: Not clear what you mean: The function $f(a,x)=\frac{x^2-x}{1-ax}$ will simplify to $f(1,x)=-x$ which attains all real values.
Comment: @gammatester Which means that $1$ is one value of $a$ for which the expression attains all real values, and OP needs to find all such values of $a$...
Answer: Suppose $f(x)=\frac{x^2-x}{1-ax}=k$ for some fixed constants $a,k$. Solving for $x$ we get
$$x^2-x=k(1-ax)=k-kax$$
$$x^2+(ka-1)x-k=0$$
$$x=\frac{1-ka\pm\sqrt{(ka-1)^2+4k}}2$$
For a chosen $a$, $f$ attains all real numbers if and only if the discriminant $(ka-1)^2+4k$ is non-negative for all $k$. Expanding:
$$(ak)^2-2ka+1+4k\ge0$$
$$a^2k^2+(4-2a)k+1\ge0$$
Using the discriminant a second time we find
$$(4-2a)^2-4(a^2)(1)\le0$$
$$16-16a+4a^2-4a^2\le0$$
$$16\le16a$$
$$a\ge1$$
If $a=1$, $f(x)$ behaves like $-x$. However, it has a removable singularity at $x=1$, which means it does not attain a value of $-1$. Therefore $a=1$ is excluded, and $\frac{x^2-x}{1-ax}$ attains all real values when $a>1$.
Comment: f attains real numbers for any real x as long as the denominator is not zero.
Comment: @AmeetSharma No, did you read the question? _All_ real values, not just one. Please retract your downvote.
Comment: oops sorry about that.
Comment: @ParclyTaxel But my textbook also includes $a=1$.
Comment: @J.Deff In an informal setting where you could simplify the expression at $a=1$ to $-x$, $a=1$ would be included, but that relies on the cancellation of an $x-1$ term and as a mathematician you have to pay attention to whether or not you can do that. Perhaps your textbook's inclusion of $a=1$ is a simple oversight.
Comment: How did you get the idea that we have to check the function at a =1?
Comment: @ParclyTaxel Let's say $a$ takes the value $2$, but then the function would be $\mathrm{f(x)=\frac{x^2-x}{1-2x}}$ which wont be defined for $\mathrm{x=1/2}$
Comment: @ParclyTaxel How did you conclude that the discriminant (second) is $\leq 0$ ?...
Comment: Hi, this might be a bit late but I have one doubt. How are we sure that 1 is the only value which we will have to ignore?
Answer: Hint: Calculate the discriminant and see when this stays non-negative for every value of $y$.
Comment: $a^2y^2+2y(2-a)+1 \geq 0$
Comment: Then continue and calculate yet a discriminant to see when this is verified. Note that this time the discriminant should be non-positive! (the case $a=1$ needs special attention).
Comment: Didn't understand


Distribution of the minimum of a pair of random observations

Question: A test results interpretation question, which I think boils down to this: what is the distribution of the minima of pairs of values sampled at random from a known distribution (say, Gaussian) and can the parameters of the latter be estimated knowing or estimating the parameters of the former?
Suppose that one wants to measure the breaking strength of some type of rope, by pulling it to failure, but with a twist: the rope is to be attached to the test rig with a particular knot.  The idea is that the knot weakens the rope and that the rope will break at the knot at some lower range of tensions than without it.
If one keeps testing samples of the rope with the knot on one end, eventually some outline of the distribution of the rope+knot breaking strength will emerge and predictive inferences may be attempted.
But what happens if each test uses a length of rope with two knots, one at each end?  One can only record the breaking strength of the weaker of the two (one knot breaks first which ends the test).
I imagine that the distribution of values in such dual-knot tests will be biased low and be less scattered?  But if this is the only data available, can one try to estimate back from it what the actual distribution of breaking strength of all the knots may have been?
It may not be quite true in practice - as the rope/knots breaking strengths tend to be positively skewed resembling Log-Normal PDF, and sometimes seem to be even multimodal - but maybe assuming that the original distribution was Normal or at least symmetric (which probably happens often enough) could make such transformation back to the underlying distribution easier?
Comment: You may wish to read into [order statistics](https://en.wikipedia.org/wiki/Order_statistic) more if you have not already. See [*Probability of Min of X Greater than Max of Y*](https://galenseilis.github.io/posts/dist-min-greater-than-max/) as a related example.
Answer: If the pairs are sampled from the same distribution, I think this is pretty straightforward, although I don't have time to flesh out the reasoning.
Here's an example for the Gaussian case.
generate_data = function(n=1000, mu, sigma){
  x1 = rnorm(n, mu, sigma)
  x2 = rnorm(n, mu, sigma)
  ifelse(x1 < x2, x1, x2)
}
x = generate_data(10000, mu = 10, sigma = 2)
hist(x)

log_likelihood = function(x, mu, sigma){
  # Likelihood of x1 taking on this value
  log_lik_x1 = dnorm(x, mu, sigma, log = T)
  # Probability that x2 exceeds this value
  log_lik_x2_is_higher = pnorm(x, mu, sigma, log.p = T, lower.tail = F)
  # Using sum here, because these are log values
  log_lik_x1 + log_lik_x2_is_higher
}

f = function(pars){
  -1 * sum(log_likelihood(x, pars[1], pars[2]))
}
initial_guess = c(2, 2)
optim(initial_guess, f)
#> Warning in dnorm(x, mu, sigma, log = T): NaNs produced
#> Warning in pnorm(x, mu, sigma, log.p = T, lower.tail = F): NaNs produced
#> $par
#> [1] 9.988886 2.000579
#>
#> $value
#> [1] 26124.43
#>
#> $counts
#> function gradient
#>       91       NA
#>
#> $convergence
#> [1] 0
#>
#> $message
#> NULL

Comment: Many thanks for this - I think I almost understand it.  Such Monte Carlo solution should be applicable to any distribution, not just Gaussian, I think.  I have added as an answer what seems to be an acceptable analytical solution/estimate which should work for minima of pairs from the same Gaussian distribution.
Comment: This isn't a Monte Carlo simulation, it's maximum-likelihood estimation. The sample is just to generate test data.
Answer: I found this paper.  If equations 11 and 12 are simplified for pairs of values sampled from a single Gaussian distribution with parameters mu1 and sigma1, then the estimated parameters of the resulting distribution of minima of those pairs (mu2 and sigma2, also Gaussian or close to it) can be linked as follows, I believe:
To estimate the parameters of the original distribution:
mu1 = mu2 + 0.683*sigma2
sigma1 = 1.212*sigma2
To estimate the parameters of the distribution of pairs' minima:
mu2 = mu1 - 0.564*sigma1
sigma2 = sqrt(mu1^2 + sigma1^2 - 1.129mu1sigma1 - mu2^2)
While I posted it as an 'answer', it would be great if this could be confirmed by someone else.  I think it's right and it seems to agree with a few Monte Carlo runs I tried.
p.s. I'm sorry for not using MathJax - I'm not sure how yet...


Why not open up the table when it is snooker-friendly?

Question: Below is shown a position from the famous Fu-Day game of snooker in which Day achieved four snookers. This was aided by the snooker-friendly condition of the balls in a cluster at the end of the table, allowing the cue to be hidden.
Why would Fu not clear the cluster by hitting the brown/green to the side of the table? Obviously it will be a foul, but he would only take one foul penalty and it would make it a lot harder for Day to hide the cue after that.
Answer: In most situations, not attempting to hit the ball "on" would be a "Foul and a Miss" and the opponent would have the option of having the balls reset to the position before the shot, rendering this tactic worthless:

The striker shall, to the best of his ability, endeavour to hit the ball on or a
  ball that could be on after a Red has been potted. If the referee considers
  the Rule infringed, he shall call FOUL AND A MISS
[...]
After a FOUL AND A MISS has been called, the next player may request
  the offender to play again from the position left, or at his discretion, from
  the original position, with all balls being replaced

(Official rules, Section 3, Rule 14 Foul and a Miss). However, my reading of Rule 14 is that "Foul and a Miss" cannot be called if snookers are required:

If the referee considers the Rule infringed, he shall call FOUL AND A MISS unless:
(i) any player needed penalty points before, or as a result of, the stroke
  being played;

so Fu could perhaps have done this. On the other hand, there is Section 4, Rule 1:

In the event of:
[...]
any conduct by a Player which in the opinion of the referee is wilfully
  or persistently unfair

the referee has the option of awarding the frame to the opponent. I don't know what counts as "wilfully unfair" for world class players.


How to block the user after a few failed logins

Question: modules like login security deny the user IP after afew failed logins. there are softwares that randomly generate new IP for user so it makes such modules useless. sending cookie to the user browser is also unreliable because the user can disable accepting cookie. What is the most reliable solution to block some users?
Answer: Rules is what comes to mind. You can react to the user logging in I guess.


finding the probability of winning lottery

Question: i saw an question in stackexchange .it attract me because the given answers  are different from  one another.Moreover , i think that the accepted solution is wrong and the second most voted answer is correct.I am putting the question in here.

Blockquote
Lottery: Finding the probability of winning respective prizes.

What do you think about it. Which solution is correct? I think the the second..
Answer: The explanation given in the answer by Satish Thulva (the accepted answer, but strangely now deleted) is correct.

For all $5$ probabilities, the denominator should be ${\large{\binom{45}{6}}}$ since that's the number of possible tickets.

As Satish Thulva explained, there are $3$ groups:

Group $1$: The first $6$ numbers chosen in the draw.$\\[4pt]$
Group $2$: The $1$ additional number chosen in the draw.$\\[4pt]$
Group $3$: The $38$ numbers not chosen in the draw.

hence, of the ${\large{\binom{45}{6}}}$ possible tickets, we get the following counts
$$
\begin{array}
{|c|c|}
\hline
\text{prize #}&\;\;\;\text{number of winning tickets}\;\;\;\\
\hline
1&{\vphantom{\Large{\frac{0}{0^2}}}}{\large{\binom{6}{6}}}\\
\hline
2&{\vphantom{\Large{\frac{0}{0^2}}}}{\large{\binom{6}{5}\binom{1}{1}}}\\
\hline
3&{\vphantom{\Large{\frac{0}{0^2}}}}{\large{\binom{6}{5}\binom{38}{1}}}\\
\hline
4&{\vphantom{\Large{\frac{0}{0^2}}}}{\large{\binom{6}{4}\binom{1}{1}\binom{38}{1}}}\\
\hline
5&{\vphantom{\Large{\frac{0}{0^2}}}}{\large{\binom{6}{4}\binom{38}{2}}}\\
\hline
\end{array}
$$
matching the approach suggested in Satish Thulva's answer.

To explain in a little more detail, consider the count for Prize #$4$ . . .

A winning ticket for Prize #$4$ must have

$4$ numbers from Group $1$:$\;{\large{\binom{6}{4}}}$ choices.$\\[6pt]$
$1$ number from Group $2$:$\;{\large{\binom{1}{1}}}$ choices.$\\[6pt]$
$1$ number from Group $3$:$\;{\large{\binom{38}{1}}}$ choices.

hence by the product rule,$\;\,{\large{\binom{6}{4}\binom{1}{1}\binom{38}{1}}}\;\,$is the number of winning tickets for Prize #$4$.
Comment: @awkward: Strange that it was deleted within the last hour by someone other than Satish Thulva. And it was the accepted answer!
Comment: i guess you missed something, additional number is not chosen in first,third and fifth prizes.then they must have been $C(39,1) or C(39,2)$
Comment: @leonard: If you look at the expressions for those prizes, I didn't choose the additional number. More precisely, I chose $6$ numbers which specifically _avoid_ choosing the additional number. For example, for the third prize, the answer I gave could be rewritten as
$$
\binom{6}{5}\binom{1}{0}\binom{38}{1}
$$
Comment: A moving target is hard to hit.  It looks like Satish Thulva's answer has been deleted (why, I don't know).  You might consider adding your answer to the original question.
Comment: @quasi thanks for your elegant explanation. i misunderstood the question in the beginning. i assumed that the additional number are apart from the six number


bridge in linux

Question: I have an issue with bridge networking in my CentOS 5.5 box:
server has two bridge interfaces : one to public net , second to private net
all works good , but when I'm adding new interface to the bridge
/usr/sbin/brctl addif br1 veth237151.1

(openvz virtual interface for public network)
network hangs for 30 seconds, then works again
in logs I have just this
Jul 28 09:04:08 sea kernel: device veth237151.1 entered promiscuous mode
Jul 28 09:04:08 sea kernel: br1: topology change detected, propagating
Jul 28 09:04:08 sea kernel: br1: port 3(veth237151.1) entering forwarding state
Jul 28 09:04:08 sea kernel: br1: topology change detected, propagating
Jul 28 09:04:08 sea kernel: br1: port 3(veth237151.1) entering forwarding state

some additional info
bridge name     bridge id               STP enabled     interfaces
br0             8000.001851083838       yes             eth0
br1             8000.0018511f824f       yes             veth237151.1
                                                        eth1

Comment: Out of the man page: "brctl setfd   sets the bridge's 'bridge forward delay' to  seconds."  by default it's 30 seconds, so I'm guessing that's what you're experiencing. Set it to 0 right after you bring up the bridge interface.
Answer: Whole network hangs or only the added interface? The latter case is a normal behaviour of an Ethernet switch. A port, when added to the switch, does not send any frames for the time defined by a 'forward delay' parameter. That is needed to properly protect from topology loops, especially when STP is in use.
Please note, that in Linux STP on/off and forward delay settings are controlled separately. The port will still wait in 'listening' state when 'forward delay' is defined, even if STP is off. And you can have STP enabled with no forward delay (I guess it is a bit against the STP specification).
To disable the forwarding delay try:
brctl setfd br1 0

Comment: > Whole network hangs or only the added interface?
just br0 (or br1) interface which has private/public ip which I use for access to server
so when I'm adding new interface to bridge my ssh connection hangs. Other interfaces in bridge works without any problems (for instance interfaces from another virtual machine)
Comment: brctl setfd br1 0

didn't help
Comment: How can this `forward delay` setting be made permanent over reboots?
Answer: Did you try disabling STP ?
Comment: On linux that could not affect the delay – forward-delay is configured separately.
Comment: yes, unfortunately disabling\enabling STP no role...

anyway I don't need STP and disabled it.
Answer: Permanently reducing forward delay
Here is how to permanently reduce forward delay, regardless of any reboots.
Edit /etc/network/interfaces:
$ sudo vim `/etc/network/interfaces`

Add a bridge_fd line:
auto br0
iface br0 inet dhcp
    bridge_ports all
    bridge_fd 2.5

bridge in linux


Advice on optimal random-effects structure for not fully crossed repeated-measures design?

Question: I have a study that is designed such that it seems to straddle a within- and between-subject design. I posted about this previously here, but at that stage I was hoping for a simple ANOVA-like solution. I am beginning to think one does not exist and have turned to the multilevel modelling literature instead. If I find a solution here, I will post an answer to the original question as well.
To recap, my study is interested in attitudes toward the homeless and in particular whether ethnicity interacts with homelessness to increase stigma. To study this, participants read vignettes about someone and make ratings related to stigma. My independent variables are whether the character in the vignette has a home or not (homed, homeless) and ethnicity (white, black). In a perfect world, everyone would receive all four resulting conditions (homed-white, homed-black, homeless-white, homeless-black). However, due to time, each participant can receive only two. As such, each participant receives one of the following:
homeless-black / homed-white
homeless-white / homed-black
(the order of the two vignettes counterbalanced for each but that isn't important here – likewise, due to design constraints, we could use only a single name for each black / white character and wanted to use only 1 vignette for each homed and homeless condition)
This looks like a 2 x 2 repeated measures design in that each participant receives both levels of homelessness and both levels of ethnicity, but it isn't quite because they don't receive all four conditions, only two.
My question is, were we to fit this as a multilevel model, would it be appropriate to use the following random-effects structure (for convenience I use lme4 like notation):

stigma ~ home + ethnicity + home:ethnicity + (home + ethnicity |
subject)

This would include a random intercept for each participant, as well as random slopes for the main effects, but exclude the random slope for the interaction as we lack sufficient information to explore within-subject variation in that. Am I correct that this the maximal structure permitted by the data?
Open to any other advice, also, or alternate proposals for analytic approaches!
Comment: This was asked in the previous thread by @Sointu, and is worth asking again. Have you already collected this data or do you still have time to alter the design? The comments and answers in the other thread all seem to converge on the idea that this design is not particularly amenable to your stated research questions. You made it very difficult to de-confound race and homed/homeless in this design and it's not clear that they can be disentangled.
Comment: @ErikRuzek, unfortunately the design is locked in at this time and not something I have the power to change due to a few constraints. But this is also only a pilot for now and we'll use a different design. Still, we'll have data and need to do something with it. Given these constraints, and accepting that within-participant variability cannot be modelled for the interaction, does the above model sound okay (at this stage, I should ask... the best we can do)? Or is there another way?
Answer: The question of how to model this data is an important one, but before doing so, I want to show how the structure of the data can provide clues about the true design your study implies. Note that I assume you have only two ethnicities (black/non-black). To start, I will reiterate that the two conditions you showed are indeed between-subjects factors. I will encode these as follows:
Cond == 0 -- homeless-black / homed-white
Cond == 1 -- homeless-white / homed-black
You then have indicators for whether the target is homeless (is_homeless), whether the target is black (is_black), an interaction of these two (homeless_by_black), the subject identifier (subject), and the outcome (stigma). This is how I would set up your data:

subject
is_homeless
is_black
homeless_by_black
condition
stigma

1
1
1
1
0
4.3

1
0
0
0
0
4.8

2
1
0
0
1
3.5

2
1
0
0
1
3.2

Some things that stick out:

As you said, each participant only sees targets that correspond to the condition they were assigned to, which means that no subject sees all conditions.

The interaction term only "turns on" for those in condition==0.

Accordingly, the interaction is confounded with condition. You could include the interaction term in the model, but it is only giving you the contrast of interest for those in condition==0. It will use information from those in condition==1 but they all have a value of 0 and they never saw a homeless-black target. Not very useful, unfortunately.

Each subject receives both a black and a non-black target and a homed and homeless target for rating.

These can be considered within-subjects (sometimes called "main effects") factors.

To model this, I would lean toward a minimal model. Depending on a lot of factors (sample size, variability of the outcome, true between subjects variation in the association of interest, etc.), a maximal model is often overkill and doesn't necessarily do what its proponents claim. You can explore it, but know that you are likely run into estimation problems due to overfitting and you will have to pare down the random effect structure. I would run the following model:
<code>m1 <- lmer(stigma ~ is_homeless + is_black + condition + (1 | subject), d=data))
</code>
This gives you mean differences in the within-subjects factors of homed/homeless, black/non-black, and the between-subjects factor of condition. The latter, as shown above, is giving you some (minimal) information about the interaction but you cannot conclude that any mean differences are solely due to this. You and others may choose to model the interaction, but I personally think it is not meaningful because it isn't a test of what you really want. Specifically, in the current design, it is not a true within-person comparison of whether viewing a homeless black target is associated with more or less stigma compared to other groups.