Conjugate prior distribution for a specific (normal) curved exponential family

Question: Is there a conjugate prior distribution in the model $\text{N}(\theta, \sigma^2=\theta^2)$, that is a normal distribution where the mean and standard deviation are equal ($\theta>0$)? (This question is related to Conjugate for a special normal distribution)
Answer: There is a conjugate distribution for $\theta$ in the model $X_1, X_2, \dotsc, X_n$ iid $\text{N}(\theta, \theta^2)$ with $\theta>0$, but it is not a commonly named distribution. First find the likelihood of this "normal parabola" model, as it is called:
$$
L(\theta) = \prod_i^n \frac1{\sqrt{2\pi}\theta}e^{-\frac12\sum_i^n \left(\frac{x_i-\theta}{\theta} \right)^2}
$$
and (leaving out constants) this is proportional to
$$
L(\theta) \propto \theta^{-n} e^{-\theta^{-2}\sum_i x_i^2/2 + \theta^{-1}\sum_i x_i}
$$
Then we need a prior distribution on $\theta$ that can "absorb" these three factors. Using a form of bayes' theorem,
$$
\pi(\theta | x) \propto f(x | \theta) \pi(\theta) \\
= \theta^{-n} e^{-\theta^{-2}\sum_i x_i^2/2} e^{\theta^{-1}\sum_i x_i}\pi(\theta)
$$
So we need a prior density having some corresponding factors. We can try with a form which is a particular generalization of a generalized inverse gamma density
$$
   \pi(\theta) = K^{-1} \cdot \theta^{-\alpha-1}e^{-\frac{\beta}{\theta}-\frac{\gamma}{\theta^2}},\qquad \theta>0
$$
which is convergent for $\alpha>0,\beta\in\mathbb{R}, \gamma>0$. The proportionality factor $K$ has a very complicated form which will be given at the end.  This distribution will have a finite expectation for $a>1$ and a finite variance for $a>2$.
Using this we find that
$$
\pi(\theta | x) \propto \theta^{-(n+\alpha)-1} e^{-(\beta-\sum_i x_i)/\theta } e^{-(\gamma+\sum_i x_i^2/2)/\theta^2}
$$
that is, the posterior has the same form as the prior.
I calculated the  constant $K$ with maple:
<code>int( (theta^(-a-1))*exp(-b/theta - c/theta^2), theta=0..infinity ) assuming a>0,c>0,b,real;
</code>
which gives the following result:
$$
   1/2\,{\frac {{c}^{-a/2}}{\sqrt {\pi}} \cdot \\ \left( 1/4\,{\frac {{\pi}^{2}b}{
\sqrt {c}\cos \left( 1/2\,\pi\,a \right) \Gamma \left( 2-a/2 \right) }
 \left( 1/2\,{\frac {{b}^{2}}{c}}-1+a \right) {\it LaguerreL} \left( 1
/2-a/2,1/2, \\ 1/4\,{\frac {{b}^{2}}{c}} \right) }-1/8\,{\frac {{\pi}^{2}{
b}^{3}}{{c}^{3/2}\cos \left( 1/2\,\pi\,a \right) \Gamma \left( 2-a/2
 \right) }{\it LaguerreL} \left( 1/2-a/2,3/2,1/4\,{\frac {{b}^{2}}{c}}
 \right) }+ \\ 1/2\,{\frac {{\pi}^{2}}{\sin \left( 1/2\,\pi\,a \right)
\Gamma \left( 3/2-a/2 \right) } \left( 1/2\,{\frac {{b}^{2}}{c}}+1
 \right) {\it LaguerreL} \left( -a/2,1/2,1/4\,{\frac {{b}^{2}}{c}}
 \right) }- \\ 1/4\,{\frac {{\pi}^{2}{b}^{2}}{c\sin \left( 1/2\,\pi\,a
 \right) \Gamma \left( 3/2-a/2 \right) }{\it LaguerreL} \left( -a/2,3/
2,1/4\,{\frac {{b}^{2}}{c}} \right) } \right) }
$$
For the ${\it LaguerreL}$ function see https://en.wikipedia.org/wiki/Laguerre_polynomials.
Answer: I wrote a paper in 1991 (!) about this problem, which got published in Statistics and Probability Letters. And which recoups Kjetil's solution as the generalised inverse Normal distribution, which generalises the distribution of the inverse of a Normal random variable (not to be confused with the inverse Gaussian distribution). The density is expressed as
$$K(\alpha,\mu,\tau)\,|z|^{-\alpha}\exp\{-(z^{-1}-\mu)^2/2\tau^2\}\qquad\alpha>1,\ \tau>0$$
The paper also contains a representation of the normalising constant using confluent hypergeometric functions
$$K(\alpha,\mu,\tau)=\tau^{\alpha-1}e^{-\mu^2/2\tau^2} 2^{(\alpha-1)/2}
\Gamma((\alpha-1)/2){}_1F_1((\alpha-1)/2,1/2,\mu^2/2\tau^2)$$


fast and memory efficient way to deserialize a GUID from a byte array to a string in JavaScript

Question: At the moment I've used this code:
getGuid(): string {
    const guid = this.array[this.offset + 3].toString(16).padStart(2, '0') + this.array[this.offset + 2].toString(16).padStart(2, '0') + this.array[this.offset + 1].toString(16).padStart(2, '0') + this.array[this.offset + 0].toString(16).padStart(2, '0') + "-" +
        this.array[this.offset + 5].toString(16).padStart(2, '0') + this.array[this.offset + 4].toString(16).padStart(2, '0') + "-" +
        this.array[this.offset + 7].toString(16).padStart(2, '0') + this.array[this.offset + 6].toString(16).padStart(2, '0') + "-" +
        this.array[this.offset + 8].toString(16).padStart(2, '0') + this.array[this.offset + 9].toString(16).padStart(2, '0') + "-" +
        this.array[this.offset + 10].toString(16).padStart(2, '0') + this.array[this.offset + 11].toString(16).padStart(2, '0') + this.array[this.offset + 12].toString(16).padStart(2, '0') + this.array[this.offset + 13].toString(16).padStart(2, '0') + this.array[this.offset + 14].toString(16).padStart(2, '0') + this.array[this.offset + 15].toString(16).padStart(2, '0');
    this.offset += 16;
    return guid;
}

