Java JScrollpane not visible

Question: I'm trying to display a series of buttons in a JScrollpane. Reading around, I managed to exit with this code, but nothing is displayed. I do not understand a possible mistake. Thank you for help
As suggested I made some changes, I edited but not works
EDITED
or I'm stupid, or here is some other problem. Here is my complete code with the output image
public class Main extends javax.swing.JFrame {
    private final JPanel gridPanel;

    public Main() {
        initComponents();
        // EXISTING PANEL
        gridPanel = new JPanel();
        JScrollPane scrollPane = new JScrollPane(gridPanel);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        JPanel borderLayoutPanel = new JPanel(new BorderLayout());
        borderLayoutPanel.add(scrollPane, BorderLayout.CENTER);

        this.Avvio();
    }

    private void Avvio() {
        JPanel pane = new JPanel(new GridBagLayout());
        pane.setBorder(BorderFactory.createLineBorder(Color.BLUE));
        pane.setLayout(new GridBagLayout());

        for (int i = 0; i < 10; i++) {
            JButton button;
            GridBagConstraints c = new GridBagConstraints();
            c.fill = GridBagConstraints.HORIZONTAL;
            c.anchor = GridBagConstraints.PAGE_START;

            button = new JButton("Button 1");
            c.weightx = 0.5;
            c.gridx = 0;
            c.gridy = i;
            pane.add(button, c);

            button = new JButton("Button 2");
            c.gridx = 1;
            c.gridy = i;
            pane.add(button, c);

            button = new JButton("Button 3");
            c.gridx = 2;
            c.gridy = i;
            pane.add(button, c);

        }
        gridPanel.add(pane);
        gridPanel.revalidate();
        gridPanel.repaint();

    }
}

Comment: Please read (and follow) the
[Java Naming Conventions](http://www.oracle.com/technetwork/java/codeconventions-135099.html) - methods start with a *lower case* letter and with a *verb* by any chance...
Comment: you never add the `borderLayoutPanel` to the frames content Pane.
Comment: Related to your edits and bounty, what you are trying to achieve is display a series of buttons divided in 3 cols and 10 rows? Along with a `JScrollPane` always visible? Do you have an image of what should be the output and / or clarify what is your question?
Comment: I can see the actual output, but what should be the expected output. No, you're not stupid, rather than that you're not explaining clearly what your problem is and / or what you're trying to achieve. That way we'll be able to help even more
Answer: Alright, from your comments in another answer:

No problem for compile , simply the Jpanel is empty. The buttons does not appear.

After calling this.Avvio(); you must call:
this.add(scrollPane);
this.pack();

This will produce the following outputs (before and after resizing it):

But there's still no JScrollPanel
This at least solves the first problem, however you have more errors in your code, some of which have already been commented in other answers:

You're extending JFrame, this isn't needed as you can create a JFrame instance / object and use it later. You're never changing the JFrame's behavior and that's why it's not needed to extend it. See Extends JFrame vs. creating it inside the program for more information about this.

You're not calling pack() nor setSize(...) this creates a tiny window, which you need to manually resize. Call pack() recommended before making your JFrame visible. (As suggested at the beginning of this answer).

You're calling .invokeLater() method twice. You need to call it just once, I prefer this way:
 SwingUtilities.invokeLater(() -> new Main()); //Note there is no call to .setVisible(true); as per point #1. It should go later in the program like:  frame.setVisible(true);

You're calling gridPanel.revalidate(); and gridPanel.repaint() while it doesn't affect your program, it's not needed as your GUI is still not visible, and thus those calls have no effect on your program, you can safely remove them.

You're creating a new GridBagConstraints object on each iteration of the for loop, you can just change its properties inside it and declaring it outside the for loop, which will make your program better.

After following the above recommendations, you can end up with a code like this one:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

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

public class Main {
    private final JPanel gridPanel;
    private JFrame frame;

    public Main() {
        // EXISTING PANEL
        gridPanel = new JPanel();
        JScrollPane scrollPane = new JScrollPane(gridPanel);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        JPanel borderLayoutPanel = new JPanel(new BorderLayout());
        borderLayoutPanel.add(scrollPane, BorderLayout.CENTER);

        this.Avvio();

        frame.add(scrollPane);
        frame.pack();
        frame.setVisible(true);
    }

    private void Avvio() {
        JPanel pane = new JPanel(new GridBagLayout());
        pane.setBorder(BorderFactory.createLineBorder(Color.BLUE));
        pane.setLayout(new GridBagLayout());

        for (int i = 0; i < 10; i++) {
            JButton button;
            GridBagConstraints c = new GridBagConstraints();
            c.fill = GridBagConstraints.HORIZONTAL;
            c.anchor = GridBagConstraints.PAGE_START;

            button = new JButton("Button 1");
            c.weightx = 0.5;
            c.gridx = 0;
            c.gridy = i;
            pane.add(button, c);

            button = new JButton("Button 2");
            c.gridx = 1;
            c.gridy = i;
            pane.add(button, c);

            button = new JButton("Button 3");
            c.gridx = 2;
            c.gridy = i;
            pane.add(button, c);

        }
        gridPanel.add(pane);
    }

    public static void main(String args[]) {
        /* Create and display the form */
        SwingUtilities.invokeLater(() -> {
            new Main();
        });
    }
}

Which still produces this output:

BUT... We still can improve it a little more!
We may have two nested for loops, for the GridBagConstraints properties as well as the generation of the buttons:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;

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

public class ScrollablePaneWithButtons {
    private static final int ROWS = 10;
    private static final int COLS = 3;

    private JFrame frame;
    private JPanel pane;
    private JButton[][] buttons;
    private GridBagConstraints gbc;
    private JScrollPane scroll;
    private JButton[] menuButtons;
    private JPanel menuPane;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new ScrollablePaneWithButtons()::createAndShowGui);
    }

    private void createAndShowGui() {
        frame = new JFrame(this.getClass().getSimpleName());

        pane = new JPanel();
        pane.setLayout(new GridBagLayout());

        menuPane = new JPanel();
        menuPane.setLayout(new GridLayout(1, 3));

        buttons = new JButton[ROWS][COLS];

        menuButtons = new JButton[] {new JButton("Edit"), new JButton("Delete"), new JButton("Sort Fields")};

        gbc = new GridBagConstraints();

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.anchor = GridBagConstraints.PAGE_START;
        gbc.weightx = 0.5;

        for (int i = 0; i < ROWS; i++) {
            for (int j = 0; j < COLS; j++) {
                buttons[i][j] = new JButton("Button " + (j + 1));

                gbc.gridx = j;
                gbc.gridy = i;

                pane.add(buttons[i][j], gbc);
            }
        }

        scroll = new JScrollPane(pane, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

        for (JButton b : menuButtons) {
            menuPane.add(b);
        }
        frame.add(scroll);
        frame.add(menuPane, BorderLayout.SOUTH);

        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

And this example is (in my opinion) easier to read and follow up. And this is the output the above code is generating:

You can still choose which code to use, either doing the modifications at the first part of this answer, the second one following the recommendations above or the last one which is shorter.
Comment: Friend, I'm forced to call Jframe, because I have other things ..... can I contact you in the chat?
Answer: Problems noted:

Avvio - the pane layout was reset during each loop.  Set it once before the loop.
Avvio - the pane was added to the grid pane in each loop.  Add it once after the loop.
Avvio - the constraints place the buttons in the same grid locations. With the previous two issues fixed, only the last three buttons placed appear.

I'm assuming you want three buttons in a row, so I changed the loop to use the counter as a row counter. The code below will create ten rows of three buttons.
What appears:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.WindowConstants;

public class Main extends javax.swing.JFrame {
    private JPanel gridPanel;

    public Main() {

        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setSize(600,400);

        //EXISTING PANEL
        gridPanel = new JPanel();
        JScrollPane scrollPane = new JScrollPane(gridPanel);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        JPanel borderLayoutPanel = new JPanel(new BorderLayout());
        borderLayoutPanel.add(scrollPane, BorderLayout.CENTER);

        this.Avvio();
        this.add(borderLayoutPanel, BorderLayout.CENTER);
        this.setVisible(true);
    }

    private void Avvio() {
        JPanel pane = new JPanel(new GridBagLayout());
        pane.setBorder(BorderFactory.createLineBorder(Color.BLUE));
        pane.setLayout(new GridBagLayout());

           for (int i = 0; i < 10; i++) {
               JButton button;
               GridBagConstraints c = new GridBagConstraints();
               c.fill = GridBagConstraints.HORIZONTAL;
               c.anchor = GridBagConstraints.PAGE_START;

               button = new JButton("Button 1");
               c.weightx = 0.5;
               c.gridx = 0;
               c.gridy = i;
               pane.add(button, c);

               button = new JButton("Button 2");
               c.gridx = 1;
               c.gridy = i;
               pane.add(button, c);

               button = new JButton("Button 3");
               c.gridx = 2;
               c.gridy = i;
               pane.add(button, c);

           }
           gridPanel.add(pane);
           gridPanel.revalidate();
           gridPanel.repaint();

    }

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

Comment: `GridLayout` is unnecessary and you are calling `invokeLater()` twice.
Comment: @Michael McKay are you testing it? it does not work, JScrollPane not visible
Comment: Made the changes suggested. Not trying to fix everything here - just the Avvio method.
Comment: in the Avvio() method, if I not insert this: `scrollPane.setViewportView(pane);`, all not visible
Comment: @user2847219.  Added a picture showing the output as written before your suggestion. The `scrollPane` object is not visible inside the Avvio method as I have it coded above but the `gridPanel` is. (In your original code, you refer to gridPanel but didn't instantiate it.)  The Main() JFrame is built Main->borderLayout->scrollPane->gridPanel->pane. You can remove `gridPanel` and just use the `scrollPane` if you make `scrollPane` a field.
Comment: Seems you removed the call `this.add(borderLayoutPanel, BorderLayout.CENTER);` in the Main() constructor.  Without that call, the Main JFrame has nothing to display.
Answer: There are several things to do to make it work:

Add a main method
This main method is the entry point. This makes sure the swing-code runs in the AWT-thread. This is what the SwingUtilities.invokeLater is for
Instantiate, pack and display the frame. The size setting is only for experimenting with the scrollpane
Declare the gridPanel as an instance variable
wrap the gridPanel with the scrollPane
Optionally, wrap the scrollPane with the borderLayoutPanel
Invoke the Avvio method because this is the one that adds the buttons
Add the outmost element to the frame

Here is the fixed code:
public class MyFrame extends javax.swing.JFrame {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            MyFrame frame = new MyFrame();
            frame.pack();
            frame.setSize(600, 300);
            frame.setVisible(true);
        });
    }

    private JPanel gridPanel;

    public MyFrame() {
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        gridPanel = new JPanel(new GridLayout(0, 1));
        JScrollPane scrollPane = new JScrollPane(gridPanel);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        JPanel borderLayoutPanel = new JPanel(new BorderLayout());
        borderLayoutPanel.add(scrollPane, BorderLayout.CENTER);
        this.Avvio();
        this.add(borderLayoutPanel, BorderLayout.CENTER);
    }

    private void Avvio() {...}
}

Comment: The code in my answer works. So something went wrong duirng translation. The first question is: what is the problem you're having now. Is it a compilation problem? Do the buttons appear incorrectly? Please specify.
Comment: No problem for compile , simply the Jpanel is empty. The buttons does not appear. In my Jframe I have only the Jpanel (gridPanel)
Comment: There are a few differences between my code and yours. What are those?
Comment: Sorry, but I do not see any difference, other than that:'private JPanel gridPanel;'of which there is no need, and this 'initComponents();'. If there is an error or a lack in my code, is inside the 'Avvio()' method.  I asked help for that
Comment: So that's the difference. You add `gridPanel` in one method and add buttons to another `gridPanel` in another method. You can either use an instance variable or you can pass that as a method parameter.
Answer: I have simplified the program and removed all the mistakes
and bad practices. (Missing package, unnecessary panels, calling invokeLater() twice and others.)
Here is a working example:
package com.zetcode;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class JavaScrollPaneEx extends JFrame {

    public JavaScrollPaneEx() {

        initUI();
    }

    private void initUI() {

        JPanel panel = new JPanel(new BorderLayout());

        JPanel buttonPanel = createButtonPanel();
        JScrollPane scrollPane = new JScrollPane(buttonPanel);

        panel.add(scrollPane, BorderLayout.CENTER);
        add(panel);

        setTitle("Buttons in JScrollBar");
        setSize(350, 250);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

    }

    private JPanel createButtonPanel() {

        JPanel panel = new JPanel(new GridBagLayout());

        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.HORIZONTAL;
        c.anchor = GridBagConstraints.PAGE_START;
        c.insets = new Insets(5, 5, 5, 5);

        for (int i = 0, j = 0; i < 5; i++) {

            JButton btn = new JButton("Button " + (j + 1));
            c.weightx = 0.5;
            c.gridx = i;
            c.gridy = 0;
            panel.add(btn, c);

            btn = new JButton("Button " + (j + 2));
            c.gridx = i;
            c.gridy = 1;
            panel.add(btn, c);

            btn = new JButton("Button " + (j + 3));
            c.gridx = i;
            c.gridy = 2;
            panel.add(btn, c);

            j += 3;
        }

        return panel;
    }

    public static void main(String args[]) {

        EventQueue.invokeLater(() -> {
            JavaScrollPaneEx ex = new JavaScrollPaneEx();
            ex.setVisible(true);
        });
    }
}

And this is the screenshot.

And since I consider GridBagLayout to be a very bad
layout manager, I have created a similar example with MigLayout
manager.
We need the following Maven dependency for this example:
<dependency>
    <groupId>com.miglayout</groupId>
    <artifactId>miglayout-swing</artifactId>
    <version>5.0</version>
</dependency>

The source:
package com.zetcode;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import net.miginfocom.swing.MigLayout;

public class JavaScrollPaneEx2 extends JFrame {

    public JavaScrollPaneEx2() {

        initUI();
    }

    private void initUI() {

        JPanel panel = new JPanel(new BorderLayout());

        JPanel buttonPanel = createButtonPanel();
        JScrollPane scrollPane = new JScrollPane(buttonPanel);

        panel.add(scrollPane, BorderLayout.CENTER);
        add(panel);

        setTitle("Buttons in JScrollBar");
        setSize(350, 250);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

    }

    private JPanel createButtonPanel() {

        JPanel panel = new JPanel(new MigLayout());

        for (int i = 0, j = 0; i < 5; i++) {

            JButton btn1 = new JButton("Button " + (j + 1));
            JButton btn2 = new JButton("Button " + (j + 2));
            JButton btn3 = new JButton("Button " + (j + 3));
            JButton btn4 = new JButton("Button " + (j + 4));
            JButton btn5 = new JButton("Button " + (j + 5));

            panel.add(btn1, "sgx");
            panel.add(btn2, "sgx");
            panel.add(btn3, "sgx");
            panel.add(btn4, "sgx");
            panel.add(btn5, "sgx, wrap");

            j += 5;
        }

        return panel;
    }

    public static void main(String args[]) {

        EventQueue.invokeLater(() -> {
            JavaScrollPaneEx2 ex = new JavaScrollPaneEx2();
            ex.setVisible(true);
        });
    }
}

Java JScrollpane not visible


Python (googletrans) - AttributeError: 'NoneType' object has no attribute 'group'

Question: Trying to detect language code in Python using googletrans. But it generating ERROR (Refer error block for info).
Require solution for the same
Code :
import googletrans
from googletrans import Translator
translator = Translator()
result = translator.translate('Mitä sinä teet')
print(result.src)
print(result.dest)
print(result.origin)
print(result.text)
print(result.pronunciation)

Error:

C:\ProgramData\Anaconda3\lib\site-packages\googletrans\gtoken.py in _update(self)
     60
     61         # this will be the same as python code after stripping out a reserved word 'var'
---> 62         code = self.RE_TKK.search(r.text).group(1).replace('var ', '')
     63         # unescape special ascii characters such like a \x3d(=)
     64         code = code.encode().decode('unicode-escape')

AttributeError: 'NoneType' object has no attribute 'group'

Comment: @Steve always good to check the GitHub issues page first, this exact error ended up being there, along with a workaround.
Answer: It worked post re-installing googletrans
pip install googletrans==4.0.0-rc1
Comment: This works for me, nice and simple solution!
Answer: This is a known, reported issue in the googletrans library's github page. Take a look there to see the status of the fix and potential work arounds: https://github.com/ssut/py-googletrans/issues.
According to the most recent comment, installing a different version, googletrans==4.0.0-rc1, appears to work, but with caveats:

fire17 commented 16 days ago
normal pip installation failed but uninstalled and reinstalled
googletrans==4.0.0-rc1
then worked :)
tho the object is wierd, i can access the translated text like
a = translator.translate("hi")
translated_text = a.__dict__()["text"]

