PHP mail not receiving using this code

Question: This below code using for receive the email for password, but email not sent due to some error. Kindly review the code and corrected, update the new code for send email. We are using forgot password in html and validate and email using php.
<?php
    if(isset($_POST['submit'])) {
        mysql_connect('localhost','connect','connect') or die(mysql_error());
        mysql_select_db('connect') or die(mysql_error());
        $Email_Address = $_POST['Email_Address'];
        $q = mysql_query("SELECT * from erp_ng_form_reg WHERE    Email_Address='$Email_Address' ") or die(mysql_error());

        while($row = mysql_fetch_assoc($q)) {
            $result[] = $row;
        }
        //$p = mysql_affected_rows();
        //$res = mysql_fetch_array($q);
        $to = $result['Email_Address'];
        $message = $result['Password'];
        $subject="Remind password";
        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
        $headers .= 'From: <email@example.com>' . "\r\n";
        $m=mail($to, $subject, $message, $headers);
        if($m) {
            echo'Check your inbox in mail';
            echo $message;
        } else {
            echo  "";
            echo 'mail is not send';
        }
    }
?>

Forgot Password

        <form action='#' method='post'>

                    Email Address:	<input type='text' id='Email_Address' name='Email_Address'/>

                    <input type='submit' name='submit' value='Submit'/>

        </form>

Comment: What is the error in this code ?
Comment: `print_r($result)` debug this ist, u will get the solution.
Comment: print_r($result) this is not in code.
Comment: LOL, `print_r()` is a function just for checking your `$result`, check what are you getting in `$result`...
Comment: before this line `$to = $result['Email_Address'];` use `print_r($result);` and share the result.
Comment: Array ( [0] => Array ( [id] => 35 [Licensee_Name] => team zulu [FACT_ERP_NG_Serial_Number] => 12304567890 [Email_Address] => email@example.com [Password] => 12345 [Confirm_Password] => 12345 ) ) mail is not send
Comment: this is the result but error came "mail not sent"
Comment: sounds like, your mail function is not working on local. u need to configure it
Comment: Yes. I know, i configure this in server. due to some safety so i set localhost.
Answer: <?php
    if(isset($_POST['submit'])) {
        mysql_connect('localhost','connect','connect') or die(mysql_error());
        mysql_select_db('connect') or die(mysql_error());
        $Email_Address = $_POST['Email_Address'];
        $q = mysql_query("SELECT * from erp_ng_form_reg WHERE    Email_Address='$Email_Address' ") or die(mysql_error());
        $numofemails = mysql_num_rows($q);
        if($numofemails > 0) {
            $result=mysql_fetch_assoc($q);
            $to = $result['Email_Address'];
            $message = $result['Password'];
            $subject="Remind password";
            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
            $headers .= 'From: <email@example.com>' . "\r\n";
            $m = mail($to, $subject, $message, $headers);
            if($m) {
                echo'Check your inbox in mail';
                echo $message;
            } else {
                echo  "";
                echo'mail is not send';
            }
        } else {
            echo 'Email Not found';
        }
    }
?>

Comment: test this, may you not getting email id after query.
Comment: check your mail function is working on server or not?

$msg = "First line of text\nSecond line of text"; mail("firstname.lastname@example.com","My subject",$msg); cehck by put the file on server with proper emailid.
Comment: all function configure to server. but mail not received.
Comment: try this one may authentication required! http://stackoverflow.com/a/23905054/1374160
Comment: yes. the mail function configure to server. but the mail not receiving till now.
Comment: First check by simple sending mail, mail receiving or not. if not received than check your mail server settings.
Comment: the password shown in page but the mail not received.
Comment: i am not configure SMTP. Is this problem for email not received?
Comment: the test email received from SMTP Configure.
Comment: please send me ur email i need ur help

PHP mail not receiving using this code


=GOOGLEFINANCE("AAPL";"eps";TODAY(); today()-60)

Question: I've found nice function =GOOGLEFINANCE("AAPL";"price";TODAY(); today()-60) that gives stock prices for defined date range - it works fine.
I was trying to use it to get EPS or PE data. Is that possible to get EPS historical data using googlefinance() (I was trying with =GOOGLEFINANCE("AAPL";"eps";TODAY(); today()-60) but it is not working) or we can get only current EPS with =GOOGLEFINANCE("AAPL;"eps")
Will appreciate your support on this.
KG
Answer: EPS is not supported, only:
<code>=GOOGLEFINANCE("AAPL"; "all"; TODAY(); TODAY()-60)
</code>
Answer: EPS data is not supported.
However the price is adjusted for bonus, stocksplit ESOPS etc.
Answer: Use following, A3 is the cell with tricker name:
=GOOGLEFINANCE(A3,"eps")
In your case it is like this:
=GOOGLEFINANCE("AAPL", "eps")
Problem is that eps is only support teal-time data, so we can't fill any data with that.


How do I derive a general formula for $I(n,m)$?

Question:
To prove the first one, here's what I did:
$\int x^nln(x)^mdx=$
IBP: $ln(x)^m=u \Rightarrow \frac{mln(x)^{m-1}}{x}dx=du$
$x^ndx=dv \Rightarrow v=\frac{x^{n+1}}{n+1}$ $\Rightarrow$
$$ln(x)^m\frac{x^{n+1}}{n+1}-\int\frac{x^{n+1}}{n+1}\frac{mln(x)^{m-1}}{x}dx=ln(x)^m\frac{x^{n+1}}{n+1}-\frac{m}{n+1}\int x^nln(x)^{m-1}dx=ln(x)^m\frac{x^{n+1}}{n+1}-\frac{m}{n+1}I(n,m-1)$$
To show the second:
$I(n,1)=\frac{x^{n+1}}{n+1}ln(x)-\frac{1}{n+1}I(n,0)$
$I(n,0)=\int x^nln(x)^{0}= \int x^n= \frac{x^{n+1}}{n+1} \Rightarrow I(n,1)=\frac{x^{n+1}}{n+1}ln(x)-\frac{1}{n+1}\Biggl( \frac{x^{n+1}}{n+1}\Biggr)$
Now, for the third:
$I(0,1)=xln(x)-I(0,0)=x\Bigl(ln(x)-1\Bigr)$ since $I(0,0)=\int x^0ln(x)^0= \int 1= x$
$I(0,2)=xln(x)^2-I(0,1)=xln(x)^2-x(ln(x)-1)=x\Biggl(ln(x)^2-ln(x)+1\Biggr)$
$I(0,3)=xln(x)^3-x(ln(x)^2-ln(x)+1)= x\Biggl(ln(x)^3-ln(x)^2+ln(x)-1\Biggr)$
$\Rightarrow I(0,m)=x(ln(x)^m+(-1)^mln(x)^{m-1}+...+(-1)^m)$
Would this be correct?
Also how do I derive a general formula for $I(n,m)$?
Answer: Knowing $I(n,0)$ and how to express $I(n,m)$ in terms of $I(n,m-1)$ means you can express $I(n,m)$ in terms of $I(n,0)$ by unfolding the recursion. You can write this recursion as
$$I(n,m)=f_{n,m}+c_{n,m-1} I(n,m-1)$$
where according to your work $f_{n,m}(x)=\ln(x)^m \frac{x^{n+1}}{n+1}$ and $c_{n,m-1}=-\frac{m}{n+1}$.
Unfolding one more time just to make the pattern more apparent:
$$I(n,m)=f_{n,m}+c_{n,m-1} f_{n,m-1} + c_{n,m-1} c_{n,m-2} I(n,m-2).$$
So you see that $f_{n,m-k}$ will have $k$ of the $c$'s multiplying with it when you are done unfolding, and then you will sum up all those terms. So $I(n,m)=\sum_{k=0}^m \left ( \prod_{j=1}^k c_{n,m-j} \right ) f_{n,m-k}$ for $m \geq 1$. You can simplify the product inside the sum down to be in terms of factorials and exponents.
Answer: You start iterating the recurrence like this:
\begin{align*}
& I(n,m) = \frac{{x^{n + 1} }}{{n + 1}}\log ^m x - \frac{m}{{n + 1}}I(n,m - 1)
\\ &
 = \frac{{x^{n + 1} }}{{n + 1}}\log ^m x - \frac{m}{{n + 1}}\left[ {\frac{{x^{n + 1} }}{{n + 1}}\log ^{m - 1} x - \frac{{m - 1}}{{n + 1}}I(n,m - 2)} \right]
\\ &
 = \frac{{x^{n + 1} }}{{n + 1}}\log ^m x - \frac{{x^{n + 1} }}{{(n + 1)^2 }}m\log ^{m - 1} x  + \frac{1}{{(n + 1)^2 }}m(m - 1)I(n,m - 2)
\\ & = \frac{{x^{n + 1} }}{{n + 1}}\log ^m x - \frac{{x^{n + 1} }}{{(n + 1)^2 }}m\log ^{m - 1} x \\ & \quad \, + \frac{1}{{(n + 1)^2 }}m(m - 1)\left[ {\frac{{x^{n + 1} }}{{n + 1}}\log ^{m - 2} x - \frac{{m - 2}}{{n + 1}}I(n,m - 3)} \right]
\\ & = \frac{{x^{n + 1} }}{{n + 1}}\log ^m x - \frac{{x^{n + 1} }}{{(n + 1)^2 }}m\log ^{m - 1} x + \frac{{x^{n + 1} }}{{(n + 1)^3 }}m(m - 1)\log ^{m - 2} x \\ &\quad\,- \frac{1}{{(n + 1)^2 }}m(m - 1)\frac{{m - 2}}{{n + 1}}I(n,m - 3),
\end{align*}
etc. From this, you can conjecture that
$$
I(n,m) = \frac{{x^{n + 1} }}{{n + 1}}\sum\limits_{k = 0}^m {\frac{{( - 1)^k }}{{(n + 1)^k }}\frac{{m!}}{{(m - k)!}}\log ^{m - k} x} ,
$$
and verify it by using the recurrence and induction.


PHP: Removing an attribute from a DOMNode object

Question: I've got a DOMNode object that has some attributes. $Node->attributes is a DOMNamedNodeMap, which has no methods for removing one of the entries in the map. The DOMNode class also has no methods for removing attributes from an element.  I've looked through a number of the other related classes and none of them seem to provide a mechanism for removing an attribute node from its parent.
DOMNode::removeChild doesn't work; it throws a "Not found error" if I pass a DOMAttr object to it.
Aside from constructing a new DOMNamedNodeMap and adding all the attributes to it except the one I don't want... any ideas?  Thanks.
Answer: If you've got a DOMNode that has some attributes, it must be a DOMElement. In which case you should be able to call removeAttribute/removeAttributeNS/removeAttributeNode on it.
It is somewhat curious that PHP's DOMNamedNodeMap documents getNamedItem[NS] but does not acknowledge the existence setNamedItem[NS] and removeNamedItem[NS], which would have been another way of doing it.
DOMNode::removeChild can't work because a DOMAttr is not a child of another DOMNode; 'attributes' is a separate space to childNodes. You also can't create a new NamedNodeMap on its own to write to DOMNode::attributes, as that's a read-only property.
Comment: That was it!  Thank you.  I hadn't yet grokked that the DOMNode would also be a DOMElement.  That's what I get for not using ReflectionClass::export() enough :)


Why would Belichick spilt Gronk out wide against the Seahawks?

Question: Bill Barnwell writes about the 2014-15 Super Bowl,

