Bigcommerce Product SKU's -> Options

Question: Having a little trouble with the Bigcommerce API when trying to access Product SKU's 'Options' array_object.
I can access everything else within the SKU object, just not the Options - doing a print_r on the $sku->options doesn't show any returned data and var_dump shows '(bool)false'. Here is my code:
$filter = array('sku' => '940801DB');
$skus = Bigcommerce::getSkus($filter);

foreach ( $skus as $sku ){
    echo '
';
    print_r( $sku->options );
    echo '
';
}

Any ideas how to access this array/object?
Further info:
If I print_r($sku) I get:
Array
(
    [0] => Bigcommerce\Api\Resources\Sku Object
    (
        [ignoreOnCreate:protected] => Array
            (
                [0] => product_id
            )

        [ignoreOnUpdate:protected] => Array
            (
                [0] => id
                [1] => product_id
            )

        [fields:protected] => stdClass Object
            (
                [id] => 1
                [product_id] => 225
                [sku] => 940801DB
                [cost_price] => 0.0000
                [upc] =>
                [inventory_level] => 0
                [inventory_warning_level] => 0
                [bin_picking_number] =>
                [options] => Array
                    (
                        [0] => stdClass Object
                            (
                                [product_option_id] => 1
                                [option_value_id] => 834
                            )

                        [1] => stdClass Object
                            (
                                [product_option_id] => 2
                                [option_value_id] => 829
                            )

                        [2] => stdClass Object
                            (
                                [product_option_id] => 3
                                [option_value_id] => 827
                            )

                    )

            )

        [id:protected] => 1
        [ignoreIfZero:protected] => Array
            (
            )

        [fieldMap:protected] => Array
            (
            )

    )
)

Comment: you solved the issue?
Comment: No, still unsolved...
Answer: Not sure why you are not able to access that variable. It seems more like an issue with PHP than Bigcommerce.
Still, a workaround would be to get the options data yourself.
Just send a GET request to the following endpoint:
/products/{{product_id}}/options.json

Answer: This seems like a bug of Bigcommerce API. I installed it using composer, if you take a look at the source code of Bigcommerce API, inside vendor/bigcommerce/api/src/Bigcommerce/Api/Resources/Sku.php:
public function options()
{
    $options = Client::getCollection($this->fields->options->resource, 'SkuOption');

    foreach ($options as $option) {
        $option->product_id = $this->product_id;
    }

    return $options;
}

See that it gets $this->fields->options->resource, but the options array doesn't have resource in it. In products it's like this:
"options": {
    "url": "https://store-et7xe3pz.mybigcommerce.com/api/v2/products/32/options.json",
    "resource": "/products/32/options"
  },

but in sku it's this:
"options": [
      {
        "product_option_id": 15,
        "option_value_id": 18
      },
      {
        "product_option_id": 16,
        "option_value_id": 26
      }
    ]

seems like a bug to me.
Answer: options is below fields
Try
print_r($sku->fields->options);

Bigcommerce Product SKU's -> Options


Write a number as different differences of powers

Question: Is there a positive integer $n$ that can be written as $a_i-b_i$ for $i=2,3,4,5$, where $a_i,b_i$ are positive perfect $i$th powers, and no two among $a_i$ or $b_i$ are the same?
This might be related to the question here which asks when a number is a difference of two $k$th powers. For squares, we know this is the case iff a number is not $2\pmod 4$.
Comment: Can $a^i$, $b^i$ be negative (e.g. $(-1)^3$)?
Comment: No, they should be positive
Answer: Yes. And there are infinite of them.

Since $a^2 - b^2 = (a-b)(a+b)$, we can easily find $a_2,b_2$ by factoring the difference and solving a linear equation. So the real problem would be finding $g^5-h^5=e^4-f^4=c^3-d^3$.
Through brute-forcing $g^5-h^5=e^4-f^4$, we could find several candidates, first of which is
$$ 275^4 - 66^4 = 97^5 - 78^5 = 11^4 \cdot 19 \cdot 31 \cdot 661 \tag1 $$
(I think this is solvable without brute force but I don't bother to check :p )

We now try to solve $c^3 - d^3 = pq$. We factor the LHS into $(c-d)(c^2+cd+d^2)=pq$, then we have
$$\left\{\begin{aligned}
c-d &= p\\
c^2 + cd + d^2 &= q
\end{aligned}\right. \implies c,d = \frac{\sqrt{3(4q-p^2)}\pm3p}{6}$$
In order for $c,d\in\mathbb Q$, we need $3(4q-p^2)$ to be a perfect square. Here we pick $p, q$ such that $pq\mid n$ for reasons explained in the next section. Using the factors in (1), we will use:
$$ 20^3 - 9^3 = 11 \cdot 661 \tag2 $$

OK so now we have got 3 equations,
\begin{align}
20^3 - 9^3 &= 11\cdot 661 \tag3 \\
275^4 - 66^4 &= (11\cdot 661) \cdot (11^3 \cdot 19\cdot 31) \tag4 \\
97^5 - 78^5 &= (11\cdot 661) \cdot (11^3 \cdot 19\cdot 31) \tag5
\end{align}
Now notice that we can multiply both sides of (4), (5) by $r^{20}$ for any $r$ without changing the "shape". This is why we pick $pq\mid n$ before. We choose $r = 19\cdot 31$ so that the factor becomes a perfect cube:
\begin{align}
(11^3 \cdot 19^{21}\cdot 31^{21})\cdot(20^3 - 9^3) &= (11\cdot 661) \cdot (11^3 \cdot 19^{21}\cdot 31^{21}) \tag6 \\
(275r^5)^4 - (66r^5)^4 &= (11\cdot 661) \cdot (11^3 \cdot 19^{21}\cdot 31^{21}) \tag7 \\
(97r^4)^5 - (78r^4)^5 &= (11\cdot 661) \cdot (11^3 \cdot 19^{21}\cdot 31^{21}) \tag8
\end{align}

Finally we just need to find $a^2 - b^2 = (11\cdot 661) \cdot (11^3 \cdot 19^{21}\cdot 31^{21})$, which is pretty trivial (just make sure you don't pick perfect square $a,b$ which coincide with the quartic solutions).
\begin{align}
& 143943941566433550753732821282296405837497469123172655460549556689 \\
&= 11^4 \cdot 19^{21} \cdot 31^{21} \cdot 661 \\
&= 6235538756477338734239125439443855^2 - 6223985832403904367008453242140156^2 \\
&= \left( 20 \cdot 11\cdot19^7\cdot31^7 \right)^3 - \left( 9 \cdot 11\cdot19^7\cdot31^7 \right)^3 \\
&= \left( 275 \cdot 19^5 \cdot 31^5 \right)^4 - \left( 66 \cdot 19^5 \cdot 31^5 \right)^4 \\
&= \left( 97 \cdot 19^4 \cdot 31^4 \right)^5 - \left( 78 \cdot 19^4 \cdot 31^4 \right)^5
\end{align}
You could check that all 8 numbers are also different. (Note that, now we have got this solution, every $nk^{60}$ for every $k$ will also be a solution, not to mention there are many other base solutions.)


If $V^{\mu}$ is a killing vector, then is $∇_μ V^{\mu} = 0$?

Question: Working with the Levi-Civita Connection and a symmetric metric I want to show that if $V^{\mu}$ is a killing vector, then $∇_μ V^{\mu} = 0$.
I am not sure how to show this fact, but I believe it to be true. I proceeded as follows:
$$∇_μ V^{\mu} = g^{\lambda\mu}∇_μ V_{\lambda} = -g^{\lambda\mu}∇_{\lambda} V_{\mu}$$ Then I got stuck. It it not obvious to me how to proceed.
Comment: Well, since the metric is symmetric, you indeed proved that $f=g^{\lambda\mu}\nabla_\lambda V_\mu$ satisfies $f=-f$, so ... $f=$?
Answer: Hint: The defining property of the Killing vector is
$$\nabla_iV_j+\nabla_jV_i=0$$
A contraction by $g^{ij}$ will lead to your result as $2\nabla_iV^i=0$.


Clearing canvas has a delay

Question: Below is the code for a simple app that draws a rectangle on a canvas in a window and then takes a screen shot of the app using the CopyFromScreen function when any key is pressed. Just before this is called however, I call canvas.Children.Clear(). I would then expect the resultant image to not have the rectangle in it, but it does. It seems that the actual rectangle image isn't removed from the canvas when the function is called but some time after.
I tried putting in a System.Threading.Thread.Sleep(1000); after the Clear() call but the rectangle stays on screen for that full second as well. Clearly it's getting removed after the key press function finishes, is there any way to remove it before the CopyFromScreen call?
To run this you will need to add a reference to System.Drawing.
XAML code
<Window x:Class="CanvasTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Width="210" Height="240"
        KeyDown="keyPressed">
    <Window.Background>
        <SolidColorBrush Color="White"/>
    </Window.Background>
    <Grid>
        <Canvas Name="canvas"
            HorizontalAlignment="Left" VerticalAlignment="Top">
        </Canvas>
    </Grid>
</Window>

.cs code
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Shapes;

namespace CanvasTest {
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();

            Left = 0;
            Top = 0;

            Rectangle rect = new Rectangle {
                Stroke = System.Windows.Media.Brushes.Black,
                StrokeThickness = 1,
                Width = 100,
                Height = 100
            };

            canvas.Children.Add(rect);
            Canvas.SetLeft(rect, 50);
            Canvas.SetTop(rect, 50);
        }

        private void keyPressed(object sender, System.Windows.Input.KeyEventArgs e) {
            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap((int)Width, (int)Height);

            System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap);

            canvas.Children.Clear();
            graphics.CopyFromScreen(0, 0, 0, 0,
                                    new System.Drawing.Size(bitmap.Width, bitmap.Height),
                                    System.Drawing.CopyPixelOperation.SourceCopy);

            String path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            path += "\\MuckleEwesPic.png";

            bitmap.Save(path, System.Drawing.Imaging.ImageFormat.Png);
        }
    }
}