Comment: it is [AttributeError: 'NoneType' object has no attribute 'group' · Issue #354 · ssut/py-googletrans · GitHub](https://github.com/ssut/py-googletrans/issues/354)

`a = translator.translate("Guten Abend")` then `a.text` gives `'Good evening'` :-)


Determining the metric through lengths of distance minimizing curves

Question: Consider a two dimensional smooth Riemannian manifold $(M,g)$ with boundary $(N,h)$, where $h$ is the induced metric. For simplicity let $M$ be homotopic to a disk. Does specifying the length of distance-minimizing curves in $M$ between any two points $x,y\in N$ uniquely determine $g$ up to diffeomorphism $M\to M$ such that $N$ is fixed?
Answer: In 2005 Pestov and Uhlmann showed that distances between boundary points determine the Riemannian metric up to diffeomorphism:

Two dimensional compact simple Riemannian manifolds are boundary
  distance rigid, Ann. of Math. 161 (2005), no. 2, 1093--1110;
  MR2153407 (2006c:53038).


How to format the rows of only selected columns of df

Question: I have the following df:
df = pd.DataFrame({'A': ['foo', 'bar'],
                   'B': [134.532, 543.009],
                   'C': [1.98, 0.9],
                   'D': [300.99, 7000.89]

})
Output:
     A        B     C
0  foo  134.532  1.98
1  bar  543.009  0.90

I want to format/round every row of the columns B and C to have 0 decimal places.
I do not want to change the original df to contain only these columns, that is, the formatting of the others needs to stay.
And I need to select the columns by their index because I have many columns, that I can't manually select by manually typing their headers.
I have tried:
new_df = df.iloc[:, 1:].map('{:,.0f}'.format)

But Im getting: AttributeError: 'DataFrame' object has no attribute 'map'. Did you mean: 'mad'?
Comment: you can use `applymap` instead of `map`, but the type becomes string, do you want this? if you want keep numerical values, then `df.iloc[:, 1:].astype(int)` may work
Comment: also I'm surprised the error include `Did you mean: mad?` never saw this in an error message
Comment: Before your comment, I was, in fact, mad.
Comment: If these are only a couple of all the columns in the df, how can I make this change inplace if I don't want to format the other columns?
Answer: new_df = df.round({"B":0,"C":0})

You can change dictionary values for nay number of decimal places for each column
Answer: Maybe something along the line:
df[['B', 'C']].apply(lambda x: np.around(x, decimals=2), axis=0)

for two decimal digits....
Answer: to round the value i.e., .5 will round up and then drop the decimal (0) part
df[['B','C']]=df[['B','C']].round(0).astype(int)
df

    B   C
0   135     2
1   543     1

using index location
# choose all rows, and columns from 1 and onward
df.iloc[:,1:]=df.iloc[:,1:].round(0).astype(int)
df

    A   B   C
0   foo     135     2
1   bar     543     1


How is this junction box intended to be used?

Question: I am in Europe and recently purchase this junction box:

I have two questions:

