text:
Q: UPDATE table SET col = CONVERT(int, col) I am trying  this
UPDATE table
SET col =  CONVERT(int, col)

and i am getting

Msg 245, Level 16, State 1, Line 2
  Conversion failed when converting the varchar value '106/1' to data type int.

A: If 2012+, you can use TRY_CONVERT()  ... invalid would return NULL
UPDATE table SET col = TRY_CONVERT(int, col)

If not 2012+
UPDATE table SET col = case when isnumeric(col+'.01')=0 then null else CONVERT(int,col) end

Edit (learned that isnumeric() trick last night by Shnugo)

A: Check the type of argument you are passing into the method , your method asks for an argument of Type Int but you are giving it as a varchar  that's why its throwing exception.
Try with giving an int once


text:
Q: Incompatible function declaration I'm stuck, why am i getting an error: declaration is incompatible...
'void A::function(int,int,std::vector<_Ty> *)' : overloaded member function not found in 'A'
error C2061: syntax error : identifier 'vector'
1>          with
1>          [
1>              _Ty=Point
1>          ]
//cpp file
void A::function(int a, int b, vector<B> *p)
{

}

//header file

class B
{
public:
     int q;
};
class A
{
public:
     void function(int a, int b, vector<B> *p);
};

A: Problems!!!!
void function(int a, int b, vector<B> *line); and void function(int a, int b, vector<B> & line); are two different signatures (function prototypes).
More importantly there is no such keyword Class in C++.

A: It's because the header of the function should be exactly the same.
//cpp file
void A::function(int a, int b, vector<B>* c) { }

//header file
Class B {
public:
    int q;
};
class A {
public:
    void function(int a, int b, vector<B> *line);
};

or :
//cpp file
void A::function(int a, int b, vector<B>& c) { }

//header file
Class B {
public:
    int q;
};
class A {
public:
    void function(int a, int b, vector<B> &line);
};

However, when calling the function in the first case, you should replace the * with & if passing an object, so the local pointer will get the address of the passed object. Or manually pass a pointer.

A: Well, for starters, you're missing a semicolon at the end of B.  Additionally, you're using Class instead of class.
For the signature itself, your declaration (in the header file) takes a pointer to a vector while your definition (in the .cpp file) takes a reference.
//cpp file
void A::function(int a, int b, vector<B>& c) // // Arguments are an int, an int, and a vector<B> reference.
{

}

//header file

class B
{
public:
     int q;
};

class A
{
public:
     void function(int a, int b, vector<B>& line);
        // Same arguments.
};

redpajama_set_name: RedPajamaStackExchange


text:
Q: WPF Screenshot JPG from UIElement with C# I'm trying to create a JPG from part of my WPF Applications.  Like a screenshot, only of individual UIElements.  I started here: http://www.grumpydev.com/2009/01/03/taking-wpf-screenshots/
I am using his extension method, which essential allows you to get a byte[] with UIElement.GetJpgImage().  This can then be written using a filestream to a JPG image.  If I make a JPG of the whole window, it looks just fine!  However, this is not ideal because it just captures what the user sees.  Things that are not visible because of the scrollviewer or because their parent was animated to a small size won't show up.
If I take a "screenshot" of, say, a grid that I use for layout:
alt text http://img697.imageshack.us/img697/4233/fullscreenshot2.jpg
I get this crap with a black background.  I don't want that.  Furthermore, if I've collapsed this grid's height using animation, I won't get anything at all.  Those are actually templated checkboxes, they should have black text above them, and the background of the grid should be white.  Here's the code that someone else wrote to return the byte[] array that gets written to a filestream:
public static byte[] GetJpgImage(this UIElement source, double scale, int quality)
{
    double actualHeight = source.RenderSize.Height;
    double actualWidth = source.RenderSize.Width;

    double renderHeight = actualHeight * scale;
    double renderWidth = actualWidth * scale;

    RenderTargetBitmap renderTarget = new RenderTargetBitmap((int) renderWidth, (int) renderHeight, 96, 96, PixelFormats.Pbgra32);
    VisualBrush sourceBrush = new VisualBrush(source);

    DrawingVisual drawingVisual = new DrawingVisual();
    DrawingContext drawingContext = drawingVisual.RenderOpen();

    using (drawingContext)
    {
        drawingContext.PushTransform(new ScaleTransform(scale, scale));
        drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(actualWidth, actualHeight)));
    }
    renderTarget.Render(drawingVisual);

    JpegBitmapEncoder jpgEncoder = new JpegBitmapEncoder();
    jpgEncoder.QualityLevel = quality;
    jpgEncoder.Frames.Add(BitmapFrame.Create(renderTarget));

    Byte[] _imageArray;

    using (MemoryStream outputStream = new MemoryStream())
    {
        jpgEncoder.Save(outputStream);
        _imageArray = outputStream.ToArray();
    }

    return _imageArray;
}

Somewhere in there, we're getting a black background.  Any insight?
EDIT: If I set the grid's background property to white, the screenshot comes out as expected.  However, it's not feasible to set everything's background that I need to take a screenshot of.

A: Just a guess, I would think that a black background would represent portions of the byte array that are not set to anything in this process. The initial zeros in the array would appear as black.
To avoid this, I suggest initializing the array with 0xFF (byte.MaxValue) values.
UPDATED:
From looking at this closer, I think you should draw a white rectangle onto the image before you render the UI element. That ought to work anyway.
Just before this line of code
drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(actualWidth, actualHeight)));

put something like this
drawingContext.DrawRectangle(Brushes.White, null, new Rect(new Point(0, 0), new Point(actualWidth, actualHeight)));

A: Unfortunately the only thing that worked was just setting the element's background in the XAML.  I didn't want to do this, but I guess it is what I need to do in this case.  Thanks anyway for the suggestion.


text:
Q: Solving Eikonal Equation $u_x^2+u_y^2=u^2$ The problem is the following:
I have the bidimensional eikonal equation with non-constant propagation:
$u_x^2+u_y^2=u^2$
The goal is:
i) To find the characteristic strips for the parametrization $x=f(s)$, $y=g(s)$ and $z=u(f(s),g(s))=h(s)$;
ii)To find the integral surfaces passing through the circle $x=cos(s)$, $y=sin(s)$, $z=1$;
iii)To find the integral surfaces through the line $x=s$, $y=0$, $z=1$.
Writing the equation in general form,$F(x(s),y(s),u,p(s),q(s))=0$, i.e., $p^2+q^2-u^2=0$, where $p=u_x, q=u_y$,we have, for the item i), the following system of EDO's:
$\frac{dx}{ds}=F_p=2p$
$\frac{dy}{ds}=F_p=2q$
$\frac{dz}{ds}=pF_p+qF_q=2(p^2+q^2)$
$\frac{dp}{ds}=-F_x-pF_u=2(u_xu+pu)$
$\frac{dq}{ds}=-F_y=2(u_yu+qu)$
For item ii), I know the answer is $z=\exp[\pm (1-\sqrt{x^2+y^2})]$, but I don't know how to find it;
For item iii), I know the answer is $u=\exp(\pm y)$, but I don't know how to find it.
Suggestions to solve the problem?

A: Write the PDE as $F(x,y,u,u_{x},u_{y})=0$, where $F(x,y,z,p,q)=p^{2}+q^{2}-z^{2}$. The characteristic equations are
$$\begin{cases}\dot{x}(s)=F_{p}(x(s),y(s),z(s),p(s),q(s))=2p(s)\\ \dot{y}(s)=F_{q}(x(s),y(s),z(s),p(s),q(s))=2q(s)\\ \dot{z}(s)=p(s)F_{p}(x(s),y(s),z(s),p(s),q(s))+q(s)F_{q}(x(s),y(s),z(s),p(s),q(s))=2(p(s)^{2}+q(s)^{2})=2z(s)^{2}\\ \dot{p}(s)=-F_{x}(x(s),y(s),z(s),p(s),q(s))-p(s)F_{z}(x(s),y(s),z(s),p(s),q(s))=2p(s)z(s)\\ \dot{q}(s)=-F_{y}(x(s),y(s),z(s),p(s),q(s))-q(s)F_{z}(x(s),y(s),z(s),p(s),q(s))=2q(s)z(s)\end{cases}$$
Suppose that we have initial data $(x^{0},y^{0},z^{0},p^{0},q^{0})$. We first solve the ODE for $z(s)$, obtaining
$$z(s)=\dfrac{z^{0}}{1-2z^{0}s}$$
We substitute this result in to the ODEs for $p(s),q(s)$ to obtain
$$\begin{cases}\dot{p}(s)=2p(s)\dfrac{z^{0}}{1-2z^{0}s}, & p(s)=\dfrac{p^{0}}{1-2z^{0}s}\\ \dot{q}(s)=2q(s)\dfrac{z^{0}}{1-2z^{0}s}, & q(s)=\dfrac{q^{0}}{1-2z^{0}s} \end{cases}$$
Lastly, we substitute these results into the ODEs for $x(s),y(s)$ to obtain
$$\begin{cases}\dot{x}(s)=2\dfrac{p^{0}}{1-2z^{0}s}, & x(s)=-\dfrac{p^{0}}{z^{0}}\ln\left|1-2z^{0}s\right|+x^{0}\\ \dot{y}(s)=2\dfrac{q^{0}}{1-2z^{0}s}, & y(s)=-\dfrac{q^{0}}{z^{0}}\ln\left|1-2z^{0}s\right|+y^{0}\end{cases}$$
for $s$ in the appropriate domain.
Suppose our boundary condition is $u=1$ on $\Gamma=S^{1}$. Fix a point $(x,y)\in\mathbb{R}^{2}$, and let $s$ and $(x^{0},y^{0})=(\cos\theta^{0},\sin\theta^{0})$, for some $\theta^{0}\in[0,2\pi]$ be such that $(x,y)=(x(s),y(s))$. Clearly, $z^{0}=1$, so it remains to solve for $x^{0},y^{0},p^{0},q^{0},s$. Since $\frac{d}{d\theta}u(\cos\theta,\sin\theta)_{\theta^{0}}=Du(x^{0},y^{0})\cdot (-y^{0},x^{0})=0$, we see that $(p^{0},q^{0})=\lambda(x^{0},y^{0})$, where $\lambda$ is some nonzero scalar. Since ${p^{0}}^{2}+{q^{0}}^{2}={z^{0}}^{2}=1$, we see that $\left|\lambda\right|=1$.
$$x^{2}+y^{2}=\left({x^{0}}^{2}+{y^{0}}^{2}\right)\left[\lambda^{-1}(1-\lambda\ln\left|1-2s\right|)\right]^{2}\Rightarrow s=\dfrac{1-\exp[\lambda^{-1}(1-\sqrt{x^{2}+y^{2}})]}{2}$$
We conclude that
$$u(x,y)=u(x(s),y(s))=z(s)=\exp\left[-\lambda^{-1}(1-\sqrt{x^{2}+y^{2}})\right]=\exp\left[\pm(1-\sqrt{x^{2}+y^{2}})\right]$$
Suppose now our boundary condition is $u=1$ on $\Gamma=\mathbb{R}\times\left\{0\right\}$. Proceeding as above, we fix a point $(x,y)\in\mathbb{R}^{2}$, and let $s$ and $(x^{0},0)$ be such that $(x,y)=(x(s),y(s))$. As before, $z^{0}=1$. Since $u=1$ on $\Gamma$, we obtain that $p^{0}=u_{x}(x^{0},0)=0$. From the identity ${p^{0}}^{2}+{q^{0}}^{2}={z^{0}}^{2}$, we obtain that $\left|q^{0}\right|=1$. Substituting this information into the equations above, we see that
$$x=x^{0}, y=-q^{0}\ln\left|1-2s\right|\Rightarrow s=\dfrac{1-e^{\pm y}}{2}$$
Substituting this result into the equation for $z(s)$, we conclude that
$$u(x,y)=u(x(s),y(s))=z(s)=e^{\pm y}$$