but I think it is highly inefficient, and has many gc overhead because of all the strings created. Problem is, I get thousand messages guids per second which I need to convert to strings. (it's in browser not in a node application)
this.array is a Uint8Array
Comment: Do you have any direct evidence that these temporary strings are actually a problem?
Comment: They are not directly a problem, but I'm working on a generic deserialization lib, wich should be as fast and memory efficient as possible
Answer: In general, without a specific measurable problem, it's hard to suggest solutions that could solve that problem. Without measurements (ideally real-world measurements rather than synthetic benchmarks), you don't know whether what you're doing improves things or makes them worse.
That said, one thing that jumps out in this use case is that you're recreating padded hex strings for the same 256 input values repeatedly. Given the volumes you're seeing, you might do better to build those strings once and reuse them. That consumes a small bit of static memory to store the 256 strings, but avoids the repeated toString and padStart operations on every input GUID.
A second thing you can do is cache the repeated property accesses to a local const.
Example:
// Build the strings once
const byteStrings = Array.from({ length: 256 }, (_, value) =>
    value.toString(16).padStart(2, "0")
);

// Reuse them
class Something {
    // ...
    getGuid(): string {
        const { array, offset } = this;
        const guid =
            byteStrings[array[offset + 3]] +
            byteStrings[array[offset + 2]] +
            byteStrings[array[offset + 1]] +
            byteStrings[array[offset + 0]] +
            "-" +
            byteStrings[array[offset + 5]] +
            byteStrings[array[offset + 4]] +
            "-" +
            byteStrings[array[offset + 7]] +
            byteStrings[array[offset + 6]] +
            "-" +
            byteStrings[array[offset + 8]] +
            byteStrings[array[offset + 9]] +
            "-" +
            byteStrings[array[offset + 10]] +
            byteStrings[array[offset + 11]] +
            byteStrings[array[offset + 12]] +
            byteStrings[array[offset + 13]] +
            byteStrings[array[offset + 14]] +
            byteStrings[array[offset + 15]];
        this.offset += 16;
        return guid;
    }
}

byteStrings could even just be a simple array literal, though the one-time creation loop shouldn't be an issue:
const byteStrings = [ "00", "01", "02", "03", "04", "05", "06", /*...*/, "ff"];

But again, take both of these with a grain of salt, and profile/benchmark to see whether either helps.
Comment: Love this ideas! I'll create a benchmark and test
Comment: Looks like it's nearly 5 times faster.
https://jsbench.me/c6loosw7fx/1
Comment: Excellent, glad that helped! I figured the lookup in particular was likely to be helpful. :-) (And indeed, [it seems to be the big one](http://jsben.ch/yrNAx) though the `const` thing helps too. [jsbench.me wouldn't let me save a setup block > 2048 chars. ♂] jsben.ch isn't as rigorous, but is showing similar results to the jsbench.me test I couldn't save.) Hopefully you see a similar improvement in real-world use.


$X_k$ are $\mathcal U(0,2\theta)$ distributed, and $Y_n=\max_{1\leq k < n}X_k$, how is $F_{Y_n}(t)=(\frac{t-\theta}{\theta})?$

Question: $X_k$ are $\mathcal U(0,2\theta)$ distributed, and $Y_n=\max_{1\leq k < n}X_k$, how is $F_{Y_n}(t)=(\frac{t-\theta}{\theta}),\theta<t<2\theta\ \ ?$
$F_{Y_n}(t) \text{ aka }(CDF)$;
This does not seem intuitively correct and why is $t$ restricted to this interval?
Answer: It is indeed incorrect.
$F_{Y_n}(t) = P( \max_{i} X_i \leq t) = P(X_1,X_2, \dots X_n \leq t) $
Assuming $X_i$ are independent and not simply identically distributed:
$P(X_1,X_2, \dots X_n \leq t)  = \prod_i P(X_i \leq t) = (\frac{t}{2\theta})^n$ where $ 0 \leq t \leq 2\theta$
Thus,
$$
F_{Y_n}(t) = \begin{cases}
(\frac{t}{2\theta})^n & 0 \leq t \leq 2\theta\\
0 & t<0\\
1 & \text{otherwise}
\end{cases}
$$


UWP create new window for each file opened

Question: I'm trying to make an app open a window for each file.
-- Code ---
App.cs:
    protected async override void OnFileActivated(FileActivatedEventArgs Args)
    {
        //Opens Main Page
        base.OnFileActivated(Args);
        var RF = new Frame();
        var MW = new MainPage();
        AppWindow appWindow = await AppWindow.TryCreateAsync();
        var TB = appWindow.TitleBar;
        RF.Navigate(typeof(MainPage), Args);
        ElementCompositionPreview.SetAppWindowContent(appWindow, RF);
        appWindow.Equals(MW);
        Window.Current.Equals(MW);
        await appWindow.TryShowAsync();
        TB.ButtonHoverBackgroundColor = Colors.White;
        TB.ButtonHoverForegroundColor = Colors.Black;
        TB.ButtonBackgroundColor = Colors.Transparent;
        TB.ButtonPressedBackgroundColor = Colors.WhiteSmoke;
        TB.ButtonPressedForegroundColor = Colors.Black;
        TB.ButtonInactiveBackgroundColor = Colors.Transparent;
        TB.ButtonInactiveForegroundColor = Color.FromArgb(1, 3, 165, 252);
        TB.ExtendsContentIntoTitleBar = true;
        Window.Current.Activate();
    }

MainPage.cs:
    protected override async void OnNavigatedTo(NavigationEventArgs EvArgs)
    {
        //File opened arguments
        base.OnNavigatedTo(EvArgs);
        var Args = EvArgs.Parameter as IActivatedEventArgs;
        var FArgs = Args as FileActivatedEventArgs;
        string Value = GetText(REB);
        string SecValue = GetText(RTB);
        if (Args != null)
        {
            //Check if the app is opened by file
            if (Args.Kind == ActivationKind.File)
            {
                //Set file content
                TXTFile = FArgs.Files[0] as StorageFile;
                if (Value == "")
                {
                    var Str = await TXTFile.OpenReadAsync();
                    ContentDialog ED2 = FileSaveDialog;
                    ED2.PrimaryButtonClick += ED2_PrimaryButtonClick;
                    void ED2_PrimaryButtonClick(ContentDialog Sender, ContentDialogButtonClickEventArgs DialogEvArgs)
                    {
                        //Save the file if it isn't saved
                        Save();
                    }
                    ED2.SecondaryButtonClick += ED2_SecondaryButtonClick;
                    void ED2_SecondaryButtonClick(ContentDialog Sender, ContentDialogButtonClickEventArgs DialogEvArgs)
                    {
                        //Don't save the file
                        //Set document content
                        REB.Document.LoadFromStream(TextSetOptions.FormatRtf, Str);
                        RTB.Document.LoadFromStream(TextSetOptions.FormatRtf, Str);
                        Str.Dispose();
                    }
                    ED2.CloseButtonClick += ED2_CloseButtonClick;
                    void ED2_CloseButtonClick(ContentDialog Sender, ContentDialogButtonClickEventArgs DialogEvArgs)
                    {
                        //Cancel the action
                    }
                    await ED2.ShowAsync();
                    Str.Dispose();
                }
                else
                {
                    //Set document content
                    var Str = await TXTFile.OpenReadAsync();
                    REB.Document.LoadFromStream(TextSetOptions.FormatRtf, Str);
                    RTB.Document.LoadFromStream(TextSetOptions.FormatRtf, Str);
                    Str.Dispose();
                }
            }
        }
        else
        {
            //If there are no arguments, the file, and the RichEditBox should both remain empty
        }
    }

    public string GetText(RichEditBox RichEditor)
    {
        RichEditor.Document.GetText(TextGetOptions.FormatRtf, out string Text);
        var Range = RichEditor.Document.GetRange(0, Text.Length);
        Range.GetText(TextGetOptions.FormatRtf, out string Value);
        return Value;
    }

Note:

the GetText method used is equivalent to RichEditBox.Document.GetText(TextGetOptions.FormatRtf, out string Value);
REB is the main workspace for the user to type in
RTB is the box that is compared with REB to see if the contents are saved or not (if the contents are saved, the GetText method should return their values equal)

Expected behavior:
If the app has a window active with text, the app should open a file on double click in a secondary window. Else, if the text is equal to "", the app should replace it with whatever is in the file.
Actual behavior:
The app overrides the text, crashes, makes windows randomly, or creates black windows that can only be killed with Task Manager or Visual Studio
Answer: I'm not sure what is the file type that you are using so I didn't check the text part. But I have to say that the way you are creating a new window is not correct. If you want to open a new window every time when you open a new file, you don't have to call Window.Current.Activate(); every time.  I've made a simple demo that you could check.
In App.xaml.cs:
   protected async override void OnFileActivated(FileActivatedEventArgs args)
    {
        Frame rootFrame = Window.Current.Content as Frame;

        // Do not repeat app initialization when the Window already has content,
        // just ensure that the window is active
        if (rootFrame == null)
        {
            // Create a Frame to act as the navigation context and navigate to the first page
            rootFrame = new Frame();
            // Place the frame in the current Window
            Window.Current.Content = rootFrame;

            rootFrame.Navigate(typeof(MainPage), args.Files);

            Window.Current.Activate();
        }
        else
        {
            AppWindow appWindow = await AppWindow.TryCreateAsync();

            Frame appWindowContentFrame = new Frame();
            appWindowContentFrame.Navigate(typeof(MainPage),args.Files);

            ElementCompositionPreview.SetAppWindowContent(appWindow, appWindowContentFrame);

            await appWindow.TryShowAsync();
        }
    }

When you launch the app for the first time, you should go through the normal launch process. When the app is launched more than onetime, then you could create a new window with AppWindow.
In MainPage.cs
  protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        // this is the file you need
        var d = e.Parameter;
    }

You could try this code first to make sure that your window is created and shown correctly.
Comment: The file type I am using is a rich text file. I had to edit the MainPage.cs code a little, but it worked. Thank you!


Matrix notation

Question: I have the following equation:
$\Delta \dot{\boldsymbol{x}}_2 = D_2(\boldsymbol{x}_0)\begin{bmatrix}
\Phi^T_{G_{21}}(\boldsymbol{x}_0)\Delta \delta_e & \Phi^T_{G_{22}}(\boldsymbol{x}_0) \Delta \delta_a & \Phi^T_{G_{23}}(\boldsymbol{x}_0) \Delta \delta_r
\end{bmatrix}\begin{bmatrix}
\Theta_{G_{21}} \\
\Theta_{G_{22}}\\
\Theta_{G_{23}}
\end{bmatrix}$
where $\Delta \dot{\boldsymbol{x}}_2$ is size $3\times 1$, where $D_2$ is $3\times 3$, where $\Phi^T_{G_{2\star}}$ is $3\times 6$, where $\Delta \delta_\star$ are scalars and where $\Theta_{G_{2\star}}$ is $6\times 1$.
This equation is valid at every time instance, so I want to write the following set of equations:
$\begin{bmatrix}
\Delta \dot{\boldsymbol{x}}_{2,1}\\
\Delta \dot{\boldsymbol{x}}_{2,2}\\
\vdots\\
\Delta \dot{\boldsymbol{x}}_{2,N}
\end{bmatrix} = \begin{bmatrix}
D_2(\boldsymbol{x}_0)\\
D_2(\boldsymbol{x}_1)\\
\vdots\\
D_2(\boldsymbol{x}_N)
\end{bmatrix}\begin{bmatrix}
\Phi^T_{G_{21}}(\boldsymbol{x}_0)\Delta \delta_{e,1} & \Phi^T_{G_{22}}(\boldsymbol{x}_0) \Delta \delta_{a,1} & \Phi^T_{G_{23}}(\boldsymbol{x}_0) \Delta \delta_{r,1} \\
\Phi^T_{G_{21}}(\boldsymbol{x}_1)\Delta \delta_{e,2} & \Phi^T_{G_{22}}(\boldsymbol{x}_1) \Delta \delta_{a,2} & \Phi^T_{G_{23}}(\boldsymbol{x}_1) \Delta \delta_{r,2} \\
\vdots & \vdots & \vdots
\\
\Phi^T_{G_{21}}(\boldsymbol{x}_{N-1})\Delta \delta_{e,N} & \Phi^T_{G_{22}}(\boldsymbol{x}_{N-1}) \Delta \delta_{a,N} & \Phi^T_{G_{23}}(\boldsymbol{x}_{N-1}) \Delta \delta_{r,N}
\end{bmatrix}\begin{bmatrix}
\Theta_{G_{21}} \\
\Theta_{G_{22}}\\
\Theta_{G_{23}}
\end{bmatrix} \,.$
However, I doubt whether this notation is correct (especially the matrix containing $D_2$).
Answer: The size of the left side of your equation is $3N \times 1$, so we need the right hand side to be the same.
Right hand side: The first term is $3N\times 3$, the second term is $3N \times 18$ and the third term is $18 \times 1$, which isn't correct.
First guess would be to make the first matrix a diagonal matrix with $D_2(x_i)$ on the diagonal and the rest of the entries $3\times 3$ zero matrices. Haven't worked this out, but seems correct. That would at least give you the correct dimensions: diagonal matrix is $3N\times 3N$.

Matrix notation


whats wrong with the following code for thread in java?

Question: class threaddemo extends Thread

{
    Thread t ;
    t=Thread.currentThread();//error(incompatible type. thread cant,t be converted to t)
    String s=t.getName();

    @Override
    public void run()
    {
        for(int i=0;i<5;i++)
        {
            System.out.println(i+" "+t.getName());
            try
            {
                Thread.sleep(1000);
            } catch (InterruptedException ex)
            {
                Logger.getLogger(threaddemo.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

Comment: Rephrasiing the question might help (and by the way it seems that you gave the answer yourself `thread cant,t be converted to t`. So the real question might be "Why does assigning Thread.currentThread() to Thread variable raise a compilation error?" Besides the rest of the code seems more to distract from the original problem (i.e. the `for` loop, which could have left out by replacing with `...`.
Answer: You can't do initialisation like:
Thread t ;
t=Thread.currentThread(); //error(incompatible type. thread cant,t be converted to t)

if you are outside of a method.
If the variable is a field of a class, you basically* have to do declaration and instantiation on one line:
Thread t = Thread.currentThread();

*I say basically because this is not strictly true. You can also use constructors, for example:
class MyClass
{
    String str; //declaration

    MyClass()
    {
        str = "hello"; //instantiation
    }
}

There is at least one other method which is less common and I wouldn't worry about for now. This page of Oracle's site describes it.


How to register a renderer for a class in JSP/JSTL?

Question: I was wondering if there is a way to register default renderer for a particular class in JSP/JSTL.
I am on my page displaying a tabular report where each table row arrives as generic List<Object>. Since I don't know the type of particular item in advance I am outputting the value with <c:out ...>. This does toString() as far as I know.
Now I want to change the format based on the class of the item e.g. change the format of decimal numbers. Of course I can't use <fmt:formatXXX ...> because I don't know the type in advance.
I believe this is possible in JSF. But is there a way how to achieve this in JSP?
My best shot sofar would be to convert the List<Object> to List<String> and applying the formatting  in my controller class but this is slightly less elegant than register a renederer IMHO.
Answer: JSP has no notion of "renderers", it's not a component based MVC framework. But you could create a custom tag for this.
Alternatively, you can do something like this with plain JSTL, it's possible to figure the class of an EL object by just checking Object#getClass():
<c:choose>
    <c:when test="${item['class'].name == 'java.lang.Integer'}">
        <fmt:formatNumber value="${item}" type="number" />
    </c:when>
    <c:when test="${item['class'].name == 'java.math.BigDecimal'}">
        <fmt:formatNumber value="${item}" type="currency" />
    </c:when>
    <c:when test="${item['class'].name == 'java.util.Date'}">
        <fmt:formatDate value="${item}" type="date" />
    </c:when>
    <c:otherwise>
        <c:out value="${item}" />
    </c:otherwise>
</c:choose>


How to detect collision between a graphic and a Sprite in phaser 3?

Question: In my game I want to implement a range sort of feature that would restrict players area. I tried to draw a graphic circle and assign it physics properties. Then I setup collision detection between sprite and graphic. The code shows no errors but the collision is not detected.
I followed the following tutorial.
Graphic and Sprite
Answer:

var config = {
    type: Phaser.AUTO,
    parent: 'phaser-example',
    loader: {
      baseURL: 'https://firstname.lastname@example.com/assets/',
      crossOrigin: 'anonymous'
    },
    width: 800,
    height: 600,
    physics: {
      default: 'arcade'
  },
  scene: {
    preload: preload,
    create: create,
    update:update
  }
};

var game = new Phaser.Game(config);
var player;

function preload()
{
  this.load.image('dude', 'sprites/phaser-dude.png')
}

function create ()
{
  player = this.physics.add.sprite(100, 100, 'dude');
  player.setCollideWorldBounds(true);

  var graphics = this.add.graphics({ fillStyle: { color: 0xff0000 } });
  var circle = new Phaser.Geom.Circle(50, 50, 25);
  graphics.fillCircleShape(circle);
  this.physics.add.existing(graphics);

  cursors = this.input.keyboard.createCursorKeys();

  this.physics.add.collider(player, graphics);

}

function update()
{
  if (cursors.left.isDown)
  {
      player.setVelocityX(-160);
  }
  else if (cursors.right.isDown)
  {
      player.setVelocityX(160);
  }
  else if (cursors.down.isDown)
  {
      player.setVelocityY(160);

  }
  else if (cursors.up.isDown)
  {
      player.setVelocityY(-160);
  }
}


Running a single test with invoker plugin

Question: Following is the directory structure for my integration tests
 /src/it/first-test
           -->my-test
               -->build.log
               -->inoker.properties
               -->pom.xml
               -->verify.groovy

When I try to run a single integration tests as described https://maven.apache.org/plugins/maven-invoker-plugin/usage.html. It gives a message that ' No projects were selected for execution' Here is the command I used to invoke the project
/src/main> mvn invoker:run -Dinvoker.test=first-test/my-test*

How should I make sure the test is run?
Comment: It looks like you misunderstood the docs how to structure your integration tests. The first integration test should be located `/src/it/first-test` the second integration test should be located `/src/it/second-test` which means your folder `my-test` should be removed...Furthermore you should start the integration test from your project root and not by `mvn invoker:run ` you should use `mvn verify -Dinvoker.test=first-test` instead...
Comment: Thank you, this worked. Do you want to answer it so I can accept it?
Answer: It looks like you misunderstood the docs how to structure your integration tests. The first integration test should be located /src/it/first-test the second integration test should be located /src/it/second-test which means your folder my-test should be removed...Furthermore you should start the integration test from your project root and not by mvn invoker:run you should use mvn verify -Dinvoker.test=first-test instead...
Answer: It looks like you are executing it from src/main. Try it again from the root of the project (where the pom.xml is located).


Change background and item color of a spinner

Question:
Does anyone know how I can change the background color and the item color on the spinner?
    <Spinner
        android:id="@+id/spinner_categoryselect"
        android:background="@drawable/side_nav_bar"
        android:background="#CCC"
        android:layout_weight="4"
        android:layout_width="0dp"
        android:layout_height="wrap_content"></Spinner>

Thanks in advance.
Answer: Try this my friend
android:popupBackground="#000000"

Answer: <Spinner android:id="@+id/spinner"
     ...
     android:background="#YOUR_COLOR"/>

Answer: You can simply use the following attribute in your <spinner> tag
android:background="#000000"

If you want to change the background color for drop-down menu then
android:popupBackground="#000000"

Answer: You can simply change popup background color:

Use android:popupBackground on the Spinner in your XML or setPopupBackgroundResource(int) in code.
Check here Dupllicate question


Total differential -- which point do I use?

Question: I'm working through Mary L. Boas's Mathematical Methods in the Physical Sciences and have come across either a confusion or an error in the text. (p. 197, 3rd edition.)
I am asked to show that when n is very large $\frac{1}{n^2} - \frac{1}{(n+1)^2} = \frac{2}{n^3}$.  (This equality should be approximate; I just don't know how to write that.)  The author takes $df = d \frac{1}{n^2} = \frac{-2dn}{n^3}$.  But then she takes $dn = -1$.
It seems to me that, in order for us to use $dn = -1$, we must use $d \frac{1}{(n+1)^2}$.  (Of course, using this does not result in the required result.)  In fact, the author does this very thing in the previous exercise.
Where am I going wrong here?  Or am I right, and this is a mistake in the text?
Comment: `\approx` produces $\approx$.
Comment: Actually, $f(n)=1/n^2$ so $\Delta f = f(n+1)-f(n) = 1/(n+1)^2-n^2 \approx f'(n) (n+1-n) = f'(n) < 0$. What you have up there is not $f(n+1)-f(n)$ but the opposite.
Comment: In terms of approximations, $\frac{2}{(n+1)^3} = \frac{2}{n^3}$. Might have been better to say $dn = 1$ and then multiply with $-1$, since the expression is $f(n) - f(n+1)$ and not $f(n+1)-f(n)$.
Comment: That's just what I was saying.  The author, apparently, disagrees.
Answer: Let $f(x)=x^{-2}$. By the mean value theorem, we can write $$f(x+1)-f(x)=f'(\xi)$$ for some $x<\xi<x+1$. As $x\to\infty$, $\xi\to\infty$. What is $f'(\xi)$? Does it go to zero as $\xi\to\infty$? It seems the author is writing $$x^{-2}-(1+x)^{-2}=f(x)-f(x+1)=-f'(\xi)={2}\xi^{-3}$$ since $x-(x+1)=-1$. That is the "$dn=-1$" she is suggesting. Morover, since $x<\xi<x+1$ we have $\dfrac{\xi}x\to 1$ as $x\to\infty$, so $2\xi^{-3}\sim 2x^{-3}$ as $x\to\infty$; as claimed.
Comment: Yes, but that doesn't explain why the derivative of f(x) was taken, rather than that of f(x+1).  Also, I don't understand the first half of your comment.  That isn't what the mean value theorem says... aren't you off by a factor?  I didn't downvote you, by the way.
Comment: @JamesDolinger I had a typo. Now fixed.
Comment: Maybe I didn't state my question well enough: I agree with all of this and understand it.  But that doesn't change that what the author did is wrong, as written.  In order to do this problem correctly, it seems you must multiply by -1 at the start and finish of it.  This was not stated, and the differential of the wrong function was taken.  Do you agree that, as written, the author made a mistake?
Comment: If we just multiply at the beginning and end, we can take dn = 1, using the differential of 1/n^2; this, I think, is the correct way.
Comment: @JamesDolinger No, the author is not wrong. As I explain, since you're looking at $f(x)-f(x+1)$ what you have is a decrease, not in increment, for $x-(x+1)=-1$. Thus, the author is correct that "$dn=-1$".
Comment: But the differential should be taken of f(x+1), in that case, should it not?  If we're decrementing from f(x+1), we must take the derivative of 1/(n+1)^2.  This is clearly not the same as the derivative of 1/n^2, and we don't reach the required answer.
Comment: @JamesDolinger No. The mean value theorem writes $$\frac{f(x)-f(y)}{x-y}=f'(\xi)$$

In this case we're simply taking $y=x+1$. There is no problem with that.
Comment: I see that you are right, though I maintain that the way the author has written it in the book (maybe you would agree if you saw it) is confusing at best.  Thank you very much.


Reliability of a fitted curve?

Question: I would like to estimate the uncertainty or the reliability of a fitted curve. I intentionally don't name a precise mathematical quantity that I am looking for, since I don't know what it is.
Here $E$ (energy) is the dependent variable (response) and $V$ (volume) is the independent variable. I would like to find the Energy-Volume curve, $E(V)$, of some material. So I made some calculations with a quantum chemistry computer program to get the energy for some sample volumes (green circles in the plot).
Then I fitted these data samples with the Birch–Murnaghan function:
$$
\mathbb{E}(E|V) = E_0 + \frac{9V_0B_0}{16}
\left\{
\left[\left(\frac{V_0}{V}\right)^\frac{2}{3}-1\right]^3B_0^\prime +
\left[\left(\frac{V_0}{V}\right)^\frac{2}{3}-1\right]^2
\left[6-4\left(\frac{V_0}{V}\right)^\frac{2}{3}\right]\right\}\;,
$$
which depends on four parameters: $E_0, V_0, B_0, B_0'$. I also assume that this is the correct fitting function, so all errors just come from the noise of the samples. In what follows, the fitted function $(\hat{E})$ will be written as a function of $V$.
Here you can see the result (fitting with a least squares algorithm). The y-axis variable is $E$ and the x-axis variable is $V$. The blue line is the fit and the green circles are the sample points.

I now need some measure of the reliability (at best in dependence of the volume) of this fitted curve, $\hat{E}(V)$, because I need it to calculate further quantities like transition pressures or enthalpies.
My intutition tells me that the fitted curve is most reliable in the middle, so I guess that the uncertainty (say uncertainty range) should increase near the end of the sample data, like in this sketch:

However, what it this kind of measure that I am looking for and how can I calculate it?
To be precise, there is actually only one error source here: The calculated samples are noisy due to computational limits. So if I would calculate a dense set of data samples they would form a bumpy curve.
My idea to find the desired uncertainty estimate is to calculate the following ''error'' based on the parameters as you learn it in school (propagation of uncertainty):
$$
\Delta E(V) = \sqrt{ \left(\frac{\partial E(V)}{\partial E_0} \Delta E_0\right)^2 + \left(\frac{\partial E(V)}{\partial V_0} \Delta V_0\right)^2 + \left(\frac{\partial E(V)}{\partial B_0} \Delta B_0\right)^2 + \left(\frac{\partial E(V)}{\partial B_0'} \Delta B_0'\right)^2}
$$
The $\Delta E_0, \Delta V_0, \Delta B_0$ and $\Delta B_0'$, are given by the fitting software.
Is that an acceptable approach or am I doing it wrong?
PS: I know that I could also just sum up the squares of the residuals between my data samples and the curve to get some kind of ''standard error'' but this is not volume dependent.
Comment: I think the V is A^3. that's what I used and my plot looked identical to his.
Comment: none of your parameters is an exponent, which is good. Which NLS software did you use? Most will return an estimate for the parametric uncertainty (which can be completely unrealistic if your parameters are exponents, but this is not your case).
Comment: There's no A on the right hand side of your equation but it appears in your plot. When you say "four parameters" do you mean parameters in the statistical sense (in which case, where are your IVs) or do you mean variables (in which case where are your parameters)? Please clarify the roles of the symbols -- what is measured and what are unknowns?
Comment: @Glen_b  I just assumed the Y axis is E in the  Birch–Murnaghan function while the x axis is V. The four parameters are the four parameters in the Birch–Murnaghan function. If you assume that you get something that looks like what he has.
Comment: Ah, wait, I finally get it. $E()$ isn't an expectation operator (as I'd expect  to see on the LHS of an equation without an error term on the RHS), $E$ is the response variable written as a function in the form $y(x)$. BIG HINT to everyone: Don't show an equation with $E()$ on the left of a regression equation to a statistician without carefully defining what you mean, because they'll likely assume it's an expectation.
Comment: @thyme I've made some small edits to help disambiguate your equation. Please check I haven't altered the meaning of anything
Answer: This is an ordinary least squares problem!
Defining
$$x = V^{-2/3}, \ w = V_0^{1/3},$$
the model can be rewritten
$$\mathbb{E}(E|V) = \beta_0 + \beta_1 x + \beta_2 x^2 + \beta_3 x^3$$
where the coefficients $\beta=(\beta_i)^\prime$ are algebraically related to the original coefficients via
$$16 \beta = \pmatrix{16 E_0 + 54 B_0 w^3 - 9 B_0 B_0^\prime w^3\\
 -144 B_0 w^5 + 27 B_0 B_0^\prime w^5\\
 126 B_0 w^7 - 27 B_0 B_0^\prime w^7\\
 -36 B_0 w^9 + 9 B_0 B_0^\prime w^9}.$$
This is straightforward to solve algebraically or numerically: pick the solution for which $B_0, B_0^\prime$, and $w$ are positive.  The only reason to do this is to obtain estimates of $B_0, B_0^\prime, w$, and $E_0$ and to verify they are physically meaningful.  All analyses of the fit can be carried out in terms of $\beta$.
This approach is not only much simpler than nonlinear fitting, it is also more accurate: the variance-covariance matrix for $(E_0, B_0, B_0^\prime, V_0)$ returned by a nonlinear fit  is only a local quadratic approximation to the sampling distribution of these parameters, whereas (for normally distributed errors in measuring $E$, anyway) the OLS results are not approximations.
Confidence intervals, prediction intervals, etc. can be obtained in the usual way without needing to find these values: compute them in terms of the estimates $\hat\beta$ and their variance-covariance matrix.  (Even Excel could do this!)  Here is an example, followed by the (simple) R code that produced it.

#
# The data.
#
X <- data.frame(V=c(41, 43, 46, 48, 51, 53, 55.5, 58, 60, 62.5),
                E=c(-48.05, -48.5, -48.8, -49.03, -49.2, -49.3, -49.35,
                    -49.34, -49.31, -49.27))
#
# OLS regression.
#
fit <- lm(E ~ I(V^(-2/3)) + I(V^(-4/3)) + I(V^(-6/3)), data=X)
summary(fit)
beta <- coef(fit)
#
# Prediction, including standard errors of prediction.
#
V0 <- seq(40, 65)
y <- predict(fit, se.fit=TRUE, newdata=data.frame(V=V0))
#
# Plot the data, the fit, and a three-SEP band.
#
plot(X$V, X$E, xlab="Volume", ylab="Energy", bty="n", xlim=c(40, 60))
polygon(c(V0, rev(V0)), c(y$fit + 3*y$se.fit, rev(y$fit - 3*y$se.fit)),
        border=NA, col="#f0f0f0")
curve(outer(x^(-2/3), 0:3, `^`) %*% beta, add=TRUE, col="Red", lwd=2)
points(X$V, X$E)

If you are interested in the joint distribution of the original parameter estimates, then it is easy to simulate from the OLS solution: simply generate multivariate Normal realizations of $\beta$ and convert those into the parameters. Here is a scatterplot matrix of 2000 such realizations.  The strong curvilinearity shows why the Delta method is likely to give poor results.
Comment: While it is true that algorithms for fitting linear models are much more numerically stable than those for nonlinear models, it is not true that there is a difference in the accuracy of the diagnostics so long as the nonlinear fitting algorithm converges. I checked and we have the same residual sum of squares to at least 4 sig figs. Also the linear parameterization you chose is highly confounded so that none of the parameters is significant according to t test.  All of mine are. Not really a big deal, but amusing and might confuse the young player.
Comment: @Dave Those are thoughtful points, thank you.  In a physical problem one typically is not concerned with significance: the theory implicates all the variables. One is instead concerned with *estimating* the values.  Although both approaches ought to achieve the same minimum loss (sum of squares of residuals), OLS produces correct distributions for the sampling variance of its parameters.  The nonlinear approach does not.  It is accurate to apply the transformation from the distribution of $\beta$ to $(E_0,\ldots)$, but using covariances of the $(\hat E_0\ldots)$ is only an approximation.
Comment: @Dave I agree: the models are the same but with different parameters.  The advantages of the OLS formulation extend to the fact that iid Normal errors in the response translate to an *exact* solution for the distribution of the parameter estimates $\hat\beta$, which is easily turned into an estimate of the full four-dimensional distribution of estimates of the original parameters.  Although this could be done by using the original parameterization, that would require more numerical work.  Moreover, the conceptual advantages of seeing the original model is just OLS in disguise are important.
Comment: Also, I guess you did not answer the OP's question since she stated she wanted something like confidence limits for the  enthalpy-volume-function
Comment: Your  model and mine are identical independent of the parameterization. (I am talking about the OLS model.) It is true that if a particular parameter  enters into the model linearly then the standard deviations produce better confidence limits for that parameter. the standard deviations obtained via the delta method will be the same whether it is used to parametrize the model or solved for as a dependent variable. In this case the dependent variable of interest is the  enthalpy-volume-function and its delta method std dev will be the same whether one uses your parametrization or mine.
Comment: @Dave I added a figure illustrating the problems with attempts at direct estimation of the joint distribution of the estimates of the original parameters.  It shows (forcibly) why standard deviations of those parameter distributions might not be worth much.  You need to estimate the full distribution because it is so nonlinear and heavily skewed.
Comment: What I am saying is that to second order both models contain identical information. If I use your equations to solve for your betas as dependent variables their standard deviaitons are estimated to be                                           9   beta_0      -2.7939e+01 1.5407e+01
    10   beta_1      -6.4243e+02 6.3200e+02
    11   beta_2       4.9346e+03 8.6054e+03
    12   beta_3      -1.6960e+03 3.8894e+04
If you multiply by sqrt(10/6) to correct for degrees of freedom they are identical to those produced by the R OLS routine.
Comment: If you use simulation (which I agree is a good idea) then it is valuable that the independent variables in the model are jointly normally distributed. If you use the delta method you get the same result in either case.  However there is still the problem that one should use a moderately robust procedure and I have provided a way of doing this. Getting back to the OP's original problem, I think your parametrization combined with a moderately robust estimation procedure would be the superior approach. I agree that should have noticed that the model was essentially linear.
Comment: Of course once you move to a robust model the exact nomality of the estimates in lost, but only slightly.
Answer: There is a standard approach for this called the delta method.
You form the inverse of the Hessian of the log-likelihood wrt
your four parameters. There is an extra parameter for the variance of
the residuals, but it does not play a role in these calculations.
Then you calculate predicted response for the desired values of the
independent variable and calculate its gradient (the derivative wrt)
these four parameters.  Call the inverse of the Hessian $I$ and the
gradient vector $g$. You form the vector matrix product
$$-g^tIg$$
This gives you the estimated variance for that dependent variable.
Take the square root to get the estimated standard deviation. then the
confidence limits are the predicted value +- two standard deviations.
This is standard likelihood stuff. for the special case of a nonlinear regression you can correct for the degrees of freedom. You have 10 observations and 4 parameters so you can increase the estimation of the
variance in the model by multiplying by 10/6. Several software packages will do this for you. I wrote up your model in AD Model
in AD Model Builder and fit it and calculated  the (unmodified) variances.
They will be slightly different from yours because I had to guess a bit at the values.
                    estimate   std dev
10   pred_E      -4.8495e+01 7.5100e-03
11   pred_E      -4.8810e+01 7.9983e-03
12   pred_E      -4.9028e+01 7.5675e-03
13   pred_E      -4.9224e+01 6.4801e-03
14   pred_E      -4.9303e+01 6.8034e-03
15   pred_E      -4.9328e+01 7.1726e-03
16   pred_E      -4.9329e+01 7.0249e-03
17   pred_E      -4.9297e+01 7.1977e-03
18   pred_E      -4.9252e+01 1.1615e-02

This can be done for any dependent variable in AD Model Builder. One declares a variable in the appropriate spot in the code like this
   sdreport_number dep

and writes the code the evaluate the dependent variable like this
dep=sqrt(V0-cube(Bp0)/(1+2*max(V)));

Note this is evaluated for a value of the independent variable 2 times
the largest one observed in the model fitting. Fit the model and one obtains
the standard deviation for this dependent variable
19   dep          7.2535e+00 1.0980e-01

I have modified the program to include code for calculating the
confidence limits for the  enthalpy-volume function
The code (TPL) file looks like
DATA_SECTION
 init_int nobs
 init_matrix data(1,nobs,1,2)
 vector E
 vector V
 number Vmean
LOC_CALCS
 E=column(data,2);
 V=column(data,1);
 Vmean=mean(V);

PARAMETER_SECTION
 init_number E0
 init_number log_V0_coff(2)
 init_number log_B0(3)
 init_number log_Bp0(3)
 init_bounded_number a(.9,1.1)
 sdreport_number V0
 sdreport_number B0
 sdreport_number Bp0
 sdreport_vector pred_E(1,nobs)
 sdreport_vector P(1,nobs)
 sdreport_vector H(1,nobs)
 sdreport_number dep
 objective_function_value f
PROCEDURE_SECTION
  V0=exp(log_V0_coff)*Vmean;
  B0=exp(log_B0);
  Bp0=exp(log_Bp0);
  if (current_phase()<4)
  f+=square(log_V0_coff) +square(log_B0);

  dvar_vector sv=pow(V0/V,0.66666667);
  pred_E=E0 + 9*V0*B0*(cube(sv-1.0)*Bp0
    + elem_prod(square(sv-1.0),(6-4*sv)));

  dvar_vector r2=square(E-pred_E);
  dvariable vhat=sum(r2)/nobs;
  dvariable v=a*vhat;
  f=0.5*nobs*log(v)+sum(r2)/(2.0*v);

  // code to calculate the  enthalpy-volume function
  double delta=1.e-4;
  dvar_vector svp=pow(V0/(V+delta),0.66666667);
  dvar_vector svm=pow(V0/(V-delta),0.66666667);
  P = -((9*V0*B0*(cube(svp-1.0)*Bp0
      + elem_prod(square(svp-1.0),(6-4*svp))))
      -(9*V0*B0*(cube(svm-1.0)*Bp0
      + elem_prod(square(svm-1.0),(6-4*svm)))))/(2.0*delta);
  H=E+elem_prod(P,V);

dep=sqrt(V0-cube(Bp0)/(1+2*max(V)));

Then I refitted the model to get the standard devs for the estimates of H.
29   H           -3.9550e+01 5.9163e-01
30   H           -4.1554e+01 2.8707e-01
31   H           -4.3844e+01 1.2333e-01
32   H           -4.5212e+01 1.5011e-01
33   H           -4.6859e+01 1.5434e-01
34   H           -4.7813e+01 1.2679e-01
35   H           -4.8808e+01 1.1036e-01
36   H           -4.9626e+01 1.8374e-01
37   H           -5.0186e+01 2.8421e-01
38   H           -5.0806e+01 4.3179e-01

These are calculated for your observed V values, but could be easily calculated for any value of V.
It has been pointed out that this is actually a linear model for which there is simple R code to perform the parameter estimation via OLS. This is very appealing especially to naive users.  However since the work of Huber over thirty years ago we know or should know that one should probably almost always replace OLS with a moderately robust alternative. The reason this is not routinely done I believe is that robust methods are inherently nonlinear. From this point of view the simple appealing OLS methods in R are more of a trap, rather than a feature. An advabtage of the AD Model Builder approach is its built in support for nonlinear modelling. To change the least squares code to a robust normal mixture only one line of the
code needs to be changed. The line
    f=0.5*nobs*log(v)+sum(r2)/(2.0*v);

is changed to
f=0.5*nobs*log(v)
  -sum(log(0.95*exp(-0.5*r2/v) + 0.05/3.0*exp(-0.5*r2/(9.0*v))));

The amount of overdispersion in the models is measured by the parameter
a. If a equals 1.0, the variance is the same as for the normal model. If there is inflation of the variance by outliers we expect that a will be smaller than 1.0.  For these data the estimate of a is about 0.23 so that
the variance is about 1/4 the variance for the normal model. The interpretation is that outliers have increased the variance estimate by a factor of about 4.  The effect of this is to increase the size of the confidence bounds for parameters for the OLS model. This represents a loss of efficiency. For the normal mixture model the estimated standard deviations for the  enthalpy-volume function are
 29   H           -3.9777e+01 3.3845e-01
 30   H           -4.1566e+01 1.6179e-01
 31   H           -4.3688e+01 7.6799e-02
 32   H           -4.5018e+01 9.4855e-02
 33   H           -4.6684e+01 9.5829e-02
 34   H           -4.7688e+01 7.7409e-02
 35   H           -4.8772e+01 6.2781e-02
 36   H           -4.9702e+01 1.0411e-01
 37   H           -5.0362e+01 1.6380e-01
 38   H           -5.1114e+01 2.5164e-01

One sees that there are small changes in the point estimates,
while the confidence limits have been reduced to about 60%
of the ones produced by OLS.
The main point I want to make is that all the modified calculations occur automatically once one changes the one line of code in the TPL file.
Comment: For @thyme's benefit, I'd like to note that the "delta method" is essentially the exact same procedure as the "propagation of uncertainty" that s/he is familiar with and which is commonly taught to scientists -- at least, they are the same procedure when the latter is done correctly. One caveat is that the posted formula in the question ignores correlations between the estimated values of the parameters. Ignoring the correlations is equivalent to only considering the diagonal elements of $I$ in the delta method.
Comment: Also for @thyme, propagation of uncertainties / the delta method only produces the uncertainty in $\mathbb{E}(E\mid V)$. On top of this is any bias/variance due to noise. I take it that you're making predictions about physical samples, whose energy/enthalpy/other thermodynamic quantities don't have the same noise as they do in your simulation software, but in either case this adds an extra source of variance on top of the variance in $\mathbb{E}(E\mid V)$ or $\mathbb{E}(H \mid V)$ that's due to the uncertainty from the fit.
Comment: @jwimberley , you're basically saying that dave fourier gave the formula for the confidence interval of the (conditional) mean, while thyme may be interested in the prediction interval for a new observation. It's easy to compute the latter for OLS. How do you compute it in this case?
Comment: @DeltaIV It would still be easy in this case -- if the non-linear least-squares model $E = f(V) + \epsilon$ is correct, then the residuals $E -\hat E$ of the fit are distributed like $\epsilon$. So, the extra variance in the prediction interval is the variance of the fit residuals. This is related to the idea in the answer's post-script (which is not $V$-dependent because the fit model is not heteroskedastic). However, more importantly, $\epsilon$ in the fit comes from computational limits, while $\epsilon$ in the world comes from thermodynamic fluctuations, which probably aren't comparable.
Comment: @jwimberley I only showed the confidence limits for the predicted values corresponding to observed V values simply because they were available.  I have edited my answer to show how to get confidence limits for any dependent variable.
Comment: @DeltaIV I had to work with the model as stated (or more precisely the model as I assumed the OP intended it to be stated). If you want to formulate a statistical model which is more reasonable from a physical standpoint, I'm sure the approach could be extended to it.
Comment: Thank you very much for this spirited debate! Unfortunately I am a bit swamped by all this statistical buzz words ;-) . Anyway I will try to understand what you all wrote. Let me clarify my goal. I need this energy-volume-function, $E(V)$, to get the pressure-volume-function $p(V)=-\frac{\partial E(V)}{\partial V}$. Finally I construct an enthalpy-volume-function from that: $H(V) = E(V) + p(V) \cdot V$. Then I compare the enthalpy with an experimentally measured enthalpy. For this I need to understand how the noise of my energy-volume samples affect my enthalpy-volume-function.
Comment: For the fitting I use the leasqr function of octave. It returns (among others): the parameters, the correlation matrix for parameters, the covariance matrix of the parameters, the diagonal(covariance matrix of the residuals), the standardized residuals, the matrix that defines confidence region, the coefficient of multiple determination: http://octave.sourceforge.net/optim/function/leasqr.html
Comment: @dave fournier: Is the "covariance matrix of the parameters" equal to your inverse of the Hessian, $I$? Because this is what I get from the octave fitting routine. And did I understand that correctly if I define $\vec g(V) = \big( \partial_{E_0} E(V), \partial_{V_0} E(V), \partial_{B_0} E(V), \partial_{B'_0} E(V) \big)$ in order to calculate the variance? For some reason I don't need the minus sign, so I calculate $\sigma^2(V) = g^{T}(V)Ig(V)$.
Comment: This is because you already have the minus I think. It is like $x^2/2=-\log(\exp(-x^2/2))$ However I still think that you should use a robust estimation technique.  Look at the residuals of the model and you will see that one of them (first or second I think) is an outlier. Also whuber's linear parameterization should be exploited if possible. Then you could get more exact confidence limits via Monte Carlo calculations. You (and everyone) should read the introduction to Huber, Robust Statistics , second edition for a really good discussion of models with data just like yours.
Answer: Cross-validation is a simple way to estimate reliability of your curve:
https://en.wikipedia.org/wiki/Cross-validation_(statistics)
Propagation of uncertainty with partial differentials is great is you really know $\Delta E_{0},\Delta V_{0},\Delta B_{0}$, and $\Delta B'$. However, the program you are using gives only fitting errors(?). Those will be too optimistic (unrealistically small).
You can calculate 1-fold validation error by leaving one of your points away from fitting and using the fitted curve to predict value of the point that was left away. Repeat this for all points so that each is left away once. Then, calculate validation error of your final curve (curve fitted with all points) as an average of prediction errors.
This will only tell you how sensitive your model is for any new data point. For example, it will not tell you how inaccurate your energy model is. However, this will be much more realistic error estimate mere fitting error.
Also, you can plot prediction errors as a function of volume if you want.

Reliability of a fitted curve?


Ajuda cURL+ sleep

Question: Existe a possibilidade de fazer um script que tenho em CURL aguardar 50 segundos para executar?
Tentei sleep mais ele da stop para todo a execução, estou precisando pausar somente o Curl em questão
function writeMessage() {
$fields = array('site' => $site, 'uid' => $uid, 'ip' => $ip, 'id' => $id);
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, 'https://xxxx.xx/widget-ajax.php');
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
  $result = curl_exec($ch);
  curl_close($ch);
    }

consigo fazer ele esperar 50 segundos ante de de executar sem trava o restante do código?
Tentei também por ajax em jsonp mais está complicado realiza o POST cross-domain a segurança do navegador impede..
Answer: Partindo do princípio que você já conhece o fluxo de requisições ajax (pelo fato de ter tentando jsonp), você pode fazer um sistema de "proxy" onde você faria a requisição ajax para um arquivo específico no seu servidor e esse arquivo faria a requisição via curl ou file_get_contents para o site desejada para driblar o CORS. o fluxo seria mais ou menos assim.

Usuario entra na pagina abc
A página é rederizada no navegador
Após x segundos, um js na página abc faz ajax para o arquivo xpto.php no mesmo servidor.
Arquivo xpto.php faz cURL, prepara os dados para devolver para abc
página abc recebe os dados e faz a lógica do negócio

Na prática o fluxo implementado seria mais ou menos assim:
Página abc (somente a parte do ajax com jQuery)
jQuery(document).ready(function ($) {
    setTimeout(function () {
        $.get('xpto.php', function (dados) {
            alert('Dados recebidos, veja o console para mais detalhes');
            console.log(dados);
            // fazer alguma coisa coms os dados
        });
    }, 50000); // 50 segundos
});

Arquivo xpto.php
<?php
$fields = array('site' => $site, 'uid' => $uid, 'ip' => $ip, 'id' => $id);
$ch  = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://xxxx.xx/widget-ajax.php');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

// Talvez você precise desativar a verificação de peers localmente
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

$result = curl_exec($ch);
curl_close($ch);

// To Do não esquecer de tratar a respota antes de devolvê-la
echo json_encode(['data' => $result]);
exit;

Se você precisar sempre ficar fazendo a checagem de tempos em tempos basta trocar a função de setTimeout para setInterval
Se você preferir um abordagem apenas do lado o PHP você tentar uma das soluções propostas neste artigo (em inglês)
Comment: Isso nao funciona, ele paraliza todo o script da pagina!
Comment: @ViníciusRemonti Editei minha resposta com um exemplo como uma alternativa ao jsonp que evita o problema do CORS
Answer: Existe mas não é muito comum fazer isso em php. Como o código é executado assíncrono, tu vai ter que fazer um fork do processo e nele tu vai esperar 50s enquanto isso no processo principal vai ser executado o resto da sua lógica.
$pid = pcntl_fork();
if ($pid == -1) {
     die('erro');
} else if ($pid) {
    // continua o resto do processo aqui;
    pcntl_wait($status);
} else {
    sleep(50);
    writeMessage();
}
// Qualquer código que tiver aqui vai ser executado pelos dois processos
// então vai passar duas vezes por aqui, por isso deixar o resto da lógica dentro
// do if pra ser rodado somente no processo pai.

Recomendo ver melhor sobre fork aqui. Além disso se estiver utilizando php 7.2+ tu pode utilizar uma nova biblioteca padrão pra paralelismo.

Ajuda cURL+ sleep


Chain js function and then method in vue.js

Question: Within a Vue component, I am calling a function from a separate JS file. I then need to call a method in my component just after this first function is completed:
My .vue component:
import myFunction from '@/components/functions';

export default {
  name: 'test',
  components: {
    myFunction,
  },
  created(){
    if (....) {
      myFunction.function1(myParam)
        .then((response) => {
        this.method2();
       });
  },
  methods:{
    method2(){
      something;
    },
  }
};

My separate functions.js file:
export default {
  function1(myParam) {
    ...
    return true;
  },
};

I tried several things such as the last one shown in my code which gives me a
.function1(...).then is not a function

I am sure it is not that complicated but can not find the correct syntax.
Answer: The function in your other file could return a Promise or it can except a callback from your view component. Also, if you set this equal to self/vm and then use vm.method2(), this is because in the then callback this is defined in scope of that function not the Vue component.


Find the PID(s) of running processes and store as an array

Question: I'm trying to write a bash script to find the PID of a running process then issue a kill command. I have it partially working, but the issue I face is that there may be more than one process running. I want to issue a kill command to each PID found.
I presume I need to put each PID in to an array but am at a loss as to how to do that.
What I have so far:
pid=$(ps -fe | grep '[p]rocess' | awk '{print $2}')
if [[ -n $pid ]]; then
    echo $pid
    #kill $pid
else
echo "Does not exist"
fi

What this will do is return all PIDs on a single line, but I can't figure out how to split this in to an array.
Comment: Check the `killall`  or `pkill`  command to save yourself a lot of work.
Answer: Here's a little one liner that might help
for pid in `ps -ef | grep your_search_term | awk '{print $2}'` ; do kill $pid ; done

Just replace your_search_term with the process name you want to kill.
You could also make it into a script and swap your_search_term for $1
EDIT: I suppose I should explain how this works.
The back ticks `` collects the output from the expression inside it.  In this case it will return a list of pids for a process name.
Using a for loop we can iterate through each pid and kill the process.
EDIT2: replaced kill -9 with kill
Comment: Don't `kill -9` unless you know processes are likely to fail closing neatly.
Comment: Also, `grep A | awk '{ B }'` is almost always better written `awk '/A/ { B }'`. If you want to pass in a regex as a parameter, `awk -v param=A '$0 ~ param { B }'`
Answer: You don't need to use an array if you're going to immediately iterate over the results and perform an action:
for pid in $(ps -fe | grep '[p]rocess' | grep -v grep | awk '{print $2}'); do
    kill "$pid"
done

Notice we have to exclude grep's pid from the list of processes to kill. Or we could just use pgrep(1):
for pid in $(pgrep '[p]rocess'); do
    kill "$pid"
done

If you actually needed to store the pids in an array, pgrep is how you would do it:
pids=( $(pgrep '[p]rocess') )

Back to killing process. We can still do better. If we're just using pgrep to get a list of processes to kill them, why not go straight for pgrep's sister program: pkill(1)?
pkill '[p]rocess'

As it turns out, no need for bash scripting at all.
Answer: Don't know why you would ever grep for a process to kill, unless you didn't know the command name. Most modern versions of ps have the flags
    -C cmdlist
          Select by command name.  This selects the processes whose executable name is given in cmdlist.

and
   -o format
          User-defined format.  format is a single argument in the form of
          a blank-separated or comma-separated list, which offers a way to
          specify individual output columns.  The recognized keywords are
          described in the STANDARD FORMAT SPECIFIERS section below.
          Headers may be renamed (ps -o pid,ruser=RealUser -o
          comm=Command) as desired.  If all column headers are empty (ps
          -o pid= -o comm=) then the header line will not be output.
          Column width will increase as needed for wide headers; this may
          be used to widen up columns such as WCHAN (ps -o pid,wchan=WIDE-
          WCHAN-COLUMN -o comm).  Explicit width control (ps opid,
          wchan:42,cmd) is offered too.  The behavior of ps -o pid=X,
          comm=Y varies with personality; output may be one column named
          "X,comm=Y" or two columns named "X" and "Y".  Use multiple -o
          options when in doubt.  Use the PS_FORMAT environment variable
          to specify a default as desired; DefSysV and DefBSD are macros
          that may be used to choose the default UNIX or BSD columns.

So you can just do
ps -o pid= -C commandName

Will return the pid of all processes named exactly commandName and is cleaner and faster. Or kill a loop
while read -r pid; do
  kill "$pid"
done < <(ps -o pid= -C commandName)

But really, you should always just be able to do
> pkill commandName

Answer: Your script seems fine, if you want to have each pid list on a new like then replace:
echo $pid
#kill $pid

with
echo "$pid"
#kill "$pid"

Comment: This is poor advice. Without the quotes, the shell splits the variable's value into tokens on whitespace, so when the variable contains multiple PIDs, `kill` receives them as positional arguments. *With* the quotes, the variable is passed to `kill` as a single parameter, with newlines and all, which is not a valid argument to `kill`. So the quotes only work sort of by accident only when the variable contains a single PID, and provide no value (or actually, only negative value).


SQL Server 2012 - where is Management Studio?

Question: I recently downloaded and installed the RC0 of SQL Server 2012.
I followed the installation process as usual, however - I can't seem to find SQL Server Management Studio (ssms.exe).
Where can it be found?
Comment: Denali comes with "SQL Server Data Tools" (SSDT). It looks like Visual Studio
Answer: I got it installed the other night and it was under Start > Programs > Microsoft SQL Server 2012 (I think was the full name). Same folder structure as SQL Server 2008 R2.
You can also just go to Start > Run, and type in ssms.exe.
If neither of these work you might want to just search your system drive for the exe to see if it actually got installed. You may not have checked the box for management tools depending on how you walked through the wizard.


Is the inverse busy beaver calculable?

Question: Obviously "Largest $n$ that $BB(n)$ isn't larger than the input" is not calculable, otherwise while(iBB(i)<n)i++ solves the busy beaver;
However, if we define inverse busy beaver as "$n$ that $BB(n)$ is the input; undefined behavior if no $n$ satisfies", the proof above no longer works.
In this case is it solvable?
Answer: However, if we define inverse busy beaver as "$n$ that $BB(n)$ is the input; undefined behavior if no $n$ satisfy"
It should be easy to see that this function can't be a partial computable function. Well the simple way to see it is suppose that some program $P$ computed this given partial function. But now we can easily construct a program that computes a total computable function $f:\mathbb{N} \rightarrow \mathbb{N}$ such that $f(x) \ge BB(x)$ for all $x \in \mathbb{N}$.
Here is how we compute $f$ on some given input $x$. If $x=0$, just return $BB(0)$ as output. If $x>0$, one can just simulate this program $P$ on all inputs (in a certain fixed manner). Now each time the program $P$ halts on some input, you record this input value. Let's denote this value as $t$. Now you just check the condition $t>f(x-1)$ every time. If this condition is true, then return the value $t$ as output. Otherwise just keep simulating the program $P$.

So the above argument shows that there is no partial recursive function $g$ such that $g(BB(n))=n$ for all $n \in \mathbb{N}$ and $g$ is undefined on all other inputs (ones that are not of the form $BB(n)$). It seems that the intended question was whether there is some partial recursive function $f:\mathbb{N} \rightarrow \mathbb{N}$ which "extends" $g$ in the sense that $f(x)=g(x)$ whenever $g(x)$ is defined. Don't confuse this function $f$ with the one in the first part of the answer (this is intended to be a different function).
I think there should be such a function $f$. For example, we can define $f$ as follows: $(1)$ If there is no program (with blank/zero input of course) that halts exactly on the $n$-th step, then define $f(n)=\uparrow$. $(2)$ Now Suppose there is a program that halts exactly on the $n$-th step. Now consider the program(s) of smallest length (it doesn't matter if there are two programs of smallest length) which halt on $n$-th step, and let's denote the length of such  program(s) as $N$. We define $f(n)=N$.
It seems that if we choose the specifics (such as definition of time and length of a program), then we can drop $(1)$ in above definition. For example, "normally" we assume that, for all $n$, there is always some program of length $n$ that halts exactly on the $n$-th step, on blank input. In that case, we will have $f$ as total and we will get $f(n) \leq n$ (for all $n$).
First, we can observe that the function $f$ extends $g$ because $f(x)=g(x)$ for all points where $g$ is defined. For example, consider the value $BB(n)$ (for an arbitrary $n$). Now, by definition, there is exists a program of length $n$ which halts exactly on this step (when given zero/blank input). Now under most reasonable definitions, I think, $BB$ should be a strictly increasing function. That means there is no program of length less than $n$ which halts exactly on this step (when given zero/blank input). If that was true then we would have $BB(m)=BB(n)$ for some $m<n$ (violating the strictly increasing condition). Hence the function $f$ extends $g$.
Finally, here is a (very) rough sketch for the partial computable function $f$. We can proceed in iterations. In the $i$-th iteration we simulate all programs of length $\leq i$ up unitl $i$ steps (on zero/blank input of course). Now consider any value $x \leq i$. If there is some program of length $i$ or less that halts on the $x$-th step, then we can easily determine this. In fact, we can easily determine the value $f(x)$ based upon this. For example, generically, on $BB(n)$-th step we will simulate all programs of length $BB(n)$ or less exactly till $BB(n)$ number of steps. We will find that the smallest program that halts on this step is of length $n$ (and hence we will output $f(BB(n))=n$).
Comment: I guess you assume it doesn't halt if no $n$ satisfy? (otherwise the proof don't make much sense)
Comment: Yes, I assumed that you were trying to define a partial function $g:\mathbb{N} \rightarrow \mathbb{N}$ so that it returns $n$, when the input given to it is $BB(n)$. In symbols, $g(BB(n))=n$ for all $n \in \mathbb{N}$. Otherwise, it is undefined (and hence the program $P$ computing it doesn't halt) on any other input. That's how I understood it. What I was describing in the answer was that the function $g$ can't be a partial computable function. If you were trying to define something else, then this answer might not apply.
Comment: "Undefined behavior" can also return arbitrarily value (actually it's allowed to destroy the world, but it just have no ability to do so)
Comment: I think what you are asking is that whether there is a partial computable function which "extends" the function $g$ mentioned above. I think the answer to this might be positive (unless I am making a mistake with sketch in my mind). I will update the answer later in that case.
Answer: One can define $\Sigma^{-1}(n) = m$ to be the number of states $m$ needed for Turing machine to write $n$. But then the function $\Sigma^{-1}(n)$ may be decreasing sometimes, as there are only $(4n+4)^{2m}$ Turing machines with m states, and there may be numbers below $10^{10^{100}}$ which are writable only with the number of states equivalent to itself.

Is the inverse busy beaver calculable?


Matrix-rank changes after rotation

Question: I might be wrong. Assume matrix $M$ as a data matrix (e.g., a 2D image). $M$'s rank represents the underlying dimension of the data (or the degree of freedom). For example, $M$ usually isn't full-rank, which means the underlying data lie on some low-dimensional manifold. Now if I rotate the matrix with regard to its centre, even with a tiny angle, the rank of the matrix changes (and the change could be significant). For example, assume $M$ is a matrix of alternating allzero- and allone- columns, like the following:
$$\left(\begin{array}{ccccc}
1 & 0 & 1 & 0 & 1\\
1 & 0 & 1 & 0 & 1\\
1 & 0 & 1 & 0 & 1\\
1 & 0 & 1 & 0 & 1\\
1 & 0 & 1 & 0 & 1\\
\end{array}\right)$$
The rank of this matrix is $1$. But even if you rotate it with $0.1$ degree, it becomes full-rank. On the other hand, however, the underlying data hasn't changed during the rotation, which means it still lies on the same low-dimensional manifold. My questions are:
1), Does this conflict that the matrix-rank represents the underlying dimension of the data (or the degree of freedom)?
2), I guess there exist some theory about such matrix-rotation and data dimension, etc. What's the theory? I don't even know what keywords to use for searching the theory. 'matrix rotation' always returns results about 'rotation matrix'..
Thank you all!
Comment: What do you mean by "rotate the matrix with regard to its centre"?
Comment: I think user44197's description is more accurate than mine. Basically it can be seen as rotating the target while keeping the camera fixed, or rotating the camera while keeping the target fixed.
Comment: Ok, then what do you think is the "underlying dimension of the data" of a $1000\times1000$ identity matrix? If I understand you correctly, it is an image of a diagonal line but has rank 1000.
Comment: Yes that's another example of my question. On one hand, the underlying dimension of the I matrix is 1 million since it's full-rank. On the other hand, it's an image of 1 line so its underlying dimension should be low. For example, if you rotate it 45 degrees to change get a 'allones' column, the underlying dimension becomes 1999.
Answer: Note you are not "rotating" the matrix. You are rotating the indices. The matrix you have can be (and is) viewed as a function of $x$ and $y$ (or rows and columns) as
$$
M = M(x,y) = M(p) \text{ where $p = (x,y)^T$ is vector representing the point}
$$
When you rotate the image you are doing
$$
\hat M(p) = M(R^{-1} p)
$$ where $R$ is a rotation matrix.
You are confusing this with rotating the matrix
$$
\hat M = R M R^{-1}
$$
where $R$ is a rotation matrix.
The two are different. If you view $M$ as a function, the first is rotation in the domain space and the second is rotation in the range space.
Comment: Well, while I think this is more accurate description of my question, is there still my problem? You rotate the coordinates while keeping the camera static, then take a shot. The result is a different image of the same data, however this new image probably has a different rank from the one taken before the rotation. How to explain this?
Comment: Because *rank* has no meaning. In mathematics you use matrices in a variety of ways. One is to encode data. This is what image processing does. The other is to represent linear transformation. Concept of rank is meaningful only if you use matrices for linear transformation. In the first case it is only a rectangular array for organizing data. If you are trying to use rank for image compression using KLT or similar methods, rotation will introduce very small eigenvalues whose components can be safely ignored.

Matrix-rank changes after rotation


Increasing Google Analytics API Quota

Question: Our organization is approaching the hard limits for the Google Analytics API (10000 profile access/day). Google clearly indicates that they will not increase this.

Analytics API quota request form
Quotas that CANNOT be increased:
  -- Per view (profile) limit of 10,000 requests/day  [403 Error with Message about Profile limit: dailyLimitExceeded]

There is a Google Analytics Premium  for 150 000USD a year but that is much more that we can afford for such a service.
Is there no middle ground for a paid increase to the Google Analytics API quotas?
Comment: You should contact Google's customer or sales support for that.
Comment: @simbabque There is no Google Analytics customer sales or support for free accounts the support is here on stackoverflow.
Comment: @DaImTo this reminds me of http://meta.stackoverflow.com/questions/296893/more-actively-discourage-product-support-at-stack-overflow. While technical help is fine, asking for different plans are very likely off-topic here.
Comment: So if we change the question to "how can we increase the Quota, or how can I program around it?"
Answer: There is no way to increase the 10,000 request per profile / view limit. Even if you have a premium Google analytics account that wont change.
What you do get with a Premium analytics account is the option to use BigQuery with Google Analytics making this problem go away.
Option make a second profile / view for the web property you get another 10k that way.

Increasing Google Analytics API Quota


what is the purpose of site_key?

Question: In ROOT/modules/update/update.fetch.inc, there is the following code.
$site_key = drupal_hmac_base64($base_url, drupal_get_private_key());
$url = _update_build_fetch_url($project, $site_key);

_update_build_fetch_url() contains the following code.
  // Only append usage information if we have a site key and the project is
  // enabled. We do not want to record usage statistics for disabled projects.
  if (!empty($site_key) && (strpos($project['project_type'], 'disabled') === FALSE)) {
    // Append the site key.
    $url .= (strpos($url, '?') !== FALSE) ? '&' : '?';
    $url .= 'site_key=';
    $url .= rawurlencode($site_key);

    // Append the version.
    if (!empty($project['info']['version'])) {
      $url .= '&version=';
      $url .= rawurlencode($project['info']['version']);
    }

    // Append the list of modules or themes enabled.
    $list = array_keys($project['includes']);
    $url .= '&list=';
    $url .= rawurlencode(implode(',', $list));
  }

This function generates the URL to fetch information about project updates, returning a URL like http://updates.drupal.org/release-history/examples/7.x?site_key=FuSSIDdX3JtCJQV7F1hWK6WopklCLf0jjHFDC1Nevys&version=7.x-1.x-dev&list=ajax_example%2Cexamples.
Why does Drupal need site_key? How do I know the value of $base_url from site_key?
Answer: It's a unique value that allows to identify the site asking for updates. It is used on Drupal.org when giving the number of site using a module, which is shown in every project page.

Without that value, Drupal.org could not report the number of sites using a module, since it could not understand which site is asking for updates.
Since site_key is a crypted hash derived from $base_url, you cannot get the value of $base_url from its hash; that is how hash works. Hashes are used to save the passwords in the database; nobody can get the value of the password from the hash saved in the database.
Answer: I believe this is a unique token for each site, that Drupal reports when checking for updates. So the statistics (below the releases there is a 'view usage statistics' link) are checked against a token. Otherwise if you would check for updates 100 times, there would be in increased usage for all your modules.
So it enhances accuracy on Drupal.org backed.

what is the purpose of site_key?


Problems using portproxy mapping on windows

Question: I have a server app installed on windows server 2012 called air video server which on installation attaches to my local address [::1] instead of my network address [192.168.0.3] on port 45631, I need the server to be reachable at 192.168.0.3:45631. I've looked for solutions and tried
<code>netsh interface portproxy set v4tov6 listenaddress=[192.168.0.3] listenport=45631 connectaddress=[::1] connectport=45631
</code>
but it doesn't seem to work. Am I going the right way to do this?
Answer: The service in question is currently bound to the loopback interface. You should read the documentation for the program in question and figure out how to bind it to 192.168.0.3.
Doing what you are doing now is almost certainly not the right way.
Comment: I've looked at the documentation, but there is nothing about setting an alternative. it shouldn't be using the loopback interface, but it does, I know it's almost certainly not the right way, but am looking for a solution (even if it's a hack!)
Comment: Are you using the latest version? I just installed it on a test machine and it binds to `[::]` not `[::1]`


is laravel 5.4 running migrations from vendor folders now?

Question: I have installed some packages that have migrations in their vendor folders, previously one of the packages I used published these migrations to migrations folder by running:
php artisan vendor:publish
Now I found alteast 2 packages that no longer published migrations when running this command, so I went into vendor folder and grabbed migration file and manually moved it and when I run
composer dump-autoload I got a warrning message from it that said: Warning:

Ambiguous class resolution, "CreateRevisionsTable" was found in both "$baseDir . '/database/migrations/2013_04_09_062329_create_revisions_table.php" and "C:\xampp\htdocs\example\vendor/venturecraft/revisionable/src/migrations\2013_04_09_062329_create_revisions_table.php", the first will be used.

why is this happening? Has something changed in 5.4?
Answer: Yes, since version 5.4 Laravel supports loading migrations from any directory.
<code>$this->loadMigrationsFrom(__DIR__.'/path/to/migrations');
</code>
Which could be used by a service provider of any package.
Comment: @AmitShah make sure you have the correct path into the `loadMigrationsFrom()` method and the migration file is inside. This will probably not throw an error on a not found path or empty folder.
Comment: I am developing my custom package using this : https://wisdmlabs.com/blog/create-package-laravel/ but i am not able to run the migration. it seems the execution is coming to the above line but no table is being created.
Comment: thanks it was my mistake about the wrong relative path.


Confusion with Python import

Question: I have a package of utility modules and classes that are imported using the following example statement:
from MarixFramework.switcher import SwitchClient

When MarixFramework is installed as a package the above statement works fine. However, I want to do some local testing of the package contents, so I want to import directly from my local folder tree that has the following structure:
Workspace
   MarixFramework
      MarixFramework
   eBlanketBot
      -- project source files

If I add Workspace\MarixFramework to sys.path then I get the following error:
>>> sys.path: ['/home/pi/hd1/Projects/Workspace/MarixFramework', '', '/home/pi/hd1/Projects/Workspace/eBlanketBot', '/usr/share/eric/modules/DebugClients/Python', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/home/pi/.local/lib/python3.7/site-packages', '/usr/local/lib/python3.7/dist-packages', '/usr/lib/python3/dist-packages']
Exception "ImportError"
cannot import name 'SwitchClient' from 'MarixFramework.switcher' (/home/pi/hd1/Projects/Workspace/MarixFramework/MarixFramework/switcher.py)
File: /home/pi/hd1/Projects/Workspace/eBlanketBot/blanketClient.py, Line: 9

The import procedure has obviously found the desired source file, but fails to import from it. Why?
What I am trying to achieve is to import the MarixFramework modules directly from the folder tree. Then, when my local testing is complete I can just rebuild and install it as a package without having to change the import statement syntax.
Answer: Okay, my mistake. It seems that relative importing using the dot syntax is possible. I had an error in my import statement - attempting to import a class from the wrong source file. Duh!
Setting up the sys.path as in the above example does work. Phew! That simplifies package testing.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

Confusion with Python import


In how many ways can we distribute $2$ types of gifts?

Question: The problem: In how many ways can we distribute $2$ types of gifts, $m$ of the first kind and $n$ of the second to $k$ kids, if there can be kids with no gifts?
From the stars and bars method i know that you can distribute m objects to k boxes in $\binom{m+k-1}{k-1}$ ways.
So in my case i can distribute m gifts to k kids in $\binom{m+k-1}{k-1}$ ways, same for n gifts i can distribute them in $\binom{n+k-1}{k-1}$ ways.
So now if we have to distribute m and n gifts we can first distribute m gifts in $\binom{m+k-1}{k-1}$ ways, then n gifts in $\binom{n+k-1}{k-1}$ ways, so in total we have: $$\binom{m+k-1}{k-1} \cdot \binom{n+k-1}{k-1} \quad \textrm{ways.}$$
Is my reasoning correct?
What about when we have to give at least 1 gift to each kid, can we do that in $$\binom{m-1}{k-1} \cdot \binom{n+k-1}{k-1}+\binom{n-1}{k-1} \cdot \binom{m+k-1}{k-1}  \quad \textrm{ways?}$$
Any help would be appreciated.
Comment: Yes, your reasoning is correct
Comment: @mode_er Thank you very much! After looking into it i modified the second answer a bit, is that also correct?
Comment: Hm, I don't think so. Your second answer assumes that if each kid gets one gift, then each kid must get only at least one of either the first gift or only at least one of the second gift, when in reality, the requirement can be satisfied just by every kid getting at least one gift, not necessarily of the same kind. Your reasoning is correct so far, you just need to interpolate for the cases in between, which unless you have an identity at hand to use, might result in an "ugly" answer. I'll do some research to see if such an identity exists
Comment: @mode_er This is how i came up with that answer. The number of ways you can distribute gifts to kids such that every kid gets at least one gift is $\binom{m-1}{k-1}$, so i thought if i first give at least one of the first kind there wouldn't be any restrictions to giving the second, but then we can also give out the second kind of gift first and give out the rest of the first kind without any restrictions.
As you mentioned i think this may count some ways twice but i can't figure out how to remove those. Thanks for the insight.
Answer: Your reasoning for the problem where kids with no gifts are allowed is correct. To solve the main problem you need to apply the PIE to exclude cases where one or more kids get no gift. You will obtain:
$$
\sum_{i=0}^{k} (-1)^i\binom ki\binom{n+k-1-i}{n}\binom{m+k-1-i}{m}.
$$
Comment: Thank you for answering , but can you explain it just a bit why this works. You are first counting the number of ways that there can be kids with no gifts, then you take away the number of ways n-1 and m-1 gifts can be distributed but this takes away too much so you add the ways that n-2 and m-2 can be distributed and so on? Also does the $\binom{k}{i}$ take away and/or add the repeated counting of gifts that are given to a kid? If you could explain it a bit it would be greatly appreciated.
Comment: @Neti. In general it is very similar to what you wrote. First we are counting  the number of ways that there can be kids with no gifts, then we choose a kid with no gift and take away the number of ways $n$ and $m$ gifts can be distributed between the rest $k-1$ kids. But this takes away too much so we choose a pair of kids with no gift and add the ways that $n$ and $m$ gifts can be can be distributed between the rest $k-2$ kids and so on.
Comment: Thank you very much!


Laplace Transformation of Negative exponent Real Numbers like $t^\frac{-3}{2}$

Question: How would we apply LT for functions that has exponents as negative real numbers.
I am not sure how the highlighted portion in below solution is arrived at.
Answer: $\int_0^\infty t^{a-1} e^{-st}dt$ diverges whenever $\Re(a) \le 0$. So you need to regularize it for making sense to $\mathcal{L}\{t^{-3/2}\}$, for example : $$F_a(s) = \int_0^\infty t^{a-1} (e^{-st}-e^{-t})dt$$ One can show that (change of variable $x = st$) $$F_a(s) = \int_0^\infty (x/s)^{a-1} e^{-x}\frac{dx}{s}-\int_0^\infty t^{a-1}e^{-t}dt=(s^{-a} -1)\Gamma(a)$$  for $\Re(a) > 0, s > 0$ and by analytic continuation this stays true for $\Re(a) > -1, \Re(s) > 0$.


Jsoup: String element.attr() doesn't work in if()

Question: I'm not experienced in Java, and I have a problem.
Using Jsoup, I have an element called td. If I do:
String attr = td.attr("class");
System.out.println(attr);

The output is "free", which is perfectly alright. If I do:
String attr = td.attr("class");
if (attr == "free") {
System.out.println("freedom!");
}

There is no output!
Does anyone know how to solve this problem?
Thanks in advance.
Comment: @Rohit Jain Yes, you are right. Because I am new to Java, I didn't see this, because I thought it was a problem with Jsoup specifically. Now I see the answer I understand that my thoughts were completely wrong.
Answer: You have to compare the string using the equals method as == compare references, not strings contents.
String attr = td.attr("class");
if (attr.equals("free")) {
    System.out.println("freedom!");
}

Comment: Thank you, that worked! When I see it like this, it's logical, but I'm not experienced in Java.


Can I narrow my search range in seeking solutions for equations?

Question: I got help here with a formula to find Pythagorean triples given only area. Using Euclid's formula,  $Area = D=m^3 n-mn^3\quad$ the final equations are:
$$n_0=2\sqrt{\frac{m^2}{3}}\cos\biggl({\biggl(\frac{1}{3}\biggr)\arccos{\biggl(-\frac{3\sqrt{3}D}{2m^4}\biggr)}\biggr)}$$
$$n_1=2\sqrt{\frac{m^2}{3}}\cos\biggl({\biggl(\frac{1}{3}\biggr)\arccos{\biggl(\frac{3\sqrt{3}D}{2m^4}\biggr)}\biggr)}$$
$$n_2=n_1-n_0$$
where $$\lfloor\sqrt[4]{D}\rfloor\le m\le \lceil\sqrt[3]{D}\space \rceil$$
Given an area $D$, any value of $m$ that yields an integer for one-or-more of $n_0, n_1, n_2$ provides the $m,n$ values that identify a triple that has area $D$. The limits I show are heuristic; I found them by experimentation in a spreadsheet. I would like to justify them with something more than, "they work", but I can't and I would also like to do better if possible.
Are there logical reasons for my limits? and Is there a way to narrow the search or is this as good as it gets?
Comment: It would help to know what $D$ and $m$ etc actually are in relation to which cubic equation. At the moment this appears to me to be no more than a mysterious list at which I must guess at the interpretation to make any sense of the question.
Comment: Yes, use the formula for the solution of cubic equations.
Comment: Please make the question self-contained.
Comment: I'm confused. The  $n_0$ formula is for a solution of the equation $$mx^3 - m^3x - D = 0$$ but the $n_1$ formula is for a root of $$mx^3 - m^3x + D = 0$$ and taking their difference means $n_2$ wouldn't be a root of either one. Is this what you intended? I note that for all but the very last example you gave, $m$ divides $D$.
Comment: @Paul Sinclair The formula works well, e.g. for $D=68640, m=26,\quad $ $n_0=23.76819745\quad n_1=27.76819745\quad n_2=4. $ The combinations of $D,m$ that yield integers for one or more of $n_x$ are the ones sought.
Answer: The value $m$ needed to create a triple with a given area magnitude is higher when
$m^3(1)-m(1)^3-D=0\quad$ than when $\quad m^3 (m - 1) - m (m - 1)^3 - D = 0$
but it is smallest when $n\approx\frac{m}{2}.\quad $ The limits found by solving with $(m,m/2)$ and then with $(m,1)$ are
$$\bigg\lfloor\sqrt[4]{\frac{8P}{3}}\bigg\rfloor\le m \le \frac{\sqrt[3]{\sqrt{3} \sqrt{27 D^2 - 4} + 9 D}}{\sqrt[3]{2} \sqrt[3]{3^2}} + \frac{\sqrt[3]{\frac{2}{3}}}{\sqrt[3]{\sqrt{3} \sqrt{27 D^2 - 4} + 9 D}}$$
and the search can be limited,  as indicated by one of the other posters, by using only the factors of $D$ within this range.
Answer: So you are indeed trying to find integer solutions to the equation
$$mn^3 - m^3n = D$$
It looks like you've flipped the sign of $n_1$, presumably because the associated root is always negative (if $m$ and $D$ are both positive, this equation will always have exactly one negative root, with the other two roots either positive or complex conjugates). Since you are only interested in positive roots, it does not matter whether $n_1$ is integer or not. The actual root $-n_1$ is negative. Thus you are actually only interested in $n_0$ and $n_2$.
For your purposes, there is a better expression for $n_2$. First, to simplify the notation, define $$A := \frac {2m}{\sqrt 3}$$ and $$\theta := \frac 13\arccos\left(-\frac {3\sqrt 3 D}{2m^4}\right)$$
then
$$n_0 = A\cos (\theta)\\n_2 = A\cos\left(\theta - \frac{2\pi}3\right)$$
This way, you only have to take the arccosine of one value.
That is fairly minor. I think the biggest help for you comes from the observation that $m$ divides $D$, since $m(n^3 - m^2n) = D$. So while you have a wide range for $m$, most of the values can be quickly eliminated.
This points out that your final entry above is incorrect: $48$ does not divide $1878120$, so it cannot be a valid value of $m$.
Comment: My solution(s) works very well. I am only interested in narrowing the search for values of $m$. BTW, for $f(1878120,48), n_2=21$.
Comment: $48\cdot 21^3 - 48^3\cdot 21 = -1877904$. How is that a solution for $D = 1878120$? And what is your complaint about the means of signficantly narrowing down the values of $m$ to be searched that I described?
Comment: You got the original equation signs reversed. It is $m^3n-mn^3=D$. I made no complaint about a solution to narrow the search. I did not see one offered until I read your answer with this focus. Now I see what you are trying to say but your answer appears to include $\frac{D}{m}$ and I don't have $m$ until after the search. It took me about $3$ years to find my solutions for a paper I've been working on for $10$ years; they have $3$ real roots whenever $m\ge x$ where $x$ is the lowest integer that yields an integer $n$. I'm happy with them.
Comment: You did give me food for thought. It is true that $m|D$. There are $86$ values of $m$ where

$lo=\lceil\sqrt[4]{1878120} \rceil=38\le m \le\lceil\sqrt[3]{1878120} \rceil=123=hi$

but only $12$ factors $x$ of $1878120$ where $38\le x\le 123$. If you edit your answer to reflect that, it will be worth points to you. Thanks
Comment: Sometimes there is more than one answer for a given area using the same $m$. For example $D=71831760\land m=169$  yields $3$ answers. $$n_0=161((2640,54418,54482), n_1=176((2415,59488,59537), n_2=15((28336,5070,28786)$$. My function just work.


Drupal views get fields after filters without html markup

Question: I have a question about Drupal 7 and Views. Let's assume that I have views where I extract 2 articles ordered by post date. I want to extract only title and trimmed introduction (trim configured in field settings in view)
Now I would like to extract this data programmatically without HTML markup. So the result will be similar to this:
array(
    0 => array(
        'title' => 'Lorem ipsum',
        'introduction' => 'Lorem ipsum dolar solor...'
    ),
    1 => array(
        'title' => 'Lorem ipsum2',
        'introduction' => 'Lorem ipsum2 dolar solor...'
    )
)

Is it possible to extract such information from views?
I tried to do something like this:
$view = views_get_view('view_name');
$view->set_display('display_id');
$view->execute();
$data = $view->result;

But $data contain two elements with full nodes (all additional fields that I don't want to grab from database)
In addition for instance introduction is grabbed fully (must be trimmed somewhere in PHP).
Is it possible to do something like this:
$view->applyFilters(); //Like trim etc
$data = $view->getResults(); //return title + trimmed introduction but without HTML markup

Do You have any tips how to solve this problem? Is it possible for instance to pass template that will be rendered (where I could display only raw result without any HTML tags) or something?
Any help would be appreciated:)
Comment: what do you indent to do with this result?
Comment: Anything, for instance return it via ajax as JSON
Comment: Have you tried using strip html and trim on the views page when adding the fields?
Comment: Could You explain it a little more? Or maybe I don't clear it up enough. When views is rendered normally for instance `$view->preview()` it will generate something like this: `Lorem ipsum...`

I don't want the outer html i just want Lorem ipsum...
Comment: I don't get it - is there HTML in your fields, in their data in database, and you want to strip it, or something adds HTML formatting and you want to disable it?
Comment: @Mołot Second thing - disable formatting around record. `<div class="views-field..` is added while rendering. It's not saved in database. I want to strip this tags on every field
Comment: Have you looked into writing a views style plugin? That might be the cleanest way to solve your issue. https://api.drupal.org/api/views/plugins!views_plugin_style.inc/group/views_style_plugins/7
Comment: @AlfredArmstrong thanks a lot! Your tip with views style plugin was very good. after `$view->execute()` execute `$data = $view->style_plugin->render_fields($view->result);` and under `$data` I have array of filtered results without HTML code:)
Answer: After suggestion from AlfredArmstrong I checked plugin style docs.
To get filtered data without rendering html template simply do:
 $data = $view->style_plugin->render_fields($view->result);

Under $data will be array of filtered fields from view.
Comment: I feel like I've been searching all my life for this answer. THANK YOU!
Answer: In your fields settings, open "Style settings:

Customize HTMLs, setting them both to -None- .
If that's not enough, Look at the right column. Section Other. Click on Theme information and provide custom tpl.php file for your field.
Comment: That's nice, it's actually give results without extra html markup. But is it possible to do it programmaticaly like in the code in my question? To get array of data instead of rendered view?
Comment: @Astaz3l If you only want a query result, why don't you query directly? You can easily "steal" query from views.
Comment: True, I can get the query directly but for instance it won't return trimmed content - it's done in PHP, not it MySQL query.
Comment: @Astaz3l have you tried to (ab)use [views_get_views_as_options](https://api.drupal.org/api/views/views.module/function/views_get_views_as_options/7)?


NodeJS copy directories and contents that don't exist already

Question: I need a function in NodeJS (or an existent one, although I did't find one) that copies a folder to a diferent location but only copies the non existing files in the destination:
Folder to Copy:
-- Folder1
---- Folder1_1
------- File1_1_1
---- Folder1_2
------- File1_2_1

Destination Path has:
-- Folder1
---- Folder1_1
------- File1_1_1

So this method should only copy Folder1.2 and it's contents (File1.2.1) since all the other files are present already.
Does anyone have any idea on how to do this or if there is a module that has a method that does this?
Answer: simply use ncp and set the property options.clobber to false, then it wont replace any files already existing.
Comment: thank you! i searched that module but didn't notice that option... i'm a nodeJS newbie :p
Comment: sure no problem, im happy i was of help :)


How to get function names from profile addresses?

Question: I am putting together a performance profiler in Linux and I am having trouble mapping the collected stack trace information to function names.
I am currently calling addr2line as follows from my post processing code
<code>  FILE* pipe = popen("addr2line -f -i -s -C -e <libname> <address>", "r");
  if (!pipe) return;

  const size_t BUFFER_SIZE = 8192;
  char buffer[BUFFER_SIZE];
  string result;
  while (!feof(pipe))
  {
    if (fgets(buffer, BUFFER_SIZE, pipe) != NULL)
    result += buffer;
  }

  pclose(pipe);
</code>
However, this is terribly slow as my profile has a lot of samples. Is there any other utility like addr2line that is faster or can I call addr2line in a more efficient way than I am doing?
Answer: I got past this problem by modifying the source code of the addr2line utility and converted it into a library. So I am now loading this library into my profile analyzer and calling 'addr2line' as if it were a function!
Comment: Nice idea. Mind sharing the code or instructions? Would be very helpful to me and maybe others.


IE8 is detecting the pages as mobile media

Question: I am trying to workout why http://www.tradecarsspain.com/ is loading as a mobile page when viewed in IE8 ...
Comment: Which module are you using for detecting mobile device? Or the logic?
Comment: This question appears to be off-topic because it is a bugreport for IE 8 or for module that is used to detect mobile browsers. Please report to appropriate issue queue instead.
Answer: As you haven't provided any information this is a complete guess, based on the assumption that you're using the Omega 3 theme with respond.js.
There's a known issue with IE8, respond.js and CSS aggregation. To fix it, you can implement hook_css_alter() in your theme like so:
function MYTHEME_css_alter(&$css) {
  // Enable respond.js to work with Omega.
  foreach ($css as $key => $value) {
    if (preg_match('/^ie::(\S*)/', $key)) {
      unset($css[$key]);
    }
    else {
      $css[$key]['browsers']['IE'] = TRUE;
    }
  }
}