What is the intended use of the two brass colored busbars versus the three steel colored busbars?
What is the intended use of the straight busbar in the middle versus those curved busbars on the periphery?
Answer:
neutral and ground vs three phases.
ground

Note the "N" and ground-symbol moulded on the plastic base.


Almost formatted my main disk with GParted. Is it safe to reboot?

Question: While trying to format my USB key, I accidentally selected /dev/sda and proceeded to format the disk. Luckily, the formatting was interrupted when GParted noticed the drive was currently mounted. However, I can't see the partitions anymore (even when I restart GParted, I keep seeing this):

I haven't rebooted yet as I am afraid to do so. At the moment, I can use my filesystem just fine but I'm afraid that if I reboot some bad things might happen. What can I do to fix this? Is it safe to reboot?
UPDATE:
I was attempting to create a bootable USB key for Windows 7 so I clicked Device/Create partition table and selected "msdos". I then attempted to create a primarty partition (NTFS) and got an error due to the fact that /dev/sda was already mounted. I'm not sure where I can get an exact log. Here's the output of sudo fdisk -l:
➜  ~  sudo fdisk -l
[sudo] password for olalonde:

Disk /dev/sda: 500.1 GB, 500107862016 bytes
255 heads, 63 sectors/track, 60801 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x0001db65

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1               1       60801   488384001    7  HPFS/NTFS

Disk /dev/sdb: 7998 MB, 7998537728 bytes
255 heads, 63 sectors/track, 972 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x0005e98c

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1               1         972     7807558+   7  HPFS/NTFS

As I said, my file system is correctly mounted so I can backup all my files but I'd rather not go through that lengthy process if it is safe to reboot or if there's a way to fix this before rebooting...
UPDATE 2:
Output of mount and cat /proc/mounts:
➜  ~  mount
/dev/sda1 on / type ext4 (rw,errors=remount-ro)
proc on /proc type proc (rw,noexec,nosuid,nodev)
none on /sys type sysfs (rw,noexec,nosuid,nodev)
none on /sys/fs/fuse/connections type fusectl (rw)
none on /sys/kernel/debug type debugfs (rw)
none on /sys/kernel/security type securityfs (rw)
none on /dev type devtmpfs (rw,mode=0755)
none on /dev/pts type devpts (rw,noexec,nosuid,gid=5,mode=0620)
none on /dev/shm type tmpfs (rw,nosuid,nodev)
none on /var/run type tmpfs (rw,nosuid,mode=0755)
none on /var/lock type tmpfs (rw,noexec,nosuid,nodev)
none on /lib/init/rw type tmpfs (rw,nosuid,mode=0755)
binfmt_misc on /proc/sys/fs/binfmt_misc type binfmt_misc (rw,noexec,nosuid,nodev)
/home/olalonde/.Private on /home/olalonde type ecryptfs (ecryptfs_check_dev_ruid,ecryptfs_sig=ee352762b400fa23,ecryptfs_fnek_sig=70e5eee62e053b1b,ecryptfs_cipher=aes,ecryptfs_key_bytes=16,ecryptfs_unlink_sigs)
gvfs-fuse-daemon on /home/olalonde/.gvfs type fuse.gvfs-fuse-daemon (rw,nosuid,nodev,user=olalonde)
/dev/sda1 on /mnt type ext4 (rw)

➜  ~  cat /proc/mounts
rootfs / rootfs rw 0 0
none /sys sysfs rw,nosuid,nodev,noexec,relatime 0 0
none /proc proc rw,nosuid,nodev,noexec,relatime 0 0
none /dev devtmpfs rw,relatime,size=2005108k,nr_inodes=501277,mode=755 0 0
none /dev/pts devpts rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000 0 0
/dev/disk/by-uuid/bbf66c3f-ae71-4389-9f83-282e95ce6ee9 / ext4 rw,relatime,errors=remount-ro,barrier=1,data=ordered 0 0
none /sys/fs/fuse/connections fusectl rw,relatime 0 0
none /sys/kernel/debug debugfs rw,relatime 0 0
none /sys/kernel/security securityfs rw,relatime 0 0
none /dev/shm tmpfs rw,nosuid,nodev,relatime 0 0
none /var/run tmpfs rw,nosuid,relatime,mode=755 0 0
none /var/lock tmpfs rw,nosuid,nodev,noexec,relatime 0 0
none /lib/init/rw tmpfs rw,nosuid,relatime,mode=755 0 0
binfmt_misc /proc/sys/fs/binfmt_misc binfmt_misc rw,nosuid,nodev,noexec,relatime 0 0
/home/olalonde/.Private /home/olalonde ecryptfs rw,relatime,ecryptfs_fnek_sig=70e5eee62e053b1b,ecryptfs_sig=ee352762b400fa23,ecryptfs_cipher=aes,ecryptfs_key_bytes=16,ecryptfs_unlink_sigs 0 0
gvfs-fuse-daemon /home/olalonde/.gvfs fuse.gvfs-fuse-daemon rw,nosuid,nodev,relatime,user_id=1000,group_id=1000 0 0
/dev/sda1 /mnt ext4 rw,relatime,errors=remount-ro,barrier=1,data=ordered 0 0

UPDATE 3:
I am trying to use testdisk. Can anyone confirm that I'm doing this right and whether I should click that scary looking "Write"?

(selected N)
Comment: Yes, there's hope :). Backup important data though...  If geirha doesn't solve this for you before then, I will continue working on this in about 12 hours.
Comment: Does `sudo mount /dev/sda1 /mnt` successfully mount the filesystem on `/mnt`? gparted should keep a log of what it did, but it is lost when you close gparted, unless you chose "Save details".
Comment: It does work. http://pastebin.com/ynbgp2eM
Comment: Now when I open GParted it says "Mounted on /, /mnt". Is that a good sign? Can I safely reboot?
Comment: You need to tell us HOW you were running `gparted`. What is the output of `sudo fdisk -l`? It should be easy to save/restore the in-memory layout of `sda`. However **if at all possible** I would back up the important stuff to an external drive/another disk/etc. without rebooting.
Comment: Good, so the filesystem appears to be intact, however, if it managed to do any modifications on the partition table, those changes will take effect next boot, in which case, it won't boot. So, do you have the gparted log? Or, do you remember exactly what changes you did?
Comment: Answered your questions as an update to the question. Thanks guys! @izx "It should be easy to save/restore the in-memory layout of sda" could you explain how?
Comment: `fdisk -l` output confirms that it managed to change the partition table, so a reboot now will fail. `testdisk` may be able to restore it, but I'd start by backing up just in case.
Comment: @izx, Ubuntu won't work if its `/` filesystem is NTFS... `fdisk` is showing the changed partition table (not the one the kernel loaded during boot). Also, I'd expect there to be a swap partition.
Comment: @geirha, nevermind, I misunderstood his edit. You're right....
Comment: Can we get the output of `mount` or `cat /proc/mounts`
Comment: Updated question with command outputs. Is there any hope to recover the partitions without a complete backup/reinstall? Also, what should I do if I accidentally shutdown my computer?
Comment: Actually, all that needs to be done is (a) read the in-memory (kernel) partition table of /dev/sda and (b) write that to /dev/sda, overwriting the bogus NTFS layout. If you don't get quick answers here, try asking on Unix.SE and Gilles can tell you how to do (a)
Comment: @izx asked the question over here: http://unix.stackexchange.com/questions/43922/how-to-read-the-in-memory-kernel-partition-table-of-dev-sda
Comment: That looks right to me, based on your `mount` output. On the next-to-last screen, `testdisk` reported that it recovered the partition structure from an `EXT4 Large file Sparse superblock` which is  about as certain as you can get that it got it right. I am surprise there's no swap partition. Can you run `sudo swapon -s` to report if your have a swap area?
Answer: I'm having trouble replicating your scenario -- if a partition is mounted, whether explicitly (fstab/mount), or implicitly (by Nautilus, etc.), GParted will not let you create a partition table on the parent device before unmounting.
I suspect GParted successfully overwrote the MBR/partition table on /dev/sda. Rebooting WILL make the contents inaccessible, don't do it yet. If you are prepared to, I believe testdisk should be able to recover the partition table.
There should be a way to get the in-memory (kernel) partition table layout -- that's how you can still access the contents -- but I can't remember an easy way to do that.
In the meanwhile it may be a good idea to at least back the critical stuff up....
Comment: +1 for the backup suggestion. But I think, Gparter allow creating a new partition table on the parent device before unmounting
Answer: Could you do:
sudo fdisk -l /dev/sda

This way you should be able to see if it still recongizes the partitions, e.g:
Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048     1171455      584704   83  Linux
/dev/sda2         1171456     3125247      976896   82  Linux swap / Solaris
/dev/sda3         3127294    15611903     6242305    5  Extended
/dev/sda5         3127296    13869483     5371094   83  Linux
/dev/sda6        13871104    15611903      870400   83  Linux

Is what I get on my system. If it does not recognize your filesystem properly anymore then I am not sure whether there is much more you can do.
I recommend making a backup of all of your most important files in this case, since you might be able to use fdisk or cfdisk to set the partition type, and afterwards use fsck to check the filesystem.
But I am not sure whether it will still fix your partition. Things like this can really be bummer, I accidentally typed rm -rf /tmp / once, in the split second that I pressed CTRL+C half of my /bin was already removed and I had to reinstall.
I hope my advise guides you in the right direction and that you are able to fix your system.
If you run into anything just let me know.
Answer to Update 3:
I believe Write is the way to go. It should restore the partition type and flags as they were before gparted. However I cannot state how important it is to have a backup just in case something does go wrong.
After 'testdisk' is done run 'fdisk -l /dev/sda' again and post output.
Answer: I just reproduced your problem in a virtual machine using fdisk instead of gparted.
Before I had:
  Device  Boot  Start   End    Blocks   Id  System
/dev/sda1   *       1    18    144553+  83  Linux
/dev/sda2          19  2450  19535040   83  Linux
/dev/sda4        2451  2610   1285200   82  Linux swap / Solaris