text:
Q: How to run scheduled code without user manipulation In WordPress, I want to do the licensing system for plugins and theme that I write. I have no problem entering the key and checking it, but I want the key to be checked in a schedule of, say, 12 hours. I want the user to not be able to change it. If I use cron, the user will be able to change it by installing a plugin. Another way came to my mind was to save the last check in the database and check the last check time in my plugin or template was loaded each time, and if it was past, the key would be checked, but in this way the user can write a plugin and load it Earlier than my plugin or theme.  Or my template loads and that plugin constantly pulls the last check time forward, so my plugin or theme doesn't check the license. If anyone has a solution, thank you for giving it to me.
Thank you in advance.

A: I have one suggestion, check if it is good for you.
You can use a "lottery script" (inpired by Laravel).
The idea is that the script checker will be executed randomically, so it not will consume the server all time but you will keep having one script that depends only of itsef.
$lottery = rand(1, 100);
if($lottery <= 2)
    echo 'check license';
else
    echo 'sleep ...';


text:
Q: Amazon PHP API MWS to get Fulfillment I'm trying to get the inventory of my fulfillment using the PHP API of the MWS. When I use the parameters given by amazon on the scratchpad I get the answer perfectly, but when I try using my code it says that the signature doesn't match, what am I doing wrong?
<?php
$base_url = "https://mws.amazonservices.co.uk/FulfillmentInventory/2010-10-01";
$method = "POST";
$host = "mws.amazonservices.co.uk";
$uri = "/FulfillmentInventory/2010-10-01";

function amazon_xml() {

    $params = array(
        'AWSAccessKeyId' => "123456788",
        'Action' => "ListInventorySupply",
        'SellerId' => "234234123412341",
        'SignatureVersion' => "2",
        //'Timestamp'=> gmdate("Y-m-d\TH:i:s.Z", time()),
        'Timestamp'=> gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", time()),
        'Version'=> "2010-10-01",
        'SignatureMethod' => "HmacSHA256",
        'SellerSkus.member.1' => '1EU-AMZ-FIRE-TV-MOUNT');

    // Sort the URL parameters
    $url_parts = array();
    foreach(array_keys($params) as $key)
        $url_parts[] = $key . "=" . str_replace('%7E', '~', rawurlencode($params[$key]));

    sort($url_parts);

    // Construct the string to sign
    $url_string = implode("&", $url_parts);
    $string_to_sign = "POST\nmws.amazonservices.co.uk\n/FulfillmentInventory/2010-10-01\n" . $url_string;
    echo $string_to_sign."
";

    // Sign the request
    $signature = hash_hmac("sha256", $string_to_sign, 'sdgsdfgsdfgsdgsdgsdg', TRUE);
    echo $signature."
";
    // Base64 encode the signature and make it URL safe
    $signature = urlencode(base64_encode($signature));
    echo $signature."
";

    $url = "https://mws.amazonservices.co.uk/FulfillmentInventory/2010-10-01" . '?' . $url_string . "&Signature=" . $signature;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    $response = curl_exec($ch);
    echo "La respuesta es ".$response;
    $parsed_xml = simplexml_load_string($response);

    //return ($parsed_xml);
    echo $parsed_xml;

}

amazon_xml();

?>

A: You appear to be sorting your $url_parts array by value, where you should be sorting it by key.
ksort($url_parts);

I cannot see any other systematic problem in your code. Another point where my code differs from yours though, is that mine uses a Merchant parameter instead of SellerId - I have not checked if using SellerId actually works as well.


text:
Q: Why is this code getting faster when I'm using way more threads than my CPU has cores? I have some timing code which I'm using to measure the runtime of a given snippet of code:
struct time_data {
    std::chrono::steady_clock::time_point start, end;

    auto get_duration() const {
        return end - start;
    }

    void print_data(std::ostream & out) const {
        out << str();
    }

    std::string str() const {
        static const std::locale loc{ "" };
        std::stringstream ss;
        ss.imbue(loc);
        ss << "Start:    " << std::setw(24) << std::chrono::nanoseconds{ start.time_since_epoch() }.count() << "ns\n";
        ss << "End:      " << std::setw(24) << std::chrono::nanoseconds{ end.time_since_epoch() }.count() << "ns\n";
        ss << "Duration: " << std::setw(24) << std::chrono::nanoseconds{ get_duration() }.count() << "ns\n";
        return ss.str();
    }

    static friend std::ostream & operator<<(std::ostream & out, const time_data & data) {
        return out << data.str();
    }
};

template<typename T>
time_data time_function(T && func) {
    time_data data;
    data.start = std::chrono::steady_clock::now();
    func();
    data.end = std::chrono::steady_clock::now();
    return data;
}

Then, to make use of it, I have the following code designed to perform an accumulation on a set of data, but instead of simply adding the numbers together, it first finds the Total Stopping Time from applying the Collatz Conjecture and accumulates that instead.
template<typename T>
T accumulation_function(T a, T b) {
    T count = 0;
    while (b > 1) {
        if (b % 2 == 0) b /= 2;
        else b = b * 3 + 1;
        ++count;
    }
    return a + count;
}

template<typename IT>
auto std_sum(IT begin, IT end) {
    auto sum = (*begin - *begin);
    sum = std::accumulate(begin, end, sum, accumulation_function<decltype(sum)>);
    return sum;
}

template<typename IT>
auto single_thread_sum(IT begin, IT end) {
    auto sum = (*begin - *begin);
    IT current = begin;
    while (current != end) {
        sum = accumulation_function(sum, *current);
        ++current;
    }
    return sum;
}

template<typename IT, uint64_t N>
auto N_thread_smart_sum(IT begin, IT end) {
    auto sum = (*begin - *begin);
    std::vector<std::thread> threads;
    std::array<decltype(sum), N> sums;
    auto dist = std::distance(begin, end);
    for (uint64_t i = 0; i < N; i++) {
        threads.emplace_back([=, &sums] {
            IT first = begin;
            IT last = begin;
            auto & tsum = sums[i];
            tsum = 0;
            std::advance(first, i * dist / N);
            std::advance(last, (i + 1) * dist / N);
            while (first != last) {
                tsum = accumulation_function(tsum, *first);
                ++first;
            }
        });
    }
    for (std::thread & thread : threads)
        thread.join();
    for (const auto & s : sums) {
        sum += s;
    }
    return sum;
}

template<typename IT>
auto two_thread_smart_sum(IT begin, IT end) {
    return N_thread_smart_sum<IT, 2>(begin, end);
}

template<typename IT>
auto four_thread_smart_sum(IT begin, IT end) {
    return N_thread_smart_sum<IT, 4>(begin, end);
}

template<typename IT>
auto eight_thread_smart_sum(IT begin, IT end) {
    return N_thread_smart_sum<IT, 8>(begin, end);
}

template<typename IT>
auto sixteen_thread_smart_sum(IT begin, IT end) {
    return N_thread_smart_sum<IT, 16>(begin, end);
}

template<typename IT>
auto thirty_two_thread_smart_sum(IT begin, IT end) {
    return N_thread_smart_sum<IT, 32>(begin, end);
}

template<typename IT>
auto sixty_four_thread_smart_sum(IT begin, IT end) {
    return N_thread_smart_sum<IT, 64>(begin, end);
}

And for reference sake: the boilerplate main code that runs it all:
int main() {
    std::vector<int64_t> raw_data;
    auto fill_data = time_function([&raw_data] {
        constexpr uint64_t SIZE = 1'000'000'000ull;
        raw_data.resize(SIZE);
        std::vector<std::thread> threads;
        for (int i = 0; i < 8; i++) {
            threads.emplace_back([i, SIZE, &raw_data] {
                uint64_t begin = i * SIZE / 8;
                uint64_t end = (i + 1) * SIZE / 8;
                for (uint64_t index = begin; index < end; index++) {
                    raw_data[index] = begin % (20 + i);
                }
            });
        }
        for (std::thread & t : threads)
            t.join();
    });

    int64_t sum;

    std::cout << std::setw(25) << "Fill Data" << std::endl;
    std::cout << fill_data << std::endl;

    auto std_data = time_function([&] {
        sum = std_sum(raw_data.begin(), raw_data.end());
    });

    std::cout << std::setw(25) << "STD Sum: " << sum << std::endl;
    std::cout << std_data << std::endl;

    auto single_data = time_function([&] {
        sum = single_thread_sum(raw_data.begin(), raw_data.end());
    });

    std::cout << std::setw(25) << "Single Sum: " << sum << std::endl;
    std::cout << single_data << std::endl;

    auto smart_2_data = time_function([&] {
        sum = two_thread_smart_sum(raw_data.begin(), raw_data.end());
    });

    std::cout << std::setw(25) << "Two-Thread-Smart Sum: " << sum << std::endl;
    std::cout << smart_2_data << std::endl;

    auto smart_4_data = time_function([&] {
        sum = four_thread_smart_sum(raw_data.begin(), raw_data.end());
    });

    std::cout << std::setw(25) << "Four-Thread-Smart Sum: " << sum << std::endl;
    std::cout << smart_4_data << std::endl;

    auto smart_8_data = time_function([&] {
        sum = eight_thread_smart_sum(raw_data.begin(), raw_data.end());
    });

    std::cout << std::setw(25) << "Eight-Thread-Smart Sum: " << sum << std::endl;
    std::cout << smart_8_data << std::endl;

    auto smart_16_data = time_function([&] {
        sum = sixteen_thread_smart_sum(raw_data.begin(), raw_data.end());
    });

    std::cout << std::setw(25) << "Sixteen-Thread-Smart Sum: " << sum << std::endl;
    std::cout << smart_16_data << std::endl;

    auto smart_32_data = time_function([&] {
        sum = thirty_two_thread_smart_sum(raw_data.begin(), raw_data.end());
    });

    std::cout << std::setw(25) << "Thirty-Two-Thread-Smart Sum: " << sum << std::endl;
    std::cout << smart_32_data << std::endl;

    auto smart_64_data = time_function([&] {
        sum = sixty_four_thread_smart_sum(raw_data.begin(), raw_data.end());
    });

    std::cout << std::setw(25) << "Sixty-Four-Thread-Smart Sum: " << sum << std::endl;
    std::cout << smart_64_data << std::endl;
    return 0;
}

This is the output of the program:
                Fill Data
Start:          16,295,979,890,252ns
End:            16,300,523,805,484ns
Duration:            4,543,915,232ns

                STD Sum: 7750000000
Start:          16,300,550,212,791ns
End:            16,313,216,607,890ns
Duration:           12,666,395,099ns

             Single Sum: 7750000000
Start:          16,313,216,694,522ns
End:            16,325,774,379,684ns
Duration:           12,557,685,162ns

   Two-Thread-Smart Sum: 7750000000
Start:          16,325,774,466,014ns
End:            16,334,441,032,868ns
Duration:            8,666,566,854ns

  Four-Thread-Smart Sum: 7750000000
Start:          16,334,441,137,913ns
End:            16,342,188,642,721ns
Duration:            7,747,504,808ns

 Eight-Thread-Smart Sum: 7750000000
Start:          16,342,188,770,706ns
End:            16,347,850,908,471ns
Duration:            5,662,137,765ns

Sixteen-Thread-Smart Sum: 7750000000
Start:          16,347,850,961,597ns
End:            16,352,187,838,584ns
Duration:            4,336,876,987ns

Thirty-Two-Thread-Smart Sum: 7750000000
Start:          16,352,187,891,710ns
End:            16,356,111,411,220ns
Duration:            3,923,519,510ns

Sixty-Four-Thread-Smart Sum: 7750000000
Start:          16,356,111,471,288ns
End:            16,359,988,028,812ns
Duration:            3,876,557,524ns

