text:
Q: Service in unreachable from outside I have a problem with accessible my service from outside.
First of all, here is my conf yaml files:
nginx-pod.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-nginx
  namespace: development
spec:
  selector:
    matchLabels:
      app: my-nginx
  replicas: 2
  template:
    metadata:
      labels:
        app: my-nginx
    spec:
      containers:
      - name: my-nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80

nginx-service.yaml
apiVersion: v1
kind: Service
metadata:
  name: nginx-service
  namespace: development
spec:
  type: LoadBalancer
  selector:
    app: my-nginx
  ports:
  - name: http
    port: 80
    targetPort: 80
    protocol: TCP

metallb-config.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  namespace: metallb-system
  name: config
data:
  config: |
    address-pools:
    - name: default
      protocol: layer2
      addresses:
      - 51.15.41.227-51.15.41.227

Then i have created the cluster. Command kubectl get all -o wide prints:

NAME                            READY   STATUS    RESTARTS   AGE   IP            NODE         NOMINATED NODE
pod/my-nginx-5796dcf6c4-rxl6k   1/1     Running   1          20h   10.244.0.16   scw-7d6c86
pod/my-nginx-5796dcf6c4-zf7vd   1/1     Running   0          20h   10.244.1.4    scw-7a7908

NAME                    TYPE           CLUSTER-IP      EXTERNAL-IP    PORT(S)        AGE   SELECTOR
service/nginx-service   LoadBalancer   10.100.63.177   51.15.41.227   80:30883/TCP   54m   app=my-nginx

NAME                       DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE   CONTAINERS   IMAGES        SELECTOR
deployment.apps/my-nginx   2         2         2            2           20h   my-nginx     nginx:1.7.9   app=my-nginx

NAME                                  DESIRED   CURRENT   READY   AGE   CONTAINERS   IMAGES        SELECTOR
replicaset.apps/my-nginx-5796dcf6c4   2         2         2       20h   my-nginx     nginx:1.7.9   app=my-nginx,pod-template-hash=5796dcf6c4

Everythink is fine, also kubectl describe service/nginx-service prints:
Name:                     nginx-service
Namespace:                development
Labels:
Annotations:
Selector:                 app=my-nginx
Type:                     LoadBalancer
IP:                       10.100.63.177
LoadBalancer Ingress:     51.15.41.227
Port:                     http  80/TCP
TargetPort:               80/TCP
NodePort:                 http  30883/TCP
Endpoints:                10.244.0.16:80,10.244.1.4:80
Session Affinity:         None
External Traffic Policy:  Cluster
Events:
  Type    Reason       Age   From                Message
  ----    ------       ----  ----                -------
  Normal  IPAllocated  56m   metallb-controller  Assigned IP "51.15.41.227"

Curl command inside master server curl 51.15.41.227 prints Welcome to nginx blablabla. Next i tried to open from another network, it doesn't work, however i added node port it works curl 51.15.41.227:30883. All this i did on a bare-metal. I expected to happen curl 51.15.41.227 from external host should reach result.
What did i do wrong?

A: Definitely it will work with http://51.15.41.227 or 51.15.41.227:80. You can upvote answer by pressing up button.

A: You should definitely use the node port 30883(randomly assigned port) while accessing from External Network. Otherwise it don't know where to route the request.
curl http://51.15.41.227:30883


text:
Q: ZK How to handle multiple events? I have textbox and method which listens two events.
<textbox id="test" />

@Listen("onOK = #test; onBlur = #test")
public void action(Event event) {
  // do something ...
}

When I press Enter on the Textbox, the event  "onOK " is triggered. It's OK.
But then when I lose focus from the Texbox the  event  "onBlur" is triggered too.  It's bad, because in that case my method "action" is called two times.
How can I cancel this second event ?

A: If you don't need that the event be triggered when the textbox lose the focus, then you have to delete the onBlur part:

@Listen("onOK = #test")
public void action(Event event) {
    // do something ...
}

that's because in your code you are doing with the anotation @listen that every time that in the textbox with id="test" are made any of these events: an onOk or onBlur (which is the one that is trigger when the focus is lose), then the method action is executed.
Update
Now, if you need that the textbox trigger an event with onOK but another when lose the focus (onBlur) then obviously you need two diferent methods and put the listen tag in both but with its own behavior and conditions, like this:
@Listen("onOK = #test")
public void action(Event event) {
    // do something when Ok...
}

@Listen("onBlur = #test")
public void anotherAction(Event event) {
    // do something when loses focus...
}

A: You could forward any event to another event :
I created a fiddle where you can test it.
But some explication :
In the zul :
<textbox id="test" forward="onOK=test.onBlur"/>

What says that the onOK will be forwarded to onBlur, and it will be an onBlur later on.
In java code :
@Listen("onBlur = #test")
public void action(Event event) {
    Clients.showNotification(event.getName() + " " + ++counter);
}

So now we only listen for the onBlur because onOK is forwarded to the onBlur.
Will this help your case atm, not yet.
Not calling the event => not possible, if you declare it, it will be triggered.
But how can you handle your situation :
Hold the String in your composer, and check it with the new value.
If it's equal => the event is already triggered, or there are no changes.
If it's not equal => do your stuff.

redpajama_set_name: RedPajamaStackExchange


text:
Q: django one widget for two m2m fields I have two manytomany fields for my model ModelFrom, that both go to the same Model, call it ModelTo.
ModelFrom(models.Model):
    field_one = ManyToManyField(ModelTo)
    checked = ManyToManyField(ModelTo)

checked is a subset of field one. I have properly validated this in model clean() and adminform clean() methods, and updated model::save() to call self.full_clean().
Ideally, I would have one widget, much like the django.forms.SelectMultiple, but with a checkbox inside each <option>.
what it currently looks like, I have one of these widgets for each field:
:
I want to combine them and have a checkbox or something, here is my unicode representation of what it would look like
{  [ blah: 2 ☐] , [blah: 1 ☑] }
Value in the list -> field one is set. Checked box -> checked is set as it is a subset of field_one.
I have seen jQuery UI MultiSelect Widget but there doesn't seem to be a way to be able to select an option, but not check the box.

A: I couldn't directly answer my own question, but like most questions, if the answer is not possible then there may be an underlying problem.
Instead of having two many2many fields, I should just have one, setting the through property, for an intermediate field.
Like so:
class IntermediateField(models.Model):
     checked = BooleanField()
     from = ForeignKey(ModelFrom)
     to = ForeignKey(ModelTo)

ModelFrom(models.Model):
    field_one = ManyToManyField(ModelTo, through=IntermediateField)

Then, we can just use an inline for IntermediateField in ModelFrom admin, easily checking the boxes etc


text:
Q: simultaneous read and write to child's stdio using boost.process i am trying to write and read to child's stdio using boost.process using something like this:
boost::asio::io_service writeService, readService;
bp::async_pipe in{writeService};
bp::async_pipe out{readService};

bp::child process(CompressCmd.c_str(), bp::std_in < in, bp::std_out > out);
Buffer src;
src.reserve(4 * 1024 * 1024);
integer_type read = 0;
//std::atomic_int64_t totalWrite{0};
integer_type totalWrite = 0;
while (callback(CallbackActions::NeedMoreInput, src, read)) {
    in.async_write_some(
        boost::asio::buffer(src.data(), read),
        [](const boost::system::error_code &e, std::size_t) { });
    // written data is not important, that's why using same buffer
    out.async_read_some(boost::asio::buffer(src.data(), src.capacity()),
                        [&](const boost::system::error_code &e,
                           std::size_t byte_transferred) { totalWrite += byte_transferred; });
}
writeService.run();
in.close();
readService.run();

all read and write operations are noitified as success but value of totalWrite is totally incorrect f.e reported 29356032, real value should be around 50000000
  i noticed the program is terminating half way , using process.wait() after readService.run() freezes child, using atomic int produces same behaviour  for now i actually only need to know how much data is actually wriiten, that's why i am using same buffer

A: *

*This pattern:
while (callback(CallbackActions::NeedMoreInput, src, read)) {
    in.async_write_some(...);
    out.async_read_some(...);
}

