text:
Q: Playing music in the background of a JFrame window I am trying to play an audio file in the background of a Frame window and I'm finding out it is way more complicated then just adding a picture.
I found a "tutorial" that should how to add music and it seemed fairly simple, at least in the amount of code required.  However, I am not able to play the audio file, it is saying two things...
1st - I was trying to play a audio file I copied to my java project and that was telling me it could not find that file or directory.
2nd - I gave the method a path to a audio file and it's telling me...
could not get audio input stream from input file

Please keep in mind I'm very new and this tutorial did not give a lot of help, so I do not know a lot of what this play method is actually doing.  I'd love to learn how to do this but everything I've seen is overly complicated for this project and I don't have the time to put in because it's not necessary just a little added flair is all.
Any help is greatly appreciated!!  I put stars around the code in question.
public MultiForm() {
    super("Multi Form Program");
    setLayout(new FlowLayout());
    menu = new JComboBox(fileName);
    add(menu);

    /*How to add a background image to the Menu.
     * add(new JLabel(new ImageIcon(getClass().getResource("MatrixPIC.png"))));
     */

    TheHandler handler = new TheHandler();
    menu.addItemListener(handler);
}

public void matrixPanel() {

    TheHandler handler = new TheHandler();
    //Create a new window when "The Matrix" is clicked in the JCB
    newFrame = new JFrame();
    panel = new JPanel();
    panel2 = new JPanel();

    newFrame.setLayout(new FlowLayout());
    newFrame.setSize(500, 300);
    newFrame.setDefaultCloseOperation(newFrame.EXIT_ON_CLOSE);

    matrixQuote = new JLabel("After this, there is no turning back. "
            + "
You take the blue pill—the story ends, you wake up "
            + "
in your bed and believe whatever you want to believe."
            + "
You take the red pill—you stay in Wonderland, and I show"
            + "
you how deep the rabbit hole goes. "
            + "
Remember: all I'm offering is the truth. Nothing more.");

    panel.add(matrixQuote);
    newFrame.add(panel, BorderLayout.NORTH);

    //Blue pill button and picture.
    Icon bp = new ImageIcon(getClass().getResource("Blue Pill.png"));
    bluePill = new JButton("Blue Pill", bp);
    panel2.add(bluePill);
    bluePill.addActionListener(handler);

    //Red pill button and picture
    Icon rp = new ImageIcon(getClass().getResource("Red Pill.png"));
    redPill = new JButton("Red Pill", rp);
    panel2.add(redPill);

    newFrame.add(panel2, BorderLayout.CENTER);
    newFrame.setVisible(true);
}

*********************************************************************************
public void play(String path, int delay, int numberOfLoops) {
    for(int i = 0; i < numberOfLoops; i++) {
        new Thread() {
            @Override
            public void run() {
                try {
                    File file = new File(path);
                    Clip clip = AudioSystem.getClip();
                    clip.open(AudioSystem.getAudioInputStream(file));
                    clip.start();
                    Thread.sleep(clip.getMicrosecondLength());

                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            }
        }.start();
        try {
            Thread.sleep(delay);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
*********************************************************************************

private class TheHandler implements ItemListener, ActionListener{

    public void itemStateChanged(ItemEvent IE) {
        //listen for an item to be selected.
        if(IE.getStateChange() == ItemEvent.SELECTED) {
            Object selection = menu.getSelectedItem();

            if("The Matrix".equals(selection)) {
                matrixPanel();
            }
            else if("Another Option".equals(selection)) {
            }
        }
    }

    public void actionPerformed(ActionEvent AE) {
        if(AE.getSource() == bluePill) {
            //Clear panels after button is clicked.
            newFrame.remove(panel);
            newFrame.remove(panel2);
            newFrame.repaint();
    *********************************************************************************
            play("/Users/SWD/Downloads/fail.mp3", 10, 30);
 *********************************************************************************
            newFrame.setSize(600, 400);
            bpPanelLabel = new JPanel();
            bpLabel = new JLabel("WELCOME TO THE BEGINING OF YOUR NEW LIFE!  " +
                     "
YOU'RE ABOUT TO SEE HOW DEEP THE RABBIT HOLE GOES!");
            newFrame.add(bpLabel);
            newFrame.add(bpPanelLabel, BorderLayout.NORTH);
            bpPanelPic = new JPanel();
            newFrame.add(new JLabel(new ImageIcon(getClass().getResource("MatrixPIC.png"))));
            newFrame.add(bpPanelPic, BorderLayout.CENTER);
            newFrame.validate();
        }

    }
}

//Main method sets up the main JFrame with the menu
public static void main(String[] args) {

    MultiForm go = new MultiForm();
    go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    go.setSize(400, 200);
    go.setVisible(true);
}
}

A: *

*Java's Audio API doesn't support (all) mp3 encoding.  If you need to play mp3's then you should have a look at JavaZoom's JLayer API

*If the file you are trying to play is within the project's src (or the Jar file by extension), you need to use Class#getResource or Class#getResourceAsStream instead

*Clip auto supports looping by itself, so you don't need to use a loop of your own, which could block the Event Dispatching Thread.

*The Thread's seem a little over kill IMHO and while you could still use one to add an artificial delay, I used a Swing Timer in my example, as it's just simpler :P

For example
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileFilter;

public class JavaApplication5 {

    public static void main(String[] args) {
        new JavaApplication5();
    }

    public JavaApplication5() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private Clip clip = null;

        private JTextField audioFile;
        private JButton browse;
        private JSpinner loops;
        private JSpinner delay;
        private JFileChooser chooser;

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            add(new JLabel("Audio File:"), gbc);

            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.weightx = 1;
            gbc.gridx++;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.anchor = GridBagConstraints.WEST;
            audioFile = new JTextField(20);
            add(audioFile);

            gbc.gridwidth = 1;
            gbc.weightx = 0;
            gbc.gridx++;
            browse = new JButton("...");
            add(browse, gbc);

            gbc.gridx = 0;
            gbc.gridy++;
            add(new JLabel("Loops: "), gbc);

            loops = new JSpinner(new SpinnerNumberModel(1, 1, 100, 1));
            gbc.gridx++;
            gbc.fill = GridBagConstraints.NONE;
            add(loops, gbc);

            gbc.gridx = 0;
            gbc.gridy++;
            add(new JLabel("Delay (seconds): "), gbc);

            delay = new JSpinner(new SpinnerNumberModel(0, 0, 10, 1));
            gbc.gridx++;
            gbc.fill = GridBagConstraints.NONE;
            add(delay, gbc);

            gbc.anchor = GridBagConstraints.CENTER;
            gbc.gridx = 0;
            gbc.gridy++;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            JButton play = new JButton("Play");
            add(play, gbc);

            play.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        play(
                                        audioFile.getText(),
                                        (int) delay.getValue(),
                                        (int) loops.getValue());
                    } catch (LineUnavailableException | IOException | UnsupportedAudioFileException ex) {
                        ex.printStackTrace();;
                        JOptionPane.showMessageDialog(TestPane.this, "Failed to play audio file:
" + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                    }
                }
            });

            browse.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (chooser == null) {
                        chooser = new JFileChooser();
                        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                        chooser.setMultiSelectionEnabled(false);
                        chooser.addChoosableFileFilter(new FileFilter() {
                            @Override
                            public boolean accept(File f) {
                                System.out.println(f);
                                return f.getName().toLowerCase().endsWith(".wav");
                            }

                            @Override
                            public String getDescription() {
                                return "Wave Files (.wav)";
                            }
                        });
                    }

                    if (chooser.showOpenDialog(TestPane.this) == JFileChooser.APPROVE_OPTION) {
                        File selected = chooser.getSelectedFile();
                        audioFile.setText(selected.getPath());
                    }
                }
            });

        }

        public void play(String path, int delay, int numberOfLoops) throws LineUnavailableException, IOException, UnsupportedAudioFileException {
            if (clip != null) {
                clip.stop();
                clip = null;
            }

            if (delay > 0) {
                System.out.println("Start with delay");
                Timer timer = new Timer(delay * 1000, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        try {
                            play(path, numberOfLoops);
                        } catch (UnsupportedAudioFileException | LineUnavailableException | IOException ex) {
                            ex.printStackTrace();;
                            JOptionPane.showMessageDialog(TestPane.this, "Failed to play audio file:
" + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                });
                timer.setRepeats(false);
                timer.start();
            } else {
                play(path, numberOfLoops);
            }
        }

        private void play(String path, int numberOfLoops) throws UnsupportedAudioFileException, LineUnavailableException, IOException {
            File file = new File(path);
            if (file.exists()) {
                clip = AudioSystem.getClip();
                clip.open(AudioSystem.getAudioInputStream(file));
                clip.start();
            }
        }
    }

}


text:
Q: Authenticating with dovecot I'm trying to access my emails using thunderbird but I'm getting an auth problem. I'm using valid certs and did adduser testuser with a simple password (1 letter, 8 didn't seem to change anything).
According to the logs it can't find the user. I haven't modified 10-auth.conf or anything in conf.d do I need to? Here is my dovecot.conf and log file
disable_plaintext_auth = no
mail_privileged_group = mail
mail_location = mbox:~/mail:INBOX=/var/mail/%u
userdb {
  driver = passwd
}

passdb {
  driver = shadow
  args = blocking=no
}

protocols = " imap"

service auth {
  unix_listener /var/spool/postfix/private/auth {
    group = postfix
    mode = 0660
    user = postfix
  }
}
ssl=required
ssl_cert = </etc/letsencrypt/live/MY_DOMAIN.COM/fullchain.pem
ssl_key = </etc/letsencrypt/live/MY_DOMAIN.COM/privkey.pem

auth_verbose=yes
auth_debug=yes
auth_debug_passwords=yes
mail_debug=yes

Log file
dovecot: master: Warning: Killed with signal 15 (by pid=1 uid=0 code=kill)
dovecot: anvil: Warning: Killed with signal 15 (by pid=1 uid=0 code=kill)
dovecot: log: Warning: Killed with signal 15 (by pid=1 uid=0 code=kill)
dovecot: master: Dovecot v2.2.13 starting up for imap (core dumps disabled)
dovecot: auth: Debug: Loading modules from directory: /usr/lib/dovecot/modules/auth
dovecot: auth: Debug: Read auth token secret from /var/run/dovecot/auth-token-secret.dat
dovecot: auth: Debug: auth client connected (pid=5293)
dovecot: auth: Debug: client in: AUTH#0111#011PLAIN#011service=imap#011secured#011session=dtEqfrs9fwBo3ndE#011lip=1.2.3.4#011rip=123.123.123.123#011lport=143#011rport=6527
dovecot: auth: Debug: client passdb out: CONT#0111
dovecot: auth: Debug: client in: CONT#0111#011AHRlc3R1c2VyAHA= (previous base64 data may contain sensitive data)
dovecot: auth: Debug: shadow(testuser,123.123.123.123,<dtEqfrs9fwBo3ndE>): lookup
dovecot: auth: shadow(testuser,123.123.123.123,<dtEqfrs9fwBo3ndE>): unknown user
dovecot: auth: Debug: client passdb out: FAIL#0111#011user=testuser
dovecot: auth: Debug: client in: AUTH#0112#011PLAIN#011service=imap#011secured#011session=dtEqfrs9fwBo3ndE#011lip=1.2.3.4#011rip=123.123.123.123#011lport=143#011rport=6527#011resp=AHRlc3R1c2VyAHA= (previous base64 data may contain sensitive data)
dovecot: auth: Debug: shadow(testuser,123.123.123.123,<dtEqfrs9fwBo3ndE>): lookup
dovecot: auth: shadow(testuser,123.123.123.123,<dtEqfrs9fwBo3ndE>): unknown user
dovecot: auth: Debug: client passdb out: FAIL#0112#011user=testuser
dovecot: imap-login: Disconnected (auth failed, 2 attempts in 8 secs): user=<testuser>, method=PLAIN, rip=123.123.123.123, lip=1.2.3.4, TLS, session=<dtEqfrs9fwBo3ndE>
dovecot: auth: Debug: auth client connected (pid=5296)

