text:
Q: Gmail API with heroku and django project I am stuck with identyfing issue on application being deployed to Heroku. It is a python django project that using a Gmail API should send out emails to defined subscribers. Code is as below
views.py (where function is called)
def MailJournals(new_acts):
    mailAdresses = models.EmailSubscriber.objects.all().values_list('email')
    mail_list = [x[0] for x in mailAdresses]
    journal_date = datetime.strftime(datetime.now(), '%d/%m/%Y')

    message = MIMEText(render_to_string('newsScrapper/mail.html',{
    'journal_date': journal_date,
    'new_acts': new_acts,
}), 'html')

    message['to'] = ",".join(mail_list)
    message['from'] = EMAIL_HOST_USER
    message['subject'] = 'Official Journal as of ' + journal_date

    with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp:
        smtp.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD)
        smtp.send_message(message)

settings.py:
EMAIL_HOST_USER = env('EMAIL_USERNAME')
EMAIL_HOST_PASSWORD = env('EMAIL_PASSWORD')

The thing is it perfectly works on localhost so I do not believe this is a code issue. Here are some heroku logs I have extracted for the call of that function:

2021-11-30T21:09:30.657994+00:00 heroku[router]: at=info method=GET path="/home/load/" host=legisync.herokuapp.com request_id=6c5c138d-05a4-488e-8bcd-c0bdc03da7fa fwd="83.23.240.85" dyno=web.1 connect=0ms service=464ms status=302 bytes=259 protocol=https

Unfortunately I have no idea how to correctly identify underlying root cause why it does not work from heroku...
Any ideas, or if sth else is needed from my side to share pls let me know.


text:
Q: Remove Meta Privilege for MSE (only) What I am asking here is to please remove the privilege to participate in Meta for MSE.
This privilege is literally useless. You can't really have a meta site for a meta site. There's no Meta.Meta.SE here or any other SE site out there: Meta.SE covers for every site in SE, including itself.
When users find out that you don't really get anything new, it's kinda sad for those people. There is no use for it except just to be there and fill up the space between the first and third privilege.
Privileges should be shown only if you earn something new, and this privilege to participate in the meta isn't new because it's where you report problems in all of SE, including Meta.SE.
So please remove the privilege to participate in meta just for Meta.SE.
This is not a dupe as this is a feature-request to remove it, not support on why it is there.

A: All privileges exist here on Meta because Meta serves as the global hub for all the privilege pages across the network. This is where the staff can edit the master pages and the changes eventually get pushed out across the network.
Side Note: Regular users could suggest edits to these pages at one point too, but that ability has since been removed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: WebView load url not working I have a Swing application with a JavaFX WebView embedded in it. I can load an initial web page using the WebView's WebEngine. However, subsequent calls to WebEngine.load are not working for some reason. Here's the debugging code I've added to the WebEngine:
private static WebView initFX(JFXPanel fxPanel) {
    StackPane root = new StackPane();
    Scene scene = new Scene(root, Color.ALICEBLUE);

    final WebView webView = new WebView();
    final WebEngine webEngine = webView.getEngine();
    root.getChildren().add(webView);

    webEngine.load("http://www.google.com");

    webEngine.setOnAlert(new EventHandler<WebEvent<String>>() {
        @Override
        public void handle(WebEvent<String> arg0) {
            System.out.println("alert: " + arg0);
        }
    });

    webEngine.getLoadWorker().progressProperty().addListener(new ChangeListener<Number>() {
        @Override
        public void changed(ObservableValue<? extends Number> arg0, Number arg1, Number arg2) {
            System.out.println("Process changed: " + arg0 + ", arg1: " + arg1 + ", arg2: " + arg2);
        }
    });

    webEngine.getLoadWorker().messageProperty().addListener(new ChangeListener<String>() {
        @Override
        public void changed(ObservableValue<? extends String> arg0, String arg1, String arg2) {
            System.out.println("message changed: " + arg0 + ", arg1: " + arg1 + ", arg2: " + arg2);
        }
    });

    webEngine.getLoadWorker().exceptionProperty().addListener(new ChangeListener<Throwable>() {
        @Override
        public void changed(ObservableValue<? extends Throwable> arg0, Throwable arg1, Throwable arg2) {
            throw Throwables.throwUncheckedException(arg2);
        }
    });

    webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
        @Override
        public void changed(ObservableValue<? extends Worker.State> arg0, Worker.State arg1, Worker.State arg2) {
            System.out.println("old state: " + arg1 + ", new state: " + arg2 + ", arg0: " + arg0);
        }
    });

    fxPanel.setScene(scene);
    return webView;
}

And then we have the code that tries to change the web page:
// Drag and drop event comes in on the AWT thread.
// Switch to the FX thread and run the load there
public void dropObjects(Iterable<Locator> objects) {
    try {
        browserControllerLatch.await();
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                webView.getEngine().load("http://www.arstechnica.com");
            }
        });
    } catch (InterruptedException e) {
        throw Throwables.throwUncheckedException(e);
    }
}

This produces the following output. I first load google, and then try to load the nytimes.com.
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@7f311653, name: progress, value: 0.30000000000000004], arg1: 0.0, arg2: 0.30000000000000004
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@7f311653, name: progress, value: 0.3750537109375], arg1: 0.30000000000000004, arg2: 0.3750537109375
message changed: ReadOnlyStringProperty [bean: javafx.scene.web.WebEngine$LoadWorker@2514c48a, name: message, value: Loading http://ssl.gstatic.com/gb/images/b_8d5afc09.png], arg1: , arg2: Loading http://ssl.gstatic.com/gb/images/b_8d5afc09.png
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@2514c48a, name: progress, value: 0.0], arg1: -1.0, arg2: 0.0
old state: READY, new state: SCHEDULED, arg0: ReadOnlyObjectProperty [bean: javafx.scene.web.WebEngine$LoadWorker@2514c48a, name: state, value: SCHEDULED]
old state: SCHEDULED, new state: RUNNING, arg0: ReadOnlyObjectProperty [bean: javafx.scene.web.WebEngine$LoadWorker@2514c48a, name: state, value: RUNNING]
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@2514c48a, name: progress, value: 0.1361267397098016], arg1: 0.0, arg2: 0.1361267397098016
message changed: ReadOnlyStringProperty [bean: javafx.scene.web.WebEngine$LoadWorker@7f311653, name: message, value: Loading complete], arg1: Loading http://www.google.com/, arg2: Loading complete
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@7f311653, name: progress, value: 1.0], arg1: 0.3750537109375, arg2: 1.0
old state: RUNNING, new state: SUCCEEDED, arg0: ReadOnlyObjectProperty [bean: javafx.scene.web.WebEngine$LoadWorker@7f311653, name: state, value: SUCCEEDED]
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@2514c48a, name: progress, value: 0.2439676525013781], arg1: 0.1361267397098016, arg2: 0.2439676525013781
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@2514c48a, name: progress, value: 0.3674793663516144], arg1: 0.2439676525013781, arg2: 0.3674793663516144
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@2514c48a, name: progress, value: 0.49099108020185067], arg1: 0.3674793663516144, arg2: 0.49099108020185067
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@2514c48a, name: progress, value: 0.5579187727289953], arg1: 0.49099108020185067, arg2: 0.5579187727289953
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@2514c48a, name: progress, value: 0.6248464652561398], arg1: 0.5579187727289953, arg2: 0.6248464652561398
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@2514c48a, name: progress, value: 0.6917741577832844], arg1: 0.6248464652561398, arg2: 0.6917741577832844
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@2514c48a, name: progress, value: 0.7067348499897916], arg1: 0.6917741577832844, arg2: 0.7067348499897916
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@2514c48a, name: progress, value: 0.8196757488843449], arg1: 0.7067348499897916, arg2: 0.8196757488843449
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@2514c48a, name: progress, value: 0.8548236404421787], arg1: 0.8196757488843449, arg2: 0.8548236404421787
message changed: ReadOnlyStringProperty [bean: javafx.scene.web.WebEngine$LoadWorker@2514c48a, name: message, value: Loading complete], arg1: Loading http://ssl.gstatic.com/gb/images/b_8d5afc09.png, arg2: Loading complete
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@2514c48a, name: progress, value: 1.0], arg1: 0.8548236404421787, arg2: 1.0
old state: RUNNING, new state: SUCCEEDED, arg0: ReadOnlyObjectProperty [bean: javafx.scene.web.WebEngine$LoadWorker@2514c48a, name: state, value: SUCCEEDED]