The first few results aren't surprising: my self-written accumulate code works about the same as the std::accumulate function (I've seen both emerge as the "fastest" on consecutive runs, implying their implementation is probably similar). And when I move to Two threads, and Four threads, the code gets faster. This makes sense, because I'm using an Intel 4-core processor.
But the results beyond that point are confusing. My CPU only has 4 cores (8 if you consider the hyperthreading), but even if I excuse that the Hyperthreading is giving marginal performance increases at 8 threads, bumping the number up to 16, 32, and 64 threads all yield additional performance gains. Why is this? How are the additional threads yielding additional performance gains, when I've long since maxed out the number of threads the CPU can physically concurrently run?
Note: this is not the same as this linked question, as I'm dealing with a specific use case and code, whereas the linked question is dealing in generalities.
EDIT:
I made an adjustment to the code so that when threads are created, their priority is set to the highest priority Windows allows. Results, broadly speaking, seem to be the same.
                Fill Data
Start:          18,950,798,175,057ns
End:            18,955,085,850,007ns
Duration:            4,287,674,950ns

                STD Sum: 7750000000
Start:          18,955,086,975,013ns
End:            18,967,581,061,562ns
Duration:           12,494,086,549ns

             Single Sum: 7750000000
Start:          18,967,581,136,724ns
End:            18,980,127,355,698ns
Duration:           12,546,218,974ns

   Two-Thread-Smart Sum: 7750000000
Start:          18,980,127,426,332ns
End:            18,988,619,042,214ns
Duration:            8,491,615,882ns

  Four-Thread-Smart Sum: 7750000000
Start:          18,988,619,135,487ns
End:            18,996,215,684,824ns
Duration:            7,596,549,337ns

 Eight-Thread-Smart Sum: 7750000000
Start:          18,996,215,763,004ns
End:            19,002,055,977,730ns
Duration:            5,840,214,726ns

Sixteen-Thread-Smart Sum: 7750000000
Start:          19,002,056,055,608ns
End:            19,006,282,772,254ns
Duration:            4,226,716,646ns

Thirty-Two-Thread-Smart Sum: 7750000000
Start:          19,006,282,840,774ns
End:            19,010,539,676,914ns
Duration:            4,256,836,140ns

Sixty-Four-Thread-Smart Sum: 7750000000
Start:          19,010,539,758,113ns
End:            19,014,450,311,829ns
Duration:            3,910,553,716ns

DOUBLE EDIT COMBO:
I edited the program to make sure the tsum variable was a local variable inside the lambda, rather than a reference to outside the lambda. The Multithreaded code sped up quite significantly, but it's still exhibiting the same behavior.
                Fill Data
Start:          21,740,931,802,656ns
End:            21,745,429,501,480ns
Duration:            4,497,698,824ns

                STD Sum: 7750000000
Start:          21,745,430,637,655ns
End:            21,758,206,612,632ns
Duration:           12,775,974,977ns

             Single Sum: 7750000000
Start:          21,758,206,681,153ns
End:            21,771,260,233,797ns
Duration:           13,053,552,644ns

   Two-Thread-Smart Sum: 7750000000
Start:          21,771,260,287,828ns
End:            21,777,845,764,595ns
Duration:            6,585,476,767ns

  Four-Thread-Smart Sum: 7750000000
Start:          21,777,845,831,002ns
End:            21,784,011,543,159ns
Duration:            6,165,712,157ns

 Eight-Thread-Smart Sum: 7750000000
Start:          21,784,011,628,584ns
End:            21,788,846,061,014ns
Duration:            4,834,432,430ns

Sixteen-Thread-Smart Sum: 7750000000
Start:          21,788,846,127,422ns
End:            21,791,921,652,246ns
Duration:            3,075,524,824ns

Thirty-Two-Thread-Smart Sum: 7750000000
Start:          21,791,921,747,330ns
End:            21,794,980,832,033ns
Duration:            3,059,084,703ns

Sixty-Four-Thread-Smart Sum: 7750000000
Start:          21,794,980,901,761ns
End:            21,797,937,401,426ns
Duration:            2,956,499,665ns

TRIPLE EDIT WOMBO-COMBO:
I ran the same tests again, but in reverse. Results are quite similar:
                Fill Data
Start:          22,845,472,001,475ns
End:            22,850,746,219,215ns
Duration:            5,274,217,740ns

Sixty-Four-Thread-Smart Sum: 7750000000
Start:          22,850,747,328,223ns
End:            22,853,951,903,952ns
Duration:            3,204,575,729ns

Thirty-Two-Thread-Smart Sum: 7750000000
Start:          22,853,951,981,830ns
End:            22,857,239,237,507ns
Duration:            3,287,255,677ns

Sixteen-Thread-Smart Sum: 7750000000
Start:          22,857,239,307,839ns
End:            22,860,389,285,305ns
Duration:            3,149,977,466ns

 Eight-Thread-Smart Sum: 7750000000
Start:          22,860,389,353,524ns
End:            22,864,828,560,484ns
Duration:            4,439,206,960ns

  Four-Thread-Smart Sum: 7750000000
Start:          22,864,828,633,834ns
End:            22,870,640,982,096ns
Duration:            5,812,348,262ns

   Two-Thread-Smart Sum: 7750000000
Start:          22,870,641,056,956ns
End:            22,877,032,284,384ns
Duration:            6,391,227,428ns

             Single Sum: 7750000000
Start:          22,877,032,367,997ns
End:            22,889,501,695,960ns
Duration:           12,469,327,963ns

                STD Sum: 7750000000
Start:          22,889,501,770,820ns
End:            22,902,014,633,229ns
Duration:           12,512,862,409ns

A: All of your tsum writes are to the same array, which will occupy consecutive addresses in memory.  This will cause cache contention issues with all those writes.  Having more threads spreads those writes out to different cache lines, so the CPU cores spend less time invalidating and reloading cache lines.
Try accumulating to a local tsum variable (not a reference into sums), then writing that to sums[i] when the loop is done.

A: I suspect that you are seeing the speed up because the threads for your application represent a larger percentage of the total active threads running on the system, giving you a more slices of time overall. You might want to see if the numbers change for the better or worse when you have additional programs running.


text:
Q: 405 Not Allowed Wordpress При авторизации в wp-config.php выдает ошибку 405 Not Allowed
Локальный сервер xampp.
Насколько я понял из "гугла" то это ошибка связанная с недостаточной памятью.
Как решить данную проблему?

A: Вы не правильно поняли. Ошибка 405 отдается, когда ресурс запрашивается не разрешенным методом (например вы пытаетесь достучатся до ресурса методом PUT, а он ждет только GET,POST или HEAD). Проверьте, правильным ли вы методом стучитесь. Гуф сказал бы, что 405 это как 404, только на один побольше)


text:
Q: handling warning: implicit declaration of function 'sigignore' Here's my code:
#include <sys/types.h>
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>
#include <assert.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>

int main(int argc, char** argv) {

sigignore(SIGTERM);
return 0;
}

Why do I get the following warning and how could I remove it?

implicit declaration of function 'sigignore'
  [-Wimplicit-function-declaration]  sigignore(SIGTERM);

The program must be compiled like this: gcc -o foo.o foo.c.
Thanks

A: Man sigignore  tells you to use #define _XOPEN_SOURCE 500 to enable sigignore. More on X/Open can be found here

A: The function you want to call has been marked as obsolete 15 years ago. The normal way to discourage people from using those functions (without actually breaking programs) is to have the implementation of the function left in the standard library, but remove the declaration from header files (or at least make it hard to enable).
Use sigaction or sigprocmask (depending on what you actually want to accomplish).


text:
Q: Multiple inheritance from abstract classes with same parent but different child? django I have read few threads and know that for sure django can have multiple abstract classes.  But pretty much all the samples I saw are...
class AbsOne(models.Model):
    pass
class AbsTwo(models.Model):
    pass

class AbsThree(AbsOne, AbsTwo):
    pass

but what if I have something like...
class AbsOne(models.Model):
    pass

class AbsTwo(AbsOne):  // this actually inheritance AbsOne
    pass
class AbsThree(AbsOne):  // this inheritance AbsOne
    pass

What if I need to inheritance both AbsTwo, AbsThree but these two are also inheritance to the same parent.
class AbsFour(AbsTwo, AbsThree):
    pass

Is this doable without any conflict or extra fields?
Thanks in advance.

A:
Just as with Python's subclassing, it's possible for a Django model to
inherit from multiple parent models. Keep in mind that normal Python
name resolution rules apply. The first base class that a particular
name (e.g. Meta) appears in will be the one that is used; for example,
this means that if multiple parents contain a Meta class, only the
first one is going to be used, and all others will be ignored.

https://docs.djangoproject.com/en/1.11/topics/db/models/#multiple-inheritance
It's possible but it has some restrictions like ( overriding fields in parent class and meta classes ) and in Django ORM or the model way of classes is a bit different in architecture than regular python inheritance, read carefully what the documentation mentions and try to keep it simple.

... The main use-case where this is useful is for "mix-in" classes: adding
a particular extra field or method to every class that inherits the
mix-in. Try to keep your inheritance hierarchies as simple and
straightforward as possible so that you won't have to struggle to work
out where a particular piece of information is coming from

edited: added another quote :)


text:
Q: Contact Form 7 Default value from url I have a contact form . I want to set default value by url . For example my contact form url is that
http://website.com/referral-partners/?firstname=Admintest&surname=test&=emailtest@c.com

And my form element is that
[text* firstname placeholder "Enter your first name"]

I tried this solution but not work for me.
[text* firstname placeholder "Enter your first name" default:get]

Not working
also tried this
[text* firstname default:get default:post_meta "First Name"]

I want to add default value in firstname, Lastname and eamil all set by url.
Thank you.

A: Get the values from URL using $_GET request and set it in some hidden input. After that use jQuery to get the values of the hidden input and set it in the contact form elements.


text:
Q: NTFS alternate stream in compressed archive? Does any of the major compressed archive formats in Windows (e.g. zip, rar, 7z) support NTFS alternate data stream?

A: It is in the GUI when you go to create an archive under the "Advanced" tab, in the "NTFS options" frame, along with the checkbox to save NTFS permissions information.

A: RAR is the only one that does right now, AFAIK.
From the command line, you would use the -os switch
-os     Save NTFS streams. Windows version only.

        This switch has meaning only for NTFS file system and allows
        to save alternative data streams associated with a file.
        It is especially important in Windows 2000, XP and newer,
        which use streams to keep some file dependent information
        like file descriptions. If you use RAR to backup your
        NTFS disks, it is recommended to specify this switch.

I'm not sure how the ability is surfaced in WinRAR's GUI, if at all.


text:
Q: Varnish cache installation failed I am trying to run varnish but I get this error:
Backend host "myapp.app": resolves to multiple IPv4 addresses.
Only one address is allowed.
Please specify which exact address you want to use, we found these:
     192.168.10.10
     192.168.10.10
If anyone could give me a suggestion on how to resolve this.
Thank you in advance!

A: It seems like you have multiple entries for "myapp.app" in your local hosts file or in your local DNS-server. Varnish doesn't support that.
Check your hosts file by
cat /etc/hosts

And remove any duplicates of myapp.app. If the hostname resolves to a DNS-server you have to adjust the entries there so myapp.app only points to 1 ip-address.


text:
Q: How to retain search terms in input field? I have an input element,

  <input type="text" id="query" autocomplete="off" />

that triggers an Apache Solr search. Upon submission the input field is cleared (possibly due to a page reload?).
How can I retain the query terms in the input field (or repopulate it, upon submission)?

A: I suspect the button associated with your page issues a submit (e.g. <button type="submit">Search</button>). If that is your case, you'll need to make sure you put the value the user submitted when you render the page again, you'll do this in the value attribute, e.g.

  <input type="text" id="query" autocomplete="off" value="the-value-the-user-entered" />

You could also issue an AJAX call when the user issues the search, in which case, the form won't reload and you won't need to worry about this, but then you will need to write the code to issue the AJAX call.