A: In all likelihood, you want to be using the pam password database, not the shadow password database. But if you're going to use the shadow database, you need to either disable the auth-worker processes (by adding args = blocking=no to the passdb section) or have the auth-workers run as group shadow:
service auth-worker {
  group = shadow
}

Both of those solutions come from the wiki. Another good solution is not to use system passwords and instead use, e.g., the passwd-file database. Example with passwd-file:
passdb {
  driver = passwd-file
  args = scheme=SHA512-CRYPT username_format=%u /etc/dovecot/passwords

}

then for your example user "testuser" with password of "p", /etc/dovecot/passwords would look like:
testuser:{SHA512-CRYPT}$6$R6MuJ818vCtvNw1y$ALycf9nfP8mL7EZysLTZJlnNGuygRHhr9xCDFi8tlIHND4i6fI8wwY6t0dAL6rOY0Jat2iZmQgqz4vEFT/0fa1

That huge hash value can be obtained via doveadm pw -s SHA512-CRYPT (it will be different each time, due to salting).

redpajama_set_name: RedPajamaStackExchange


text:
Q: truncate filter to shorten URL I have an ng-repeat that displays a bunch of long url paths in an input text box.
<div ng-repeat = path in paths>
    <input type="text" value="{{path}}">
</div>

the paths looks like this
endpoint:8000/foo/foo/foo/charlie1.file

I would just like to display the charlie1.file part
I could do it with regex and I even successfully made a function that splits it the path, reverses it, then does a for loop that pushes each character to an array, catches the first "/" then breaks the function, then re-reverses it. Then I have to loop through each path in my api call with this split/reverse function which is cumbersome.
Is there an easier way filter/truncate in angular to achieve this without a bunch of for loops?

A: You could just create a simple filter:-
 app.filter('trunc', function(){
     return function(input){
       if(!angular.isString(input)) return;
       return input.split('/').pop();
     }
 });

and do:-
 <input type="text" value="{{path | trunc}}">


text:
Q: How to delete more than one row in a matrix, not just last row, when using a for loop in R I tried to go about this myself and looked up online how to do this, but no direct answer. Basically, I am trying to delete the rows in a matrix that have more than 3 characters. My code is only deleting the last row. Rows 16-31 should be deleted. The i gets iterated, but only deletes the last column which satisfies the condition. However, more rows must be deleted. Thanks for the help in advance!
setwd("~/Desktop/Rpractice")

c <- c("1", "2", "3", "4", "5")

combine <- function (x, y) {combn (y, x, paste, collapse = ",")}

combination_mat <- as.matrix(unlist(lapply (1:length (c), combine, c)))

for (i in length(combination_mat)) {

  if (nchar(combination_mat[i]) > 3) {

  newmat <- print(as.matrix(combination_mat[-i,]))

  }
}

A: You really do not need a loop to remove those rows, eg you can look for the rows with more than 3 characters and remove those (please note the drop=FALSE argument to keep the tabular format of the data instead of simplifying that to a vector):
> combination_mat[nchar(combination_mat[, 1]) <= 3, , drop = FALSE]
      [,1]
 [1,] "1"
 [2,] "2"
 [3,] "3"
 [4,] "4"
 [5,] "5"
 [6,] "1,2"
 [7,] "1,3"
 [8,] "1,4"
 [9,] "1,5"
[10,] "2,3"
[11,] "2,4"
[12,] "2,5"
[13,] "3,4"
[14,] "3,5"
[15,] "4,5"


text:
Q: Using MetroFramework in VS2013 guys! I want use MetroFramework in my Visual Studio Express 2013.
What did I do:

*

*Follow to Tools -> Library Package Manager -> Package Manager Console

*Enter this string to it: Install-Package Winform.Metroframework.Install

*Get "installation finished successfully" message

*In the file "Form1.cs" I changed public partial class Form1 : Form to public partial class Form1 : MetroFramework.Forms.MetroForm.
From constructor it looks like correct MetroForm, but when I try to add any control I get this error:

How can I fix it?

A: I think the working project is in this package.
Install-Package MetroFramework

I am also using metroframework which is from github.
I also make some changes where I want.
so i'll recommend you to download from this link


text:
Q: Test Class Not Covering Original Class So I am trying to cover this Chatter Answers Class so I can increase my system's code coverage. The test class runs successfully but the original class is still 0% covered. What do I need to do to make sure the test class covers the original class?
Here is my original class:
public class ChatterAnswers {
    public String createAccount(String firstname, String lastname, Id siteAdminId) {
         Account a = new Account(name = firstname + ' ' + lastname, ownerId = siteAdminId);
         insert a;
         return a.Id;
    }
}

And here is my test class
@isTest
public class ChatterAnswersTest
{
 @isTest static void testChatterAnswers()
 {
 Account testAccount = new Account() ;
 testAccount.Name='Joe' + 'Smith' ;
 testAccount.OwnerId= '0050Y000003tTH8QAM';
 System.assertEquals('Joe' + 'Smith', testAccount.Name);
 System.assertEquals('0050Y000003tTH8QAM', testAccount.OwnerId);

  //testAccPlan.save();

 }
}

I tried calling the original class in the test class but that doesn't seem to be working. Can anyone please help me?
Thank you!

A: Your test class ChatterAnswersTest is not really calling the class ChatterAnswers that you intend to test, Instead it's just creating a new account record.
To be able to test the class here, you will need to create an instance of your class and call the methods within that class. Your test class should look something as below:
@isTest
public class ChatterAnswersTest {
    @isTest static void testChatterAnswers() {
        // construct variables
        // my other code
        ChatterAnswers chatAns = new ChatterAnswers();
        String accountId = chatAns.createAccount(firstName, lastName, adminId);
        // assertion statements

    }
}


text:
Q: How can I prevent react component from re-rendering by apollo usequery? I have a react component which is included in my Tabbar(Material-ui).
And this component has lots Apollo useQuery hooks(15 useQuery) to fetch some data. I tried to use loading parameter which are the result of each useQuery in order to prevent useless rendering.
    const { loading: loading_1, data: data_1} = useQuery<GetQuery1>(QUERY_1);
    const { loading: loading_2, data: data_2} = useQuery<GetQuery2>(QUERY_2);
    const { loading: loading_3, data: data_3} = useQuery<GetQuery3>(QUERY_3);

    // . . .

    const { loading: loading_15, data: data_15} = useQuery<GetQuery15>(QUERY_15);

    if (
        loading_1 ||
        loading_2 ||
        loading_3 ||
        // ... loading parameters
        loading_10
    ) {
        return Loading...;
    }

    return (
        <>
            {loading_11 ? ("Loading ... 11") : (<MyComponent_A data={data_11} options={data_6,data_7}/> )}
            {loading_12 ? ("Loading ... 12") : (<MyComponent_B data={data_12} options={data_1,data_2,data_8}/> )}
            {loading_13 ? ("Loading ... 13") : (<MyComponent_C data={data_13} options={data_4,data_7,data_9}/> )}
            {loading_14 ? ("Loading ... 14") : (<MyComponent_D data={data_14} options={data_8,data_10}/> )}
            {loading_15 ? ("Loading ... 15") : (<MyComponent_E data={data_15} options={data_3}/> )}
        </>
    );

When this component first appeared, I was able to control rendering because loading parameters of useQuery hooks return true.
However, when I reopen this component(I just clicked on the other tabs and came back), this component render 15 times always(I just printed it using console.log() for each component). I checked the loading parameters and those never had a true.
So when I re-opened this component, I didn't even get a loading message and it felt like it was stopping a bit.
How can I solve this?


text:
Q: No such file or directory Error with Google Cloud Storage I quite new to Google Cloud Platform and I am trying to train a model with TPU. I follow this tutorial to set up the TPU with Google Colab. All the code below follows the tutorial.
This is the step I have done:
import datetime
import json
import os
import pprint
import random
import string
import sys
import tensorflow as tf

assert 'COLAB_TPU_ADDR' in os.environ, 'ERROR: Not connected to a TPU runtime; please see the first cell in this notebook for instructions!'
TPU_ADDRESS = 'grpc://' + os.environ['COLAB_TPU_ADDR']
print('TPU address is => ', TPU_ADDRESS)

from google.colab import auth
auth.authenticate_user()
with tf.Session(TPU_ADDRESS) as session:
  print('TPU devices:')
  pprint.pprint(session.list_devices())

  # Upload credentials to TPU.
  with open('/content/adc.json', 'r') as f:
    auth_info = json.load(f)
  tf.contrib.cloud.configure_gcs(session, credentials=auth_info)
  # Now credentials are set for all future sessions on this TPU.

Output:
TPU address is =>  grpc://10.4.89.154:8470

Provide my BUCKET name and OUPUT DIRECTORY name:
BUCKET = 'my_xlnet' #@param {type:"string"}
assert BUCKET, '*** Must specify an existing GCS bucket name ***'
output_dir_name = 'xlnet_output' #@param {type:"string"}
BUCKET_NAME = 'gs://{}'.format(BUCKET)
OUTPUT_DIR = 'gs://{}/{}'.format(BUCKET,output_dir_name)
tf.gfile.MakeDirs(OUTPUT_DIR)
print('***** Model output directory: {} *****'.format(OUTPUT_DIR))

Move the pretrained model to GCS bucket:
!gsutil mv /content/xlnet_extension_tf/model/xlnet_cased_L-24_H-1024_A-16 $BUCKET_NAME

Output:
...
Operation completed over 5 objects/1.3 GiB.

Then run the main code:
!python /content/xlnet_extension_tf/run_coqa.py \
--use_tpu=True \
--tpu_name=grpc://10.4.89.154:8470 \
--spiece_model_file=$BUCKET_NAME/xlnet_cased_L-24_H-1024_A-16/spiece.model \
--model_config_path=$BUCKET_NAME/xlnet_cased_L-24_H-1024_A-16/xlnet_config.json \
--init_checkpoint=$BUCKET_NAME/xlnet_cased_L-24_H-1024_A-16/xlnet_model.ckpt \
...

