text:
Q: API-Server on master stops after adding second control-plane In my current test setup I've several VMs running Debian-11. All nodes have a private IP and a second wireguard interface. In the future the nodes will be in different locations with different network and Wireguard is used to "overlay" all the different network environments. I want to install a Kubernetes on all nodes.
node   public ip        wireguard ip
vm1    192.168.10.10    10.11.12.10
vm2    192.168.10.11    10.11.12.11
vm3    192.168.10.12    10.11.12.12
...

So I've installed docker and kubeadm/kubelet/kubectl in version 1.23.5 on all nodes. Also I've installed a haproxy on all nodes too. It works as a load balancer by listing to localhost:443 and forwarding the requests to one of the online control-planes.
Then I started the cluster with kubeadm
vm01> kubeadm init --apiserver-advertise-address=10.11.12.10 --pod-network-cidr=10.20.0.0/16

After that I tested to integrate either flannel or calico. Either by adding --iface=<wireguard-interface> or by setting the custom manifest ...nodeAddressAutodetectionV4.interface: <wireguard-interface>.
When I add a normal node - everything is fine. The node is added, pods are created and the communication is done via the defined network interface.
When I add a control plane without the wireguard interface, I can also add different control planes with
vm2> kubeadm join 127.0.0.1:443 --token ... --discovery-token-ca-cert-hash sha256:...  --control-plane