I then used fdisk to delete partitions 4, 2 and 1 and create a new primary partition covering the whole disk. I then changed the type to NTFS (07) and wrote it to disk.
fdisk -l /dev/sda then reported:
  Device  Boot  Start   End    Blocks   Id  System
/dev/sda1           1  2610  20964793+   7  HPFS/NTFS

I then ran 'testdisk /dev/sda' which almost instantly came up with a list of partitions which when written were reported as:
  Device  Boot  Start   End    Blocks   Id  System
/dev/sda1   *       1    18    144553+  83  Linux
/dev/sda2          19  2450  19535040   83  Linux
/dev/sda3        2451  2610   1285200   82  Linux swap / Solaris

The only difference is that it moved /dev/sda4 to /dev/sda3. The VM rebooted successfully.
In your case, since mount shows you only have a single partition, /dev/sda1, testdisk should be able to recover it without any problem.
In any event, testdisk gives you the option of deciding whether to write its findings out, so you can't lose by running it. Obviously, you may need to do sudo apt-get install testdisk.
Of course, if it's possible, it's probably prudent to back up anything critical.


How to evaluate the sum for definite integrals using limit definition?

Question:
If $f$ is integrable on $[a,b]$, then
  $$
\int_a^b f(x) dx = \lim_{n \to \infty} \sum_{i=1}^n f(x_i) \Delta x_i
$$
  where $\Delta x = (b-a)/n$ and $x_i = a + i\Delta x$. Use this definition of the integral to evaluate $\int_2^4 (1-2x)dx$.

We have $\int_2^4 (1-2x)dx = \lim_{n \to \infty} \sum_{i=1}^n ???$
Evaluating the sum gives $\int_2^4 (1-2x)dx = \lim_{n \to \infty} ???$
Evaluating the limit gives $\int_2^4 (1-2x)dx = ???$

So I'm able to solve the first part of this question correctly with getting
$(1-2(2+\frac{2i}{n}))(\frac{2}{n})$. But for the second part which is 'evaluating the sum', I'm not able to figure out what the question is exactly asking for and how to calculate it.
It's not the same as evaluating the limit so this is confusing me a bit.
It will help if someone's able to help me understand this 'evaluate the sum' and how to solve this part of the question.
Thank you!
Answer: Without checking the correctness of your representation, you have
$$
\frac{2}{n} \left[1 - 2\left(2+\frac{2i}{n}\right)\right]
 = \frac{2}{n} \left[-3 - \frac{4i}{n}\right]
 = -\frac{6}{n} - \frac{8i}{n}
$$
Therefore,
$$
\sum_{i=0}^{n-1} \frac{2}{n} \left[1 - 2\left(2+\frac{2i}{n}\right)\right]
= -\sum_{i=0}^{n-1} \frac{6}{n}-\sum_{i=0}^{n-1} \frac{8i}{n}
= -6-\frac{8}{n}\sum_{i=0}^{n-1} i
$$
Can you finish this?
Comment: Nope. I'm really weak with this so I'm not sure where to go after that.
Comment: @rockettj **Hint:** $$\sum_{k=1}^n k = \frac{n(n+1)}{2}$$
Comment: I'm getting like -10. but I'm not sure at all if its right. I tried substituting what you showed me with the i. Is that correct or wrong?
Comment: Nope I'm apparently wrong. I know I have to substitute that for i but I'm still completely lost.
Comment: @rockettj Your result of $-10$ is correct, you can check it via $$\int_2^4 (1-2x)dx = \left. x - x^2 \right|_2^4 = (4-16)-(2-4) = -10.$$


The integer part of $x+1$ is the integer part of $x$ plus $1$

Question: How do you solve the proof:
If $x$ is a real number, then: $[x+1]  = [x] + 1$.
For my proof, I tried to describe the interior of the argument inside the parentheses, but I was unsuccessful. Please help!
Comment: Probably $[\cdot]$ denotes the floor function.
Comment: What are the brackets referring to? What does your notation mean?
Answer: Let $y = [x] \Rightarrow x-1 <y \leq x\Rightarrow x < y+1 \leq x+1\rightarrow y+1 = [x+1]\Rightarrow [x]+1=[x+1]$


R package "spatstat": How do you get standard errors for non-smooth terms in a poisson process model (function: ppm) when use.gam=TRUE?

Question: In the R package spatstat (I am using the current version, 1.31-0) , there is an option use.gam. When you set this to true, you can include smooth terms in the linear predictor, the same way you do with the R package mgcv. For example,
g <- ppm(nztrees, ~1+s(x,y), use.gam=TRUE)

Now, if I want a confidence interval for the intercept, you can usually use summary or vcov, which works when you don't use gam but fails when you do use gam
vcov(g)