Then I got this error:
OSError: Not found: "gs://my_xlnet/xlnet_cased_L-24_H-1024_A-16/spiece.model": No such file or directory Error #2

This is the GCS bucket screen:

I don't know why this error exists because I can move my pretrained model to the bucket successfully.
Do you guys know how to fix this?
Update:
The run_coqa.py file: https://github.com/stevezheng23/xlnet_extension_tf/blob/master/run_coqa.py

A: Can you post the part where run_coqa.py is opening the file?
It seems like you're trying to open it with a regular os. command where you should be using GCP's sdk.

A: This tutorial was created by a third party. I cannot see any common issue going on right now that would stop this code from running.


text:
Q: not single-group grouping function while using regr_slope HI I try to run :
 select
  year,
  regr_slope(sum(sale_count),year) as slope,
from products
group by year

It throws "00937. 00000 -  "not a single-group group function"" .When i delete year from select clause problem disapears. Shouldn't I be able to select column with which I'm grouping?
Oracle 11.2 sqldeveloper
ty for help !

A: It's because you're attempting to use a function (REGR_SLOPE) that can be either an aggregate (or analytical) function on the result of another aggregate (SUM) - use:
  SELECT x.year,
         REGR_SLOPE(sum_sales, x.year) AS slope
    FROM (SELECT y.year,
                 SUM(y.sale_count) AS sum_sales
            FROM PRODUCTS y
        GROUP BY y.year) x
GROUP BY x.year

Alternative using WITH clause (Oracle 9i+):
WITH sums AS (
     SELECT y.year,
            SUM(y.sale_count)
       FROM PRODUCTS y
   GROUP BY y.year)
  SELECT x.year,
         REGR_SLOPE(sum_sales, x.year) AS slope
    FROM sums x
GROUP BY x.year

A: Did you try it like this?
select
   a.year
 , regr_slope(a.sale_count,a.year) as slope,
from (SELECT year
           , sum(sale_count) sale_count
        FROM products
      GROUP BY year) a


text:
Q: Test for Statistical Differences Among Coefficients of Variation (using R)? I have two datasets, and I wish to determine the statistical difference between two groups. I am comparing a visual plant injury scoring system to a remotely-sensed scale, and the coefficient of variation (CV) is usually used for this purpose (it goes on the assumption that the lower the CV of the dataset, the "better" the scale). It's important to note that the data has been normalized between 0 and 1, to make for a more accurate comparison.
How can I test for differences in the two CVs? Given there are just two datasets, it would be easy to do a t-test if comparing means. However, I'm not needing to compare the means. Can this be done in R?
Here is the data, in case reference is needed:
dataset <- data.frame(visual = c(152,
                                 150,
                                 275,
                                 407,
                                 364,
                                 105,
                                 415,
                                 221,
                                 374,
                                 408,
                                 265,
                                 290,
                                 186,
                                 130,
                                 263,
                                 113,
                                 290,
                                 157,
                                 348,
                                 384,
                                 369,
                                 175,
                                 421,
                                 183,
                                 214,
                                 146,
                                 333,
                                 374,
                                 201,
                                 262,
                                 364,
                                 343,
                                 395,
                                 332,
                                 290,
                                 294),
                      remotesense = c(104,
                                      132,
                                      148,
                                      370,
                                      257,
                                      373,
                                      409,
                                      320,
                                      350,
                                      178,
                                      236,
                                      100,
                                      219,
                                      403,
                                      107,
                                      345,
                                      102,
                                      307,
                                      292,
                                      258,
                                      271,
                                      220,
                                      165,
                                      211,
                                      204,
                                      420,
                                      339,
                                      380,
                                      227,
                                      390,
                                      354,
                                      153,
                                      423,
                                      103,
                                      342,
                                      116))


text:
Q: QgisInterface.addVectorLayer Error I am Esri-trained, trying to move into QGIS using Python.  Simply trying to add a vector layer in QGIS returns the below error:
TypeError: QgisInterface.addVectorLayer(QString, QString, QString): first argument of unbound method must have type 'QgisInterface'
Here's my code:
layer = qgis.core.QgsVectorLayer("C:\mypath\mypath\GTM_adm1.shp", "GTM_adm1", "ogr")
qgis.gui.QgisInterface.addVectorLayer(layer, "GTM_adm1", "ogr")

Not sure what I'm missing here but the Vector layer object is in the registry.

A: Just as a remark: QgisInterface is an abstract class and has virtual functions so it may not be instantiated, i.e. it defines an interface and not a complete implementation. But you can use QgisInterface class within a standalone application where the iface class is not available. There you can reimplement and override the main functions of the class. An example very trivial is the following:
from qgis.core import QgsMapLayerRegistry, QgsVectorLayer
from qgis.gui import QgisInterface

def addVectorLayer(uri, provider, name):
    vl = QgsVectorLayer(uri, name, provider)
    QgsMapLayerRegistry.instance().addMapLayer(vl)
    return vl, name

class MyIface(QgisInterface):
    def __init__(self):
        QgisInterface.__init__(self)

    def addVectorLayer(self, path, name, provider):
        return addVectorLayer(path, provider, name)

# usage:
# >>> myiface = MyIface()
# >>> myiface.addVectorLayer("some_path_to_layer", "some_name", "ogr")

So using

>>> myiface.addVectorLayer("some_path_to_layer", "some_name", "ogr")
(<qgis._core.QgsVectorLayer object at 0x7546440>, 'some_name')

it will work, but another method e.g

>>> myiface.activeLayer()
NotImplementedError: QgisInterface.activeLayer() is abstract and must be overridden

will raise to NotImplementedError because that method is defined into the class but it is not re-implemented, i.e. it is an abstract method.
BTW: your error (...first argument of unbound method...) is a different error though, the origin of the error is you don't have instantiated the class before, so the correct way to write was:

qgis.gui.QgisInterface().addVectorLayer(layer, "GTM_adm1", "ogr")

which would raise to TypeError: qgis._gui.QgisInterface represents a C++ abstract class and cannot be instantiated
Hope this helps as explanation.

A: Try simply:
layer = iface.addVectorLayer("/path/to/shapefile/file.shp", "layer_name_you_like", "ogr")

Here you have a nice guide for PyQGIS: http://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/intro.html


text:
Q: Do photons influence charged particles? As a neutrally charged particle, a photon shouldn't interact electrically with another charged particle. However, since photons are electromagnetic waves, they should interact with charged particles, both electrically and magnetically.
Is this because the average in time of the electric and magnetic fields is zero?
(physics student)

A: No, as you also said that photons are neutral particles due to this property, no charge will be interact with Photons because the rest mass and charge is zero and also they don't have any magnetic poles.


text:
Q: Como passar um texto como parâmetro para uma função JavaScript? Preciso fazer uma função JavaScript e quero que ela receba os parâmetros em formato de texto:
Código HTML:
<button onClick="AlteraNome(Felipe)">Enviar Nome</button>

Código JavaScript:
function AlteraNome(nome){
   document.write(nome);
}

Se alguém puder me ajudar, agradeço!

A: Se estás a tentar obter o nome aplicado ao botão no exemplo da tua pergunta, podes fazer isso utilizando document.getElementById("meuBotao").innerText; da seguinte maneira:

function alteraNome() {
    // procura o id="meuBotao" e substitui o texto dentro dele por - "Outro Nome Aqui"
    document.getElementById("meuBotao").innerText="Outro Nome Aqui";
}
<button onclick="alteraNome()" id="meuBotao">Altera Nome do Botão</button>

Se estás a tentar pegar um nome introduzido num input e passá-lo para outro lado qualquer, como uma outra div por exemplo, podes fazê-lo da seguinte maneira:

function transfereNome() {
    var input = document.getElementById('enviaNome')
    var div = document.getElementById('mostraNome');
    // diz que o conteúdo dentro do id="mostraNome" é igual ao valor introduzido no input
    div.innerText = input.value;
}
<input type="text" id="enviaNome"/>
<button onclick="transfereNome()">Enviar Nome</button>


text:
Q: why is my instance garbage collected I have the following class hierarchy. For some reason, my listener gets garbage collected even though I maintain a strong reference to it.
class MyModule {
   MySubModule submodule = null;

   MyModule(Channel ch) {
      submodule = new MySubModule(ch);
   }
}

class MySubModule {
   MyListener listener = null;

   MySubModule(Channel ch) {
      listener = new MyListener();
      ch.subscribe(listener);
   }
}

class Channel {
   Map<MyListener, Boolean> backend = new WeakHashMap<MyListener, Boolean>();
   Set<MyListener> listeners = Collections.newSetFromMap(backend);

   void subscribe(MyListener listener) {
       listeners.add(listener);
   }

   void fireListeners() {
       // listeners get garbage collected so they won't get fired
       for (MyListener listener:listeners) {
          listener.observe(someEvt);
       }
   }
}

The class Channel maintains a set of listeners in a WeakHashSet. So I register the listener in MySubModule along with keeping a strong reference to it in the same class(variable listener). However, JVM still garbage collects the listener instance. Shouldn't it stay in the WeakHashSet as soon as there is strong reference to it? In which case, I truly believe I have one above. Can someone tell me what wrong I am doing here?
edit:
I added the implementation of Channel above as well. Also in main(...) method, I have the following:
static void main(...) {
    Channel ch = new Channel();
    MyModule myModule = new MyModule(ch);
    // do some real stuff here.
}

A: It's impossible that MyListener gets garbage collected, if you still have strong reference to MyModule.
Either you do not set correctly submodule, or you do not set correctly listener, or you never add your listener to the backend WeakHashMap (which I guess is the most probable).
How do you even know that listener is garbage collected? You probably check whether it's present in the backend WeakHashMap. It's not there so you claim it's gc'ed. But in reality it was never added to it. Let me know if that's correct.
First check if you really have strong reference to Module and SubModule. If you have, then check if SubModule has a valid reference to MyListener.


text:
Q: Не могу понять почему выражение y >> x++ * z всегда равно 0 Делаю дз на курсах и не могу понять почему компилятор пишет что Result of 'y >> x++ * z' is always '0'. В консоли итоговый ответ 5. Подскажите пожалуйста почему же выражение равно нулю.
int x = 5, y = 10, z = 15;
x += y >> x++ * z;
System.out.println("Переменная х = " + x);

A: Я не понимаю, что это значит 15 >> 75 из комментария. Число 10 (1010) сдвигается на 5 позиций вправо. Все единицы исчезнут, останется ноль.

A: Для начала смотрим на приоритет операторов в Java

*

*Постфиксный инкремент и декремент

*Префиксный инкремент и декремент

*Умножение, деление, нахождение остатка

*Сложение, вычитание

*И самое последнее - присвоение.

Теперь расставим скобки в вашем выражении
x += (y >> ((x++) * z));