Of course before that, I've copied several files from vm01 to vm02 from /etc/kubernetes/pki like the ca.*, sa.*, front-proxy-ca.*, apiserver-kubelet-client.* and etcd/ca.*.
But when I use the flannel or calico network together with the wireguard interface, something strange happens after the join command.
root@vm02:~# kubeadm join 127.0.0.1:443 --token nwevkx.tzm37tb4qx3wg2jz --discovery-token-ca-cert-hash sha256:9a97a5846ad823647ccb1892971c5f0004043d88f62328d051a31ce8b697ad4a --control-plane
[preflight] Running pre-flight checks
[preflight] Reading configuration from the cluster...
[preflight] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -o yaml'
[preflight] Running pre-flight checks before initializing the new control plane instance
[preflight] Pulling images required for setting up a Kubernetes cluster
[preflight] This might take a minute or two, depending on the speed of your internet connection
[preflight] You can also perform this action in beforehand using 'kubeadm config images pull'
[certs] Using certificateDir folder "/etc/kubernetes/pki"
[certs] Generating "front-proxy-client" certificate and key
[certs] Generating "etcd/server" certificate and key
[certs] etcd/server serving cert is signed for DNS names [localhost mimas] and IPs [192.168.10.11 127.0.0.1 ::1]
[certs] Generating "etcd/peer" certificate and key
[certs] etcd/peer serving cert is signed for DNS names [localhost mimas] and IPs [192.168.10.11 127.0.0.1 ::1]
[certs] Generating "etcd/healthcheck-client" certificate and key
[certs] Generating "apiserver-etcd-client" certificate and key
[certs] Generating "apiserver" certificate and key
[certs] apiserver serving cert is signed for DNS names [kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local mimas] and IPs [10.96.0.1 192.168.10.11 127.0.0.1]
[certs] Using the existing "apiserver-kubelet-client" certificate and key
[certs] Valid certificates and keys now exist in "/etc/kubernetes/pki"
[certs] Using the existing "sa" key
[kubeconfig] Generating kubeconfig files
[kubeconfig] Using kubeconfig folder "/etc/kubernetes"
[endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address
[kubeconfig] Writing "admin.conf" kubeconfig file
[endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address
[kubeconfig] Writing "controller-manager.conf" kubeconfig file
[endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address
[kubeconfig] Writing "scheduler.conf" kubeconfig file
[control-plane] Using manifest folder "/etc/kubernetes/manifests"
[control-plane] Creating static Pod manifest for "kube-apiserver"
[control-plane] Creating static Pod manifest for "kube-controller-manager"
[control-plane] Creating static Pod manifest for "kube-scheduler"
[check-etcd] Checking that the etcd cluster is healthy
[kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[kubelet-start] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
[kubelet-start] Starting the kubelet
[kubelet-start] Waiting for the kubelet to perform the TLS Bootstrap...
[etcd] Announced new etcd member joining to the existing etcd cluster
[etcd] Creating static Pod manifest for "etcd"
[etcd] Waiting for the new etcd member to join the cluster. This can take up to 40s
[kubelet-check] Initial timeout of 40s passed.
error execution phase control-plane-join/etcd: error creating local etcd static pod manifest file: timeout waiting for etcd cluster to be available
To see the stack trace of this error execute with --v=5 or higher

And after that timeout even on vm01 the API server stops working, I cannot run any kubeadm or kubectl commands anymore. The HTTPS service on 6443 is dead. But neither I understand why the API server on vm01 stops working when adding a second API server nor I can find a reason, whe the output is talking about the 192.168.... IPs, because the cluster should communicate only via the 10.11.12.0/24 wireguard network.

A: After finding a similar problem in https://stackoverflow.com/questions/64227042/setting-up-a-kubernetes-master-on-a-different-ip I think, this is also the solution here. When I add --apiserver-advertise-address=<this-wireguard-ip>, the output changes (no 192.168.. IP) and it joins. What I don't understand, why VM01 API server stops working.
Whatever the join command is doing under the hood, it needs to create a etcd service on the second control plane and that service must also run on the same IP then the flannel/calico network interface. In case of using the primary network interface this parameter is not necessary on the second/third control plane.


text:
Q: Typedef for recursive lambda Is there a way to create a typedef such that the following (a basic "pure" implementation of the y-combinator) would compile?
typedef ??? f;
[](f x){x(x);} ([](f x){x(x);});

This has the effect of creating a "recursive lambda", i.e. one which calls itself by using a second lambda to get a reference to itself. x in the first lambda is a reference to the second lambda, so x(x) calls the second lambda with a reference to itself. Thereafter, the second lambda recurses by calling x(x). This code, when executed, should produce an infinite loop until it hits stack overflow. More sophisticated implementations of the second function can produce arbitrary recursive behaviour.
I have tried typedefing various versions of void(*)(...) but I do not believe that can succeed. My template metaprogramming is not strong enough to handle this kind of thing.

A: How about this one?
#include <functional>
#include <iostream>

struct X
{
    template<typename F>
    X(F f) : _f(f)
    { }

    void operator () (std::function<void(X)> f)
    {
        std::cout << "Calling myself..." << std::endl;
        _f(f);
    }

    std::function<void(X)> _f;
};

int main()
{
    typedef X f;
    [](f x){x(x);} ([](f x){x(x);});
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to send keys/ input to a process that is running without a logged in user using powershell? I'm having an issue with automating part of an application install with powershell.
Part of the install is running a command line tool with parameters and entering credentials to access a database. This is supposed to be done without logging in.
For that purpose I've been using scheduled tasks to start my scripts at system startup.
I've been trying to get this particular step working by using AppActivate and SendWait to send the credentials to the window. This does not work though since there is no interactive window if I use the task scheduler.
This is the current script I've been using. It works if I would use the RunOnce key for example.
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.VisualBasic")

powershell.exe add-type -AssemblyName microsoft.VisualBasic

add-type -AssemblyName System.Windows.Forms

$parms = 'create instance'

Start-Process "app.exe" -ArgumentList $parms -WorkingDirectory "C:\app\app.exe"

start-sleep -Milliseconds 1000

[Microsoft.VisualBasic.Interaction]::AppActivate("C:\app\app.exe")

[System.Windows.Forms.SendKeys]::SendWait("username")

start-sleep -Milliseconds 1000

[Microsoft.VisualBasic.Interaction]::AppActivate("C:\app\app.exe")

[System.Windows.Forms.SendKeys]::SendWait("password")

This script is called by another script which is run by the task scheduler.
Right now it fails with:
Exception calling "AppActivate" with "1" argument(s): "Process '{0}' was not found."

and:
Exception calling "SendWait" with "1" argument(s): "Access is denied"

Which is due to not being able to access the window.
Is there any way to send the username and password to the process without requiring an active windows? From what I've seen it doesn't seem to be supported by powershell but I'm still hoping that there is a way. Maybe using Handles? I can not use any applications like AutoHotkey or AutoIt.

A: Try this,
    $proc = Get-process | where {$_.path -eq "C:\app\app.exe"}
    [Microsoft.VisualBasic.Interaction]::AppActivate($Proc.id)


text:
Q: Powershell extracting IIS Bindings

I have an Excel spreadsheet that has about 190 lines worth of IIS bindings. What I need to do is go line by line and get each binding from the line.
Example from one line could be:

SITE "Gateway"
  (id:1,bindings:http/192.168.1.1:80:www.sample.test.com,http/192.168.1.1:80:sample.test.com,https/192.168.1.1:443:,net.tcp/808:,net.pipe/,net.msmq/localhost,msmq.formatname/localhost,state:Started)

So I would need to seperate out the two webpages, www.sample.test.com and sample.test.com. Then what I wanted to do was do an nslookup on each webpage that is pulled out from each line.
I have gotten as far as going line by line and getting each set of bindings using:
$worksheet = $workbook.sheets.item($sheetname1)
For ($1=0;$i -le 190;$i++) {
$a = $worksheet.Columns.Item(1).Rows.Item($i).text}

Edit:
I have added the following code and it seems to work (but is there a better way to do this?)
 For ($1=0;$i -le 190;$i++) {
$a =@($worksheet.Columns.Item(1).Rows.Item($i).text)
For ($2=0;$2 -lt $a.length; $2++) {
$a[$2].split(':,')[5]
$a[$2].split(':,')[8]
$a[$2].split(':,')[11]
$a[$2].split(':,')[14]
$a[$2].split(':,')[17]
 }

I got it to work with this but now my issue is that some of the lines dont have more than two host names to do the nslookup so in the output file I get extra data that I dont want
$a =@($worksheet.Columns.Item(1).Rows.Item($i).text)
    For ($2=0;$2 -lt $a.length; $2++) {
    $d = $a[$2].split(':,')[5] | Out-File -Filepath $outfile -append
    $a[$2].split(':,')[5] | nslookup($_) | Out-File -Filepath $outfile -append
    $e = $a[$2].split(':,')[8]  |Out-File -Filepath $outfile -append
    $a[$2].split(':,')[8] | nslookup($_) | Out-File -Filepath $outfile -append
    $f = $a[$2].split(':,')[11]  |Out-File -Filepath $outfile -append
    $a[$2].split(':,')[11] | nslookup($_) | Out-File -Filepath $outfile -append
    $h = $a[$2].split(':,')[14]  |Out-File -Filepath $outfile -append
    $a[$2].split(':,')[14] | nslookup($_) | Out-File -Filepath $outfile -append
    $j = $a[$2].split(':,')[17]  |Out-File -Filepath $outfile -append
    $a[$2].split(':,')[17] | nslookup($_) | Out-File -Filepath $outfile -append
    $k = $a[$2].split(':,')[20] |Out-File -Filepath $outfile -append
    $a[$2].split(':,')[20] | nslookup($_) | Out-File -Filepath $outfile -append
    $l = $a[$2].split(':,')[23]  |Out-File -Filepath $outfile -append
    $a[$2].split(':,')[23] | nslookup($_) | Out-File -Filepath $outfile -append}


text:
Q: Returning a reference local variable assigned by reference I'm being a bit confused about this simple case:
O& foo() {
  O& o = bar(); // sig: O& bar();
  return o;
}

Is that ok ? I'm quite confident it is, but I searched advanced explanations about this, and nothing definitive popped up. Any good reference ? Or maybe am I just wrong ?
EDIT: the result from the bar() function is legit (it's a reference element from a list), and making the o variable static is not really part of the question, I just wanted to make sure a local variable assigned by reference can itself by returned by reference. static's semantic is entirely different.

A: It depends on what bar returns. If it returns a local variable by reference, then no. If the returned value is persistent after it returns, the yes.
O& bar() {
   static O o;
   return o;
}

O& bar1() {
   return O();  // temporary
}

O& foo() {
  O& o = bar();   // okay
  O& o1 = bar1(); // not okay
  return o;
}

A: You can use static keyword to let your object exist after being returned from. But this way you are not following rules of object orientation.
If you are returning the reference to avoid cost of copying, you can use shared_ptr<O> by which you will return the address of o and you will not worry about deleting your pointer or such issues.
Here you can find how shared_ptr works.

A: You aren't returning a reference to a local variable. The following code returns a reference to a local variable:
 O& foo() {
     O o;
     return o;
 }

In your code, 'o' is already a reference. It's not a variable assigned by reference, it is a reference.
The fact that the function also returns a reference simply means that you pass the reference back, not a reference to your reference. Simply put: your function simply returns a reference. Lets flesh it out:
struct O {};
static O s_o;

O& foo() { return s_o; } // returns a reference, to s_o

O& bar() {
    O& o = foo(); // os now refers to s_o;
    return o; // o is a reference, but it refers to s_o,
    // so this returns a reference to s_o, not o.
    // we're returning "O&", not "(O&)&".
}

This is essentially the same as the following:
O* bar(); // returns a pointer to X.
O* optr = bar(); // optr points to X.
return optr; // returns the address of x.

We're not returning a pointer to 'optr' here, we're returning the value that optr contains, which is a pointer to an instance of an 'O'.
In C++ references are generally implemented as a contractual layer over pointers - that is, the underlying type of a reference is generally a pointer. The contract trades access to the pointer, thus the ability to change what the reference points/refers to, in exchange for some degree of guarantee that it will refer/point to a concrete instance. There are ways you can still shoot yourself in the foot with a reference, especially when referencing the target of a pointer.
The simplest reduction of your code then, which from the callers perspective has the same effect:
O& foo() {
    return bar();
}

A: You can make static object to return local variables for a single threaded application:
O& foo() {
  static O o = bar();
  return o; //foo will return reference to O
}

For Multi threading : This will work in c++11


text:
Q: Delay return from function using promise I'd like to run the function that consists of:
if condition is solved
1)add class
2)sleep 4 sec then remove class
3)then stop running function using return.
    function sleep(time) {
    return new Promise(resolve => {
        setTimeout(resolve, time)
    })
  }
    function playGame() {
    if (counter === 3) {
        Promise.resolve().then(function () {
            message.classList.add('winner');
            sleep(2500).then(function () {
                message.classList.remove('winner');
            });
        });
        return;
      }
    ...
   }

If I run this code, function returning immediately of course. How do I add return to the promise chain.

A: This should work:
Promise.resolve()
.then(function () {
    message.classList.add('winner');
})
.then(sleep(2500))
.then(function() {
    message.classList.remove('winner');
});

This should be self-explanatory. Feel free to ask more questions as needed.
EDIT : Oooops it seems that I answered this one too quickly. You can never postpone a "return" statement in javascript. In your case, your code, or mine executes immediately, and the return of the enclosing function is called immediately, and the execution goes back to the event loop. Then, the first then() of the promise is called, etc...
Since you can't postpone the return of the function, you use callbacks, or better, Promises, to chain events:
function playGame() {
    return Promise.resolve()  // note the return !
    .then(function () {
        message.classList.add('winner');
    })
    .then(sleep(2500))
    .then(function() {
        message.classList.remove('winner');
    });
}

...then

playGame()
.then(function() {
    // this code is called after playGame's Promise has been executed
});

// this code is called when playGame ends, ie immediately, and before any promises code

To put it differently: once you begin to have asynchronous code (through callbacks or promises), every further code needs to be driven by promises, too.


text:
Q: Determine if f: Z × Z → Z is onto This is the solution I found:

Why does the pairing (0,-x) work to prove the whole function is onto?

A: To show the function is onto we need to show that every element in the range is the image of at least one element of the domain.  This does exactly that.  It says if you give me an $x \in \Bbb Z$ I can find you an element $y \in \Bbb {Z \times Z}$ such that $f(y)=x$ and the one I find is $(0,-x)$.  Other examples are possible, for example $(2,-x+4)$, but we only need one.


text:
Q: Updating MongoDB object field I have searched and tried many answers but I can't seem to get this working.  I have a user in MongoDB (db.users...) and I'm trying to update a field titled 'role' in one particular document.  If I perform a :
db.users.find();

I get:
{ "_id" : "fDx2g34G8vxsDu3vf", "createdAt" : ISODate("2014-06-03T16:31:47.382Z"),
  "emails" : [  {  "address" : "andrewmlarking@gmail.com",  "verified" : false } ],
  "profile" : { "name" : "Admin", "role" : "user", "division" : "0", "enrolled" : "false" },
  "services" : { "password" : { "srp" : { "identity" "dEad06c_5mjzsprUzgRyh6tB66OiaybdLzbnxFzO1xh",
  "salt" : "zqWsh etc etc

Which is fine, if I then perform a:
db.users.update({_id:"2xnoy3jqcHCaFp7Br"}, { role:"admin"});

I get a:

assert failed : need an object Error: Printing Stack Trace
      at printStackTrace (src/mongo/shell/utils.js:37:15)
      at doassert (src/mongo/shell/assert.js:6:5)
      at assert (src/mongo/shell/assert.js:14:5)
      at DBCollection.update (src/mongo/shell/collection.js:220:5)
      at (shell):1:10

Any ideas?
Thanks.

A: Maybe you should try adding ObjectId to the query.
Also, as pointed by @John Petrone you should use $set
I usually do
db.users.update({_id:ObjectId("2xnoy3jqcHCaFp7Br")}, {$set: { "profile.role":"admin"});

A: First of all if you are trying to update the role field of the profile subdocument your syntax is off. It should be:
db.users.update({_id:"2xnoy3jqcHCaFp7Br"}, {$set: { "profile.role":"admin"}})
Otherwise you will just delete all the other fields of the document.
Regarding the error message, that normally only occurs when you run update with a single argument (the query) without the fields to update. Are you sure you are calling it as documented in your question?
Regardless I would highly advise you to review MongoDB documentation for updates:
http://docs.mongodb.org/manual/tutorial/modify-documents/


text:
Q: ionic 4 - cordova-plugin-chrome-apps-sockets-udp I'm trying to build an ionic app for android and ios.
In this app I need to send and receive udp packets to the server.
For that I trying to use https://github.com/MobileChromeApps/cordova-plugin-chrome-apps-sockets-udp
but i keep getting this error while running on a real device android device:
core.js:9110 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'bind' of undefined
TypeError: Cannot read property 'bind' of undefined

My code that causes this error is:
async broadcasting(messageSend)
{

    this.platform.ready().then(
        (readySource) => {
    var udp = require('udp-packet');
    chrome = window['chrome'];
    if(readySource == 'cordova')
    {
      const pack = udp.encode({
        sourceIp: '10.0.0.1',
        sourcePort: 58936,
        destinationIp: '85.214.60.74',
        destinationPort: 7810,
        data: new Buffer(messageSend)
      });

      (<any>window).chrome.sockets.udp.bind(123445, pack,'85.214.60.74',7810, function(result){
        console.log("result bind",result);
      });
      chrome.sockets.udp.send(123445, pack,'85.214.60.74',7810, function(result){
        console.log("result send",result);
      });
      chrome.sockets.udp.onReceive.addListener(function(result){
        console.log("result listener",result);
      });
    }
        });
}

Any idea on what I'm doing wrong?

A: I ended up finding that I only had tcp plugin installed, I had to run "cordova plugin add cordova-plugin-chrome-apps-sockets-udp" to make it work.


text:
Q: is "content://" in the Uri of Content Provider in Android replaceable ? In our platform, we use a certain format from paths. In the Android App, it receives those paths to load some data or do something.
I want to do all the data handling using content provider, I want to give the path and get data. A simple transaction.
When I read into content providers, the documentation and all the tutorials out there always use "content://" at the beginning. However, I want to use our own start of the path which is usually "is-://". Can something like this work?

A: no, this is how the system categorize the uri as content provider.
its like relacing file:// with something else.

A: After referring to Developer.google site

A content URI is a URI that identifies data in a provider. Content URIs include the symbolic name of the entire provider (its authority) and a name that points to a table (a path). When you call a client method to access a table in a provider, the content URI for the table is one of the arguments.

From this I believe you can't set it on your own as it includes the symbol name.
Also why do you want to change it?


text:
Q: FetchType.LAZY is working as FetchType.EAGER I have a problem with hibernate, namely with lazy data fetching. I have two entities and one of them clinic is having relation @OneToMany. I setup FetchType to LAZY, but still, when I am making request to get all clinic, I still have an array in the clinic entity. The questions is - why I am still getting full @OneToMany array? Shouldn't it be null?
Here I provided my entity classes
@Getter
@Setter
@Entity(name = "clinic")
public class Clinic {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String name;
  @OneToMany(fetch = FetchType.LAZY, mappedBy="clinic")
  private List<Doctor> doctors;
}

And doctor entity
@Getter
@Setter
@Entity(name = "doctor")
public class Doctor {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String firstname;
  private String lastname;
  @ManyToOne(fetch = FetchType.LAZY)
  @JsonIgnore
  private Clinic clinic;
}

And my controller, which is JpaRepository interface
@RestController
@RequestMapping("clinics")
public class ClinicController {

  private final ClinicRepository clinicRepository;

  public ClinicController(ClinicRepository clinicRepository) {this.clinicRepository = clinicRepository;}

  @GetMapping()
  public List<Clinic> getAllClinics() {
    return clinicRepository.findAll();
  }
}

I also logged SQL provided by Hibernate and it looks like this
Hibernate: select clinic0_.id as id1_0_, clinic0_.name as name2_0_ from clinic clinic0_
Hibernate: select doctors0_.clinic_id as clinic_i4_1_0_, doctors0_.id as id1_1_0_, doctors0_.id as id1_1_1_, doctors0_.clinic_id as clinic_i4_1_1_, doctors0_.firstname as firstnam2_1_1_, doctors0_.lastname as lastname3_1_1_ from doctor doctors0_ where doctors0_.clinic_id=?
Hibernate: select doctors0_.clinic_id as clinic_i4_1_0_, doctors0_.id as id1_1_0_, doctors0_.id as id1_1_1_, doctors0_.clinic_id as clinic_i4_1_1_, doctors0_.firstname as firstnam2_1_1_, doctors0_.lastname as lastname3_1_1_ from doctor doctors0_ where doctors0_.clinic_id=?

As I understand, it supposed to send only one query (first select).
And of course, I also will provide an answer that I am getting right now
[
    {
        "id": 1,
        "name": "Clinic 1",
        "doctors": [
            {
                "id": 1,
                "firstname": "Bob",
                "lastname": "Fisher"
            },
            {
                "id": 2,
                "firstname": "John",
                "lastname": "Cena"
            }
        ]
    },
    {
        "id": 2,
        "name": "Clinic 2",
        "doctors": [
            {
                "id": 3,
                "firstname": "Some",
                "lastname": "guy"
            }
        ]
    }
]

A: The association is lazily loaded because Jackson (JSON serialization library) simply serializes this proxy collection. Lazy loading is possible because Spring enables the open-session-in-view by default. If you turn that config off, you will see a LazyInitializationException.
What you want though, is to tell Jackson not to serialize the collection, by annotating it with @JsonIgnore:
@JsonIgnore
@OneToMany(fetch = FetchType.LAZY, mappedBy="clinic")
private List<Doctor> doctors;


text:
Q: jQuery toggles for table rows with cookies I'm trying to combine the codes from these two questions:

*

*using jQuery to slideToggle a group of Table Rows

*jQuery toggle with cookies  - collapsed state by default
The first example implements slide toggles to hide or reveal groups of rows in a table.  The second example shows how to use cookies in a group of lists that use slide toggles to hide or reveal the items in each list.
Now I'd like to build a table (like in the first example) that uses cookies (like in the second example) so that the rows stay hidden or revealed when the page is refreshed.  I've put together a code that's a hybrid of the two, but I'm having a hard time figuring out how link the cookie values with their respective table rows.
EDIT:
Okay, I figured it out.  I rearranged my "flip" and "panel" classes to give my html a clearer structure and make it easier to navigate.  Then the solution was much easier to find.  See the code in the answers section below.

A: Here's the code (requires jquery.cookie.js to work).
Almost all of the credit for this goes to Toby Pitman.  All I did was adapt his collapsible panels concept to work inside of a table.

                    Column1
                    Column2
                    Column3
                    Column4

                     Section 1

                    item 111
                    item 112
                    item 113
                    item 114

                    item 121
                    item 122
                    item 123
                    item 124

                    item 131
                    item 132
                    item 133
                    item 134

                     Section 2

                    item 211
                    item 212
                    item 213
                    item 214

                    item 221
                    item 222
                    item 223
                    item 224

                    item 231
                    item 232
                    item 233
                    item 234

                     Section 3

                    item 311
                    item 312
                    item 313
                    item 314

                    item 321
                    item 322
                    item 323
                    item 324

                    item 331
                    item 332
                    item 333
                    item 334


text:
Q: Math competition for school I am trying to find a math competition where a 10 year old kid can participate.
Can someone suggest a competition in USA?

A: A great online competition we use is Beestar math competition. It also is super convenient and grade level specific. Also, a lot of students in Texas use it to prepare for Mathcounts (mentioned above). We also really like using Beestar math competition since it gives you a percentile ranking which gives you a really good guidance on how to help your kiddos in the next round.


text:
Q: easiest document format for displaying pages containing images and text in java I want to be able to open up documents containing a combination of one or two pictures and text from java.  The documents don't have to be pretty, but I need to be able to switch documents relatively quickly.  I'm trying to figure out what the easiest method to do this is.
I can save the documents in whatever format is easiest for me, for instance html or PDF.  But the documents must be somewhat easy to modify or generate new ones.  I don't care if the document is displayed within a java frame or by an external tool so long as the tool is common enough to be installed on most OS and I can switch documents quickly and without too much hassle.  This is an internal tool so it doesn't have to work at professional level quality.
Unfortunately, various company limitations make it a real hassle to get approval to use open source packages that haven't been pre-approved.  So I can't do the obvious thing and grab an open source implementation of PDF or HTML reader for java.
So, any suggestions on the easiest format for my documents and how to read it?

A: You can use XHTML. So, your document will be directory that contains HTML document and image files as-is. you do not need anything beyond JDK to implement this and can use any browser to view such document. Modification is easy too.
Note: I said XHTML as a HTML that can be parsed using regular XML parser. I think it is the best choice for you.


text:
Q: J. Oliver's usage of the word 'bog' I have a question about the usage of the word 'bog' in the following sentence:

Bog standard scoops of ice cream etc

I understand that the meaning is 'form'; nevertheless, this is the first time I have seen it. Of course, I'm not a native speaker, Italian being my mother tongue. Any help would be much appreciated. Smile.

A: Probably most British speakers of English would be familiar with the phrase; I have often heard it in the London area, and never thought about its origin. OED mentions the theories about the origin of the phrase given above, then says "The most commonly held view is that the transition from box to bog resulted from a mishearing or misunderstanding of box-standard n." That theory does have the problem that the earliest printed evidence for 'box-standard' is 20 years later than 'bog-standard,' and all the theories about its origin seem a little speculative.

A: There is a common backronym for bog-standard: "British Or German Standard" - but as the answers above make clear that is very much post hoc.
The phrase caused political controversy in 2001 when the UK Prime Minister's spokesman referred to "bog-standard comprehensive" schools - which was taken to be insulting by some (an interpretation strongly denied by the PM's office.)

A: From Tony Thorne, The Dictionary of Contemporary Slang (1990):

bog-standard adj British totally unexceptional, normal and unremarkable. Bog here is used as an otherwise meaningless intensifier.

From Paul Beal, Partridge's Concise Dictionary of Slang and Unconventional English (1989):

bog-standard. Standard, straight from a factory, with no refinement or modification: orig. applied mainly to motorcycles, since mid-1950s; by 1980s > gen. engineering, with wier application. Prob. ex bog-wheel. (Bishop; Hanley, 1988.)
...
bog-wheel. A bicycle: Cambridge undergraduates': earlier C.20. (Keynes, 1981, quoting his diary for 1907.) Its wheels are—like the gap in a water-closet seat—round. Cf. bog n., 1.—2. ["Abbr. bog-house, ... a privy, since early C.19 (in Spy, 1825); orig. Oxford University s{tudents}"; "Abbr. bog-wheel, a bicycle: Marlborough College"] Hence, a motorcycle: Army: WW2. (L.S. Beale.)

So Oxford University students were calling privies "bog-houses" by 1825, and Marlborough College and Cambridge University students were calling bicycles "bog-wheels" by 1907—presumably because of a perceived similarity between the roundness of bicycle wheels and the roundness of the open space in a privy seat. From bicycles, the term bog-wheel was extended to motorcycles, and by World War 2 the term was sometimes shortened (when used in that sense) to the word bog.
The compound adjective bog-standard then arose in the 1950s in the sense of "standard-issue," first in connection with motorcycles, but later applied to other machinery, and eventually (it seems) to such general things as scoops of ice cream.

A: "Bog-standard" means ordinary. Here's a link:
http://www.bbc.co.uk/worldservice/learningenglish/radio/specials/1728_uptodate/page25.shtml
"Bog" is not a verb that means "to form"--"bog standard" is an adjective. There is no verb in the phrase "bog standard scoops of ice cream."

A: British English [slang] usage: regular, not fancy or unusual, commonplace.
See: http://www.phrases.org.uk/meanings/bog-standard.html


text:
Q: My MySQL query with two JOINs does not work I have written the following query, which does not work. I want to know how to make it work. It is a two-JOIN query which fails to work.
SELECT oc_download.download_id, oc_product_to_download.download_id, oc_download_description.download_id
  FROM oc_download
         LEFT JOIN oc_product_to_download
                ON oc_download.download_id = oc_product_to_download.download_id
         LEFT JOIN
                   oc_download.download_id = oc_download_description.download_id
 WHERE oc_product_to_download.product_id = 89

With single JOIN it works, but adding the second JOIN it fails. here is the clean working one-JOIN query:
SELECT oc_download.download_id, oc_product_to_download.download_id, oc_download_description.download_id
  FROM oc_download
         LEFT JOIN oc_product_to_download
                ON oc_download.download_id = oc_product_to_download.download_id
 WHERE oc_product_to_download.product_id = 89

How should I use multiple JOIN in one single query?

A: You forgot the table name in the 2nd join
SELECT d.download_id, p.download_id, dd.download_id
FROM oc_download d
LEFT JOIN oc_product_to_download p ON d.download_id = p.download_id
LEFT JOIN oc_download_description dd ON d.download_id = dd.download_id
WHERE p.product_id = 89

And your where clause turns your left join into an inner join. If you don't want that then change your query to
SELECT d.download_id, p.download_id, dd.download_id
FROM oc_download d
LEFT JOIN oc_product_to_download p ON d.download_id = p.download_id
                                  AND p.product_id = 89
LEFT JOIN oc_download_description dd ON d.download_id = dd.download_id

A: This is your query fixed up a bit, using table aliases and proper join syntax:
SELECT od.download_id, opd.download_id, odd.download_id
FROM oc_download od LEFT JOIN
     oc_product_to_download opd
     ON od.download_id = opd.download_id LEFT JOIN
     oc_download_description odd
     od.download_id = odd.download_id
WHERE opd.product_id = 89;

You are using left join, but this appears to be unnecessary.  The on clause is undoing the first outer join, turning it into an inner join (unmatched rows would have a NULL value, which are filtered out by the where clause).  In fact, I would guess that your data has well defined foreign key relationships among the columns being joined.  If this is the case, you should use inner join (or just join) for the query:
SELECT od.download_id, opd.download_id, odd.download_id
FROM oc_download od JOIN
     oc_product_to_download opd
     ON od.download_id = opd.download_id JOIN
     oc_download_description odd
     od.download_id = odd.download_id
WHERE opd.product_id = 89;

The left join is misleading because it implies that some keys might not match.  You also run the risk of confusing the optimizer.


text:
Q: kubernetes helm, jenkins lost token I'v had jenkins deployment from helm charts, did by colleague a month ago. I'v been working on it and somehow lost the jenkins-token-xxxx secret, it's literally gone from the cluster any idea how to recover it, if possible? (the weird thing is I didn't delete it, it just dissapeared)
I did a quick helm install stable/jenkins --name jenkins on minikube to show what's missing
$ kubectl get secrets -o wide
NAME                  TYPE                                  DATA   AGE
default-token-lvkpt   kubernetes.io/service-account-token   3      6d19h
jenkins               Opaque                                2      18m
jenkins-token-rxh2d   kubernetes.io/service-account-token   3      18m <-------

On cluster:
$ kubectl get secrets
NAME                                                TYPE                                  DATA   AGE
default-token-xyzca                                 kubernetes.io/service-account-token   3      yd
jenkins                                             Opaque                                2      yd
jenkins-nginx-nginx-ingress-backend-token-xxxx     kubernetes.io/service-account-token   3      yd
jenkins-nginx-nginx-ingress-token-zzzz             kubernetes.io/service-account-token   3      yd

A: You can run:

kubectl get secret jenkins -oyaml


text:
Q: Convergence of subsets defined by measure
Let $2^X$ denote the set of all subsets of $X$. Given two subsets $A,B\subseteq X$, we define the distance $d(A,B)=\mu^*((A-B)\cup (B-A))$, where $\mu^*$ is the outer measure.
Let $A_1,A_2,\ldots\subseteq X$ be such that for some $\varepsilon$, for all $n$, if $i>j>n$ then $d(A_i,A_j)<\varepsilon^n$. Let $B=\bigcap_{l=1}^{\infty}\bigcup_{j\geq l}A_j$. Prove that the sequence $A_1,A_2,\ldots$ converges to $B$.

So the sequence $A_i$ is a Cauchy sequence, and it converges geometrically. Since we must prove that $A_1,A_2,\ldots $ converges to $B$, I looked at the difference $d(A_i,B)=\mu^*((A_i-B)\cup(B-A_i))\leq \mu^*(A_i-B)+\mu^*(B-A_i)$. I need to find an upper bound of this.
The set $B$ contains exactly all elements $x$ that appear in infinitely many $A_i$'s.
I should have $B-A_i\subseteq \bigcup_{k=i+1}^{\infty}(A_k-A_i)$, which yields an upper bound for $\mu^*(B-A_i)$. We have $\mu^*(B-A_i)\leq \sum_{i=1}^{\infty}\mu^*(A_k-A_i)$, but this is an infinite sum, and even though each term is less than $\varepsilon^i$, we still cannot bound it by anything better than infinity. In particular, how can we use the geometric convergence condition?


text:
Q: Why doesn't Some(List(1,2,3)).flatten compile? In Scala 2.9.1, I could do
> Some(List(1,2,3)).flatten
List(1,2,3)

But in Scala 2.10.0,
> Some(List(1,2,3)).flatten
Cannot prove that Seq[Int] <:< Option[B]

I found this closed bug, but I don't understand the verdict, or why it was closed.
(1) Why doesn't this work in Scala 2.10 (apparently by design?)
(2) What is the idiomatic 2.10 equivalent of my 2.9 code?

A: flatten adopts the type of the outer container.  You can't fit a List into an Option, so that doesn't work.  Instead, change the type of the outer container first so flattening is possible:
Some(List(1,2,3)).toList.flatten

A: flatten is really only intended to work on a single monad at a time. That is, it transforms M[M[T]] into M[T], as in List(List(1,2),List(3)).flatten => List(1,2,3). scala.Predef provides implicits to coerce Option[T] into List[T], but not the other way around. While it is somewhat reasonable to treat an Option as a List of zero or one elements, there's no general pattern for Lists with two or more elements.
The other way around, however, is supported for convenience:
List(Some(1),None,Some(2),Some(3)).flatten => List(1, 2, 3)

Edit: i misspoke. it's not an implicit conversion to Option that makes this possible, but rather that Option is traversable. In the api docs, List's flatten is actually:
def flatten[B](implicit asTraversable: (A) ⇒ GenTraversableOnce[B]): List[B]


text:
Q: modify json using form and PHP I'm developing a page that takes the info of a json, print a form with the json's values, the user can change it and now I'm trying to upload this data to override the original json with the new data. At this point, I have two arrays, one with the "keys" of the json, and another with the new data that must contain. I can't build the json in the correct way. The problem is to match the two propierties (key and data) to make an array for json_decode after.
I have:
$arrayClave with the keys of the json.
and $guardar with the new data.
I have to build a new json with the keys plus the data, like this:
{"ID":"12450","MARCA":"Roly" .... }
I've tried to build the array like array($arrayClave[1] => $guardar[1]);
but I need to build it for every number of inputs, that change in different cases, so I need to use a loop, but it's not possible to do something like:
for($i=0; $i<99; $i++){
    $var = $arrayClave[$i] => $guardar[$i],;
}

$result = array($var);

I know this is not correct, but I don't know the way to do it. If someone can help me I'll be gratefull, I hope I've explained myself in the best way :) Thanks in advance!

A: where $arrayClave and $guardar should be arrays
 for($i=0; $i<99; $i++){
  $arrayClave[$i] = $guardar[$i];
  }

 print_r(json_encode($arrayClave));

try this

A: Array 1: The Array that containd the Keys "tags" of the json, it comes from the previous page, by a form input:
$arrayClave

Array2: The Array that contains the values of the json, it gets the value of each input that the user has modified in the previous page:
foreach ($arrayClave as $value){
    $valorA = ($_GET[$value]);
    $guardar[] = $valorA;
}


text:
Q: Split by three spaces - batchscript I have a string like this.
adsads   d b c   dsad   ds   ads

How do I split this string (on 3 spaces) to obtain d b c from this string?

A: @echo off
setlocal EnableDelayedExpansion

set "str=adsads   d b c   dsad   ds   ads"

set "i=1" & set "part[!i!]=%str:   =" & set /A i+=1 & set "part[!i!]=%"

echo part[2] = "%part[2]%"

If you want to know how this simple (one line) method works, just remove the @echo off line and carefully review the executed code! ;)

A: @ECHO OFF
SETLOCAL

SET "string=adsads   d b c   dsad   ds   ads"

FOR /f "tokens=1delims=#" %%p IN ("%string:   =#%") DO ECHO token 1 is "%%p"
FOR /f "tokens=2delims=#" %%p IN ("%string:   =#%") DO ECHO token 2 is "%%p"
FOR /f "tokens=3delims=#" %%p IN ("%string:   =#%") DO ECHO token 3 is "%%p"
FOR /f "tokens=1,3delims=#" %%p IN ("%string:   =#%") DO ECHO token 1 is "%%p"; token 3 is "%%q"
GOTO :EOF

Here, for /f parses the string supplied (in quotes) and assigns the nominated token number to %%p (and if more than 1 token is specified to %%q, %%r...)
The string between the quotes is constructed by substituting # for SpaceSpaceSpace - # being a character that doesn't otherwise occur in the string.

A: You seem to need the second "token". This is possible with simple substring substitution (no need for a for or delayed expansion)
set string=adsads   d b c   dsad   ds   ads

set string=%string:*   =%
set string=%string:   =&REM %
echo "%string%"

The first set removes from the start of string all until (including) the three spaces. The second one uses a parser trick to remove the next three spaces and anything after.

A: This is dependent on your current input as per question. in other words, the first 3 space will be matched until next 3 spaces.
@echo off
set "line=adsads   d b c   dsad   ds   ads"
set "line=%line:   =:%"
for /f "tokens=1,2 delims=:" %%a in ("%line%") do (
echo %%b
)

A: You could set each token separated by three spaces as variables and just echo the one you want.
e.g.
Rem Turn off echoing of commands to the screen
@Echo Off
Rem enable delayed expansion
SetLocal EnableDelayedExpansion
Rem define a variable to hold the test string
Set "str=adsads   d b c   dsad   ds   ads"
Rem clear all variables beginning with `token`
For /F "Delims==" %%A In ('"Set token 2>Nul"') Do Set "%%A="
Rem Starting token number
Set "i=1"
Rem Set each token separated by three spaces as a variable
Set "token!i!=%str:   =" & Set /A i+=1 & Set "token!i!=%"
Rem Exit if there token number was not incremented
If %i% Lss 2 Exit /B
Rem Show all token variables
Set token
Rem Echo only "token number 2"
Echo "%token2%"
Rem halt script to allow end user to read output
Pause

All lines beginning with Rem are for information only, they can be removed thus:
@Echo Off
SetLocal EnableDelayedExpansion

Set "str=adsads   d b c   dsad   ds   ads"

For /F "Delims==" %%A In ('"Set token 2>Nul"') Do Set "%%A="
Set "i=1"
Set "token!i!=%str:   =" & Set /A i+=1 & Set "token!i!=%"
If %i% Lss 2 Exit /B
Echo %token2%
Pause


text:
Q: Is there a faster way to avoid the for loop in K cross validation in R? I have a code for implementing the K fold cross validation in R:
set.seed(123)
y = rnorm(100,0,1)
x1 = rnorm(100,0,1)
x2 = rnorm(100,0,1)
x3 = rnorm(100,0,1)
x4 = rnorm(100,0,1)
x5 = rnorm(100,0,1)
data = data.frame(y,x1,x2,x3,x4,x5);head(data)

# create k = 10 fold cross validation
folds = cut(seq(1,nrow(data)),breaks=10,labels=FALSE)

# perform the cv
for(i in 1:10){
  fold        = which(folds==i,arr.ind=TRUE)
  testData    = data[fold, ]
  trainData   = data[-fold, ]
}

Is there a faster way for R to implement this k-fold cv and avoid the for loop ?

A: Your test_data can be more efficiently divided into a list as
split(data, folds)

#or better
split(data, ceiling(seq_len(nrow(data))/10))
$`1`
             y          x1          x2         x3          x4          x5
1  -0.56047565 -0.71040656  2.19881035 -0.7152422 -0.07355602 -0.60189285
2  -0.23017749  0.25688371  1.31241298 -0.7526890 -1.16865142 -0.99369859
3   1.55870831 -0.24669188 -0.26514506 -0.9385387 -0.63474826  1.02678506
4   0.07050839 -0.34754260  0.54319406 -1.0525133 -0.02884155  0.75106130
5   0.12928774 -0.95161857 -0.41433995 -0.4371595  0.67069597 -1.50916654
6   1.71506499 -0.04502772 -0.47624689  0.3311792 -1.65054654 -0.09514745
7   0.46091621 -0.78490447 -0.78860284 -2.0142105 -0.34975424 -0.89594782
8  -1.26506123 -1.66794194 -0.59461727  0.2119804  0.75640644 -2.07075107
9  -0.68685285 -0.38022652  1.65090747  1.2366750 -0.53880916  0.15012013
10 -0.44566197  0.91899661 -0.05402813  2.0375740  0.22729192 -0.07921171

$`2`
            y          x1         x2         x3          x4          x5
11  1.2240818 -0.57534696  0.1192452  1.3011760  0.49222857 -0.09736927
12  0.3598138  0.60796432  0.2436874  0.7567748  0.26783502  0.21615254
13  0.4007715 -1.61788271  1.2324759 -1.7267304  0.65325768  0.88246516
14  0.1106827 -0.05556197 -0.5160638 -0.6015067 -0.12270866  0.20559750
15 -0.5558411  0.51940720 -0.9925072 -0.3520465 -0.41367651 -0.61643584
16  1.7869131  0.30115336  1.6756969  0.7035239 -2.64314895 -0.73479925
17  0.4978505  0.10567619 -0.4411632 -0.1056713 -0.09294102 -0.13180279
18 -1.9666172 -0.64070601 -0.7230660 -1.2586486  0.43028470  0.31001699
19  0.7013559 -0.84970435 -1.2362731  1.6844357  0.53539884 -1.03968035
20 -0.4727914 -1.02412879 -1.2847157  0.9113913 -0.55527835 -0.18430887

$`3`
            y          x1          x2          x3          x4         x5
21 -1.0678237  0.11764660 -0.57397348  0.23743027  1.77950291  0.9672673
22 -0.2179749 -0.94747461  0.61798582  1.21810861  0.28642442 -0.1082801
23 -1.0260044 -0.49055744  1.10984814 -1.33877429  0.12631586 -0.6984207
24 -0.7288912 -0.25609219  0.70758835  0.66082030  1.27226678 -0.2759452
25 -0.6250393  1.84386201 -0.36365730 -0.52291238 -0.71846622  1.1146485
26 -1.6866933 -0.65194990  0.05974994  0.68374552 -0.45033862  0.5500440
27  0.8377870  0.23538657 -0.70459646 -0.06082195  2.39745248  1.2366758
28  0.1533731  0.07796085 -0.71721816  0.63296071  0.01112919  0.1390979
29 -1.1381369 -0.96185663  0.88465050  1.33551762  1.63356842  0.4102751
30  1.2538149 -0.07130809 -1.01559258  0.00729009 -1.43850664 -0.5584569

$`4`
             y          x1          x2         x3          x4         x5
31  0.42646422  1.44455086  1.95529397  1.0175586 -0.19051680  0.6053707
32 -0.29507148  0.45150405 -0.09031959 -1.1884340  0.37842390 -0.5063335
33  0.89512566  0.04123292  0.21453883 -0.7216044  0.30003855 -1.4205655
34  0.87813349 -0.42249683 -0.73852770  1.5192177 -1.00563626  0.1279930
35  0.82158108 -2.05324722 -0.57438869  0.3773880  0.01925927  1.9458512
36  0.68864025  1.13133721 -1.31701613 -2.0522228 -1.07742065  0.8009143
37  0.55391765 -1.46064007 -0.18292539 -1.3640375  0.71270333  1.1652534
38 -0.06191171  0.73994751  0.41898240 -0.2007810  1.08477509  0.3588557
39 -0.30596266  1.90910357  0.32430434  0.8657794 -2.22498770 -0.6085572
40 -0.38047100 -1.44389316 -0.78153649 -0.1018833  1.23569346 -0.2022409

$`5`
             y         x1         x2          x3         x4         x5
41 -0.69470698  0.7017843 -0.7886220  0.62418747 -1.2410445 -0.2732481
42 -0.20791728 -0.2621975 -0.5021987  0.95900538  0.4547693 -0.4686998
43 -1.26539635 -1.5721442  1.4960607  1.67105483  0.6599026  0.7041673
44  2.16895597 -1.5146677 -1.1373036  0.05601673 -0.1998898 -1.1973635
45  1.20796200 -1.6015362 -0.1790516 -0.05198191 -0.6451140  0.8663661
46 -1.12310858 -0.5309065  1.9023618 -1.75323736  0.1653210  0.8641525
47 -0.40288484 -1.4617556 -0.1009749  0.09932759  0.4388187 -1.1986224
48 -0.46665535  0.6879168 -1.3598407 -0.57185006  0.8833028  0.6394920
49  0.77996512  2.1001089 -0.6647694 -0.97400958 -2.0523370  2.4302267
50 -0.08336907 -1.2870305  0.4854600 -0.17990623 -1.6363793 -0.5572155

$`6`
             y         x1          x2          x3         x4          x5
51  0.25331851  0.7877388 -0.37560287  1.01494317  1.4304023  0.84490424
52 -0.02854676  0.7690422 -0.56187636 -1.99274849  1.0466288 -0.78220185
53 -0.04287046  0.3322026 -0.34391723 -0.42727929  0.4352889  1.11071142
54  1.36860228 -1.0083766  0.09049665  0.11663728  0.7151784  0.24982472
55 -0.22577099 -0.1194526  1.59850877 -0.89320757  0.9171749  1.65191539
56  1.51647060 -0.2803953 -0.08856511  0.33390294 -2.6609228 -1.45897073
57 -1.54875280  0.5629895  1.08079950  0.41142992  1.1102771 -0.05129789
58  0.58461375 -0.3724388  0.63075412 -0.03303616 -0.4849876 -0.52692518
59  0.12385424  0.9769734 -0.11363990 -2.46589819  0.2306168 -0.19726487
60  0.21594157 -0.3745809 -1.53290200  2.57145815 -0.2951578 -0.62957874

$`7`
             y         x1          x2         x3          x4         x5
61  0.37963948  1.0527115 -0.52111732 -0.2052993  0.87196495 -0.8338436
62 -0.50232345 -1.0491770 -0.48987045  0.6511933 -0.34847245  0.5787224
63 -0.33320738 -1.2601552  0.04715443  0.2737665  0.51850377 -1.0875807
64 -1.01857538  3.2410399  1.30019868  1.0246732 -0.39068498  1.4840309
65 -1.07179123 -0.4168576  2.29307897  0.8176594 -1.09278721 -1.1862066
66  0.30352864  0.2982276  1.54758106 -0.2097932  1.21001051  0.1010792
67  0.44820978  0.6365697 -0.13315096  0.3781678  0.74090001  0.5329893
68  0.05300423 -0.4837806 -1.75652740 -0.9454088  1.72426224  0.5867353
69  0.92226747  0.5168620 -0.38877986  0.8569230  0.06515393 -0.3017467
70  2.05008469  0.3689645  0.08920722 -0.4610383  1.12500275  0.0795020

$`8`
            y          x1          x2          x3         x4          x5
71 -0.4910312 -0.21538051  0.84501300  2.41677335  1.9754191  0.96126415
72 -2.3091689  0.06529303  0.96252797 -1.65104890 -0.2814821 -1.45646592
73  1.0057385 -0.03406725  0.68430943 -0.46398724 -1.3229511 -0.78173971
74 -0.7092008  2.12845190 -1.39527435  0.82537986 -0.2393516  0.32040231
75 -0.6880086 -0.74133610  0.84964305  0.51013255 -0.2140412 -0.44478198
76  1.0255714 -1.09599627 -0.44655722 -0.58948104  0.1516805  1.37000399
77 -0.2847730  0.03778840  0.17480270 -0.99678074  1.7123050  0.67325386
78 -1.2207177  0.31048075  0.07455118  0.14447570 -0.3261439  0.07216675
79  0.1813035  0.43652348  0.42816676 -0.01430741  0.3730047 -1.50775732
80 -0.1388914 -0.45836533  0.02467498 -1.79028124 -0.2276841  0.02610023

$`9`
              y          x1         x2          x3          x4         x5
81  0.005764186 -1.06332613 -1.6674751  0.03455107  0.02045071 -0.3164159
82  0.385280401  1.26318518  0.7364960  0.19023032  0.31405766 -0.1023465
83 -0.370660032 -0.34965039  0.3860266  0.17472640  1.32821470 -1.1815592
84  0.644376549 -0.86551286 -0.2656516 -1.05501704  0.12131838  0.4986580
85 -0.220486562 -0.23627957  0.1181445  0.47613328  0.71284232 -1.0389564
86  0.331781964 -0.19717589  0.1340386  1.37857014  0.77886003 -0.2262220
87  1.096839013  1.10992029  0.2210195  0.45623640  0.91477327  0.3814258
88  0.435181491  0.08473729  1.6408462 -1.13558847 -0.57439455 -0.7835158
89 -0.325931586  0.75405379 -0.2190504 -0.43564547  1.62688121  0.5829914
90  1.148807618 -0.49929202  0.1680654  0.34610362 -0.38095674 -1.3165104

$`10`
             y          x1          x2         x3         x4         x5
91   0.9935039  0.21444531  1.16838387 -0.6470456 -0.1057842 -2.8097747
92   0.5483970 -0.32468591  1.05418102 -2.1576463  1.4040503  0.4649680
93   0.2387317  0.09458353  1.14526311  0.8842508  1.2940839  0.8405398
94  -0.6279061 -0.89536336 -0.57746800 -0.8294776 -1.0899919 -0.2858454
95   1.3606524 -1.31080153  2.00248273 -0.5735603 -0.8730710  0.5041263
96  -0.6002596  1.99721338  0.06670087  1.5039006 -1.3580791 -1.1559165
97   2.1873330  0.60070882  1.86685184 -0.7741449  0.1818472 -0.1271486
98   1.5326106 -1.25127136 -1.35090269  0.8457315  0.1648409 -1.9415184
99  -0.2357004 -0.61116592  0.02098359 -1.2606829  0.3641147  1.1811809
100 -1.0264209 -1.18548008  1.24991457 -0.3545424  0.5521577  1.8599109

Now your train_data can be also created as a list by using purrr::map and anti_join as
map(split(data, ceiling(seq_len(nrow(data))/10)), ~ anti_join(data, .x))

Its baseR equivalent should be
Map(function(x) setdiff(data, x), split(data1, ceiling(seq_len(nrow(data))/10)))


text:
Q: finding "active" branch in EGIT repository I have to modify a faulty program/feature, which is an extension to org.eclipse.jgit
the program overrides the close method of the PushResultDialog and passes the Repository to an method.
Here i want to find the branch which was actually pushed/checked out. I am only interested if its the master, if not i don't wanna do anything.
else i need the list of the pushed files.
First the program looked like this :
    head = repo.resolve(Constants.HEAD);
        RevCommit commit = rw.parseCommit(head);

        PersonIdent committerIdent = commit.getCommitterIdent();
        sCommitter = committerIdent.getName();

        String sBranch = "?";

        for (Map.Entry<String, Ref> e : repo.getAllRefs().entrySet()) {
            if (e.getKey().startsWith(Constants.R_HEADS)) {
                Ref ref = e.getValue();
                if (rw.isMergedInto(commit, rw.parseCommit(ref.getObjectId()))) {
                    sTemp = ref.getName();

                    int i = sTemp.lastIndexOf('/');
                    if (i == -1)
                        continue;

                    sBranch = sTemp.substring(i + 1);

                    System.out.println("Ref " + sBranch
                            + " < contains > " + commit);

                    if (sBranch.equalsIgnoreCase("master")) {
                        break;
                    } else {
                        return;
                    }
                }
            }
        }

        RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
        DiffFormatter df = new DiffFormatter(
                DisabledOutputStream.INSTANCE);
        df.setRepository(repo);
        df.setDiffComparator(RawTextComparator.DEFAULT);
        df.setDetectRenames(true);
        List<DiffEntry> diffs = df.scan(parent.getTree(),
                commit.getTree());
        for (DiffEntry diff : diffs) {
            sTemp = diff.getNewPath();
            pushedObjects.add(sTemp);
        }

now .. this works as long as the workflow in eclipse is just "checkout master" "pull" "merge branch" "push"
any other order seems to mess with the order of the branches in the set, and it stumbles over this "else" :
if (sBranch.equalsIgnoreCase("master")) {
      break;
 } else {
      return;
 }

the question is : is there an eaasy method to pick the right branch?

A: Ok, i think i can simply look at the HEAD in the set:
e.getKey().startsWith(Constants.HEAD)

and then parse the branchname, that should always be the branch which is checked out, if (in my case),if it is the master, i am happy.


text:
Q: Error Code 1215 foreign key en mysql Estoy teniendo problemas con tres FK. Es una relación N:N que apunta a sus PK . Todas tienen el mismo tipo (SMALLINT)
Esta es la tabla dónde tengo que poner esas FK
CREATE TABLE IF NOT EXISTS result(
municipalityID SMALLINT,
districtID     SMALLINT,
sectionID      SMALLINT,
tableID        SMALLINT,
partyID        SMALLINT,
provinceID     SMALLINT,
votes          INTEGER,

Tabla que tiene las PK y quiero que sean FK.
introducir el código aquí
CREATE TABLE IF NOT EXISTS  tableElection (
municipalityID  SMALLINT,
districtID      SMALLINT,
sectionID         SMALLINT,
tablesID        SMALLINT,
possibleVotes   INTEGER,
totalVotes      INTEGER,
nullVotes       INTEGER,
blankVotes      INTEGER,
pollingstationID SMALLINT NOT NULL,
CONSTRAINT pk_tableElection PRIMARY KEY
(municipalityID,districtID,sectionID,tablesID),
CONSTRAINT fk_tableElection_pollingstation FOREIGN KEY
(pollingstationID)
                         REFERENCES pollingstation(ID)
                               ON DELETE CASCADE ON UPDATE CASCADE

);

Sólo he tenido problemas con esas tres FK. Las estoy añadiendo con esta sentencia
ALTER TABLE result
ADD FOREIGN KEY (districtID) REFERENCES tableElection (districtID);

ALTER TABLE result
ADD FOREIGN KEY (sectionID) REFERENCES tableElection (ID);

ALTER TABLE result
ADD FOREIGN KEY (tableID) REFERENCES tableElection(tableID);

Y me sale un "ERROR CODE 1215 CANNOT ADD FOREIGN KEY CONSTRAINT" . ¿Porque me da este error si tengo la tabla creada y el tipo de dato coincide?
Gracias!!!

A: Para que puedas crear tus tablas, deberías hacerlo en el orden siguiente idealmente:
CREATE TABLE pollingstation(
    id SMALLINT NOT NULL,
    name VARCHAR(100)
);

CREATE TABLE IF NOT EXISTS result(
municipalityID SMALLINT,
districtID     SMALLINT,
sectionID      SMALLINT,
tableID        SMALLINT,
partyID        SMALLINT,
provinceID     SMALLINT,
votes          INTEGER
);

CREATE TABLE IF NOT EXISTS  tableElection (
municipalityID  SMALLINT,
districtID      SMALLINT,
sectionID         SMALLINT,
tablesID        SMALLINT,
possibleVotes   INTEGER,
totalVotes      INTEGER,
nullVotes       INTEGER,
blankVotes      INTEGER,
pollingstationID SMALLINT NOT NULL,
CONSTRAINT pk_tableElection PRIMARY KEY (municipalityID,districtID,sectionID,tablesID),
CONSTRAINT fk_tableElection_pollingstation FOREIGN KEY (pollingstationID) REFERENCES pollingstation(ID) ON DELETE CASCADE ON UPDATE CASCADE
);

Yo solo agregué al inicio una tabla de ejemplo, para complementar el ejercicio y de este modo te evitas los comandos de ALTER TABLE


text:
Q: Getting this error constantly: IOUnserialize has detected a string that is not valid UTF-8 I'm getting these errors constantly from various processes, the invalid string is always the same though. How do I find where the string is located?
Here are the latest ones. I removed the duplicates.
3/27/14 04:57:51.705 SystemUIServer[331]: FIXME: IOUnserialize has detected a string that is not valid UTF-8, "~?�".
3/27/14 04:57:57.568 airportd[65]: FIXME: IOUnserialize has detected a string that is not valid UTF-8, "~?�".
3/27/14 04:57:57.685 configd[18]: FIXME: IOUnserialize has detected a string that is not valid UTF-8, "~?�".
3/27/14 04:57:57.698 Little Snitch Daemon[77]: FIXME: IOUnserialize has detected a string that is not valid UTF-8, "~?�".
3/27/14 04:58:47.176 com.apple.preference.network.remoteservice[12469]: FIXME: IOUnserialize has detected a string that is not valid UTF-8, "~?�".
3/27/14 04:59:35.939 CrashPlanService[75]: FIXME: IOUnserialize has detected a string that is not valid UTF-8, "~?�".
3/27/14 05:16:13.434 Finder[347]: FIXME: IOUnserialize has detected a string that is not valid UTF-8, "~?�".

A: It looks like your Mavericks installation had a hick up.
Reinstall it.
To find out the source one has to open the pref files of all named processes and look for the UTF-8, "~?�"
You wont be able to fix it there but maybe see it.
You can try the search with Terminal fgrep -iR "~?�" /Library/Preferences
There is also a way to investigate the

configd

You can debug configd by running another copy. You type in the terminal:
sudo /usr/libexec/configd -dv

It will ask for you password. This should give you debugging info about each bundle as it loads and dump any messages that normally go into the syslog to the terminal window.
You can load each bundle mentioned in your console log one at a time too e.g:
sudo /usr/libexec/configd -dv -t /System/Library/SystemConfiguration/Logger.bundle

Use ctrl-c to quit the process.
The number is the process id listed in the leftmost column in the Activity Monitor next to the process you want to close.
Looking at your console log, it looks like the common theme is Network. It might have to do with your airport app, but not sure since insufficient information given.
Does it comes up in Safe mode?


text:
Q: Solve $x+a^xThe answer to $x+3^x<4$ is $x<1$ by plotting the graph of $y=x+3^x$ and $y =4$. Is there a way to get to the solution algebraically?
Updated:  is there a way to get to the solution of $x+a^x<b$ in general, algebraically?

A: The function $x + 3^x$ is strictly increasing and $1 + 3^1 = 4$. (Not sure if this is what you mean by algrebraic method).

A: The Lambert $W$ Function is defined to be the inverse of $f(x) = xe^x$.  It is not an elementary function, so it cannot be expressed in terms of elementary functions (like $\exp$, $\sin$, $\sqrt[n]{x}$, $x^n$, etc.).  I don't know how exactly you are defining 'algebraic', but whatever your definition is, the Lambert $W$ function is not algebraic.
Let's see if we can solve your problem in terms of the Lambert $W$ function.  Since the Lambert $W$ function is not elementary (algebraic), this will show that we can't solve your equation algebraically.
Let's consider the equation
$$x + a^x = b$$
I'll focus on the case $a \ge 1$, so $x + a^x$ is strictly increasing and the unique solution to this equation is the right endpoint to the infinite interval of points that satisfy $x + a^x < b$.  To use the $W$ function, we'll have to get all of the $x$'s on one side, so we have something like $f(x)e^{f(x)} = C$.
$$e^{x\ln a} = b - x$$
$$e^{b\ln a} = (b-x)e^{(b-x)\ln a}$$
$$a^b\ln a = \ln a(b-x)e^{(b-x)\ln a}$$
Now, using the definition of the $W$ function, we have
$$\ln a(b-x) = W\left(a^b\ln a\right)$$
which we can simplify to get
$$x = b - \frac{W\left(a^b\ln a\right)}{\ln a}$$
For $0 < a < 1$, the situation is more complicated, since
$$\lim_{x\to+\infty} x + a^x = +\infty$$
and
$$\lim_{x\to-\infty} x+a^x = +\infty$$
so the set of points that satisfy $x + a^x < b$ (if any such points exist) will be bounded above and below.  Since the second derivative of $f(x) = x + a^x$ is $f''(x) = a^x(\ln a)^2$, which is positive everywhere, we can see that the set of solutions will either be a finite open interval $(a,b)$, or the empty set (no solutions).

A: What happens if x=1? Then x+3^x becomes 1+3=4 so that choice is to large because we want less then 4, so anything less than 1 will give us something less than 4. It makes sense !


text:
Q: How can I remove a newline from inside a string in C++? I am trying to take text input from the user and compare it to a list of values in a text file. The values are this:

That line at the end is the cursor, not a straight line, but it doesn't matter. Anyway, I sort by word and produce the values, then check the values. Semicolon is a separator between words. All the data is basic to get the code working first. The important thing is that all the pieces of data have newlines after them. No matter what I try, I can't get rid of the newlines completely. Looking at the ASCII values shows why, My efforts remove only the new line, but not the carriage return. This is fine most of the time, but when comparing values they won't be the same because the one with the carriage return is treated as longer. Here is the important parts of the code:
    int pos = 0;
    while (pos != std::string::npos)
    {
        std::string look = lookContents.substr(pos+1, lookContents.find("\n", pos + 1) - pos);
        //look.erase(std::remove(look.begin(), look.end(), '\n'), look.end());

        //##
        for (int i = 0; i < look.length(); i++)
        {
            std::cout << (int)(look[i]) << " ";
        }
        std::cout << std::endl;
        std::cout << look << ", " << words[1] << std::endl;
        std::cout << look.compare(0,3,words[1]) << std::endl;
        std::cout << pos << std::endl;
        //##

        //std::cout << look << std::endl;
        if (look == words[1])
        {
            std::cout << pos << std::endl;
            break;
        }
        pos = lookContents.find("\n", pos + 1);
    }

Everything between the //## are just error checking things. Heres what is outputs when I type look b:2

As you can see, the values have the ASCII 10 and 13 at the end, which is what is used to create newlines. 13 is carriage return and 10 is newline. The last one has its 10 remove earlier in the code so the code doesn't do an extra loop on an empty substring. My efforts to remove the newline, including the commented out erase function, either only remove the 13, or remove both the 10 and 13 but corrupt later data like this:

Also, you can see that using cout to print look and words1 at the same time causes look to just not exist for some reason. Printing it by itself works fine though. I realise I could fix this by just using that compare function in the code to check all but the last characters, but this feels like a temporary fix. Any solutions?

A:
My efforts remove only the new line, but not the carriage return

The newline and carriage control are considered control characters.
To remove all the control characters from the string, you can use std::remove_if along with std::iscntrl:
#include <cctype>
#include <algorithm>
//...
lookContents.erase(std::remove_if(lookContents.begin(), lookContents.end(),
                  [&](char ch)
                  { return std::iscntrl(static_cast<unsigned char>(ch));}),
                  lookContents.end());

Once you have all the control characters removed, then you can process the string without having to check for them.


text:
Q: Assign value to entities - Anylogic I am just starting with Anylogic & Java. Could you please help me with my simple issue?
I have two windows: Main & Trucks
The trucks are entities generated on my model using a "source" within "Main".
I asked the model to create 10 trucks at the same time. It creates the trucks and then they move to another defined point at different speeds. When they arrive at the final point I want to know which truck arrived first (1, 2, ... or 10).
So... I am assuming that there is a way to assign a number to each truck when they are created. And I am also assuming I can read this number at the final point to know which one arrived first.
How can I do this?

A: Yes it is possible. Use a parameter. Truck is an agent and it can have multiple parameters. The easiest way to use parameters is to drag them from the Agent pallet into the Truck window. You define its name and type (in your case will be integer). When the truck is generated at the source you can give the parameter the value you want. If you want to have a sequential number, create a variable in your main window called ID with initial value 1 and then, in the source object, on the On Exit code area you type something like:
Agent.parameter = ID++;
Note that "parameter" should be the name of the parameter you created in Truck window.
Hope that helps.


text:
Q: Setting Arbitrary Configuration Options Using Cargo According to the docs "For rustc, arbitrary-set configuration options are set using the --cfg flag." Sure enough I can enable the message using rustc --cfg foo main.rs. How do I do this in cargo?
fn main() {
    #[cfg(foo)]
    println!("FOO");
}

Note: I'd rather not use a feature as discussed in this question. Alternatively convince me why I should always use a feature flag for custom compile time options.


text:
Q: Recursively remove all the numbers in the string and return reversed version of that string without numbers I need to remove all the numbers from the string recursively and then return the reversed string.
def remove_numbers_and_reverse(string):

if string == "":
    return string
elif string[-1].isdigit():
    string.replace(string[-1], "")
return string[-1] + remove_numbers_and_reverse(string[:-1])

For example if the input is "bunny1234" then the output should be "ynnub". But i get "4321ynnub".
"bunny1234" -> "ynnub"
"3434string" -> "gnirts"

A: For Removing number try below approach:
1. using join and isdigit
ini_string = "Test123ing127you"
print("initial string : ", ini_string)
res = ''.join([i for i in ini_string if not i.isdigit()])
print("final string : ", res)

2. Using translate and digits
from string import digits
ini_string = "Test123ing127you"
remove_digits = str.maketrans('', '', digits)
res = ini_string.translate(remove_digits)
# printing result
print("final string : ", res)

3. Using filter and lambda
ini_string = "amol23bais"
res = "".join(filter(lambda x: not x.isdigit(), ini_string))
# printing result
print("final string : ", str(res))

A: The problem with your solution is the elifpart: You are not doing anything with your replaced string, replace is not working in-place. So instead you might try this:
def remove_numbers_and_reverse(string):

    if string == "":
        return string
    elif string[-1].isdigit():
        return remove_numbers_and_reverse(string[:-1])
    else:
        return string[-1] + remove_numbers_and_reverse(string[:-1])

print(remove_numbers_and_reverse("bunny1234"))
print(remove_numbers_and_reverse("3434string"))

Here I just ignore the last character if it is a digit.
For shorter and smarter solutions see @Amolb's answer.

A: Other people have answered it but might as well throw in my example too.
def remove_numbers_and_reverse(my_string):
  if not my_string:
    return my_string
  else:
    for letter in my_string:
      if letter.isdigit():
        continue
      output = letter + output
  return output

The output:
[user@machine test-dir]$ python3
Python 3.6.9 (default, Aug 15 2019, 16:59:35)
>>> import test
>>> test.remove_numbers_and_reverse("bunny1234")
'ynnub'
>>> test.remove_numbers_and_reverse("3434string")
'gnirts'
>>> test.remove_numbers_and_reverse("3434string123123morestring")
'gnirtseromgnirts'
>>> test.remove_numbers_and_reverse("")
''
>>>


text:
Q: Search and replace html element from string How do I remove all form elements and their contents using php. What pattern should I insert in preg_replace;
HTML string:

Hey I am a boy

<form id='id1' class='class1'>Content</form>

Hey I am a girl

<form id='id1' class='class1'>content</form>

Preg_replace should return string:

I am a boy

Hey I am a girl

i want all form elements stripped out of return string

A: Use the below regex and then replace the match with an empty string.
(?s)(^|\n)?<form\b.*?<\/form>

DEMO
Explanation:
(?s)                     set flags for this block (with . matching
                         \n) (case-sensitive) (with ^ and $
                         matching normally) (matching whitespace
                         and # normally)
(                        group and capture to \1 (optional):
  ^                        the beginning of the string
 |                        OR
  \n                       '\n' (newline)
)?                       end of \1 (NOTE: because you are using a
                         quantifier on this capture, only the LAST
                         repetition of the captured pattern will be
                         stored in \1)
<form                    '<form'
\b                       the boundary between a word char (\w) and
                         something that is not a word char
.*?                      any character (0 or more times)
<                        '<'
\/                       '/'
form>                    'form>'

A: <form[^>]*>((?!<\/form>).)*<\/form>

Try this.Replace by empty string.See demo.
http://regex101.com/r/dZ1vT6/17

A: You can use this :
preg_replace('#<form*>*</form>#isU','',$str);

A: You can use strip_tag to remove all tags but pass the
 as a second parameter to return only that.
echo strip_tags($text, '
');

If that doesn't work, use:
echo preg_replace('/<form[^>]*>([\s\S]*?)<\/form[^>]*>/', '', '$text);


text:
Q: How to install a postgresql JDBC driver in pyspark I use pyspark with spark 2.2.0 on a lubuntu 16.04 and I want to write a Dataframe to my Postgresql database. Now as far as I understand it I have to install a jdbc driver on the spark master for it. I downloaded the postgresql jdbc driver from their website and tried to follow this post. I added spark.jars.packages /path/to/driver/postgresql-42.2.1.jar to spark-default.conf with the only result that pyspark no longer launches.
I'm kinda lost in java land for one I don't know if this is the right format.The documentation tells me I should add a list but I don't know how a path list is supposed to look like. Then I don't know if I also have to specify spark.jars and or spark.driver.extraClassPath or if  spark.jars.packages is enough? And if i have to add them what kind of format are they?

A: spark.jars.packages is for dependencies that can be pulled from Maven (think it as pip for Java, although the analogy is probably kinda loose).
You can submit your job with the option --jars /path/to/driver/postgresql-42.2.1.jar, so that the submission will also provide the library, that the cluster manager will distribute on all worker nodes on your behalf.
If you want to set this as a configuration you can use the spark.jars key instead of spark.jars.packages. The latter requires Maven coordinates, rather then a path (which is probably the reason why your job is failing).
You can read more about the configuration keys I introduced on the official documentation.


text:
Q: Clarify on enriched categories The teacher mentioned that, given a category $\mathbb C$ enriched in a (monoidal) category $\mathbb V$,the category $\mathbb C^{op}$ is enriched in $\mathbb V$ iff $\mathbb V$ is commutative. However I don't see where actually is requested the commutativity of the product of $\mathbb V$; for example, in the case of a usual category (i.e. enriched in sets) $\mathbb C$, when I verify that the definition of $\mathbb C^{op}$ gives raise to a category, I don't see where I use that the product of sets is commutative. Thanks in advance

A: The composition in the opposite category is
$$C^\mathrm{op}(x,y)\otimes C^\mathrm{op}(y,z)=C(y,x)\otimes C(z,y)\cong C(z,y)\otimes C(y,z)\xrightarrow{\circ}C(z,x)=C^\mathrm{op}(x,z)$$
and to define it you need the symmetry isomorphism in the middle.


text:
Q: Attempt to invoke virtual method 'androidx.lifecycle.LiveData com.example.xxx.viewmodels.CoffeeViewModel.getAllOrders()' on a null object reference **I would like to find out how to fix this exception... Please, help me to fix this.
Full Error App Stops and in Logcat I have: **

2021-08-05 01:26:38.697 11264-11264/com.example.mikhail_myorder E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mikhail_myorder, PID: 11264
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mikhail_myorder/com.example.mikhail_myorder.OrderScreen}: java.lang.NullPointerException: Attempt to invoke virtual method 'androidx.lifecycle.LiveData com.example.mikhail_myorder.viewmodels.CoffeeViewModel.getAllOrders()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'androidx.lifecycle.LiveData com.example.mikhail_myorder.viewmodels.CoffeeViewModel.getAllOrders()' on a null object reference
at com.example.mikhail_myorder.OrderScreen.onCreate(OrderScreen.java:62)
at android.app.Activity.performCreate(Activity.java:7009)
at android.app.Activity.performCreate(Activity.java:7000)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

CoffeeViewModel
public class CoffeeViewModel extends AndroidViewModel {
    private CoffeeRepo coffeeRepo;
    private LiveData<List<Coffee>> allDisplayCoffee;

    public CoffeeViewModel(Application application) {
        super(application);
        this.coffeeRepo = new CoffeeRepo(application);
        this.allDisplayCoffee = this.coffeeRepo.allCoffee;
    }

    public LiveData<List<Coffee>> getAllOrders() {
        return allDisplayCoffee;
    }

    public Coffee getCoffeeById(int id){
        return this.coffeeRepo.getCoffeeById(id);
    }

    public void insertCoffee(Coffee newCoffee){
        this.coffeeRepo.insertCoffee(newCoffee);
    }

    public void updateCoffee(Coffee coffee){
        this.coffeeRepo.updateCoffee(coffee);
    }

    public void deleteCoffee(Coffee coffee){
        this.coffeeRepo.deleteCoffee(coffee);
    }
}

OrderScreen
public class OrderScreen extends AppCompatActivity implements OnOrderItemClickListener {

    private final String TAG = this.getClass().getCanonicalName();
    private ArrayList<Order> coffeeArrayList;
    private ActivityOrderViewBinding binding;
    private OrderAdapter orderAdapter;
    private CoffeeViewModel coffeeViewModel;
    private ItemTouchHelper helper;
    private Order tempCoffeeItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_score_board);
        this.binding = ActivityOrderViewBinding.inflate(getLayoutInflater());
        setContentView(this.binding.getRoot());

        this.helper = new ItemTouchHelper(simpleCallback);
        this.helper.attachToRecyclerView(this.binding.recyclerView);

        this.coffeeArrayList = new ArrayList<>();

        this.orderAdapter = new OrderAdapter(this, this.coffeeArrayList, this);
        this.binding.recyclerView.setAdapter(orderAdapter);
        this.binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        this.binding.recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));

        this.coffeeViewModel.getAllOrders().observe(this, new Observer<List<Coffee>>() {
            @Override
            public void onChanged(List<Coffee> coffeeList) {
                if (!coffeeList.isEmpty()){
                    Log.e(TAG, "onChanged: coffees received from DB " + coffeeList.toString() );
                    coffeeArrayList.clear();

                    for(Coffee tempOrder: coffeeList){
                        tempCoffeeItem = new Order();
                     //   tempCoffeeItem.setChosenCoffeeId(tempOrder.getCoffeeId());
                        tempCoffeeItem.setChosenCoffeeType(tempOrder.getCoffeeType());
                        tempCoffeeItem.setChosenCoffeeSize(tempOrder.getCoffeeSize());
                        tempCoffeeItem.setChosenCoffeeQuantity(tempOrder.getCoffeeQuantity());

                        coffeeArrayList.add(tempCoffeeItem);
                    }
                    orderAdapter.notifyDataSetChanged();
                }else{
                    Log.e(TAG, "onChanged: empty coffee/order list");
                }
            }
        });

//        ArrayList<Order> extraScores = this.getIntent().getParcelableArrayListExtra("EXTRA_ORDER_LIST");
//        if (extraScores != null){
//            this.orderArrayList = extraScores;
//            Log.d(TAG, "onCreate: Order list received from MainActivity " + this.orderArrayList.toString());
//        }else{
//            Log.e(TAG, "onCreate: No data received from MainActivity");
//        }
//
//        this.orderAdapter = new OrderAdapter(this, this.orderArrayList);

    }

    @Override
    public void onCoffeeItemClicked (Order order) {
        Log.e(TAG, "onMealItemClicked: Update the coffee name");

        Coffee selected = new Coffee();
        selected.setCoffeeType(order.getChosenCoffeeType());
        selected.setCoffeeSize(order.getChosenCoffeeSize());
        selected.setCoffeeQuantity(order.getChosenCoffeeQuantity());

        AlertDialog.Builder updateAlert = new AlertDialog.Builder(this);
        updateAlert.setTitle("Update");
        updateAlert.setMessage("Provide the updated name for the coffee.");

        final EditText inputName = new EditText(this);
        inputName.setText(selected.getCoffeeType());
        updateAlert.setView(inputName);

        updateAlert.setPositiveButton("Done", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //update the coffee in DB

                selected.setCoffeeType(inputName.getText().toString());
                coffeeViewModel.updateCoffee(selected);
                orderAdapter.notifyDataSetChanged();

                Toast.makeText(getApplicationContext(),
                        selected.getCoffeeType() + " has been updated",
                        Toast.LENGTH_LONG).show();
            }
        });

        updateAlert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        updateAlert.show();
    }

    ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
        @Override
        public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
            if (direction == ItemTouchHelper.LEFT){
                //delete the coffee from DB
                deleteCoffee(viewHolder.getAdapterPosition());
            }
        }
    };

    private void deleteCoffee(int position){
        Order selectedOrder = coffeeArrayList.get(position);

        //ask for confirmation
        AlertDialog.Builder deleteAlert = new AlertDialog.Builder(this);
        deleteAlert.setTitle("Delete");
        deleteAlert.setMessage("Are you sure you want to remove "+ selectedOrder.getChosenCoffeeType() + " from the list?");

        deleteAlert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //delete the meal in DB

                Coffee toDelete = new Coffee();
                toDelete.setCoffeeType(selectedOrder.getChosenCoffeeType());
                toDelete.setCoffeeQuantity(selectedOrder.getChosenCoffeeQuantity());
                toDelete.setCoffeeSize(selectedOrder.getChosenCoffeeSize());

                coffeeViewModel.deleteCoffee(toDelete);

                Toast.makeText(getApplicationContext(),
                        selectedOrder.getChosenCoffeeType() + " has been removed from list",
                        Toast.LENGTH_LONG).show();
            }
        });

        deleteAlert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                orderAdapter.notifyDataSetChanged();
                dialog.dismiss();
            }
        });

        deleteAlert.show();
    }
}