message changed: ReadOnlyStringProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: message, value: Loading stopped], arg1: Loading http://www.google.com/, arg2: Loading stopped
old state: RUNNING, new state: CANCELLED, arg0: ReadOnlyObjectProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: state, value: CANCELLED]
message changed: ReadOnlyStringProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: message, value: ], arg1: Loading stopped, arg2:
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: -1.0], arg1: 0.0, arg2: -1.0
old state: CANCELLED, new state: READY, arg0: ReadOnlyObjectProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: state, value: READY]
message changed: ReadOnlyStringProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: message, value: Loading http://www.nytimes.com/], arg1: , arg2: Loading http://www.nytimes.com/
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.0], arg1: -1.0, arg2: 0.0
old state: READY, new state: SCHEDULED, arg0: ReadOnlyObjectProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: state, value: SCHEDULED]
old state: SCHEDULED, new state: RUNNING, arg0: ReadOnlyObjectProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: state, value: RUNNING]
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.30000000000000004], arg1: 0.0, arg2: 0.30000000000000004
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.37692307692307697], arg1: 0.30000000000000004, arg2: 0.37692307692307697
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.4153846153846154], arg1: 0.37692307692307697, arg2: 0.4153846153846154
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.4371344828559657], arg1: 0.4153846153846154, arg2: 0.4371344828559657
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.46145061663389897], arg1: 0.4371344828559657, arg2: 0.46145061663389897
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.4889858904668283], arg1: 0.46145061663389897, arg2: 0.4889858904668283
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.4996095231732179], arg1: 0.4889858904668283, arg2: 0.4996095231732179
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.49962536129670365], arg1: 0.4996095231732179, arg2: 0.49962536129670365
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.5333407915930204], arg1: 0.49962536129670365, arg2: 0.5333407915930204
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.5626822750946262], arg1: 0.5333407915930204, arg2: 0.5626822750946262
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.5941663733048309], arg1: 0.5626822750946262, arg2: 0.5941663733048309
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.6221525081979236], arg1: 0.5941663733048309, arg2: 0.6221525081979236
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.6427489898360779], arg1: 0.6221525081979236, arg2: 0.6427489898360779
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.6511656916228664], arg1: 0.6427489898360779, arg2: 0.6511656916228664
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.6781609002406684], arg1: 0.6511656916228664, arg2: 0.6781609002406684
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.7014367363219931], arg1: 0.6781609002406684, arg2: 0.7014367363219931
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.7259500858917705], arg1: 0.7014367363219931, arg2: 0.7259500858917705
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.7502698308413603], arg1: 0.7259500858917705, arg2: 0.7502698308413603
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.7746271668215516], arg1: 0.7502698308413603, arg2: 0.7746271668215516
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.7753621953130199], arg1: 0.7746271668215516, arg2: 0.7753621953130199
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.7971212698771013], arg1: 0.7753621953130199, arg2: 0.7971212698771013
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.7978113746702923], arg1: 0.7971212698771013, arg2: 0.7978113746702923
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.8246883429436381], arg1: 0.8045146825367253, arg2: 0.8246883429436381
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.8506063568503134], arg1: 0.8246883429436381, arg2: 0.8506063568503134
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.8658103758125865], arg1: 0.8506063568503134, arg2: 0.8658103758125865
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.8897690876754529], arg1: 0.8658103758125865, arg2: 0.8897690876754529
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.8986044176113637], arg1: 0.8897690876754529, arg2: 0.8986044176113637
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.8994287053144517], arg1: 0.8986044176113637, arg2: 0.8994287053144517
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.8994895637143085], arg1: 0.8994287053144517, arg2: 0.8994895637143085
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.8996659228140144], arg1: 0.8994895637143085, arg2: 0.8996659228140144
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.899756240085032], arg1: 0.8996659228140144, arg2: 0.899756240085032
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.8999302539945363], arg1: 0.899756240085032, arg2: 0.8999302539945363
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.8999779051067591], arg1: 0.8999302539945363, arg2: 0.8999779051067591
message changed: ReadOnlyStringProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: message, value: Loading complete], arg1: Loading http://www.nytimes.com/, arg2: Loading complete
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 1.0], arg1: 0.8999779051067591, arg2: 1.0
old state: RUNNING, new state: SUCCEEDED, arg0: ReadOnlyObjectProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: state, value: SUCCEEDED].scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.8045146825367253], arg1: 0.7978113746702923, arg2: 0.8045146825367253
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.8246883429436381], arg1: 0.8045146825367253, arg2: 0.8246883429436381
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.8506063568503134], arg1: 0.8246883429436381, arg2: 0.8506063568503134
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.8658103758125865], arg1: 0.8506063568503134, arg2: 0.8658103758125865
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.8897690876754529], arg1: 0.8658103758125865, arg2: 0.8897690876754529
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.8986044176113637], arg1: 0.8897690876754529, arg2: 0.8986044176113637
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.8994287053144517], arg1: 0.8986044176113637, arg2: 0.8994287053144517
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.8994895637143085], arg1: 0.8994287053144517, arg2: 0.8994895637143085
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.8996659228140144], arg1: 0.8994895637143085, arg2: 0.8996659228140144
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.899756240085032], arg1: 0.8996659228140144, arg2: 0.899756240085032
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.8999302539945363], arg1: 0.899756240085032, arg2: 0.8999302539945363
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 0.8999779051067591], arg1: 0.8999302539945363, arg2: 0.8999779051067591
message changed: ReadOnlyStringProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: message, value: Loading complete], arg1: Loading http://www.nytimes.com/, arg2: Loading complete
Process changed: ReadOnlyDoubleProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: progress, value: 1.0], arg1: 0.8999779051067591, arg2: 1.0
old state: RUNNING, new state: SUCCEEDED, arg0: ReadOnlyObjectProperty [bean: javafx.scene.web.WebEngine$LoadWorker@4d8ed331, name: state, value: SUCCEEDED]

From the output, it seems like the WebView has loaded nytimes.com. However, the WebView never shows the update.
Does anyone have ideas about what might be wrong, or suggestions for how I can get more information about what's going on within the WebView?
I see the same behavior in Java 7 and 8.
Edit: If anyone has requests for additional info or debugging output, I'm happy to provide that.
Edit: This was caused by a mistake in other code not related to the JavaFX/Swing integration. Thank you all for your suggestions!

A: Here's a fully working example about how to do it. In the future please post a MCVE, especially since you got Swing involved and posted only some parts of JavaFX code.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class SwingBrowser extends JPanel {

    WebEngine webEngine;

    private static void initAndShowGUI() {

        JFrame frame = new JFrame();

        frame.add(new SwingBrowser());
        frame.setSize(1024, 768);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    public SwingBrowser() {

        JPanel toolbar = new JPanel();
        toolbar.setLayout(new FlowLayout());

        JButton button;

        button = new JButton("Google");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                loadPage("http://www.google.com");
            }
        });

        toolbar.add(button);

        button = new JButton("NY Times");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                loadPage("http://www.nytimes.com");
            }
        });

        toolbar.add(button);

        final JFXPanel fxPanel = new JFXPanel();

        setLayout(new BorderLayout());
        add(fxPanel, BorderLayout.CENTER);
        add(toolbar, BorderLayout.NORTH);

        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                initFX(fxPanel);
            }
        });
    }

    private void loadPage(String url) {

        Platform.runLater(new Runnable() {
            @Override
            public void run() {

                webEngine.load(url);

            }
        });

    }

    private void initFX(JFXPanel fxPanel) {
        Scene scene = createScene();
        fxPanel.setScene(scene);
    }

    private Scene createScene() {

        WebView webView = new WebView();

        webEngine = webView.getEngine();

        webEngine.getLoadWorker().progressProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> arg0, Number arg1, Number arg2) {
                System.out.println("Process changed: " + arg0 + ", arg1: " + arg1 + ", arg2: " + arg2);
            }
        });

        webEngine.getLoadWorker().messageProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> arg0, String arg1, String arg2) {
                System.out.println("message changed: " + arg0 + ", arg1: " + arg1 + ", arg2: " + arg2);
            }
        });

        webEngine.getLoadWorker().exceptionProperty().addListener(new ChangeListener<Throwable>() {
            @Override
            public void changed(ObservableValue<? extends Throwable> arg0, Throwable arg1, Throwable arg2) {
                System.out.println(arg0);
                System.out.println(arg1);
                System.out.println(arg2);
            }
        });

        webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
            @Override
            public void changed(ObservableValue<? extends Worker.State> arg0, Worker.State arg1, Worker.State arg2) {
                System.out.println("old state: " + arg1 + ", new state: " + arg2 + ", arg0: " + arg0);
            }
        });

        webEngine.load("http://www.google.com");

        BorderPane bp = new BorderPane();

        bp.setCenter(webView);

        Scene scene = new Scene(bp);

        return (scene);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                initAndShowGUI();
            }
        });
    }
}


text:
Q: will_paginate helper undefined in sinatra with mongoid I am using sinatra 1.4.3 and mongoid 3.1.4. I tried adding will_paginate gem from master branch for mongoid support so I added this to my gemfile:
gem 'will_paginate', :git => 'git://github.com/mislav/will_paginate.git',
                     :branch => 'master'

In environment.rb I added:
require 'will_paginate'
require 'will_paginate/mongoid'