Теперь распишем значение каждой скобки исходя из
int x = 5, y = 10, z = 15;

*

*x++ == 5,

*5 * 15 == 75

*10 >> 75 == 0

*5 += 0 == 5


text:
Q: Placing $t$ horizontal dominoes in a $2 \times n$ table with some restrictions
Given positive integers $n$ and $t$ find the number of ways to place $t$ horizontal dominoes in a $2\times n$ table so that no two dominoes form a $2\times 2$ square and no $2\times 3$ rectangle contains two dominoes such that the one in the upper row has occupied the middle and the rightmost cell and the one in the lower row has occupied the middle and the leftmost cell.

Apart from $A(n,1) = 2(n-1)$ and $A(n,t) = 0$ for $t\geq n$ I have no further good ideas. Perhaps some recursion (hopefully with not too many equations to manipulate)?
Any help appreciated!

A: For convenience, let's say that Rule 1 is that there are no 2 dominoes forming a 2x2 square and Rule 2 is that there are no two dominoes forming the upper right and lower left corners of a 2x3 square.
Let us consider an arbitrary acceptable arrangement of a $2\times n$ square with $t$ horizontal dominoes.  As I see it, there are four distinct possibilities:

*

*The rightmost column has no dominoes in it. There are $A(n-1,t)$ of these.

*There is a domino in the rightmost two squares of the top row.  There is no domino in the rightmost square of the bottom row (by Rule 1) or the second right-most square (by Rule 2), so there are $A(n-2,t-1)$ of these.

*There is a domino in the rightmost two squares of the bottom row.  There is no domino in the rightmost square of the top row (by Rule 1).

*

*There are $A(n-2,t-1)$ arrangements where there is no domino in the second rightmost square of the top row.

*There could be a domino in the second and third rightmost squares of the top row without violating Rule 2.  However, there could not be a domino in the third rightmost square of the bottom row, because that domino and the second one would violate Rule 2.  Therefore, there are $A(n-3,t-2)$ of these.

In all, our recursion formula is $$A(n,t)=A(n-1,t)+2A(n-2,t-1)+A(n-3,t-2)$$
As for the base cases, I think that all you would need are $A(0,0)=1$ and $A(0,t)=A(1,t)=0$ for all $t>0$, but I could be missing something.

A: We can prove the recurrence:
$$
A(n,t) = A(n-1,t) + 2A(n-2,t-1) + A(n-3,t-2),\\\tag{$n\ge 1\text{ or }t\ge 1$}
A(0,0)=1.\hspace{3.25in}
$$
by considering all possibilities for what the left end of a tiling looks like, and the number of ways to complete each to a legal tiling, as shown below:

To solve this recurrence, let $F(x,y)=\sum_{n,t\ge 0}A(n,t)x^ny^t$ be the two variable generating function for $A(n,t)$. The recurrence relation implies the generating function equation
$$
F(x,y) = 1+xF(x,y) + 2x^2yF(x,y) + x^3y^2F(x,y)
$$
which implies
$$
F(x,y) = \frac1{1-(x+2x^2y+x^3y^2)}=\frac1{1-x(1+xy)^2}=\sum_{m\ge 0}\big(x(1+xy)^2\big)^m=\sum_{m\ge 0}\sum_{k=0}^{2m} \binom{2m}kx^{m+k}y^k
$$
Finally, the coefficient of $x^ny^t$ in $F(x,y)$ is obtained by setting $k=t$ and $m=n-t$ in the last summation, for which the accompanying coefficient is $$\boxed{A(n,t)=\binom{2(n-t)}t.}$$

With this hindsight, we can now derive a combinatorial proof of this formula. To choose a tiling of a $2\times n$ board with $t$ dominos, label the first $n-t$ columns of the board from $1$ to $2(n-t)$ as shown below. Then, select $t$ squares from the first $2(n-t)$ columns, which can be done in $\binom{2(n-t)}{t}$ ways. Next, for each $k=1,2,\dots,t$, take the selected square with the $k^{th}$ smallest label, and move it $k-1$ squares to the right. Finally, place the left end of a domino covering each of the selected squares.
$$
\begin{array}{|c|c|c|c}
\hline
1&3&5&\dots\\\hline
2&4&6&\dots
\\\hline
\end{array}
$$
Here is an example with $n=8$ and $t=4$. The first picture shows the squares selected arbitrarily from the first $n-t=4$ columns, and the second picture shows the resulting tiling.

A: Here's a combinatorial proof that $A(n,t)=\binom{2(n-t)}{t}$.  Let $X = \{1,\dots,n−t\}$ and $Y = \{H,L\}$. Then $|X \times Y| = 2(n−t)$. Choose a $t$-subset $\{(x_i,y_i): i = 1,\dots,t\}$, listed lexicographically for convenience. The corresponding domino arrangement has domino $i$ starting in column $x_i + i − 1$ in either the High or Low position, according to $y_i$. The $+i−1$ ensures that the dominoes don't overlap. Also, if $x_i = x_{i+1}$, we must have $y_i = H$ and $y_{i+1} = L$, by the lexicographic convention. In that case, we get two dominoes in columns $x_i + i−1$ through $x_i + i + 1$. The inverse mapping is clear: to recover $x_i$, just subtract $i−1$ from the starting column of domino $i$, and $y_i$ is $H$ or $L$, according to whether domino $i$ is High or Low.


text:
Q: Unpickle class instances by interating over a list I am trying to unpickle various class instances which are saved in separate .pkl files by iterating over a list containing all the class instances (each class instance appends itself to the appropriate list when instantiated).
This works:
# LOAD IN INGREDIENT INSTANCES
for each in il:
    with open('Ingredients/{}.pkl'.format(each), 'rb') as f:
        globals()[each] = pickle.load(f)

For example, one ingredient is Aubergine:
print(Aubergine)

output:
Name:         Aubergine
Price:        £1.00
Portion Size: 1

However, this doesn't work:
# LOAD IN RECIPE INSTANCES
for each in rl:
    with open('Recipes/{}.pkl'.format(each.name), 'rb') as f:
        globals()[each] = pickle.load(f)

I can only assume that the issue stems from each.name being used for the file names of the recipes, whereas each is used for the ingredient file names. This is intentional, however, as the name attribute of the recipes is formatted for the end-user (i.e. contains white space etc.) I think this may be the issue, but I am not sure.
Both the ingredient and recipe classes use:
def __repr__(self):
    return self.name

For example:
I have a recipe class instance SausageAubergineRagu, for which self.name is 'Sausage & Aubergine Ragu', and this is inside the list rl. I have tried testing this individually:
input:
rl

output:
[Sausage & Aubergine Ragu]

So I believe that this code:
# LOAD IN RECIPE INSTANCES
for each in rl:
    with open('Recipes/{}.pkl'.format(each.name), 'rb') as f:
        globals()[each] = pickle.load(f)

...should result in this:
with open('Recipes/Sausage & Aubergine Ragu.pkl', 'rb') as f:
    globals()[SausageAubergineRagu] = pickle.load(f)

But attempting to access the recipe class instances results in a NameError.
One final note - please don't ask why I am doing things this way. Instead help me to address and solve the problem, so I can make it work, and understand what is going on. Appreciated :)

A: The NameError you are getting is Python telling you that you are trying to use a variable that hasn't been defined yet.
You aren't defining SausageAubergineRagu before you use it in this line:
globals()[SausageAubergineRagu] = pickle.load(f)

In your first example, you are adding keys and values to globals.  You are using instances of recipes (each) as keys, and the pickled data as values.
In your second example, you are attempting to do the same thing, but instead of using instances of recipes (each) as keys, you are using SausageAubergineRagu, which is undefined.
How is Python supposed to know what SausageAubergineRagu is?  If you want that line to work, you will need to define it first, or use something that is already defined, like each, which is what you do in your other snippet.
Honestly, using instances of custom classes as keys in globals seems bizarre to me anyway (usually people use strings), but since you apparently want to make it work, the answer is simple:
Define SausageAubergineRagu before attempting to use it as a key in a dictionary.


text:
Q: Save DB query into an array and group all entries of user_id into one array entry I currently have a database with a user entry TABLE - where I query out something like:
user_id: 1
user_point: 20

user_id: 1
user_point: 50

user_id: 2
user_point: 10

This data is saved into an array, which looks like this:
$highscoreData = array();

while ($row = mysql_fetch_assoc($res))
{
  $highscoreData []= (object) array(
     "user_id" => $row['user_id'],
     "username" => $row['username'],
     "user_firstname" => $row['user_firstname'],
     "user_lastname" => $row['user_lastname'],
     "user_point" => $row['user_point']
  );
}
$feedback = $highscoreData;

*

*How do I save my array where I GROUP entries based on user_id , so that that user_id = 1 will only appear once in the array with a related added up user_point - which in this case would equal to "70 points"?

*And how do I afterwards sort the array, so that the user_id with highest number of user_point will line up first in the array?
For question 1 - I figured to do something like a for loop:
for( var i = 0; i < highscoreData.length; i++ ){
  //check if user_id = user_id - then perhaps save into a new array?
}

For question 2 - looked at usort() - but not totally sure how to use it in this context
Any help, examples would be truly appreciated!

A: Use it: I could not describe in detail for time limitation
<?php

$highscoreData []= (object) array(
     "user_id" => 1,
     "username" => 'name1',
     "user_firstname" => "First Name 1",
     "user_lastname" => "Last Name 1",
     "user_point" => 20
  );

 $highscoreData []= (object) array(
     "user_id" => 1,
     "username" => 'name1',
     "user_firstname" => "First Name 1",
     "user_lastname" => "Last Name 1",
     "user_point" => 50
  );

$highscoreData []= (object) array(
     "user_id" => 2,
     "username" => 'name2',
     "user_firstname" => "First Name 2",
     "user_lastname" => "Last Name 2",
     "user_point" => 80
  );

$user_point_sum = array();
$users = array();
foreach($highscoreData as $array) {
  //check if user_id = user_id - then perhaps save into a new array?
  $user_id = $array->user_id;
  $username = $array->username;
  $user_firstname = $array->user_firstname;
  $user_lastname = $array->user_lastname;
  $user_point = $array->user_point;

  if(!isset($user_point_sum[$user_id])) {

     $user_point_sum[$user_id] = 0;

     $user_info = new stdClass();
     $user_info->user_id = $user_id;
     $user_info->username = $username;
     $user_info->user_firstname = $user_firstname;
     $user_info->user_lastname = $user_lastname;
     $users[$user_id] = $user_info;
  }
  $user_point_sum[$user_id] += $user_point;
}

arsort($user_point_sum);

$array_object = array();
foreach($user_point_sum as $user_id=>$user_point) {

    $object = new stdClass();

    $object->user_id = $user_id;
    $object->username = $users[$user_id]->username;
    $object->user_firstname = $users[$user_id]->user_firstname;
    $object->user_lastname = $users[$user_id]->user_lastname;
    $object->user_point = $user_point;

    $array_object[] = $object;
}