A: It looks like you haven't created your coffeeViewModel yet. Use a ViewModelProvider.
coffeeViewModel = new ViewModelProvider(this).get(CoffeeViewModel.class);


text:
Q: 2d array of actionListeners and 2d arry of JButton trouble I'm having a little bit of trouble getting my actionListeners with my Jbuttons... So I have 3 files - one for the model (information storage), one for the actual GUI, and then a third that deals with all the actions to the buttons. In my GUI, i made a 8 by 8 array of JButtons with icons, each equipped with a selectedIcon as well. Then, in my controller class, I set the action listeners for all my buttons.. How do I properly set and use them for the 2D array of JButtons? I used a double for loop to make the grid.. and for the controller class, here is the code for the action listener that I have now:
for (i = 0; i < model.ROWS; i ++) {
  for (j = 0; j < model.ROWS; j ++) {

    buttonListeners[i][j] = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        view.buttonGrid[i][j].setSelected(!view.buttonGrid[i][j].isSelected());
      }
    };
  }
}
i = 0;
j = 0;
enableListeners();

What it does now though is when i click any button, it only selects and deselects the first button... Any help would be greatly appreciated!!

A: When you want to use the variables i and j in the ActionListener that you are creating there, the variables either have to be final, or instance variables of the enclosing class.
At the moment, they are abviously declared as instance variables. And after the action listeners have been created, you set them back to i=0 and j=0. That's why all action listeners only affect buttonGrid[0][0]!
You can define local final variables for your purpose:
for (int i = 0; i < model.ROWS; i ++)
{
    for (int j = 0; j < model.ROWS; j ++)
    {
        final int fi = i;
        final int fj = j;
        buttonListeners[i][j] = new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                view.buttonGrid[fi][fj].setSelected(
                    !view.buttonGrid[fi][fj].isSelected());
            }
        };
    }
}