is most likely misguided (async operations always immediately return, so you'd simply keep adding more async operations without giving them a chance to run).

*Also misguided is the fact that you have separate services for the pipes, but you're running them in total exclusion, so no read operation will ever run until the writeService completes.

*atomic types are misguided since there's no access from multiple threads

*What are you trying to do? You reserve a large buffer but never put any data into it (reserve != resize). Therefore you can only hope to write nothing.
Even more ironically, you are reading into the exact same buffer, at the exact same spot. However, that's immediately Undefined Behaviour¹ because you pass it src.capacity() when you know that src.size()==0.
Even without that error how can you "simultaneously" read and write from exactly the same bytes in memory and still know what the expected outcome would be?

*you are not passing your own io_service to Boost Process
A Working Demo
Here's a working sample. Of course I had to guess what you actually want to do.
I opted to make the program send its own source (main.cpp) to stdin, and read stdout iteratively, recording the total_received bytes. It then prints the exit code and that total.
As a make-shift compressor I used '/usr/bin/xxd' because it's available and could even be usefully printed to std::cout for debugging.
Live On Coliru // trouble on Coliru
#include <boost/asio.hpp>
#include <boost/process.hpp>
#include <boost/process/async.hpp>
#include <iostream>
std::vector<char> read_file(std::string const&);

namespace bp = boost::process;
using boost::system::error_code;

using Loop = boost::function<void()>;
using Buffer = std::array<char, 4*1024>;

int main() {
    boost::asio::io_service svc;

    std::string const CompressCmd = "/usr/bin/xxd";

    bp::async_pipe in{svc}, out{svc};
    bp::child process(CompressCmd, bp::std_in < in, bp::std_out > out, svc);

    auto data = read_file("main.cpp");

    Loop read_loop, write_loop;

    Buffer recv_buffer;
    std::size_t total_received = 0;
    read_loop = [&read_loop, &out, &recv_buffer, &total_received] {
        out.async_read_some(boost::asio::buffer(recv_buffer),
            [&](error_code ec, size_t transferred) {
                std::cout << "ReadLoop: " << ec.message() << " got " << transferred << " bytes\n";
                total_received += transferred;
                if (!ec)
                    read_loop(); // continue reading
            });
    };

    boost::asio::async_write(in, boost::asio::buffer(data),
        [&](error_code ec, size_t transferred) {
            std::cout << "WriteLoop: " << ec.message() << " done, " << transferred << " bytes\n";
            in.close(ec);
            std::cout << "WriteLoop: closed pipe (" << ec.message() << ")\n";
        }); // async

    read_loop(); // async

    svc.run(); // Await all async operations

    std::cout << "Process exitcode " << process.exit_code() << ", total_received=" << total_received << "\n";
}

#include <fstream>
#include <iterator>
std::vector<char> read_file(std::string const& fname) {
    std::ifstream ifs(fname);
    return {std::istreambuf_iterator<char>(ifs), {}};
}

Printing
WriteLoop: Success done, 1787 bytes
WriteLoop: closed pipe (Success)
ReadLoop: Success got 4096 bytes
ReadLoop: Success got 3515 bytes
ReadLoop: End of file got 0 bytes
Process exitcode 0, total_received=7611

Explanations, Simplifications
Note that we do all of the writing without a loop. That's because boost::asio::async_write is a composed operation (it hides the loop).
Likewise, if you can "afford" to store the whole received data in memory, you can simplify by using boost::asio::streambuf and using a similar composed operation:
Live On Coliru // trouble on Coliru
#include <boost/asio.hpp>
#include <boost/process.hpp>
#include <boost/process/async.hpp>
#include <iostream>
std::vector<char> read_file(std::string const&);

namespace bp = boost::process;
using boost::system::error_code;

int main() {
    boost::asio::io_service svc;

    std::string const CompressCmd = "/usr/bin/xxd";

    bp::async_pipe in{svc}, out{svc};
    bp::child process(CompressCmd, bp::std_in < in, bp::std_out > out, svc);

    auto data = read_file("main.cpp");

    boost::asio::streambuf recv_buffer;
    boost::asio::async_read(out, recv_buffer,
            [&](error_code ec, size_t transferred) {
                std::cout << "ReadLoop: " << ec.message() << " got " << transferred << " bytes\n";
            });

    boost::asio::async_write(in, boost::asio::buffer(data),
        [&](error_code ec, size_t transferred) {
            std::cout << "WriteLoop: " << ec.message() << " done, " << transferred << " bytes\n";
            in.close(ec);
            std::cout << "WriteLoop: closed pipe (" << ec.message() << ")\n";
        }); // async

    svc.run(); // Await all async operations

    std::cout << "Process exitcode " << process.exit_code() << ", total_received=" << recv_buffer.size() << "\n";
}

#include <fstream>
#include <iterator>
std::vector<char> read_file(std::string const& fname) {
    std::ifstream ifs(fname);
    return {std::istreambuf_iterator<char>(ifs), {}};
}

Conversely, if you cannot afford to have all the data in memory before sending, you can create a loop to send input block-wise

Two Asynchronous Loops, With Delays
Let's do that, and make it more entertaining by delaying a second before writing each block. What you'd expect to see is alternating reads/writes happening because of the delays:
Live On Coliru // yay running on Coliru
#include <boost/asio.hpp>
#include <boost/asio/high_resolution_timer.hpp>
#include <boost/process.hpp>
#include <boost/process/async.hpp>
#include <iostream>
#include <fstream>

namespace bp = boost::process;
using boost::system::error_code;
using namespace std::chrono_literals;

using Loop = boost::function<void()>;
using Buffer = std::array<char, 500>;

int main() {
    boost::asio::io_service svc;
    auto on_exit = [](int code, std::error_code ec) {
            std::cout << "Exited " << code << " (" << ec.message() << ")\n";
        };

    std::string const CompressCmd = "/usr/bin/xxd";

    bp::async_pipe in{svc}, out{svc};
    bp::child process(CompressCmd, bp::std_in < in, bp::std_out > out, svc, bp::on_exit(on_exit));

    Loop read_loop, write_loop;

    Buffer recv_buffer;
    std::size_t total_received = 0;
    read_loop = [&read_loop, &out, &recv_buffer, &total_received] {
        out.async_read_some(boost::asio::buffer(recv_buffer),
            [&](error_code ec, size_t transferred) {
                std::cout << "ReadLoop: " << ec.message() << " got " << transferred << " bytes\n";
                total_received += transferred;
                if (!ec)
                    read_loop(); // continue reading
            });
    };

    std::ifstream ifs("main.cpp");
    std::size_t total_written = 0;
    Buffer send_buffer;
    boost::asio::high_resolution_timer send_delay(svc);
    write_loop = [&write_loop, &in, &ifs, &send_buffer, &total_written, &send_delay] {
        if (!ifs.good())
        {
            error_code ec;
            in.close(ec);
            std::cout << "WriteLoop: closed stdin (" << ec.message() << ")\n";
            return;
        }
        ifs.read(send_buffer.data(), send_buffer.size());

        boost::asio::async_write(in, boost::asio::buffer(send_buffer.data(), ifs.gcount()),
            [&](error_code ec, size_t transferred) {
                std::cout << "WriteLoop: " << ec.message() << " sent " << transferred << " bytes\n";
                total_written += transferred;
                if (!ec) {
                    send_delay.expires_from_now(1s);
                    send_delay.async_wait([&write_loop](error_code ec) {
                        std::cout << "WriteLoop: send delay " << ec.message() << "\n";
                        if (!ec) write_loop(); // continue writing
                    });
                }
            });
    };

    read_loop(); // async
    write_loop(); // async

    svc.run(); // Await all async operations

    std::cout << "Process exitcode " << process.exit_code() << ", total_received=" << total_received << "\n";
}

Prints
WriteLoop: Success sent 500 bytes
WriteLoop: send delay Success
WriteLoop: Success sent 500 bytes
ReadLoop: Success got 500 bytes
ReadLoop: Success got 500 bytes
ReadLoop: Success got 500 bytes
ReadLoop: Success got 500 bytes
ReadLoop: Success got 500 bytes
ReadLoop: Success got 500 bytes
ReadLoop: Success got 500 bytes
ReadLoop: Success got 500 bytes
ReadLoop: Success got 96 bytes
WriteLoop: send delay Success
WriteLoop: Success sent 500 bytes
WriteLoop: send delay Success
WriteLoop: Success sent 500 bytes
ReadLoop: Success got 500 bytes
ReadLoop: Success got 500 bytes
ReadLoop: Success got 500 bytes
ReadLoop: Success got 500 bytes
ReadLoop: Success got 500 bytes
ReadLoop: Success got 500 bytes
ReadLoop: Success got 500 bytes
ReadLoop: Success got 500 bytes
ReadLoop: Success got 96 bytes
WriteLoop: send delay Success
WriteLoop: Success sent 500 bytes
WriteLoop: send delay Success
WriteLoop: Success sent 134 bytes
WriteLoop: send delay Success
WriteLoop: closed stdin (Success)
ReadLoop: Success got 500 bytes
ReadLoop: Success got 500 bytes
ReadLoop: Success got 500 bytes
ReadLoop: Success got 500 bytes
ReadLoop: Success got 500 bytes
ReadLoop: Success got 22 bytes
Exited 0 (Success)
ReadLoop: End of file got 0 bytes
Process exitcode 0, total_received=11214

¹ perhaps just unspecified, I'm not inclined to find out the difference right now


text:
Q: EaselJS sprite on("click) returns CORS error First off, I am working on a local EaselJS/CreateJS project, only to test some sprite and mouse interaction.
I have added a simple sprite image to the stage, and I called it "enemy1":
//Create the enemy sprite and add it to the stage
var enemy_image = new Image();
enemy_image .src = "enemy_sprite.png";
var enemy1 = new createjs.Bitmap(enemy_image);

enemy1 .x = 0;
enemy1 .y = 0;

stage.addChild(enemy1);

Using this code, I want to show an alert every time the user clicks on it:
enemy1.on("click", function()
{
     alert("Clicked!");
});

Instead I get a cross-domain error on each click, as shown below:

If the problem is that I am working local or related to cross-domain requests - why does the picture load (and show) just fine on the stage, and the errors only show just as I click on it?

A: Canvas is perfectly happy to allow you to add cross origin data to it, but doing so (without CORS) will taint the canvas.
You get the error when you try to read data from the canvas while it is tainted.
Presumably the library you are using is trying to read the data as part of its code for determining what you clicked on.

A: I ran into a similar issue when trying to use images hosted on the web. Here is the function I wrote based on that answer as a work around:
function loadImg(uri) {
  var image = document.createElement("img")
  image.crossOrigin = "Anonymous"
  image.src = uri
  return image
}

Then do:
var enemy1 = new createjs.Bitmap(loadImg("http://example.com/enemy_sprite.png"))


text:
Q: error: no context exists with the name: "Aks_cluster_name" when tried from WSL I am trying to deploy a kubernetes pipeline from Windows Subsystem for Linux.
I am able to run these commands
az login
az account set --subscription Azure.NPE.Riviera
az aks get-credentials --resource-group RivieraRG --name RivieraAksCls0

When I run the below command
kubectl config use-context RivieraAksCls0

It gives me
error: no context exists with the name: "RivieraAksCls0"

How do I fix this issue?
(Note: I have all the permissions and able to run the above commands from Powershell)

A: I have tested in my environment. The reason for the error is .kube/config file is created in the windows but not in the wsl. The .kube/config file needs to be copied to wsl.
Please use the below command to copy the config file from your windows machine to ubuntu.
cp /mnt/c/Users/[USERNAME]/.kube/config ~/.kube/config

Please refer below screenshot :


text:
Q: Can I stop XCode from breaking on a fatalError/preconditionFailure? I've got some conditions where I need my frameworks to report a fatalError or a preconditionFailure and crash. I have set up some unit tests around these conditions to make sure they hit correctly.
It works really well if the unit tests are run without a Test Host application, but the moment a Test Host application is involved, any fatalError or preconditionFailure hits an automatic XCode break with the message Thread 1: Fatal error: <CUSTOM ERROR HERE>. and stops the execution of the rest of the tests until I press the Continue program execution button manually.
This is obviously an issue because I can't just let my tests run in the background and I need to be actively hitting the Continue button every time one of these tests hits which is quite annoying.
Is there any way to disable this XCode break?

A: Looks like this is fixed in Nimble 7.1.3, a library which I use to test these particular cases. I also found this specific issue in the Nimble library issue 478 which has a comment on a workaround you can use to disable the debug executable when running you tests. Hopefully this helps anyone else stuck with the same problem I had.


text:
Q: Canvas События с мышью Здравствуйте,прошу помощи в следующем:
Необходимо сделать анимацию, чтобы в заданной области (квадрат), объект (круг)произвольно отскакивал от курсора мыши, не вылетая за пределы заданной области.
<html>
<head>
<title>Тени и простенькая анимация</title>
<script type="text/javascript">
var canvas, ctx, w, h;

var ball = {
    x : 50,
    y : 100,
    r : 15,
    vx : 0,
    vy : 0
};
var count = 0;

function init() {
    canvas = document.getElementById("canvas");
    ctx = canvas.getContext("2d");
    w = canvas.width;
    h = canvas.height;
    ctx.font = "18px Times-Roman";
    ctx.strokeRect(0, 0, w, h);
}

setInterval(function() { ctx.clearRect(1, 1, w - 2, h - 2);

    ball.x += ball.vx;
    ball.y += ball.vy;
    ball.vx *=1;

    ball.vy *= 1;
    ball.vy += .55;
    if (ball.y + ball.r > h - 15) {
        count++;
        ball.y = h - 15 - ball.r;
        ball.vy = -Math.abs(ball.vy);
    }

    if (count >= 1) { ball.vy *= 0.99; } if (count == 1) {
    ball.vx =5; } if (ball.x+ball.r > w - 15) { ball.x = w - 30; ball.vx = -Math.abs(ball.vx); } if (ball.x < 30) { ball.x = 30; ball.vx = -ball.vx; }

    ctx.save();
    ctx.fillText("Count: " + count, 250, 50);
    ctx.fillStyle = "black";
    ctx.translate(ball.x, ball.y);
    ctx.beginPath();
    ctx.arc(0, 0, ball.r * 2, 0, 2 * Math.PI, true);
    ctx.closePath();
    ctx.fill();
    ctx.restore();

},25);

</script>

</head>
<body onload="init()">
<canvas id="canvas" width="600" height="600"> error </canvas>
</body>

</html>

http://jsfiddle.net/jLQwb/
A: Напишите обработчик события mousemove для вашего canvas'а. В обработчике получаете кооринаты мыши на canvas'е, определяете, попадает ли курсор в круг. Дальше изменяете направление движения круга. Аналогично, используя несложные формулы, определяете, пересекает ли ваш круг границы области и, если пересекает, меняете направление его движения по вот этим формулам. Формулы для отражения можно сильно упростить, если предположить, что границы области строго вертикальные и горизонтальные. В этом случае достаточно поменять знак у соответствующей составляющей вектора скорости круга.
A: var canvas, ctx, w, h;

var ball = {
    x : 50,
    y : 100,
    r : 15,
    vx : 0,
    vy : 0
};
var count = 0;
var mouseActive = false;
var start = -.5 * Math.PI;

function init() {
    canvas = document.getElementById("canvas");
    ctx = canvas.getContext("2d");
    w = canvas.width;
    h = canvas.height;
    ctx.font = "18px Times-Roman";
    ctx.strokeRect(0, 0, w, h);

    canvas.addEventListener('mouseout', function() {
        mouseActive = false;
    }, false);

    canvas.addEventListener('mousemove', function(e) {
        mouseActive = {
            x: e.clientX - this.getBoundingClientRect().left,
            y: e.clientY - this.getBoundingClientRect().top
        };
    }, false);
}

setInterval(function() {
    ctx.clearRect(1, 1, w - 2, h - 2);

    ball.x += ball.vx;
    ball.y += ball.vy;
    ball.vx *=1;

    ball.vy *= 1;
    ball.vy += .50;
    if (ball.y + ball.r > h - 15) {
        count++;
        ball.y = h - 15 - ball.r;
        ball.vy = -Math.abs(ball.vy);
    }

    if (count >= 1) {
        ball.vy *= 0.99;
    }
    if (count == 1) {
        ball.vx =5;
    }
    if (ball.x+ball.r > w - 15) {
        ball.x = w - 30;
        ball.vx = -Math.abs(ball.vx);
    }
    if (ball.x < 30) {
        ball.x = 30;
        ball.vx = -ball.vx;
    }

    ctx.save();
    ctx.fillText("Count: " + count, 250, 50);

    if(mouseActive) {
        // если шарик касается, то отпружиниваем его
        var x0 = mouseActive.x - ball.x;
        var y0 = mouseActive.y - ball.y;

        if(Math.sqrt(Math.pow(x0, 2) + Math.pow(y0, 2)) < ball.r * 2) {

            if(mouseActive.x < ball.x)  {
                ball.vx = 10;
            }
            else {
                ball.vx = -10;
            }

            ctx.fillStyle = "red";
        }
        else {
            ctx.fillStyle = "black";
        }
    }

    ctx.translate(ball.x, ball.y);
    ctx.beginPath();
    ctx.arc(0, 0, ball.r * 2, 0, 2 * Math.PI, true);
    ctx.closePath();
    ctx.fill();
    ctx.restore();
}, 25);

Вам остается только правильно отразить по формулам @fori1ton
Подсказка: нахождение угла можно подглядеть в этом вопросе: Обработчик mousemove в canvas


text:
Q: Proving Bernoulli's Inequality for $h<0$ I'm answering question 19 of chapter two of Spivak's Calculus and I can't seem to think of a way of doing it. I don't want to look up the answer so I thought I'd ask for a hint as to the general direction I should go in. The question states:
If $h>-1$, then $(1+h)^n\geq1+nh$, why is this trivial for $h>0$?
I think I have proved it for $h>0$ using the binomial expansion which eventually leads to:
$\sum\limits_{i=2}^n { \binom{n}{k}h^k}\geq0$ which I believe is true given $h>0\implies h^k>0$ and $\binom{n}{k} \gt0$ for all $k$ in the range $2\leq k \leq n$.
I can't see how this can generalise easily to the case with $-1<h\lt0$ since obviously I can't use the same logic above. I thought about induction but concluded that it wouldn't work since the range only has non-integer values of $k$. It seems intuitively true since $\left|{h^k}\right|>\left|{h^{k+1}}\right|$ and therefore the terms get smaller and smaller but this doesn't take into account the binomial coefficients. So hopefully this isn't a duplicate, I didn't want to browse too much since I don't want the answer just a hint!
Thanks in advance.

A: We proceed by induction on $n$. The $n=1$ case is trivial: it is just $1+h\ge 1+h$. Suppose the result holds for $n$. Then
$$\begin{align}
(1+h)^{n+1} &=(1+h)(1+h)^n\\
&\ge (1+h)(1+nh)\\
&=1+(n+1)h+nh^2\\
&\ge 1+(n+1)h
\end{align}$$
as desired. Thus by induction this holds for all $n$.
Note: The hypothesis $h\ge -1$ is necessary for the inequality
$$(1+h)(1+h)^n\ge (1+h)(1+nh)$$
since for this to hold, we need $1+h>0$.


text:
Q: Is there a way to determine if Flash has cached an object? Greetings,
I am writing a networked flash application.  The server (an independent C++ app) sends resources for the flash client to manipulate and/or display, eg, images and sound.  I'm assuming that the browser stores these resources in its cache.  Since the resources can be pretty big, I don't want to resend them from the server each time the client restarts the app. I can't use the LSO (flash cookies) because those won't update if the cache gets independently cleared by the browser or the user.
So for the flash gurus..
1) Is there a way to detect if an item has been cached, eg to query the browser cache for a crc or something? Maybe load the object offscreen and (somehow) detect if it shows up?
-OR-
2) Is there a way to avoid using the normal browser cache and cache things myself, in some kind of larger LSO?
Thanks for the help.