var_dump($array_object);

?>

Output:

array
  0 =>
    object(stdClass)[6]
      public 'user_id' => int 2
      public 'username' => string 'name2' (length=5)
      public 'user_firstname' => string 'First Name 2' (length=12)
      public 'user_lastname' => string 'Last Name 2' (length=11)
      public 'user_point' => int 80
  1 =>
    object(stdClass)[7]
      public 'user_id' => int 1
      public 'username' => string 'name1' (length=5)
      public 'user_firstname' => string 'First Name 1' (length=12)
      public 'user_lastname' => string 'Last Name 1' (length=11)
      public 'user_point' => int 70


text:
Q: msyql database selection based on if else statement and php variables Having trouble with getting this to work and the syntax - I have never done anything like this before and didn't write some of the original stuff.  I have a url that passes two variables.  I then GET those variables in the page. I then want to select which mysql db I connect to based on one of these variables.
Variable:
$account_id=$_GET["reference"];

It then chooses which db to connect to:
$link = mysql_connect('connect', 'user', 'pass');
if (!$link) {
     die('Not connected : ' . mysql_error());
 }

if ($item = "A"){
     $db_selected = mysql_select_db('A', $link);
     } elseif ($item = "B") {
    $db_selected = mysql_select_db('B', $link);
    } elseif (!$db_selected) {
    die ('Can\'t use foo : ' . mysql_error());
 }

It is consistently choosing item A.  I cannot get it to choose B or give an error. Where am I going wrong?

A: use == instead of =
if ($item == "A"){
     $db_selected = mysql_select_db('A', $link);
     } elseif ($item == "B") {
    $db_selected = mysql_select_db('B', $link);
    } elseif (!$db_selected) {
    die ('Can\'t use foo : ' . mysql_error());
 }

A: When comparing values for logic operations, you must use >, <, ==, ===, !=, or !==. You are using a single equals sign, which is not for comparison but for assignment.
This is what you are doing
$item = 'b';          // a single equals sign assigns a value
if ($item = 'a') {    // so in this line, we are not comparing but assigning!
    echo 'Item is a'; // this line will always be reached
} else {
    echo 'Item is b'; // this line will NEVER be reached
}
echo 'Item = '.$item; // will ALWAYS read "Item = a"

This is what you meant to do
$item = 'b';           // a single equals sign assigns a value
if ($item == 'a') {    // double-equals compares value, with type juggling
    echo 'Item is a';
} else {
    echo 'Item is b';  // now this line will be reached, because item != 'a'
}
echo 'Item = '.$item;  // will read "Item = b"

`==`  - value is equal, not necessarily the same type (1 == "1")
`!=`  - value is not equal, may or may not be the same type (2 != "3")
`===` - value is equal AND the same type (1 === 1)
`!==` - value is not the same type, or not the same value (2 !== "2")

Documentation

*

*PHP Comparison operators: http://php.net/manual/language.operators.comparison.php


text:
Q: How can i generate a 3d textures from regular cell grid for volume rendering? I need to generate a visualization of an object, for this, I plan to use a GPU ray casting technique. The information of this object is described in two txt files. One file describes the structure of this object through a regular cell grid, and the other file has the information about intensity for each cell in the grid.
The grid is described by a list of x,y,z float point in cartesian axes, which form the cells, and the second file is simply a list o float that describes the intensity for each cell.
How can I generate a 3d texture with these files for later create a volume visualization witch "volume ray casting"?
[Edit1 by Spektre]
Here sample input file:
1
0
0
0
1 1 1
32 32 32
-1.495980e+14
-1.402481e+14
-1.308982e+14
-1.215484e+14
-1.121985e+14
-1.028486e+14
-9.349875e+13
-8.414888e+13
-7.479900e+13
-6.544912e+13
-5.609925e+13
-4.674938e+13
-3.739950e+13
-2.804962e+13
-1.869975e+13
-9.349875e+12
 0.000000e+00
 9.349875e+12
 1.869975e+13
 2.804962e+13
 3.739950e+13
 4.674938e+13
 5.609925e+13
 6.544912e+13
 7.479900e+13
 8.414888e+13
 9.349875e+13
 1.028486e+14
 1.121985e+14
 1.215484e+14
 1.308982e+14
 1.402481e+14
 1.495980e+14
-1.495980e+14
-1.402481e+14
-1.308982e+14
-1.215484e+14
-1.121985e+14
-1.028486e+14
-9.349875e+13
-8.414888e+13
-7.479900e+13
-6.544912e+13
-5.609925e+13
-4.674938e+13
-3.739950e+13
-2.804962e+13
-1.869975e+13
-9.349875e+12
 0.000000e+00
 9.349875e+12
 1.869975e+13
 2.804962e+13
 3.739950e+13
 4.674938e+13
 5.609925e+13
 6.544912e+13
 7.479900e+13
 8.414888e+13
 9.349875e+13
 1.028486e+14
 1.121985e+14
 1.215484e+14
 1.308982e+14
 1.402481e+14
 1.495980e+14
-1.495980e+14
-1.402481e+14
-1.308982e+14
-1.215484e+14
-1.121985e+14
-1.028486e+14
-9.349875e+13
-8.414888e+13
-7.479900e+13
-6.544912e+13
-5.609925e+13
-4.674938e+13
-3.739950e+13
-2.804962e+13
-1.869975e+13
-9.349875e+12
 0.000000e+00
 9.349875e+12
 1.869975e+13
 2.804962e+13
 3.739950e+13
 4.674938e+13
 5.609925e+13
 6.544912e+13
 7.479900e+13
 8.414888e+13
 9.349875e+13
 1.028486e+14
 1.121985e+14
 1.215484e+14
 1.308982e+14
 1.402481e+14
 1.495980e+14

And file format info:
For a regular grid, without grid refinement, the amr grid.inp looks like:

iformat <=== Typically 1 at present 0 <=== Grid style (regular = 0)
  coordsystem gridinfo incl_x incl_y incl_z nx ny nz
xi[1] xi[2] xi[3] .....… xi[nx+1]
yi[1] yi[2] yi[3] .....… yi[ny+1]
zi[1] zi[2] zi[3] .....… zi[nz+1]
The meaning of the entries are:
iformat: The format number, at present 1. For unformatted files this
  must be 4-byte integer.
coordsystem: If coordsystem <100 the coordinate system is cartesian.
  If 100<= coordsystem <200 the coordinate system is spherical (polar).
  If 200<= coordsystem <300 the coordinate system is cylindrical.For
  unformatted files this must be 4-byte integer.
gridinfo: If gridinfo ==1 there will be abundant grid information
  written into this file, possibly useful for post-processing routines.
  Typically this is redundant information, so it is advised to set
  gridinfo =0 to save disk space. In the following we will assume that
  gridinfo =0. For unformatted files this must be 4-byte integer.
incl x, incl y, incl z: These are either 0 or 1. If 0 then this
  dimension is not active (so upon grid refinement no refinement in this
  dimension is done). If 1 this dimension is fully active, even if the
  number of base grid cells in this direction is just 1. Upon refinement
  the cell will also be splitted in this dimension. For unformatted
  files these numbers must be 4-byte integer.
nx, ny, nz: These are the number of grid cells on the base grid in
  each of these dimensions. For unformatted files these numbers must be
  4-byte integer.
xi[1] ... xi[nx+1]: The edges of the cells of the base grid in
  x-direction. For nx grid cells we have nx+1 cell walls, hence nx+1
  cell wall positions. For unformatted files these numbers must be
  8-byte reals (=doubleprecision).
yi[1] ... yi[ny+1]: Same as above, but now for y-direction.
zi[1] ... zi[nz+1]: Same as above, but now for z-direction.
Example of a simple 2x2x2 regular grid in cartesian coordinates: 1 0 1
  0 1 1 1 2 2 2
  -1. 0. 1.
  -1. 0. 1.
  -1. 0. 1.

A: was curious and based on your sample grid this is what I come up with:
//---------------------------------------------------------------------------
//--- AMR class ver: 1.000 --------------------------------------------------
//---------------------------------------------------------------------------
#ifndef _amr_grid_h
#define _amr_grid_h
//---------------------------------------------------------------------------
#include "gl\OpenGL3D_double.cpp"
//---------------------------------------------------------------------------
// https://stackoverflow.com/q/55319835/2521214
//---------------------------------------------------------------------------
class amr_grid
    {
public:
    // BVH file
    int iformat;        // 0,1
    int gridstyle;      // 0 regular
    int coordsystem;    // <0,100) cartesian, <100<200) spherical/polar, <200,300) cylindrical
    int gridinfo;       // 0:  1: additional info added to file
    int en[3];          // enable x,y,z?
    int sz[3];          // size of grid [cells]
    List<double> p[3];  // walls per dimension
    // misc
    double min[3],max[3];   // BBOX
    double dl;              // avg cell size

    amr_grid(){ reset(); }
    amr_grid(amr_grid& a)   { *this=a; }
    ~amr_grid(){}
    amr_grid* operator = (const amr_grid *a) { *this=*a; return this; }
    //bvh* operator = (const bvh &a) { ...copy... return this; }
    // render/set/load
    void reset();               // clear whole skeleton data
    void draw();                // render actual set frame
    void load(AnsiString name); // load from AMR grid file
    };
//---------------------------------------------------------------------------
void amr_grid::reset()
    {
    iformat=1;
    gridstyle=0;
    coordsystem=0;
    gridinfo=0;
    en[0]=1; sz[0]=0;   p[0].num=0; min[0]=0.0; max[0]=0.0;
    en[1]=1; sz[1]=0;   p[1].num=0; min[1]=0.0; max[1]=0.0;
    en[2]=1; sz[2]=0;   p[2].num=0; min[2]=0.0; max[2]=0.0;
    dl=0.0;
    }
//---------------------------------------------------------------------------
void amr_grid::draw()
    {
    int i,x,y,z;

    glColor3f(0.0,1.0,0.5);
    glBegin(GL_LINES);

    if ((gridstyle>=0)&&(gridstyle<100))    // cartesian
        {
        if ((en[0])&&(en[1])&&(en[2]))      // 3D
            {
            for (x=0;x<=sz[0];x++)
             for (y=0;y<=sz[1];y++)
                {
                glVertex3d(p[0][x],p[1][y],min[2]);
                glVertex3d(p[0][x],p[1][y],max[2]);
                }
            for (x=0;x<=sz[0];x++)
             for (z=0;z<=sz[2];z++)
                {
                glVertex3d(p[0][x],min[1],p[2][z]);
                glVertex3d(p[0][x],max[1],p[2][z]);
                }
            for (y=0;y<=sz[1];y++)
             for (z=0;z<=sz[2];z++)
                {
                glVertex3d(min[0],p[1][y],p[2][z]);
                glVertex3d(max[0],p[1][y],p[2][z]);
                }
            }
        }

    glEnd();
    }