Gronkowski spent a surprising amount of time matched up early split
  out as the world's biggest decoy against Richard Sherman, but as the
  game wore on, he ended up in matchups against linebackers and safety
  Kam Chancellor and found them more to his liking.

Why would the Patriots split Gronkowski, arguably the Patriots' biggest receiving threat and a guy who's comfortable in the middle of the field out wide, where Richard Sherman is at his best?
Answer: Well to answer the question specifically, a big reason they chose to split him out wide against Sherman, is because of Sherman's arm injury.  A big part of Sherman's game is getting his hands on receivers, being more physical, and bumping them off their routes.  Now Gronk has 3 inches and 70 pounds on Sherman, and with his bum arm, he wasn't able to lift it and use it to full strength, so Gronk would be able to take advantage of the size differential a lot better with a less than healthy Sherman.  That's why you saw, at times in the game, other people going against Gronk, because Sherman wasn't at his best and able to be as effective against the bigger receiver like he usually is.

"The one thing that stands out on tape is that no matter where he(Gronkowski) lines up, the teams that disrupted him -- either at the line of scrimmage or within five yards of his release -- had the most success. Gronk is a bad man and if he gets a free run off the line, bad things happen."

Source
Comment: There's also the fact that Seattle likes to play Cover-3 most of the time, a formation that leaves Earl Thomas as the centerfield and puts Kam Chancellor near the line. Now, Gronk almost always draw double-coverage from the defense, but since Thomas is set as the deep safety, Seattle had to commit Kam or some of the linebackers to Gronk outside. This opened a gigantic hole in the middle of Seahawks defense, where Brady completed passes to Edelman, Amendola and Vereen, moving the chains. Belichick knew he could not count on running on Seattle for first downs.


Error mounting ebs in amazon ec2

Question: I have accidently changed permissions for my /etc/sudoers and /etc folders and thereby I am unable to access anything through sudo.
After that I detached my ebs volume from the instance and attached it to another instance by using device name /dev/sdf. But when I am mounting it to new instance by using
sudo mkdir -m 000 /vol-a
sudo mount /dev/sdf /vol-a

it returns an error saying
 mount:/dev/xvdf is write protected,mounting read only mount:wrong fs type,bad option

Answer: try running fdisk -l just to make sure /def/sdf is the actual block name, so probably it should mount with:

sudo mount /dev/sdf1 /vol-a
Comment: The better tool to use is `blkid`. less noise, plus it shows you filesystem types & labels.
Comment: yeah thanx for your help it worked great yar....

Error mounting ebs in amazon ec2


How to set timer to execute at specific time in c#

Question: I have a requirement where i need to execute timer at 00:01:00 A.M every day...But  i am not getting how to achieve this ..If i am taking Systems time,it can be in different format..
Here is my timer code..
static System.Timers.Timer timer;
timer = new System.Timers.Timer();
timer.Interval = 1000 * 60 * 60 * 24;//set interval of one day
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
start_timer();

static void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        // Add timer code here

    }
    private static void start_timer()
    {
        timer.Start();
    }

Comment: Nico's answer will not be accurate or reliable.  Grant's answer is a better solution, you need to poll and check against DateTime.Now
Answer: If you want to start a timer at exactly 00:01:00am do some processing time and then restart the timer you just need to calculate the difference between Now and the next 00:01:00am time slot such as.
static Timer timer;
static void Main(string[] args)
{
    setup_Timer();
}

static void setup_Timer()
{
    DateTime nowTime = DateTime.Now;
    DateTime specificTime = new DateTime(nowTime.Year, nowTime.Month, nowTime.Day, 1, 0, 0, 0);
    if (nowTime > specificTime)
        specificTime= specificTime.AddDays(1);

    double tickTime = (specificTime- nowTime).TotalMilliseconds;
    timer = new Timer(tickTime);
    timer.Elapsed += timer_Elapsed;
    timer.Start();
}

static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
    timer.Stop();
    //process code..
    setup_Timer();
}

Comment: This won't work. Timers are not accurate

http://stackoverflow.com/questions/10605639/timer-component-not-accurate-enough-is-there-an-alternative

It measures ticks, they can be offset by high cpu usage
Comment: @Mick it does not need to be a realtime issue. approximatly at 1 am or at 1 am and a second he want's something to happen.
It's true that Timers can have slight delays. but it's good enough for most scenarios.
for thous scenarios you can use MMTimer
http://www.codeproject.com/Articles/5501/The-Multimedia-Timer-for-the-NET-Framework
Comment: A better link describing why this is problematic

http://stackoverflow.com/questions/416522/c-sharp-why-are-timer-frequencies-extremely-off
Answer: What you should do is write your program that does whatever you need it to do, and then use your OS's built-in task scheduler to fire it off. That'd be the most reliable. Windows's Task Scheduler, for instance, can start your app before the user logs in, handle restarting the app if necessary, log errors and send notifications, etc.
Otherwise, you'll have to run your app 24/7, and have it poll for the time at regular intervals.
For instance, you could change the interval every minute:
timer.Interval = 1000 * 60;

And inside your Elapsed event, check the current time:
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
    if (DateTime.Now.Hour == 1 && DateTime.Now.Minute == 0)
    {
        // do whatever
    }
}

But this is really unreliable. Your app may crash. And dealing with DateTime's can be tricky.
Answer: You could always calculate it:
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
    // Do stuff

    start_timer();
}

private static void start_timer()
{
    timer.Interval = CalculateInterval();
    timer.Start();
}

private static double CalculateInterval()
{
    // 1 AM the next day
    return (DateTime.Now.AddDays(1).Date.AddHours(1) - DateTime.Now).TotalMilliseconds;
}

Comment: http://stackoverflow.com/questions/416522/c-sharp-why-are-timer-frequencies-extremely-off
Answer: Here is a timer implementation which takes an Interval (just like any other timer) and fires exactly when that interval expires, even the machine goes to sleep mode in between.
public delegate void TimerCallbackDelegate(object sender, ElapsedEventArgs e);
public class TimerAbsolute : System.Timers.Timer
{
    private DateTime m_dueTime;
    private TimerCallbackDelegate callback;

    public TimerAbsolute(TimerCallbackDelegate cb) : base()
    {
        if (cb == null)
        {
            throw new Exception("Call back is NULL");
        }
        callback = cb;
        this.Elapsed += this.ElapsedAction;
        this.AutoReset = true;
    }

    protected new void Dispose()
    {
        this.Elapsed -= this.ElapsedAction;
        base.Dispose();
    }

    public double TimeLeft
    {
        get
        {
            return (this.m_dueTime - DateTime.Now).TotalMilliseconds;
        }
    }

    public int TimeLeftSeconds
    {
        get
        {
            return (int)(this.m_dueTime - DateTime.Now).TotalSeconds;
        }
    }

    public void Start(double interval)
    {
        if (interval < 10)
        {
            throw new Exception($"Interval ({interval}) is too small");
        }

        DateTime dueTime = DateTime.Now.AddMilliseconds(interval);

        if (dueTime <= DateTime.Now)
        {
            throw new Exception($"Due time ({dueTime}) should be in future. Interval ({interval})");
        }
        this.m_dueTime = dueTime;

        // Timer tick is 1 second
        this.Interval = 1 * 1000;
        base.Start();
    }

    private void ElapsedAction(object sender, System.Timers.ElapsedEventArgs e)
    {
        if (DateTime.Now >= m_dueTime)
        {
            // This means Timer expired
            callback(sender, e);
            base.Stop();
        }
    }
}


R square and R square adjusted

Question: As $R^2$ increases, $R^2_{adj}$ increases too.
Is that statement true?
Comment: Is that probably a [tag:self-study] question? Consider tagging it as such. Regarding the question, open up any econometrics textbook, and you will find the answer.
Answer: Note that $R_{\text{adj}}^2 = 1-(1-R^2){n-1 \over n-p-1}$
So, if you fix $n$ and $p$, but move your data points about to increase $R^2$, then yes, adjusted $R^2$ must increase.

R square and R square adjusted


Line plot with arrows in matplotlib for all 4 lines plotted with lists of 4 elements

Question: These variables are all lists containing 4 elements. I am trying to get the arrows to show in between these 4 elements for all the lists below in the line plot. In another words, I will have 3 arrows for each of the 4 lines in the plot shown below.
I came across this post that suggested the use of quiver but I am not sure how to apply it to my use case Line plot with arrows in matplotlib Any suggestion is appreciated.
median1
median2
median3
median4

median_a
median_b
median_c
median_d

import matplotlib.pyplot as plt

x1 = median_a
x2 = median_b
x3 = median_c
x4 = median_d

y1 = median1
y2 = median2
y3 = median3
y4 = median4

line1 = plt.plot(x1, y1,'bo-',label='B0')
line2 = plt.plot(x2, y2,'go-',label='B1')
line3 = plt.plot(x3, y3,'ko-',label='B2')
line4 = plt.plot(x4, y4,'ro-',label='B3')

plt.title("Flow")
plt.ylabel("Speed")
plt.xlabel("Size")

plt.legend(bbox_to_anchor=(1.5, 1),
           bbox_transform=plt.gcf().transFigure)

Answer: import numpy as np
import matplotlib.pyplot as plt

median_a, median_b, median_c, median_d = [np.random.random((4, 1)) for _ in range(4)]
median1, median2, median3, median4 = [np.random.random((4, 1)) for _ in range(4)]

x1 = median_a
x2 = median_b
x3 = median_c
x4 = median_d

y1 = median1
y2 = median2
y3 = median3
y4 = median4

deltaX1, deltaX2, deltaX3, deltaX4 = [x[1:]-x[:-1] for x in [x1, x2, x3, x4]]
deltaY1, deltaY2, deltaY3, deltaY4 = [y[1:]-y[:-1] for y in [y1, y2, y3, y4]]

line1 = plt.plot(x1, y1,'bo-',label='B0')
line2 = plt.plot(x2, y2,'go-',label='B1')
line3 = plt.plot(x3, y3,'ko-',label='B2')
line4 = plt.plot(x4, y4,'ro-',label='B3')

arrows1 = plt.quiver(x1[:-1], y1[:-1], deltaX1, deltaY1, scale_units='xy', angles='xy', scale=1)
arrows2 = plt.quiver(x2[:-1], y2[:-1], deltaX2, deltaY2, scale_units='xy', angles='xy', scale=1)
arrows3 = plt.quiver(x3[:-1], y3[:-1], deltaX3, deltaY3, scale_units='xy', angles='xy', scale=1)
arrows4 = plt.quiver(x4[:-1], y4[:-1], deltaX4, deltaY4, scale_units='xy', angles='xy', scale=1)

plt.title("Flow")
plt.ylabel("Speed")
plt.xlabel("Size")

plt.legend()

plt.show()

Answer: To prevent the double plotting in the other answers, you can specify the arrow colour directly. Also, since you are plotting four times it would be easier to do it in a loop.
xx = [median_a, median_b, median_c, median_d]
yy = [median1, median2, median3, median4]
colors = ['b', 'g', 'k', 'r']

for idx, (x, y) in enumerate(zip(xx, yy)):
    Q = plt.quiver(x[:-1], y[:-1], x[1:]-x[:-1], y[1:]-y[:-1], color=colors[idx], scale_units='xy', angles='xy', scale=1)
    plt.quiverkey(Q, 0.95, 1-idx/10, 0.05, label=f'B{idx}', labelpos='N')