And pagination method started working. I have still problem with will_paginate helper. In my views I get errors like:
NoMethodError: undefined method `will_paginate' for #<Class:0x006ff5df8578b0>

Am I missing something for helper to work under sinatra?

A: I don't know if it's best solution but adding
include WillPaginate::Sinatra::Helpers

in my controller solved my problems.


text:
Q: Code style defining multiple constants in PHP Is there any significant difference in how I define multiple constants in PHP class between:
this:
<?php
abstract class Some_Class
{
    const CONSTANT_ONE   = 101;
    const CONSTANT_TWO   = 102;
    const CONSTANT_THREE = 103;
}

and probably closer to JS style of defining:
<?php
abstract class Some_Class
{
    const CONSTANT_ONE   = 101,
          CONSTANT_TWO   = 102,
          CONSTANT_THREE = 103
    ;
}

A: Regarding syntax there is no difference.
Even the PHP-FIG Standards concerning constants allows the use of the second form documentation-wise (they call it compound statements).
Personally I prefer the first form :)
abstract class Some_Class {
    /**
     * @var int CONSTANT_ONE This constant is magical
     */
    const CONSTANT_ONE   = 101;

    /**
     * @var float CONSTANT_TWO This is Pi!
     */
    const CONSTANT_TWO   = 3.14;

    /**
     * @var string CONSTANT_THREE The magical door number
     */
    const CONSTANT_THREE = "103a";
}


text:
Q: django.urls.exceptions.NoReverseMatch: Reverse for 'change_view' with keyword arguments i am getting error

django.urls.exceptions.NoReverseMatch: Reverse for 'change_view' with keyword arguments '{'view_type': 'sla', 'curr_url': '/home/'}' not found. 1 pattern(s) tried: ['change_view\/(?P[^/]+)\/$']

Using django 2.1.7 and python 3.6 version
i have tried to add both the arguments as dynamic fields in urls.py
home.html

    View

SLA

Priority

urls.py
urlpatterns = [
    path('change_view/<str:view_type>/', views.change_view , name='change_view'),
]

view.py
def change_view(request,view_type=None):
    request.session['view'] = view_type
    request_data = json.loads(request.body)
    curr_url = request_data['curr_url']
    return redirect(curr_url)

I want the function change_view to set the request.session['view'] to user selected input and stay on the same url.

A: You are getting error because you are trying to find url with 2 arguments (view_type and curr_url), but you have only with 1 attribute (view_type).
Consider this solution - you will not provide curr_url with your request and send user back using HTTP_REFERER request header.

    View

SLA

Priority

views.py:
def change_view(request,view_type):
    request.session['view'] = view_type
    return redirect(request.META.get('HTTP_REFERER', '/'))


text:
Q: Object Expected - IE7 and 8 When opening our client front end in IE, I get the error "Object Expected" and it points to the following when I debug. I've googled, but nothing straightforward yet, at least not specifics.
$(document).ready(function () {
    $("#login_form").bind("submit", function () {
        processLogin();
        return false;
    })

    if ('<?php echo $_GET['email ']?>' != '' && '<?php echo $_GET['password ']?>' != '') {
        $('#login_form').submit();
    }
});

I know there is php in the js, so I attempted to put in a
document.write(<?php echo $_GET['email']?>)

in place of just the straight php, so that its differentiated. Though then it leads to another error based off this:
$("#description").toggle();

This is proof that IE is a pain. This works in Chrome, Safari and FF....
Ideas?

A: This line could be a problem (don´t know if it´s a copy-past problem...):
 if ('<?php echo $_GET['email ']?>' != '' && '<?php echo $_GET['password ']?>' != '')

It should be:
 if ('<?php echo $_GET['email']?>' != '' && '<?php echo $_GET['password']?>' != '')

The spaces after email and password will generate a warning (if they're turned on) that will lead to an auto-submit with php warnings as values.

A: I use this code to debug Javascript in IE. If the web page throws an error, move this code farther up in your HTML. This will help you track down the specific Javascript code that is causing the problem.
If IE is still working even through it is throwing an error, this code can be useful to prevent people from seeing the error until you have a chance to fix it.
<script type="text/javascript">
function noError(){return true;}
window.onerror = noError;
 </script>

A: Check your quotes.
if ('<?php echo $_GET['email ']?>' != '' && '<?php echo $_GET['password ']?>' != '') {

Should be:
if ('<?php echo $_GET["email"]?>' != '' && '<?php echo $_GET["password"]?>' != '') {

Note the doublequotes around email.


text:
Q: Outlook calendar event view from inbox
Hello,
I have a question regarding the view of event in outlook (2016) in the email area (inbox or sent items).
As you can see in the attached picture, the "when" part is showing the date, but not showing the week day.
How can i fix it to show the day as well, and not only the date?
Thanks.

A: Ok. found it.
it is the windows setting for date and time.
So in windows setting need to select the option of dddd dd/mm/yyyy for long date to fix this issue.


text:
Q: 'closeapp' was not declared in this scope Hello i change the usbdriveby project.
It is just to just the keyboard for fun
The error message app :'closeapp' was not declared in this scope.
Here is the code :
#if defined(CORE_TEENSY)
#define LED_PIN 11
#else
#define LED_PIN 13
#endif
void setup() {
delay(800);

  openapp("Terminal");
  typeln("screen -S SYSTEMUpdater");
  typeln("say dont use unknown usb sticks because its not safe.");
  closeapp;
}
void openapp(String app)
{
  cmd(KEY_SPACE);
  typeln(app);
}
void typeln(String chars)
{
  Keyboard.print(chars);
  delay(ds);
  Keyboard.println("");
  delay(ds * 4);
}
void closeapp
{
  cmd(KEY_Q);
}
void k(int key)
{
  Keyboard.set_key1(key);
  Keyboard.send_now();
  delay(ds/2);

  Keyboard.set_key1(0);
  Keyboard.send_now();
  delay(ds/2);
}

void mod(int mod, int key)
{
  Keyboard.set_modifier(mod);
  Keyboard.send_now();
  Keyboard.set_key1(key);
  Keyboard.send_now();
  delay(ds);

  Keyboard.set_modifier(0);
  Keyboard.set_key1(0);
  Keyboard.send_now();
  delay(ds);
}

void ctrl(int key)
{
  mod(MODIFIERKEY_CTRL, key);
}

void cmd(int key)
{
  mod(MODIFIERKEY_GUI, key);
}

void shift(int key)
{
  mod(MODIFIERKEY_SHIFT, key);
}

void loop()
{
  digitalWrite(LED_PIN, HIGH);
  delay(ds/2);
  digitalWrite(LED_PIN, LOW);
  delay(ds/2);
}

I searched for the same error but I am pretty sure that  I made an error in the writing.

A: Function closeapp is not syntactically valid in C language.
It should be something like:
void closeapp()
{
  cmd(KEY_Q);
}

Moreover function call should be something like:
closeapp();

to be syntactically valid.
The last point is, that you shouldn't call function before its implementation. It means either you will provide prototype or put its definition before it's really called.
EDIT FYI: Statement closeapp; is syntactically valid, but it is empty instruction just like 42;. Literally it is the address of closeapp function, so basically just a number.


text:
Q: struggling with Displaying Timer Hi all I found a useful bit of JS here:
http://jsfiddle.net/4tj6r/2/
and I am trying to run this as follows but, for some reason I am receiving no output on the webpage - I am a complete newbie so if this is simple many apologies but if there is anyone kind enough out there please point me in the right direction - the code is as follows:

many thanks in advance

A: All you miss is to call the jQuery library


text:
Q: Angular2, Browser back button displays blank screen I am new to Angular2. In my app, please find below routing configuration.
    export const routes: Routes = [
  {
    path: '',
    component: LoginHomepageComponent
  },
  {
    path: 'login',
    component: LoginHomepageComponent
  },
  {
    path: 'contact',
    component: ContactComponent,
    canActivate: [AuthGuard]
  },
  {
    path: 'default',
    component: DefaultNavigationBarComponent
  },
  {
    path: 'mainContent',
    component: MainContentComponent,
    children: [
      { path: '', component: SearchComponent, canActivate: [AuthGuard] },
      { path: 'changepassword', component: ChangePasswordComponent, canActivate: [AuthGuard] },
      { path: 'searchResults', component: SearchResultsComponent, canActivate: [AuthGuard] },
      { path: 'addUser', component: AddUserComponent, canActivate: [AuthGuard], canDeactivate: [UnsavedChangesGuard] }
    ]
  },
  {
    path: 'not-found',
    component: ErrorPageComponent,
    data: {
      message: 'Page not found!'
    }
  },
  {
    path: 'declarationofuse',
    component: DeclarationComponent,
    canActivate: [AuthGuard],
  },
  {
    path: '**',
    redirectTo: '/not-found'
  }
];

export const AppRouting = RouterModule.forRoot(routes, { enableTracing: true });

in app.module.ts
@NgModule({
  declarations: [
  ],
  imports: [
    AppRouting,
  ],
  exports: [RouterModule],
  providers: [
    UnsavedChangesGuard
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
export function cookieServiceFactory() { return new CookieService(); }

When I logged in into application, it works perfectly and each and every page is getting loaded successfully.
Issue occurres while user follow below steps

*

*Login to Application, automatically loads /declarationofuse uri

*Now user goes to google.com, and after that user press the back button

Browser shows blank page only, however uri in url bar shows /declarationofuse url. There are no exception thrown in console tab as well.


text:
Q: Randomly selecting a pushed value with an input from an array with a button in JS i have the following code:
    <input type="text" id="wisselspelers" onkeypress="return (event.charCode == 32|| event.charCode > 64 &&
    event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)">
    <button id="opslaanBtn">Wisselspeler toevoegen</button>

This code allows someone to enter a value into the input and add it to the array. I'd like to create another button, which allows a user to randomly select one of the values he added to the (empty) array.
I've tried the following code, but this code shows everything the user added and doesn't randomly select one:
  <button id="gekozenBtn">Kies een random wisselspeler</button>

A: Putting all your code in the same script tag works:

    <input type="text" id="wisselspelers" onkeypress="return (event.charCode == 32|| event.charCode > 64 &&
    event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)">
    <button id="opslaanBtn">Wisselspeler toevoegen</button>

  <button id="gekozenBtn">Kies een random wisselspeler</button>

(I've placed the random selection inside the gekozen function so you select the random value from the most up to date spelers, maybe the original problem was that it was too early to choose a value)


text:
Q: Not able to Install and run test chaincode on AWS I am following this tutorial Link. I am getting this error.
Error Error: could not assemble transaction, err proposal response was not successful, error code 500, msg instantiation policy violation: signature set did not satisfy policy
How can I fix the issue ?

A: I encountered the same issue
I deleted the admin cert and enrolled the fabric admin again, so that the old cert which was used to create the channel "mainchannel" was lost so that I cannot upgrade the channel chain code anymore.
Every time I instantiated or upgraded the chaincode, I received the error: err proposal response was not successful, error code 500, msg instantiation policy violation: signature set did not satisfy policy
Finally, I have to create new channel


text:
Q: Javascript Regex expression for matching words with digits ignoring 4 digit numbers I have a string that is just words with a single whitespace in-between. Assuming no special characters I would like to match all words containing digits while ignoring 4 digit numbers.
I.E.
hello12345 12345hello 123456789 12 red hello 1234 5678
Would Match:
hello12345 12345hello 123456789 12
The ultimate goal would be replacing hello12345 12345hello 123456789 12 with an empty string resulting in:
red hello 1234 5678
The following \w*\d\w* matches words with digits
and \b\d{4}\b matches all 4 digit numbers.
However, I am unsure of how to combine them.

A: Match and capture what you need and just match what you do not need (see The Best Regex Trick Ever):

var re = /\b\d{4}\b|(\w*\d\w*)/g;
var str = "hello12345 12345hello 123456789 12 red hello 1234 5678";
var m, res = [];
while (m = re.exec(str)) {
    if (m[1]) res.push(m[1]);
}
console.log(res);

The \b\d{4}\b alternative is only matched, but the second one, (\w*\d\w*), is also captured with the help of the capturing group, (...). This value is kept in Group 1, accessed via m[1].

A: This regex
/((\b(\d{1,3}|\d{5,})\b)|([a-z]+\d\w*|\w*\d[a-z]+))\s*/gi

matches:
// Digit-only words with less than or more than 4 digits
\b(\d{1,3}|\d{5,})\b

// Words that contain at least a number and a letter
[a-z]+\d\w*|\w*\d[a-z]+

incl. whitespace between them.

var string = "hello12345 12345hello 123456789 12 red hello 1234 5678";
var regex = /((\b(\d{1,3}|\d{5,})\b)|([a-z]+\d\w*|\w*\d[a-z]+))\s*/gi
console.log(string.replace(regex, ""));

There might be a simpler one. That's just from the top of my head.


text:
Q: Can I lazy-bind @Named dependencies? Is it possible to register a handler with Guice that is called when a @Named dependency is not found?
I could then look up missing bindings in the application's configuration file at runtime; otherwise I'd need to pre-bind all properties as Strings.


text:
Q: Получение списка cpu и процессов привязанных к ним Имеется сервер. На сервере установлен Centos 7. В рамках интерфейса имеется только CLI. Под ОС работают несколько дополнительно установленных модулей. Для каждого модуля в его конфигурационном файле установлена привязка к определенному ядру CPU.
Имеется ли возможность как-то собрать список оставшихся под систему ядер CPU, не перебирая конфигурационные файлы дополнительно установленных модулей? Может быть можно что-то найти в /proc?

A: Например так:

lscpu

*

*посмотреть(если не известно) сколько CPU в системе (core)

ps -o pid,psr,comm -C thunderbird

*

*thunderbird к примеру ваша программа - покажет какие CPU заняты

ну а дальше посчитать

ps -o pid,psr,comm -C thunderbird  | wc -l

*

*количество занятых ядер и вычитаем из общего количества

При желании всё можно завернуть в одну команду или скрипт


text:
Q: Try-Catch unknown behaviour I'm currently learning after a book about how to convert xaml code into objects during runtime.
I have the following code:
try
{
    ctrl = XamlReader.Load(xaml) as UserControl;
}
catch (Exception exc)
{
    OnXamlResult(new XamlCruncherEventArgs(exc.Message)); return;
}

The code is not mine, I took it from the book.
The problem is that try-catch does not work properly, or at least as I know till now.
During debugging the program stops when it reaches the line :
ctrl = XamlReader.Load(xaml) as UserControl;

without catching the exception.
What am I doing wrong or how can I solve this problem?
"xaml" is a string. It is taken from a textbox and if the xaml is correctly typed by the user the program should convert the xaml code into object otherwise it should display the corresponding error.
About how the program reacts, i can say that debug stops(it returns me to visual studio pointing the error) and it is not behaving like going into a infinite cycle.

A: It's probably the debugger breaking as the exception occurs.  Stick a breakpoint inside the catch and F5 to continue, it should carry on and hit your breakpoint.
And by "breaking", I don't mean it fails, I mean it pauses execution of the app on the offending line of the exception, so it's a Good Thing in this instance.
If you are using Visual Studio, you can enable/disable this "break on exception" behaviour:

*

*Debug -> Exceptions... (Ctrl + Alt + E)

*Common Language Runtime Exceptions, check the boxes to the right as needed.

As for the exception itself, unless it's there specifically to show exceptions, it is likely having trouble loading the provided XAML string.


text:
Q: Debian squeeze dual booting with Win7 - How to turn on an ntfs partition by default I've setup squeeze on a separate partition on my existing win-7 system. However, I'm facing two issues:
[1] The ntfs drive isn't mounted automatically when the computer starts. I have to manually mount it by giving the root-password. I've added the below lines to /etc/fstab but its not working:
#Added by Prahlad
/dev/sda3   /media/SHARED   ntfs    user,auto    0    0

Is there anything wrong in this entry? user,auto option should auto-mount on startup right? I also verified /dev/sda3 is correct by running "fdisk -l".
[2] The grub boot-loader displays the secod OS as "Windows Vista (Loader)". I want to change this to "Windows-7" and also make it default. How to make that. Should I edit the /boot/grub/grub.cfg directly?
Thanks in Advance.

A: [1] - fstab
Only obvious thing I can see wrong is that you're using ntfs rather than ntfs-3g. The latter is a user-space filesystem (which has been around for many years and is VERY stable) which can read and write NTFS reliably. The ntfs filesystem driver is a kernel module in the Linux kernel that is much less mature and (AFAIK) does not provide write support, nor can it handle volumes that have a dirty journal (again, AFAIK).
When you have issues like this, the best way to debug it is to try and mount it manually. As root (or add sudo in front of it):
mount /media/SHARED
If you get an error post it here. If not..... hmm.
The other problem that may exist is that the device may not be stable. Sometimes the BIOS boot order and plugging in / unplugging devices (SATA disks, USB disks, etc) can cause the block devices to have different names. One boot it may be /dev/sda, the next boot it may be /dev/sdd. You can get the UUID of the specific partition and use that in /etc/fstab instead of the /dev/sda3 device node identifier. A fairly good write-up on how to determine UUIDs and use them in fstab is at the Ubuntu wiki, but note that some commands they advise you to run may not work with Debian. Instead, just follow the instructions under "Finding UUIDs" and manually plug the UUID into /etc/fstab by using the syntax UUID=BlahBlahIAmAUUID instead of /dev/sda3.
[2] - Grub entry name
/boot/grub/grub.cfg is for GRUB2. If the file exists, you can go ahead and edit it and replace the name appropriately. You can also see if a setting in /etc/default/ directory lets you customize the default name.
If /boot/grub/grub.cfg doesn't exist, then /boot/grub/menu.lst should -- that's the GRUB Legacy menu file. It's reasonably similar to GRUB2's, in the sense that changing the boot order priority is just a matter of copying and pasting the various sections in the document into the desired order, or changing the default command to reflect the zero-based index of the desired default boot menu item. And of course you can change the name to whatever you want.
If the package tools detect that you have modified a GRUB menu item, generally they won't overwrite your changes automatically, so you don't have to worry about that. But even in the event that your changes are overwritten by a package upgrade, the changes you want to make are only "cosmetic", so it's not a disaster...


text:
Q: How to use map instead of list for qabstractproxymodel? how can use a map property as stored data that inherited by qabstractproxymodel, and using as model in QML views?
Repeater{

model: cppMapModel;

delegate:delegateComponent

}

even used it in ListView.

A: Give this a try it should be similar to other data types.
#include <QAbstractProxyModel>

calss QAbstractProxyModel{

private:

QAbstractProxyModel cppMapModel;

std::map<std::QAbstractProxyModel, int> map;

};


text:
Q: Jquery and IE10 I have three input fields, input1, input2 and input3.
When the value of input1 changes, input2 is set accordingly:
$('input[name=input1]').change(function () {
        console.debug("input1");
    $('input[name=input2]').val($(this).val());
    $('input[name=input3]').prop("disabled", true);
});

$('input[name=input2]').change(function () {
    console.debug("input2");

    ...
});

It works, but not on IE10. It doens't print on the console "input1" and "input2" and it doesn't change the input2 value.
EDIT
The problem seems to be also in IE<10
It seems to work if I use on with keyup.
But what if the user uses the mouse to select a cached value?
mouseenter has a strange effect.

A: Why dont you use 'console.log' instead of 'console.debug' and check if that was a problem for IE to figure!

A: If you use the latest jQuery you could try to bind an event listener like so
$(document).on('change','#input1',changeFunction)

older version you might use
$('#input1').on('change',changeFunction)

and then use the changeFunction(event) to do whatever


text:
Q: Can we say that the radiator of our home is a black body? I would like to understand the concept of Black Body through this question : can we say that the radiator of our home is a black body ?

A: So as said in the comments, I'm adding something long I wrote some time ago to explain better what is black body radiation. I tried to translate it from Hebrew so I hope the English makes sense. If you have any more questions regarding how this is applicable to your radiator, you are more than welcome to comment.
How did the equilibrium problem with radiation give rise to quantum theory?

What is a thermodynamic equilibrium?
Let's say we finished cooking ourselves a gourmet meal (ability we acquired during the quarantine days) and left the hot pan on the counter after we finished. What will happen to it? After a while - it will cool down and reach room temperature. Why does this happen? Because the atoms that make up the pan are fast and constantly collide with the atoms of the air near the pan, which is slower, causing the air around to heat up and the pan atoms to cool. After long enough, the "extra" energy that was only in the pan atoms transferred almost entirely to the energy in the air atoms - the room warmed up a bit, and the pan cooled a bit - until they reached the same temperature.
Similarly, for an ice block placed on the table - in the collisions between the particles in the ice and the atoms of the air, more energy will pass from the air to the ice - meaning the ice will heat and the air will cool until it is at the same temperature.
In thermodynamics, everything that can happen, will happen (for example, energy transfer from the ice/pan to the air and viceversa). In thermal equilibrium, you just demand that nothing changes - which tells you that the net flux of certain quantities will be zero, meaning temperatures, pressures, etc.. will be equal (if possible).

Thermal equilibrium with radiation
Now imagine a closed, black room with no particles in it at all. If the room is not at absolute 0 degrees kelvin, at any given moment there are particles in the walls that move, accelerate and collide (with each other). The thing is, when particles collide and accelerate, they emit radiation and lose some of their energy. (This comes from classical EM theory). Meaning EM theory tells us that there is a mechanism of losing energy from a material to the EM field.
Similarly, if the room was at zero temperature and there was radiation in the room, it would be absorbed and it heats the atoms - so here too one can see that energy will stop flowing from the room to the radiation or the radiation to the room when the two systems are in equilibrium.
This is exactly the point - there is nothing "mystical" about black hot bodies radiating, this is known from the classical and quantum mechanical descriptions of how matter and light interact. The point in black body radiation is that demanding thermal equilibrium (no net energy flux between the material and the radiation field) can predict the spectrum in thermal equilibrium. That is black body radiation! The radiation must also be in equilibrium with the material so that there is no energy leakage from one to the other! (That is, on average, the amount of energy that the substance emits will be the same as the amount of energy the substance consumes).
In other words, no room at a temperature different from zero can be dark - the room is always lit by the walls! In equilibrium, this light is emitted from the walls and absorbed in such a way that the total light in the room is always unchanged (this is the equilibrium definition)
Note that if the room is transparent, and does not interact with radiation (it does not absorb), there is also no reason to emit. In general, the more matter a radiation absorbs at a certain frequency, the more it will emit. This can be generalized and explained in further details by Kirchhoff's law relating emissivity to absorption, and this is the basis to the answer I gave you in the comment - your radiator is a black body only in the frequencies it absorbs well. This is also why hot gasses, which absorb and emit in specific frequencies, don't give black body curves. Therefore, the maximum radiation that can emit from an equilibrium material is indeed from black bodies, and for this situation one can calculate from equilibrium principles how much energy each radiation frequency should be.
When analyzing the result, a problem emerged - the power per unit frequency was proportional to the square in frequency, which means that as the frequency increases there is more and more energy, and it goes on and on! It can't be that equilibrium has infinite energy in radiation, so obviously something was incomplete in the laws of physics of the time ... This mystery became known as the "ultraviolet catastrophe" (because ultraviolet is in the high frequency range).

Planck's solution
One bright day in the early 20th century, Max Planck thought of a rather strange idea, but tried to analyze what would happen if he took a strange assumption: that the absorption and emission of radiation cannot be done with any energy, but only in whole multiples of some size that increase with frequency. In other words, Planck "manually" put a condition on the the emission of radiation to "block the problem" at high frequencies: a wall particle cannot emit any radiation at too high a frequency if it does not have enough energy for it (as opposed to classical theory, which did not have this limit). Strangely, this assumption predicted exactly the amount of radiation that is from a black body: the amount of radiation emitted was finite, and each temperature has a frequency at which it has maximum energy! These understandings helped later understand how to measure the temperature of things only by the radiation they emit (like 'seeing' a star's temperature or just measuring someone's temperature without touch).
But the solution hinted at something strange for physicists: did the interaction between light and matter really come in discrete energy packets (discrete dose = quanta)? Is really the smallest amount of energy that can be emitted or increases with frequency? This interpretation seemed like a curiosity until a patent office clerk used it to solve another mystery a few years later (The photoelectric effect). This official was named Albert Einstein, and he won the Nobel Prize after solving the mystery 16 years after he proposed his solution. And all because something didn't work out in some radiation and got swallowed up by hot things. And then quantum theory was born.

A: No you can't. A blackbody is an object that absorbs all radiation incident upon it and is in thermal equilibrium.
Neither of these are true for a household radiator. Most often they are white and so clearly don't absorb visible radiation very well. There will also be temperature gradients between the water in the interior and the surface, and/or inhomogeneities that lead to the received radiation arising from material at slightly different temperatures.
So the question is really whether a blackbody works as an approximation? Clearly it doesn't at visible wavelengths, but the bulk of the radiation is emitted in the infrared, where the absorptivity will be much higher and the approximation might be justified. Typical ways of approaching this approximation are to multiply the intrinsic spectrum by a wavelength-dependent fudge factor that is the fraction of radiation absorbed at that wavelength, or to characterise the total radiative losses in terms of an "effective temperature", which is the temperature that a true blackbody with similar radiative losses would have.


text:
Q: How do i iterate through JSON array in javascript? I have a json data coming from rest in following format:
{
"status_code": 200,
"data": {
"units": -1,
"unit_reference_ts": null,
"tz_offset": -4,
"unit": "day",
"countries": [{"country": "IN", "clicks": 12}]},
"status_txt": "OK"
}

I want to access the countries part and need to generate data in format like
{"IN":12, ......}

I dont know how to iterate through javascript, JSON array? Please help i am confused between methods which is the best & easiest that will work throughout the JSON?
I tried this:
 $.each(response.countries, function(key, value) {
 console.log(value.country + ": " + value.clicks);});

but it is showing me type error e is undefined...

A: Make sure you parse your JSON first (var data = JSON.parse(json)), then use a simple loop:
var obj = {};
for (var i = 0, l = data.data.countries.length; i < l; i++) {
    var tmp = data.data.countries[i];
    obj[tmp.country] = tmp.clicks
}

console.log(obj); // { IN: 12, UK: 123 }

DEMO
Since (from your edit) you're using jQuery, you'll probably need to do this (note that jQuery automatically parses JSON data if you retrieve it using one of its AJAX methods):
var obj = {};
$.each(response.data.countries, function(key, value) {
    obj[value.country] = value.clicks;
});

If you want a string instead of an object, just JSON.stringify the obj:
var json = JSON.stringify(obj);

DEMO


text:
Q: Does there exist a duality between the following two quantum systems? Consider two systems:
A) $N$ number of independent spin $0$ bosons living on a circle.
B) A single spin $0$ boson moving on an $N$-torus.
How do we detect the difference between the two systems mathematically?
In both cases, the RHS of commutators $[X_a,P_b]$ is the same ``i.e. $i\hbar \delta_{ab}$"


text:
Q: Use Database in C# I recently write a simple program that use database.
I've created an DB1.MDF and get data from it.
When I try to do Select from its Table (i.e. Table1), it gets run time error!
How I should do that?!
One more question:
I've created Data Grid View and put data in that. Now, how I can for example use column[2] of it (e.g. column[2] in my dataGridView is LastName and I want to save all LastNames in one String).
Here is my Code:
private void button1_Click(object sender, EventArgs e)
{

     SqlConnection conn = new SqlConnection();

     conn.ConnectionString = @"Data Source=.\SQLEXPRESS;
           AttachDbFilename=|DataDirectory|\DB1.mdf;
           Integrated Security=True;User Instance=True";

     conn.Open();

     SqlCommand cmd = new SqlCommand();

     cmd.Connection = conn;

     cmd.CommandText = "SELECT ID, Name, LastName from Table1 WHERE Name == Joe ";

     SqlDataAdapter da = new SqlDataAdapter();

     da.SelectCommand = cmd;

     DataTable dt = new DataTable();
     da.Fill(dt);

     dataGridView1.DataSource = dt;
     conn.Close();
 }

 private void button2_Click(object sender, EventArgs e)
 {
   textBox1.Text = dataGridView1.Columns[0].ToString();
 }

A: The select query should be like this
cmd.CommandText = "SELECT ID, Name, LastName from Table1 WHERE Name = 'Joe'";

And for your second question, you could use something like this
private void button2_Click(object sender, EventArgs e)
{
     StringBuilder builder = new StringBuilder();
     dataGirdView1.Rows.Cast<DataGridViewRow>().ToList()
         .ForEach(r => builder.Append(r.Cells[2].Value));
     textBox1.Text = builder.ToString();
}

A: This query seems wrong.
SELECT ID, Name, LastName from Table1 WHERE Name == Joe

Can you try this?
cmd.CommandText = "SELECT ID, Name, LastName from Table1 WHERE Name = 'Joe'"

Also, please post the details of the error message.

A: Bala R has it right, the == operator does not exist in SQL, therefore if your testing for an equality you should use the single = operator. And if you're comparing strings (varchar or nvarchar in SQL) you should put them in single quotes i.e. 'Joe'.


text:
Q: file_get_contents synchronous or asynchronous Today I came across one situation.
I am using file_get_contents to get token from a file for a user.
$data=file_get_contents("http://example.com/aaa.php?user=tester&akey=abcdef1234");
$dec=json_decode($data,true);
$tokenid=$dec['message']['result']['tokenid'];

Using the token i will call another file to get details;
$data=file_get_contents("http://example.com/bbb.php?user=tester&token=".$tokenid);

the problem is sometimes i am  not getting tokenid,  after refreshing the page  i get it.
There is no problem in aaa.php its working fine.
I doubt whether php is not waiting for the response of the file_get_contents of token before going to the second file_get_contents(asynchronous);
I have tried with curl too but sometimes  I am  not getting tokenid. I haven't faced these kind of issues.

A: file_get_contents is synchronous. You can get FALSE sometimes because of different reasons like network fail, DNS fail etc.
Use curl instead: it's faster and more customizable. You can wait for good response recursive if you need 100% success.

A: Definitely not a question of synchronous vs. asynchronous.  But as is debugging is pretty impossible.  Try something like this.  The die statements are ugly but illustrates the validation you might want to incorporate...
$data = file_get_contents("http://example.com/aaa.php?user=tester&akey=abcdef1234");
if (empty($data)) die('Failed to fetch data');

$dec = json_decode($data, true);
if (is_null($dec) || $dec === false) die('Failed to decode data');

$tokenid = isset($dec['message']['result']['tokenid']) ? $dec['message']['result']['tokenid'] : null;
if (is_null($tokenid) die('Token ID is not set');

//...

$data=file_get_contents("http://example.com/bbb.php?user=tester&token=".$tokenid);

A guess might be your token sometimes contains 'special' characters that need to be escaped.

A: the best way to waiting for file_get_contents, i hop that help you.
if ($result = file_get_contents("http://exemple.com", false)) {
 echo $result; // for exemple
}


text:
Q: How can I print the length of this JSON Object? I'm trying to print the length of this JSON Object to the console but I keep receiving 'undefined'.
This is being JSON encoded in PHP and then returned via ajax to an anonymous function as 'msg'
{"1":{"item_id":"shirt_straight--small","quantity":5},"2":{"item_id":"shirt_straight--medium","quantity":"2"}}

Printing to console:
console.log(msg.length); //undefined
console.log(msg[1].item_id); //shirt_straight--small

I'm able to print the value of msg[1].item_id but I'm not able to get the length via msg.length
Thanks for your help.

A: Arrays have a length property.  Objects do not (by default).  I think the problem is on the php end ... You should be encoding an array and sending that back instead.  Arrays are zero-indexed, so that may be the problem.  Perhaps json_encode(array_values($msg)).
If your keys are correct after all, give Object.keys(msg).length a shot.

A: This can be a duplicate of Length of a JavaScript object
Look at the accepted answer.
BTW, just found googling "javascript object length" ;)
EDIT:
It's true that objects don't have a length property, and you can get the length with Object.keys(foobar).length, but it won't work in IE8 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)


text:
Q: Java jar install trouble I'm trying to use charva, and according to the instructions, I should just be able to point LD_LIBRARY_PATH to a shared library and put the jar on my classpath and then I should be able to use the library.
Yet while I have the jar on the classpath, the following code fails with "package charva does not exist":
import charva.awt;

class ...

when I attempt to compile it.
I'm probably messing this up because I have no experience with java packages: why am I getting a package does not exist message if the jar is on the classpath?
I'm pretty sure that the jar isn't broken as the library came with a test script and a demo which appeared to be working correctly.
Thanks.

A: You don't point LD_LIBRARY_PATH to a shared library. You point it to a directory containing one or more of them.
Assuming that you have a .so for the right architecture, you need LD_LIBRARY_PATH as well as -Djava.library.path (unless the Java code is especially tricky).
More to the point, your question concerns a compile-time error. This has to just be that you didn't tell javac about the jar with -cp.


text:
Q: Encrypting Authentication Cookies using Data Protection Keys Stored in Database for .Net Core and .Net Framework 4.x Websites Question:
How can I encrypt authentication cookies using data protection keys stored in a database rather than the file system or file share for Asp.Net Framework 4.x and Asp.Net Core 2 websites?
Context:
I have a .Net Framework 4.x website and a .Net Core 2.0 website.  I need to share authentication cookies between these two apps and encrypt the data using DataProtection keys.
In production, these applications are hosted on several web servers.  So, I also need to share the keys between servers, hence the database.
Currently, the data protections keys are manually sync'd across file system locations on each server.
I would like to have a common location for the data protection keys that each web server can use.
The obvious solution is a file share but this introduces a single-point of failure to the architecture.
I would rather use the common database backing these two apps.
I know the database itself is a SPoF, but it already is and always will be.
Using it for this purpose does not increase risk.
I know that I can create my own IXmlRepository implementation that gets and saves data protection keys to my database.
I have done this and it works well. During debug, I can see the application getting and setting data protection keys in my database.
I use this in StartUp.cs where DataProtectionRepository is my implementation to a database:
services.AddSingleton<IXmlRepository, DataProtectionRepository>();
var serviceProvider = services.BuildServiceProvider();
services.AddDataProtection().AddKeyManagementOptions(opt =>
            opt.XmlRepository =
                new DataProtectionRepository(serviceProvider.GetService<DataProtectionContext>()));

The problem is when I set up CookieAuthenticationOptions, the TicketDataFormat property requires an implementation of IDataProtector to construct.  IDataProtector is provided by DataProtectionProvider.CreateProtector, but to create a data protection provider a DirectoryInfo object indicating the location where the keys are to be stored is required.
var securityOptions =
services.BuildServiceProvider().GetService<IOptions<SecurityOptions>>();
var protectionProvider = DataProtectionProvider.Create(new DirectoryInfo(securityOptions.Value.KeyringLocation));
var dataProtector = protectionProvider.CreateProtector("CookieAuthenticationMiddleware", "Federation", "v2");
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                           {
                               <blah>
                               options.TicketDataFormat = new TicketDataFormat(dataProtector);
                               <blah>
                           });

I suppose I could create my own implementation of IDataProtectionProvider and IDataProtector, but this seems hairy and perilous since the IDataProtector handles the actual protection and un-protection of data payloads but does not expose any detail of how keys are retrieved or from where they are sourced.  Also, I don't really want to change any of the actual protect/unprotect functionality.  I merely want to retrieve the keys from my repository.
I have trouble believing I'm unique with this problem.  Am I completely down the wrong path?  Is there an alternate solution or should I just put in a file share and move on?
Thanks.


text:
Q: Normalizing from values [- 1, 1] to [0, 1] This function takes value from [-1, 1] and turns value to [0, 1](it's not an array)
function normalize(x){
 var y = 2 * x / 2;
 return y;
}

With x=0.5 it would return x=0.25, but when x is 0, it returns 0, I need value 0,5.

A: To normalize on an interval from [-1, 1], first add 1 and then divide by 2. You are multiplying by 2 and then dividing by 2, which yields the original number.
function normalize(x){
 var y = (x + 1) / 2;
 return y;
}


text:
Q: How do i setup OpenDNS family shield? I am using ubuntu 15.04 with a mobile broadband connection, i want to setup OpenDNS family shield on it.

A: manually add dns server to your connection as in make it your main DNS resolver.
click on the connection icon located at the top right hand corner.

*

*Then click on edit connections.

*Then select your connection then click edit.

Go to IPv4 Settings Tab
Switch method to "Automatic (DHCP) addresses only"

Enter in your DNS Server in the Additional DNS Servers Field: like so

then click save now you are set up with OpenDNS family shield.


text:
Q: How to have equation number for the below equation I am trying to put the equation number for the below expression. how to do it?
\documentclass[12pt,a4paper]{article}
\usepackage{amssymb}
\usepackage{amsmath}
\usepackage{mathtools}

\begin{document}

\[  \Phi_{1}= \left\{
\begin{array}{ll}
      a(x) & x\leq \frac{1}{3} \\
      b(x) & x> \frac{1}{3} \\
\end{array}
\right. \]

\end{document}

A: Like this:

For such equations is in amsmath defined environment cases. For its numbering you should insert in equation environment as stated @Henri Menke  in his comment:
\documentclass[12pt,a4paper]{article}
\usepackage{amssymb}
\usepackage{amsmath}
\usepackage{xcolor}  % <---

\begin{document}

\begin{equation}\color{blue!70!black} <---
\Phi_{1} =
\begin{cases}
      a(x) & x\leq \frac{1}{3} \\
      b(x) & x> \frac{1}{3} \\
\end{cases}
\end{equation}

\end{document}

Edit (1):
If you like to have only this equation in blue color, than after \begin{equation} add for example \color{blue!70!black}, as is added now in above MWE.
Edit (2):
However, if you like to have all math expressions colored, than two solutions are provided in answer of Stefan Kottwitz and in answer of David Carlisle. Considering them in above MWE, you will get:

and

respectively. Difference between them is color of equation numbers.


text:
Q: actuator/shutdown not killing Java process Recently I have upgraded spring boot version to 2.6.7 from 2.3.11 Release
I am using management.server.port as 8080 when call curl post https://localhost:8080/actuator/shutdown then my application stopped but still Java PID running why?

A: What port is the PID listening on?
Perhaps its a Java process that is not related to the Spring Boot application.
To view process id and ports assigned to it this command should do the trick if using Linux
lsof -i -P -n | grep LISTEN

Do you still see 8080 (LISTEN) ?


text:
Q: C# overload resolution with generics I come from a C++ background and I am relatively new to C#.
Currently, I am trying to write two print functions, the first of which accepts a generic array parameter (and prints the items of the array to the command line) and a second one which accepts a generic primitive parameter (and invokes its ToString() method). Here's my code:
using System;

namespace OverloadResolution
{
  class Program
  {
    static void Main(string[] args)
    {
      string[] foo = new string[] { "A", "B", "C" };
      Extensions.PrintMe(foo);
      Extensions.PrintMe("Hello world");
      Console.ReadLine();
    }
  }

  public static class Extensions
  {
    public static void PrintMe<T>(T[] elm)
    {
      Console.WriteLine("PrintMe<T>(T[] elm)");
      Console.WriteLine(string.Join("", elm));
    }

    public static void PrintMe<T>(T elm)
    {
      Console.WriteLine("PrintMe<T>(T elm)");
      Console.WriteLine(elm.ToString());
    }
  }
}

Everything works as expected and the correct overloads are chosen. However, if I change my code as follows:
using System;

namespace OverloadResolution
{
  class Program
  {
    static void Main(string[] args)
    {
      string[] foo = new string[] { "A", "B", "C" };
      Extensions.PrintMe2(foo); // <<< Note the PrintMe2 function
      Extensions.PrintMe2("Hello world"); // <<< Note the PrintMe2 function
      Console.ReadLine();
    }
  }

  public static class Extensions
  {
    public static void PrintMe2<T>(T elm)
    {
      PrintMe(elm);
    }

    public static void PrintMe<T>(T[] elm)
    {
      Console.WriteLine("PrintMe<T>(T[] elm)");
      Console.WriteLine(string.Join("", elm));
    }

    public static void PrintMe<T>(T elm)
    {
      Console.WriteLine("PrintMe<T>(T elm)");
      Console.WriteLine(elm.ToString());
    }
  }
}

the type information seems to get lost when calling the PrintMe2 function because, internally, the second PrintMe function is invoked in both cases. Are there any special rules which apply in this case? Or am I missing something? I use C#7.0 and .NET framework 4.7. I should note that I already learned that the use of C# generics is quite limited as compared to C++ templates...

A: When PrintMe2 is being compiled, we have to perform overload resolution to determine which PrintMe method is being called, and we have to emit the correct method token into PrintMe2s IL to identify that method.
At the point at which PrintMe2 is being compiled, we do not know the nature of its T type parameter. It could be anything. The only version of PrintMe that is similarly unrestricted is PrintMe<T>(T elm). Therefore, we emit the method token for that specific method into our IL.
Generics are different to templates, most notably because they are compiled separately from any code that may make use of them. We have to make decisions at their compile time, and those decisions have to be valid for all possible type parameters (subject to any type constraints applied to the class/method in which the type parameter(s) are declared)
If you want a method in which overload resolution only takes place based on the runtime type of the passed in parameter, you can use dynamic, but that's quite ugly and brings in lots of overheads. It may also lead to runtime errors in no specific overload is most specific for some use cases.

A: You can cast the argument to pseudo-type dynamic to force C# compiler to select the most specific overload based on the actual value of the argument, like this:
PrintMe((dynamic)elm);

However, if you inspect the generated IL code, this comes with a runtime penalty, so you should use the dynamic keyword sparingly.


text:
Q: MPR121 sensor sensitivity I have connected and tested the two break-board versions of MPR121 Proximity Capacitive Touch Sensor Controller with various mcu's (ESP32, RPI pico, ARDUINO)
The one on a keypad version (Sparkfun compatible) and the one that you can connect custom pads to it. I tried them both with cpp and micropython. I connected them via I2C and everything is functioning on all occasions, with the IRQ option as well.
However I have trouble increasing sensitivity and by that I mean that if I place even a thin piece of paper or other layer before the touch pads, I can't get a touch signal.
Looking into the MPR121 micropython example Library I modified the following:
MicroPython MPR121 capacitive touch keypad and breakout board driver
https://github.com/mcauser/micropython-mpr121
Inside this library I see the following parameters for tuning that I tried:
# Set touch and release trip thresholds
#self.set_thresholds(15, 7)  default....
self.set_thresholds(15, 7)

# Set config registers
# Debounce Touch, DT=0 (increase up to 7 to reduce noise)
# Debounce Release, DR=0 (increase up to 7 to reduce noise) .....default was 0x00
self._register8(MPR121_DEBOUNCE, 0x00)

# First Filter Iterations, FFI=0 (6x samples taken)
# Charge Discharge Current, CDC=16 (16uA) .default was 0x10 5-30 less to more sensitive
self._register8(MPR121_CONFIG1, 0x30)

# Charge Discharge Time, CDT=1 (0.5us charge time)
# Second Filter Iterations, SFI=0 (4x samples taken)
# Electrode Sample Interval, ESI=0 (1ms period) .default was 0x20 5-30 less to more sen
self._register8(MPR121_CONFIG2, 0x20)

I tried various combinations but the effect is minimal if non-existent. My target or best case scenario is to be able to place a 3mm plexiglass on top of the breakout board or custom pads.


text:
Q: Can I delete files in nginx client_body_temp directory? On my nginx server, I can't login to my wordpress site. The error log mentions " No space left on device".

2014/09/26 02:02:05 [crit] 1197#0: *32 open() "/usr/local/nginx/client_body_temp/0030999742" failed (28: No space left on device)

There is space but I found that my inode usage was 100%
I have tracked down the ridiculous amount of files to /usr/local/nginx/client_body_temp where there are too many files to count.
So my question is: what is this directory for, and can I delete these files?

A:
what is this directory (/usr/local/nginx/client_body_temp/) for?

The directory was used to save buffered temporary file from client request body. Normally the temporary file inside the directory was used to buffer request body that larger than client_body_buffer_size. And normally the file was removed after nginx has finished process the request.
Other use of that directory is to debug client request body. When you set client_body_in_file_only on;, nginx will save the body to those directory. But, in this case nginx won't remove them. You can use client_body_in_file_only clean; for clean the temporal files or disable it with client_body_in_file_only off;

and can I delete these files?

Yes, you can safely remove those files.


text:
Q: SerializationException on 'CustomIdentity' when user is denied in ASP.NET I try to implement ASP.NET Authentication and Authorization on top of our existing database.
We have a website calling a webservice to fetch its data. To use the webservice, i need to provide the username and password.
Knowing that, I decided to implement IIdentity and IPrincipal to store the encrypted password and be able to provide it when performing webservice calls.
In the future, we might want to use more of the built-in security of asp.net, so I implement membership and role provider and override just what I need (ValidateUser and GetRoles)
Though, after validating the user thanks to the membership provider implementation I am still setting my own CustomIdentity to the Context.User to be able to retrieve its password when needed.
It's working perfectly as long as the user is allowed to visit the page. but when the user is denied, instead of throwing an AccessDeniedException, the framework throws a Serialization exception on my CustomIdentity.
I found a perfectly similar behaviour with more details described on this link , but no answer have been posted.
My exception is exactly the same as on the link above

Type is not resolved for member'CW.CustomAuthentication.CWIdentity,CW.CustomAuthentication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Runtime.Serialization.SerializationException: Type is not resolved for member 'CW.CustomAuthentication.CWIdentity,CW.CustomAuthentication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[SerializationException: Type is not resolved for member 'CW.CustomAuthentication.CWIdentity,CW.CustomAuthentication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.]
   Microsoft.VisualStudio.WebHost.Connection.get_RemoteIP() +0
   Microsoft.VisualStudio.WebHost.Request.GetRemoteAddress() +65
   System.Web.HttpRequest.get_UserHostAddress() +18
   System.Web.HttpRequest.get_IsLocal() +13
   System.Web.Configuration.CustomErrorsSection.CustomErrorsEnabled(HttpRequest request) +86
   System.Web.HttpContext.get_IsCustomErrorEnabled() +42
   System.Web.Configuration.UrlAuthFailedErrorFormatter.GetErrorText(HttpContext context) +16
   System.Web.Security.UrlAuthorizationModule.WriteErrorMessage(HttpContext context) +29
   System.Web.Security.UrlAuthorizationModule.OnEnter(Object source, EventArgs eventArgs) +8777783
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +68
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75

Is it correct to use membership and custom IIdentity and IPrincipal at the same time?
If not, where to add properties like the password or other userdata if I use the membership and role providers?
Best regards,
Stephane Erbrech

A: after some more testing, according to what the link I posted said, it seems that this error is happening only when I run in debug mode from visual studio. If I set the project to run in IIS, the error is gone and the security implementation works as expected.
---Is that a bug in the lightweight webserver implemented in Visual studio then?---
Edit :
You can go in the Properties of your web project, go to the "Web" tab, and check "Use local IIS Server". However, this will require you to run Visual Studio as an Administrator and to have IIS installed on your machine, so that VS can create the virtual directory in the local IIS server when it loads the project.

A: In my case, I simply had to inherit from MarshalByRefObject.
public class IcmtrIdentity :  MarshalByRefObject, IIdentity
{
   ...
}

A: This might not be the correct answer, but I had this issue also but fixed it.
Originally, I just had a custom class that inherited GenericIdentity (or implimented IIdentity). When I finally created a custom class which inheritted GenericPrincipal (or implimented IPrincipal) then it all worked?
my CustomPrincipal class did nothing but inherited from GenericPrincipal and had one constructor which called the base constructor.
Both the CustomPrincipal and CustomIdentity classes did NOT impliment any Serialization or ISerializable stuff. Then again, my classes were all very basic.

A:
You can go in the Properties of your web project, go to the "Web" tab, and check "Use local IIS Server". However, this will require you to run Visual Studio as an Administrator and to have IIS installed on your machine, so that VS can create the virtual directory in the local IIS server when it loads the project.

I had the same issue when trying to run the web app using CustomIdentity. In order to set the project to use your IIS in VS 2008, you will need to define the URL to your application pool in your web application project.

A: This can also be resolved by adding the assembly containing your custom identity to the GAC on your dev machine.


text:
Q: nrow() return null when I am referring to the data frame using index I am trying to create a for loop which will create a new column in each of the data frame that I have, and the value of each cells in the column equals to the name of the dataframe. Anyways, I am encountering this issue when I trying to employ the for loop.
dflist <- list(df1, df2, df3, df4)
dflist_name <- c('df1', 'df2', 'df3', 'df4')

when I use this:
nrow(df1)
>1000
nrow(dflist[1])
>NULL

eventually I want to do this:
for (i in 1:length(dflist)) {
  cbind(dflist[i], rep(dflist_name[i], nrow(dflist[i])))

Can someone help explain this issue?

A: If you create a nested df with your dataframes in a column and their names in another column, you can use the unnest function in tidyr. Here's an example:
library(tidyverse)

df1 <- data.frame(
  a = rbinom(10, 1, .5),
  b = rbinom(10, 1, .5)
)

df2 <- data.frame(
  c = rbinom(10, 1, .5),
  d = rbinom(10, 1, .5)
)

df3 <- data.frame(
  e = rbinom(10, 1, .5),
  f = rbinom(10, 1, .5)
)

file_names = c('df1', 'df2', 'df3')

dflist <- list(df1, df2, df3)

df_nest <- data_frame(
  file_contents = dflist,
  file_name = file_names)

df_all <- unnest(df_nest)

This will give you a single dataframe with a column describing the name of the dataframe where each obs comes from.
edit: You can then split the dataframe by column values if you want separate dfs.


text:
Q: Running Cucumber Scenarios in parallel using cucumber-groovy I am trying to update a project that uses Groovy's Cucumber implementation.  I am getting the following error when trying to run:
./gradlew cucumber -Denv=test -Ptags=@myTest --continue --no-daemon
Error: Could not find or load main class io.cucumber.core.cli.Main
Caused by: java.lang.ClassNotFoundException: io.cucumber.core.cli.Main

I see the relevant dependency locally

and from my IntelliJ Run Configuration, I am able to set the Main class:io.cucumber.core.cli.Main with no errors. Yet when I run from this context, it gives me undefined step definition errors, despite being able to click through to the Step Defs from the feature files.
I am using Gradle (from wrapper context) 5.0
The section that declares the jar in the cucumber task in the build.gradle is:
    doLast {
    javaexec {
        main = "io.cucumber.core.cli.Main"
        classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
        systemProperty "parallel", System.properties.getProperty("parallel", setParallel)
        if (setParallel == "true") cucumberArgs.addAll(cucumberThreadsOption)
        args = cucumberArgs
        jvmArgs = [
                "-Denv=$env",
        ]
    }
}

My dependencies:
dependencies {
    implementation "io.cucumber:cucumber-core:5.1.3"
    implementation "io.cucumber:cucumber-groovy:5.1.3"
    compile "org.codehaus.groovy:groovy-all:2.5.6"
}

Wonder if there is anything obvious?


text:
Q: Writing a .txt file from SQL row's data I am setting up a application with Django/ExpressJS(prototyping) and vueJS and MYSQL.
One goal is generate .txt file from data store in row. Each row will have one .txt file and user can download them via button click.
Quit not sure how to do that, Can use SQL query but hope there is some way via Django.
I am new with Django, experience in ExpressJS.


text:
Q: assign a value to a custom column when a document is added or created in a sharepoint document library I thought this would be pretty simple, but guess not.  I have the following code, it deploys and activates just fine, but when I add a new document to the document library, nothing happens.  No errors either.  And this is taken directly from another example from someone online who said it works.
Here's the code for my feature:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;

namespace DocNumGenerator
{
    class DocNumGenerator : SPItemEventReceiver
    {
        public override void ItemAdded(SPItemEventProperties properties)
        {
            base.ItemAdded(properties);
        }

        public override void ItemAdding(SPItemEventProperties properties)
        {
            properties.AfterProperties["DocNum"] = "4321";
            base.ItemAdding(properties);
        }

        public override void ItemUpdated(SPItemEventProperties properties)
        {
            base.ItemUpdated(properties);
        }

        public override void ItemUpdating(SPItemEventProperties properties)
        {
            base.ItemUpdating(properties);
        }

    }
}

Simple right!  Why doesn't this work?  Do I need to somehow specify the name of the document library in addition to the name of the custom column that I am specifying?  I'm lost on this one and desperate for a solution.  This is a SharePoint 2007 environment, publishing site.
Thanks for any help!

A: could you try first calling base, base.ItemAdding(properties);, then just set properties.ListItem["DocNum"] and the call properties.ListItem.SystemUpdate(false);

A: Is DocNum the display name or the internal name? Try change between those.

A: Try this in the ItemAdded event handler:
DisableEventFiring();
SPListItem item = properties.ListItem;
item["DocNum"] = "4321";
item.Update();
EnableEventFiring();

A: I got it to work..and I swear I'd tried this before.  I also did a reboot, so maybe that was it???
Here's what is working for me now:
public override void ItemAdding(SPItemEventProperties properties)
        {
            this.DisableEventFiring();
            properties.AfterProperties["Document Number"] = "whatever";
            this.EnableEventFiring();
        }


text:
Q: MySQL replace UNION with LEFT JOIN IFNULL sorry for the Title but I couldn't find a better description for our problem.
We have a user table and a token table which both needs to be UNIONt into one table but for performance reason without a UNION ALL.
The table structure is as follows:
Table USER:
ID Username Password

Table TOKEN:
ID User_ID Token Token_Secret

What we need is now a union of both tables.
An user is always present, an user has in most cases 1 or more tokens (1:N). The resulting table should contain
ID Username Password

with all users (wether they have a token or not) and, if the user has a token, all tokens
So with a UNION the result would be
SELECT * FROM user WHERE (SOME JOINS TO GET THE RIGHT USERS)
UNION ALL
SELECT Token as Username, Token_Secret AS Password FROM token WHERE (SOME JOINS TO GET THE RIGHT TOKENS)

What I've tried so far is to just do a RIGHT JOIN like
SELECT IFNULL(b.Token, a.Username, b.Token) ... FROM
(SELECT * FROM user WHERE (SOME JOINS)) AS a
RIGHT JOIN
(SELECT * FROM token WHERE (SOME JOINS)) AS b
ON
b.User_ID = a.ID

But in this case, I'll get all users, which have either no token (so I get the Username, Password from the user table) OR just the Token from the token table.. But what I need is both! If a user has also a token, I would need the username, password and all tokens (renamed as username, password)
Is there any way to do that without an UNION? The problem with the UNION is the temptable in MySQL and the huge amount of users, which will force MySQL to write a temp table with at least more than 10.000 records

A: SELECT u.id, u.user_name,
       GROUP_CONCAT(t.token) AS tokens
    FROM users u
    LEFT JOIN tokens t ON t.user_id = u.id
    GROUP BY u.id;

If you need id, user, token:
SELECT u.id, u.user_name,
       IFNULL(t.token, '(no token for this user)') as token
    FROM users u
    LEFT JOIN tokens t ON t.user_id = u.id
    ORDER BY user_name, token;


text:
Q: directive does not get executed on $watch I'm a bit struggling to get my head around .directive, what I'm trying to do is to force/ or a way so that the directive is called if value changes. Right now the value only gets changed when I refresh the browser. However, I want the value to dynamically gets replaced if it gets changed by some other service.
here is the controller
$scope.status = 'warning';

here is the html

   status
   <icon-selector filterby="status"></icon-selector>

here is the directive
angular.module('myApp')
.directive('iconSelector', function ($compile, $timeout) {

    var linkingFunction = function (scope, element, attrs) {
        scope.$watch('filterby', function () {
            if (scope.filterby === 'OK') {
                element.replaceWith('
Running OK
');
            } else {
                element.replaceWith('
Not running
');
            }
        });
    };

    return {
        restrict: 'E',
        scope: {
            filterby: '=filterby'
        },
        link: linkingFunction
    };
});

Now if I set $scope.status = 'danger'; with $watch in place, I would expect the function in `directive to be executed again but it does not get executed, it only get executed when page is reloaded.
Can someone tell me what I'm doing wrong please.