//---------------------------------------------------------------------------
void amr_grid::load(AnsiString name)
    {
    int hnd,siz,adr,i,j,k;
    AnsiString lin,s;
    BYTE *txt=NULL;
    reset();
    // file -> memory
    hnd=FileOpen(name,fmOpenRead);
    if (hnd<0) return;
    siz=FileSeek(hnd,0,2);
        FileSeek(hnd,0,0);
    txt=new BYTE[siz];
    if (txt==NULL) { FileClose(hnd); return; }
    siz=FileRead(hnd,txt,siz);
    FileClose(hnd);
    // memory -> amr_grid data
    adr=0;
    iformat=str2int(txt_load_lin(txt,siz,adr,true));
    gridstyle=str2int(txt_load_lin(txt,siz,adr,true));
    coordsystem=str2int(txt_load_lin(txt,siz,adr,true));
    gridinfo=str2int(txt_load_lin(txt,siz,adr,true));
    lin=txt_load_lin(txt,siz,adr,true); i=1; for (j=0;j<3;j++) en[j]=str2num(str_load_str(lin,i,true));
    lin=txt_load_lin(txt,siz,adr,true); i=1; for (j=0;j<3;j++) sz[j]=str2num(str_load_str(lin,i,true));
    for (j=0;j<3;j++) for (p[j].num=0,i=0;i<=sz[j];i++) p[j].add(str2num(txt_load_str(txt,siz,adr,true)));
    // BBOX
    for (j=0;j<3;j++) for (min[j]=max[j]=p[j][0],i=0;i<=sz[j];i++)
        {
        if (min[j]>p[j][i]) min[j]=p[j][i];
        if (max[j]<p[j][i]) max[j]=p[j][i];
        }
    double q[3];
    vector_sub(q,max,min);
    dl=3.0*vector_len(q)/double(sz[0]+sz[1]+sz[2]);
    }
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------

This just loads and draws the grid. However I expect you got the 3D texture file containing the cells intensities so simply use that as a color for a box and change the draw routine that will render cells as a box with color from your texture. the corner points of a box for any cell are 8 combination of these coordinates:
x: p[0][i],p[0][i+1]
y: p[1][i],p[1][i+1]
z: p[2][i],p[2][i+1]

you can adapt mine glBox (beware its float but code above uses double ...):
void glBox(GLfloat x0,GLfloat y0,GLfloat z0,GLfloat xs,GLfloat ys,GLfloat zs)
    {
    xs*=0.5;
    ys*=0.5;
    zs*=0.5;
    glBegin(GL_QUADS);

    glNormal3f(+1.0,0.0,0.0);
    glVertex3f(x0+xs,y0-ys,z0-zs);
    glVertex3f(x0+xs,y0+ys,z0-zs);
    glVertex3f(x0+xs,y0+ys,z0+zs);
    glVertex3f(x0+xs,y0-ys,z0+zs);

    glNormal3f(-1.0,0.0,0.0);
    glVertex3f(x0-xs,y0-ys,z0+zs);
    glVertex3f(x0-xs,y0+ys,z0+zs);
    glVertex3f(x0-xs,y0+ys,z0-zs);
    glVertex3f(x0-xs,y0-ys,z0-zs);

    glNormal3f(0.0,+1.0,0.0);
    glVertex3f(x0-xs,y0+ys,z0+zs);
    glVertex3f(x0+xs,y0+ys,z0+zs);
    glVertex3f(x0+xs,y0+ys,z0-zs);
    glVertex3f(x0-xs,y0+ys,z0-zs);

    glNormal3f(0.0,-1.0,0.0);
    glVertex3f(x0-xs,y0-ys,z0-zs);
    glVertex3f(x0+xs,y0-ys,z0-zs);
    glVertex3f(x0+xs,y0-ys,z0+zs);
    glVertex3f(x0-xs,y0-ys,z0+zs);

    glNormal3f(0.0,0.0,+1.0);
    glVertex3f(x0+xs,y0-ys,z0+zs);
    glVertex3f(x0+xs,y0+ys,z0+zs);
    glVertex3f(x0-xs,y0+ys,z0+zs);
    glVertex3f(x0-xs,y0-ys,z0+zs);

    glNormal3f(0.0,0.0,-1.0);
    glVertex3f(x0-xs,y0-ys,z0-zs);
    glVertex3f(x0-xs,y0+ys,z0-zs);
    glVertex3f(x0+xs,y0+ys,z0-zs);
    glVertex3f(x0+xs,y0-ys,z0-zs);

    glEnd();
    }

to x0,y0,z0,x1,y1,z1 form or write an VBO or whatever ...
PS.
I also use mine dynamic list template so:
List<double> xxx; is the same as double xxx[];
xxx.add(5); adds 5 to end of the list
xxx[7] access array element (safe)
xxx.dat[7] access array element (unsafe but fast direct access)
xxx.num is the actual used size of the array
xxx.reset() clears the array and set xxx.num=0
xxx.allocate(100) preallocate space for 100 items
and the C++ code is VCL based so you need to rewrite AnsiString to string type you got at your disposal. Also I used mine own string routines for loading lines,string and converting to numbers so you need to port that too but I assume you already got a loader ...
btw this is the output for the simple sample file in the fileformat description:


text:
Q: I want to see "redirecting you to the login page" when a user successfully registers on my website. How can i do this? This is a php question. Here's my code for inserting data into my database:
$con=mysql_connect("localhost","root","");
if(!$con){
die('Could not connect:' .mysql_error());
}

echo "Connected successfully.";

$database=mysql_select_db('90210store');

if(!$database){
die('
Could not select database:' .mysql_error());
}

echo "
Database successfully selected";

$FirstName=$_POST['FirstName']; //to get the information written in the form
$LastName=$_POST['LastName'];
$EmailAdd=$_POST['EmailAdd'];
$check_list=$_POST['check_list'];
$dob=$_POST['dob'];
$Gender=$_POST['gender'];
$Password=$_POST['Password'];

$first= "INSERT INTO login
(FirstName,LastName,EmailAdd,Newsletter,DOB,Gender,Password)
VALUES ('$FirstName','$LastName','$EmailAdd','$check_list','$dob','$Gender','$Password')";

$result=mysql_query($first);

if($result){
echo('
Data entered successfully');
}

else{
echo('
Fail');
}

if($result)
{
header('Location: phpredirectlogin.php');
}
mysql_close($con);

?>

I tried to redirect the user to the page phpredirectlogin.php so as to have "redirecting you to the login page" written on the page and then redirecting him to the login page but i'm not being able to find a way to do it. Here's the code for the phpredirectlogin.php page:
<?
echo ('Redirecting you to the login page');

header('Location:account.html');

?>

It redirects the user to the login page directly without showing "redirecting you to the login page". Can someone tell me how to do this? Thank you and sorry for my English.

A: That is not possible ..
You cannot display something and do a redirect at the same time , you will only be redirected and you will not be able to see that message.
You can use native Javascript alert with its redirect.
<?php
echo "";
echo "";

A: Like @ShankarDamodaran has said, you need to use of something more in PHP. But you can also make use of this HTML tag where you can specify the time duration before it redirects:
echo '<meta http-equiv="refresh" content="3; url=phpredirectlogin.php">';
The number 3 above specifies the page should be redirected after 3 seconds.


text:
Q: Trying to send mail alert for mysql how to send mail alert for MySQL?
can we send alerts when the MySQL has large number of connections, or MySQL is not responding properly. Can someone help me to solve this prolem ?

A: You can do this in a number of ways. SHOW FULL PROCESSLIST; query would give you information about the number of connections as well as the queries being executed by each connection(thread). A sample result is as follows.
mysql> SHOW FULL PROCESSLIST;
+------+------+--------------------+------+---------+------+-------+-----------------------+
| Id   | User | Host               | db   | Command | Time | State | Info                  |
+------+------+--------------------+------+---------+------+-------+-----------------------+
| 1298 | root | 192.168.1.76:37648 | NULL | Sleep   |    0 |       | NULL                  |
| 1491 | root | localhost          | NULL | Query   |    0 | init  | show full processlist |
+------+------+--------------------+------+---------+------+-------+-----------------------+

If you are only concerned with the number of current connection(threads) you can use the following query.
mysql> SHOW STATUS WHERE `variable_name` = 'Threads_connected';
+-------------------+-------+
| Variable_name     | Value |
+-------------------+-------+
| Threads_connected | 2     |
+-------------------+-------+

Now about the mail alerts, you can setup a cron job(shell script) to fire a mail alert as soon as the number of current connections exceed a certain limit. mail command can be used for this.
$ echo "Max MySQL Connections reached"| mail -s "your subject" your@email.com

Also, I came across a great MySQL Monitoring tool- MONyog. It would let you setup mail alerts for any of the MySQL variable.


text:
Q: sending push notification with firebase - FATAL EXCEPTION (android) First attempts at getting firebase push notifications to work isn't going so well. I have followed the tutorial listed here to set it up, but whenever I try and send a notification, the app "closes unexpecedly", and the logical throws the following crash information:
Logcat:
--------- beginning of crash
04-23 23:04:28.081 7395-7395/com.surfdogdesigns.pandsi E/AndroidRuntime: FATAL EXCEPTION: main
     Process: com.surfdogdesigns.pandsi, PID: 7395
     java.lang.RuntimeException: Unable to instantiate service com.surfdogdesigns.pandsi.MainActivity$MyFirebaseMessagingService: java.lang.InstantiationException: class com.surfdogdesigns.pandsi.MainActivity$MyFirebaseMessagingService has no zero argument constructor
         at android.app.ActivityThread.handleCreateService(ActivityThread.java:2746)
         at android.app.ActivityThread.access$1800(ActivityThread.java:151)
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1386)
         at android.os.Handler.dispatchMessage(Handler.java:102)
         at android.os.Looper.loop(Looper.java:135)
         at android.app.ActivityThread.main(ActivityThread.java:5254)
         at java.lang.reflect.Method.invoke(Native Method)
         at java.lang.reflect.Method.invoke(Method.java:372)
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
      Caused by: java.lang.InstantiationException: class com.surfdogdesigns.pandsi.MainActivity$MyFirebaseMessagingService has no zero argument constructor
         at java.lang.Class.newInstance(Class.java:1597)
         at android.app.ActivityThread.handleCreateService(ActivityThread.java:2743)
         at android.app.ActivityThread.access$1800(ActivityThread.java:151)
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1386)
         at android.os.Handler.dispatchMessage(Handler.java:102)
         at android.os.Looper.loop(Looper.java:135)
         at android.app.ActivityThread.main(ActivityThread.java:5254)
         at java.lang.reflect.Method.invoke(Native Method)
         at java.lang.reflect.Method.invoke(Method.java:372)
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
      Caused by: java.lang.NoSuchMethodException: <init> []
         at java.lang.Class.getConstructor(Class.java:531)
         at java.lang.Class.getDeclaredConstructor(Class.java:510)
         at java.lang.Class.newInstance(Class.java:1595)
         at android.app.ActivityThread.handleCreateService(ActivityThread.java:2743)
         at android.app.ActivityThread.access$1800(ActivityThread.java:151)
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1386)
         at android.os.Handler.dispatchMessage(Handler.java:102)
         at android.os.Looper.loop(Looper.java:135)
         at android.app.ActivityThread.main(ActivityThread.java:5254)
         at java.lang.reflect.Method.invoke(Native Method)
         at java.lang.reflect.Method.invoke(Method.java:372)
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
04-23 23:04:28.082 1543-1559/system_process W/ActivityManager:   Force finishing activity 1 com.surfdogdesigns.pandsi/.MainActivity
04-23 23:04:28.093 1164-1164/? E/EGL_emulation: tid 1164: eglCreateSyncKHR(1299): error 0x3004 (EGL_BAD_ATTRIBUTE)
04-23 23:04:28.211 1543-1599/system_process I/OpenGLRenderer: Initialized EGL, version 1.4
04-23 23:04:28.225 1174-1724/? E/Drm: Failed to find drm plugin
04-23 23:04:28.226 2728-6161/com.google.android.gms.unstable W/DG.WV: Widevine DRM not supported on this device
                                                                      android.media.UnsupportedSchemeException: Failed to instantiate drm object.
                                                                          at android.media.MediaDrm.native_setup(Native Method)
                                                                          at android.media.MediaDrm.<init>(MediaDrm.java:180)
                                                                          at ono.a(:com.google.android.gms:122)
                                                                          at okh.run(:com.google.android.gms:1095)
                                                                          at lmq.run(:com.google.android.gms:450)
                                                                          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                          at lra.run(:com.google.android.gms:17)
                                                                          at java.lang.Thread.run(Thread.java:818)