plt.title("Flow")
plt.ylabel("Speed")
plt.xlabel("Size")

plt.show()


Run docker in pre-exisiting network namespaces

Question: I need to run a docker in a pre-existing namespace, which wasn't created by docker infrastructure. Is it possible to do ? I am aware of reusing another container option but as I mentioned the pre-existing ns wasn't created by one ( so answer to this question is irrelevant). I need solution for Linux.
Answer: Edit your docker systemd unit file, you can find it via systemctl status docker.service

● docker.service - Docker Application Container Engine
Loaded: loaded (/usr/lib/systemd/system/docker.service; disabled; preset: disabled)

Modify the [Service] part of the unit file /usr/lib/systemd/system/docker.service:
[Service]
Type=notify
# This tells systemd to run dockerd in the network namespace
NetworkNamespacePath=/run/netns/ns_name
# This is the original docker command, it caused some issues for me
#ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
# This is the replacement if the default exec doesn't work
ExecStart=/usr/bin/dockerd -H fd://
ExecReload=/bin/kill -s HUP $MAINPID
TimeoutStartSec=0
RestartSec=2
Restart=always

Now refresh the configs and start docker with
systemctl daemon-reload
systemctl restart docker

If you're lucky, you can now try running a docker container and it will just work. However, sometimes the configuration between containerd and docker doesn't work as smoothly and you will get the following error:

Error response from daemon: failed to create task for container:
failed to create shim task: OCI runtime create failed: runc create
failed: unable to start container process: exec: "/sbin/tini": stat
/sbin/tini: no such file or directory: unknown

This error appears to be from a misconfiguration between containerd and docker.
Open the containerd unit file and replace its ExecStart with the following:
ExecStart=/usr/bin/containerd --config=/var/run/docker/containerd/containerd.toml

This will tell containerd to use docker's configuration and your containers should work after you reload the configs restart all the services.
Frankly, it is easier to just reboot the machine at this point.
As for what this does, we get an interesting series of effects.

The docker executable talks to dockerd via a unix socket, so it does not matter what namespace you run docker or docker-compose commands from, as long as the socket is accessible.
containerd is running in the default network namespace, which has all of the proper cgroups to create containers.
dockerd is running inside your namespace, so it will create all network interfaces inside this namespace and all container networks will be generated inside this namespace by default.

As a final note, unless you setup a service to create your network namespace on boot, you will probably want to leave docker disabled and have a startup script create the namespace and then start docker.
In addition, you may need to run chattr +i on your unit files to prevent updates from overwriting your config changes.
Comment: I think the OP really meant he wanted a docker container to use an existing netns. I don't see how placing the docker daemon into one help. (If it does, wouldn't all containers be sharing one netns? Which would be a total mess?)


mongodb import error using makefile

Question: I'm trying to use mongoimport to import multiple collections. I do that in a .sh file "seed.sh" which contains the following :
mongoimport --db blog --collection users --file ./db/users.json --jsonArray
mongoimport --db blog --collection articles --file ./db/articles.json --jsonArray

I use makefile in cygwin64 terminal. The first import always fails. The second always succeeds. This holds true if I change the order of the collection that is being imported. I receive the error "Error parsing command line: unknown option jsonArray". What is the problem here?
Comment: try running it outside the script??
Answer: The problem is that your seed.sh file currently has CRLF line ending. Convert to LF line ending for seed.sh to work properly.
Answer: The problem is because of CR LF and LF characters line ending. Windows uses CR LF while Unix uses LF.
Now changing those two lines of yours to mongoimport --db blog --collection users --file ./db/users.json --jsonArray && mongoimport --db blog --collection articles --file ./db/articles.json --jsonArray will probably solve your problem.
for more information about line endings please refer to this stackoverflow post.

mongodb import error using makefile


EmptyStackException at java

Question: while i am running the below source  code
import java.util.Stack;
public class Assignment3 {

boolean conflict, complete = false;

public static int solve(int n) {

    int solution = 0;
    int nextQueen = 0;
    boolean problem = false;
    s.push(0);
    do{
      for(int i = 0; i < s.size(); i++)
      {
        if(s.get(i) == nextQueen){
          problem = true;
          break;
        }
        else if(s.get(i) - i == nextQueen - s.size()){
          problem = true;
          break;
        }
        else if(s.get(i) + i == nextQueen + s.size()){
          problem = true;
          break;
        }
      }
      if(problem = false){
        s.push(nextQueen);
        nextQueen = 0;}
      else{
        nextQueen++;
      }
      if(nextQueen == n){
        if(s.peek() == n){
          s.pop();
          nextQueen = s.pop()+ 1;
        }
        else{
          nextQueen = s.pop()+ 1;
        }
      }
      }while(s.size() != n);

      printSolution(s);
      solution++;
      return solution;
      }

    private static void printSolution(Stack<Integer> s) {
      for (int i = 0; i < s.size(); i ++) {
        for (int j = 0; j < s.size(); j ++) {
          if (j == s.get(i))
            System.out.print("Q ");
          else
            System.out.print("* ");
        }
        System.out.println();
      }
      System.out.println();
    }

    // ----- the main method -----
    // (you shouldn't need to change this method)
    public static void main(String[] args) {

      int n = 8;

      // pass in parameter n from command line
      if (args.length == 1) {
        n = Integer.parseInt(args[0].trim());
        if (n < 1) {
          System.out.println("Incorrect parameter");
          System.exit(-1);
        }//if
      }//if

      int number = solve(n);
      System.out.println("There are " + number + " solutions to the " + n + "-queens problem.");
    }
}

Getting the following error. Help me to clear :
Exception in thread "main" java.util.EmptyStackException
        at java.util.Stack.peek(Stack.java:79)
        at Assignment3.solve(Assignment3.java:40)
        at Assignment3.main(Assignment3.java:87)