A: your watch trigger is replacing the directive element.
So basically, after the first trigger, the element you ask to replace is still the directive element, but eh, it's not in the document anymore, because you already replaced it the first time. funny, isnt ?
Why not only replacing the text (or the inner html is you really need to) in the directive instead of replacing the whole element ( a directive element should NEVER be replaced on the fly, only angular inner compilation has the 'right' to do so )
EDIT : the example :
angular.module('myApp')
    .directive('iconSelector', function () {
        return {
            restrict: 'E',
            replace : true,
            template : '{{message}}',
            scope: {
                filterby: '='
            },
            link: function ($scope, $element, $attrs) {
                $scope.$watch('filterby', function (filterby) {
                    if (filterby === 'OK') {
                        $scope.message = 'Running OK';
                    } else {
                        $scope.message = 'Not running';
                    }
                });
            }
        };
    });


text:
Q: active record summation in codeigniter I want to find sum of votes and am using codeigniter and mysql. In my votes table i've a column which shows type of vote 0 for down vote and 1 for up vote how can i generate an sql that looks like this
SELECT sum(type) FROM `votes` WHERE questions_id=1

using codeigniter database class
Cheers

A: That should do the trick:
$this->db->select('SUM(type) as score');
$this->db->where('question_id',1);
$q=$this->db->get('votes');
$row=$q->row();
$score=$row->score