text:
Q: How to redirect subdirectory to new domain with masking? I have a URL with a subdirectory that I want to forward to a different domain I was able to achieve this by adding:
Options +FollowSymLinks
RewriteEngine On
Redirect 301 /youthinc http://rbcrftk.com/
Where /youthinc is my subdirectory domain and rbcftk is the domain where the site is hosted. This forwards the subdirectory however it doesn't mask the rbcrftk.com domain. How would I be able to achieve this with masking?

A: Simple you should create a new default page in this subdirectory like index.html or index.php or index.aspx as per your server and put redirect script in this page . i hop this will help you

A: You are confusing Mod-alias with Mod-rewrite. You have the RewriteEngine but then using a mod-alias directive. Also you can not Mask a URL using a 301 redirect. That is what a redirect is supposed to do. The only way you can Mask a domain the way you are trying it is by using mod-proxy with Rewrite. If you use it in htaccess you will need to use the P flag. Mod-proxy has to also be enabled. This will keep the domain from changing.
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^youthinc/?$ http://rbcrftk.com/ [P]

http://httpd.apache.org/docs/2.4/rewrite/proxy.html


text:
Q: Projecting a ray from screen to model for picking I'm trying cast a ray from mouse click position on screen and transform it into the model space for triangle intersection testing. I'm sure the intersection code works fine and I understand the theory behind unprojecting the ray. However my code doesn't work. I've tried several implementations for the same basic idea, and the results I'm getting seem to be all over the place.
Is there something fundamental missing from the code below?
 // 1. Convert x, y from screen to normalized device coordinates [-1:1]
auto screenPos = pick->position();
float x = (2.0f * screenPos.x()) / Viewer::window()->width() - 1.0f;
float y = 1.0f - (2.0f * screenPos.y()) / Viewer::window()->height();

// 2. Create a ray xy coordinates with a z pointing forward
QVector3D ray = QVector3D(x, y, -1.0f);

// 3. Convert from device space to view space using inverted projection matrix
QMatrix4x4 projectionMatrix = Viewer::window()->camera()->projectionMatrix();
ray = ray * projectionMatrix.inverted();

// 4. Convert from view space to world space using inverted view matrix
QMatrix4x4 viewMatrix = Viewer::window()->camera()->viewMatrix();
ray = ray * viewMatrix.inverted();
ray.normalize();

// 5. Convert from world space to object space using object transformation matrix
QMatrix4x4 modelMatrix = this->transform()->matrix();
ray = ray * modelMatrix.inverted();
ray.normalize();

// 6. Get camera position for ray origin and transform it to object coordinates
QVector3D camera_pos = Viewer::window()->camera()->position();
QVector3D origin = camera_pos * modelMatrix.inverted();

// 7. Find intersections
auto intersection = testRay(mesh.get(), origin, ray);


text:
Q: Can't assign a `std::unique_ptr` to a base class in clang when using an alias template The following code compiles and runs just fine on gcc 4.9.3 and clang 3.7.1
// std::unique_ptr
#include <memory>

// Template class for template-template arguments
template <typename Real>
struct Bar {};

// Base class
template <typename T,template <typename> class XX>
struct Base {};

// Derived class that operates only on Bar
template <typename Real>
struct Derived : public Base <Real,Bar> {};

// Holds the unique_ptr
template <typename T,template <typename> class XX>
struct Foo {
    std::unique_ptr <Base <T,XX>> foo;
};

// Create an alias template
template <typename Real>
using Buz = Bar <Real>;

int main() {
    #if 0
    auto f = Foo <double,Buz> (); //Causes error!
    #else
    auto f = Foo <double,Bar> ();
    #endif
    f.foo =  std::make_unique <Derived <double>> (Derived <double>());
}

However, if we change the #if 0 to #if 1, gcc compiles, but clang does not:
g++ -std=c++14 test03.cpp -o test03_gcc
clang++ -std=c++14 test03.cpp -o test03_clang
test03.cpp:32:11: error: no viable overloaded '='
    f.foo =  std::make_unique <Derived <double>> (Derived <double>());
    ~~~~~ ^  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.3/include/g++-v4/bits/unique_ptr.h:249:7: note:
      candidate function not viable: no known conversion from
      'unique_ptr<Derived<double>, default_delete<Derived<double>>>' to
      'unique_ptr<Base<double, Buz>, default_delete<Base<double, Buz>>>' for
      1st argument
      operator=(unique_ptr&& __u) noexcept
      ^
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.3/include/g++-v4/bits/unique_ptr.h:278:7: note:
      candidate function not viable: no known conversion from 'typename
      _MakeUniq<Derived<double> >::__single_object' (aka
      'unique_ptr<Derived<double> >') to 'nullptr_t' for 1st argument
      operator=(nullptr_t) noexcept
      ^
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.3/include/g++-v4/bits/unique_ptr.h:357:19: note:
      candidate function not viable: no known conversion from
      'unique_ptr<Derived<double>, default_delete<Derived<double>>>' to
      'const unique_ptr<Base<double, Buz>, default_delete<Base<double,
      Buz>>>' for 1st argument
      unique_ptr& operator=(const unique_ptr&) = delete;
                  ^
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.3/include/g++-v4/bits/unique_ptr.h:264:22: note:
      candidate template ignored: disabled by 'enable_if' [with _Up =
      Derived<double>, _Ep = std::default_delete<Derived<double> >]
        typename enable_if< __and_<
                            ^
1 error generated.
Makefile:2: recipe for target 'all' failed
make: *** [all] Error 1

What's the problem with using the alias template in this context?  Or, if gcc is more permissive than it should be, why is that the case?

A: This is CWG issue 1244:

The example in 14.4 [temp.type] paragraph 1 reads in significant part,
template<template<class> class TT> struct X { };
template<class> struct Y { };
template<class T> using Z = Y<T>;
X<Y> y;
X<Z> z;

and says that y and z have the same type.
This would only be true if alias template Z were considered to be equivalent to class template Y. However, 14.5.7 [temp.alias] describes equivalence only for specializations of alias templates, not for the alias templates themselves. Either such rules should be specified, which could be tricky, or the example should be deleted.

We can reduce your example down to:
std::unique_ptr<Base<double, Buz>> f =
    std::make_unique<Base<double, Bar>>();

This is well formed if and only if Buz and Bar are considered equivalent. gcc thinks they are, clang thinks they aren't. It's still an open question as to what the actual answer is.


text:
Q: How to NOT handle some Universal Links programmatically? My iOS application handles universal links to redirect safari users to my app. So far everything is working great, if a user tap a link to my web site from Google my app is opening instead of my web site like this:
from safari https://my-web-site.com -> my-app

But my app doesn't implement certains features that my web site does, so I would like to programmatically reject some URLs and let my users on safari instead of redirecting him in my app, like this:
from safari https://my-web-site.com -> my-app

OR
from safari https://my-web-site.com?reject -> safari

That should by possible according to Apple documentation:

It's important to understand that if your app uses openURL: to open a universal link to your website, the link does not open in your app. In this scenario, iOS recognizes that the call originates from your app and therefore should not be handled as a universal link by your app.

Unfortunately that's not what's appending, instead of staying in safari, my user is redirected to my app for a brief moment, then redirected again to safari like this:
from safari https://my-web-site.com?reject -> my-app (briefly) -> safari

here is my code for AppDelegate.swift:
internal func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
    guard let url = userActivity.webpageURL else { return false }
    guard let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true) else { return false }

    let params = urlComponents.queryItems ?? []

    if params.contains(where: { $0.name == "reject" }) {
        // This line should prevent the app from opening according to Apple's documentation
        application.open(url)
        return false
    } else {
        return true
    }
}

So anyone have an idea how I could make the rejection of an Universal link the way it's described by Apple's documentation ?
note: the rejection of an universal link need to be done programmatically by the app, according to data stored locally. So adding a path exception in the apple-app-site-association file is not an option in my case :
{
  "applinks": {
    "apps": [],
    "details": [
      {
        "appID": "XXXXXXXXX.com.my-app",
        "paths": [
          "*",
        "NOT /reject"
        ]
      }
    ]
  }
}

A: If you prefix an entry in the paths array with "NOT" then you can explicitly prevent a match.  So in your example you could do something like
["NOT /settings/*", "NOT /activity/*", "/*"]

which would prevent paths with /settings or /activity prefixes, and then match everything else.

Reference


text:
Q: Rotating cubes in OpenGL I want to have a cube that rotates around the center. This is something i can do with this transformation:
model = glm::rotate(identity, glm::radians(-100.0f * time), glm::vec3(0.0, 1.0, 0.0)); //rotate around y-axis
model = glm::translate(model, glm::vec3(8.0, 0.0, 0.0));
model = glm::rotate(model, glm::radians(-100.0f * time), glm::vec3(1.0, 0.0, 0.0)); //self-rotation

Now I want a cube that will rotate around the first cube as it is rotating around y-axis.
Imagine that the first cube is the Earth and the second cube is the moon.
I tried this, but it didn't work.
test = glm::rotate(test, glm::radians(-100.0f * time), glm::vec3(0.0, 1.0, 0.0));
test = glm::translate(test, glm::vec3(3.0, 0.0, 0.0));
test = glm::translate(test, glm::vec3(8.0, 0.0, 0.0));
test = glm::rotate(test, glm::radians(-100.0f * time), glm::vec3(0.0, 1.0, 0.0));
test = glm::translate(test, glm::vec3(-8.0, 0.0, 0.0));
test = glm::rotate(test, glm::radians(-100.0f * time), glm::vec3(1.0, 0.0, 0.0)); // self-rotation

Any ideas what I'm doing wrong?
Here is a picture of the rotations:

A: Your comment suggest you have this order of operations:
mvp = m_projection*m_view*m_model
vertex' = mvp*vertex