which gives the error message
Error in model.frame.default(formula = fmla, data =
    list(.mpl.W = c(7.09716796875,  :invalid type (list) for variable 's(x, y)'

I am aware that this standard error approximation here is not justified when you use gam, but this is captured by the warning message:
In addition: Warning message: model was fitted by gam();
            asymptotic variance calculation ignores this

I'm not concerned about this - I am prepared to justify the use of these standard errors for the purpose I'm using them - I just want the numbers and would like to avoid "writing-my-own" to do so.
The error message I got above does not seem to depend on the data set I'm using. I used the nztrees example here because I know it comes pre-loaded with spatstat. It seems like it's complaining about the variable itself, but the model clearly understands the syntax since it fits the model (and the predicted values, for my own dataset, look quite good, so I know it's not just pumping out garbage).
Does anybody have any tips or insights about this? Is this a bug? To my surprise, I've been unable to find any discussion of this online. Any help or hints are appreciated.
Edit: Although I have definitively answered my own question here, I will not accept my answer for the time being. That way, if someone is interested and willing to put in the effort to find a "workaround" for this without waiting for the next edition of spatstat, I can award the bounty to him/her. Otherwise, I'll just accept my own answer at the end of the bounty period.
Comment: I get the same error message if I just try to print the g to the screen. It seems that the problem occurs when calling the model.frame function. With simple debugging the error seems to occur in line data <- .Internal(model.frame(formula, rownames, variables, varnames, extras, extranames, subset, na.action))
Comment: Hi @Hemmo, I can see that. But, the model still is estimated (e.g. `coef(g)` works) and you can plot predicted values, etc. (although, when you try to get standard errors for the predictions, you're back to this error). Any tips?
Comment: Quick looking at the code of ppm and mpl.engine, I would say that ppm and it's subfunctions do not use model.frame approach. It saves formula and data into the output (g$internal), but default formula parsing /model.frame.default cannot handle list s(x,y) as there is no such thing in the data frame. My guess is that this is a bug, and you should ask this from the package author. You could also test this with older version of the package and see if you get the same error.
Answer: I have contacted one of the package authors, Adrian Baddeley, about this. He promptly responded and let me know that this is indeed a bug with the software and, apparently, I am the first person to encounter it. Fortunately, it only took him a short time to track down the issue and correct it. The fix will be included in the next release of spatstat, 1.31-1.
Edit: The updated version of spatstat has been released and does not have this bug anymore:
g <- ppm(nztrees, ~1+s(x,y), use.gam=TRUE)
sqrt( vcov(g)[1,1] )
[1] 0.1150982
Warning message:
model was fitted by gam(); asymptotic variance calculation ignores this

See the spatstat website for other release notes. Thanks to all who read and participated in this thread!
Answer: I'm not sure you can specify the trend the way you have which is possibly what is causing the error. It doesn't seem to make sense according to the documentation:

The default formula, ~1, indicates the model is stationary and no trend is to be fitted.

But instead you can specify the model like so:
g <- ppm(nztrees, ~x+y, use.gam=TRUE)
#Then to extract the coefficientss:
>coef(g)
(Intercept)             x             y
-5.0346019490  0.0013582470 -0.0006416421
#And calculate their se:
vc <- vcov(g)
se <- sqrt(diag(vc))
> se
(Intercept)           x           y
0.264854030 0.002244702 0.003609366

Does this make sense/expected result? I know that the package authors are very active on the r-sig-geo mailing lsit as they have helped me in the past. You may also want to post your question to that mailing list, but you should reference your question here when you do.
Comment: Hi @Simon, thanks for your attention. The `s(x,y)` is `gam` syntax for specifying the effect of `x,y` by a non-parametric smooth function (that is estimated). See the [gam documentation](http://127.0.0.1:31246/library/mgcv/html/gam.html). Note that the model *is* estimated as a functional parameter when you run my code (e.g. plot the predicted surface - `plot(predict(g))`), but it seems that the link with `gam` is incomplete, since SEs for the non-smooth terms aren't available. The model you've fit is a usual log-linear in `x` and `y` and I have had success getting those standard errors, etc.
Comment: @Macro ah I should have paid more attention. I will look into it further to see if I can help, but I strongly advise to post to r-sig-geo, and I strongly advise to read the [posting guide](http://www.r-project.org/posting-guide.html) first. I have been slated for a poorly formed question the mailing list before!
Comment: Non-local [gam documentation](http://finzi.psych.upenn.edu/R/library/mgcv/html/gam.html) for anyone else following this


Grub does not show up at start, cannot select older kernel

Question: I just built a newer kernel and tried to install it. I use a script (which I have successfully used before) to that effect.
Now the kernel won't start. It shows:
Loading Linux <my version string>
Loading initial ramdisk

on a Ubuntu purple background, then switches to black screen and no more.
The strange thing is that I can't seem to access the bootloader to choose the older kernel.
I could start with an usb-live, mount the hard-drive and check /etc/default/grub, but I cannot run update-grub since it's the usb-live running.
There I could see that <mounted_sda1>/etc/default/grub still had GRUB_HIDDEN and GRUB_HIDDEN_TIMEOUT.
How do I make the grub start prompt pop up, so that I can boot with the older kernel?
Answer: As inaccurate as this answer may seem, the only way I can get grub to show up is if I spam right-shift and space-bar just before the OS is starting to boot (just after the BIOS splash screen flashes off).
My own anecdotal efforts seem to indicate that I have the best luck when I interchange my key presses, as opposed to just spamming the 2 keys at the same time.
Having said that, I've successfully had grub show up by just holding the shift key, and just spamming the space-bar - it seems a bit temperamental, and it sometimes takes me a few reboots just to get it.
Comment: You got it, thanks :) . And I love (or hate) how this feels like black magic... The older kernel does not boot either, but that's for another question.
Comment: Incidentally, if you want grub to always pop up at start, edit `/etc/default/grub` with `sudo`, comment the lines starting with `GRUB_HIDDEN_`, run `sudo update-grub`, and restart.


Date inconsistency across browsers - MVC 5 date from model

Question: I have this in a view model:
[Required]
[Display(Name = "Date of birth")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime DateOfBirth { get; set; }

And on the form:

      @Html.LabelFor(model => model.DateOfBirth, htmlAttributes: new { @class = "control-label col-md-2" })

             @Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control" } })
             @Html.ValidationMessageFor(model => model.DateOfBirth, "", new { @class = "text-danger" })

Works nicely in all browsers apart from Chrome which only displays "dd/MM/yyyy" instead of populating the field with the value from the model.
So I tried changing the date format in the ViewModel:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]

Chrome starts showing the model value in the format dd/MM/yyyy (potentially due to my local region settings?), but all the other browsers start showing the yyyy-MM-dd format.
I get that it's an international recognised standard, but being an Australian website the design we were working with was in the format of dd/MM/yyyy.
Can I get it working so that all the browsers show dd/MM/yyyy without needing to resort to:
@Html.TextBoxFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control" }, @Value = Model.DateOfBirth.ToString("dd/MM/yyyy") })

Which means that Chrome doesn't provide the date picker functionality.
Using latest version of MVC, with a c# view model.  Looks like Opera behaves similarly to Chrome.
Answer: It appears Chrome only accepts the format as yyyy-MM-dd, so the following will work
[Required]
[Display(Name = "Date of birth")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime DateOfBirth { get; set; }

It will then display the assigned date (using your regional settings) rather than the date string.  I guess that has an advantage in that a user in another culture would see the date in their culture rather than yours.
This actually in accordance with the specifications
This does not help much if you are also using @Html.DisplayFor(m=> m.DateOfBirth). One workaround would be to create a DisplayTemplate DateTime.cshtml that formats the date string using .ToString("dd/MM/yyyy")
Comment: OK, now understand.  Chrome and Opera have actually implemented this in accordance with the standards (i.e. the date input string should be "yyyy-MM-dd" and then displayed in accordance with the browsers regional settings. IE (typically) has not so you are probably out of luck. Not sure what you can do other than use a DatePicker plugin
Comment: Someone on the team wasn't 100% convinced about defining a EditorTemplate for the date type in case we want to do something funky with it on another screen.  Or do you control it in the view you want to use it in ?
Comment: Sorry, not sure I understand - do you mean EditorTemplate or DisplayTemplate? - from your question you do not appear to be using an editor template for `DateTime`
Comment: I might be getting confused about terminology.  It needs to be an editable field in the correct format with the date prepopulated.
Comment: If in the `DisplayFormatAttribute`, you use `DataFormatString = "{0:yyyy-MM-dd}"` and then in the view use `@Html.EditorFor(m=> m.DateOfBirth)` then this will render `<input type="date" ...` which will use the browsers internal datepicker (including being properly displayed in Chrome).  Because you need to use this format it means that if you used @Html.DisplayFor() in a non edit page, the date would be displayed as "2014-08-09" which may not be what you want, hence my suggestion to use a custom `DisplayTemplate`
Comment: Ahh ok - not concerned about a non edit page.  But I am concerned about Chrome and Opera showing date as expected (dd/MM/yyyy) due to the way they handle the date input correctly, but all the other browsers just showing it (in an editable state) in the format yyyy-MM-dd.  Sorry if that wasn't clear
Answer: We've ended up just using separate drop down lists for the day, month, year fields.  I imagine the other option would have been to find a datepicker plugin that worked in all browsers (and on mobile devices).  Annoying!


InnoSetup script uses JSONConfig.dll to read a json file but fails to retrieve key/values from file

Question: I have an InnoSetup script that reads a json file to retrieve some values (bool and strings mostly).
To achieve this I'm using Tlamas JSONConfig.dll downloaded from here: https://github.com/nsdevaraj/inno-json-config.
the problem now is that it fails to read the values from json-file and therefore only uses the default ones given as parameter to the functions. I've tried to debug it but not sure how to, added logs to this and tried to update the JSONConfig.dll by adding debug logging to its code but get only exceptions then.
What am I doing wrong here? Appreciate all the help I can get.
My original code is company code so I'm using the examples given in inno-json-config to do the same thing and failing, so will post that code instead.
I'm using Inno Setup 5.6.1. Variable WideString is not recognized and I changed it to String.
Example.iss
<code>[Setup]
AppName=My Program
AppVersion=1.5
DefaultDirName={pf}\My Program
OutputDir=userdocs:Inno Setup Examples Output

[Files]
Source: "C:\inno-json-config-master\JSONConfig.dll"; Flags: dontcopy

[code]
function JSONQueryString(FileName, Section, Key, Default: String;
  var Value: String; var ValueLength: Integer): Boolean;
  external 'JSONQueryString@files:jsonconfig.dll stdcall';
function JSONQueryBoolean(FileName, Section, Key: String;
  Default: Boolean; var Value: Boolean): Boolean;
  external 'JSONQueryBoolean@files:jsonconfig.dll stdcall';

function BoolToStr(Value: Boolean): string;
begin
  Result := 'True';
  if not Value then
    Result := 'False';
end;

procedure InitializeWizard;
var
  FileName: String;
  IntValue: Integer;
  StrValue: String;
  StrLength: Integer;
  BoolValue: Boolean;
begin
  FileName := 'C:\inno-json-config-master\Example.json';
  if FileExists(FileName) then begin
   Log('file found');
   end else begin
   Log('file not found');
  end;

  SetLength(StrValue, 16);
  StrLength := Length(StrValue);

  Log('StrValue_before:' + StrValue);
  Log('BoolValue_before: ' + BoolToStr(BoolValue));

  if JSONQueryString(FileName, 'Section_1', 'Key_1', 'Default', StrValue, StrLength) then
  begin
    MsgBox('Section_1:Key_1=' + StrValue, mbInformation, MB_OK);
  end;
  Log('Section_1:Key_1=' + StrValue);

  if JSONQueryBoolean(FileName, 'Section_1', 'Key_3', True, BoolValue) then
  begin
    MsgBox('Section_1:Key_3=' + BoolToStr(BoolValue), mbInformation, MB_OK);
  end;
  Log('Section_1:Key_3=' + BoolToStr(BoolValue));

  if JSONQueryBoolean(FileName, 'Section_2', 'Key_3', True, BoolValue) then
  begin
    MsgBox('Section_2:Key_3=' + BoolToStr(BoolValue), mbInformation, MB_OK);
  end;
  Log('Section_2:Key_3=' + BoolToStr(BoolValue));
end;
</code>
<code>{
    "Section_1": {
        "Key_1": "String 1",
        "Key_2": "1",
        "Key_3": "True"
    },
    "Section_2": {
        "Key_1": "String 2",
        "Key_2": "2",
        "Key_3": "False"
    }
}
</code>
Answer: I found another way to solve my problem and it is to use an ini file instead. Inno setup has built-in functions to read/write from/to an ini file. This way I save lots of time and ini is easy to read for a user as well.


how do i auto restart a crashed app that I run via "npm run start"?

Question: I have the following in my package.json:
  "scripts": {
    "test": "node test.js",
    "ffmpeg": "ffmpeg -framerate 30 -i frames/test_%04d.png -y -s:v 1280x720 -c:v libx264 -profile:v high -crf 20 -pix_fmt yuv420p output.mp4",
    "deploy": "surge -p .",
    "start": "budo browser.js:bundle.js -p 80 --live -- -t babelify",
    "build": "browserify browser.js -t babelify | uglifyjs -m -c warnings=false > bundle.js"
  },

I start my node app via "npm run start", and it runs this line from my package.json just fine:
"start": "budo browser.js:bundle.js -p 80 --live -- -t babelify",

However, i want a process to detect if the app crashes, and reruns the same command to restart it. Not sure the best way to go about this...do i use something native to npm like forever, or use something on the linux side to restart the process?
What is the best way to handle this?
Comment: Check out my answer here: https://stackoverflow.com/a/36907953/1871033
Answer: The simplest solution is a bit ugly, but seems to work:
"start": "RC=1; while [ $RC -ne 0 ]; do budo browser.js:bundle.js -p 80 --live -- -t babelify; RC=$?; done",

Namely, run your command (budo browser.js:bundle.js -p 80 --live -- -t babelify) in a loop, until it exits with status code 0 (success).
Answer: Your problem is typically solved with process managers. The most popular one for Node.js has always been PM2


align center a UL with only images

Question: I have a
 with 6 images, no text. I can't seem to make it be in the center of the page. This is my code.
CSS
.logos{
      margin:0 auto;
      text-align:center;
      display:table;
      float: left;
}

HTML

Answer: First of all remove the class name for div. ul and div have the same class name.
Give float:left to li

.logos{
      margin:0 auto;
      display:table;
}
.logos li{
  float:left;
}

Answer: You need to change
.logos{
      margin:0 auto;
      text-align:center;
      display:table;
      float: left;
}

to
.logos{
      margin:0 auto;
      text-align:center;
      display:table;

}

and the content will be in the middle of the page
Also you need to delete the div because is useless ,you set the same class to the ul and to div
Comment: thank you, it is centered now but vertically. i can't seem to make it centered horizontally... :(
Comment: @hal2001 to be in a line add  li {
    float: left;
}
Comment: i tried but it goes all left
Comment: Remove the DIV and the style code will be   .logos{
       margin:0 auto;
      text-align:center;
      display:table;

}
li {
    float: left;
}
Comment: thank you, thank you, thank you. it works!
Comment: @hal2001 Good luck!
Answer: Do it like this

.logo_wrapper {
  width: 100%;
  position: relative;
}
.logos {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  padding: 0;
}
.logo {
  display: inline-block;
  margin: 0 auto;
  text-align: center;
  float: left;
}

align center a UL with only images


get back the value of varibles created on php url

Question: I want to get back and use on my index.php the value of commentNewCount which will be created on load-comments.php. How can I do that?

load-comments.php
    <?php
    include 'dbh.php';

    $commentNewCount = $_POST['commentNewCount'];

    $sql = "SELECT * FROM comments LIMIT $commentNewCount";
    $result = mysqli_query($conn, $sql);
    if (mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            echo "
";
            echo $row['author'];
            echo "
";
            echo $row['message'];
            echo "
";
        }
    } else {
        echo "There are no comments!";
    }
?>

Answer: If you are just looking to pass variable from one page to another then you can either save the value of commentNewCount to a SESSION variable or COOKIE.
//on load-comments.php
$_SESSION['commentCount'] = $_POST['commentNewCount'];

//on index.php
$commentCount = $_SESSION['commentCount'];


Is this a correct way to struct Java DAO?

Question: I'm trying to develop an statistics / achievement system in my minecraft server.
I've done some research, but still couldn't make decision well, so decided to post my very first question in stack overflow.
There are multiple types of achievements, such as block broken, crop harvested, animal killed.. and so on. Table initializer looks like this. ( I intentionally set those values as double )
    public static void init() {
        String query = "CREATE TABLE IF NOT EXISTS statistic ("
                + " uuid            VARCHAR(255) PRIMARY KEY,"
                + " block_break     double,     crop_break      double,     ore_break       double,"
                + " wood_break      double,     animal_kill     double,     monster_kill    double,     boss_kill       double,"
                + " fish_natural    double,     fish_auto      double      "
                + ")";
        try {
            Connection conn = HikariPoolManager.getInstance().getConnection();
            PreparedStatement ps =  conn.prepareStatement(query);
            ps.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

and I save it back with this
    public static void save(String uuidString, StatisticsType stat, double val) {

        String query= "INSERT INTO statistics (uuid, {stat}) "
                +" VALUE (?,?) ON DUPLICATE KEY UPDATE "
                +" uuid=VALUES( uuid ), {stat}=VALUES( {stat} )"
                .replace("{stat}", stat.name());

        try (Connection conn = HikariPoolManager.getInstance().getConnection();
             PreparedStatement ps = conn.prepareStatement(query)
        ){
            ps.setString(1, uuidString);
            ps.setDouble(2, val);
            ps.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

PlayerCache.java

public class PlayerCache {

    @Getter
    private static final Map<UUID, PlayerCache> cacheMap = new HashMap<>();

    private final UUID uuid;
    @Getter
    private HashMap<StatisticsType, Double> statistics;

    @Getter
    private HashSet<StatisticsType> changed;

    public PlayerCache(UUID uuid) {
        this.uuid= uuid;
    }

    public void init(HashMap<StatisticsType,Double> achievements) {
        this.statistics = new HashMap<>();
        this.changed = new HashSet<>();
        this.statistics.putAll(achievements);
    }

    public void addValue(StatisticsType type, double addition) {
        statistics.put(type, statistics.get(type) + addition);
        changed.add(type);
    }

    public double getStatistic(StatisticsType type) {
        return statistics.getOrDefault(type, 0.0D);
    }

    public void save() {
        for (StatisticsType statisticsType : changed) {
            StatisticDAO.save(uuid.toString(),statisticsType, getStatistic(statisticsType));
        }
        changed.clear();
    }

    public static PlayerCache get(final UUID uuid) {
        PlayerCache playerCache = cacheMap.get(uuid);

        if (playerCache == null) {
            playerCache = new PlayerCache(uuid);
            cacheMap.put(uuid, playerCache);
        }
        return playerCache;
    }

}

I have question on general design of programming , not fixing code itself.
For now, this is how things go.
For simplicity, let me pick two actions of statistics - break stone , and kill monster.

player joins game, and read data , make a cache of player and put statistics information into the cache.

player breaks stone, and it increments statistics in player cache.

If player broke stone, it toggles a boolean flag to show he has broken stone, thus this information need to be flushed to database at some point.

Server loops all players , and check if player has done anything. If player has done something,  it calls sql save method, and toggle boolean flag back.

However, there are few problems I encountered this time.

player can break stone, and kill monster in duration of writing to the database. or even more different actions. That will result multiple save functions to be called from a player. Is there better way to deal with this?

Is my general apparoach to read and write data correct? I'm pretty much using same way to do database stuff to other functionalities, but unsure if this is the good way.
Comment: 1) You should use try/resource/catch in the first code too, just like you do in the second code. 2) The way you're doing it, you have lots of small writes (not a problem in this case, still too few queries per second). BUT You could keep the statistics in RAM, and a 'changed' flag. Then run a timer (daemon thread loop with sleep or sth alik) that checks them every second or so, and writes all changed datasets to the DB in batch (multiple data rows at once, prepared statement) call. Theoretically, if there was still problems with performance, the write cycle time would just increase on its own.
Answer: That will result multiple save functions to be called from a player. Is there better way to deal with this?
I think you are exacerbating the severity of running multiple SQL insert statements for a player. On a Minecraft server, there won't be very much load on the database at all and the fact you are using Hikari ensures that the performance impact of having these extra few queries is negligible.
However, if you are very sure that the environment you are working in is incredibly performance sensitive (which for a Minecraft plugin it probably isn't) then consider running batch SQL statements or combining updates for the same player manually into a single statement and sending that to the SQL database.
Answer: For me, you should use an object that will keep all informations, and save them only when you wants. For example: StatsPlayer.
You have a static map : HashMap<UUID, StatsPlayer> that contains all instance of players.
Each instance contains all informations like that :
private HashMap<StatisticsType, Double> stats;

Or:
private double blockBreak;

When creating new instance, don't forget to get informations from DB, for example :
public StatsPlayer(Player p) {
   try {
       Connection conn = HikariPoolManager.getInstance().getConnection();
       PreparedStatement ps = conn.prepareStatement("SELECT * FROM statistics WHERE uuid = ?");
       ps.setString(1, p.getUniqueId().toString());
       ResultSet rs = ps.executeQuery();
       if(rs.next()) {
          // get informations from ResultSet instance
       } else {
          // Insert line into database
       }
   } catch(Exception e) {
       e.printStackTrace();
   }
}

Now, you have to do a static getter like that :
public static StatsPlayer getPlayer(Player p) {
    synchronized(PLAYERS) {
        return PLAYERS.computeIfAbsent(p, StatsPlayer::new);
    }
}

In your StatsPlayer object, you should add method to update values, and one to save everything :
public void save() {
   try {
       Connection conn = HikariPoolManager.getInstance().getConnection();
       PreparedStatement ps = conn.prepareStatement("UPDATE statistics SET block_break = ? WHERE uuid = ?");
       ps.setDouble(1, getBlockBreak());
       ps.setString(2, p.getUniqueId().toString());
       ps.executeUpdate(); // make the update
   } catch(Exception e) {
       e.printStackTrace();
   }
}

Finally, you should save the object sometimes, for example only when they left server or when server stop
Answer: There are very few situations where this is a single correct way to do anything; but you did mention a Data Access Object.  DAO's follow a pattern, but that pattern is a general one.  Depending on your needs the actual objects might contain more (or less) data, or be structured in to back to one (or many tables).
the DAO pattern is a class that performs all direct operations on the database.  Minimally it includes add(Object), remove(Object), get(id), and maybe getAll() but it can also include getOldest(), remove(id), and so on.
What it should generally NOT do is expose the underlying table structure directly.  So in a sense, your approach (by exposing UUID and the stat to be updated independently) is not following the pattern.
public class PlayerStats {
   // contains a UUID field, as well as other stat fields
}

public class PlayerStatsDAO {
   public PlayerStatsDAO(DatabaseConnection connection) {
      // store the connection and check the connection
   }

   public void update(PlayerStats value) {
   }

   public void add(PlayerStats value) {
   }

   public void addOrUpdate(PlayerStats value) {
   }

   public PlayerStats newEmptyStats() {
   }

   public void remove(PlayerStats value) {
   }

   // as well as searching methods

   public PlayerStats statsForUUID(UUID uuid) {
   }

   public PlayerStats statsForPlayerName(String name) {
   }

   public PlayerStats mostBockBreaks() {
   }

   ... etc ...
 }

The advantage of a DAO is that if you later decide to change the underlying table (or set of joined tables), you have one location to bind the existing "Data Object" to the new table structures.


Convert object to JSON in serverside JavaScript aspx

Question: My application uses serverside JavaScript in aspx files on IIS 8 (Windows 2012R2) .
I want to convert a javascript hash to JSON.
My file test.aspx:
<%@language="javascript" Debug="true"%>
<%
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

var header =
{
  "typ": "JWT",
  "alg": "HS256"
};

var str = serializer.Serialize(header);
Response.Write(str);
%>

Result: ["typ","alg"]
Expected result: {"typ":"JWT","alg":"HS256"}
Why does the JavaScriptSerializer not work as expected?
Comment: If I'm understanding you correctly, you expect that serializer.Serialize(header) returns header?
Comment: I expect it to return the string `'{"typ":"JWT","alg":"HS256"}'` (added quotes for clarification)
Answer: I'm not sure how well System.Web.Script.Serialization.JavascriptSerializer, which is a server component, will work inside client code.
Probably you'll have better results just using
var str = JSON.stringify(header);

instead of
var str = serializer.Serialize(header);

Comment: I am running serverside code, this has nothing to do with client code.

On the server there is no JSON object: JS1135: Variable 'JSON' has not been declared
Comment: The only thing that comes to my mind is that the input you're sending to Serialize is a JS object and maybe this class is not prepared to deal with it (as it surely expects a .NET object).


Building a multi-part project with SCons

Question: I am trying to setup SCons to build my project and am having a hard time figuring out exactly how to organize things. It consists of basically the following parts:
Module: A separate small c project that compiles a small library already setup with SCons.
Core: Another c project already set up with Scons. It generates some code by calling TheScript on some files internal to the project.
Main: A project that directly uses files in both Module and Core; it generates code by invoking TheScript on a file within Module and it needs to include both source files within Core and library files generated by building Core.
TheScript A single python file that lives by itself somewhere.
My question is how do I arrange this stuff? For Core and Main, I need both projects to somehow invoke the newest version of TheScript. Currently I have a symlink to the script in each project directory, but that is hardly a long term solution. The same problem comes up when I want to refer between the projects: I don't want to simply enter magic paths that work on my machine, but I do want to keep them as standalone projects.
What is a good way to solve this? I've seen version control software used for something like this, where dependency projects are pulled in, but I have so far only used bazaar for straight up version control. I have no idea where to begin with the problems I have described. I don't need specific examples in bazaar - general concepts and pointers to documentation will do nicely.
Answer: Normally this would be done with a SCons hierarchical build Hierarchical builds But if you want to keep both Core and Main as stand-alone projects, this wont help. Ive never tried, but maybe you could have a Sconscript AND a SConstruct in both Core and Main. The SConsctruct would allow it to be a stand-alone project, while the SConscript would allow it be built all together, thus allowing for correct dependancy checking.
You could organize the project as follows:
.
|-- SConstruct
|-- Core
|     |--
|     |-- SConscript
|     `-- SConstruct
|-- Main
|     |--
|     |-- SConscript
|     `-- SConstruct
`-- Module
      |--
      `-- SConscript

As for the latest version of TheScript, you could invoke it in the SConscript files without specifying the path, and in the root level SConstruct, pull in the Unix Env PATH variable like this: Propagating PATH From the External Environment
Additionally, you could consider the SCons Repository function: Building From Code Repositories in the SCons user's guide. It wont let me post more than 2 hyperlinks for spam prevention.
Hope this helps,
Brady


Starting Hadoop file system with `start-dfs.sh` permission denied

Question: I try to install hbase one a standalone node but I have some issue to launch Hadoop file system with start-dfs.sh :
mike@mike-thinks:/usr/local/hadoop/sbin$ ./start-dfs.sh
Incorrect configuration: namenode address dfs.namenode.servicerpc-address or dfs.namenode.rpc-address is not configured.
Starting namenodes on []
./start-dfs.sh: line 61: /usr/local/hadoop/sbin/hadoop-daemons.sh: Permission denied
./start-dfs.sh: line 74: /usr/local/hadoop/sbin/hadoop-daemons.sh: Permission denied
Starting secondary namenodes [0.0.0.0]
./start-dfs.sh: line 87: /usr/local/hadoop/sbin/hadoop-daemons.sh: Permission denied

And with sudo :
mike@mike-thinks:/usr/local/hadoop/sbin$ sudo ./start-dfs.sh
[sudo] password for mike:
Incorrect configuration: namenode address dfs.namenode.servicerpc-address or dfs.namenode.rpc-address is not configured.
Starting namenodes on []
./start-dfs.sh: line 61: /usr/local/hadoop/sbin/hadoop-daemons.sh: Permission denied
./start-dfs.sh: line 74: /usr/local/hadoop/sbin/hadoop-daemons.sh: Permission denied
Starting secondary namenodes [0.0.0.0]
./start-dfs.sh: line 87: /usr/local/hadoop/sbin/hadoop-daemons.sh: Permission denied

So I did sudo chmod +x /usr/local/hadoop/sbin/
mike@mike-thinks:/usr/local/hadoop/sbin$ sudo chmod +x /usr/local/hadoop/sbin/
[sudo] password for mike:
mike@mike-thinks:/usr/local/hadoop/sbin$ ./start-dfs.sh
Incorrect configuration: namenode address dfs.namenode.servicerpc-address or dfs.namenode.rpc-address is not configured.
Starting namenodes on []
./start-dfs.sh: line 61: /usr/local/hadoop/sbin/hadoop-daemons.sh: Permission denied
./start-dfs.sh: line 74: /usr/local/hadoop/sbin/hadoop-daemons.sh: Permission denied
Starting secondary namenodes [0.0.0.0]
./start-dfs.sh: line 87: /usr/local/hadoop/sbin/hadoop-daemons.sh: Permission denied

I have yet to try to go to sshd_config, change PermitRootLogin without-password -> PermitRootLogin yes and do an ssh restart as gsamaras suggests in a related question but it seems so unlikely to be linked.

I did a chmod +x *.sh and it solved the issue. And I now have a Incorrect configurationerror :
mike@mike-thinks:/usr/local/hadoop/sbin$ ./start-dfs.sh
Incorrect configuration: namenode address dfs.namenode.servicerpc-address or dfs.namenode.rpc-address is not configured.
Starting namenodes on []
localhost: mkdir: cannot create directory '/usr/local/hadoop/logs': Permission denied
localhost: chown: cannot access '/usr/local/hadoop/logs': No such file or directory
localhost: starting namenode, logging to /usr/local/hadoop/logs/hadoop-mike-namenode-mike-thinks.out
localhost: /usr/local/hadoop/sbin/hadoop-daemon.sh: line 159: /usr/local/hadoop/logs/hadoop-mike-namenode-mike-thinks.out: No such file or directory
localhost: head: cannot open '/usr/local/hadoop/logs/hadoop-mike-namenode-mike-thinks.out' for reading: No such file or directory
localhost: /usr/local/hadoop/sbin/hadoop-daemon.sh: line 177: /usr/local/hadoop/logs/hadoop-mike-namenode-mike-thinks.out: No such file or directory
localhost: /usr/local/hadoop/sbin/hadoop-daemon.sh: line 178: /usr/local/hadoop/logs/hadoop-mike-namenode-mike-thinks.out: No such file or directory
localhost: mkdir: cannot create directory '/usr/local/hadoop/logs': Permission denied
localhost: chown: cannot access '/usr/local/hadoop/logs': No such file or directory
localhost: starting datanode, logging to /usr/local/hadoop/logs/hadoop-mike-datanode-mike-thinks.out
localhost: /usr/local/hadoop/sbin/hadoop-daemon.sh: line 159: /usr/local/hadoop/logs/hadoop-mike-datanode-mike-thinks.out: No such file or directory
localhost: head: cannot open '/usr/local/hadoop/logs/hadoop-mike-datanode-mike-thinks.out' for reading: No such file or directory
localhost: /usr/local/hadoop/sbin/hadoop-daemon.sh: line 177: /usr/local/hadoop/logs/hadoop-mike-datanode-mike-thinks.out: No such file or directory
localhost: /usr/local/hadoop/sbin/hadoop-daemon.sh: line 178: /usr/local/hadoop/logs/hadoop-mike-datanode-mike-thinks.out: No such file or directory
Starting secondary namenodes [0.0.0.0]
The authenticity of host '0.0.0.0 (0.0.0.0)' can't be established.
ECDSA key fingerprint is SHA256:/s7X8QMliB6FVx5bde5AaCycprQ/B+NtcTXrInrXxJM.
Are you sure you want to continue connecting (yes/no)? no
0.0.0.0: Host key verification failed.

Comment: Did you check for execute permission - exactly like your previous question [hdfs: command not found with Hadoop2.9.0](https://askubuntu.com/questions/983175/hdfs-command-not-found-with-hadoop2-9-0)
Comment: @steeldriver like `sudo chown -R` ? Not yet I'm thinking about what to write then
Comment: @steeldriver I think I've understood I did `sudo chmod +x /usr/local/hadoop/sbin/` but the errors remain
Comment: You probably need to change permissions on the **file** `/usr/local/hadoop/sbin/hadoop-daemons.sh` not the **directory** `/usr/local/hadoop/sbin/`
Answer: # Create the .ssh directory:
$ mkdir ~/.ssh

# Set the right permissions:
$ chmod 700 ~/.ssh

# Create the authorized_keys file:
$ touch ~/.ssh/authorized_keys

# Set the right permissions:
$ chmod 600 ~/.ssh/authorized_keys

The permissions are important! It won't work without the right permissions!
Now you can add the public key to the authorized_keys file:
$ cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys

And finally you can execute:
$ ./start-dfs.sh


Failed resolution of: Ldagger/internal/Preconditions

Question: My app worked well but due to some problem with my operating system Debian I decided to reinstall it and I choose to install Ubuntu-16.04 instead of the last Debian. Now everything is OK.
The problem is my android application. After reinstalling android-studio the stable version, I can not test my application anymore.
Why? Because every time I launch the application, I got this error. I don't know what it means, and after some searching on the internet, I didn't get anywhere.
Here is the stack trace:
10-13 07:47:10.749 1631-1631/com.gre E/AndroidRuntime: FATAL EXCEPTION: main
                                                      Process: com.gre, PID: 1631
                                                      java.lang.NoClassDefFoundError: Failed resolution of: Ldagger/internal/Preconditions;
                                                          at com.gre.di.components.DaggerApplicationComponent$Builder.applicationModule(DaggerApplicationComponent.java:209)
                                                          at com.gre.GreApplication.onCreate(GreApplication.java:47)
                                                          at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1012)
                                                          at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4593)
                                                          at android.app.ActivityThread.access$1600(ActivityThread.java:154)
                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1382)
                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                          at android.os.Looper.loop(Looper.java:135)
                                                          at android.app.ActivityThread.main(ActivityThread.java:5294)
                                                          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:904)
                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
                                                       Caused by: java.lang.ClassNotFoundException: Didn't find class "dagger.internal.Preconditions" on path: DexPathList[[zip file "/data/app/com.gre-1/base.apk", zip file "/data/app/com.gre-1/split_lib_dependencies_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_0_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_1_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_2_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_3_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_4_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_5_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_6_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_7_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_8_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.gre-1/lib/arm, /vendor/lib, /system/lib]]
                                                          at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
                                                          at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
                                                          at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
                                                          at com.gre.di.components.DaggerApplicationComponent$Builder.applicationModule(DaggerApplicationComponent.java:209)
                                                          at com.gre.GreApplication.onCreate(GreApplication.java:47)
                                                          at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1012)
                                                          at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4593)
                                                          at android.app.ActivityThread.access$1600(ActivityThread.java:154)
                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1382)
                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                          at android.os.Looper.loop(Looper.java:135)
                                                          at android.app.ActivityThread.main(ActivityThread.java:5294)
                                                          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:904)
                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
                                                        Suppressed: java.lang.ClassNotFoundException: dagger.internal.Preconditions
                                                          at java.lang.Class.classForName(Native Method)
                                                          at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
                                                          at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
                                                          at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
                                                                ... 14 more
                                                       Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available

How to solve it please ??
Here is my build.gradle file
    apply plugin: 'com.android.application'
     apply plugin: 'realm-android'
     // apply plugin: 'com.neenbedankt.android-apt'

     android {
         compileSdkVersion 25
         buildToolsVersion '25.0.2' // '23.0.2'

    defaultConfig {
        applicationId "com.gre"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        multiDexEnabled true

    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        /*debug {
            applicationIdSuffix ".debug"
        }*/

        /**
         * The 'initWith' property allows you to copy configurations from other build types,
         * so you don't have to configure one from the beginning. You can then configure
         * just the settings you want to change. The following line initializes
         * 'jnidebug' using the debug build type, and changes only the
         * applicationIdSuffix and versionNameSuffix settings.
         */

        jnidebug {

            // This copies the debuggable attribute and debug signing configurations.
            initWith debug

            applicationIdSuffix ".jnidebug"
            jniDebuggable true
        }
    }
    dexOptions {
        // javaMaxHeapSize "2048M"
        javaMaxHeapSize "4g"
    }
    configurations.all {
        // all*.exclude group: 'com.squareup.okhttp3', module: 'okhttp'configurations.all {
        // OkHttp 3.5.0+ includes the websockets API, so we need this to prevent a conflict
        exclude module: 'okhttp-ws'
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile('io.socket:socket.io-client:0.8.1') {
        exclude group: 'org.json', module: 'json'
    }

    /*compile 'com.google.android.gms:play-services-auth:10.0.1'
    compile 'com.google.android.gms:play-services-maps:10.0.1'
    compile 'com.google.android.gms:play-services-appindexing:10.0.1'*/

    // compile 'com.android.support.constraint:constraint-layout:1.0.2'

    // Android
    // Glide

    // Facebook Stetho
    // OkHttp
    // SquareUp
    // Rx
    // Dragger
    // Realm

    // RippleButton
    compile 'com.balysv:material-ripple:1.0.2'
    compile 'com.android.support:appcompat-v7:'
    compile "com.android.support:cardview-v7:${buildTools}"
    compile "com.android.support:recyclerview-v7:${buildTools}"
    compile "com.android.support:design:${buildTools}"
    compile "com.android.support:support-v13:${buildTools}"
    compile "com.android.support:support-v4:${buildTools}"
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.github.bumptech.glide:glide:4.0.0-RC0'
    compile 'com.github.florent37:materialtextfield:1.0.7'
    compile 'uk.co.chrisjenx:calligraphy:2.2.0'
    compile 'com.splitwise:tokenautocomplete:2.0.8@aar'
    compile 'com.github.Plumillon:ChipView:1.2.0'
    compile 'com.github.clans:fab:1.6.4'
    compile 'org.greenrobot:eventbus:3.0.0'
    compile 'com.amulyakhare:com.amulyakhare.textdrawable:1.0.1'
    compile 'com.google.android.gms:play-services:10.2.6'
    compile 'com.google.android.gms:play-services-location:10.2.6'
    compile 'com.google.android.gms:play-services-maps:10.2.6'
    compile 'com.google.firebase:firebase-core:9.2.0'
    compile 'com.google.firebase:firebase-messaging:9.2.0'
    compile 'com.bignerdranch.android:recyclerview-multiselect:+'
    compile 'com.facebook.stetho:stetho:1.5.0'
    compile 'com.uphyca:stetho_realm:2.0.0'
    compile 'com.lapism:searchview:4.0'
    compile 'com.miguelcatalan:materialsearchview:1.4.0'
    compile 'com.github.arimorty:floatingsearchview:2.1.1'
    compile 'me.philio:pinentryview:1.0.6'
    compile 'com.alimuzaffar.lib:pinentryedittext:1.3.1'
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.github.pchmn:MaterialChipsInput:1.0.8'

    /*----- Retrofit 2 */
    compile 'com.squareup.okhttp3:okhttp:3.4.1'
    compile 'com.squareup.okhttp3:okhttp-ws:3.4.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'io.reactivex.rxjava2:rxjava:2.0.2'
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
    compile 'com.google.dagger:dagger:2.11'
    compile 'com.google.dagger:dagger-android:2.11'
    compile 'javax.inject:javax.inject:1'
    compile 'io.realm:android-adapters:2.0.0'
    compile 'org.parceler:parceler-api:1.1.6'
    compile 'com.jakewharton:butterknife:8.5.1'
    compile 'com.theartofdev.edmodo:android-image-cropper:2.4.+'
    compile 'com.github.yalantis:ucrop:2.2.1-native'
    compile 'jp.wasabeef:picasso-transformations:2.1.2'
    compile 'jp.co.cyberagent.android.gpuimage:gpuimage-library:1.4.1'
    compile 'com.github.dmytrodanylyk:android-morphing-button:98a4986e56'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    annotationProcessor 'com.google.dagger:dagger-android-processor:2.11'
    annotationProcessor 'com.google.dagger:dagger-compiler:2.11'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.0.0-RC0'
    annotationProcessor 'org.parceler:parceler:1.1.6'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
    provided 'javax.annotation:jsr250-api:1.0'
    compile 'com.mikhaellopez:circularimageview:3.0.2'          // circle image view
}

apply plugin: 'com.google.gms.google-services'

Comment: try to **`clear-Rebuild-run`** your Project
Comment: Sorry nothing. same error
Comment: Related to https://github.com/google/dagger/issues/403
Answer: In my case I was updating the Gradle version, so I have the following lines in the dependencies:
compileOnly 'com.google.dagger:dagger:2.11'
annotationProcessor 'com.google.dagger:dagger-compiler:2.11'
testAnnotationProcessor "com.google.dagger:dagger-compiler:2.11"

but bassed on a tutorial, I found this lines and the problem was solved.
implementation 'com.google.dagger:dagger:2.11'
implementation 'com.google.dagger:dagger-android-support:2.11'
annotationProcessor 'com.google.dagger:dagger-compiler:2.11'
annotationProcessor 'com.google.dagger:dagger-android-processor:2.11'

Answer: You have to maintain your multidex library for that
add this gradle into your dependency
dependencies {
 compile 'com.android.support:multidex:1.0.1'
}

and enable multidex in
 android {
   defaultConfig {
    ...
    minSdkVersion 21
    targetSdkVersion 26
    multiDexEnabled true // check it carefully
 }
...
}

Now you have to create a MyApplication class and extend it to Application
 public class MyApplication extends Application {
  @Override
  protected void Create() {
    MultiDex.install(this);
  }
}

and define it into your manifest like
 <application
        android:name=".MyApplication" >
    ...
</application>

Now build your project and try to  run. I think now your problem will be solved
Answer: I faced the same problem and spent 2 - 3 hours over it and I am able to find that this problem is caused by dex limit. In your app.gradle file please make following changes:
defaultConfig {
    multiDexEnabled true
}

And inside dependencies section add
compile 'com.android.support:multidex:1.0.2'

and the last thing you need todo is,
public class YourApplication extends MultiDexApplication {
...
}

you have to use MultiDexApplication rather than Application class. Hope some dev comes out using this solution.
Answer: If any sdk in the app is using dagger dependency, then even app should add
dagger dependencies in app level build.gradle file.
In my scenario,SDK is using dagger dependencies.But I didn't include dagger dependencies in my App.
After including dagger dependencies in app,issue is solved.


Is it possible to use inheritance in AIDL interfaces?

Question: I want to share an interface via AIDL with client applications. I have been getting compile time errors. The code snippet is :-
interface ChildListener extends ParentListener {

    public void onUpdate(Class1  c1);
}

AIDL Set(All in the same package) -->
ChildListener.aidl - Contains the above code.
Class1.aidl - Declares Class1 as parcelable. Definition of Class1 implements parcelable.
ParentListener.aidl - Declares ParentListener.
Errors -->
I am getting compile time errors (while compiling service)
1. syntax error don't know what to do with "extends"
2. syntax error don't know what to do with "ParentListener "

It seems that we can not use inheritance in AIDL interfaces? Or is it that I am missing something here. Any pointers would be appreciated.
Best Regards
Comment: Has someone encountered such an error before?
Answer: You cannot use extend when you declare aidl interface. Aidl interface is of special format. It even does not correspond to java interface declaration.
If you specify what you want to do we will try to point you how to solve the problem.
Comment: Yes, aidl interfaces does not support inheritance. I figured that out. Thanks for the answer. For anyone else who wants to use aidl ---> 1). for data classes, when you make a class parcelable, you can handle the parent data members in the writeToParcel & static CREATOR fields.  2). For interfaces, drop all inheritance(if you are trying to reuse the existing design in aidl) to expose the mechanism to share the data classes in the simplest possible manner.


How to implement a Central Authentication Server in Django?

Question: I am trying to implement a Authentication Server using Django which will be used only for user authentication.
We have multiple services hosted on different subdomains like one.service.com, two.service.com, three.service.com etc. And we don't want our users to memorize/use different login credentials for each service. We want a system where user can authenticate themselves through the auth server and can access all the services of the subdomains.
Just think about Google or Microsoft, we just need one login credential and then we can access all of their services.
How can I implement this type of system for our services using Django ??
Note: We are primarily using JWTAuthentication for our servers.
Answer: Use SSO with SimpleJWT is the best and easier approach.
in Django settings set SESSION_COOKIE_DOMAIN to all subdomains use cookies and save tokens on that
check links for detail