Your $score variable now contains the sum of the types for that particular question.
Hope that helps!


text:
Q: SQL Query for accessing information from two separate tables I have two tables named Articles and Publishers
In Article table, there are multiple columns but there are 3 of note: ArticleId, PublishDate, and AuthorName.
In the Publishers table, there are also multiple columns but 2 of note: ArticleId and HasPublisher.
So for example if the Article table contains:
ArticleID   PublishDate  AuthorName
1              9/27/21     John
2              12/13/21   Smith
3               1/3/22.    Bob

and the Publisher table contains
ArticleID   HasPublisher
 1             Yes
 2             No
 3              Yes

What query will I have to run to check how many rows in the Publisher table has column HasPublisher = yes in which the same Id in the Article table has a publishDate column value of past date X.
So in this example if we want to fit criteria of date being past 9/26/21, the result would be 2 (Id = 1 and Id = 3 are value HasPublisher = Yes in the second table) but if we wanted to fit critera of date being past 1/1/22, the result would only be 1 entry (Id = 3).

A: select COUNT(p.*)
from Article a
inner join Publisher p on p.ArticleID = a.ArticleID
where p.HasPublisher = 'Yes' AND a.PublishDate > '2021-09-26'

Note how I formatted the date literal. If you're actually storing the dates as varchar columns in the 9/27/21 format, you're doing it wrong. The schema itself is broken, and you need to fix it. It is still possible to write this query with the broken schema, but the fixed version can take advantage of an index to run multiple orders of magnitude faster, and I promise you will save you much heartache in the future.