A: no you can't. but if you have a preloader for the resources, so the user sees something is loading it should do just fine. if the resources are already in the cache, then they won't see the preloader, the app will just appear. and the request for the images/sounds won't be made to the server so no traffic there. if they aren't in the cache, they will see the preloader so you're exactly there to begin with. i see no reason why you are trying to manipulate the cache in any way in your case.


text:
Q: Adding the onepage checkout on product page I have encounter a slight problem regarding magento checkout process.
Currently I am using the list.phtml file to add orders into the cart, and upon changing the product, the cart is emptied and the newly selected product is added. I do this via this functionality:
this is the form for deleting (i have the form key into it)
<form action="<?php echo $this->getUrl('checkout/cart/updatePost') ?>" method="POST" name="emptyTheCart">
            <?php echo $this->getBlockHtml('formkey'); ?>
            <button type="submit" name="update_cart_action" value="empty_cart" style="display:none" title="<?php echo $this->__('Empty Cart'); ?>" id="empty_cart_button"></button>
      </form>

$('.item').click(function() {
$(this).find('input:radio')[0].checked = true;
var formurl = $(this).find('input:radio').val();
var datafile=$("#product_addtocart_form").serialize();
    var dataExecURL = "<?php echo $this->getUrl('checkout/cart/updatePost') ?>";
     var datafiles=$("#emptyTheCart").serialize();
     datafiles = datafiles + "&update_cart_action=empty_cart";

     $.ajax({
            type : 'POST',
            data : datafiles,
            url  : dataExecURL,
            success: function()
            {
                  $.ajax({
                            type : 'POST',
                            data : datafile,
                            url  : formurl

                        });
            }

        });
});

This part works very good.
The thing is that on the Category page i have the following custom design in the Custom Layout Update:
<block type="cms/block" name="opdracht_text" before="-">
        <action method="setBlockId"><block_id>opdracht_text</block_id></action>
    </block>
<block type="catalog/product_list" name="home.catalog.product.list" alias="products_homepage" template="catalog/product/list.phtml" >

<block type="cms/block" name=" shipping_method" >
        <action method="setBlockId"><block_id> shipping_method </block_id></action>
    </block>
<block type="checkout/onepage_shipping_method_available" template="checkout/onepage/shipping_method/available.phtml"/>

<block type="cms/block" name="billing" >
        <action method="setBlockId"><block_id>billing</block_id></action>
    </block>

<block type="checkout/onepage_billing" name="checkout.onepage.billing" as="billing" template="checkout/onepage/billing.phtml"/>
<block type="cms/block" name="opdracht-delivery" >
        <action method="setBlockId"><block_id>opdracht-delivery</block_id></action>
    </block>

<block type="cms/block" name="payment_method" >
        <action method="setBlockId"><block_id> payment_method </block_id></action>
    </block>
<block type="checkout/onepage_payment" name="checkout.onepage.payment" as="payment" template="checkout/onepage/payment.phtml">
                    <block type="checkout/onepage_payment_methods" name="checkout.payment.methods" as="methods" template="checkout/onepage/payment/info.phtml">
                        <action method="setMethodFormTemplate"><method>purchaseorder</method><template>payment/form/purchaseorder.phtml</template></action>
                    </block>
                    <block type="core/template" name="checkout.onepage.payment.additional" as="additional" />
                    <block type="core/template" name="checkout.onepage.payment.methods_additional" as="methods_additional" />
                </block>
</reference>

As a onepage checkout functionality I have added to magento the extension from
http://www.magentocommerce.com/magento-connect/one-page-checkout.html
when I navigate to my store_url/chekout/cart
I can clearely see the cart and the shipping methods and update the price there and after that proceed to the checkout page at
store_url/ onepage/
where I have my billing + shipping + payment methods
I have taken the blocks from the checkout.xml file from the layout folder from my template (default rwd template) and added them to the category page
The main issue that I am having is the fact that upon opening the page I cannot view the shipping method until after I have selected a product and refreshed the page.
The State/Province Field is not shown at all and also the Payment methods do not show up.
The thing that I am currently trying to accomplish is that the checkout forms to be on the product page like in the following flow:
Product Selection -> Shipping Method -> Billing Method -> Payment Method
These are the steps that I am currently trying to put in one single page  ( the  product display page / category page )

A: I have managed to find the best solutin in this case by using the default xml for the magento iwd one page chekout.
in case you want to have the checkout page on the same page as the product page,
in Catalog->Manage Categories, select your category, then on the Display Settings choose the Static Blocks and products option.
In the custom Design tab, set the page layout to no layout and then use the wrapper block and the desired blocks that you want on the page.
Also, do not forget to include the javascript files on the page.
Example for One page checkout with product list on the same page:
 <reference name="head">

<action method="addItem"><type>skin_js</type><name>js/iwd/opc/checkout.js</name></action>
            <action method="addItem"><type>skin_js</type><name>js/iwd/opc/extend.js</name></action>
            <action method="addJs"><file>mage/directpost.js</file></action>
            <action method="addItem"><type>skin_js</type><name>js/opcheckout.js</name></action>
            <action method="addItem" ifconfig="opc/paypal/status"><type>skin_js</type><name>js/iwd/opc/lipp.js</name></action>

            <action method="addJs" ifconfig="payment/braintree/active"><file>braintree/braintree-1.3.4.js</file></action>
            <action method="addCss" ifconfig="payment/braintree/active"><stylesheet>braintree/css/braintree.css</stylesheet></action>

        </reference>

<reference name="content">

 <!-- Auguria Insurance -->