meaning m_view is inverse matrix of view and m_model is direct matrix of actual mesh.
So you should set m_projection and m_view once and then just updating the m_model.
I do not use GLM (have my own libs for math) however IIRC they mimic old fixed pipeline matrix math. So when I do this (C++/VCL/OpenGL/GLSL ... I know the points should be VBO/VAO I just wanted test quickly):
//---------------------------------------------------------------------------
//    ang   ,ang speed,body r,orbit r
//    [deg] ,[deg/s]   [unit],[unit]
float                  rs=1.0;          // star
float a0=0.0,da0= 50.0,r0=0.5,R0= 7.0;  // planet
float a1=0.0,da1=200.0,r1=0.2,R1= 1.0;  // moon
float a2=0.0,da2=250.0,r2=0.2,R2= 1.5;  // moon
float a3=0.0,da3= 20.0,r3=0.5,R3=10.0;  // planet
float a4=0.0,da4=150.0,r4=0.2,R4= 1.0;  // moon
float a5=0.0,da5=180.0,r5=0.2,R5= 1.5;  // moon
float b =0.0,db =50.0;                  // common self rotation
//---------------------------------------------------------------------------
void gl_draw()
    {
    GLint ix;
    GLfloat mp[16],mv[16],mm[16],m0[16];
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    float aspect=float(xs)/float(ys);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(60.0/aspect,aspect,0.1,100.0);
    glGetFloatv(GL_PROJECTION_MATRIX,mp);
    glMatrixMode(GL_TEXTURE);
    glLoadIdentity();
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(0.0,0.0,-25.0);
    glGetFloatv(GL_MODELVIEW_MATRIX,mv);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glGetFloatv(GL_MODELVIEW_MATRIX,mm);

    glDisable(GL_DEPTH_TEST);
    glDisable(GL_TEXTURE_2D);
    glDisable(GL_CULL_FACE);
//  glEnable(GL_CULL_FACE);

    // GLSL sphere shader
    glUseProgram(prog_id);
    ix=glGetUniformLocation(prog_id,"m_projection"); glUniformMatrix4fv(ix,1,false,mp);
    ix=glGetUniformLocation(prog_id,"m_view");       glUniformMatrix4fv(ix,1,false,mv);
    ix=glGetUniformLocation(prog_id,"m_model");

    // sun
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glRotatef(b,0.0,0.0,1.0);
    glGetFloatv(GL_MODELVIEW_MATRIX,mm); glUniformMatrix4fv(ix,1,false,mm);
    glBegin(GL_POINTS); glColor3f(1.0,1.0,0.0); glVertex4f(0.0,0.0,0.0,rs); glEnd();
    // planet
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glRotatef(a0,0.0,0.0,1.0);
    glTranslatef(R0,0.0,0.0);
    glGetFloatv(GL_MODELVIEW_MATRIX,m0);
    glRotatef(b,0.0,0.0,1.0);
    glGetFloatv(GL_MODELVIEW_MATRIX,mm); glUniformMatrix4fv(ix,1,false,mm);
    glBegin(GL_POINTS); glColor3f(0.0,0.7,1.0); glVertex4f(0.0,0.0,0.0,r0); glEnd();
    // moon
    glLoadMatrixf(m0);
    glRotatef(a1,0.0,0.0,1.0);
    glTranslatef(R1,0.0,0.0);
    glRotatef(b,0.0,0.0,1.0);
    glGetFloatv(GL_MODELVIEW_MATRIX,mm); glUniformMatrix4fv(ix,1,false,mm);
    glBegin(GL_POINTS); glColor3f(0.4,0.4,0.4); glVertex4f(0.0,0.0,0.0,r1); glEnd();
    // moon
    glLoadMatrixf(m0);
    glRotatef(a2,0.0,0.0,1.0);
    glTranslatef(R2,0.0,0.0);
    glRotatef(b,0.0,0.0,1.0);
    glGetFloatv(GL_MODELVIEW_MATRIX,mm); glUniformMatrix4fv(ix,1,false,mm);
    glBegin(GL_POINTS); glColor3f(0.4,0.4,0.4); glVertex4f(0.0,0.0,0.0,r2); glEnd();
    // planet
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glRotatef(a3,0.0,0.0,1.0);
    glTranslatef(R3,0.0,0.0);
    glGetFloatv(GL_MODELVIEW_MATRIX,m0);
    glRotatef(b,0.0,0.0,1.0);
    glGetFloatv(GL_MODELVIEW_MATRIX,mm); glUniformMatrix4fv(ix,1,false,mm);
    glBegin(GL_POINTS); glColor3f(0.0,0.7,1.0); glVertex4f(0.0,0.0,0.0,r3); glEnd();
    // moon
    glLoadMatrixf(m0);
    glRotatef(a4,0.0,0.0,1.0);
    glTranslatef(R4,0.0,0.0);
    glRotatef(b,0.0,0.0,1.0);
    glGetFloatv(GL_MODELVIEW_MATRIX,mm); glUniformMatrix4fv(ix,1,false,mm);
    glBegin(GL_POINTS); glColor3f(0.4,0.4,0.4); glVertex4f(0.0,0.0,0.0,r4); glEnd();
    // moon
    glLoadMatrixf(m0);
    glRotatef(a5,0.0,0.0,1.0);
    glTranslatef(R5,0.0,0.0);
    glRotatef(b,0.0,0.0,1.0);
    glGetFloatv(GL_MODELVIEW_MATRIX,mm); glUniformMatrix4fv(ix,1,false,mm);
    glBegin(GL_POINTS); glColor3f(0.4,0.4,0.4); glVertex4f(0.0,0.0,0.0,r5); glEnd();

    glUseProgram(0);

    glFlush();
    SwapBuffers(hdc);
    }
//---------------------------------------------------------------------------
void __fastcall TForm1::Timer1Timer(TObject *Sender)
    {
    // this is periodicaly called by timer
    gl_draw();
    float dt=0.001*float(Timer1->Interval); // timer period in seconds
    a0=fmod(a0+da0*dt,360.0);
    a1=fmod(a1+da1*dt,360.0);
    a3=fmod(a3+da3*dt,360.0);
    a4=fmod(a4+da4*dt,360.0);
    a5=fmod(a5+da5*dt,360.0);
    b =fmod(b +db *dt,360.0);
    }
//---------------------------------------------------------------------------

I got this output (using my sphere shader):

The shader just takes point x,y,z,r as a sphere 3D center and radius, emit BBOX quad and render inscribed sphere with normal shading. It also uses color and your 3 matrices.
So if I see it right you should do something like this:
model = identity;
model = glm::rotate(model, glm::radians(b), glm::vec3(0.0, 1.0, 0.0));
// render star
model = identity;
model = glm::rotate(model, glm::radians(a0), glm::vec3(0.0, 1.0, 0.0));
model = glm::translate(model, glm::vec3(R0, 0.0, 0.0));
model0= model;
model = glm::rotate(model, glm::radians(b), glm::vec3(0.0, 1.0, 0.0));
// render planet
model = model0;
model = glm::rotate(model, glm::radians(a1), glm::vec3(0.0, 1.0, 0.0));
model = glm::translate(model, glm::vec3(R1, 0.0, 0.0));
model = glm::rotate(model, glm::radians(b), glm::vec3(0.0, 1.0, 0.0));
// render moon
model = model0;
model = glm::rotate(model, glm::radians(a2), glm::vec3(0.0, 1.0, 0.0));
model = glm::translate(model, glm::vec3(R2, 0.0, 0.0));
model = glm::rotate(model, glm::radians(b), glm::vec3(0.0, 1.0, 0.0));
// render moon
model = identity;
model = glm::rotate(model, glm::radians(a3), glm::vec3(0.0, 1.0, 0.0));
model = glm::translate(model, glm::vec3(R3, 0.0, 0.0));
model0= model;
model = glm::rotate(model, glm::radians(b), glm::vec3(0.0, 1.0, 0.0));
// render planet
model = model0;
model = glm::rotate(model, glm::radians(a4), glm::vec3(0.0, 1.0, 0.0));
model = glm::translate(model, glm::vec3(R4, 0.0, 0.0));
model = glm::rotate(model, glm::radians(b), glm::vec3(0.0, 1.0, 0.0));
// render moon
model = model0;
model = glm::rotate(model, glm::radians(a5), glm::vec3(0.0, 1.0, 0.0));
model = glm::translate(model, glm::vec3(R5, 0.0, 0.0));
model = glm::rotate(model, glm::radians(b), glm::vec3(0.0, 1.0, 0.0));
// render moon

If this is not working then your got some other mismatch between matrix order and used math or the GLM behaves differently than I expect. I used common angle for self-rotations so you just add indexes for your bodies ...
Also beware old GL rotations use [deg] so if GLM want [rad] you need to convert the angles and angular speed constants ...
If you want to have something more precise/related to real world or better visually see this:

*

*Is it possible to make realistic n-body solar system simulation in matter of size and mass?

A: object A rotating around B order: self rotation of A, translate to offset of A to B, rotate about B, translate by B position. Since B is the sun which I assume is in your world origin, and everything is on the xz plane (Cartesian not OpenGL coords), this becomes:
model = glm::rotate(identity, glm::radians(-100.0f * time), glm::vec3(1.0, 0.0, 0.0)); //self-rotation
model = glm::translate(model, glm::vec3(8.0, 0.0, 0.0)); // earth is 8 away from sun, where unrotated about sun is 8 units east
model = glm::rotate(model, glm::radians(-100.0f * time), glm::vec3(0.0, 1.0, 0.0)); //rotate about sun
// no need for another translation since sun is at origin

Then for a object whose parent is the earth, you first resolve that relationship before you resolve the parent to world relationship:
model = glm::rotate(identity, glm::radians(-100.0f * time), glm::vec3(1.0, 0.0, 0.0)); //self-rotation of moon
model = glm::translate(model, glm::vec3(-4.0, 0.0, 0.0)); // moon is 4 away from Earth, where unrotated about Earth is 4 units west
model = glm::rotate(model, glm::radians(-100.0f * time), glm::vec3(0.0, 1.0, 0.0)); //rotate about Earth
// translate to Earth origin, which is calculate from above code block

Disclaimer, I don't use glm-math, this is just the order of transformation geometrically, and I don't know if it translates directly to glm::x


text:
Q: Did I get too good a confidence interval for Pearson's R using bootstrap on a very unbalanced data set? I can't find this type of bootstrap problem described anywhere, where the data is so unbalanced: 50 y-values vs 2500 values yielding 50 means that become the x's. Another thing: the 50 strata yielding the means are internally autocorrelated time series. The bootstrapped mean histograms looked mostly normal distributed.
Problem 1: I just can't intuit if the improvement in confidence interval is too good to be true when I bootstrap from all 2500 values instead of directly from the 50 x, y-pairs: A span of 0.39 improved to 0.039. I.e. 10 times narrower. It makes no sense when having only 50 y-values available - or does it? I started to doubt either the bootstrap in this context, or my own R-code provided below, or my theoretical understanding. Should I trust the result or is there a theoretical reason not to? (I have checked out a few papers and I know bootstrap is not always that precise and that better variants and methods exist for correlation CIs, e.g: Confidence intervals for correlations when data are not normal)
bootstrap directly on means: R = 0.608 ( 0.3878,  0.7790 )
bootstrap from underlying values: R = 0.608 ( 0.5916,  0.6290 )
Problem 2: Why is including all data better according to this experiment? I can reason it both ways:
(Wrong way) Say I bootstrap from 50 fix y-values, and 50 X's that are averages. Then I have fix x-values with no variation and should get a narrower CI than if I introduce an uncertainty - a spread in each x average - by using all 2500 values.
(correct by experiment) On the other hand: Say I use all 2500 values in a two-step bootstrap computing first the mean and from it the x,y-correlation. Then I use more information than is inherent in the 50 x-averages, and should get a narrower confidence interval for the Pearson correlation.
I expected the second method to yield narrower confidence interval for Pearson's R since more information is utilized, but I don't know how or why and I am curious.
This is not commercial in any way. I help out a friend that is about to publish a paper I believe could be beneficial to general health. I benefit from it myself mostly by learning R (yes I am an R and Tidyverse newbie), and by the thrill of doing some real science for a good cause. I am a system developer by profession.
Here is the R code for using all data, with the unnecessaries removed:
testst <-function(tb,i) {
  # Generate correlation between yStrat and xStrat.
  # arg: tibble with about 2500 rows with about 50 strata

  tbi <- tb[i, ] # Bootstrap sample

  yTbi <- tbi %>% group_by(StratumID) %>%
    summarise(yStrat=last(YPrevalence)) # All Y identical per stratum
                                        # Could have used unique as well
  # Apply mean to each stratum of bootstrapped draws from stratum
  xTbi <- tbi %>% group_by(StratumID) %>%
      summarise(xStrat = mean(XConsumption, na.rm = TRUE))

  # Apply cor to fixed y values against each stratum mean
  pears <- cor(x = xTbi$xStrat,
                 y = yTbi$yStrat,
                 method = "pearson")

  return(c(pears))
}

# Executing on tibble tbd with ~2500 rows, ~50 strata. One fix Y-value per stratum
tbd$StratumID <- as_factor(tbd$StratumID)
bt <- boot(tbd,testst,R=10000,strata=tbd$StratumID)
bc<-boot.ci(bt,type="bca",index=1)

A: Thank you @ben-bolker! Your answer led me to this paper: Estimating Pearson's Correlation Coefficient With Bootstrap Confidence Interval From Serially Dependent Time Series. It confirms that the effective sample size I have is in reality much reduced due to the autocorrelation, as I suspected. I think I can adapt the method by using block bootstrap on each individual time series.
I will look up bootstrapping residuals as well when I get the time.
(Btw: my question was migrated to this forum and it seems I do not own it anymore - "You have not asked any questions" - so I could not just add a comment due to lack of "reputation")


text:
Q: Changing number format in ToC and in cross references independently I am trying tu customize how the numbering format of sections, subsections, etc. in the table of contents using the book class. Basically, the problem is that changing any style with \renewcommand changes it everywhere, and I want to change it for the table of contents independently from the style for the cross references.
I know the titlesec package, but it only changes the style of the actual headers, and not the cross references.
More precisely, my MWE is the following.
\documentclass[oneside,12pt]{book}