A: SELECT COUNT(1) FROM Article art
INNER JOIN Publisher pub
ON  art.ArticleID   = pub.ArticleID
WHERE PublishDate  > '2021-07-26'
AND HasPublisher = 'Yes'

You can inner join both the table on the ArticleId column and then filter on the criteria of HasPublisher and PublishDate.
Edit: Corrected the date format


text:
Q: Telerik RadListBox dont want to drag In my asp.net solution i am trying to use Listbox drag and drop capabilyties (like in this example : http://demos.telerik.com/aspnet-ajax/listbox/examples/functionality/draganddrop/defaultcs.aspx). But the problem ive got now is that drag and drop doesnt work. instead of draging its marking items... i tryed to copy html directly to my page and it still doesnt work. any ideas what can be wrong?
Is it because i miss CSS?
View:
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentToolbar" runat="server">

<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">

</asp:ScriptManagerProxy>
<%if(false) {%>

<%} %>

<telerik:RadAjaxManager ID="RadAjaxManager1" OnAjaxRequest="RadAjaxManager1_AjaxRequest" runat="server">
</telerik:RadAjaxManager>

    <telerik:RadToolBar ID="RadToolBar1" runat="server"
                        OnButtonClick="Toolbar_ButtonClick"
                        EnableEmbeddedSkins="False"
                        OnClientButtonClicked="OnClientButtonClicked"
                        CssClass="pickers_width"
                        Skin="AgendaSkin">
        <Items>
            <telerik:RadToolBarButton   AccessKey="<%$ Resources:Shortcuts, GLOBAL_SAVE %>"
                                        PostBack="false"
                                        Text="<%$ Resources:Language, Generel.Expression.SaveAndClose %>"
                                        CommandName="SAVEANDCLOSE"
                                        Value="SAVEANDCLOSE"
                                        ImageUrl="~/Images/Icons/save_16.png"></telerik:RadToolBarButton>

            <telerik:RadToolBarButton   AccessKey="<%$ Resources:Shortcuts, POPUPS_RETURN %>"
                                        PostBack="False"
                                        Text="<%$ Resources:Language, Generel.Expression.Close %>"
                                        CommandName="CLOSE"
                                        ImageUrl="~/Images/Icons/close_16.png"></telerik:RadToolBarButton>
        </Items>
    </telerik:RadToolBar>

</asp:Content>

<asp:Content ID="Content3" ContentPlaceHolderID="ContentHeader" runat="server">

</asp:Content>

<asp:Content ID="Content4" ContentPlaceHolderID="ContentWorkspace" runat="server">

        <asp:Panel ID="pnlRoleList" runat="server" CssClass="prof_item_value_section">

       <telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server" CssClass="example-panel">
        <telerik:RadListBox ID="RadListBox1" runat="server" Width="200px" Height="200px"
            SelectionMode="Single" AllowReorder="true"
            EnableDragAndDrop="true" OnDropped="RadListBox1_Dropped">

        </telerik:RadListBox>
    </telerik:RadAjaxPanel>
        </asp:Panel>

 <asp:HiddenField runat="server" ID="hidRoleInObjectUId" />
 <asp:HiddenField runat="server" ID="hidRoleInObjectName" />
</asp:Content>
<asp:Content ID="Content5" ContentPlaceHolderID="ContentScripts" runat="server">

</asp:Content>

CS :
    private void FillMandatoryItemFirstList(Guid item_guid)
    {
        //MandatoryItems First

        IEnumerable<MandatoryItem> mandatoryFirst = MandatoryItem.GetMandatoryItemByCommitteeAndPos(item_guid, Enums.GetGuidFromEnum(Enums.AgendaElementPositionEnum.PosFirst));
        foreach (var item in CheckCount(mandatoryFirst))
        {
                    RadListBox1.Items.Add(new RadListBoxItem(item.UIdHandlingItemHandlingItem.Title, item.Id.ToString()));

        }

    }

A: Have you tried replacing your standard ScriptManager with a RadScriptManager?