04-23 23:04:28.661 1543-1564/system_process W/ActivityManager: Activity pause timeout for ActivityRecord{cb0d51e u0 com.surfdogdesigns.pandsi/.MainActivity t31 f}
04-23 23:04:29.521 1828-2091/com.google.android.googlequicksearchbox W/OpenGLRenderer: Incorrectly called buildLayer on View: aep, destroying layer...
04-23 23:04:29.633 3034-6156/com.google.android.gms.persistent W/GLSUser: [AppCertManager] IOException while requesting key:
                                                                          java.io.IOException: Invalid device key response.
                                                                              at ewg.a(:com.google.android.gms:274)
                                                                              at ewg.a(:com.google.android.gms:4238)
                                                                              at ewf.a(:com.google.android.gms:45)
                                                                              at evz.a(:com.google.android.gms:50)
                                                                              at evy.a(:com.google.android.gms:104)
                                                                              at com.google.android.gms.auth.account.be.legacy.AuthCronChimeraService.b(:com.google.android.gms:4049)
                                                                              at edi.call(:com.google.android.gms:2041)
                                                                              at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                              at lmq.run(:com.google.android.gms:450)
                                                                              at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                              at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                              at lra.run(:com.google.android.gms:17)
                                                                              at java.lang.Thread.run(Thread.java:818)
04-23 23:04:29.693 1646-1646/com.android.systemui W/ResourceType: No package identifier when getting value for resource number 0x00000000
04-23 23:04:29.694 1646-1646/com.android.systemui W/PackageManager: Failure retrieving resources for com.surfdogdesigns.pandsi: Resource ID #0x0
04-23 23:04:33.229 2285-7929/com.google.android.gms W/PlatformStatsUtil: Could not retrieve Usage & Diagnostics setting. Giving up.
04-23 23:04:34.372 2285-2299/com.google.android.gms W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/data/com.google.android.gms/databases/metrics.db' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
04-23 23:04:34.380 2285-2299/com.google.android.gms W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/data/com.google.android.gms/databases/help_responses.db.18' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
04-23 23:04:34.388 2285-2299/com.google.android.gms W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/data/com.google.android.gms/databases/auto_complete_suggestions.db' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
04-23 23:04:39.325 1543-1564/system_process W/ActivityManager: Activity destroy timeout for ActivityRecord{cb0d51e u0 com.surfdogdesigns.pandsi/.MainActivity t31 f}
04-23 23:04:42.527 8148-8148/? D/AndroidRuntime: >>>>>> START com.android.internal.os.RuntimeInit uid 0 <<<<<<
04-23 23:04:42.532 8148-8148/? D/AndroidRuntime: CheckJNI is ON
04-23 23:04:42.561 8148-8148/? E/memtrack: Couldn't load memtrack module (No such file or directory)
04-23 23:04:42.561 8148-8148/? E/android.os.Debug: failed to load memtrack module: -2
04-23 23:04:42.574 8148-8148/? D/AndroidRuntime: Calling main entry com.android.commands.am.Am
04-23 23:04:42.579 1543-1560/system_process I/ActivityManager: Force stopping com.surfdogdesigns.pandsi appid=10058 user=0: from pid 8148
04-23 23:04:42.579 1543-1560/system_process I/ActivityManager: Killing 7395:com.surfdogdesigns.pandsi/u0a58 (adj 0): stop com.surfdogdesigns.pandsi
04-23 23:04:42.580 1543-1560/system_process W/libprocessgroup: failed to open /acct/uid_10058/pid_7395/cgroup.procs: No such file or directory
04-23 23:04:42.588 1543-1560/system_process W/ActivityManager: Scheduling restart of crashed service com.surfdogdesigns.pandsi/.MainActivity$MyFirebaseMessagingService in 29020ms
04-23 23:04:42.588 1543-1560/system_process I/ActivityManager:   Force stopping service ServiceRecord{2a3bed30 u0 com.surfdogdesigns.pandsi/.MainActivity$MyFirebaseMessagingService}
04-23 23:04:42.599 1543-1811/system_process I/ActivityManager: Killing 2654:com.android.settings/1000 (adj 15): empty #17
04-23 23:04:42.599 1543-1811/system_process W/libprocessgroup: failed to open /acct/uid_1000/pid_2654/cgroup.procs: No such file or directory
04-23 23:04:42.600 8148-8148/? D/AndroidRuntime: Shutting down VM
04-23 23:04:42.608 1543-1560/system_process W/InputMethodManagerService: Got RemoteException sending setActive(false) notification to pid 7395 uid 10058
04-23 23:04:42.625 2004-8160/com.google.android.googlequicksearchbox:search I/HotwordRecognitionRnr: Starting hotword detection.
04-23 23:04:42.627 2004-8159/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_starting gzi@cc534c0
04-23 23:04:42.636 1174-1542/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000
04-23 23:04:42.654 1174-8162/? I/AudioFlinger: AudioFlinger's thread 0xb5d99000 ready to run
04-23 23:04:42.663 2004-8159/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_started gzi@cc534c0
04-23 23:04:42.670 2004-2004/com.google.android.googlequicksearchbox:search I/HotwordWorker: onReady
04-23 23:04:42.750 2285-8164/com.google.android.gms W/IcingInternalCorpora: getNumBytesRead when not calculated.
04-23 23:04:42.812 2285-2425/com.google.android.gms I/Icing: Usage reports 0 indexed 0 rejected 0 imm upload true

Main Activity:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class MainActivity extends AppCompatActivity {

    public MainActivity() {

    }
    public class MyFirebaseMessagingService extends FirebaseMessagingService {
        private static final String TAG = "FCM Service";
        @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
            //
            //TODO: Handle FCM messages here.
            //If the application is in the foreground handle both data and notification messages here.
            //Also if you intend on generating your own notifications as a result of a received FCM
            //message, here is where that should be initiated.
            //
            Log.d(TAG, "From: " + remoteMessage.getFrom());
            Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
        }
    }

    public class FirebaseIDService extends FirebaseInstanceIdService {
        private static final String TAG = "FirebaseIDService";

        @Override
        public void onTokenRefresh() {
            // Get updated InstanceID token.
            String refreshedToken = FirebaseInstanceId.getInstance().getToken();
            Log.d(TAG, "Refreshed token: " + refreshedToken);

            // TODO: Implement this method to send any registration to your app's servers.
            sendRegistrationToServer(refreshedToken);
        }

        /**
         * Persist token to third-party servers.
         *
         * Modify this method to associate the user's FCM InstanceID token with any server-side account
         * maintained by your application.
         *
         * @param token The new token.
         */
        private void sendRegistrationToServer(String token) {
            // Add custom implementation, as needed.
        }
    }

Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.surfdogdesigns.pandsi">
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"

        >
        <activity android:name=".MainActivity">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>

        <service android:name=".MainActivity$MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>

        <service android:name=".MainActivity$FirebaseIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>

    </application>

</manifest>

Can anybody see what is going wrong? And how to fix it?

A: You need to add the empty constructor in the class MyFirebaseMessagingService
public MyFirebaseMessagingService() {
    super("MyFirebaseMessagingService");
}

For explanation, you can see the details here

A: I haven't tested it, but I suspect that your services cannot be inner classes of MainActivity.  It would be safer, and may be required, to declare them as non-nested classes, as is done in the sample project:
MyFirebaseInstanceIDService
MyFirebaseMessagingService
It's also possible that the services can be nested classes of MainActivity if you declare them as static nested classes:
public static class MyFirebaseMessagingService...

A: check if you have different version with dependency implementation
implementation 'com.google.android.gms:play-services-gcm:+'
implementation 'com.google.firebase:firebase-core:+'
implementation 'com.google.firebase:firebase-messaging:+'


text:
Q: A surge of controller errors on \Device\Ide\IdePort0 I made a clean reinstall of my computer yesterday after I seemed to have hard-drive problems.
Now it seems they have returned. My computer freezes for a few seconds every few minutes. I checked the Event log and discovered there was a surge of errors with the following characteristics:

*

*Level: Error

*Source: atapi

*"The driver detected a controller error on \Device\Ide\IdePort0."

*Binary Data:0000: 00100000 00000001 00000000 C004000B
0008: 00000004 C0000185 00000000 00000000
0010: 00000000 00000000 00000000 00000000
0018: 00000000 00001005

How can I diagnose the problem?
I suspect my 1.5TB drive, but how can I confirm it? Currently I have 2 hard drives in my desktop - one is a brand new SSD and the other is the 1.5TB Western Digital "green" drive.
UPDATES

*

*I don't want to diagnose only which hard drive causes the problem, but also if it's a hard-drive problem, cable problem or chipset problem.

A: Disconnect the one hard drive you can and see if the errors stop. If they don't its the one plugged in, if they do its the one you unplugged.
.


text:
Q: Unable to Close Drop down menu on Outside click in LWC I am unable to close the dropdown menu in LWC on clicking anywhere else on the page apart from the dropdown menu  . Please find the code below ,
HTML Code :

                                User Profile
                                Service Terms & Conditions
                                Logout

Javascript Code :
 displayUser(e) {
    e.preventDefault();
    let displayStyle = this.template.querySelector("div.dropdown-menu").style
      .display;
    if (displayStyle === "none" || displayStyle === "") {
      this.template.querySelector("div.dropdown-menu").style.display = "block";
    } else {
      this.template.querySelector("div.dropdown-menu").style.display = "none";

    }
  }