<block type="opc/wrapper" name="es.checkout.container" template="opc/wrapper.phtml">

              <!-- SHIPPING METHODS FORM -->
                    <block type="checkout/onepage_shipping_method" name="checkout.onepage.shipping_method" as="shipping_method" template="opc/onepage/shipping_method.phtml">
                        <block type="checkout/onepage_shipping_method_available" name="checkout.onepage.shipping_method.available" as="available" template="checkout/onepage/shipping_method/available.phtml"/>
                        <block type="checkout/onepage_shipping_method_additional" name="checkout.onepage.shipping_method.additional" as="additional" template="checkout/onepage/shipping_method/additional.phtml"/>

                    </block>

 <!-- Guest -->

                    <!-- BILLING FORM -->
                  <block type="opc/onepage_billing" name="checkout.onepage.billing" as="billing" template="opc/onepage/billing.phtml"/>

                    <!-- SHIPPING FORM -->
                    <block type="opc/onepage_shipping" name="checkout.onepage.shipping" as="shipping" template="opc/onepage/shipping.phtml"/>

                    <!-- COMMENT FORM -->
                    <block type="opc/onepage_comment" name="checkout.order.comment" as="customer.comment" />

                    <!-- PAYMENTS METHOD FORM -->
                    <block type="checkout/onepage_payment" name="checkout.onepage.payment" as="payment" template="opc/onepage/payment.phtml">
                        <block type="checkout/onepage_payment_methods" name="checkout.payment.methods" as="methods" template="checkout/onepage/payment/methods.phtml">
                            <action method="setMethodFormTemplate"><method>purchaseorder</method><template>payment/form/purchaseorder.phtml</template></action>
                        </block>
                    </block>

                    <block type="checkout/agreements" name="checkout.onepage.agreements" as="agreements" template="opc/onepage/agreements.phtml"/>
                    <block type="opc/onepage_subscribed" template="opc/onepage/review/subscribed.phtml" name="opc.newsletters" />

            </block>

</reference>


text:
Q: How to write to a file and leave an empty line every two records? Python 3.7
I have a list with cities and i want to write them in a text file. Is there a way I can leave an empty line every two cities?
For example:
listc=[London,Rome,Moscow,Paris]
nfile=open("towns.txt",'w')
for line in nfile:
    for town in listc:
        if line%2==0:
            nfile.write(town+'\n')
        else:
            nfile.write('\n')
nfile.close()

I want to achieve this:
London
Rome
\n      # leave an empty line every second city
Moscow
Paris

But it's wrong because it skips the cities instead of writing them next.

A: You should do something like this:
listc=["London", "Rome", "Moscow", "Paris"]
nfile=open("towns.txt", 'w')

i = 0

for town in listc:
       nfile.write(town)
       if i == 2:
           nfile.write('\n')
           i = 0
           continue
       i += 1

nfile.close()

If you just want to reuse your code, just replace the
nfile.write('\n')

with
nfile.write(town)

because that means that if it is not second line, you want to just write "\n" which means empty line => it leaves out the town

A: You're close, but you want to write the name every time and only add an extra line after every other one:
listc = ['London', 'Rome', 'Moscow', 'Paris']
nfile = open("towns.txt", 'w')
for line, town in enumerate(listc):
    nfile.write(town + '\n')
    if line % 2 == 1:
        nfile.write('\n')
nfile.close()


text:
Q: Bijection between $2^{\mathbb R}$ and $\mathbb{ R ^ R}$ I'm well aware of the standard proof based on cardinality arithmetic to show that these two sets have the same cardinality and the question of defining a bijection between the two sets came up. I worked on it a little while and was wondering if there were any gaps, or a simpler method of coming up with such a bijection.
The main idea I had was to take a family of sequences indexed by the real numbers. So that each one of these sequences corresponds to a unique real number. Then I can map each one of these sequences to another number, by applying the binary function from $\mathbb R$ to $\{0,1\}$ and mapping the infinite binary sequence to a real number, use one of the standard bijections.
First let $E$ be a family of sequences indexed by the real numbers. Such that $E_{xi}\neq E_{yj}$ for all $x,y \in \mathbb R$ and $i,j \in \mathbb N$ also with the property that
$\mathbb R= \bigcup_{x \in \mathbb R, i \in \mathbb N} E_{xi}$.
What sort of theorems would I need to prove such a family existed, is it enough to note that the reals can be represented as a uncountable union of countably infinite sets?
Also let $P: 2^{\mathbb N} \rightarrow \mathbb R$ be you favorite bijection.
Now consider an element of $2^{\mathbb R}$ as a function $f: \mathbb R \rightarrow \{0,1\}$ and $g \in \mathbb{ R^R}$ in a similar manner. Then our bijection between the two sets will be the function $\Phi$ which maps $f$ to a function $g$, such that $g(x)=P(F(E_x))$ where $F$ applies $f$ to each element of the sequence $E_x$.
I'm fairly sure this is an onto and one-to-one function. The one-to-one property should follow because the sequences are disjoint, cover $\mathbb R$ and $P$ is a bijection. The onto argument is a little hazier, but it should be possible to recreate the function $f$, by first inverting each element with $P$ and then defining $f$ based on these sequences.

A: Once you have the bijection
$P:2^\mathbb{N}\cong\mathbb{R}$, you can build your desired
bijection as follows.
First, note that $\mathbb{N}\times 2^\mathbb{N}\cong
2^\mathbb{N}$, essentially  by the bijection that associates $(n,A)$ with
$\{n\}\cup (n+1+A)$, except that this will miss the empty set on the right, but we can fix this by composing with a map witnessing $2^\mathbb{N}-\{\varnothing\}\cong 2^\mathbb{N}$, such as shifting on a fixed countable subset.
Now simply observe that
$$\mathbb{R}^\mathbb{R}\cong
(2^\mathbb{N})^{(2^\mathbb{N})}\cong 2^{(\mathbb{N}\times
2^\mathbb{N})} \cong 2^{(2^\mathbb{N})} \cong 2^\mathbb{R},
$$
which provides the desired bijection. The first map is conjugation by $P$, simply
composing with $P^{-1}$ and $P$ before and after; the second map is an easy exercise in parenthesis rearranging; the
third map applies the observation above; and the final map
applies $P$.

A: A function $f:\mathbb R\rightarrow\mathbb R$ can be seen as a member of $\mathcal P(\mathbb R\times\mathbb R)$, which is just the so-called graph of the function, namely the set of all pairs $(x,y)$ such that $y=f(x)$. Since $$|\mathcal P(\mathbb R\times\mathbb R)|={|2^{\mathbb R\times\mathbb R}|}=|2^\mathbb R|$$
the result follows.


text:
Q: Rename Data sql to xml I have a table with different data, and I'm creating an xml of those tables, but I would like to change the name of those fields in the xml, for example
this my query
 SELECT TOP (1) [ECB_ID]
     ,[ECB_PASSWORD_GENERATED]
     ,[ECB_CONSECUTIVE_NUMBER]
     ,[ECB_BILL_DATE]
     ,[TRN_ID]
    ,[RCV_ID]
    ,[SLC_ID]
    ,[ECB_CREDIT_TIME]
    ,[PMN_ID]
    ,[IVS_ID]
    ,[RFI_ID]
    ,[NMT_ID]
    ,[SCM_ID]
    ,[OTH_ID]
    ,[ECB_SEND_DATE]
     ,[MST_ID]
   ,[ECB_RESPONSE_DATE]
    ,[ECB_PAYDATE]
    ,[MTP_ID]
     ,[QRC_ID]
   FROM [crdx_COREDev1].[dbo].[ECB_ELECTRONICBILL]
   FOR XML PATH ('FE')

and this is my output xml
 <FE>
 <ECB_ID>1</ECB_ID>
 <ECB_PASSWORD_GENERATED>0</ECB_PASSWORD_GENERATED>
 <ECB_CONSECUTIVE_NUMBER>0</ECB_CONSECUTIVE_NUMBER>
 <ECB_BILL_DATE>2017-10-18T11:03:48.313</ECB_BILL_DATE>
 <TRN_ID>1</TRN_ID>
 <RCV_ID>48418</RCV_ID>
 <SLC_ID>1</SLC_ID>
 <ECB_CREDIT_TIME>0</ECB_CREDIT_TIME>
 <PMN_ID>1</PMN_ID>
 <IVS_ID>196</IVS_ID>
 <RFI_ID>1</RFI_ID>
 <NMT_ID>2</NMT_ID>
 <SCM_ID>1</SCM_ID>
 <OTH_ID>1</OTH_ID>
 <ECB_SEND_DATE>1900-01-01T00:00:00</ECB_SEND_DATE>
 <MST_ID>-1</MST_ID>
 <ECB_RESPONSE_DATE>1900-01-01T00:00:00</ECB_RESPONSE_DATE>
 <ECB_PAYDATE>2017-10-18T11:03:48.313</ECB_PAYDATE>
 <MTP_ID>1</MTP_ID>
<QRC_ID>1</QRC_ID>
</FE>

and I would like the output to be like this
<FE>
 <id>1</id>
 <pass>0</pass>
 <CONSECUTIVE>0</CONSECUTIVE>
  ....
 </FE>

A: Just alias the fields.
 SELECT TOP (1) [ECB_ID] AS id
   ,[ECB_PASSWORD_GENERATED] AS pass
   ,[ECB_CONSECUTIVE_NUMBER] AS CONSECUTIVE...


text:
Q: How to add UICollectionView in UICollectionView (programmatically) Watching a youtube, I'm studying.
I want to change parts.
ImageView want to use instead UICollectionView.
So I want to scroll the image horizontally.
I would like to know how to add UICollectionView.
How can I ...?

code: https://github.com/purelyswift/facebook_feed_dynamic_cell_content

A: Looking at the image, it looks more like a UICollectionView inside a UITableView. See this article


text:
Q: How can I achieve portability with sed -i (in-place editing)? I'm writing shell scripts for my server, which is a shared hosting running FreeBSD. I also want to be able to test them locally, on my PC running Linux. Hence, I'm trying to write them in a portable way, but with sed I see no way to do that.
Part of my website uses generated static HTML files, and this sed line inserts correct DOCTYPE after each regeneration:
sed -i '1s/^/<!DOCTYPE html> \n/' ${file_name.html}

It works with GNU sed on Linux, but FreeBSD sed expects the first argument after -i option to be extension for backup copy. This is how it would look like:
sed -i '' '1s/^/<!DOCTYPE html> \n/' ${file_name.html}

However, GNU sed in turn expects the expression to follow immediately after -i.
(It also requires fixes with newline handling, but that's already answered in here)
Of course I can include this change in my server copy of the script, but that would mess i.e. my use of VCS for versioning. Is there a way to achieve this with sed in a fully portable way?

A: You can also do manually what perl -i used to do under the hood:
{ rm -f file && { echo '<!DOCTYPE html>'; cat; } > file;} < file

Like perl -i, there's no backup, and like most solutions given here, beware it may affect the permissions, ownership of the file and may turn a symlink into a regular file.
With:
sed '1i\
<!DOCTYPE html>' file 1<> file

sed would overwrite the file over itself, so would not affect ownership and permissions or symlinks. It works with GNU sed because sed will typically have read a buffer full of data from file (4k in my case) before overwriting it with the i command. That wouldn't work if the file was more than 4k except for the fact that sed also buffers its output.
Basically sed works on blocks of 4k for reading and writing. If the line to insert is smaller than 4k, sed will never overwrite a block it has not read yet.
I wouldn't count on it though.
Beware that with all those solutions, if the file system is full or the system crashes in the middle, you may end up losing data.

A: GNU sed accepts an optional extension after -i. The extension must be in the same argument with no intervening space. This syntax also works on FreeBSD sed.
sed -i.bak -e '…' SOMEFILE

Note that on FreeBSD, -i also changes the behavior when there are multiple input files: they are processed independently (so e.g. $ matches the last line of each file). Also this won't work on BusyBox.
If you don't want to use backup files, you could check which version of sed is available.
# Assume that sed is either FreeBSD/macOS or GNU
case $(sed --help 2>&1) in
  *GNU*) set sed -i;;
  *) set sed -i '';;