\renewcommand{\thechapter}{\Roman{chapter}}
\renewcommand{\thesection}{\thechapter.\arabic{section}}
\renewcommand{\thesubsection}{\thechapter.\arabic{section}.\alph{subsection}}
\renewcommand{\theparagraph}{\roman{chapter}.\arabic{paragraph}.}

\setcounter{secnumdepth}{4}

\begin{document}

\tableofcontents

\chapter{First Chapter}
\section{Section one}\label{sec:one}
\subsection{Subsection A}\label{subsec:one.a}

\subsection{Subsection B}

\section{Section two}
Same as Section~\ref{sec:one}.

\section{Section three}
\subsection{Subsection A}
Same as Subsection~\ref{subsec:one.a}.

\end{document}

It produces the table of contents

and the body of the book

Now, I am happy with how the body looks, but I would like, for example, to drop the roman "I" in front of the section and subsection numbers in the table of contents, and NOT in the cross references.
I would appreciate all your suggestions.

A: When writing out the toc-entry LaTeX sets \label to \@gobble. So you could test for it:
\documentclass[oneside,12pt]{book}

\renewcommand{\thechapter}{\Roman{chapter}}
\makeatletter
\renewcommand{\thesection}{\ifx\label\@gobble\else\thechapter.\fi\arabic{section}}
\renewcommand{\thesubsection}{\ifx\label\@gobble\else\thechapter.\fi\arabic{section}.\alph{subsection}}
\renewcommand{\theparagraph}{\roman{chapter}.\arabic{paragraph}.}

\setcounter{secnumdepth}{4}

\begin{document}

\tableofcontents

\chapter{First Chapter}
\section{Section one}\label{sec:one}
\subsection{Subsection A}\label{subsec:one.a}

\subsection{Subsection B}

\section{Section two}
Same as Section~\ref{sec:one}.

\section{Section three}
\subsection{Subsection A}
Same as Subsection~\ref{subsec:one.a}.

\end{document}


text:
Q: Wordpress list child pages on child page using foreach loop I'm using a foreach loop to list child pages on a parent page, which works great. However, the child pages don't list on a child page, which is what I'd like.
Here's what works for the parent page so far:
<?php

$nav = array(
    'post_type' => 'page',
    'orderby' => 'title',
    'order' => 'ASC',
    'post_parent' => $post->ID
);

$child_pages = get_posts($nav);

?>

    <?php foreach ($child_pages as $child_page) : ?>

            <a href="<?=get_permalink($child_page->ID); ?>"><?=$child_page->post_title; ?>

    <?php endforeach; ?>

Ideally I'd like to keep using foreach rather than any other loop. I'm wondering if I need to add another loop inside my existing loop, but I'm unsure how to proceed.
Any help would be much appreciated.

A: What you could do here is to check if the current page is a child page using wp_get_post_parent_id - see http://codex.wordpress.org/Function_Reference/wp_get_post_parent_id and then if the page is a child page - use the parent id, otherwise just use the post id. Something like this should work:
global $post;
if(wp_get_post_parent_id( $post->ID ))
{
    $nav = array(
        'post_type' => 'page',
        'orderby' => 'title',
        'order' => 'ASC',
        'post_parent' => wp_get_post_parent_id( $post->ID )
    );
}
else{
    $nav = array(
    'post_type' => 'page',
    'orderby' => 'title',
    'order' => 'ASC',
    'post_parent' => $post->ID
    );
}
$child_pages = get_posts($nav);

A: Use parent instead of post_parent
    <?php

    $nav = array(
        'post_type' => 'page',
        'orderby' => 'title',
        'order' => 'ASC',
        'child_of' => $post->ID
    );

    $child_pages = get_posts($nav);

    ?>

        <?php foreach ($child_pages as $child_page) : ?>

                <a href="<?=get_permalink($child_page->ID); ?>"><?=$child_page->post_title; ?>

        <?php endforeach; ?>

hope it helps

A:         <? foreach (get_posts(array('post_type' => 'page','orderby' => 'title','order' => 'ASC','post_parent' => $post->ID)) as $p) { ?>
            <?=$p->post_title; ?>
        <? } ?>


text:
Q: Python strip date from CSV I've currently got a loop that iterates through each line of a CSV and pulls out information and to enter a website via selenium.
I'm currently struggling with a dropdown box date field. The date is format 30/12/2000.
I think I should be able to strip out each part of the date and send it to send keys in that box and press enter.
I'm using something like this.
from datetime import datetime

with open('/Users/me/Downloads/dates_test.csv',newline='') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
        try:
           driver = find stuff on page
           d = (row[1])
           objd = datetime.strptime(d, '%d %m %Y')
           sign_up_date = driver.find_element_by_xpath("//*[@id='membership-signed-up-     on']/a").click()
            sleep(1)
            day1 = driver.find_element_by_xpath("//*[@id='membership_signed_up_on_3i']").click()
            day1.send_keys(objDate.day)
            day1.send_keys(Keys.RETURN)

Two questions,

*

*I'm currently getting this error.
ValueError: time data '17/05/2021' does not match format '%d %m %Y'

*Am I on the right track. Is there a better way to do this.

A: You're very close. Just change this line:
objd = datetime.strptime(d, '%d %m %Y')

to this
objd = datetime.strptime(d, '%d/%m/%Y')

A: Alternatively, if you do not want to deal with date formats, you could use the dateutil library:
from dateutil import parser as p

objd = p.parse(d)


text:
Q: Under which representation of U(1) transform electron and photon gauge field? I know that under $SU(2) \times  SU(2)$, the left-handed electron transforms under  $ ( \frac{1}{2},0 ) $ representation and the vector gauge field $A_\mu$ under $ ( \frac{1}{2},\frac{1}{2}) $.
Since the electron transforms under $U(1)$, there must be a represenation under which it transforms. What is this representation? Does it have a name?
Apparenly $A_\mu$ does not transform under the same representation, which would mean $e^{\alpha(x) Q} A_\mu$, but instead as $A_\mu + i \partial_\mu \alpha(x)$ ? What representation is this?
Of course I realize that the transformation of $A_\mu$ can't be different for the Lagrangian to be invariant, but that shouldn't be used to define the it.

A: The electron field transforms under the $\mathbf 1$ of $U(1)$, i.e., the generator is $i$ or $1$ depending on your convention/notation.
The gauge fields transform in the adjoint representation , but they transform as a connection, as @Adam mentioned. In other words, if $\psi \to g \psi$, then $D_\mu \psi \to g D_\mu \psi$ implies that $A_\mu \to g D_\mu g^{-1}$. It's a bit misleading for $U(1)$ because you don't see the non-Abelian structure, but you get the idea.

A: $U(1)$ is an Abelian group. Abelian groups only have 1-dimensional irreducible representation. Namely, transformation by a phase (in the case of the electron). The charge of fermion field is proportional to the coefficient of the phase. In particular, a field of charge $q$ transforms as $\Psi \to e^{i q \theta(x)} \Psi$
EDIT: As pointed out in the comments, the earlier answer was incorrect.


text:
Q: .rbenv/versions/2.0.0-p353/bin/ruby: No such file or directory on Cygwin To install rbenv, I installed Cygwin and some required packages (gcc, openssl, libssl, libxml, etc). Then, cloned repositories and appended to.zshrc.
$ git clone https://github.com/sstephenson/rbenv.git ~/.rbenv
$ git clone https://github.com/sstephenson/ruby-build.git ~/.rbenv/plugin
$ echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.zshrc
$ echo 'eval "$(rbenv init -)"' >> ~/.zshrc

Restarted cygwin and ran this command.
rbenv install 2.0.0-p353

However I got this error.
$ rbenv install 2.0.0-p353
Downloading ruby-2.0.0-p353.tar.gz...
-> http://dqw8nmjcqpjn7.cloudfront.net/78282433fb697dd3613613ff55d734c1
Installing ruby-2.0.0-p353...

BUILD FAILED

Inspect or clean up the working tree at /tmp/ruby-build.20140211033802.7944
Results logged to /tmp/ruby-build.20140211033802.7944.log

Last 10 log lines:
installing default gems:      /cygdrive/c/Users/MY_NAME/.rbenv/versions/2.0.0-p353/lib/ruby/gems/2.0.0 (build_info, cache, doc, gems, specifications)
                              bigdecimal 1.2.0
                              io-console 0.4.2
                              json 1.7.7
                              minitest 4.3.2
                              psych 2.0.0
                              rake 0.9.6
                              rdoc 4.0.0
                              test-unit 2.0.0.0
/cygdrive/c/Users/MY_NAME/.rbenv/plugins/ruby-build/bin/ruby-build: line 759: /cygdrive/c/Users/MY_NAME/.rbenv/versions/2.0.0-p353/bin/ruby: No such file or directory

/tmp/ruby-build.20140211033802.7944 is here:
https://gist.github.com/anonymous/a9e099a4335ae59a9714
I found a function related to openssl around line 759 of ruby-build, but I may have installed
it.
Any ideas on why versions/2.0.0-p353/bin/ruby doesn't exist?


text:
Q: arcpy.SelectByAttribute 'Parameters are not valid' error I am trying to run a python script to select 5 random points in an attribute table and to loop through every 100 points to do this. When I run the function SelectRandomByCOunt within a python shell, it works perfectly fine but I am trying to embed it in this For loop and it doesnt work. I keep getting this error mesg:
ExecuteError: Failed to execute. Parameters are not valid.
The value cannot be a feature class
ERROR 000840: The value is not a Raster Layer.
ERROR 000840: The value is not a Mosaic Layer.
Failed to execute (SelectLayerByAttribute).

The code
import arcpy
import os
from arcpy import env

# path name of the feature class
ws = r"S:\Venu\APWRAGOEAProject\APWRAGOEA.gdb"
fcname = r"PracticePythonCode"
fc = os.path.join(ws, fcname)

# replace 'xxx' with file path

# get count of features
num = arcpy.GetCount_management(fc)
print("There are "+str(num)+ " rows in your feature class.")

# start counters
count = 0
next100 = 1

with arcpy.da.SearchCursor(fc, ['OBJECTID']) as scursor:  ## column 1 name [0], column 2 name [1]

      for srow in scursor: # iterate through rows

        if count < (next100 * 100):
                      col1 = srow[0] ## grab value from column 1

      # do processing of these 100 records here using col1, col2 variables
                      def SelectRandomByCount (layer, count):
                                import random
                                layerCount = int (arcpy.GetCount_management (layer).getOutput (0))
                                if layerCount < count:
                                    print "input count is greater than layer count"
                                    return
                                oids = [oid for oid, in arcpy.da.SearchCursor (layer, "OID@")]
                                oidFldName = arcpy.Describe (layer).OIDFieldName
                                path = arcpy.Describe (layer).path
                                delimOidFld = arcpy.AddFieldDelimiters (path, oidFldName)
                                randOids = random.sample (oids, count)
                                oidsStr = ", ".join (map (str, randOids))
                                sql = "{0} IN ({1})".format (delimOidFld, oidsStr)
                                arcpy.SelectLayerByAttribute_management (layer, "", sql)

                      SelectRandomByCount (fc,5)

                      # increase count by 1
                      count = count + 1

        else:

              # move to next group of 100
                next100 = next100 + 1

del srow, scursor

A: As the exception states, SelectLayerByAttribute_management expects a layer (which is not the same thing as feature class -fc variable in your case, that you are passing, which is just the data) and you have to create one before passing into the def. If you use Make Feature Layer tool to create a layer just before SelectRandomByCount call and pass this layer into your def call, e.g., SelectRandomByCount ("SayMyLayer",5), your code should run fine. However, there are many lingering parts in your code which is not related to the error that you receive!