How can I clear the canvas and then take a screen shot without this behaviour happening? And no 'don't add the rect' isn't a solution ha, this is just a minimal example of a larger app in which the problem is occurring.
Thanks.
Comment: Please remove all references to `System.Drawing` from your application immediately. WPF does not need, nor care about that.
Comment: You need a layout and render pass to have occurred...see: http://social.msdn.microsoft.com/Forums/vstudio/en-US/693fbedb-efa6-413e-ab66-530c6961d3fb/how-to-wait-for-the-wpf-render-thread-to-catch-up
Comment: Use animation and you can get animation completed event
Answer: Using something like in ColinSmith's link:
static void WaitForRenderPass()
{
  Application.Current.Dispatcher
    .BeginInvoke( DispatcherPriority.ApplicationIdle, new Action( () => {} ) )
    .Wait();
}

sort of works for waiting on a render pass but the problem is it's not possible (afaik) to tell if that render pass contains everything you want.
In practice depending on system load/video card drivers/... it has to be called multiple times. I've had one machine where it had to be called in a loop up to 3 times, and each of those calls took about 2 frames @60Hz to complete. Only then a call to the above would return immediately indicating the render thread is really idle, which likely means all changes you want have been rendered, which in turn means screen captures contain everything they should have. So we ended up using
for( int i = 0 ; i < 5 ; ++i )
{
  WaitForRenderPass();
  Thread.Sleep( 10 );
}

It's ugly and it's a hack but it hasn't failed (yet).
Regarding HighCore's comment: you can capture the screen with Wpf-only classes as well, however:

it has the same problem the OP started this questiomn for in the first place so it won't immediately solve anything (except from not using System.Drawing)
you won't be able to get a main window's chrome in the capture
it's markedly slower than CopyScreen
it does not render the exact same pixels as rendered to the screen

Clearing canvas has a delay


Example of an infinite dimensional Hilbert space that is not an RKHS