esac
"$@" -e '…' "$file"

Or alternatively, to avoid clobbering the positional parameters, define a function.
case $(sed --help 2>&1) in
  *GNU*) sed_i () { sed -i "$@"; };;
  *) sed_i () { sed -i '' "$@"; };;
esac
sed_i -e '…' "$file"

If you don't want to bother, use Perl.
perl -i -pe '…' "$file"

If you want to write a portable script, don't use -i — it isn't in POSIX. Do manually what sed does under the hood — it's only one more line of code.
sed -e '…' "$file" >"$file.new"
mv -- "$file.new" "$file"

A: FreeBSD sed, which is used on Mac OS X as well, needs the -e option after the -i switch to define & recognise the following (regex) command correctly & unambiguously.
In other words, sed -i -e ... should work with both FreeBSD & GNU sed.
More generally, omitting the backup extension after FreeBSD sed -i requires some explicit sed option or switch following the -i to avoid confusion on part of FreeBSD sed while parsing its command-line arguments.
(Note, however, that sed in-place file edits lead to file inode changes, see "In-place" editing of files).
(As a general hint, recent versions of FreeBSD sed have the -r switch to increase compatibility with GNU sed).
echo a > testfile.txt
ls -li testfile.txt
#gsed -i -e 's/a/A/' testfile.txt
#bsdsed -i 's/a/A/' testfile.txt  # does not work
bsdsed -i -e 's/a/A/' testfile.txt
ls -li testfile.txt
cat testfile.txt

A: You can use Vim in Ex mode:
ex -s -c '1i|<!DOCTYPE html>' -c x file

*

*1 select first line

*i insert text and newline

*x save and close

A: If you don't find a trick to make sed play nice, you could try:

*

*Don't use -i :
sed '1s/^/<!DOCTYPE html> \n/' "${file_name.html}" > "${file_name.html}.tmp" &&
  mv "${file_name.html}.tmp" "${file_name.html}"

*Use Perl
perl -i -pe 'print "<!DOCTYPE html> \n" if $.==1;' "${file_name.html}"

A: ed
You can always use ed to prepend a line to an existing file.
$ printf '0a\n<!DOCTYPE html>\n.\nw\n' | ed my.html

Details
The bits around the <!DOCTYPE html> are commands to ed instructing it to add that line to the file my.html.
sed
I believe this command in sed can also be used:
$ sed -i '1i<!DOCTYPE html>\n` testfile.csv

A: To emulate sed -i for a single file portably while avoiding race conditions as much as possible:
sed 'script' <<FILE >file
$(cat file)
FILE

By the way, this also handles the possible problem that sed -i introduces in that, depending on directory and file permissions, sed -i might enable a user to overwrite a file which that user does not have permissions to edit.
You might also do backups like:
sed 'script' <<FILE >file
$(tee file.old <file)
FILE


text:
Q: Long polling HTTP Node.js using Redis I am implementing an HTTP Long Polling for an Express app but i encounter an error. Here is how the app should behave:
The app is a Evernote like, users can POST new note to the app [Note(txt, author, date)]. Users can subscribe (GET /subscribe/:author) to an author, so when a author post a new note, he should receive the response of GET /subscribe/:author.
I achieved to do this but with any note (not the good author) but I have an issue when I put a comparaison to see if the note is posted by the good author.
Here is my code:
subscribe.js
router.get('/:auteur', (req, res, next) => {

  const auteur = req.params.auteur;

  rc.lrange("notes", 0, -1, (err, reply) => {
    const notes = reply.map( note => { return JSON.parse(note) })
    const notesAuteur = notes.filter(note => note.auteur == auteur)

    subscriber.on("message", (channel, message) => {
      const noteRecu = JSON.parse(message)
      // if(noteReceived.author == authorAsked)
      if(noteRecu.auteur == auteur) {
        // Add this new note to old one
        notesAuteur.push(noteRecu)
        // Responde
        res.send(notesAuteur)
      }
    })
  })
})

subscriber.subscribe("notes_publish")

Here is a bugged scenario:

*

*user subscribe to "john" ( GET /subscribe/john )

*"alex" post a new note ( POST /notes ) #Server don't respond

*"john" post a new note ( POST /notes ) #Server error : "Can't set headers after they are sent."

How to tell my server :
if(note.author == goodAuthor) {
    res.send(data)
} else {
    Don't()
}

Thanks for your help !


text:
Q: Finding and combining lines (Strings) together So I have a String/txt file:
All purchases: blabla : 1 derp : 20 blabla : 1 herp : 30
This is just an example, a real file will be generated based on the users input
So what I need to do is combine the similar strings with similar names (First part) together and make them look like this: (name) : (number) x(amount of same strings)
For example lets take the file that we had:
All purchases: blabla : 1 derp : 20 blabla : 1 herp : 30
After parsing it must look like: All purchases: blabla : 1 x2 derp : 20 herp : 30
I have tried writing down the last value into a variable and checking it with the next value, but what if the values are in a different order? That's where I got stuck.

A: Since each entry has three components:
[name] : [number]
You can do a few things here. Something along the lines of:
Scanner s = new Scanner(new File("YourFileHere.txt"));
ArrayList<String> entries = new ArrayList<String>();
while(s.hasNext())
{
    entries.add(s.next() + " " + s.next() + " " s.next());
}

You'll of course have to remove the leading 'All purchases:', but now everything is in the arraylist in the form [name] : [number]

You simply have to determine how many of each there are. From here you can sort them and then count them.


text:
Q: Best way to compile subdirectories into libraries with automake? I have the following files
├── configure.ac
├── main.cpp
├── Makefile.am
└── procs
    ├── Makefile.am
    ├── proc1
    │   └── subprocs
    │       ├── subprocA
    │       │   ├── ProcA_SubprocA.cc
    │       │   └── ProcA_SubprocA.h
    │       └── subprocB
    │           ├── ProcA_SubprocB.cc
    │           └── ProcA_SubprocB.h
    ├── proc2
    │   └── subprocs
    │       ├── subprocA
    │       │   ├── ProcB_SubprocA.cc
    │       │   └── ProcB_SubprocA.h
    │       └── subprocB
    │           ├── ProcB_SubprocB.cc
    │           └── ProcB_SubprocB.h
    └── Subprocs.h

My goal is to create a library from everything in procs so it can be used in main.cpp which could look something like this:
main.cpp
#include "Subprocs.h"

int main(){

    ProcA_SubprocA * p = new ProcA_SubprocA();
    p->use();
    delete p;

    return 0;
}

I would like to have all the includes of the subprocs in Subprocs.h, so it can be used as some kind of interface:
Subprocs.h
#include "ProcA_SubprocA.h"
#include "ProcA_SubprocB.h"
#include "ProcB_SubprocA.h"
#include "ProcB_SubprocB.h"

My configure.ac looks like this:
configure.ac
AC_PREREQ([2.69])
AC_INIT([main], [0.1])
AM_INIT_AUTOMAKE([foreign subdir-objects])

#AC_CONFIG_MACRO_DIR([m4])
#LT_INIT

AC_PROG_CXX
AC_PROG_CC
AC_PROG_RANLIB

AC_CONFIG_FILES([Makefile procs/Makefile])
AC_OUTPUT

and my Makefile.am's like this
Makefile.am
SUBDIRS = procs

AM_CPPFLAGS = -Iprocs

bin_PROGRAMS = main
main_SOURCES = main.cpp
#added:
main_LDADD = procs/libprocs.a

#ACLOCAL_AMFLAGS = -I m4

procs/Makefile.am
AM_CPPFLAGS = -Iproc1/subprocs/subprocA -Iproc1/subprocs/subprocB \
              -Iproc2/subprocs/subprocA -Iproc2/subprocs/subprocB

#lib_LIBRARIES = libprocs.la
noinst_LIBRARIES = libprocs.a
libprocs_a_SOURCES = Subprocs.h \
                      proc1/subprocs/subprocA/ProcA_SubprocA.cc proc1/subprocs/subprocA/ProcA_SubprocA.h \
                      proc1/subprocs/subprocB/ProcA_SubprocB.cc proc1/subprocs/subprocB/ProcA_SubprocB.h \
                      proc2/subprocs/subprocA/ProcB_SubprocA.cc proc2/subprocs/subprocA/ProcB_SubprocA.h \
                      proc2/subprocs/subprocB/ProcB_SubprocB.cc proc2/subprocs/subprocB/ProcB_SubprocB.h

When I type
#libtoolize && autoreconf -i -f && ./configure && make
autoreconf -i -f && ./configure && make

I get a file called libprocs.la in procs but I don't get a binary. I am also fairly certain that my Makefiles are wrong since I can't even compile main.cpp by hand.
Is it at all possible to do what I want here? Or am I overthinking this and I don't even need a library in the first place? The important part for me is that main.cpp only includes Subprocs.h which then contains all includes of the subprocs.
Thank you in advance!

A: There are numerous oddities in what you've presented, and one clear error.  You say,

I get a file called libprocs.la in procs but I don't get a binary. I
  am also fairly certain that my Makefiles are wrong since I can't even
  compile main.cpp by hand.

Surely make's output contains one or more error messages that explain why the build fails.  Unless your makeing only the procs subdirectory in the first place, I guess, in which case of course you would not be getting main built.
But I'm reasonably confident that I can guess: you're getting a linker error complaining that it can't find ProcA_SubprocA::ProcA_SubprocA.  This would be because although your Makefile specifies that the library should be built (and also installed), it nowhere says that it needs to be linked into main.  There's a pretty easy fix for that, which I will return to in a moment.
First, however, let's talk about libprocs.la.  The .la suffix is meaningful to the Autotools, designating a "libtool archive", but you're actually building it as an ordinary static library.  Indeed libtool isn't doing anything particularly useful for you here; I would dump it by removing the LT_INIT from your configure.ac (and do not run libtoolize again, as it will put that back).  Then, change the name of the library to be built to the more standard libprocs.a.
Furthermore, since this library seems to be intended only for use with the one program being built, it is unhelpful to include it in the install in its own right.  Therefore, instead of designating it in lib_LIBRARIES, designate it as a non-installed convenience library:
noinst_LIBRARIES = libprocs.a

You will then need to make a corresponding change to the library's SOURCES variable:

libprocs_la_SOURCES = ...

libprocs_a_SOURCES = ...

Coming back to the main program now, you need to tell make (and Automake) that the library needs to be linked into program main.  There are a few variations on how you could do that, but I'm going to suggest a fairly simple one:
main_LDADD = procs/libprocs.a

After those changes, rerun autoreconf (but not libtoolize).  Remember, however, that you need to run that only after changing Autotools sources -- just Makefile.am and configure.ac files in your case.  It is a detail of maintaining and developing the package and its build system in particular.  It should not be a routine part of building or installing the package.


text:
Q: Cannot GET / error in browser (nodejs express) while running this script const express=require('express')
const path=require('path')

const app=express()

app.use(function(req,res,next){
console.log('hello')
next()

})
app.get('/signup',function(req,res,next){
res.sendFile(path.join(__dirname,'signup.html'))
next()

})
app.get(function(req,res){
console.log('end')

})
app.post('/signup',function (req,res){
res.send('hhhhh')

})