(and don't forgest to remove the instance variables i and j, you should not need them any more)


text:
Q: Как с помощью canvas растянуть изображение на весь экран, без потери качества Помогите решить проблему. Нужно с помощью canvas растянуть изображение на весь экран, без потери качества. И чтоб при изменении размеров окна изображение подстраивалось под размеры. Вообщем заказчик хочет как тут (http://www.a-gu.ru/). На этом сайте реализовано с помощью флеша.
Или подскажите другие способы решения проблемы. Буду благодарен за ссылки на флеш-модули, которые так растягивают изображение.

A: Посмотрите на эти примеры: непринужденные фоновые изображения на весь экран с помощью jQuery.
A: Что лучше canvas, flash или css3 вам выбирать, да.
Вот с канвой пример. Только надо еще правильно ширину и высоту считать и смещение, когда размеры окна имеют отличные от картинки пропорции. В общем все возможно и реализуемо.


text:
Q: Vivado Integrated Logic Analyzer Waveform empty I am using Vivado 15.2 on Linux with a Zynq FPGA. My design contains a single Integrated Logic Analyzer (ILA) core with some signals connected to it. Downloading works find and the hardware-manager loads the dashboard view as expected. The only problem, is that the Waveform window does not allow me to add any signals. The only thing it shows a is "No Content"  message. In the Trigger-Setup window it is no problem to select the signals.
What do I need to change to see the signals in the Dashboard?

A: The problem has been solved by rebooting the machine and regenerating the bitfile. :-(


text:
Q: How can I get Zurb Foundation 5 to be more mobile friendly on iPhone 5/Galaxy S4 I'm having trouble getting my layout to be more mobile friendly on high pixel count screens. On iPhone 5 and Galaxy S4 it's showing the medium layout instead of small. I really love Foundation and it's really been helpful, this is just being a hangup for me. The medium layout is so small on appearing on these high pixel count screens that it's not really usable.
The site i'm working on is mtgdatabase.com. I'm using Laravel with Foundation 5, and the source code is located here.
I started with small and worked my way up being sure to follow mobile first.
Thank you for your help, I really appreciate it!

A: It sounds like you want to adjust your media queries to show for small at a higher pixel density. You can access the media queries and adjust the parameters from the CSS files that you downloaded as part of the Foundation package.
Start here from the Foundation Docs: Zurb - media queries


text:
Q: How to work with distributions that are discrete in some variables and continuous in others?
So, in this problem I am asked to find the cumulative distribution of the continuous variable T and the probability that $J=3$ given T is larger than 10 and lastly the conditional expectation of T given $j=2.$ I have tried just adding the pdf but they do not have the same range? Any idea what to do?

A: As many comments pointed out, the information given by "$f(t, j)$" needs more clarification, because it is neither a simple pdf/pmf nor a standard representation of mixture model.  My interpretation to $f(t, j)$ is that it characterizes the joint distribution of the random vector $(T, J)$ in a way such that (in particular, you should NOT interpret $f(t, j)$ as the conditional density of $T$ given $J = j$, as $\int_\mathbb{R} f(t, j)dt < 1$ for all $j$).
\begin{align}
& F_1(t) := P[T \leq t, J = 1] =
\begin{cases}
0 & t < 0, \\
\int_0^t f(x, 1)dx = \frac{1}{300}t^2 & 0 \leq t < 5, \\
\frac{1}{12} & t \geq 5.
\end{cases} \\
& F_2(t) := P[T \leq t, J = 2] =
\begin{cases}
0 & t < 0, \\
\int_0^t f(x, 2)dx = \frac{1}{600}t^2 & 0 \leq t < 10, \\
\frac{1}{6} & t \geq 10.
\end{cases} \\
& F_3(t) := P[T \leq t, J = 3] =
\begin{cases}
0 & t < 0, \\
\int_0^t f(x, 3)dx = \frac{1}{432}t^2 & 0 \leq t < 18, \\
\frac{3}{4} & t \geq 18.
\end{cases} \\
\end{align}
It can be verified that for $t \geq 18, F_1(t) + F_2(t) + F_3(t) = P[T \leq t] = 1$, therefore, this interpretation, i.e.,
\begin{align}
f(t, j) = \frac{dP[T \leq t, J = j]}{dt}
\end{align}
indeed allows for a valid marginal distribution of $T$.  In the literature, $F_j(t)$ are sometimes referred to as "sub-distribution function".  The marginal distribution function of $T$ now can be obtained by adding $F_j(t)$:
\begin{align}
F(t) := P[T \leq t] =
\begin{cases}
0 & t < 0, \\
\frac{79}{10800}t^2 & 0 \leq t < 5, \\
\frac{1}{12} + \frac{43}{10800}t^2 & 5 \leq t < 10, \\
\frac{1}{4} + \frac{1}{432}t^2 & 10 \leq t < 18, \\
1  & t \geq 18.
\end{cases}
\end{align}
I will leave the remaining two calculations ($P[J = 3 | T > 10]$ and $E[T | J = 2]$) back to yourself, which are not hard to derive based on the above discussion.  You shall also try to recover the standard representation of $F(t)$ in terms of a mixture model, i.e., try to write $F(t)$ as
\begin{align}
F(t) = p_1 P[T \leq t | J = 1] + p_2 P[T \leq t | J = 2] + p_3 P[T \leq t | J = 3],
\end{align}
where $p_j = P[J = j], j = 1, 2, 3$.


text:
Q: Remove JS object reference Currently I'm solving https://www.hackerrank.com/challenges/the-trigram in JS. When I run the solution against the test case input - it "passes". But when submitting it - it gets Runtime error.
The main idea is I have a class (Trigram), where using the input.split(" ").forEach( ... ) (after normalising the input and stuff) I load all the possible trigrams, compare to a candid and if it occurs more times - save to a var outside the forEach.
In the loop, the objects are initialised within let scope (I'm not sure in the terminology).
After googling around, I've found out that the objects are being referenced for ever (despite let), so garbage collector does not get rid of them. That is why I get Runtime error.
How can I get rid of the unnecessary references?
// not the exact code
function processData(input) {
    var candid = new Trigram();

    input.split(" ").forEach(function(element, index, array) {
        let obj = new Trigram(array[index], array[index+1], array[index+2]); // I guess, by using array[n] I'm using some kind of ultimate referencing
        if (magic) {
            candid = obj; // with the test case's input it runs twice
        }
    });
}


text:
Q: How to simple assign vectors of different structs? So I have two different structs (a & b) with same variables and an overloaded = operator in struct b to convert a to b.
I want to be able to simple assign a vector of a to a vector b, but compiler gives me an error:
main.cpp|61|error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::vector<_Ty>' (or there is no acceptable conversion)|

I assumed that I already had the overloaded = operator and that it would simply iterate over vector a and use that = operator for each instance. How would I do this?
Here is the code:
#include <iostream>
#include <vector>
using namespace std;

struct a
{
    int x, y;
    a() {}
    a(int _x, int _y)
    {
        x = _x;
        y = _y;
    }
};

struct b
{
    int x, y;
    b(){}
    b(int _x, int _y)
    {
        x = _x;
        y = _y;
    }

    b& operator=(const a& _a)
    {
        x = _a.x;
        y = _a.y;
        return *this;
    }
};

int main()
{
    a a_test(1,2);

    std::vector<a> a_vec;
    std::vector<b> b_vec;

    for(int i = 0; i <10; i++)
    {
        a_vec.push_back(a_test);
    }

    /*
    for(int i = 0; i<a_vec.size(); i++)
    {
        b_vec.push_back(a_vec[i]);
    }
    */

    b_vec = a_vec;

    return 0;
}

A: Even though a and b look identical, the compiler sees them as different types, even if a is convertible to b (or vice versa). Hence, vector<a> and vector<b> are completely unrelated, so you cannot assign one to the other, and the whole assignment fails to compile.
You can use an algorithm like std::copy,
std::copy(a_vec.begin(), a_vec.end(), std::back_inserter(b_vec));

A: The problem is that your operator= only works on individual elements, not on whole vectors.
You need to define a constructor that converts an A into a B.
Then you can use std::vector::assign rather than std::vector::operator=.
#include <iostream>
#include <vector>
using namespace std;

struct A
{
    int x, y;
    A(): x(0), y(0) {}
    A(int x, int y): x(x), y(y) {}
};

struct B
{
    int x, y;
    B(): x(0), y(0) {}
    B(int x, int y): x(x), y(y) {}

    // need to construct B from A
    B(const A& a): x(a.x), y(a.y) {}

    B& operator=(const A& a)
    {
        x = a.x;
        y = a.y;
        return *this;
    }
};

int main()
{
    A a_test(1,2);

    std::vector<A> a_vec;
    std::vector<B> b_vec;

    for(int i = 0; i <10; i++)
    {
        a_vec.push_back(a_test);
    }

    // b_vec = a_vec; // not like this
    b_vec.assign(a_vec.begin(), a_vec.end()); // like this

    return 0;
}

NOTE: I changed some of your names because the C++ standard says we should not begin variable names with the underscore '_'.


text:
Q: VHDL ERROR: unexpected IDENTIFIER I'm trying to create this code for a circuit, but it tells me there's an error.
The code is:
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

entity seq is
    port( CLK : in std_logic;
          GEN : in std_logic;
          INI : in std_logic;
          B : in std_logic_vector(3 downto 0);
          Qo : out std_logic_vector(3 downto 0)
          );
end seq;

architecture behavior of seq is

    signal Qo_pre: std_logic_vector(3 downto 0);

    begin
        process (GEN, INI, CLK, B)
        begin
            if INI='1' then
               Qo <= B;
            elsif (INI='0' and GEN='1' and rising_edge(CLK)) then
               Qo(0)<= Qo_pre(1);
               Qo(1)<= Qo_pre(2);
               Qo(2)<= Qo_pre(3);
            end if;
        end process;

    Qo(3)<= not Qo_pre(3) when (INI='0' and GEN='1' and rising_edge(CLK) and (Qo_pre(3) xnor Qo_pre(0))='1')

end behavior;

The error that appears is:
Line 51. parse error, unexpected IDENTIFIER
help please :(

A: You are missing a semicolon, on the assignment before end behavior;.
When I paste the code in my tool, it is on line 31.