Javscript Code I am trying to add for closing the above mentioned dropdown on outside click in ConnectedCallback() function :
connectedCallback() {
    window.addEventListener("mouseup" , (e) => {
      console.log("Into mouseup");
      let dropdown =  this.template.querySelector("div.dropdown-menu");
      if(e.target != dropdown && e.target.parentNode != dropdown) {
        console.log("Into If");
        dropdown.style.display = 'none';
      }
    });
}

Note : The above addEventListener Function is getting executed on all page clicks , but is not letting me open the dropdown itself as the If Function is getting executed for the Actual Dropdown anchor tag click as well which is preventing the dropdown from opening .
Please help regarding the same and let me know if u need any more details on the same.

A: To open the dropdown you've used an onclick handler. From your description the dropdown should disappear when clicking outside of that anchor element.
Handle an event when the anchor loses focus by adding onblur handler to the anchor. This event handler should perform the logic that hides the dropdown.
This solution on its own has drawbacks such as the anchor losing focus if you press TAB.


text:
Q: How to efficiently fill a list with ray multi-processing? I'm working on a project where I need to collect rollouts to fill a dataset and then train a model on it. I'd like to collect these rollouts in parallel to speed up the process so I'm trying to use the multi-processing provided by the ray library :
import time
import ray

ray.init()

@ray.remote
class MainActor:
    def __init__(self):
        self.data_set = []

    def process_item(self, item):
        # process incoming item
        item+=1
        return item

    def append(self, val):
        # add item to data set after processing it
        item = self.process_item(val)
        self.data_set.append(item)

    def train(self):
        # train on datatset
        return len(self.data_set)

main_actor = MainActor.remote()

@ray.remote
def rollout_collector(main_actor):
    t = time.time()
    for i in range(40000):
        main_actor.append.remote(i)
    print("time per rollout : ",time.time() - t)

t = time.time()
ray.get([rollout_collector.remote(main_actor) for i in range(3)])
ray.get(main_actor.train.remote())
print("total time with multi-processing: ",time.time() - t)

# ============================== Single process ================================

class MainActor:
    def __init__(self):
        self.data_set = []

    def process_item(self, item):
        # process incoming item
        item+=1
        return item

    def append(self, val):
        # add item to data set after processing it
        item = self.process_item(val)
        self.data_set.append(item)

    def train(self):
        # train on datatset
        pass

main_actor = MainActor()
t = time.time()
for i in range(120000):
    main_actor.append(i)
main_actor.train()
print("total time with single process : ",time.time() - t)

The rollout_collector collect items and then store them, after processing, inside the MainActor to finally train on it. However, this method is extremely slow :

Each rollout when using ray take as much as 20 sec compare to 0.12 sec without ray and multi-processing. I have one cpu for the main actor and 3 for the rollout_collectors.
I don't think I can store the rollouts inside the rollout_collector workers and then send everything to the main actor as I'm using reservoir sampling for the training. Furthermore, I get a really long execution time for a very simple function when using ray : the training function on MainActor juste return the length of the dataset but it still take 20 sec to execute.
So my question is Am I doing something wrong ? What would be the best way to achieve my goal ?

A: The cost of cross-process RPC (actor.append.remote(i)) is definitely going to be higher than modifying an in-process data structure (list.append(i)). The former involves serialization/deserialization, inter-process communication via system calls, and queueing since you are calling it from 3 concurrent worker processes. The reason actor.train.remote() took so long is probably also due to the 120K queued remote calls.
If realistically your rollout process takes more time, then multiprocessing should definitely speed things up. I added a time.sleep(0.01) delay to your rollout_collector and to the single-process loop at the end, reduced the number of rollouts to 400, then the multi-process version took 4.5 seconds to complete, vs. 13 seconds for the single-process version.
If your individual rollouts are very fast, consider batching the results locally in the worker process before sending them to the main actor.


text:
Q: How to pass data from a website to a botframework web chat bot? We are building a MS botframework bot that will be hosted on a website that we control.
Is there a way to pass a session ID from the host website to the web chat bot widget so that it is accessible when processing messages from within the bot?
If not, is it possible to access the 't' token parameter as described here  http://docs.botframework.com/connector/embed-chat-control/
Thanks

A: Currently there is no way to do this with the chat control.
If you want tighter integration you should consider using the DirectLIne API and build your own UX experience via that.

A: It's possible to retrieve conversationId, which is available in the Message in your bot. For that you should make POST request to https://webchat.botframework.com/api/conversations with header Authorization with value "BOTCONNECTOR {your secure code}"
You should receive new token and conversationId as a result or request. The token is used in iframe tag creation, conversationId can be used as your session token.

A: Using DirectLine and Backchannel might help you here. You'll find the info in the readme on this repo if you scroll to the last section. It allows Webchat and the host can send/receive whatever you want from each other.

The code given above is how i used it to send value x when the page with the bot is loaded.
I hope this helps :)


text:
Q: prove that $0.2(x-1)^5$ and $4x-6$ intersect each other exactly 3 times
Prove that $q(x) = 4x-6$ and $p(x) = 0.2(x-1)^5$ intersect each other exactly 3 times.

First we need that $p=q$.
Let $E(x) = 0.2(x-1)^5 - 4x + 6$.
$E(-2) <0, \quad E(1) > 0, \quad E(2) < 0, \quad E(3)>0$.
$E(x)$ is continuous for all $x$ therefore by Intermediate Value theorem there must be at least three $x$ such that $E(x) = 0$.
$E(x)$ is also differentiable for all $x$. By Rolle theorem if there were 4 or more roots to $E(x)$ then $E'(x)$ should have at least 3 roots.
$E'(x) = (x-1)^4 - 4$.
The only time $E'(x)=0$ is when $(x-1)^4 - 4 = 0$
$(x-1)^4 = 4$
$\sqrt[4]{(x-1)^4} = \sqrt[4]4$
$x-1=\sqrt[4]4$
$x = \sqrt[4]4 + 1$
Therefore $E'(x)$ has only one root $\Rightarrow E(x)$ has only 3 roots $\Rightarrow p$ intersects $q$ only three times.
Please let me know if my solution is correct, specifically the part with solving $(x-1)^4 = 4$.

A: Your proof on the whole seems fine. The only issue I see is that you conclude there is only $1$ root of the derivative whereas there are actually 2, namely:
$$
x = 1 \pm \sqrt 2
$$
Int there are still less than 3 roots, your proof is still valid; it is just a tiny detail you missed. Other than that your proof seems sound.

A: You can apply the function $\sqrt[4]{\cdot}$ only on $\mathbb{R}^+$, which explains where is hidden the missing root. The correct computation of the roots of $E'$ would be
\begin{align*}E'(x)=0\iff (x-1)^4=4&\iff (x-1)^2=2\text{ (here I can apply $\sqrt{\cdot}$ since $(x-1)^2\in\mathbb{R}^+$)}\\
&\iff x\in\{1-\sqrt{2},1+\sqrt2\}.\end{align*}
Then your conclusion is right.


text:
Q: Use LINQ to Convert a List to a List of Lists I have a list of values:
IList<V> values = { V1, V2, V3, V4, V5, V6, V7 };

I would like to convert the list into a list of lists, where each sub-list is a specified size. The size of each sub-list could vary.  For example:
IList<IList<V>> values_size2 = { { V1, V2 }, { V3, V4 }, { V5, V6 }, { V7 } };
IList<IList<V>> values_size3 = { { V1, V2, V3 }, { V4, V5, V6 }, { V7 } };
IList<IList<V>> values_size4 = { { V1, V2, V3, V4 }, { V5, V6, V7 } };

I could probably do this pretty easily using nested loops, but was wondering if there was a clever way to do this using LINQ?
My initial thought would be to use the Aggregate method somehow, but nothing comes to mind right away.
Thanks.

A: Here is a generic IEnumerable based Batch function.  You can just change the return type from IEnumerable<IEnumerable<T>> to IEnumerable<IList<T>> with no other changes (since in my implementation it's already a list.  To change the whole thing to return a list of lists you'd need to either call `ToList on the result, or make a more involved refactor.
Note that technically this isn't using LINQ, it's just creating a new method that uses the same style and patterns commonly used by LINQ.
public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> source
    , int batchSize)
{
    //TODO validate parameters

    List<T> buffer = new List<T>();

    foreach (T item in source)
    {
        buffer.Add(item);

        if (buffer.Count >= batchSize)
        {
            yield return buffer;
            buffer = new List<T>();
        }
    }
    if (buffer.Count >= 0)
    {
        yield return buffer;
    }
}

A: You can use MoreLINQ Batch extension (available from Nuget):
IList<IList<V>> values_size2 = values.Batch(2);
IList<IList<V>> values_size3 = values.Batch(3);
IList<IList<V>> values_size4 = values.Batch(4);

Also you can view sources here.

A:  public static IEnumerable<IEnumerable<T>> Chunks<T>(this IEnumerable<T> source, int chunkSize)
 {
     while (source.Any())
     {
         yield return source.Take(chunkSize);
         source = source.Skip(chunkSize);
     }
 }

A: With .NET 6 you can use the new Chunk Linq method
List<IList<V>> values_size2 = values.Chunk(2).ToList();
List<IList<V>> values_size3 = values.Chunk(3).ToList();
List<IList<V>> values_size4 = values.Chunk(4).ToList();


text:
Q: How can I find out if the target path for each symbolic link in the current directory actually exists? When I look at the last column of output of ls -l I can see symbolic links and the target path of each symbolic link.  Is there a command or script I can write to capture the target path and check for its existence?

A: The following bash script will find all the links in the current directory and determine whether the target path exists:
for i in $(find . -type l -mindepth 1 -maxdepth 1); do
  links_to=$(readlink $i);
  echo -n "$i links to $links_to and that path ";
  if [[ -e $links_to ]]; then
    echo "exists";
  else
    echo "does not exist"
  fi
done;

Example directory:
$ ls -l
total 2
-rw-r--r--   1 user  staff     0 Sep 26 14:54 a_file
lrwxr-xr-x   1 user  staff    14 Sep 26 14:50 no_target -> does_not_exist
lrwxr-xr-x   1 user  staff    21 Aug 13 14:50 has_target -> a_file

Example output:
./no_target links to does_not_exist and that path does not exist
./sources links to a_file and that path exists

The key commands are using find to filter out anything that is not a link in the current directory, and readlink to determine the target of the link.
Note:
Some systems do not have the readlink command.
In that case, you might want to try adding the following bash function to the top:
my_readlink() { ls -ld "$1" | sed 's/.*-> //'; }

and change line 2 in the above script to call that function:
links_to=$(my_readlink $i)

but this is generally less desirable, since you are parsing output of ls -ld which is slower and more error-prone.

A: in bash this will print all symbolic links without target:
for f in $(find . -mount -type l)
do
  [ ! -e "$f" ] && echo "$f"
done