app.listen(300,function(){

console.log('server started')

Cannot GET /  error  in browser (nodejs express) while running this script
please help me...


text:
Q: Macbook retina 13" Mini DisplayPort to VGA Adapter. Does anybody test it? Recently I bought a HDMI to VGA adaptor for my macbook but it doesn't work on ubuntu 14.04. Again I am going to connect my macbook to a projector with VGA input. I need to know if anybody test Mini DisplayPort to VGA Adapter ?
If anybody know any solution to connect macbook pro retina to VGA input please let me know.

A: I have connected my 13" retina (mgx82) Macbook pro to VGA video projector(monitor) with mini display to VGA adaptor and it works fine.


text:
Q: React Native onBack takes to First Screen issue My application contain drawer navigator and stack navigator. But issue is that when i tried to goback it takes me to first screen even if i am 2-3 stack deep. It don't show previous screen it always takes me to main screen. Below is my App.js code
import React from 'react';
import {
    ActivityIndicator,
    AsyncStorage,
    Button,
    StatusBar,
    StyleSheet,
    View,
} from 'react-native';
import {StackNavigator, SwitchNavigator, DrawerNavigator} from 'react-navigation';

import Screen1 from './Screen/Screen1';
import Screen2 from './Screen/Screen2';
import Screen3 from './Screen/Screen3';
import Screen4 from './Screen/Screen4';
import Screen5 from './Screen/Screen5';
import ScreenList from './Screen/ScreenList';

import Login from './Screen/Login';

class AuthLoadingScreen extends React.Component {
    constructor() {
        super();
        this._bootstrapAsync();
    }

    // Fetch the token from storage then navigate to our appropriate place
    _bootstrapAsync = async () => {
        const userToken = await AsyncStorage.getItem('user');

        // This will switch to the App screen or Auth screen and this loading
        // screen will be unmounted and thrown away.
        this.props.navigation.navigate(userToken ? 'App' : 'Auth');
    };

    // Render any loading content that you like here
    render() {
        return (
            <View style={styles.container}>
                <ActivityIndicator/>
                <StatusBar barStyle="default"/>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
});

const AppStack = DrawerNavigator({
    Screen1: { screen: Screen1},
    Screen2: { screen: Screen2},
    Screen3: { screen: Screen3},
    Screen4: { screen: Screen4},
    Screen5: { screen: Screen5},
    ScreenList: { screen: ScreenList},
}, {contentComponent: SideBar});

const AuthStack = StackNavigator({Login: { screen: Login}},{headerMode:'none'});

const MyNavigator = SwitchNavigator(
    {
        AuthLoading: AuthLoadingScreen,
        App: AppStack,
        Auth: AuthStack,
    },
    {
        initialRouteName: 'AuthLoading'
    }
);

export default class App extends React.Component {
    render() {
        return <MyNavigator />;
    }
}

From Screen 1, i click on button and go to screen 2 and screen 3 like:
onPress={() => navigate('Screen2', { })}

And it works fine, but when i go back using bellow code from screen 3 it takes me to screen 1 not screen 2
this.props.navigation.goBack();

Am i missing something?

A: Did you try
1 -> 2 -> 3 -> 4
<Button
   onPress={() => goBack('3')}
   title="Go to 3 screen"
 />


text:
Q: SpriteBatch set below the level of the Actor in libgdx I'm making a game in libgdx , and I've added different Actor forming my scene .
Currently however, I added a texture:
//other variables:
Texture texture; int sourceX = 0;

//create() method
texture = new Texture(Gdx.files.internal("background.png"));
texture.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat);
...other code...
stage.addActor(actorMen);

and in the render() method:
//render() method
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
sourceX+=10;
batch.begin();
batch.draw(texture, 0, 0, sourceX, 0, (int) background.getWidth(), (int) background.getHeight());
batch.end();

everything works , repeat the effect goes to great ... but my problem is that I covers all Actor as if their z- index was lower than the background .
And ' you can indicate the spritebatch to remain lower than the actors ?
EDIT SOLUTION set render() method like this:
//render() method

sourceX+=10;
batch.begin();
batch.draw(texture, 0, 0, sourceX, 0, (int) background.getWidth(), (int) background.getHeight());
batch.end();
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();

A: Solution, move the stage.act() and stage.draw() on the end the method render:
//render() method

sourceX+=10;
batch.begin();
batch.draw(texture, 0, 0, sourceX, 0, (int) background.getWidth(), (int) background.getHeight());
batch.end();
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();


text:
Q: How to write a select statement that can match 1 of 3 parameters across multiple tables My MySQL is rusty and I can't figure out how to get this query to return what I'm looking for.  I first thought to just use joins but that gave me less results than it should have.
I have four tables: users, users_roles, content, subscriptions
I need to select the users' ids (uid) from the users table when it matches one of three parameters:

*

*users.uid = users_roles.uid

*users.uid = content.uid WHERE content.type=article

*users.uid = DISTINCT subscriptions.uid
Only one out of three of these parameters needs to be met, not all of them, and it is ok if it only meets 1 or 2 or all 3.
Sample Data:
Users table -
username=abc, uid=123, email=example@example.com
username=def, uid=124, email=test@test.com
username=nfc, uid=432, email=test2@test.com
username=jui, uid=999, email=spam@account.com

User roles table -
uid=123, role=1
uid=432, role=1

Content table -
cid=1, uid=432, data=x, type=article

Subscription table -
uid=124

The query should return all users in the user table of the example data above except for uid 999 since that uid is not in user roles, content, or subscriptions table.

A: As I understand your question, following statement should do it:
SELECT
    uid
FROM
    users
WHERE
    -- there's a uid in table users_roles
    uid IN (SELECT ur.uid FROM users_roles ur)
OR
    -- there's a uid in nodes with node.type is your article input value (I assume)
    uid IN (SELECT node.uid FROM node WHERE node.type = <article>)
OR
    -- or lastly your uid is in the simplenews table
    uid IN (SELECT s.uid FROM simplenews s)


text:
Q: Why is message put into a dead-letter queue (MSMQ)? Preamble:
I have a web application, which sends MSMQ messages (with UseDeadLetterQueue = true) from time to time. I can also see that some of those messages are put into a system dead letter queue. However, I can't see the failure reason directly from "Computer Management" console.
I found the following resource:
https://msdn.microsoft.com/en-us/library/ms789035(v=vs.110).aspx,

which allows to check message status and failure. But it's usable only in WCF scope (as it uses OperationContext).

Basically checking message status and failure reason is what I need, but how can I configure a WCF service to listen to a dead-letter queue and track all the messages put inside, regardless of sender?

Or is there any other (non-WCF) way to get reason of why specific message was put into a dead letter queue?

A: The linked article you found tells you how to create a WCF service that takes messages off the DLQ. Note that it tells you you must use AddressFilterMode = AddressFilterMode.Any to pull all messages off regardless of sender.
Note: by the time the message ends up on the DLQ, you will not have information about the reason this occurred. Regardless of whether or not you're using WCF that information isn't stored in the queue.
If for example your recipient is a WCF listener using the MSMQ binding any exception thrown will cause the message to fail to get delivered. MSMQ will retry for a while and then eventually give up and put the message in the DLQ. So if you wanted to know the original reason you need to add some tracing in your WCF service to catch and trace thrown exceptions.


text:
Q: How to convert Perl regular expression into Python? How do you convert this Perl regular expression into Python:
(?:

    ^(?:never|no|nothing|nowhere|noone|none|not|
        havent|hasnt|hadnt|cant|couldnt|shouldnt|
        wont|wouldnt|dont|doesnt|didnt|isnt|arent|aint
    )$

)

|

n't

A: That expression will work as is in Python. Just use the re.VERBOSE switch or remove all the whitespace.
Demo:
>>> import re
>>> pattern = re.compile('''\
... (?:
...
...     ^(?:never|no|nothing|nowhere|noone|none|not|
...         havent|hasnt|hadnt|cant|couldnt|shouldnt|
...         wont|wouldnt|dont|doesnt|didnt|isnt|arent|aint
...     )$
...
... )
...
... |
...
... n't
... ''', flags=re.VERBOSE)
>>> pattern.match('never').group()
'never'
>>> pattern.match('wouldnt').group()
'wouldnt'


text:
Q: BGI error graphics not inialize in C I am developing my project in C. On windows-7 I am using DosBox to implement my code. On compile my project doesn't show any error. But when I run my project its simply display the following line on output screen.
bgi error graphics not initialized use initgraph

Here's my code:
void firstscreen()
{
    int gm=DETECT;
    initgraph(&gm,&gm,"");
    floodfill(300,230,RED);
    settextstyle(TRIPLEX_FONT,HORIZ_DIR,5);
    setcolor(BLUE);
    sound(1345);
    outtextxy(100,40,"S.A.JAIN COLLEGE ");
    outtextxy(190,90,"AMBALA CITY");
    settextstyle(TRIPLEX_FONT,HORIZ_DIR,3);
    setcolor(GREEN);
    outtextxy(210,230,"PROJECT REPORT ");
    outtextxy(290,265,"ON ");
    outtextxy(240,300,"MOBILE SHOP");
    settextstyle(DEFAULT_FONT,HORIZ_DIR,2);

    setcolor(CYAN);
    settextstyle(SANS_SERIF_FONT,HORIZ_DIR,2);
    outtextxy(160,400,"Developed By - MAHI");
    setcolor(BLUE);
    settextstyle(1,HORIZ_DIR,1);
    outtextxy(240,440,"Press any key to enter in the program........");
    nosound();
    getch();
    closegraph();
}

void showroom()
{
    int gm=DETECT;
    initgraph(&gm,&gm,"");
    floodfill(300,230,RED);
    settextstyle(TRIPLEX_FONT,HORIZ_DIR,4);
    setcolor(BLACK);
    sound(1345);
    outtextxy(240,25,"SHOWROOM");
    outtextxy(240,50,"^^^^^^^^^");
    settextstyle(TRIPLEX_FONT,HORIZ_DIR,3);
    setcolor(RED);
    outtextxy(10,85,"Model No       Price(Rs\-)      Color        Wranty");
    settextstyle(TRIPLEX_FONT,HORIZ_DIR,2);
    setcolor(GREEN);
    outtextxy(10,125, "X2-01             2300           WHITE           1 YEAR");
    outtextxy(10,155,"X3-02             7800           BLACK           1 YEAR  ");
    outtextxy(10,185,"E5                 4800           BLACK           1 YEAR");
    outtextxy(10,215,"3110              3800           BLACK           1 YEAR  ");
    outtextxy(10,245,"7210              5200           BLACK           1 YEAR");
    outtextxy(10,275,"5233              5800           BLACK           1 YEAR ");
    outtextxy(10,305,"N70               8000           BLACK           1 YEAR");
    outtextxy(10,335,"N72               8800           BLACK           1 YEAR");
    outtextxy(10,365,"N95               10500          BLACK           1 YEAR");
    setcolor(BLUE);
    settextstyle(1,HORIZ_DIR,1);
    outtextxy(440,440,"Press enter......");

    nosound();
    getch();
    closegraph();
}

On SO I saw similar question on this but no answer is accepted by the owner. And also when I try those solutions still same problem. Most of the answers suggest to use path of BGI library. Path of BGI library in my computer.
C:\\TurboC++\\Disk\\TurboC3\\BGI

In my code I am setting path like follow-
int gm = DETECT;
initgraph(&gm,&gm,"C:\\TurboC++\\Disk\\TurboC3\\BGI");

But not working still same problem. Please help me to solve this. Thanks in advance.

A: Recently I have similar problem. To solve this copy EGAVGA.BGI from BGI folder and paste into BIN folder.
Hope it works.


text:
Q: Lenovo Legion 5 randomly kills entire wifi network I have this new Lenovo Legion 5 laptop. Since day 1, I've been having this very specific problem. It will consistently kill the wifi router in my house. It kills the wifi signal on every device that is connected to it. The issue isn't with the wireless router itself, since that doesn't happen with the multiple devices that I have connected to the router.
The wifi card isn't the issue, because when the laptop goes offline, so does everything else in my house. And when I'm not using the laptop, this isn't a problem. For the record, the operating system is Windows 10. I mistakenly thought it was an issue with the wireless card and had a lenovo technician replace it a few weeks ago. This did not alleviate the problem.


text:
Q: How to turn a string with unquoted keys into a dict in Python I have a string
"{a:'b', c:'d',e:''}"

Please not that the keys to the dictionary entries are unquoted, so a simple eval("{a:'b', c:'d',e:''}") as suggested in a previous question does not work.
What would be the most convenient way to convert this string to a dictionary?
{'a':'b', 'c':'d', 'e':''}

A: If this is from a trusted source (do not use this for general user input, as eval is not secure; but then again, if you're getting input from a potentially malicious user you should use JSON format and the json module instead), you can use eval with a trick.
source = """{e: '', a: 'b', c: 'd'}"""

class identdict(dict):
    def __missing__(self, key):
        return key

d = eval(source, identdict())
print(d)

prints
{'a': 'b', 'c': 'd', 'e': ''}

How this works is that we create a new dictionary subclass identdict that defines the magic method __missing__. This method is called for lookups on keys that are missing from the dictionary. In this case, we just return the key, so the dictionary maps keys to themselves. Then the source is evaluated using an identdict instance as the globals argument. eval will look up the values of variables from the globals mapping; as it is an identdict, the value of each variable accessed is conveniently now the name of the variable.
Works for even more complex strings as values, and anything that is proper Python literal syntax.

A: Depending on the complexity of what you're parsing, this could work:
s = "{a:'b', c:'d',e:''}"
d = dict([
    (x.split(':')[0].strip(), x.split(':')[1].strip("' "))
    for x in s.strip("{}").split(',')
])

A: WARNING This approach will not work as desired if you have a key mapping to an empty string in the middle of your "dictionary." I'll not delete this answer because I think this approach might still be salvageable.
This might be a little more general than Will's answer, although, it is still going to depend on the exact structure of what you are parsing. If your key, value pairs will consist of alphanumeric words, you should be fine, though.
In [3]: import re

In [4]: import itertools

In [5]: my_string = "{a:'b', c:'d',e:''}"

In [6]: temp = re.findall(r"\w", my_string)

In [7]: temp = itertools.zip_longest(temp[0::2], temp[1::2], fillvalue = "")

In [8]: dict(temp)
Out[8]: {'a': 'b', 'c': 'd', 'e': ''}

If you want to know what is happening with the zip function, see these questions:
Collect every pair of elements from a list into tuples in Python
I used itertools.zip_longest so you can use a fill value, inspired by:
Pairs from single list

A: Manual parsing is error-prone and hard to make general, and eval-based approaches fail when the keys are Python keywords. The currently accepted answer breaks if values contain spaces, commas, or colons, and the eval answer can't handle keys like if or for.
Instead, we can tokenize the input as a series of Python tokens and replace NAME tokens with STRING tokens, then untokenize to build a valid dict literal. From there, we can just call ast.literal_eval.
import ast
import io
import tokenize

def parse(x):
    tokens = tokenize.generate_tokens(io.StringIO(x).readline)
    modified_tokens = (
        (tokenize.STRING, repr(token.string)) if token.type == tokenize.NAME else token[:2]
        for token in tokens)

    fixed_input = tokenize.untokenize(modified_tokens)

    return ast.literal_eval(fixed_input)

Then parse("{a:'b', c:'d',e:''}") == {'a':'b', 'c':'d', 'e':''}, and no problems occur with keywords as keys or special characters in the values:
>>> parse('{a: 2, if: 3}')
{'a': 2, 'if': 3}
>>> parse("{c: ' : , '}")
{'c': ' : , '}

A: import re
str="{a:'b', c:'d',e:''}"
dict([i.replace("'","").split(":") for i in re.findall(r"(\w+\:'.*?')",str)])


text:
Q: How to fill data to template excel by php without api I have some problem using phpexcel api.
this api is taking to long to fill data to exist template excel.
so, I want to write by pure php without using any api.
I want to know how to fill data to template excel by pure php.
Please give me some advise. Thanks :)

A: Old xls files were proprietary binary file formats, quite complicated, also known as Excel BIFF, you can find

*

*reverse engineered specification here: http://www.openoffice.org/sc/excelfileformat.pdf

*Microsoft's public specification here: [MS-XLS]: Excel Binary File Format (.xls) Structure (PDF) and here: [MS-XLS]: Excel Binary File Format (.xls) Structure (HTML)
New xlsx files are "standardized" open formats. It is basically a zip file (rename it to *.zip and extract) with few xml files inside
Some general information is available at http://en.wikipedia.org/wiki/Office_Open_XML
More detailed documentation is available from

*

*MSDN: Office → Dev Center → Open XML SDK → Understanding the Open XML file formats

*and from Ecma International → Ecma Office Open XML File Formats Standard
Still even the new file format is quite complicated if you want to be able to do everything or anything. In that case reusing several man/years of development effort (including debugging) materialized in a form of an existing PHP library as suggested by @mark-baker is reasonable
If you just need to do a specific task, e.g. populate existing xlsx template file with some data then you only need

*

*a PHP functions for copying files

*a PHP functions to work with zip files

*and a PHP functions to work with xml files

*and the documentation (from the links above) or an executable documentation in a form of Excel.exe

EDIT better links to the specification both for the old and for the new Excel file formats were provided by Mark Baker


text:
Q: MDADM RAID-1 "not large enough to join array" on identical partition tables I have two disks with identical partition tables (sudo sfdisk -d /dev/sda | sudo sfdisk /dev/sdb) that mdadm refuses to merge as a RAID-1 array.
$ sudo mdadm --manage /dev/md0 --add /dev/sdb1
mdadm: /dev/sdb1 not large enough to join array

Any ideas about what's going on here?

Details
$ sudo mdadm --detail /dev/md0
/dev/md0:
           Version : 1.2
     Creation Time : Thu Mar 22 19:34:24 2018
        Raid Level : raid1
        Array Size : 976627712 (931.38 GiB 1000.07 GB)
     Used Dev Size : 976627712 (931.38 GiB 1000.07 GB)
      Raid Devices : 2
     Total Devices : 1
       Persistence : Superblock is persistent

     Intent Bitmap : Internal

       Update Time : Tue Aug 25 11:56:19 2020
             State : clean, degraded
    Active Devices : 1
   Working Devices : 1
    Failed Devices : 0
     Spare Devices : 0

Consistency Policy : bitmap

              Name : hostname:0  (local to host hostname)
              UUID : xxxxxxxx:xxxxxxxx:xxxxxxxx:xxxxxxxx
            Events : 459187

    Number   Major   Minor   RaidDevice State
       -       0        0        0      removed
       1       8        1        1      active sync   /dev/sda1

$ sudo parted /dev/sda unit s print
Model: XXX (scsi)
Disk /dev/sda: 1953525168s
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Disk Flags:

Number  Start  End          Size         Type     File system  Flags
 1      2048s  1948268543s  1948266496s  primary               raid

$ sudo parted /dev/sdb unit s print
Model: XXX (scsi)
Disk /dev/sdb: 1953519616s
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Disk Flags:

Number  Start  End          Size         Type     File system  Flags
 1      2048s  1948268543s  1948266496s  primary               raid

$ sudo mdadm -E /dev/sda1
/dev/sda1:
          Magic : a92b4efc
        Version : 1.2
    Feature Map : 0x1
     Array UUID : xxxxxxxx:xxxxxxxx:xxxxxxxx:xxxxxxxx
           Name : hostname:0  (local to host hostname)
  Creation Time : Thu Mar 22 19:34:24 2018
     Raid Level : raid1
   Raid Devices : 2

 Avail Dev Size : 1948004352 (928.88 GiB 997.38 GB)
     Array Size : 976627712 (931.38 GiB 1000.07 GB)
  Used Dev Size : 1953255424 (931.38 GiB 1000.07 GB)
    Data Offset : 262144 sectors
   Super Offset : 8 sectors
   Unused Space : before=262056 sectors, after=18446744073704300544 sectors
          State : clean
    Device UUID : xxxxxxxx:xxxxxxxx:xxxxxxxx:xxxxxxxx

Internal Bitmap : 8 sectors from superblock
    Update Time : Tue Aug 25 12:39:03 2020
  Bad Block Log : 512 entries available at offset 72 sectors
       Checksum : f47ecd0c - correct
         Events : 459193

   Device Role : Active device 1
   Array State : .A ('A' == active, '.' == missing, 'R' == replacing)

$ sudo mdadm -E /dev/sdb1
/dev/sdb1:
          Magic : a92b4efc
        Version : 1.2
    Feature Map : 0x1
     Array UUID : xxxxxxxx:xxxxxxxx:xxxxxxxx:xxxxxxxx
           Name : hostname:0  (local to host hostname)
  Creation Time : Thu Mar 22 19:34:24 2018
     Raid Level : raid1
   Raid Devices : 2

 Avail Dev Size : 1948004352 (928.88 GiB 997.38 GB)
     Array Size : 976627712 (931.38 GiB 1000.07 GB)
  Used Dev Size : 1953255424 (931.38 GiB 1000.07 GB)
    Data Offset : 262144 sectors
   Super Offset : 8 sectors
   Unused Space : before=262056 sectors, after=18446744073704300544 sectors
          State : clean
    Device UUID : xxxxxxxx:xxxxxxxx:xxxxxxxx:xxxxxxxx

Internal Bitmap : 8 sectors from superblock
    Update Time : Tue Aug 25 10:03:24 2020
  Bad Block Log : 512 entries available at offset 72 sectors
       Checksum : 4e58ad84 - correct
         Events : 81346

   Device Role : Active device 0
   Array State : A. ('A' == active, '.' == missing, 'R' == replacing)

A: You probably originally built the array with the whole disks, without any partitions. You then later probably added a partition table, which messes things. MADM expects a
whole disk.
You should consider the metadata format which may not tell if the raid metadata is supposed to apply to the whole disk or only partition. You could rebuild the array using the newer metadata format.
You could create a new RAID array with the second drive as the sole active volume spanning the whole partition minus a few MB as a safety margin in case this problem happens again. Then copy all the data from the old array to the new one.
Finally wipe the original array and then add the old disk to the new array.


text:
Q: Resize column values in header table to display names I have created the following table, which sets a header column for me. It basically looks like that:

As you can see the values of rowNames with String[] rowNames = {"Production Valuation", "Sales Production", "R&D Department", "Cost Valuation"};
 are not fully displayed.
I tried to set:
    headerTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    headerTable.getColumnModel().getColumn(0).setPreferredWidth(360);

However, nothing changes. Here is a sample program:
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.Font;
    import java.util.Calendar;

    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.SwingConstants;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.event.RowSorterEvent;
    import javax.swing.event.RowSorterListener;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumnModel;
    import javax.swing.table.TableModel;
    import javax.swing.table.TableRowSorter;

    public class JTableRowHeader {

        private JFrame frame = new JFrame("JTable");
        private JScrollPane scrollPane;
        private JTable tableAnalytics;
        private DefaultTableModel model;
        private DefaultTableModel model1;
        private TableRowSorter<TableModel> sorter;
        private JTable headerTable;

        public JTableRowHeader() {

            analyticsTable();
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.add(scrollPane);

            frame.pack();
            frame.setLocation(150, 150);
            frame.setVisible(true);
        }

        /**
         * Is the analytics table for each values.
         */
        public void analyticsTable() {
            String[] columnNames = {"2012", "2013", "2014"};
            String[] rowNames = {"Production Valuation", "Sales Production", "R&D Department", "Cost Valuation"};

            model1 = new DefaultTableModel(rowNames.length, columnNames.length) {
                /**
                 * UUID
                 */
                private static final long serialVersionUID = 8538648271391086030L;

                @Override
                public boolean isCellEditable(int row, int col) {
                    return false;
                }
            };

            tableAnalytics = new JTable(model1);
            //set Values
            for (int i = 0; i < model1.getRowCount(); i++) {
                for (int ii = 0; ii < model1.getColumnCount(); ii++) {
                    model1.setValueAt(i, i, ii);
                }
            }

            TableColumnModel tcm = tableAnalytics.getColumnModel();
            for (int k = 0; k < tcm.getColumnCount(); k++) {
                tcm.getColumn(k).setHeaderValue(columnNames[k]);
            }

            sorter = new TableRowSorter<TableModel>(tableAnalytics.getModel());
            tableAnalytics.setRowSorter(sorter);
            model = new DefaultTableModel() {
                private static final long serialVersionUID = 12312432141L;

                @Override
                public int getColumnCount() {
                    return 1;
                }

                @Override
                public boolean isCellEditable(int row, int col) {
                    return false;
                }

                @Override
                public int getRowCount() {
                    return tableAnalytics.getRowCount();
                }

                @Override
                public Class<?> getColumnClass(int colNum) {
                    switch (colNum) {
                    case 0:
                        return String.class;
                    default:
                        return super.getColumnClass(colNum);
                    }
                }
            };
            headerTable = new JTable(model);
            for (int o = 0; o < rowNames.length; o++) {
                headerTable.setValueAt(rowNames[o], o, 0);
            }

            headerTable.setShowGrid(false);
            headerTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            headerTable.getColumnModel().getColumn(0).setPreferredWidth(360);
            headerTable.setPreferredScrollableViewportSize(new Dimension(50, 0));
            headerTable.getColumnModel().getColumn(0).setPreferredWidth(50);
            headerTable.getColumnModel().getColumn(0).setCellRenderer(new TableCellRenderer() {
                @Override
                public Component getTableCellRendererComponent(JTable x, Object value, boolean isSelected, boolean hasFocus, int row, int column) {

                    boolean selected = tableAnalytics.getSelectionModel().isSelectedIndex(row);
                    Component component = tableAnalytics.getTableHeader().getDefaultRenderer().getTableCellRendererComponent(tableAnalytics, value, false, false, -1, -2);
                    ((JLabel) component).setHorizontalAlignment(SwingConstants.CENTER);
                    if (selected) {
                        component.setFont(component.getFont().deriveFont(Font.BOLD));
                        component.setForeground(Color.red);
                    } else {
                        component.setFont(component.getFont().deriveFont(Font.PLAIN));
                    }
                    return component;
                }
            });
            tableAnalytics.getRowSorter().addRowSorterListener(new RowSorterListener() {
                @Override
                public void sorterChanged(RowSorterEvent e) {
                    model.fireTableDataChanged();
                }
            });
            tableAnalytics.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    model.fireTableRowsUpdated(0, model.getRowCount() - 1);
                }
            });
            scrollPane = new JScrollPane(tableAnalytics);
            scrollPane.setRowHeaderView(headerTable);
            tableAnalytics.setPreferredScrollableViewportSize(tableAnalytics.getPreferredSize());
        }

        public static void main(String[] args) {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (UnsupportedLookAndFeelException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    @SuppressWarnings("unused")
                    JTableRowHeader TestTableRowHeader = new JTableRowHeader();
                }
            });
        }
    }