Comment: What's your question?
Comment: Well, `problem = false` is just wrong, but that's not really what's breaking you.  It's still worth fixing (and should be simplified to `!problem`).
Comment: Your `Stack` is empty at the time you are calling `[peek()]`(http://docs.oracle.com/javase/7/docs/api/java/util/Stack.html#peek())
Comment: Did you try running your code through a debugger. That would probably have shown you what's wrong with it...
Answer: As per the API documentation, peek() method will throw EmptyStackException, if the stack is empty.
You have to check whether the stack is empty or not before peek a value from it. There is a empty() method which return a boolean depends on the stack

Removes the object at the top of this stack and returns that object as
  the value of this function.
Returns:
The object at the top of this stack (the last item of the Vector
  object).
Throws:
EmptyStackException - if this stack is empty.
Answer: One possible cause could be that there is an if condition saying if(problem = false){ (actually it should be problem==false or even better !problem). The output of the statement problem = false will always be false hence the condition fails every time and nothing is added to the Stack (except for s.push(0) in the beginning). Now you are trying to pull (peek()) something from the Stack and the Stack is empty so you are getting the exception. Also it is best practice to always check if the stack is empty before pulling something from it. You can use Stack.isEmpty() for that purpose. I have not tested, but problem = false is definitely wrong.

EmptyStackException at java


Solving obtuse triangle given angles and 1 side

Question: This probably seems like a very basic question but it has been along time since I did any trigonometry...
I am trying to calculate the sides of an obtuse triangle given the 3 angles:
$$\angle A = 38.6642, \angle B = 136.56, \angle C = 4.775$$
and the side $a = 10.18$ (opposite $\angle A$).
I have tried the Sine Rule:
$$\frac{a}{\sin(A)} = \frac{b}{\sin(B)} = \frac{c}{\sin(C)}$$

thus yielding
$c = \sin(C) \cdot \dfrac{a}{\sin(A)}$ , but with the triangle I have, that gives me $-12.3948...$

What have I misunderstood? How can I calculate the sides?
Comment: What are you using for $\sin(A)$ and $\sin(C)$? Calculators have different modes for degrees and radians; software (such as spreasheets) often requires radians.
Comment: I am using MATLAB. Turns out the sin() function requires radians, a silly mistake, thanks for helping! To convert degrees to radians the degtorad() function can be used.
Comment: Type \sin x, \cos x, \tan x, \csc x, \sec x, and \cot x, respectively, when you are in math mode to obtain $\sin x$, $\cos x$, $\tan x$, $\csc x$, $\sec x$, and $\cot x$.  See this [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) on how to typeset mathematics on this site.
Answer: I was using MATLAB and the sin() function requires radians. To convert degrees to radians the degtorad() function can be used.
Comment: Or `sind`, `cosd`, etc.


Access SQL: select only records with one occurrence in combined field

Question: I have an access DB with address information in several tables.
I created an SQL statement to get the combined information out in a query, and that works.
My next step would be to get only the records with only one occurrence in the db but I can't seem to get it to work.
My code so far would return: (example)
combination lat/long postal_code letter_part house_number street name
123123               1234        aa          1            teststreet
123124               1234        aa          3            teststreet
123124               1234        aa          5            teststreet
123124               1234        aa          7            teststreet
123124               1234        aa          9            teststreet
123125               1234        aa          5            teststreet

I would like to extract only the first and last record since their combi only occurs once.
The combi field is not needed in the end result, just a way to try to get this to work.
My code:
SELECT
[Perceel.lengtegraad] & [Perceel.breedtegraad] As Combi,
Pcreeks.wijkcode,
Pcreeks.lettercombinatie,
[huisnr] & " " & [huisnr_bag_letter] & " " & [huisnr_bag_toevoeging] AS
HnrLetter,
Straat.straatnaam
FROM
(Provincies
INNER JOIN (Plaats
INNER JOIN ((Gemeente
INNER JOIN Pcreeks
ON
Gemeente.gemeenteid = Pcreeks.gemeenteid)
INNER JOIN Perceel
ON
Pcreeks.reeksid = Perceel.reeksid) ON (Gemeente.gemeenteid =
Plaats.gemeenteid) AND (Plaats.gemeenteid = Pcreeks.gemeenteid) AND
(Plaats.plaatsid = Pcreeks.plaatsid)) ON Provincies.provincicode =
Pcreeks.provinciecode) INNER JOIN Straat ON (Pcreeks.straatid =
Straat.straatid) AND (Plaats.plaatsid = Straat.plaatsid)
where Pcreeks.wijkcode = "1234" AND Pcreeks.lettercombinatie = "AA";

Any help would be appreciated
Comment: What is the primary key of `Perceel` table?

Did you try GROUP BY  / HAVING ?
Comment: Hi thanks for responding. Primary key of perceel is perceelid. When i put in a group by nothing seems to happen and if i put in having then access gives me an error (srry, REAL noob here :)
Answer: This is not most elegant but you can repeat same query to filter only groups having one element.
WHERE Combi IN (
  SELECT Combi FROM (<PASTE_YOUR_QURY_HERE>) AS something
  GROUP BY Combi
  HAVING count(*) = 1
)

PS. this is also not good for performance - you should modify the subquery to remove unnecessary joins).
Comment: Ok, I tried t simplify this to get my head around it... this code:
    SELECT Count([Perceel.lengtegraad] & [Perceel.breedtegraad]) AS
    aantal, Pcreeks.wijkcode, Pcreeks.lettercombinatie,
    [Perceel.lengtegraad] & [Perceel.breedtegraad] AS Combi
    FROM Perceel INNER JOIN Pcreeks ON Perceel.reeksid =
    Pcreeks.reeksid
    WHERE (((Pcreeks.wijkcode)="1234") AND
    ((Pcreeks.lettercombinatie)="AA"))
    GROUP BY Pcreeks.wijkcode, Pcreeks.lettercombinatie,
    Perceel.breedtegraad, Perceel.lengtegraad
    HAVING (((Count(Perceel.breedtegraad))<2));
Comment: Now i get one adress, but if i add a field, it goed back to all adresses in the 1234AA range..


How can I calculate the minimum number of moves needed in a game involving stacks?

Question: I'm currently programming a game, and I have been stuck on the following problem for a while.

The above figure is a set of stacks. The end-goal is to sort all items by color in the least possible number of moves. For a gameboard like above, computing the solution doesn't take long at all. The problem occurs when the board grows in size, with the maximum board being 8X8 (8 stacks, and 7 colors, with one empty stack) The final solution doesn't need to be exact, the main goal I have is something that's fairly close to the minimum number of moves.
In the above, there would be 6 possible moves:
(1 -> 3)  (2 -> 3)  (4 -> 3)  (2 -> 1)  (3 -> 1)  and (4 -> 1)
The algorithm I am currently using starts with all of the pieces sorted, and then works backwards to generate the game state.
I currently have a scoring function in place.
<code># The reversed order of the stacks, with R = Red, Y = Yellow, G = Green, and 0 = Empty
gameFinalState = Set( [R, 0, 0, 0], [Y, G, R, Y], [Y, Y, R, 0], [G, G, G, R] )

# The win state, which I will backtrack from (Also in reverse order)
gameCurrentState = Set ( [R, R, R, R], [Y, Y, Y, Y], [G, G, G, G], [0, 0, 0, 0] )

finalScore = 0

while numberOfStacksIn(gameCurrentState) > 0 {
    topScore = -1
    finalS = None
    currentS = None
    for each finalStack in gameFinalState {
        for integer i = 1 to numberOfItemsInStack(stack) {
            # Empty stacks have no score, and since they are in reverse order,
            # if the first element is empty they all are empty
            if Set(stack_1, stack_2, ... stack_i) != Set(0) {
                for each currentStack in gameCurrentState {
                    # if there are i elements that are in the correct order of some finalStack
                    if [finalStack[1], ... finalStack[i]] == [currentStack[1], ... currentStack[i]] {
                        # If every element is in the right order
                        if i == numberOfItemsInStack {
                            # This is the highest possible score a stack can have
                            topScore = i
                            finalS = finalStack
                            currentS = currentStack
                        } else {
                              # If the stack score is equal to the current highest scoring stack
                              if i == topScore {
                                  # A tiebreaker, that scores stacks that have the correct elements and
                                  # empty spaces since it only takes 1 move to move the
                                  # "next correct piece" to the stack, and there is no additional move to
                                  # remove an incorrect piece
                                  if currentS[i+1] == 0 {
                                      topScore = i
                                      finalS = finalStack
                                      currentS = currentStack
                                  }
                                # If the stack score is greater than the highest scoring stack
                              } else if i > topScore {
                                     topScore = i
                                     finalS = finalStack
                                     currentS = currentStack
                              }
                        }
                   # If the top score is still -1 (every stack has the wrong bottom piece)
                   } else if topScore == -1 {
                       topScore = 0
                       finalS = finalStack
                       currentS = currentStack
                   }
                }
            }
        }
    }
    # Add the topScore to the final score
    finalScore = finalScore + topScore
    # Remove the state that corresponds to the topScore from the gameFinalState set
    gameFinalState = gameFinalState - finalS
    # Remove the state that correspons to the topScore from the gameCurrentState set
    gameCurrentState = gameCurrentState - currentS

    # If there is only one element left and it is the empty stack, remove the element
    if numberOfItemsIn(gameCurrentState) == 1  and Set(0) in gameCurrentState {
        gameCurrentState = gameCurrentState - Set(0)
    }
}
</code>
This assigns each specific game state a score. I start by generating every possible move from game state one. (From state one in a 4X4 playing field, this is 3 possible moves.)
Each move is scored, and then all of the top scoring moves go on to the next round, this doesn't always lead to a minimum score however, and sometimes it becomes cyclic. In order to combat this, I also take a random sample of ~50 game states from the next 3 highest scoring sets. For a 4X4 game, this works great, and runs in milliseconds. When the game increases in size, the time complexity grows exponentially.
Are there any edge-cases I'm missing that might speed this up, or perhaps some algorithm that already exists for solving this problem?
I think the approach I'm taking is decent, but the appearance of cycles has me wondering if I can translate this into a graph problem, and use something like Dijkstra's algorithm on it.
Answer: Yes, you can formulate this as an $s$-$t$ shortest path problem in a directed graph with a node for each state and an arc from node $i$ to node $j$ for each possible transition.  The starting state is the source node $s$, but you have multiple ending states.  Introduce a dummy sink node $t$, and for each ending state, introduce an arc to $t$.  Now apply Dijkstra's algorithm.
Comment: Since there are no edge weights, this boils down to breadth-first search, which is going to have exponentially many nodes to consider even for relatively small instances of the problem...
Comment: Wouldn't creating a directed graph with a node for every state still be absurdly large? For 16 boxes with 4 items each you'd have 16!/(4!*4!*4!*4!) which is still 63,000,000 nodes for just the 4X4?
Comment: Yes, the number of nodes could be large.  I guess you need only the nodes that are reachable from the source, but as @MishaLavrov mentioned, that could still be too big.


What is the difference between accuracy and precision?

Question: I read the material on the difference betweeen accuracy and precision, but it makes me feel confused. Can I define accuracy as:
\begin{equation}
accuracy=\frac{TruePositive+TrueNegative}{TruePositive+TrueNegative+FalsePositive+FlaseNegative}
\end{equation}
So in machine learning, what is the difference between accuracy and precision?
Comment: [This picture](https://www.google.com/#q=accuracy+precision+bullseye) is a good way to internalize the difference. (In machine learning, accuracy vs. precision is actually analogous to bias vs. variance, if you are familiar with that.)
Comment: Aaah, now I see your confusion. "Accuracy" and "precision" are general terms throughout science (and have the sense indicated by the bullseye diagrams I linked to before). However in the *particular* context of [Binary Classification](https://en.wikipedia.org/wiki/Evaluation_of_binary_classifiers) these terms have very specific definitions. The chart at that Wikipedia page gives these. (Note that this context is more specialized than just "machine learning".)
Comment: @GeoMatt22, thank you, can I define accuracy as :\begin{equation}
accuracy=\frac{TruePositive+TrueNegative}{TruePositive+TrueNegative+FalsePositive+FlaseNegative}
\end{equation}
Comment: Just for reference, I made my comments into an answer. (We have far too many "unanswered questions" already that are answered in the comments!)
Answer: (Just for reference, I am posting my comments as an answer. Note that the first version of the question did not include the formula.)
"Accuracy" and "precision" are general terms throughout science. A good way to internalize the difference are the common "bullseye diagrams". In machine learning/statistics as a whole, accuracy vs. precision is analogous to bias vs. variance.
However in the particular context of Binary Classification* these terms have very specific definitions. The chart at that Wikipedia page gives these, which are
$$\mathrm{Accuracy}=\frac{\mathrm{True}}{\mathrm{Total}} \text{ , }
\mathrm{Precision}=\frac{\mathrm{True\;Positive}}{\mathrm{All\;Positive}}
$$
i.e. the fraction of cases that are correctly classified vs. the fraction of positives that are true.
(*Note that this context is much more specialized than simply "machine learning".)


How to get 2 or more LinearRegionItem to overlap each other

Question: I have added 2 LinearRegionItems to a pyqtgraph plot. When I move the boundary of 1 over the other, the boundary never overlaps the other.
I would like to know how to allow overlapping. This is a functionality that I need, where I am selecting different regions of the data plot to be used later on.
Answer: Sorry, there was a bug in my code which was handling the case where a part of one LinearRegionItem overlapped with another LinearRegionItem.
Now I see that one linearRegionItem can lie on top of another one.
Consider this solved


Which test to use to compare non-normal distributed data sets with a small sample size?

Question: So I have several data sets, but each data set consists of only 7 values. I know some of the data sets are non-normal distributed, so my idea was first to do a Wilcoxon Signed Rank Test. But doing it (in python) it tells me, that my sample size is quite too small. They suggest n > 20, and as stated, I only have 7 for each data set.
So is there another test I could use instead ?
EDIT:
I will describe the data a bit here.
So I am comparing two treatment options. For both options some data is collected about how good and bad the treatment is. In addition, this treatment is performed once every week (7 weeks = the 7 values I mentioned) where new data is collected to see if something changes.
So I have several data points for each patient and each treatment, which contains the effectiveness/side effects of the treatment. These different data points/values I have 7 of since they are performed one time each week.
So basically I end up with data looking like:
<code>Patient 1, treatment 1:

        Side effect 1    Side effect 2    Effectiveness 1    Effectiveness 2
Week 1     x-value          x-value           x-value            x-value
Week 2     x-value          x-value           x-value            x-value
Week 3     x-value          x-value           x-value            x-value
Week 4     x-value          x-value           x-value            x-value
Week 5     x-value          x-value           x-value            x-value
Week 6     x-value          x-value           x-value            x-value
Week 7     x-value          x-value           x-value            x-value

Patient 1, treatment 2:

        Side effect 1    Side effect 2    Effectiveness 1    Effectiveness 2
Week 1     x-value          x-value           x-value            x-value
Week 2     x-value          x-value           x-value            x-value
Week 3     x-value          x-value           x-value            x-value
Week 4     x-value          x-value           x-value            x-value
Week 5     x-value          x-value           x-value            x-value
Week 6     x-value          x-value           x-value            x-value
Week 7     x-value          x-value           x-value            x-value
</code>
So I'm guessing I have to do some statistics on both how it changes from week to week, and then if one treatment is better than the other ?
Comment: What are you trying to compare?  Means? Medians? Something else?
Comment: Are your data paired? Can you explain more about what the values are? (e.g. counts? proportions? Likert scales? measurements? times?)
Comment: I have edited my original post. Hopefully this would make it a bit clearer.
Answer: I agree with Tilefish Poele that you may not be approaching your problem entirely constructively. From your description of the data I understand your situation to be a cross-over design with repeated measures per research unit. This basically means that you have 2 levels of dependency in your data:

The same individual having multiple treatments
Several measures per individual within treatment

This is a more or less standard situation for mixed modelling (extension of ANOVA). There are several ways to perform such analyses: The two most common ones are marginal models (in SAS this would correspond to using the REPEATED statement in PROC MIXED) and random effects models (using the RANDOM statement in PROC MIXED). Sometimes results will differ between these two modelling approaches, but in general they give very similar results. Other statistical software have different functions/procedures/parameters corresponding to the same choice of analysis. If you aren't familiar with these modelling types in your language of choice, then remember: Google is your friend :)
In the title of your question, you are concerned with normality. Don't be. ANOVA and mixed models aren't really that sensitive to deviations from normality. And, after all, it's not the raw data that should be normally distributed - it's the residuals! And these can (and indeed should!) be monitored post analysis to check for irregularities.
If your residual distributions are really messed up, there's a quite beautiful trick to perform a similar analysis in a non-parametric fashion: Rank transform your original data and run the exact same analysis.
HTH HAND
Carl
Answer: I think you're looking at this problem the wrong way. You don't really have 7 data points as the x-values at each week aren't necessarily what you want to draw conclusions on. You really want to draw conclusions on the treatments I'm assuming. Therefore define the time interval you're curious about (maybe the difference in x-values from week 1 to week 7), then form two groups for patients receiving treatment 1 vs. treatment 2. Then you can do a simple ANOVA test.
Comment: So you would not compare each x-value in the same column, but just compare the x-value from treatment 1 with treatment 2 ?
Comment: Essentially yeah so you can draw conclusions on the effects of the treatment right? It wouldn't just be the x-value though, since if a treatment works it would be the change in x-value which would change i.e. the effectiveness at week 1 vs at week 7
Comment: I do think the main target is to figure out which treatment is the better option. I just thought that an ANOVA test would be insufficient. So a one way ANOVA would be the way to go ?
Comment: Why do you think it would be insufficient?
Comment: Because ANOVA is used to see differences among group means, and not looking at the difference in x-value1-treatment1 vs x-value1-treatment2 - if I'm not mistaken. Like the Wilcoxon test does. And least that was my assumption at that time...
Comment: Can you not form groups with the differences for treatment 1 and treatment 2, and get their means?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/65283/discussion-between-denver-dang-and-tilefish-poele).


Singleton pattern implementation from Wikipedia

Question: I am referring to the solution for the Singleton Pattern by Bill Pugh on Wikipedia:
public class Singleton
{

    // Private constructor prevents instantiation from other classes

    private Singleton() {}

     /**
    * SingletonHolder is loaded on the first execution of Singleton.getInstance()
    * or the first access to SingletonHolder.INSTANCE, not before.
    */

    private static class SingletonHolder
    {

        private static final Singleton INSTANCE = new Singleton();
    }

   public static Singleton getInstance()
   {

       return SingletonHolder.INSTANCE;
   }

}

Here they have mentioned:

The inner class is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that getInstance() is called. Thus, this solution is thread-safe without requiring special language constructs (i.e. volatile or synchronized).

However, isn't there a possibility that 2 threads would call getInstance() at the same time, which would lead to two instances of singleton being created? Isn't it safe to use synchronized here? If yes, where should it be used in the code?
Comment: Why does everyone respond to every question about Singleton with "Don't use Singleton", etc?  His question is perfectly valid and was not about whether it's the correct design pattern to use for X case.
Comment: One very simple solution is to avoid the Singleton pattern. It introduces global data and tight coupling into your application, and makes unit testing difficult. Instead, look at Dependency Injection.
Comment: danben: Because singletons do so much damage?
Comment: This would be better suited for the discussion page on wikipedia, than for SO!
Comment: If you see someone doing something unbelievably stupid and damaging, possibly encouraging other people, I think it is irresponsible to say nothing.
Comment: @Tom Hawtin - tackline: Regardless, that was not the point of the question.
Answer: See the "How it works", in the article "Initialization on demand holder idiom" linked from the same section.
In a nutshell, here's what happens when you call getInstance() the first time:

The JVM sees a reference to SingletonHolder it has never seen referenced before.
Execution is paused while it initializes SingletonHolder.  This includes running any static initialization, which includes the singleton instance.
Execution resumes.  Any other threads calling getInstance() at the same time will see that SingletonHolder is already initialized.  The Java spec guarantees that class initialization is thread-safe.
Answer: The JLS guarantees the JVM will not initialize instance until someone calls getInstance(); and that will be thread safe because it would happen during the class initialization of SingletonHolder.
However, since Java 5, the preferred approach involves Enum:
// Enum singleton - the preferred approach
public enum Elvis {
    INSTANCE;

    public void leaveTheBuilding() { ... }
}

Reference: Implementing the singleton pattern in Java
Answer: Here is the explanation from Wikipedia on this phenomenon (emphasis mine):

When the class Something is loaded by
  the JVM, the class goes through
  initialization. Since the class does
  not have any static variables to
  initialize, the initialization
  completes trivially. The static class
  definition LazyHolder within it is not
  initialized until the JVM determines
  that LazyHolder must be executed. The
  static class LazyHolder is only
  executed when the static method
  getInstance is invoked on the class
  Something, and the first time this
  happens the JVM will load and
  initialize the LazyHolder class. The
  initialization of the LazyHolder class
  results in static variable something
  being initialized by executing the
  (private) constructor for the outer
  class Something. Since the class
  initialization phase is guaranteed by
  the JLS to be serial, i.e.,
  non-concurrent, no further
  synchronization is required in the
  static getInstance method during
  loading and initialization. And since
  the initialization phase writes the
  static variable something in a serial
  operation, all subsequent concurrent
  invocations of the getInstance will
  return the same correctly initialized
  something without incurring any
  additional synchronization overhead.

So in your example, Singleton is "LazyHolder" and SingletonHolder is "Something".  Calling getInstance() twice will not cause a race condition due to the JLS guarantees.
Answer: I think the idea is that Java guarantees that a class can only be initialized once, so implicitly only the first thread to access would cause this to happen
Answer: The Singleton is created when Singleton.getInstance() is called at this time the INSTANCE will be instantiated.
Synchronization depends on a conrete implementation, since there are no values to modify (in this example) no synchronization is required.
Answer: There are two differences here that need to be noted. The first is the Singleton design pattern and the other is a singleton instance.
The Singleton design pattern is problematic due to the fact that the design pattern represents a singleton instance as is implemented using static state (which is a bad thing for a variety of reasons - especially with unit testing). The second is an instance for which there is only one instance, no matter what (like the JVM singleton implemented as an enum).
The enum version is definitely superior, when compared to the Singleton pattern.
If you don't want to implement all instances as enum instances, then you should think about using Dependency Injection (frameworks such as Google Guice) to manage the singleton instances for the application.
Answer: This idiom is known as the Initialization on Demand Holder (IODH) idiom and is discussed in Item 48 of Effective Java as reminded by Bob Lee in his great post about Lazy Loading Singletons:

Item 48: Synchronize access to shared mutable data
(...)
The initialize-on-demand holder
  class idiom is appropriate for use
  when a static field is expensive to
  initialize and may not be needed, but
  will be used intensively if it is
  needed. This idiom is shown below:
// The initialize-on-demand holder class idiom
private static class FooHolder {
     static final Foo foo = new Foo();
}
public static Foo getFoo() { return FooHolder.foo; }

The idiom takes advantage of the
  guarantee that a class will not be
  initialized until it is used [JLS,
  12.4.1]. When the getFoo method is
  invoked for the first time, it reads
  the field FooHolder.foo, causing the
  FooHolder class to get initialized.
  The beauty of this idiom is that the
  getFoo method is not synchronized
  and performs only a field access, so
  lazy initialization adds practically
  nothing to the cost of access. The
  only shortcoming of the idiom is that
  it does not work for instance fields,
  only for static fields.

However, in the Second Edition of Effective Java, Joshua explains how enums can be (ab)used for writing a serializable Singleton (this should be the preferred way with Java 5):

As of release 1.5, there is a third approach to implementing singletons. Simply
  make an enum type with one element:
// Enum singleton - the preferred approach
public enum Elvis {
     INSTANCE;
     public void leaveTheBuilding() { ... }
}

This approach is functionally equivalent to the public field approach, except that it
  is more concise, provides the serialization machinery for free, and provides an
  ironclad guarantee against multiple instantiation, even in the face of sophisticated
  serialization or reflection attacks. While this approach has yet to be widely
  adopted, a single-element enum type is the best way to implement a singleton.


Objects tracking in realtime with OpenCv multitracker

Question: I am using Opencv (Python) default trackers in an object detection and tracking task. As far as I know, we need to initialize some bounding boxes in order to make our trackers work so a detection algorithm will handle this task for us. The problem is if one (or even more) object was not detected in the initializing phase, the trackers will have to deal with it. The simplest solution is to perform the detection algorithm several times through frames to make sure that all objects are included, which is probably very computationally expensive.
I wonder if there exists an effective way to deal with this problem?
Answer: Most people do it manually on the first frame using the cv2.selectROI() method, which returns a bounding box. This is described in some detail here:
https://www.learnopencv.com/multitracker-multiple-object-tracking-using-opencv-c-python/
For cases where that is not practical (e.g., thousands of objects), you can automate the object detection part, and just make sure you find a good frame to start with that gets things right.


Partial derivative evaluated at optimum of function

Question: If I take the partial derivative evaluated at the optimum of the function $f(\cdot)$ with respect to $x$, written as $$\frac{\partial f(x,y^*(x))}{\partial x} \quad \textrm{or} \quad \frac{\partial f(x,y)}{\partial x}\biggr\rvert_{y=y^*(x)}$$ where $y^*(x)$ is the value of the $y$ at the optimum, then do I take the partial derivative with respect to $x$, holding $y$ fixed, and then evaluate at $y(x)$, or do I first evaluate at $y(x)$ and then take the partial derivative with respect $x$?
Answer: You take the partial derivative with respect to $x$ only. Notice even the name implies it - partial.
BTW - why do you call this $y^*(x)$? The optimal argument $y^*$ is independent of $x$, unless you perform some sort of partial optimization. But in that case you have converted $x$ to a parameter, not a variable, and you find an optimal $y$ for different functions that depend on a pre-defined $x$ value.
If you have a specific function to share it might help to present it.


Related limits of a function.

Question:
Let $f:[0,\infty]\rightarrow \mathbb{R}$ a bounded function in each bounded interval. If $\lim_{x\rightarrow \infty} [f(x+1)-f(x)]=L$ then prove that $\lim_{x\rightarrow \infty}\displaystyle\frac{f(x)}{x}=L$

I appreciate any hint to solve this problem.
Thanks a lot!
Answer: For any $a > 0$:
  Let $y$ be such that $f(x+1) - f(x) \in L + [-a,a]$ for any $x \ge y$
  Then $f(y+t+k) - f(y+t) \in k ( L + [-a,a] )$ for any $k \in \mathbb{N}$ and $t \in [0,1]$
  Also $f(y+t)$ is bounded over all $t \in [0,1]$
  Thus ${\large \frac{f(y+t+k)}{y+t+k} } \in {\large \frac{f(y+t)+k(L+[-a,a])}{y+t+k} } \to L+[-a,a]$ uniformly for all $t \in [0,1]$ as $k \to \infty$
  Thus ${ \large \frac{f(x)}{x} } \in L + [-2a,2a]$ as $x \to \infty$
Therefore ${ \large \frac{f(x)}{x} } \to L$ as $x \to \infty$

To explain what happens in the last two lines inside "For any $a>0$", we basically have $\large\frac{p(t)+k(L+q(t))}{y+t+k}$ for some $p$ that is bounded on $[0,1]$ and $q$ that is in $[-a,a]$. As $k$ increases, $p(t)$ becomes insignificant because it is bounded, and also $\frac{k}{y+t+k}$ approaches 1 uniformly over all $t \in [0,1]$, hence the expression approaches something in $L+[-a,a]$ uniformly over all $t \in [0,1]$. "Uniformly" means that for any desired margin of error there is a common cutoff point for $k$ beyond which the expression is within the error margin for all $t$. The next line follows from this because eventually the expression will be within $a$ of $L+[-a,a]$.
Comment: I'll edit to expand what I wrote to clarify the other two lines.
Comment: I get lose in your proof. I don't get it.
Comment: Which lines do you not get?
Comment: In the second line:
Why $f(y+t+k)-f(y+t)\in k(L+[-a,a]$? Why do you only "multiply" the interval?
In the fourth and fifth: Why this is true? Why the fifth follow from the fourh?
The others lines are "clear" :P
Comment: To get the second line, use induction on $k$. $f(x+1)-f(x)$, $f(x+2)-f(x+1)$, ... all differ by some amount in $L+[-a,a]$.
Answer: This is another proof:
Given $\epsilon>0$ there exist $y>0$ such that if $x>y$ then:
$$L-\epsilon<f(x+1)-f(x)<L+\epsilon$$
we can conclude the following inequalytis valid for every $n$
$$L-\epsilon<f(x+2)-f(x+1)<L+\epsilon$$
$$L-\epsilon<f(x+2)-f(x+1)<L+\epsilon$$
$$\vdots$$
$$L-\epsilon<f(x+n)-f(x+n-1)<L+\epsilon$$
adding each of this inequalitys
$$nL-n\epsilon<f(x+n)-f(x)<nL+n\epsilon $$
taken $n=[x]$ and $h(x)=x-[x]$ then
$$[x]L-[x]\epsilon<f(x)-f(h(x))<[x]L+[x]\epsilon $$
since $0\leq h(x) <1$ and $[0,1)$ is bounded, then there exist $M>0$ such that $|f(h(x))|<M$. This implies that $\lim_{x\rightarrow\infty}\displaystyle\frac{f(h(x))}{x}=0$. Dividing by $x$:
$$\displaystyle\frac{[x]}{x}L-\displaystyle\frac{[x]}{x}\epsilon<\displaystyle\frac{f(x)-f(h(x))}{x}<\displaystyle\frac{[x]}{x}L+\displaystyle\frac{[x]}{x}\epsilon $$
and recalling that $\lim_{x\rightarrow\infty}\displaystyle\frac{[x]}{x}=1$. We take  $x\rightarrow\infty$ then
$$L-\epsilon\leq\lim_{x\rightarrow\infty}\displaystyle\frac{f(x)}{x}\leq L+\epsilon$$
since $\epsilon>0$ is aritrary we get the result.
Comment: Your proof is wrong for two reasons. Firstly you cannot get down to $f(x) - f(x - \lfloor x \rfloor)$ since the inequality $f(x+1)-f(x)y$. Secondly you cannot claim that the limit of $\frac{f(x)}{x}$ exists at your second last line. All you can say is that it lies within some larger interval such as $L+[-2ε,2ε]$ like I showed already. Always keep in mind the scope; your second error arises because you did not see that your $y$ depends on $ε$ and hence you cannot 'unbind' $ε$ to obtain any limits while still within the scope of "for any $ε$: for some $y$".
Comment: Taken $k=[x-y]$ where $x=y+k+t$ and $m<|f(x-k)|c$: $\frac{k}{x} \in [1-ε,1]$ and $\frac{m}{x} \in [-ε,ε]$ and $\frac{M}{x} \in [-ε,ε]$", and hence: "for some $c$: for any $x>c$: $\frac{f(x)}{x} \in [1-ε,1] L + [1-ε,1] [-ε,ε] + [-ε,ε]$"...
Comment: ... which now is free of $y$, so it can be pulled out of the "for some $y$" scope, which leaves it in the outer "for any $ε>0$" scope. We now move out of that scope and see that we can make the right-hand side of the inner expression as close to $L$ as we want by instantiating sufficiently small $ε>0$. To be specific, we create a new scope "for any $d>0$:" and inside it construct a suitable $ε$ such that "$[1-ε,1] L + [1-ε,1] [-ε,ε] + [-ε,ε] \subset L + [-d,d]$", and then use the above statement to get: "for any $d>0$: for some $c$: for any $x>c$: $\frac{f(x)}{x} \in L + [-d,d]$, as desired.
Comment: On an unrelated note, use "\lfloor ... \rfloor" rather than "[...]" because some people use the latter for many other things including ceiling and it's quite confusing.
Comment: Oops three comments up I should have said "for some $c$: for any $x>max(c,y)$: $\frac{f(x)}{x} \in [1-ε,1] L + [1-ε,1] [-ε,ε] + [-ε,ε]$" which means that when you pull it out you have to use a new existentially quantified variable for $max(c,y)$.

Related limits of a function.


Controlling/selling node access by node reference?

Question: I have been using Drupal for many years now (starting with Drupal 6) and only recently - in the context of a big project - made the switch to D8. So far, working with D8 has been a very pleasant experience, to say the least. I was prepared, however, that there would be a few rocks on the road. And I would like to ask for help removing a big one (for me)...
In a nutshell, the situation is this: I am creating a kind of learning management system (LMS), with lessons, courses and classes. Each lesson belongs to exactly one course, but each courses may or may not belong to zero, one or more classes. I was thinking of using simple node references to structure this:

a field in the content type lesson that references the course that this lesson belongs to
and an entity reference field in the content type class that references all courses in this class (so, this is referenced the other way round)

Now, I'd like to sell access to each of these content types and my problem is this: If a user buys access to one of the classes, she should also be able to access all of the courses (and lessons) that are referenced by this class. So, when checking the access permissions for a single course, the system will not only have to check, if the user has bought this course, but also, if the user has access to a class that contains this course.
I was first thinking of solving this with the module Node access node reference, but this seems to work the other way round (and doesn't have a D8 version). Same for Access by Reference. (In general, most of the access control modules I looked at, don't seem to be ready for D8 yet.) But what about rule-based access control? Or groups?
Can anybody suggest a way forword?
Any help would be much appreciated.
Thanks in advance.
Answer: Why not go custom access the main thing is relating your "Class" or Item to the product the person buys aka on the product you could create a entity reference to the node or class or whatever  ...
you can do some thing like the following
use Drupal\Core\Access\AccessResult;
/**
* Implements hook_node_access().
*/
function mymodule_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account){
// Note thes checks do not work on admin (user 1). and clear cache each time.
$type = $node->bundle();
if ($type === 'your_content_type') {
  if ($account->id() !== 0) {
    $user = $account->getAccount();
    $uid = $user->id();
    // Ok we know is trying to access and the node type.
    $storage = \Drupal::entityTypeManager()->getStorage('commerce_order');
    $orders = $storage->loadByProperties(['uid' => $uid]);
    if (count($orders) != 0) {
      $has_bought = FALSE;

      // CUSTOM FIND Your Corse .
      $corse_type = $node->field_corse_type->value;
      foreach ($orders as $order) {
        $order_items = $order->order_items->referencedEntities();
        foreach ($order_items as $item) {
          // Do better than this lol ...
          // dump($item);
          if ($item->title->value == 'SOME Course' && $corse_type == 'SOMETHING RELATED TO PRODUCT') {
            $has_bought = TRUE;
        }
      }
    }
    // final check.
    if ($has_bought === TRUE) {
      return AccessResult::isAllowed();
    }
    else{
      // Kick them. as not bought.
      return AccessResult::forbidden();
    }
  }
  else {
    // Kick them. as not paid.
    return AccessResult::forbidden();
  }

  }
  else {
  // kick them.
  return AccessResult::forbidden();
  }
 }
 else {
  return AccessResult::neutral();
  }
}

Comment: Thank you very much for your detailed reply. I will have to do a bit of testing (frankly, I'm a bit at a loss as to how to combine this with Commerce, but I guess, I will be able to work that out), but at first glance the code seems to offer a good foundation for a solution. Much appreciated.


Register events

Question: I'm trying to register the DialogBoxShowing event of the UIControlledApplication. But I cannot use the OnStartup / OnShutdown implementation of the IExternalApplication interface. The best I could come up with is...
    public delegate void Handeler(object sender, DialogBoxShowingEventArgs e);

    public void RegesterDialogEvent(UIControlledApplication uicApp)
    {
        UIAppEventHandlers1 uaeh1 = new UIAppEventHandlers1();
        Handeler hdlr = new Handeler(UIAppEventHandlers1.UIAppEvent_DialogBoxShowing_Handler);

        uicApp.DialogBoxShowing += hdlr;

    }

But i'm getting the "Cannot implicitly convert type 'TaskDialogEvent_01.Form1.Handeler' to 'System.EventHandler Autodesk.Revit.UI.Events.DialogBoxShowingEventArgs> " error. My 'UIAppEventHandlers1' method has the same signature as the Handler. What am I doing wrong and can anyone provide an example? Thank you.
Answer: You probably want to use the uaeh1 instance you created:
UIAppEventHandlers1 uaeh1 = new UIAppEventHandlers1();
uicApp.DialogBoxShowing += uaeh1.UIAppEvent_DialogBoxShowing_Handler;

This is still weird because you just new'ed that object.
You say you can't just register/unregister in the app class as follows?
public Result OnStartup(UIControlledApplication app)
{
    app.DialogBoxShowing += OnDialogBoxShowing;
    return Result.Succeeded;
}

public Result OnShutdown(UIControlledApplication app)
{
    app.DialogBoxShowing -= OnDialogBoxShowing;
    return Result.Succeeded;
}

void OnDialogBoxShowing(object sender, DialogBoxShowingEventArgs args)
{
}

Handling dialogs with the DialogBoxShowing event isn't the best way in my experience. I would recommend looking into the newer failures processing API.

Register events


I can see my two means are different. What information can a t test add?

Question: Methods such as t-tests and anova find the difference between two means using a statistical method.
This seems strange to a beginner like me, one could simply find the mean of two groups and understand if they are different or not.
What is the intuition behind these methods ?
Comment: Hi Yash, welcome to CrossValidated.

If you calculate the means based on the observed data, you will observe that they are numerically different. However, when testing hypotheses we treat data as realizations of an underlying data generating process. Hence, it is more insightful to work with them as random variables.

As a result of treating them as random variables, we need to find ways to determine whether the observed difference in means reveals a statistical difference in the underlying parameters. T tests and Anova tests are examples of such measures.

I hope this helps.
Answer: This is a fundamental question about statistics, and every stats text will discuss. So I'll be brief.
The t test is not asking whether the means you observed in your sample are different. As you say, you can see those. The t test is more abstract. It asks about the population or distribution the data were sampled from. Given assumptions (normal distribution; equal standard deviations; random sampling...), the t test quantifies what can be known about the difference between the means of the populations (or distributions) the data were drawn from.
That may be too cryptic, but should point you to the right chapters in texts to read.
Comment: Thanks. I started reading on the lines of inferential statistics, makes more sense now.
Answer: You bring a good point. For some fields - such as neurobiology - statistical methods for hypothesis testing are often just supplementary to the purpose because they're based on causal data with causal manipulations. Assumptions are frequently broken, but the difference between groups is typically clear-cut and the results of the statistical tests reflect that. This is one reason why fields that use animal models can "get away with" using small samples.
But for most cases, you are not looking at dominantly causal designs and that approach is not recommended. Even in the case of a causal experimental design, the t-test is not redundant. It can help in understanding how your manipulation worked.
Building off of that and Harvey's point, I think that it would also be good to consider it in terms of the ability to measure how much a dependent variable is affected by the independent variable. A t-test doesn't just tell of a "significant difference" measured by the p-value. It is often more useful in using statistical tests to measure the extent to which your experimental manipulation (IV) explains the change in the DV, as measured by the partial eta squared value.
For a t-test example: hospital employees are randomly assigned to have a socialization break period (experimental group) or not have this break (control group) to see if and how it affects employee satisfaction ratings. The individual partial eta squared value for "break or no break" will represent the extent to which this break period explains the variance in satisfaction ratings. So a partial eta squared value of 0.137 would tell you that the break period can explain about 13.7% of the variance in our employee satisfaction ratings.
Hopefully that makes sense. I think that this StackExchange answer helps. It is not on exclusively t-tests, but the idea is pretty much the same.


Securing SSL certificate private key with nginx

Question: I've been researching how to secure privaye keys for SSL certificats using nginx as a webserver, but have not been able to find many satisfactory answers.
Specifically, for a client who wants to me to deploy a website under their own sub-domain, they are afraid that someone could access their sub-domain's certificate private key, and hence setup a legitimate-looking unsafe website. They have asked me to use some kind of software vault solution to secure they private key.
This article from nginx's blog as well as this one describe some solutions, but in the end they both rely on the same principle: the private key is protected by a passphrase, that we will retrieve from either a local or remote location, and this "retrieval" procedure requires a password/token.. that is stored locally.
Hence I fail to understand how the private key really gets more secure - it looks a bit like locking your frontdoor key in a keybox instead of leaving it under the mat... and then leaving the keybox key under the mat.
Am I missing something? Is there a better way to secure a private key with nginx?
Comment: If they are willing to point a sub domain record to your server, they have to implicitly trust you. Instead of stealing their key, you can also just use Let's Encrypt to generate a new one. There's no way around it: the server in question needs to contain the key. You haven't really made clear why this server can't be trusted.
Comment: Sorry if unclear - they do trust my server, what they are afraid of is that if a hacker compromises my server and steal the certificate and private key under their name, they could create a replica website, for phishing purpose for instance, and still get it to look like a "legit" website from their corporation. IMO it's only a real danger if the certificate they issue me is a wildcard certificate - which they shouldn't do - but as often in business, a client "is right" just because he's the client....
Comment: You may be interested in this article: https://www.nginx.com/blog/protecting-ssl-private-keys-nginx-hashicorp-vault/ which also mentions HSM as an option, but the other options are also about hardening against simple attacks
Answer: Based on your last comment, I see several options:

You show you have good SSH security, which can be IP whitelisted access, no password logins, etc.
You show the private key file is readable only to the root user and stored outside of the document root, for example, as common somewhere in <code>/etc/ssl</code>. Hacking a hosted website is much more common than the entire server, and that way, there is protection against it being read that way.
About the above point: careful of running docker containers; they typically run as root, and are, in my opinion, a security issue. Docker containers can run rootless (experimental), but images have to be designed specifically to do so. Most images you get elsewhere, depend on being root. Anything in it running as root can break the jail. (Edit: it indeed requires some nuance after re-evaluation. I should say, could break the jail. It does depend on some extra mechanisms being secure, that you otherwise wouldn't need to worry about.)
If they are really concerned, they should set up a reverse proxy to your server, and they can do the SSL termination on their end.

And about giving you an SSL certificate: they don't have to. You can just set up Letsencrypt. Added bonus is that those certificates are short lived.
Comment: I would definitely disagree, that properly configured containers are security issue. This is just personal opinion. We have NISM standards for Docker. They provide way broader isolation (process, resources and namespaces). Misconfigured containers might be a security issue, but as each service. Properly configured give better process isolation. Of course, not as much as virtualization, but still... better than nothing.
Comment: Docker containers *can* run as non-root, but images have to be designed specifically to do so. Most images you get elsewhere, depend on being root. Anything in it running as root can break the jail.
Comment: Thanks. FYI we can't use Letsencrypt certificates because they want to provide an EV certificate but I do agree a good access control and server security should be "good enough" for that specific risk. The reverse proxy is a very interesting solution (provided a VPN connection between the reverse proxy and our infrastructure is "sturdy" enough, as the machine used as RP would be in the client's infrastructure)
Comment: Do people still use EV certs? Browsers no longer show the whole company name from the certificate in the address bar, so I don't see the point of them anymore.
Comment: @Halfgaar, there is one. The two, actually. Business and prestige. Both badly understood. :)
Answer: There is one solution, but, indeed, it does not remove the need to trust your server.  If you Client is willing to put his record to your server, he has to trust you, somehow.  There is one solution that might protect your Client.

They point subdomain to Web Application Firewall, like Cloudflare. They create you an Origin certificate (the one that is on your server) and send you certificate and key, via trusted communication protocol, like GPG.
They point this subdomain to your servers IP address.
They do not give you access to their Cloudflare account.

Keeping all of that. They control Edge certificate. They control Origin certificate. They can always revoke it. They control their domain. The only thing, your Client does not control is of course your server. ;)
Of course, the whole security setup presented by @Halfgaar is still up to date.
————————————————————-
If you want to build trust, you can show audits from your server. Present audit logs. Prove that your servers security is compliant with standards, like NISM or STIGS.
Comment: Improve your Cloudflare account security by enabling 2 factor authentication.
Answer:
Everything is covered up by the comments and answers, I would just
like to add up, stealing the certificates alone is not enough. The
attacker also has to come up with valid domain for which the
certificate has been verified.
In case of phishing attacks the website might look the same but the
domain might not be the same, and the certificates won't work with
different domain.
Until the DNS is pointing correct IP, and DNS is not spoofed or
messed, stealing the SSL certificates is useless.
In this situation where client is somewhat in doubt,
you can use let's encrypt certificates which comes with less period
of validity (90 days). And have to be renewed regularly.
Obtaining and renewing Let's encrypt certificates needs domain
verification each time. So stealing the certificates won't be much useful for
long time.


Understanding the cycles $(12)(13)(14)$ and $(13)(1234)(13)$

Question: I need help in understanding the decomposition in disjoint cycles for the permutations $(1 2) (1 3) (1 4)$ and $(1 3)(1 2 3 4)(1 3)$ which has been listed in the solutions as $(1 4 3 2)$ in both cases.
For the first cycle all I can think of us that we start with the first factor $(1 4)$ and we say that $1 \to 4$ and then $4 \to 1$, which to my mind would have constituted a cycle in and of itself, but given the answer I guess we then can say that $1 \to 3$ and then $3 \to 1$ and then again that $1 \to 2$ and $2 \to 1$
So then would we continue on with a cycle even if it appears that the cycle is completed (returned to the original number) if that original number is used in another factor that is involved in the product? Like we see the number $1$ is in the product above. In other words we usually know that a cycle is completed when we return to the original number, but if in the process of returning to that original number we come back to it more than once we only complete the cycle when we return to it for the last time and disregard all the intermediate returns to that number? I find it difficult to articulate precisely what I mean, but I hope you understand what I'm asking.
For the 2nd cycle I tried to solve it by starting with $1 \to 3$ then $3 \to 4$ and then $4 \to 1$, which, since it's the last factor, would complete the cycle but then we get $(1 3 4)$ then we have $(1 3)(1 3 4)$ which I was not able to factor. I then remembered the associative rule was valid for cycles and tried that by doing $[(1 3)(1 2 3 4)](1 3)$ which just led me to $(1 3 4)(1 3)$ which I got $(1 3 4)$ obviously not correct. I must be missing something here. Any help in understanding where I am going wrong is very much appreciated.
Comment: The calculation goes like $(12)(13)(14)=f\circ g \circ h$ the consecutive application of three functions. You apply $h$ once, get the result into $g$ once, and finally $f$ once. That is $[(12)(13)(14)](1)=[(12)(13)] (14)(1)=[(12)(13)](4)=[(12)](13)(4)=[(12)](4)=(12)(4)=4.$ Then go for the next numbers in the domain:  $[(12)(13)(14)](2)=(12)(2)=1\, , \,$[(12)(13)(14)](3)=[(12)(13)](3)=(12)(1)=2$ etc.
Answer: I'm sharing this answer because your comment:

...$(134)(13) $ which I got $(134)$...

Is touching on a fun way to deal with elements of $S_n$, but you have to know that every element of $S_n$ can be written as a product of transpositions ($(ij)$ where $i\ne j$). See id* specifically for the property of transpositions that makes this so convenient.
So the first product can computed as follows, using only $(ijk)=(jki)$ and $(ij)(jk)=(ikj)$.
See:
\begin{align}
(1 2) (1 3) (1 4)& = (21) (1 3) (1 4)\\
&= (213)(14)\\
&= (321)(14)\\
&= (3214)\\
&=(1432)
\end{align}
and the following uses the fact that $(ij)(ij)=\text{id}.$ See:
\begin{align}
(1 3)(1 2 3 4)(1 3)&=  (1 3)(1 2 3)(3 4)(1 3)\\
&= (13)(312)(34)(13)\\
&=\underbrace{(13)(13)}_{\text{id*}}(12)(34)(13)\\
&=(12)(34)(13)\\
&=(12)(431)\\
&=(12)(143)\\
&=(2143)\\
&=(1432)
\end{align}
Answer: We proceed as follows:
$$\begin{align}
1&\xrightarrow{(14)}4\xrightarrow{(13)}4\xrightarrow{(12)}4\\
4&\xrightarrow{(14)}1\xrightarrow{(13)}3\xrightarrow{(12)}3\\
3&\xrightarrow{(14)}3\xrightarrow{(13)}1\xrightarrow{(12)}2\\
2&\xrightarrow{(14)}2\xrightarrow{(13)}2\xrightarrow{(12)}1
\end{align}$$
So the permutation is $(4321)$ which is equivalent to $(1432)$.
The other permutation is done similarly.
Comment: Thank you for this visualization. It has cleared up a lot of confusion on my end.
Comment: You're welcome, @KyleO'Connell.


Dúvida sobre Javascript ou jquery para collapse em viewport

Question: Criei um botão collapse "pesquisa avançada" para mobile (768px), gostaria que ele iniciasse fechado apenas na resolução 768px para ganhar espaço na tela.
Inicia atualmente assim:
<button type="button" data-toggle="collapse" data-target="#collapseExample" aria="" expanded="true" aria-controls="collapseExample" aria-expanded="true" class="btn btn-default btn-mob-block btn-sm btn-icon mb10 hidden-lg">
     Pesquisa Avançada
</button>

 Conteúdo da div a ser exibido...

Quando clico, ele fecha e assume essa propriedade, e é assim que eu gostaria que iniciasse na resolução 768px:
<button type="button" data-toggle="collapse" data-target="#collapseExample" aria="" expanded="true" aria-controls="collapseExample" aria-expanded="false" class="btn btn-default btn-mob-block btn-sm btn-icon mb10 hidden-lg collapsed">
    Pesquisa Avançada
</button>

 Conteúdo a ser exibido...

Comment: Vc está usando Bootstrap?
Comment: Estou usando Bootstrap sim.
Comment: Cara a pergunta não ficou muito clara, seu collpase já inicia fechado, se ele só aparece abaixo de 768px e já está fecha por padrão quando aparece eu não entendi a sua dúvida
Comment: A principio, nasce tudo aberto, o botão é para expandir o collapse no mobile. Tem que nascer fechado para ganhar espaço na tela.
Comment: hugocsl, re-editei a pergunta para ficar mais clara.
Comment: Ah, então ele aparece em telas menores que 768px e deve estar fechado, mas ele tb aparece em telas maiores que 768px e deve estar aberto é isso? Ou em telas maiores ele tb pode iniciar fechado?
Comment: Em telas menores fechado, em telas maiores aberto.
Utilizei a classe css hidden-lg para que o botão não apareça em telas maiores.
Answer: Veja se este código atende seu problema:
jQuery(function($){
    $("#collapseExample").removeClass('in');
    if ($(document).width() > 768) {
        $("#collapseExample").addClass('in');
    }
});

Comment: Funcionou perfeitamente! Obrigado.


Theme settings to include different PHP files into template

Question: I'm trying to include a template section into another template under conditions based on the themes settings.
page.tpl.php

    <?php
    $theme_header_style = theme_get_setting('header_style');//the value is 1
    $header_path = "header_tpl_".$theme_header_style.".php";
    include_once $header_path;//includes header_tpl_1.php
    ?>

<?php print $site_name; ?>

header_tpl_1.php

this will show up

<?php print $site_name; ?>

this will show up on page.tpl.php as well

I'm pulling in header_style from my themes settings and for this example the value is 1. The file it will include is being added, as the html from the file is displaying but any php in the file is being ignored. anything on page.tpl.php is working as expected its only the php content on included files like header_tpl_1.php that is not working.
Update
Now that I know using a PHP include doesn't work I would like to know how I could include the contents of the header_tpl_1.php into the template prior to Drupal rendering the page, as this clearly would be the solution. The end objective is being able to load different PHP files into page.tpl.php based on a value set in the themes settings. The code in my header_tmp_1.php was removed from page.tpl.php as working code and put into header_tpl_1.php so I know there are no errors in it, as it works if it's added directly into page.tpl.php. The problem is including content into a template. I need the content to be included prior to Drupal rendering the variables.
Comment: what are you trying to do?
Comment: i have files in my template directory "header_tpl_0.php", "header_top_1.php" and so on and depending on the selection made in the theme settings it will include that header section. each header section pulls in normal header data like site name, logo, breadcrumb, and so on. It works if its inside the page.tpl.php but not if its included.
Comment: It includes the file and shows the html but the php is not executed.
Comment: Templates are `eval`d, maybe a scope issue? This sort of decision should ideally be made in preprocess functions, then you wouldn't have an issue
Comment: Is there a tutorial for including sections of template into a tmp file.
Answer: Did you cleared cache ? I usually include header.inc, but I try your code and it worked on my site.
Comment: the file that you included did it try to print out drupal variables? I have cleared the cash multiple times. Its including the file. The html is showing up. the php drupal methods are not being executed.
Comment: for example if you put `` into your header_tpl_1.php file will it print out the site name?
Comment: If you need print variable on page template file, you should use hook [Hook preprocess page link](https://api.drupal.org/api/drupal/includes%21theme.inc/function/template_preprocess_page/7).

I print `` on this header_tpl_1.php and it worked nomarly.

- Code  : [Imgur image link](http://i.imgur.com/POh2hnx.jpg)
-  Demo :   [Imgur Image link](http://i.imgur.com/wRivZBP.jpg)
Comment: are you including header_tpl_1.php into page.tmp.php using a php include
Comment: Yes, see  First Image on my answer. i use your code `include_once $header_path;` to include header_tpl_1.php to page.tpl.php.  If HTML is showing up, it mean you include header_tpl_1.php success. But your variable maybe don't have value. You should test by print this vars on page.tpl.php
Comment: If variable cannot print on page.tpl.php, it's mean this vars didn't declare on hook_preprocess_page function.
Comment: the vars that are not printing are on `header_tpl_1.php` not `page.tpl.php` the include is adding the html from `header_tpl_1.php` into `page.tpl.php` but is not executing the php on `header_tpl_1.php`
Comment: Please paste your code of your header_tpl_1.php, i will check it.
Comment: I did. My question is a simple demonstration of what is going on. The calls that are being made in the header_tpl_1.php where once part of my page.tpl.php at one time and work. There is nothing wrong with the code it just will not work when its included. Its something to do with how php includes files that is the problem.


GDI+ Exception when using DrawString()

Question: I'm getting an error when trying to create a barcode image using a barcode font.  This is happening in production but not in dev.
The method creating the barcode is:
<code>/// <summary>
/// Create a barcode image by writing out a string using a barcode font and save it
/// </summary>
/// <param name="barcodeText">The text string of the barcode</param>
/// <param name="saveLocation">Where to save the file to</param>
/// <param name="font">The barcode font</param>
/// <param name="imageFormat">The image format</param>
private void CreateBarcodeImage(string barcodeText, string saveLocation, System.Drawing.Font font, ImageFormat imageFormat)
{
    // Draw the barcode image
    using (Bitmap bmp = new Bitmap(500, 75))
    {
    try
    {
        using (Graphics g = Graphics.FromImage(bmp))
        {
        g.Clear(_backgroundColour);
        g.DrawString(barcodeText, font, _foregroundBrush, 10, 0);
        bmp.Save(saveLocation, imageFormat);
        g.Dispose();
        }
    }
    catch (Exception ex)
    {
        Log.ErrorException("Exception in LabelPrinter.CreateBarcodeImage()", ex);
        throw;
    }
    }
}
</code>
This code is being called in a loop as several barcodes are needed.  In the dev environment it works fine but in live (on Win XP Pro using .net 3.5 SP1 in a winforms app), 2 barcodes are created and the exception is raised on the 3rd time.
The exception being raised & stack trace is:
<code>An unhandled exception has occurred Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at System.Drawing.SafeNativeMethods.Gdip.GdipMeasureString(HandleRef graphics, String textString, Int32 length, HandleRef font, GPRECTF& layoutRect, HandleRef stringFormat, GPRECTF& boundingBox, Int32& codepointsFitted, Int32& linesFilled)
at System.Drawing.Graphics.MeasureString(String text, Font font, SizeF layoutArea, StringFormat stringFormat)
at System.Drawing.Graphics.MeasureString(String text, Font font)
at Srcl.WasteTrak.Gui.Documents.LabelPrinter.CreateBarcodeImage(String barcodeText, String saveLocation, Font font, ImageFormat imageFormat)
in c:\scc\SRCL\SRCL.WasteTrak\SRCL.WasteTrak.Gui\Documents\LabelPrinter.cs:line 60
</code>
I can't find out what is causing the problem but from Google searches it appears to be calls into unmanaged code cause it, but i haven't found a solution.
Anyone?
Comment: did this occur on multiple computers or just one? (production) And did this work on multiple developer computers or just one? Did you ever manage to solve this?
Comment: Have you tried using a different font just to see if it makes any difference? You are calling .Dispose() twice on the Graphics object, btw.
Comment: Yeah, I've tried using a different font (the current one is a barcode font) and I've used another (normal) embedded font and also referenced a system font and still the same result.
the g.Dispose() has been taken out but still the same
Comment: The application is deployed by ClickOnce - I'm wondering if this is part of the issue at all
Comment: So you're saying that the problem remains even if you use a different font? Hm, have you made sure that the font isn't disposed when you draw with it? The same goes for _foregroundBrush.
Answer: Could you try removing following line
g.Dispose();
using statement will dispose it already.

GDI+ Exception when using DrawString()


Need to get a boolean value from XML using DataContractSerializer's ReadObject() method

Question: I have a simple XML document that I want to read into an object using the DataContractSerializer in .NET.
<Person>
<Enabled>true</Enabled>
<Name>John Smith</Name>
</Person>
When I read the object, the Enabled field is always false even though the node value is "true."  How does one define XML that will probably deserialize into a boolean true when ReadObject() is called?
Answer: It all depends on how you define your class. If you define it as follows, it should read correctly.
public class StackOverflow_8012009
{
    const string XML = "<Person><Enabled>true</Enabled><Name>John Smith</Name></Person>";
    [DataContract(Namespace = "", Name = "Person")]
    public class Person
    {
        [DataMember]
        public bool Enabled { get; set; }
        [DataMember]
        public string Name { get; set; }

        public override string ToString()
        {
            return string.Format("Person[Enabled={0},Name={1}]", this.Enabled, this.Name);
        }
    }
    public static void Test()
    {
        DataContractSerializer dcs = new DataContractSerializer(typeof(Person));
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(XML));
        object obj = dcs.ReadObject(ms);
        Console.WriteLine(obj);
    }
}


Perl regex - Find functions in C file and print their definitions

Question: -- UPDATED --
I want to find C functions in file and print their definitios
For example:
For this input:
#include <stdlib>

int function(int a)
{
    return a;
}

void func2()
{
    int b = 1;
}

int func3(int a,int b)
{
   a = a +b;
        while(x) {
            x--;
        }
   return a;
}

int main(int argc, char* argv[])
{
    int x=(a+1);
    return 0;
}

The output should be:
int function(int a);
void func2();
int func3(int a,int b);

This is my code:
#!/usr/bin/perl -w
open(FILE, "<", $ARGV[0]) or die "file open error";

if ( @ARGV ) #if there are args
{
    if ( -f $ARGV[0] ) #if its regular file
    {

    while(<FILE>)
      {
      if ($_ =~ /(.+)\s(.+)\(/){
      print $1; # type in arg $1
      print "\n";
      print $2; # name in arg $2
      print "\n";
    }
      }
    }
    else{
print "Arg is not a file\n";}
}
else{
print "no args\n";}

I end with function type in arg $1 and function name in $2. I want to get the full name and args in '()' brackets in $2. How to avoid 'main' word? the     '^[(main)] doesnt work. In the end I want to print it all with ';' at the end.
It needs to check for {} brackets to not print for example:    int x=(a+1);
Comment: You don't even have a slot for the arguments of the function?
Answer:
Try /(\S+)\s+(\S+\([^)]*\))/ and then print $1+$2+";\n".
To prevent main with negative lookahead:
/(\S+)\s+((?!main)\S+\([^)]*\))/

If lookahead is not supported:
/(\S+)\s+((m|ma|mai|[^m].*|m[^a].*|ma[^i].*|mai[^n].*)\([^)]*\))/

The part responsible for avoiding main:
(m|ma|mai|[^m].*|m[^a].*|ma[^i].*|mai[^n].*)

Comment: Good job. Can you do it with avoiding the 'main' word?
Comment: Does perl support lookahead?
Comment: `/(\S+)\s+((?!main)\S+\([^)]+\))/` Its avoiding main function very well, but doesn't print other functions than 'int' type. There is void function that should be printed too.
Comment: Worked when I changed last `+` into `*`. Void function was empty :)
Comment: @Piodo Thanks, fixed.
Comment: Oops, you're faster than me :p
Comment: I've updated the question. There are new errors. This code also prints the `int x=(a+1);` . It needs to check for {} brackets (and dont print while loop inside). Can you help me with that?
Comment: Yes, replace the `\S+` which checks for the **function name** by `[a-zA-Z_]+`.
Comment: Well, you can replace both `\S+` by that, it doesn't matter.
Comment: The variable still fits into [a-zA-Z_]+
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/111130/discussion-between-kenny-lau-and-piodo).


Gibb's sampling where target prob distribution is itself a conditional joint distribution - p(x,y|t)

Question:     I'm new to Gibb's sampling and need basic guidance. Say    p1,p2,q-> are Gaussian variables. p1->q<-p2 and q->x where x is a discrete variable (either 1 or 0). How do I go about Sampling (using Gibbs Sampling - a rough idea to begin) when the target distribution is p(p1,p2|x) given that x=1.
TIA.
Comment: @quester: dependencies
Comment: what means  p1->t<-p2 ?
Comment: @quester : Sorry I edited it now and added an image for better understanding.
Comment: this is some kind of process or by these arrows you indicate dependency?
Answer: I assume you sample vertors (p1, p2, q, x), gibbs sampling says "keep n-1 coordinates from last result and sample next coordinate" here I would add "keep x=1"