text:
Q: Is there any known issue with OpenJDK 8 (1.8.0_232) and some HTTPS connections causing HTTP error 403? When running Saxon 9.9.1.6 HE with Java 1.8.0_232 (java -version outputs
openjdk version "1.8.0_232"
OpenJDK Runtime Environment (AdoptOpenJDK)(build 1.8.0_232-b09)
OpenJDK 64-Bit Server VM (AdoptOpenJDK)(build 25.232-b09, mixed mode)

) and the command line java -cp 'C:\Program Files\Saxonica\Saxon9.9HE\saxon9he.jar' net.sf.saxon.Query -t .\harry-potter-api-ex1.xq to run an XQuery program trying to access https://www.potterapi.com/v1/sortingHat I always get an error FOUT1170: Server returned HTTP response code: 403 for URL: https://www.potterapi.com/v1/sortingHat.
Running Java 12.0.1 (java -version output
openjdk version "12.0.1" 2019-04-16
OpenJDK Runtime Environment (build 12.0.1+12)
OpenJDK 64-Bit Server VM (build 12.0.1+12, mixed mode)

) on the same machine with the same Saxon version the query always works/is able to make the HTTPS access.
Is there any known issue with Java 8/1.8 that could cause this? Is anyone using Oracle JRE 1.8 getting the same error?
The XQuery file is
declare namespace map = "http://www.w3.org/2005/xpath-functions/map";
declare namespace array = "http://www.w3.org/2005/xpath-functions/array";

declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";

declare option output:method 'json';
declare option output:indent 'yes';

json-doc('https://www.potterapi.com/v1/sortingHat')

I have tested some other HTTPS connections with Saxon and Java 8/1.8 and they do work but I for the given URL I always get the error with Java 8/1.8 and no error with Java 12.
BaseX also gives me [FOUT1170] Resource 'https://www.potterapi.com/v1/sortingHat' cannot be retrieved. when running with Java 8 and runs the query fine with Java 12.
I also tried some Java code now
    System.out.println(System.getProperty("java.version"));

    URL url = new URL("https://www.potterapi.com/v1/sortingHat");

    HttpURLConnection con = (HttpURLConnection)url.openConnection();

    try {
        con.connect();
        System.out.println(con.getResponseCode());
    }
    finally {
        con.disconnect();
    }

and the output is
1.8.0_232
403

for Java 1.8 and
12.0.1
200

Any idea what could be causing the 403 with Java 1.8/8?

A: This is a certificate / CA trust issue.
If you check the certificate of the https://www.potterapi.com/v1/sortingHat (e.g. by opening the url in a browser and click on the padlock icon) you will find that it was issued by COMODO ECC Domain Validation Secure Server CA 2.
Next, if you check the content of JEP 319: Root Certificates you will find that Comodo (and other CAs) were added to OpenJDK as part of Java 10. Consequently, since older Java versions such as Java 8 does not have the Comodo CA in its certificate chain, the server (potterapi in this example) will reject it during the TLS handshake and respond with 403 - Forbidden.


text:
Q: Homebrew: can't remove 'keg-only' OpenSSL application Given the recent OpenSSL scare I'm trying to clean out older versions from my machines but Homebrew won't let me:
$ brew dirty
openssl (1.0.1e, 1.0.1f, 1.0.1g)
$ brew cleanup openssl
Warning: Skipping (old) keg-only: /usr/local/Cellar/openssl/1.0.1e
Warning: Skipping (old) keg-only: /usr/local/Cellar/openssl/1.0.1f
$ brew dirty
openssl (1.0.1e, 1.0.1f, 1.0.1g)

How can I purge these old versions of OpenSSL from my Mac?

A: As of Homebrew f4d2141 there is a --force option.
brew cleanup --force openssl

References: man brew


text:
Q: Excel format to only prepend character, without changing number format I am trying to define a custom number format to simply prepend + or - to positive and negative numbers, and I want to use the default number formatting that only includes as many places or decimals as necessary.
For example general format:
8
-5.25
6.5
-2.75

would instead be displayed as:
+ 8
- 5.25
+ 6.5
- 2.75

The closest I've gotten so far is + #.###; - #.###;, but this still attached trailing decimal points to whole numbers. How can I just drop in the general number format after the sign?

A: You can use custom format
+ General;- General

This also works in Excel 2003

and in Excel 2007

and in 2013

I don't have ready access to any earlier versions but I don't doubt that this will also work in Excel 2000 and previous.


text:
Q: No provider for MatSnackBar error when trying to run "ng test" So I'm trying to run "ng test" on my Angular 4 Angular CLI. I'm having many problems such as the UI not loading any helpful message if a test fails, but fortunately the console works. Anyways, this error is occuring saying I did not give MatSnackBar a provider in the spec, but when I do, I get a different error.
Chrome 66.0.3359 (Linux 0.0.0) BranchNameCellComponent should create FAILED
    Error: No provider for MatSnackBar!

Error when I include MatSnackBar as an import
Chrome 66.0.3359 (Linux 0.0.0) BranchNameCellComponent should create FAILED
    Failed: Unexpected value 'MatSnackBar' imported by the module 'DynamicTestModule'. Please add a @NgModule annotation.

In my component code, I'm importing MatSnackBar and calling it in the constructor. It works fine.
import { MatSnackBar } from '@angular/material';
....
constructor(private httpClient: HttpClient, private fb: FormBuilder, public snackBar: MatSnackBar) { }

But in the spec, I try this to no avail.
import { MatSnackBar } from '@angular/material';
....
describe('BranchNameCellComponent', () => {
  let component: BranchNameCellComponent;
  let fixture: ComponentFixture<BranchNameCellComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ BranchNameCellComponent ],
      imports: [ HttpClientTestingModule, ReactiveFormsModule, MatSnackBar ],
      schemas: [ NO_ERRORS_SCHEMA ]
    })
    .compileComponents();
  }));

  it('should create', () => {
    fixture = TestBed.createComponent(BranchNameCellComponent);
    component = fixture.componentInstance;
    expect(component).toBeTruthy();
  });
});

After importing the module like Diego suggested, I now get a timeout error on that same test
08 06 2018 16:14:52.839:WARN [Chrome 66.0.3359 (Linux 0.0.0)]: Disconnected (1 times), because no message in 10000 ms.
Chrome 66.0.3359 (Linux 0.0.0) ERROR
Chrome 66.0.3359 (Linux 0.0.0) ERROR
  Disconnected, because no message in 10000 ms.
Chrome 66.0.3359 (Linux 0.0.0): Executed 16 of 56 DISCONNECTED (11.204 secs / 1.241 secs)
Chrome 66.0.3359 (Linux 0.0.0) ERROR
Chrome 66.0.3359 (Linux 0.0.0): Executed 16 of 56 DISCONNECTED (11.204 secs / 1.241 secs)

A: I was facing this error when in my angular app, I was navigating to some module which was lazy loaded. This module was importing MatSnackBarModule but I needed to import MatSnackBarModule in app.module.ts file as well

A: You should import the module instead of the component.
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
....
describe('BranchNameCellComponent', () => {
  let component: BranchNameCellComponent;
  let fixture: ComponentFixture<BranchNameCellComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ BranchNameCellComponent ],
      imports: [ HttpClientTestingModule, ReactiveFormsModule, MatSnackBarModule ],
      schemas: [ NO_ERRORS_SCHEMA ]
    }).compileComponents();
  }));

  it('should create', () => {
    fixture = TestBed.createComponent(BranchNameCellComponent);
    component = fixture.componentInstance;
    expect(component).toBeTruthy();
  });
});

For the issue related to the timeout, try adding this to your karma config file:
captureTimeout: 210000,
browserDisconnectTolerance: 3,
browserDisconnectTimeout : 210000,
browserNoActivityTimeout : 210000,

A: This has happened to me recently and I decided like this::
Include file aap.module.ts
import { MatSnackBarModule } from '@angular/material/snack-bar';
...
...
imports: [
    ...
    MatSnackBarModule
  ]
...

On file component or service:
import { MatSnackBar } from '@angular/material/snack-bar';
...
...
constructor(private snackBar: MatSnackBar) { }
...


text:
Q: Using script scope modifier on PowerShell functions in modules has no effect? I assumed that using the script scope modifier on a function in a PowerShell module would prevent the function from being exported. Sample:
function script:Get-One { 1 }

When I import the module the Get-One function is exported.
Questions

*

*Is it supposed to work to use the script scope modifier to make module functions private?

*If not: Why? Any other scope modifiers that I can use?

I know I can use Export-ModuleMember to control which functions to export, but I only have a few functions that should not be exported. I would rather specify which functions to ignore.

A: script scope in a module is redundant because the default scope is the script/module in which it's defined. It is the equivalent of an instance variable. global in a module is akin to a static variable. Posh-Git for example uses a Global preferences variable for consistency between shells.
I used an in-memory module but the idea is the same when using a psd1 to define the arguments to New-Module
# remove module from namespace for repeated testing
if(Get-Module -Name 'SOTest') { Remove-Module -Name 'SOTest' }

new-Module -Function:'*' -Name:'SOTest' -ScriptBlock {

    $global:helpers = [PSCustomObject]@{}
    Add-Member -InputObject:$global:helpers -MemberType:ScriptMethod -Name:'HiddenFoo' -Value { return "Private Foo!" }
    Add-Member -InputObject:$global:helpers -MemberType:ScriptMethod -Name:'HiddenFooWithArgs' -Value { return "Private " + $args -join ',' + '!'  }
    Add-Member -InputObject:$global:helpers -MemberType:ScriptMethod -Name:'HiddenFooWithParams' -Value { param ([string]$str, [int]$num); return "Private Str = $str + num; $num!"  }

    ## script: scope refers to module scope, which makes it redundant
    function WriteFoo {
        Write-Output "PublicFoo!"
    }

    function WritePrivate {
        #This fails, because the private now refers to the function scoped $private:helpers
        $private:helpers.HiddenFoo | Write-Verbose -Verbose
    }

    function WritePrivateShort {
        # This works because the helpers object is static across instances
        $helpers.HiddenFoo() | Write-Verbose -Verbose
        $helpers.HiddenFooWithArgs("Cow", "Moo") | Write-Verbose -Verbose
        $helpers.HiddenFooWithParams("Four", 4) | Write-Verbose -Verbose
        # This errors due to argument type mismatch
        $helpers.HiddenFooWithParams("Five", "Five") | Write-Verbose -Verbose

    }

} | Import-Module

# Prefer short errors for this demo
$ErrorView = "CategoryView"

Get-Module -Name 'SOTest'
'WF-----------------'
WriteFoo
'WP-----------------'
WritePrivate
'WPS----------------'
WritePrivateShort
'-------------------'

And the output:
ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Script     0.0        SOTest                              {WriteFoo, WritePrivate, WritePrivateShort}
WF-----------------
PublicFoo!
WP-----------------
InvalidData: (:) [Write-Verbose], ParameterBindingValidationException
WPS----------------
VERBOSE: Private Foo!
VERBOSE: Private Cow Moo
VERBOSE: Private Str = Four + num = 4!
InvalidArgument: (:) [], RuntimeException
-------------------

A: For a Powershell module, Export-ModuleMember is the preferred way to do that.
As an alternative, you can define the function that you don't want exported from inside the function(s) which uses it (in the Begin block, for example).
This makes the function only visible by the "parent" function, making it effectively private.
Also, you could try using the Private scope , instead of the Script scope.


text:
Q: Connect to PostgreSQL using integrated security or fall back to public login I am using Npgsql and I was wondering whether there was a way to connect to a PostgreSQL server using integrated security that automatically falls back to a public login? Or maybe there is another way to do what I am trying to achieve.
I have an ASP.NET web site (IIS7.5) that uses Windows Authentication, and I have configured PostgreSQL to allow access via SSPI, this works fine as long as there is a role with the right name in the database. The web site is available for everyone on the intranet to view but some users have a few extra abilities (or can see extra data) that everyone else should not be able to do.
Currently, I am using something like the following:
NpgsqlConnectionStringBuilder csb = new NpgsqlConnectionStringBuilder();