Any recommendations what I am doing wrong?
I appreciate your answer!

A: set scrollpane rowheader dimension like,
scrollPane.getRowHeader().setPreferredSize(new Dimension(120, 50));

add above statement after
scrollPane.setRowHeaderView(headerTable);

and comment the line
//headerTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);


text:
Q: Used boot camp for windows - cannot select partition at boot up I'm used boot camp and created a partition for windows. It gave the usual directions to insert windows CD. I did that and follows the installation instructions. When windows started up I inserted the OSX Leopard disk to install the drivers.
Now I cannot restart to OSX. It automatically starts to windows every time. I cannot hold down option and choose the partition. I didn't overwrite the OSX partition. It shows up when I click on "My Computer". Whats going on? Did I accidentally overwrite the OSX boot loader?

A: I believe once you install Boot Camp, the computer will boot into Windows by default unless you change it. Presumably, you're holding down the option key immediately on startup, it should be pressed as you hear the startup chime?
Apart from holding down the option key at startup, if you find you can only boot into Windows, this Apple support page tells you how you can change the default startup volume from Control Panel.

This startup volume selection is temporary.  To set the default startup volume for your Mac after your computer is running, open System Preferences and choose Startup Disk from the View menu (in Mac OS X) or open the Boot Camp control panel (in Windows).