Question: I have been studying Reproducing Kernel Hilbert Spaces (RKHS). The definition I am using is as follows: An RKHS is a Hilbert space $\mathcal{H}$ of real-valued functions on a set $X$ such that for all $x \in X$, the evaluation functional $E_x : \mathcal{H} \to \mathbb{R}$ defined by $E_x(f) = f(x)$ is continuous. (Recall that continuity in this context means $\sup_{\|f\|\leq 1}|f(x)| < \infty$ for all $x$.)
As one of the first steps in my study I want to see some positive and negative examples of these spaces. So I want to find a non-trivial (meaning infinite dimensional) space of functions which is a Hilbert space but not an RKHS, meaning the evaluation functionals are not continuous.
The problem is that in all the references I find, the only example they give is the space of functions $L_{2}$. However, this example is trivial since $L_2$ fails for the simple reason that it is not a space of functions, rather it contains equivalence classes of functions.
Can someone please help me find an infinite dimensional Hilbert space of functions that is not an RKHS?
Comment: $\mathcal{L}_2$ is a space of functions (it's the space of all square integrable functions, which you turn it into $L_2$ by considering equivalence classes), the problem with my earlier comment is that it is not an inner product space (so not a Hilbert space).
Comment: Why not just consider $\mathcal{L}_2$, i.e. $L_2$ before taking equivalence classes? That is a hilbert space of functions.
Comment: @user27182 See both answers below. The problem is that $\mathcal{L}_2$ is not a space of functions; rather, elements of that space are equivalence classes of functions.
Answer: There are no explicit examples of this kind. Indeed, if one could show you such a space $\mathcal H$, then point evaluation $f\mapsto f(x_0)$  would give an explicit example of a discontinuous linear functional on a Hilbert space. And there can be no explicit examples of this kind, because it's consistent with ZF that they do not exist. Only with the Axiom of Choice can one give a (non-constructive) proof of their existence. This is discussed in many places, such as

Discontinuous linear functional
Unbounded linear operator defined on $l^2$

So, any time someone gives you a concrete Hilbert space of functions, you can be sure that it's either RKHS, or is not really a space of functions.
Comment: That's very interesting. So if I understand correctly, there can not be "constructive" example of a Hilbert space of functions and point $x_0$, such that the evaluation functional at that point is discontinuous?


Firebase dataRef.transaction() returns wrong snapshot

Question: I'd like to assign an incremental number to users while they click on #div1 or #div2. Multiple user from different devices can get their subsequent number without problem with the following codes:
$("#div1").click(function(event) {
    doBtn();
}

$("#div2").click(function(event) {
    doBtn();
}

function doBtn() {
    counterRef.transaction( function(currentData) {
      if (currentData === null) {
        return 1;
      } else {
        // increase the counterRef by 1
        return currentData + 1;
      }
    }, function(error, committed, snapshot) {
      if (error) {
      } else if (!committed) {
      } else {
        // upon counterRef updated successfully, add a child {user: "userId", counter: xxxx} to ListRef
        // (xxxx is the increased counter number)
        ListRef.push({
            user: "userId",
            counter: snapshot.val()
        });
      }
    } );
}

counterRef.on('value', function(snapshot) {
    console.log( "Current number is " + snapshot.val() );
}

ListRef.on('child_added', function(snapshot) {
    console.log( "Your number is " + snapshot.val().counter );
}

However, if the user click the same button (or clicking #div1 and #div2 alternatively) rapidly, they will get the following results:

Current number is 1
  Current number is 2
  Current number is 3
  Current number is 4
  Current number is 5
  Current number is 6
  Current number is 7
  Current number is 8
Your number is 1
  Your number is 3
  Your number is 3
  Your number is 4
  Your number is 5
  Your number is 6
  Your number is 8
  Your number is 8

It seems that the snapshot value in function(error, committed, snapshot) cannot get the concurrent value from counterRef while being increased.
Am I using the .transaction() wrong?
Please help.
Comment: Had a look at this today [and reproduced the behavior you've described](http://jsfiddle.net/katowulf/UHDt7/4/). Not sure if there's anything wrong there. Pinging the dev team for some insight.
Comment: This error only happens for rapid-trigger from the same machine. I've tried the same thing but with different devices, it seems will return results as expected (no counter number duplication).

My temporally solution is to disable the button before .transaction() and re-enable it after .push(). Too shame that I cannot do multiple actions while offline.
Answer: Unfortunately, based on @Kato's reproduction, I think this is expected behavior based on our current implementation.
Basically, if you do multiple transactions rapidly (or while you're offline), we'll end up batching them together and performing them as a single batch, and the final snapshot each one gets will be the final snapshot after all of them ran.
I understand this may not always be ideal.  We'll look into whether we could perhaps change this behavior in the future.


Bad password when logging in via Remote Desktop

Question: I have just setup a windows 2003 server running in hyper-V.
When I log in via Hyper-V it works fine.
When I try to login via remote desktop I get a bad user name or password error.
I have:

Disabled the firewall
Enabled remote connections

Before I did the above I did not get to the login screen. I can ping the ip address of the image.
I am trying to login as Administrator.
Anyone have an idea about how to fix this?
Edit
I have now managed to fix this by changing the password to something without special characters. Strange thing is the I could not see any problems with the passord, had tried typing it into the user name field to check it.
Comment: Are you attempting to login as the administrator user or another user? If its another user did you grant them the necessary rights?
Comment: @ErnieTheGeek, thanks for the comment I have updated the question
Comment: What sort of special characters were you using? Interesting that it sounds like some chars are getting badly encoded through remote desktop. Sounds like a bug in RD? Or could it be a regional settings issue that the chars are encoded using the local computer system's settings rather than the remote computer's settings (would this even matter)?
Comment: @Chris J, it was //, when I type these into the username field they looked OK
Answer: When logging into the Remote Desktop connection, please ensure the username field contains only the username (it may have the computername / domain pre-poppulated).
 Hope this helps.
Answer: Make sure that the user you're logging in with is a member of the group "Remote Desktop Users"
Administrators should already belong to this group, but other users may not.


Marginal model versus random-effects model – how to choose between them? An advice for a layman

Question: In searching for any info about marginal model and random-effects model, and how to choose between them, I have found some info but it was more-or-less mathematical abstract explanation (like for example here: https://stats.stackexchange.com/a/68753/38080). Somewhere I have found that there were observed substantial differences between a parameter estimates between these two methods/models (http://www.biomedcentral.com/1471-2288/2/15/), however the opposite was wrote by Zuur et al. (2009, p. 116; http://link.springer.com/book/10.1007%2F978-0-387-87458-6). Marginal model (generalized estimating equation approach) brings population-averaged parameters, while outputs from random-effects model (generalized linear mixed model) take into account random effect – subject (Verbeke et al. 2010, pp. 49–52; http://link.springer.com/chapter/10.1007/0-387-28980-1_16).
I would like to see some layman-like explanation of these models illustrated on some model (real-life) examples in language familiar to non-statistician and non-mathematician.
In detail, I would like to know:
When should be used marginal model and when should be used random-effects model?
For which scientific questions are these models suitable?
How should be outputs from these models interpreted?
Answer: Thank you for linking my answer! I will try to give an explicit explanation. This question has been discussed many times at this site (see the related questions on the right side), but it is really confusing and important for a "layman".
First of all, for linear models (continuous response), the estimates of marginal and conditional (random-effects) models coincide. So I will focus on nonlinear models, especially logistic regression for binary data.
Scientific questions
The mostly used example to distinguish marginal and conditional models is:

If you are a doctor and you want an estimate of how much a statin
  drug will lower your patient's odds of getting a heart attack, the
  subject-specific coefficient is the clear choice. On the other hand,
  if you are a state health official and you want to know how the number
  of people who die of heart attacks would change if everyone in the
  at-risk population took the stain drug, you would probably want to use
  the population–averaged coefficients. (Allison, 2009)

The two kinds of scientific questions correspond to these two models.
Illustration
The best illustration I have seen so far is the following figure in Applied Longitudinal Analysis (Fitzmaurice, Laird and Ware, 2011, Page 479), if we change the covariate from "statin drug" to "time". It is clear that the two models differ in the scale of coefficients, which can be essentially explained by the fact that the mean of a nonlinear function of a random variable does not equal the nonlinear function of the mean.

Interpretation
In the above figure, the dotted lines are from a random intercept model. It shows that we need to control the random effects constant when interpreting the fixed effects, i.e. only go along a line when interpreting the slope. This is why we call the estimates from random effects models "subject specific". Specifically,

For conditional models, the interpretation is that, how would the log odds change with one unit change of time for a given subject? (See Page 403 of Fitzmaurice, Laird and Ware (2011) about the discussion about why the interpretation of time-invariant covariates in conditional models is potentially misleading.)
For marginal models, the interpretation is exactly the same as the interpretation of linear regressions, i.e., how would the log odds change with one unit change of time, or the log odds ratio of drug vs. placebo.

There is another example on this site.
Comment: Yes, the estimates for the fixed effects in random-effects model and the estimates for the mean model in marginal models coincide, regardless of the random effects structure.
Comment: Was just wondering if anybody would perhaps happen to have a worked example of both modelling approaches in R? Maybe for this specific example, as it seems quite didactical?
Comment: Thank you very much for nice answer! I have yet one question: you have wrote that the estimates of marginal and random-effects models coincide for linear models - does this hold also for random-effects model with random intercepts and slopes, if there are differences in the random slopes?


A funny question: Taylor polynomials and series associated with the Lost numbers $4, 8, 15, 16, 23, 42$

Question: The interpolation polynomial for the "Lost" numbers $4, 8, 15, 16, 23, 42$ is
$$
P(x)=60-\frac{612}{5}x+\frac{367}{4}x^{2}-\frac{235}{8}x^{3}+\frac{17}{4}x^{4}-\frac{9}{40}x^{5}.
$$
That is, $P(1)=4$, $P(2)=8$, $P(3)=15$, $P(4)=16$, $P(5)=23$, $P(6)=42$.
I would like to find the most "simple" analytic function $f(x)$ (that is not polynomial and does not contain "large" coefficients, "large" integer numbers or fractions with "large" numerators or denominators) such that $P(x)$ is the Taylor polynomial for $f(x)$ at zero (the Maclaurin polynomial). In other words, the Taylor series for $f(x)$ is
$$
60-\frac{612}{5}x+\frac{367}{4}x^{2}-\frac{235}{8}x^{3}+\frac{17}{4}x^{4}-\frac{9}{40}x^{5}+\ldots.
$$
As I see, the series of coefficients is alternating, and
$$
\frac{612}{5}>\frac{367}{4}>\frac{235}{8}>\frac{17}{4}>\frac{9}{40}.
$$
How to search such a function $f(x)$?
Comment: Since the simplest way to extend the Taylor series is with zero cefficients, but this gives a polynomial, your problem seems to be ill-posed. If you want the domain of analycity to include the points of interpolation, it is inevitable that the denominators of nonzero coefficients will grow.
Answer: i think that the most "simple" function f(n) (that is not polynomial and does not contain "large" coefficients, "large" integer numbers or fractions with "large" numerators or denominators) is this:
$ f(n) = 4n+1-(15[\frac{n}{6}]+3)[\frac{1}{v(4n)}] $
$v(n) \ $ gives the numer of distinct primes in $  n $
$[n] $ is the $floor$ function.
but the series expansion at $ n=0 $ is:
$ \ \ \begin{cases}
12[\frac{1}{v(4n)}] +1  \ \ \ \  if \ \ n<0\\
1-3[\frac{1}{v(4n)}]  \ \ \ \ otherwise\\
\end{cases}$


Changing divs to ulist

Question: I haven't worked with ulist yes, and as I know it's very important and useful thing, at the moment i have 3 divs which looks like this:

Postage

Return

Payment

How could I transform them to ulist that they would look like this? Or maybe its not posible?
Comment: Please, paste your HTML and CSS separately!
Comment: there is divs codes with css inside (style=) in the post, Im not posible to edit css using .css sheets, because in this project I wont be able to edit things which is inside  tag.
Comment: Yes, but for the sake of the question here, it'd be much easier for us if readability of your code wasn't an issue.
Answer: Reset all styles from ul and float li s to the left:
html

Postage

Return

Payment

css
ul {height:30px;line-height:30px;list-style:none;margin:0;padding:0;}
ul li {float:left;display:block;height:30px;margin:0;padding:0 5px;color: #ffffff; font-size : 28px; border-top:1px dotted #015811; border-left:1px dotted #015811; border-right:1px dotted #015811;}
ul li.c1 {background:green;}
ul li.c2 {background:red;}
ul li.c3 {background:blue;}

Added sample with inline css: http://jsfiddle.net/JBXSz/
Answer: Use display:inline-block to get the li aligned horizontally.
HTML

Postage

Return

Payment

CSS
li{display:inline-block;
  clear: both;
  margin:0 auto;
  text-align: center; width:100px;
  background-color:#58794c; color: #ffffff;
  font-size : 28px;
  border-top:1px dotted #015811;
  border-left:1px dotted #015811;
  border-right:1px dotted #015811;}
ul li:nth-child(1){background-color:#58794c;  }
ul li:nth-child(2){background-color:#558b40; }
ul li:nth-child(3){background-color:#66ac4a;  }

DEMO
Comment: Note that if you set them to inline than paddings and heights won't work.
Comment: @easwee change it to inline-block in that case

Changing divs to ulist


problema de impressão com canvas html5

Question: Tenho um form que imprime formulários de consulta, formulários criados usando canvas, e podem impressos n-vezes cópias, cada uma com uma numeração que incrementa no formulário.
Ocorre que em determinado momento, a definição do formulário se torna extremamente degradada, não sendo possível ler corretamente o formulário.
Como resolver isso?
Comment: Poderia colocar o código fonte que gera isso e talvez uma imagem com o problema/defeito.
Comment: Seguem as imagens, o código se dá em duas etapas, uma com um controle 'for' e outro com o arquivo de canvas propriamente dito (esse é bem extenso)
Comment: Pode ser que esteja redimensionando e o conteúdo seja uma imagem não vetorial e portanto isto cause perda de qualidade.
Comment: Bom, se estivesse redimensionando creio que o problema se daria logo na primeira folha (são várias folhas de um mesmo formulário), mas não foi o caso. De qualquer forma, o pessoal responsável pela criação do arquivo tinha feito uma versão em svg e me passou esta versão, cujo uso se mostrou extremamente eficiente. Agradeço a atenção dispensada :-)
Answer: Para sua aplicação talvez seja melhor utilizar o SVG ao invés do canvas, pois costuma ter uma renderização melhor.
Comment: Estou vendo com o pessoal que me enviou o arquivo com canvas para enviar um exemplo em svg, espero que resolva. Obrigado pela dica!
Comment: Recebi os arquivos em svg e, depois das adaptações (inclusão de numero de formulário automático), estes se mostraram com melhor definição.

problema de impressão com canvas html5


TensorFlow: InternalError: Blas SGEMM launch failed

Question: When I run sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) I get InternalError: Blas SGEMM launch failed. Here is the full error and stack trace:
InternalErrorTraceback (most recent call last)
<ipython-input-9-a3261a02bdce> in <module>()
      1 batch_xs, batch_ys = mnist.train.next_batch(100)
----> 2 sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in run(self, fetches, feed_dict, options, run_metadata)
    338     try:
    339       result = self._run(None, fetches, feed_dict, options_ptr,
--> 340                          run_metadata_ptr)
    341       if run_metadata:
    342         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in _run(self, handle, fetches, feed_dict, options, run_metadata)
    562     try:
    563       results = self._do_run(handle, target_list, unique_fetches,
--> 564                              feed_dict_string, options, run_metadata)
    565     finally:
    566       # The movers are no longer used. Delete them.

/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
    635     if handle is None:
    636       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
--> 637                            target_list, options, run_metadata)
    638     else:
    639       return self._do_call(_prun_fn, self._session, handle, feed_dict,

/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in _do_call(self, fn, *args)
    657       # pylint: disable=protected-access
    658       raise errors._make_specific_exception(node_def, op, error_message,
--> 659                                             e.code)
    660       # pylint: enable=protected-access
    661

InternalError: Blas SGEMM launch failed : a.shape=(100, 784), b.shape=(784, 10), m=100, n=10, k=784
     [[Node: MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/gpu:0"](_recv_Placeholder_0/_4, Variable/read)]]
Caused by op u'MatMul', defined at:
  File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/__main__.py", line 3, in <module>
    app.launch_new_instance()
  File "/usr/local/lib/python2.7/dist-packages/traitlets/config/application.py", line 596, in launch_instance
    app.start()
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelapp.py", line 442, in start
    ioloop.IOLoop.instance().start()
  File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/ioloop.py", line 162, in start
    super(ZMQIOLoop, self).start()
  File "/usr/local/lib/python2.7/dist-packages/tornado/ioloop.py", line 883, in start
    handler_func(fd_obj, events)
  File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 276, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 228, in dispatch_shell
    handler(stream, idents, msg)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 391, in execute_request
    user_expressions, allow_stdin)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/ipkernel.py", line 199, in do_execute
    shell.run_cell(code, store_history=store_history, silent=silent)
  File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2723, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2825, in run_ast_nodes
    if self.run_code(code, result):
  File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2885, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-4-d7414c4b6213>", line 4, in <module>
    y = tf.nn.softmax(tf.matmul(x, W) + b)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/math_ops.py", line 1036, in matmul
    name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_math_ops.py", line 911, in _mat_mul
    transpose_b=transpose_b, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/op_def_library.py", line 655, in apply_op
    op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2154, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1154, in __init__
    self._traceback = _extract_stack()

Stack: EC2 g2.8xlarge machine, Ubuntu 14.04
Comment: I suspect it's a GPU memory issue. I ran `mnist_softmax.py` (taken from tensorflow page). On my PC with GTX950 (2Gb vram) I get this error. On my laptop with Quadro M2000M (4Gb vram) it runs fines. Both systems are using anaconda with python 3.5 and tensorflow 1.0
Answer: Old question, but may help others.
Try to close interactive sessions active in other processes (if IPython Notebook - just restart kernels). This helped me!
Additionally, I use this code to close local sessions in this kernel during experiments:
if 'session' in locals() and session is not None:
    print('Close interactive session')
    session.close()

Comment: Could you specify which library has to be imported to use "session"?
Answer: I encountered this problem and solved it by setting allow_soft_placement=True and gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.3), which specifically define the fraction of memory of GPU been used. I guess this has helped to avoid two tensorflow processes competing for the GPU memory.
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.3)
sess = tf.Session(config=tf.ConfigProto(
  allow_soft_placement=True, log_device_placement=True))

Answer: I got this error when running Tensorflow Distributed. Did you check if any of the workers were reporting CUDA_OUT_OF_MEMORY errors? If this is the case it may have to do with where you place your weight and bias variables. E.g.
with tf.device("/job:paramserver/task:0/cpu:0"):
   W = weight_variable([input_units, num_hidden_units])
   b = bias_variable([num_hidden_units])

Answer: My environment is Python 3.5, Tensorflow 0.12 and Windows 10 (no Docker). I am training neural networks in both CPU and GPU. I came across the same error InternalError: Blas SGEMM launch failed whenever training in the GPU.
I could not find the reason why this error happens but I managed to run my code in the GPU by avoiding the tensorflow function tensorflow.contrib.slim.one_hot_encoding(). Instead, I do the one-hot-encoding operation in numpy (input and output variables).
The following code reproduces the error and the fix. It is a minimal setup to learn the y = x ** 2 function using gradient descent.
import numpy as np
import tensorflow as tf
import tensorflow.contrib.slim as slim

def test_one_hot_encoding_using_tf():

    # This function raises the "InternalError: Blas SGEMM launch failed" when run in the GPU

    # Initialize
    tf.reset_default_graph()
    input_size = 10
    output_size = 100
    input_holder = tf.placeholder(shape=[1], dtype=tf.int32, name='input')
    output_holder = tf.placeholder(shape=[1], dtype=tf.int32, name='output')

    # Define network
    input_oh = slim.one_hot_encoding(input_holder, input_size)
    output_oh = slim.one_hot_encoding(output_holder, output_size)
    W1 = tf.Variable(tf.random_uniform([input_size, output_size], 0, 0.01))
    output_v = tf.matmul(input_oh, W1)
    output_v = tf.reshape(output_v, [-1])

    # Define updates
    loss = tf.reduce_sum(tf.square(output_oh - output_v))
    trainer = tf.train.GradientDescentOptimizer(learning_rate=0.1)
    update_model = trainer.minimize(loss)

    # Optimize
    init = tf.initialize_all_variables()
    steps = 1000

    # Force CPU/GPU
    config = tf.ConfigProto(
        # device_count={'GPU': 0}  # uncomment this line to force CPU
    )

    # Launch the tensorflow graph
    with tf.Session(config=config) as sess:
        sess.run(init)

        for step_i in range(steps):

            # Get sample
            x = np.random.randint(0, 10)
            y = np.power(x, 2).astype('int32')

            # Update
            _, l = sess.run([update_model, loss], feed_dict={input_holder: [x], output_holder: [y]})

        # Check model
        print('Final loss: %f' % l)

def test_one_hot_encoding_no_tf():

    # This function does not raise the "InternalError: Blas SGEMM launch failed" when run in the GPU

    def oh_encoding(label, num_classes):
        return np.identity(num_classes)[label:label + 1].astype('int32')

    # Initialize
    tf.reset_default_graph()
    input_size = 10
    output_size = 100
    input_holder = tf.placeholder(shape=[1, input_size], dtype=tf.float32, name='input')
    output_holder = tf.placeholder(shape=[1, output_size], dtype=tf.float32, name='output')

    # Define network
    W1 = tf.Variable(tf.random_uniform([input_size, output_size], 0, 0.01))
    output_v = tf.matmul(input_holder, W1)
    output_v = tf.reshape(output_v, [-1])

    # Define updates
    loss = tf.reduce_sum(tf.square(output_holder - output_v))
    trainer = tf.train.GradientDescentOptimizer(learning_rate=0.1)
    update_model = trainer.minimize(loss)

    # Optimize
    init = tf.initialize_all_variables()
    steps = 1000

    # Force CPU/GPU
    config = tf.ConfigProto(
        # device_count={'GPU': 0}  # uncomment this line to force CPU
    )

    # Launch the tensorflow graph
    with tf.Session(config=config) as sess:
        sess.run(init)

        for step_i in range(steps):

            # Get sample
            x = np.random.randint(0, 10)
            y = np.power(x, 2).astype('int32')

            # One hot encoding
            x = oh_encoding(x, 10)
            y = oh_encoding(y, 100)

            # Update
            _, l = sess.run([update_model, loss], feed_dict={input_holder: x, output_holder: y})

        # Check model
        print('Final loss: %f' % l)

Answer: maybe you not free your gpu rigthly , if you are using linux,try "ps -ef | grep python" to see what jobs are using GPU. then kill them
Answer: In my case,  I had 2 python consoles open, both using keras/tensorflow.
As I closed the old console (forgotten from previous day),
everything started to work correctly.
So it is good to check, if you do not have multiple consoles / processes occupying GPU.
Answer: I closed all other Jupyter Sessions running and this solved the problem. I think It was GPU memory issue.
Answer: For me, I got this problem when I tried to run multiple tensorflow processes (e.g. 2) and both of them require to access GPU resources.
A simple solution is to make sure there has to be only one tensorflow process running at a single time.
For more details, you can see here.

To be clear, tensorflow will try (by default) to consume all available
  GPUs. It cannot be run with other programs also active. Closing. Feel
  free to reopen if this is actually another problem.
Answer: In my case,
First, I run

conda clean --all

to clean up tarballs and unused packages.
Then, I restart IDE (Pycharm in this case) and it works well. Environment: anaconda python 3.6, windows 10 64bit. I install tensorflow-gpu by a command provided on the anaconda website.
Answer: 2.0 Compatible Answer: Providing 2.0 Code for erko's answer for the benefit of the Community.
session = tf.compat.v1.Session()

if 'session' in locals() and session is not None:
    print('Close interactive session')
    session.close()

Answer: In my case, the network filesystem under which libcublas.so was located simply died. The node was rebooted and everything was fine. Just to add another point to the dataset.
Answer: I encountered this error when running Keras CuDNN tests in parallel with pytest-xdist. The solution was to run them serially.
Answer: For me, I got this error when using Keras, and Tensorflow was the the backend. It was because the deep learning environment in Anaconda was not activated properly, as a result, Tensorflow didn't kick in properly either. I noticed this since the last time I activated my deep learning environment (which is called dl), the prompt changed in my Anaconda Prompt to this:
(dl) C:\Users\georg\Anaconda3\envs\dl\etc\conda\activate.d>set "KERAS_BACKEND=tensorflow"
While it only had the dl before then. Therefore, what I did to get rid of the above error was to close my jupyter notebook and Anaconda prompt, then relaunch, for several times.
Answer: I encountered this error after changing OS to Windows 10 recently, and I never encountered this before when using windows 7.
The error occurs if I load my GPU Tensorflow model when an another GPU program  is running; it's my JCuda model loaded as socket server, which is not large. If I close my other GPU program(s), this Tensorflow model can be loaded very successfully.
This JCuda program is not large at all, just around 70M, and in comparison this Tensorflow model is more than 500M and much larger. But I am using 1080 ti, which has much memory. So it would be probably not an out-of-memory progblem, and it would perhaps be some tricky internal issue of Tensorflow regarding OS or Cuda. (PS: I am using Cuda version 8.0.44 and haven't downloaded a newer version.)
Answer: Restarting my Jupyter processes wasn't enough; I had to reboot my computer.
Answer: In my case, it is enough to open the Jupyter Notebooks in separate servers.
This error only occurs with me if I try using more than one tensorflow/keras model in the same server. It doesn't matter if open one notebook, execute it, than close and try opening another. If they are being loaded in the same Jupyter server the error always happens.


SwiftUI: How do I transition gracefully when parent view changes?

Question: I have a view that starts setup like this.
var body: some View {
    switch appState.userFlow {
    case .onboarding:
        Text("Not Yet Implemented")
    case .login:
        LandingPageView()
    case .home:
        HomeScreenView()
    }
}

In each of those userFlow's I change the appState utilizing an @EnvironmentObject Whenever the object changes its state, the view blinks away and the new one is presented. This looks abrupt and ugly as it stands.
I attempted to do something along the lines of this. Which had no effect. What is the proper way to handle a transition when used in this context?
LandingPageView().transition(.opacity)

Answer: The .transition needs to be applied to the container of the views that you want to switch over, so you'll need to embed your switch inside a Group, VStack, or similar.
Also, you need to have either a .animation(.default) on the container, or change appState.userFlow inside a withAnimation {} block to actually animate the change.
enum UserFlow {
    case onboarding
    case login
    case home
}
struct ContentView: View {
    @State var userFlow = UserFlow.home
    var body: some View {

        /// container
        Group {

            switch userFlow {
            case .onboarding:
                Text("Not Yet Implemented")
            case .login:
                Text("Login page")
            case .home:
                Text("Home page")
            }

        }
        .animation(.default) /// also need Animation
        .transition(.opacity)

        /// for testing
        .onAppear {
            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                userFlow = .login
            }
        }
    }
}

Result:
Comment: Wow okay, that works really good. the `animation(...)` is required? It makes things look weird in other ways doing it that way. I tried setting it to `.none` but as expected, it didn't work.
Comment: doing it `withAnimation {}` worked better than the group option. Much better. It looks gorgeous now, and exactly as I expected. Thank you for the help!
Comment: @xTwisteDx what do you mean by makes things look weird? Maybe try doing `withAnimation { appState.userFlow = .login }` instead (sometimes explicit animations are less glitchy)


How to implement a multi-themed site?

Question: I will soon start building a new reasonably large site, that will be presented to the end-user as several different sites. Different domains will map to different sections within the site, and will also have different themes.
How should I implement the "multi-theme"?
I'll be posting some ideas of my own, which I would love some feedback on, but would also very much like to hear other suggestions.
Answer: I use the Themekey module.  This allows me to give each area a distinct look without even touching any code.  It also integrates with the Print, Revisioning, Organic Groups, and other major modules out-of-the-box.
Some of the things this module enables you to do (from the module page):

individually-styled channels
a front-page / "splash" screen
a date/time-selected Christmas theme
mobile themes for different auto-detected mobile devices
special themes for "limited" or "old" browsers
content, user, or role -specific themes
indicating your environment (production, staging, testing, sandbox, … )
testing your redesign safely on a live server
Answer: Implement several themes, possibly with a common base theme, and switch theme in code, such as suggested over here: How do I change a theme based on the URL?
Answer: Implement a single theme, with all the different themes inside it, and stick a class="name_of_sub_section" onto the body element.
Answer: I am not sure if it will fit your bill, but the Domain Access module may work for you.  With it, you can map different themes to different domains (the Domain Theme submodule) does this.  I haven't used it for theme switching, but I have use other features of the module with good success.
Another option is to use the Context module, possible with combination with Delta.  With this you can have different portions of your site mapped to different contexts, and then have various reactions associated with them.  I don't use this technique, but I have colleagues who do.

How to implement a multi-themed site?


culture for datetime in c#

Question: Hi all I have written a code to parse datetime as follows
if (DateTime.TryParse(dsVchRecord.Tables[0].Rows[0]["Date"].ToString(), out _dtVoucherDate))
    _dtVoucherDate = Convert.ToDateTime(dsVchRecord.Tables[0].Rows[0]["Date"].ToString());
else
    _dtVoucherDate = DateTime.ParseExact(dsVchRecord.Tables[0].Rows[0]["Date"].ToString(), "MM-dd-yyyy", CultureInfo.InvariantCulture);

Which works fine in my system as my current datetime format is MM/DD/YYYY , but in my colleague system the datetime format is different 15 June 2013 so my code fails there. How can I convert the date to a universal format irrespective of the system date or some other
Comment: If the type of the column in the `DataTable` is already `DateTime` don't convert it to `string` and then  back to `DateTime`. Instead use the strongly typed [`Field`](http://msdn.microsoft.com/en-us/library/system.data.datarow.field(v=vs.90).aspx) extension method: `dsVchRecord.Tables[0].Rows[0].Field("Date")`
Comment: Whatever you do, don't make the mistake of parsing the date in one format and then trying in a different format if the first one fails. That would be very bad because dates with day numbers 12 or less will become ambiguous wrt dd/mm/yyyy and mm/dd/yyyy formats.
Answer: It's not possible to handle all formats, but you can speicify multiple allowed formats for ParseExact:
var str = dsVchRecord.Tables[0].Rows[0].Field<String>("Date");
var allowedFormats = new[] { "MM-dd-yyyy", "dd MMM yyyy" };
_dtVoucherDate = DateTime.ParseExact(str, allowedFormats, CultureInfo.InvariantCulture, DateTimeStyles.None);

Note: If the type of the column in the DataTable is already DateTime don't convert it to string and then back to DateTime. Instead use the strongly typed Field extension method:
dsVchRecord.Tables[0].Rows[0].Field<DateTime>("Date")

Answer: Use DateTime.TryParseExact:
if (DateTime.TryParseExact(dsVchRecord.Tables[0].Rows[0]["Date"].ToString(),
    "MM/dd/yyyy", CultureInfo.InvariantCulture,
    DateTimeStyles.None, out _dtVoucherDate))
//the rest of it

Comment: This is not the format OP is using in his `ParseExact` approach.
Comment: @TimSchmelter Whoops, sorry. Fixed.
Answer: First parse Datetime with CultureInfo.InvariantCulture
DateTime dt = DateTime.Parse(dsVchRecord.Tables[0].Rows[0]["Date"].ToString(), CultureInfo.InvariantCulture)

then Get Current Culture
CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture;

then pass DateTime Object into current culture
dt = DateTime.Parse(dt.ToString(cultureInfo))

Comment: Do you mean parse first with the invariant culture, then if that fails try and parse it with the current culture?

culture for datetime in c#


Non-specific errors, no apparent cause

Question: I am a newbie, working through exercises in 'Database Driven Websites'.
The following PHP gives two errors that a couple of hours of pondering and searching have not cleared up.
When I call the page from a browser I get:

Parse error: syntax error, unexpected $end in /home/copydesign/www/listjokes.php on line 54

Line 54 is: "", which seems right to me.
In BBedit an error is indicated for line #51, which is a blank line. Line #50 is "?>" to indicate the end of PHP parsing. I hate to ask if I should be able to solve this for myself but if anyone can help me I'll be most appreciative.

Here is the entire page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>The CopyDesign Internet Joke Database</title>

<?php if (isset($_GET['addjoke'])): // Visitor wants to add a joke
?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Type a joke here:

<textarea name="joketext" rows="10" cols="40">
</textarea>

</form>

<?php else: // Display default page

// Open a MySQL connection

$dbcnx = @mysql_connect('solas.phpwebhosting.com', 'copydesign', 'keylock');

// Select the joke database
if (!@mysql_select_db('ijdb')) {
exit('
Unable to connect to the joke database at this time.
');
}

?>

CopyDesign's Internet Joke Database:

<?php

// Request the text of all the jokes
$result = @mysql_query('SELECT joketext FROM joke');
if (!result) {
exit('
Error performing query: ' .
mysql_error() . '
');
}

// Display the text of each joke in a paragraph
while ($row = mysql_fetch_array($result)) {
echo '
' . $row['joketext'] . '
';
}

?>

Comment: Can you indicate in your code where those lines are?
Answer: You forgot a:
<?php endif; ?>

You have a <? if(...): ?> but with no end in site.
Answer: Your if (isset($_GET['addjoke'])): is not closed with an endif. Close it.
Answer: Seems like you didn't close your <?php if: <?php else: statement. "Unexpected $end" is usually inclusive of a bracket mis-match or code block ending too soon (and parser can't determine the end of the block)
Answer: The error is very specific - it tells you that the interpreter got to the end of the script, when it expected to get to the end of an already opened block instead.
What I assume is that you are missing an endif

Non-specific errors, no apparent cause


Method reference to local class constructor

Question: There are several similar questions on SO about method reference to local class constructor, but I'd like to clarify slightly other thing. Consider following piece of code:
static Callable gen(int i) {
    class X {
        int x = i;
        public String toString() { return "" + x; }
    }
    return X::new;
}

...

System.out.println(gen(0).call());
System.out.println(gen(1).call());

Obviously this will printout
0
1

It turns out, that X class has constructor of the form ...$X(int) (you can find it via X.class.getDeclaredConstructors()).
But what is interesting here, is that returned lambdas (or method references) aren't simple reference to constructor ...$X(int) like, for example, Integer::new. They internally invoke this constructor ...$X(int) with predefined argument (0 or 1).
So, I'm not sure, but looks like this kind of method reference is not precisely described in JLS. And there is not other way except this case for local classes, to produce such kind of lambdas (with predefined constructor arguments). Who can help clarify this?
To be precise:

where is in JLS such kind of method reference described?
is any other way to create such method reference to arbitrary class constructor with predefined arguments?
Comment: "It is also clear, that X class has constructor of the form". Honestly, I don't find that particularly clear :)! Maybe you could edit in your question the generated bytecode with the constructor you are talking about.
Comment: That's because it is implicitly generated by the compiler, but you can find it in the bytecode.
Comment: Thats the invocation of the super constructor.
Comment: @Andremoniy did you look under JLS section [15.13](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.13)? I don't know if there is a direct explanation
Comment: Every constructor calls the super constructor of the super class (in your case `java.lang.Object`) either implicitly or explicitly (by using `super()` in the constructor body).
Comment: @Andremoniy you tell me "sorry? Of which super constructor?"
Comment: This is the comments after all
Comment: @Andremoniy In that case, you could say everything is clear once you look in the right place ;)
Comment: *It is also clear, that X class has constructor of the form ...$X(int)* - I see no such constructor. Actually, I see no constructor.
Comment: @Bohemian It actually is, look at `X.class.getDeclaredConstructors()`
Comment: @Clashsoft but I'm asking about where such kind of method reference actually described in JLS
Comment: @Clashsoft I just inspected the bytecode and didn't find an `int` arg constructor. I found only a no-args one: `invokespecial #2                  // Method java/lang/Object."":()V` (1.8.0_66-b18)
Comment: @Bohemian `Constructor[] declaredConstructors = X.class.getDeclaredConstructors();   System.out.println(declaredConstructors[0].getParameterTypes()[0]);` this will printout `int`
Comment: @Clashsoft sorry? Of which super constructor? This is static method
Comment: @Clashsoft Sure I did
Comment: @Clashsoft OK, and how this fact is related to constructor reference?
Comment: Got it. `0: aload_0
       1: iload_1
       2: putfield      #1                  // Field val$i:I` is the implied constructor accepting an int
Comment: @Bohemian Yeah! And could you please give me explanation to my questions?
Comment: @Clashsoft OK, just misunderstanding.
Comment: @Tunaki Well, I thought this is clear from investigating constructors of given class :)
Comment: @Tunaki OK, I will edit my question and will say: *Turns out, that...* :-)
Answer: This behaviour is defined in the JLS section §15.13.3:

If the form is ClassType :: [TypeArguments] new, the body of the invocation method has the effect of a class instance creation expression of the form new [TypeArguments] ClassType(A1, ..., An), where the arguments A1, ..., An are the formal parameters of the invocation method, and where:

The enclosing instance for the new object, if any, is derived from the site of the method reference expression, as specified in §15.9.2.
The constructor to invoke is the constructor that corresponds to the compile-time declaration of the method reference (§15.13.1).

Although this talks about enclosing instances, captured variables and parameters are not mentioned in §15.13.3.
As for your second question, you need to manually capture and change the parameter:
static Callable gen(int i) {
    final int i1 = someCondition() ? i : 42;
    class X {
        int x = i1; // <-
        public String toString() { return "" + x; }
    }
    return X::new;
}

Comment: Well, I thought this is about *are the formal parameters of the invocation method*, like for `Integer::new` constructor, you have to assign it to `Function` but not to `Callable`.
Comment: @Clashoft your second part of answer unfortunately describes same way. I mean way for creating such kind of method references for arbitrary class (I will clarify it in question)
Comment: +1 for your question, but I accepted answer of @Holger due to its more detailed explanation. Thank you too
Answer: You are focusing too much on irrelevant low level details. On the byte code level, there might be a constructor accepting an int parameter, but on the language level, you didn't specify an explicit constructor, hence, there will be a default constructor without any arguments, as with any other class.
This should become clear when you write the pre-Java 8 code:
static Callable<Object> gen(int i) {
    class X {
        int x = i;
        public String toString() { return "" + x; }
    }
    X x=new X();
    …

You instantiate X by its default constructor, not taking any arguments. Your local class captures the value of i, but how it does so on the low level, i.e. that X' constructor has a synthetic int parameter and the new expression will pass the value of i to it, is an implementation detail.
You can even add an explicit constructor as
        X() {}

without changing anything.
Obviously, you can also write the expression new X() inside a lambda expression here, as expressions don't change their semantic when being placed inside a lambda expression:
    return () -> new X();

or use it's short-hand form, the method reference
    return X::new;

There is nothing special about it, the behavior is understandable even without referring to the specification, if you forget about the distracting low level details. X may capture as many local variables as you like, the constructor's number of parameters doesn't change (on the language level).
Comment: @Andremoniy: I don't get your objection. All non-reflective instantiations will invoke the synthetic constructor with the captured value of `i` as the argument. If your define the callable as a local class, it has to capture `i` as well, so it complicates matters on the low level, but what's the question?
Comment: I'm not sure, that it is just like `Callable() { X call() { return new X(); }}`, because it implicitly invokes synthetic constructor with predefined parameter.
Comment: thank you. I've just realized obviousness of this case. It was my late-night delirium :))


How to escape single quote in Flexdashboard Navbar Menu?

Question: I'm using R markdown to create a flexdashboard. I'm having difficulty escaping a single quote in the title of one of my navbar menus.
I would like for my menu title to include a single quote and have tried escaping this with {data-navmenu="The Joneses\' House"}. If I knit that code, the navbar menu for The Joneses' House does not appear. If I remove the backslash and apostrophe (') and knit, the menu will appear (but with no apostrophe of course).
I've included my code below with YAML. In this code, the menu does not appear in the dashboard. How can I make it so that the menu title includes a single apostrophe? Thank you.
---
title: "Sample Dashboard"
output:
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
---

Bedroom {data-navmenu="The Joneses\' House"}
=====================================

Answer: I've got a fix, but it's not an escape.
I believe you will not be able to do anything short of JS to change this. flexdashboard uses the navigation tab name as the ID of an HTML element. An HTML element id can't have special characters.
My workaround doesn't seem to want to work with only this sparse bit of code. However, as soon as I added another tab, a bit of R code, or anything else, it works just fine.
I used JQuery to change the nav bar text after you render the page. You can place the fixit chunk with engine='js' anywhere in your script. Don't forget the space at the end of the string of text ("House "). It's part of the steps flexdashboard takes when it compiles the page.
The code
updated; I apparently lost the dropdown arrow
---
title: "Sample Dashboard"
output:
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
---

Bedroom {data-navmenu='The Joneses House'}
=====================================

More info...

Bath {data-navmenu='The Other House'}
=====================================

```{r fixit, engine="js", results="asis"}

setTimeout(function(){
  tx = $('#TheJonesesHouse > a').html();
  tx = tx.replace("Joneses", "Joneses'");
  $('#TheJonesesHouse > a').html(tx);
}, 200); // for loading time

```

From the viewer pane (updated):

From my browser (updated):
Comment: Oh, man! I totally missed that. I've modified my answer a bit. You need this arrow tied to an action. It's fixed now!
Comment: Thank you for the clever solution, Kat. I added unicode to your code to get the dropdown arrow to appear. However, I'm unsure how to adjust the fontsize of the unicode. Any advice? This is what I've added to your code: ```setTimeout(function(){

  $('#TheJonesesHouse > a').text("The Joneses\' House \u23F7");
}, 200); // for loading time```
Comment: @ Kat: Great work! Is it possible to add several tabs under "The Joneses' Hose"? E.g. Bedroom, Kitchen, Basement, etc.?
Comment: Yes! To add "Kitchen" to "The Jones' House", copy the code for the bedroom tab creation. If you want the kitchen to be listed after the bedroom in the dropdown, then paste that copied code any time after the bedroom tab creation. Change the word "Bedroom" to "Kitchen" in the copied code.


named/bind is refusing to serve some domains after resolving them itself

Question: Why is bind refusing some of my queries? This only happens for certain domains.
A query through named fails:
$ dig -t A fedoraproject.org @127.0.0.1
;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 33117

$ journalctl -n10
...
Aug 01 17:07:11 ns3.r3.mclarkdev.com named[10807]: resolver priming query complete
Aug 01 17:09:57 ns3.r3.mclarkdev.com named[10807]: timed out resolving 'fedoraproject.org/DNSKEY/IN': 184.108.40.206#53
Aug 01 17:09:59 ns3.r3.mclarkdev.com named[10807]: timed out resolving 'fedoraproject.org/DNSKEY/IN': 188.8.131.52#53

However a direct query to the forwarder works:
$ dig -t A fedoraproject.org @18.104.22.168
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 42249

  ... records ...

Bind is using a pretty default configuration.
The only things that I've changed were allowing queries from anywhere and adding a zones file for serving a some local records.
options {
    listen-on port 53 { any; };
    allow-query     { any; };
    forwarders      { 126.96.36.199; };
    recursion yes;
    ...
    dnssec-enable yes;
    dnssec-validation yes; // also tried auto
}

...

// includes two additional `zone` definitions
include "/opt/dns/named.zones";

OS Version: CentOS Linux release 8.4.2105
Kernel Version: 4.18.0-305.10.2.el8_4.x86_64
Named Version: BIND 9.11.26-RedHat-9.11.26-4.el8_4
Watching tcpdump, I can see that named is reaching out to the forwarder and retrieving the A records, but is refusing to serve them to the client after doing some additional queries.
localhost.49683 > localhost.domain: 14274+ A? fedoraproject.org. (35)
ns3.r3.mclarkdev.com.56668 > 184.108.40.206.domain: 21852+% [1au] A? fedoraproject.org. (58)
localhost.39587 > localhost.domain: 53253+ PTR? 188.8.131.52.in-addr.arpa. (38)
ns3.r3.mclarkdev.com.55378 > 18.104.22.168.domain: 61019+% [1au] PTR? 22.214.171.124.in-addr.arpa. (61)
184.108.40.206.domain > ns3.r3.mclarkdev.com.56668: 21852$ 12/0/1 fedoraproject.org. A 184.108.40.206, fedoraproject.org. A 22.214.171.124, fedoraproject.org. A 18.104.22.168, fedoraproject.org. A 22.214.171.124, fedoraproject.org. A 22.214.171.124, fedoraproject.org. A 126.96.36.199, fedoraproject.org. A 18.104.22.168, fedoraproject.org. A 126.96.36.199, fedoraproject.org. A 188.8.131.52, fedoraproject.org. A 184.108.40.206, fedoraproject.org. RRSIG, fedoraproject.org. RRSIG (528)
  /\ bind has the A records

ns3.r3.mclarkdev.com.52120 > 18.104.22.168.domain: 7073+% [1au] DNSKEY? fedoraproject.org. (58)
220.127.116.11.domain > ns3.r3.mclarkdev.com.55378: 61019 1/0/1 184.108.40.206.in-addr.arpa. PTR dns.google. (73)
ns3.r3.mclarkdev.com.55309 > 22.214.171.124.domain: 23607+% [1au] DS? 8.in-addr.arpa. (55)
localhost.48388 > localhost.domain: 55328+ PTR? 184.108.40.206.in-addr.arpa. (44)
  /\ bind makes some extra queries

localhost.domain > localhost.48388: 55328 NXDomain* 0/1/0 (98)
  /\ bind serves NXDomain to client

Why is named refusing to serve the result to the client? It happens only for about 1% of domains.
Comment: I changed very few options, just to allow others on the network to use it as a proxy and giving it two local zones to serve. I added the lines i've changed, everything else is default.
Comment: That's odd. Why have you set forwarders?
Comment: I want this to be an internal DNS server; it will be handed out with DHCP leases to resolve all public queries and local queries (the additional zones I've loaded). I am only seeing errors related to this `DNSKEY` - other domains resolve through the forwarders just fine. It's only about 1% of domains which fail to resolve, the issues exists on two servers I am spinning up in parallel.
Comment: The NXDOMAIN isn't for `fedoraproject.org`, it's for `18.104.22.168.in-addr.arpa`. That's a reverse DNS lookup of a private IP.
Comment: You haven't explained why you configured forwardeers instead of letting it resolve external domains itself.
Answer: The tcpdump shows that it's successfully getting the A record of fedoraproject.org, but it's also trying to get the DNSKEY record, which is used for DNSSEC validation. But there's no response to that.
I queried 184.108.40.206 for this DNSKEY record, and it worked fine.
$ dig fedoraproject.org dnskey @184.108.40.206

; <<>> DiG 9.10.6 <<>> fedoraproject.org dnskey @184.108.40.206
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 63666
;; flags: qr rd ra ad; QUERY: 1, ANSWER: 4, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;fedoraproject.org.     IN  DNSKEY

;; ANSWER SECTION:
fedoraproject.org.  108 IN  DNSKEY  256 3 5 AwEAAcCWNQWl5pCI3iOOP2r8nStL60Zjb/2JQLQytamVap0L44z0YWft u7pu0hx3cnIM1ejQOsEwbg2/10IyC+38cYqJDXbSdFg1zGztOS5xNz7r 9hzSRK5N2jkycdJ/BoByJ4Y+XGpDqfG4I97++8sIzSrw60TmGAKTvM9v iL3ByeCN
fedoraproject.org.  108 IN  DNSKEY  257 3 5 AwEAAdTXJc0joiKGfTvLXi+LXxGpKvPvOoJEst9PR8TCCvXGVp7h3BY3 uXLkjckuT0aopCp2KF8zHgNgpMK03p1fd94pn9JZSuxfqvKsiYH2KvNO a/655oPj06jRhqAP5grX01Iz4BH411ZhGxIQ1BzZtOr1wAazojMJzLUg ChRJs8GVt3LU0e6T8z1RQF33Dt9UMHIR5EAsFAqfZ/tsbfJDYktGoZi3 nFlW7A745+ObM1LNXOWq3FcYPVzhH08Q7/7WpxmzM6/ET8VeqWIsvh8E nZNDNMfJyPbY9B1BOIrFCpE03ALgFMejaBZwmeQaX+D4Duup5xGOmdtC O4GSpM1YH6c=
fedoraproject.org.  108 IN  DNSKEY  257 3 14 7ttmhus8JD56ybsvMVZVsXa3U2R+2+WmOPIP7BU6t2LicosMZ2Ju3pfv ijsa5LvBvVCB4xVtLSqEdLSvW4vJPLSAB2uyJwHPJMezh0SzGmVCImLU 6qDxsxjHqtZ76/Sf
fedoraproject.org.  108 IN  DNSKEY  256 3 14 04ZsDOgyzs3kJsJ4jEY3MYufkCOWm1OI8N4M+dlBOBmweln0TSaKfafH zNCkaPiVG4bdgdnrzwxmjpK5GQgsiB47np+I8850Ea3EJG5ORDl3f//l rr92HiYh5DxCNhkG

So I suspect something in your environment is blocking the query or response. It could be a firewall issue, filtering DNS record types or large responses.
Answer: Your installation of bind appears to be choking on DNSSEC validation for DNSSEC signed domains. More recent versions of bind have DNSSEC validation enabled by default, but older versions such as 9.11 need to have it explicitly enabled:
options {
         ...
         dnssec-validation auto;
         ...
 };

Comment: Unfortunately I've already tried this, and there is no change.
Comment: @MattClark Why didn't you say so when I asked?
Comment: Sorry, I've tried a few things - I am back to a pretty much default configuration and still seeing the issue. I put this back to 'yes' which is default, but I did try 'auto' while debugging.
Comment: Anyway it still needs to be there, so you should leave it in.
Comment: I've added some additional info to the main post, not sure if the help.


How bulky are extended classes in Java?

Question: I've a class called MapTile that extends JLabel. What I'm doing is loading a JPanel with a lot of MapTile's in a GridLayout. I notice when I load in 100x100 MapTile's the process takes longer than loading in 100x100 JLabel's. This is my MapTile class below.
public class MapTile extends JLabel {
private static final long serialVersionUID = 1L;
private boolean selected;
private Point location;

public MapTile(){
    super();
    location = new Point();
}
public void setLocation(int x, int y){
    setLocation(new Point(x,y));
}
public void setLocation(Point p){
    location = p;
}
public Point getLocation(){
    return location;
}
public void setSelected(Boolean b){
    selected = b;
    if (selected){
        ((GridPanel)this.getParent()).addToSelection(this);
        this.setBorder(BorderFactory.createLineBorder(Color.RED));
    } else {
        this.setBorder(BorderFactory.createLineBorder(Color.BLACK));
    }
    this.repaint();
}
public boolean isSelected(){
    return selected;
}
}

There's nothing fancy, I just overwrote the setLocation method and added a few other methods. I also added just three instance variables.
Does extending a class cause a bunch of extra weight to deal with?
I can't help but think my MapTile class is pretty simple, yet the time between loading 100x100 MapTile's vs loading 100x100 JLabel's is hugely different. It's taking about 4-5 times longer to load MapTile's in large quantities than JLabels.
Answer: You did not just overrode the setLocation but you create a new instance of Point each time the setLocation(int,int) method is called which could have a performance impact
Besides that:
- have you tested that when you remove the overridden methods you no longer experience a slow-down
- have you profiled the application to see where the performance loss occurs
Oh yeah, I do not think your overridden version of setLocation is correct. I fear you must call super.setLocation as well if you want to JLabel to behave correctly
Comment: So the issue is that I really _am_ making my extended class bulky and slow?
Edit: Most certainly! I removed my Point instance variable just to see, and performance improved drastically. Thank you :)
Comment: @LucasMorgan Correct. Glad you could verify this in your code

How bulky are extended classes in Java?


Toggling Checkbox on Timer/Delay Without Thread.Sleep

Question: I have 2 checkboxes. Checkbox_toggle, when checked, will initiate a toggle sequence. This toggle sequence will check and uncheck Checkbox_control with a timer/delay.
I want that to keep looping as long as Checkbox_toggle is checked. However, Thread.Sleep won't work for my purposes as I need the rest of the program to continue running. I looked into BackgroundWorker and I can't quite find an example/I don't understand it well enough to apply it to my program. I'm using .NET 4.0 so I can't use Task.Delay.
I know with BackgroundWorker there's the ProgressChanged event that can be used to update the UI, but I'm not really sure how I would be able to use that for my  application. I'm also open to another solution that isn't BackgroundWorker.
I tried using this .NET 4.0 implementation of Task.Delay, but it's not working how I'd like. It runs through all of that but the delay doesn't actually delay the loop
    public static System.Threading.Tasks.Task Delay(double milliseconds)
    {
        var tcs = new TaskCompletionSource<bool>();
        System.Timers.Timer timer = new System.Timers.Timer();
        timer.Elapsed += (obj, args) =>
        {
            tcs.TrySetResult(true);
        };
        timer.Interval = milliseconds;
        timer.AutoReset = false;
        timer.Start();
        return tcs.Task;
    }

    private void Checkbox_toggle_CheckedChanged(object sender, EventArgs e)
    {
        while (Checkbox_toggle.Checked == true)
        {
            Checkbox_control.Checked = true;
            Delay(1000);
            Checkbox_control.Checked = false;
            Delay(1000);
        }
    }

Task delay event found here: https://stackoverflow.com/a/15342256/8407531
My actual question: How can I toggle a checkbox on a timer without using Thread.Sleep, or how can I offset it to another thread? If possible, this delay needs to be adjustable from the other thread.
Comment: Don't use a `BackgroundWorker`, use a `System.Windows.Forms.Timer`.
Answer: It seems that you misunderstood the use of the timer. Normally you would set up the Timer with an interval, and if you want repeated actions then you would set timer.AutoReset = true.
public Form1()
{
    InitializeComponent();

    System.Timers.Timer timer = new System.Timers.Timer();

    timer.Interval = 1000;
    timer.AutoReset = true;

    timer.Elapsed += Timer_Elapsed;

    timer.Start();
}

Now when you start the timer now it will wait until the interval is over then it will fire the Elapsed event and perform some action in the eventhandler that you implemented when you registered the event:
private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    // here you can specify whether the toggeling should occur or not
    if (Checkbox_toggle.Checked)
    {
        // toggling needs to be invoked since it is called on a different thread
        this.checkBox_Control.BeginInvoke(
                new Action(() => this.checkBox_Control.Checked = !this.checkBox_Control.Checked));
    }
}

The timer will continue to run, without freezing your GUI. And you can simply check or uncheck the Checkbox_toggle and the togegling will stop. But the timer will continue to run. If you check the Checkbox_toggle again the timer will toggle again.
Comment: I think this is definitely along the lines of what I'm looking for, but I'm struggling to figure out how I would actually make it actively toggle with that code. I'm trying to implement something that would be along the lines of: `if (Checkbox_toggle.Checked) { Checkbox_control.Checked = !Checkbox_control.CheckedState}`. That gives a syntax error, but I hope that gets the point across
Comment: @ScottMyers almost, simply reverse the `Checked` property and write it back: `Checkbox_control.Checked = !Checkbox_control.Checked;` I added it into my post
Comment: Okay it looks like that's working but there's a strange behavior. The UI only updates the status of the checkbox if I hover over it. For it to then update again I need to move my mouse off the checkbox and then move it back on.  For clarity, if I rapidly move my mouse on and off the checkbox (without clicking), then I can see the box check and uncheck. However, if I do not do this then I cannot see the UI updating. Any ideas for why that might be? If this is out of the scope of this question I can make a new one
Comment: @ScottMyers my fault. You need to call `Invoke` or `BeginInvoke` because the timer event arrives on a different thread. See my updated answer
Comment: That's perfect! Thank you so much
Comment: @ScottMyers no problem. Timers are perfect for such stuff.
Comment: @ScottMyers as a comment on your code: The while loop is executed on the main thread and is called busy waiting. This is why it blocks your GUI. The Method `Delay` doen't wait actually. It simply returns a `Task`, and sets up a new timer each time, with which you populate the memory.


port forwarding with libvirt

Question: I'm trying to get port forwarding working through libvirt on top of QEMU and KVM. I found this article (https://snippets.webaware.com.au/howto/running-qemu-with-port-redirection-through-libvirt/), but the XMLNS it points to (http://libvirt.org/schemas/domain/qemu/1.0) does not seem to exist anymore. Any advice would be greatly appreciated!
I'm running libvirt version 1.2.18 and qemu-kvm version 2.3.0
Thanks
Answer: If you want to run a server, you should not use port-forwarding anyway. You can create a bridge on your physical ethernet interface and use your VM network interfaces as slaves of this bridge as. Then every VM can get its own IP address and you can access it directly (just open the port on the VM). Network setup is mentioned in the libvirt docs.

port forwarding with libvirt


error in date solve the program

Question: This is my program :
$newEndingDate = strtotime(date("Y-m-d", strtotime($row['startdate']))."+1 year");
echo $newEndingDate;

this is my error
1332441000

whats the error
Comment: That is not an error, that is a timestamp. See [`date()`](http://www.php.net/date) for how to turn it into a readable date
Answer: The strtotime() function returns an UNIX Timestamp : the number of seconds since 1970-01-01.
The number you are getting is not an error : it just means that 1332441000 seconds have passed since 1970.

If necessary, you can use the [**`date()`**][3] function to format that timestamp, to get a string that looks a bit more user-friendly.
For instance :
echo date('Y-m-d H:i:s', $newEndingDate);

should get you the following result :
2012-03-22 19:30:00

Answer: Try using mktime to do what you want. Assume $row['startdate'] == '2011-01-01'
$mydate = strtotime($row['startdate']);
$newEndingDate = mktime(date("H", $mydate), date("i", $mydate), date("s", $mydate), date("n", $mydate), date("j", $mydate), date("Y", $mydate) + 1);
echo date('Y-m-d', $newEndingDate); //2012-01-01

What you are doing will not give you the result you're after because you can't do the following:
strotime('2011-01-01+1 year');

Try this instead:
$mydate = strtotime($row['startdate']);
$newEndingDate = date('Y-m-d', strtotime("+1 year", $mydate));
echo $newEndingDate; //2012-01-01

Answer: It is the return value of strtotime function, which is a UNIX timestamp. The seconds passed since 01/01/1970
I think this is you would like to get:
$newEndingDate = date('Y-m-d', strtotime('+ 1 year', strtotime($row['startdate'])));
Answer: you dont get an error, you get the timestamp of all the seconds that have passed since 1970/01/01
if you need a readable format try:
$date = date("Y-m-d H:i:s", $newEndingDate);

error in date solve the program


How Large a Difference Can Be Expected Between Standard GARCH and Asymmetric GARCH Volatility Forecasts?

Question: I have been using various GARCH-based models to forecast volatility for various North American equities using historical daily data as inputs.
Asymmetric GARCH models are often cited as a modification of the basic GARCH model to account for the 'leverage effect' i.e. volatility tends to increase more after a negative return than a similarly sized positive return.
What kind of a difference would you expect to see between a standard GARCH and an asymmetric GARCH forecast for a broad-based equity index like the S&P 500 or the NASDAQ-100?
There is nothing particularly special about these two indices, but I think it is helpful to give something concrete to focus the discussion, as I am sure the effect would be different depending on the equities used.
Comment: I don't think that using GARCH with asymmetric error distribution alone, makes it capable of modelling 'leverage effect', conditional variance equation should be properly modified, EGARCH is an example, interested reader could see, for description of collection of such models : http://e-archivo.uc3m.es/bitstream/handle/1001/1041/tesis_maria_jose_rodriguez.pdf
Answer: Generally, by not allowing for assymetry, you expect the effect of shocks to last longers: i.e. the half-life increases (the half life is the number of units of time, after a 1 S.D. shock to $\epsilon_{t-1}$ for $\hat{\sigma}t|I{t-1}$ to come back to the its unconditional value.)
Here is a code snipped that downloads stock data, fits (e)Garch and computes half lifes, in R:
<code>install.packages("rgarch",repos="http://R-Forge.R-project.org")
install.packages("fGarch")
install.packages("fImport")
library(rgarch)
library(fImport)
library(fGarch)
d1<-yahooSeries(symbols="ibm",nDaysBack=1000,frequency=c("daily"))[,4]
dprice1<-diff(log(as.numeric(d1[length(d1):1])))
spec1<-ugarchspec(variance.model=list(model="eGARCH",garchOrder=c(1,1)),mean.model=list(armaOrder=c(0,0),include.mean=T))
spec2<-ugarchspec(variance.model=list(model="fGARCH",submodel="GARCH",garchOrder=c(1,1)),mean.model=list(armaOrder=c(0,0),include.mean=T))
fit1<-ugarchfit(data=dprice1,spec=spec1)
fit2<-ugarchfit(data=dprice1,spec=spec2)
halflife(fit1)
halflife(fit2)
</code>
The reason for this is that generally speaking, negative spells tend to be more persistent.
If you don't control for this, you will generally bias the $\beta$ (i.e. persistance parameters) downwards.
Answer: there is a significant difference and there a couple of published papers to that effect

Comparative Performance of Volatility Models for Oil Price

International Journal of Energy Economics and Policy
Vol. 2, No. 3, 2012, pp.167-183
ISSN: 2146-4553
www.econjournals.com
and many more
Comment: This is quite short and perhaps would better suit as a comment.