csb.Pooling = false; // if true, causes intermittent DB connection issues
csb.Database = "dbname";
csb.Host = "192.168.1.100";
csb.IntegratedSecurity = true;

dbconn.ConnectionString = csb.ConnectionString;

try
{
    dbconn.Connect();
}
catch (NpgsqlException ex)
{
    if (/* check for authentication failed */)
    {
        csb.IntegratedSecurity = false;
        csb.UserName = "www-read";
        dbconn.ConnectionString = csb.ConnectionString;
        dbconn.Open();
    }
}

This works fine, except for each time it falls back to the "www-read" role, it adds a critical log entry saying that there was an authentication error. The only way I can see around this is always connecting via www-read and querying whether a suitable integrated-security role exists and reconnecting, but that seems even more cumbersome than the above.

A: I don't see any passwords in your code. Are you using any security at all?
If you don't want to embed password into your source code (and rightly so), you should create ~/.pgpass file in your home directory (%appdata%/postgresql/pgpass.conf on Windows) which has 1 or more lines like this:
hostname:port:database:username:password

This will allow any program that is using libpq (including npgsql) to look up for passwords from .pgpass upon any connection attempt.
If this will run under www-data user, .pgpass should be created in its home directory (but be sure to configure your web server not to serve this file ever!)
I think doing this should also fix problem with connection pooling that you seem to have.


text:
Q: How to scope a ChangeNotifier to some routes using Provider? I have a ChangeNotifier, and I would like to share it between multiple routes but not all routes:

Page1 is my first page. I need share data of ChangeNotifierProvider with Page2, Page3 and Page only and on enter Page1 call dispose of my ChangeNotifierProvider.
How can I do this using provider?

A: To do so, the easiest solution is to have one provider per route, such that instead of:
Provider(
  builder: (_) => SomeValue(),
  child: MaterialApp(),
)

you have:
final value = SomeValue();

MaterialApp(
  routes: {
    '/foo': (_) => Provider.value(value: value, child: Foo()),
    '/bar': (_) => Provider.value(value: value, child: Bar()),
    '/cannot-access-provider': (_) => CannotAccessProvider(),
  }
)

It is, on the other hand, not possible to have your model "automatically disposed".
provider is not able in such a situation to know that it is safe to dispose of the object.


text:
Q: What happens when one of the wires/strings supporting the plate is cut?
A uniform plate of is suspended using two in-extensible wires. When the wire at end B is cut, then we expect to observe the plate move in an arc with some angular acceleration say $\alpha$ about Centre Of Mass (just after wire is cut).
My query is:
Can the uncut wire provide any horizontal force to the plate ? If not, which force causes the motion of the plate in the horizontal direction (as it will rotate in an arc)?

A: The center of mass will not move in an arc because the system has two degrees of freedom. The angle of the wire at A as well as the orientation of the block.
It is the angle of the wire at A that provides any horizontal force.

From the general configuration above you can see how the forces applied to the block are oriented. The kinematics of the problem have the instant center of rotation of the block somewhere along the dashed gray line at all times. The reason being that otherwise point A will move towards the hanging point.

Edit 1
Rember, net forces describe the motion of the center of mass and net torques the rotation about the center of mass. So the motion of point A is a combination of the linear and angular motion of the block. If you work out the equations you should find $$\ddot{\beta} = \frac{T c^2}{2 I \ell}$$


text:
Q: Hit detection on Beziercurves with tolerance? I have some quadratic bezier curves in a Canvas. How could I best go for hit detection on them, if they are only 1-2 px wide, and I want to provide some kind of tolerance, so that the user does not have to click exactly on the line.
Is there something to eg calculate the smallest distance from a bezier, and if that distance is small enough, select the bezier?

A: I can think of at least 3 ways of broadening the hit area of a quadratic bezier curve
I wouldn't recommend this first solution, but here it is anyway!
Solution#1--Manually test your clickPoint against various points calculated on your bezier curve
Here is a function to calculate an XY which is n% of the way along your bezier and a function to test whether your clickPoint is within range of that bezier point.
var startPt=makePt(10,100);
var controlPt=makePt(50,30);
var endPt=makePt(90,100);

function makePt(X,Y){ return( { x:X, y:Y } ) }

// find points at various percent along bezier path
// (where percent is a decimal from 0 to 1)
function getQuadraticBezierXY(percent,startPt,controlPt,endPt) {
    var x = Math.pow(1-percent,2) * startPt.x + 2 * (1-percent) * percent * controlPt.x + Math.pow(percent,2) * endPt.x;
    var y = Math.pow(1-percent,2) * startPt.y + 2 * (1-percent) * percent * controlPt.y + Math.pow(percent,2) * endPt.y;
    return( makePt(x,y) );
}

// find whether 2 points are close to each other
// range is your pixel tolerance
function arePointsInRange(bezPt,testPt,range){
    var dx=testPt.x-bezPt.x;
    var dy=testPt.y-bezPt.y;
    return( dx*dx+dy*dy <= range*range )
}

Solution#2—Hit-test against a closed path which "widens" your curve
Note: isPointInPath() used below is available on modern browsers, but not on legacy browsers
Note: You don't have to actually display the widened curve to your user--you can draw the widened curve but not context.stroke().  (be sure the check out the docs for isPointInPath).
Note: Be sure to adjust your offsets for the slope of the line between your start and end points.  My illustration below uses 0 slope for simplicity.
Here is code and a Fiddle:  http://jsfiddle.net/m1erickson/4GEeu/
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    ctx.lineWidth=2;
    ctx.strokeStyle="red";

    var startX=10;
    var startY=100;
    var controlX=50;
    var controlY=50;
    var endX=90;
    var endY=100;
    var offset=20;

    ctx.beginPath();
    ctx.moveTo(startX,startY-offset);
    ctx.quadraticCurveTo(controlX,controlY-offset,endX,endY-offset);
    ctx.lineTo(endX,endY+offset);
    ctx.quadraticCurveTo(controlX,controlY+offset,startX,startY+offset);
    ctx.closePath();
    ctx.stroke();

    // hitTest point [15,110] which is known to be inside
    // the widened curve path
    if(ctx.isPointInPath(15,110)){
        alert("Point [15,110] is in the closed quadratic curve path");
    }

Solution#3—Hit-test against a widened curve on an offscreen canvas
Note: my illustration just draws the onscreen curve wider.  You might test on an offscreen canvas.
Here is code and a Fiddle:  http://jsfiddle.net/m1erickson/MJfZt/
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    ctx.lineWidth=20;
    ctx.strokeStyle="red";

    var startX=10;
    var startY=100;
    var controlX=50;
    var controlY=50;
    var endX=90;
    var endY=100;
    var offset=20;

    ctx.beginPath();
    ctx.moveTo(startX,startY);
    ctx.quadraticCurveTo(controlX,controlY,endX,endY);
    ctx.stroke();

    // hitTest point [10,100] which is known to be inside
    // the widened curve path
    if(hittestByColor(10,100,255,0,0)){
          alert("Pixel [10,100] is inside the widened curve");
    }

    function hittestByColor(x,y,red,green,blue){
        var pxData = ctx.getImageData(x,y,1,1);
        return(pxData.data[0]==red
            && pxData.data[1]==green
            && pxData.data[2]==blue);
    }


text:
Q: Does gravatar do a redirect to my server or host the default image on it's servers? If I provide a default image to gravatar using the d parameter (for users who are not registered with gravatar), will gravatar redirect to the server hosting this default image or will it cache the image on it's server?
Example link: //gravatar.com/avatar/asdfs3rwerwesdfadsfas3/?d="mysite/img.jpg". Will gravatar cache img.jpg or does it redirect to mysite each time?

A: I looked up the response headers as suggested by @deceze in the comments. Gravatar hosts the image on it's domain (http://i*.wp.com/imagename). There is no redirect involved.


text:
Q: How to iterate through various layers and export each with an additional word to its file name I'm batch dissolving some layers in QGIS and want to save each dissolved shapefile as <layername>_dissolved.shp. I'm using a for-loop but it just shows raise QgsProcessingException(msg) _core.QgsProcessingException: There were errors executing the algorithm. error.
Here's my code:
import processing
layers = QgsProject.instance().mapLayers().values()
for i in layers:
    processing.run("native:dissolve",
                   {'INPUT': i,
                    'OUTPUT': r'C:\Users\imper\Desktop\\' + str(i) + '_dissolved' + '.shp'})
    iface.addVectorLayer(str(i+_dissolved), '', 'ogr')

How should I revise my 'OUTPUT' file path?

A: Use double blackslash (\) or slash(/) to separate directories in the path.
Your loop variable "i" is a layer object, not the path to the layer, to get the path to the layer use:
for layer in QgsProject.instance().mapLayers().values():
    layer_path = layer.dataProvider().dataSourceUri().split('|')[0]
    output_path = 'C:\\Users\\imper\\Desktop\\' + layer.name() + '_dissolved' + '.shp'
    processing.run("native:dissolve",
                   {'FIELD': [], 'INPUT': layer_path, 'OUTPUT': output_path})
    iface.addVectorLayer(output_path, layer.name() + '_dissolved', 'ogr')


text:
Q: Error: ENOENT no such file or directory. When doing a get from MongoDB I get the following error when navigating to my localhost/games.html file.
GET /api/games 404 - 145
Error: ENOENT no such file or directory, stat C:\Users\rodos\Documents\Final\app\public\index.html
at Error (native)

I can POST and DELETE though, because after adding a game all of them are displayed. So the only problem is when you get into the page.
Have searched thoroughly on my code, but cant find the error on the GET operation. I'll add it in case you can find it.
function getGames(res) {
Game.find(function (err, games) {

    // if there is an error retrieving, send the error. nothing after res.send(err) will execute
    if (err) {
        res.send(err);
    }

    res.json(games); // return all games in JSON format
});
}
;

module.exports = function (app) {

//GAMES
app.get('/api/games', function (req, res) {
    // use mongoose to get all games in the database
    getGames(res);
});

Appreciate all help I can get.


text:
Q: How to change style in javascript using a variable? I want to prompt the user for a CSS property and a value and change the style of the paragraphs but I can't get the property working
function change()
  var prop = prompt("Enter a css property");
  var val = prompt("Enter a value for the property");
  var x = document.querySelectorAll("p");
  for (i = 0; i < x.length; i++) {
    x[i].style.prop = val;
  }
}

A: You're trying to set the style prop, not the variable that's inside prop. Use brackets to signify prop is a variable, and to use the value contained inside of it:
x[i].style[prop] = val;

Here is a working demo:

function change() {
  var prop = 'color';
  var val = 'blue';
  var x = document.querySelectorAll("p");
  for (i = 0; i < x.length; i++) {
    x[i].style[prop] = val;
  }
}

Will turn blue

<button onclick="change()">Turn paragraphs blue</button>

A: Try This Code

function change(){
  var prop = prompt("Enter a css property");
  var val = prompt("Enter a value for the property");
 var x = document.querySelectorAll("p");
  for (var i = 0; i < x.length; i++) {
    x[i].style[prop] = val;
  }
}

  <button onclick="change()">Change Style</button>

Hello World

Hello World

Hello World


text:
Q: Is there a C++ CalDav protocol library to connect to iCloud//Yahoo   I have started working on C++ Windows application which needs to fetch Icloud and Yahoo Calendars by connecting to the CalDav servers.
Is there a C++ library that implements this protocol?

A: Is there a C++ library that implements this protocol?
There's always a number of good opensource libs that implement standardised protocols like CalDav.
They are best hunted on FOSS project hosts (with the help of Google).
Here is afew:-

*

*http://libcaldav.sourceforge.net/

*http://trac.mulberrymail.com/repos/wiki/icalendar

*https://code.google.com/p/kcaldav/ <- unmaintained but may be usefull

*http://www.zarafa.com/ <- you might want to extract the CalDav only code from this

*https://code.google.com/p/openconnector/ <- same as above