Also, do any of the other Startup key combinations work, e.g. Safe Boot or Single User Mode?


text:
Q: Is there a Chow test for higher dimensions? With the original Chow test, you can only test two regressions vs a general one to see a structural change.
Is there a Chow test that can test structural change in 3,4...N regressions for structural changes versus a 'mother' regression at the same time?

A: Yes, there are extensions of the chow test for multiple breaks, if this is your question?
Bai and Perron investigated test, algorithms, and their distribution, look for example at:

*

*Computation and analysis of multiple structural change models

*Estimating and Testing Linear Models with Multiple Structural Changes
If you are using R, the package strucchange has many nice features to estimate and test for multiple structural breaks


text:
Q: Angular 7 Getting Json array in a Service I have an API which returns this JSON (GET@localhost:8000/:number):
[
  {
    "trip": 5,
    "time_logged": "17/12/2018 07:23:11",
    "day_logged": 17,
    "month_logged": 12,
    "year_logged": 2018,
    "hour": 10,
    "minute": 0,
    "fixquality": 6,
    "speed": 50,
    "angle": 12,
    "lon": -121.180632,
    "lat": 37.503852,
    "altitude": 100000,
    "temp": 13
  },
  {
    "trip": 5,
    "time_logged": "17/12/2018 07:24:59",
    "day_logged": 17,
    "month_logged": 12,
    "year_logged": 2018,
    "hour": 10,
    "minute": 0,
    "fixquality": 6,
    "speed": 50,
    "angle": 12,
    "lon": -122.180632,
    "lat": 37.503852,
    "altitude": 100000,
    "temp": 13
  }
]

In my Angular 7 project, I have a service that should take this JSON and return it as an Observable<HABUpdate[]>:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'
import { Observable } from 'rxjs';

export interface HABUpdate {
    trip: number;
    time_logged: string;
    day_logged: number;
    month_logged: number;
    year_logged: number;
    hour: number;
    minute: number;
    fixquality: number;
    speed: number;
    angle: number;
    lon: number;
    lat: number;
    altitude: number;
    temp: number;
}

@Injectable({
  providedIn: 'root'
})
export class HabdataService {

  url: string = 'http://localhost:8000/';

  constructor(private http: HttpClient) { }

  getUpdates(trip: number): Observable<HABUpdate[]> {
    return this.http.get<HABUpdate[]>(this.url + String(trip));
  }
}

However, I get this console error at runtime:
ERROR Error: "[object Object]"
    resolvePromise http://localhost:4200/polyfills.js:3159:31
    resolvePromise http://localhost:4200/polyfills.js:3116:17
    scheduleResolveOrReject http://localhost:4200/polyfills.js:3218:17
    invokeTask http://localhost:4200/polyfills.js:2766:17
    onInvokeTask http://localhost:4200/vendor.js:51518:24
    invokeTask http://localhost:4200/polyfills.js:2765:17
    runTask http://localhost:4200/polyfills.js:2533:28
    drainMicroTaskQueue http://localhost:4200/polyfills.js:2940:25
    invokeTask http://localhost:4200/polyfills.js:2845:21
    invokeTask http://localhost:4200/polyfills.js:3885:9
    globalZoneAwareCallback http://localhost:4200/polyfills.js:3911:17
core.js:14597

I am new to Angular, and so at first thought that I must not be parsing the JSON correctly in order to convert it into an HABUpdate[]. However, looking through the internet I have found example of people doing a similar thing and their code seems to work. For reference, this is the component which is trying to reference this service:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HabdataService, HABUpdate } from '../habdata.service';

@Component({
  selector: 'app-launches',
  templateUrl: './launches.component.html',
  styleUrls: ['./launches.component.scss']
})
export class LaunchesComponent implements OnInit {

  trip$: number;
  updates$: HABUpdate[];

  constructor(private route: ActivatedRoute, private data: HabdataService) {
    this.route.params.subscribe(
      params => this.trip$ = params.trip
    );
  }

  ngOnInit() {
    this.data.getUpdates(this.trip$).subscribe(
      data => this.updates$ = data
    );
  }

}

I am sure that I must be missing something basic, but I have not been able to find a solution for a while. Any help is appreciated.


text:
Q: The shortcut of while loops Can some one give me shortcut for this code?
list1 = [['a','b','c'],['d','e','f'],['h'',i','j']]
a = []
i = 0
while i < 4 :
  a.append(list1[0])
  i += 1
i = 0
while i < 4:
  a.append(list1[1])
  i += 1
i = 0
while i < 4:
  a.append(list1[2])
  i += 1

print(a)
I want my output should be:
[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['d', 'e', 'f'], ['d', 'e', 'f'], ['d', 'e', 'f'], ['d', 'e', 'f'], ['h', 'i', 'j'], ['h', 'i', 'j'], ['h', 'i', 'j'], ['h', 'i', 'j']]

A: A list comprehension would do this for you:
a = [sublist for sublist in list1 for i in range(4)]

Note that this only creates additional references to the lists contained in list1, not copies.
Demo:
>>> list1 = [['a', 'b', 'c'], ['d', 'e', 'f'], ['h,i', 'j']]
>>> a = [sublist for sublist in list1 for i in range(4)]
>>> a
[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['d', 'e', 'f'], ['d', 'e', 'f'], ['d', 'e', 'f'], ['d', 'e', 'f'], ['h,i', 'j'], ['h,i', 'j'], ['h,i', 'j'], ['h,i', 'j']]
>>> a[0][0] = 'spam'
>>> a
[['spam', 'b', 'c'], ['spam', 'b', 'c'], ['spam', 'b', 'c'], ['spam', 'b', 'c'], ['d', 'e', 'f'], ['d', 'e', 'f'], ['d', 'e', 'f'], ['d', 'e', 'f'], ['h,i', 'j'], ['h,i', 'j'], ['h,i', 'j'], ['h,i', 'j']]

Note how a change to the first nested list is reflected across the first four lists? That's because those are all the same object. If you wanted to create copies, use the list() function, or the [:] identity slice operator:
a = [sublist[:] for sublist in list1 for i in range(4)]