text:
Q: Laying out a keyboard in Swing I've been trying to reproduce this layout:

Here I am:

using:
import javax.swing.*;
import java.awt.*;

public class Keyb {

    private JFrame f = new JFrame("Keyboard");

    private JPanel keyboard = new JPanel();

    private static final String[][] key = {
        {"`", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=", "Backspace"},
        {"Tab", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]", "\\"},
        {"Caps", "A", "S", "D", "F", "G", "H", "J", "K", "L", ";", "'", "Enter"},
        {"Shift", "Z", "X", "C", "V", "B", "N", "M", ",", ".", "/", "Shift", "\u2191"},
        {" ", "\u2190", "\u2193", "\u2192"}
    };

    public Keyb() {
        keyboard.setLayout(new GridBagLayout());

        JPanel pRow;
        GridBagConstraints c = new GridBagConstraints();
        c.anchor = GridBagConstraints.WEST;
        c.weightx = 1d;

        for (int row = 0; row < key.length; ++row) {
            pRow = new JPanel(new GridBagLayout());

            c.gridy = row;

            for (int col = 0; col < key[row].length; ++col)
                pRow.add(new JButton(key[row][col]));

            keyboard.add(pRow, c);
        }

        f.add(keyboard);
    }

    public void launch() {
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }

    public static void main(String[] args) {
        Keyb ui = new Keyb();
        ui.launch();
    }
}

How do I adjust the size of the buttons and align them perfectly, especially Tab, Caps, Shift, Backspace, Enter and the spacebar, perhaps without using the set?Size methods?
Can it be done in a better way with other layout managers?
New at Java, so any other suggestions are welcome.

A: When all else fails, write it your self...

This uses a custom layout manager which defines a "basic" grid but allows components in a given row to expand into portions of the following column(s)...
The default cell size is defined by the largest width/height of the available components that doesn't expand beyond it's own column, makes things a little more even.
Currently the output is anchored to the top/left corner, but I'm sure you can figure out how to calculate the x/y offset needed to get it centered ;)
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.LayoutManager2;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Keyb {

    private static final Key[][] keys = new Key[][]{
        {
            createKey("`", 0, 0),
            createKey("1", 0, 1),
            createKey("2", 0, 2),
            createKey("3", 0, 3),
            createKey("4", 0, 4),
            createKey("5", 0, 5),
            createKey("6", 0, 6),
            createKey("7", 0, 7),
            createKey("8", 0, 8),
            createKey("9", 0, 9),
            createKey("0", 0, 10),
            createKey("-", 0, 11),
            createKey("=", 0, 12),
            createKey("Backspace", 0, 13, 2d)},
        {
            createKey("Tab", 1, 0, 1.5d),
            createKey("W", 1, 2),
            createKey("E", 1, 3),
            createKey("R", 1, 4),
            createKey("T", 1, 5),
            createKey("Y", 1, 6),
            createKey("U", 1, 7),
            createKey("I", 1, 8),
            createKey("O", 1, 9),
            createKey("P", 1, 10),
            createKey("[", 1, 11),
            createKey("]", 1, 12),
            createKey("\\", 1, 13)
        },
        {
            createKey("Caps", 2, 0, 1.5d),
            createKey("A", 2, 2),
            createKey("S", 2, 3),
            createKey("D", 2, 4),
            createKey("F", 2, 5),
            createKey("G", 2, 6),
            createKey("H", 2, 7),
            createKey("J", 2, 8),
            createKey("K", 2, 9),
            createKey("L", 2, 10),
            createKey(";", 2, 11),
            createKey("'", 2, 12),
            createKey("Enter", 2, 13, 2d)
        },
        {
            createKey("Shift", 3, 0, 2d),
            createKey("Z", 3, 2),
            createKey("X", 3, 3),
            createKey("C", 3, 4),
            createKey("V", 3, 5),
            createKey("B", 3, 6),
            createKey("N", 3, 7),
            createKey("M", 3, 8),
            createKey(",", 3, 9),
            createKey(".", 3, 10),
            createKey("/", 3, 11),
            createKey("fill", 3, 12, 0.5d),
            createKey("\u2191", 3, 13),
        },
        {
            createKey("fill", 4, 0, 4d),
            createKey(" ", 4, 1, 6d),
            createKey("fill", 4, 2, 1.5d),
            createKey("\u2190", 4, 3),
            createKey("\u2193", 4, 4),
            createKey("\u2192", 4, 5),
        },
    };

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

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

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

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new KeyBoardLayout());
            for (int row = 0; row < keys.length; row++) {
                for (int col = 0; col < keys[row].length; col++) {
                    Key key = keys[row][col];
                    add(createButton(key.getText()), key.getKeyConstraint());
                }
            }
        }

        protected JComponent createButton(String text) {
            JComponent comp = null;
            if (text == null || text.equalsIgnoreCase("fill")) {
                comp = new JLabel();
            } else {
                comp = new JButton(text);
            }
            return comp;
        }

    }

    public static Key createKey(String text, int x, int y, double span) {
        return new Key(text).setKeyConstraint(new KeyConstraint(x, y, span));
    }

    public static Key createKey(String text, int x, int y) {
        return new Key(text).setKeyConstraint(new KeyConstraint(x, y));
    }

    public static class Key {

        private String text;
        private KeyConstraint keyConstraint;

        public Key(String text) {
            this.text = text;
        }

        public String getText() {
            return text;
        }

        public Key setKeyConstraint(KeyConstraint keyConstraint) {
            this.keyConstraint = keyConstraint;
            return this;
        }

        public KeyConstraint getKeyConstraint() {
            return keyConstraint;
        }

    }

    public static class KeyConstraint {

        public int row, column;
        public double span = 1d;

        public KeyConstraint(int row, int column) {
            this.row = row;
            this.column = column;
        }

        public KeyConstraint(int row, int column, double span) {
            this.row = row;
            this.column = column;
            this.span = span;
        }

    }

    public class KeyBoardLayout implements LayoutManager2 {

        private Map<Component, KeyConstraint> mapComponents;
        private Map<KeyConstraint, Component> mapConstraints;
        private Matrix<Integer, List<JComponent>> matrix = new Matrix<>(); // Virtual grid...

        private Dimension gridSize;

        public KeyBoardLayout() {
            mapComponents = new HashMap<>(25);
            mapConstraints = new HashMap<>(25);
        }

        @Override
        public void addLayoutComponent(String name, Component comp) {
            throw new UnsupportedOperationException("addLayoutComponent(String, Comp) is not supported");
        }

        @Override
        public void removeLayoutComponent(Component comp) {
            KeyConstraint kc = mapComponents.get(comp);
            mapComponents.remove(comp);
            if (kc != null) {
                mapConstraints.remove(kc);
                getCellContents(matrix, kc).remove(comp);
            }
        }

        @Override
        public Dimension preferredLayoutSize(Container parent) {
            int rowHeight = getRowHeight();
            Dimension size = new Dimension();
            size.width = getMaxRowWidth();
            size.height = rowHeight * matrix.getRowCount();
            return size;
        }

        @Override
        public Dimension minimumLayoutSize(Container parent) {
            return preferredLayoutSize(parent);
        }

        protected List<JComponent> getCellContents(Matrix matrix, KeyConstraint constraint) {
            return getCellContents(matrix, constraint.column, constraint.row);
        }

        protected List<JComponent> getCellContents(Matrix<Integer, List<JComponent>> matrix, int col, int row) {
            if (!matrix.contains(col, row)) {
                matrix.add(col, row, new ArrayList<>());
            }
            return matrix.get(col, row);
        }

        protected Dimension getGridSize() {
            if (gridSize == null) {
                int maxCellWidth = 0;
                int maxCellHeight = 0;
                for (int row = 0; row < matrix.getRowCount(); row++) {
                    for (int col = 0; col < matrix.getColumnCount(); col++) {
                        List<JComponent> cell = getCellContents(matrix, col, row);
                        int cellWidth = 0;
                        int cellHeight = 0;
                        for (JComponent comp : cell) {
                            KeyConstraint kc = mapComponents.get(comp);
                            if (kc.span == 1) {
                                cellWidth = Math.max(cellWidth, comp.getPreferredSize().width);
                            }
                            cellHeight = Math.max(cellHeight, comp.getPreferredSize().height);
                        }
                        maxCellWidth = Math.max(cellWidth, maxCellWidth);
                        maxCellHeight = Math.max(cellHeight, maxCellHeight);
                    }
                }
                gridSize = new Dimension(maxCellWidth, maxCellHeight);
            }
            return gridSize;
        }

        protected int getRowHeight() {
            Dimension size = getGridSize();
            return size.height;
        }

        protected int getRowWidth(int row) {
            int rowWidth = 0;
            for (int col = 0; col < matrix.getColumnCount(); col++) {
                Dimension size = getCellSize(col, row);
                rowWidth += size.width;
            }
            return rowWidth;
        }

        protected int getMaxRowWidth() {
            int rowWidth = 0;
            for (int row = 0; row < matrix.getRowCount(); row++) {
                rowWidth = Math.max(getRowWidth(row), rowWidth);
            }
            return rowWidth;
        }

        protected int getColumnWidth(int col) {
            int width = 0;
            for (int row = 0; row < matrix.getRowCount(); row++) {

                Dimension size = getCellSize(col, row);
                width = Math.max(size.width, width);

            }
            return width;
        }

        protected Dimension getCellSize(int col, int row) {
            List<JComponent> comps = matrix.get(col, row);
            Dimension size = new Dimension();
            size.height = getRowHeight();
            for (JComponent comp : comps) {
                Dimension subSize = getCellSize(col, row, comp);
                size.width = Math.max(size.width, subSize.width);
            }

            return size;
        }

        protected Dimension getCellSize(int col, int row, JComponent comp) {
            List<JComponent> comps = matrix.get(col, row);
            Dimension size = new Dimension();
            size.height = getRowHeight();
            int defaultWidth = getGridSize().width;
            KeyConstraint kc = mapComponents.get(comp);
            if (kc.span == 1) {
                size.width = defaultWidth;
            } else {
                int totalWidth = (int)Math.round(defaultWidth * kc.span);
                size.width = totalWidth;
            }

            return size;
        }

        @Override
        public void layoutContainer(Container parent) {
            int rowHeight = getRowHeight();
            int y = 0;
            for (int row = 0; row < matrix.getRowCount(); row++) {
                int x = 0;
                for (int col = 0; col < matrix.getColumnCount(); col++) {
                    List<JComponent> comps = matrix.get(col, row);
                    Rectangle bounds = new Rectangle();
                    bounds.x = x;
                    bounds.y = y;
                    int maxWidth = 0;
                    for (JComponent comp : comps) {

                        Dimension size = getCellSize(col, row, comp);
                        bounds.setSize(size);
                        maxWidth = Math.max(maxWidth, size.width);
                        comp.setBounds(bounds);

                    }
                    x += maxWidth;
                }
                y += rowHeight;
            }
        }

        @Override
        public void addLayoutComponent(Component comp, Object constraints) {
            if (constraints instanceof KeyConstraint) {
                mapComponents.put(comp, (KeyConstraint) constraints);
                mapConstraints.put((KeyConstraint) constraints, comp);
                getCellContents(matrix, (KeyConstraint) constraints).add((JComponent) comp);
            }
        }

        @Override
        public Dimension maximumLayoutSize(Container target) {
            return preferredLayoutSize(target);
        }

        @Override
        public float getLayoutAlignmentX(Container target) {
            return 0.5f;
        }

        @Override
        public float getLayoutAlignmentY(Container target) {
            return 0.5f;
        }

        @Override
        public void invalidateLayout(Container target) {
            gridSize = null;
        }

        public class Matrix<I, O> {

            private Map<I, Map<I, O>> mapRows;

            public Matrix() {
            }

            protected Map<I, Map<I, O>> getRowMap() {
                if (mapRows == null) {
                    mapRows = new HashMap<>(25);
                }
                return mapRows;
            }

            protected Map<I, O> getColumnMap(I row) {
                Map<I, Map<I, O>> rowMap = getRowMap();
                Map<I, O> mapCols = rowMap.get(row);
                if (mapCols == null) {
                    mapCols = new HashMap<>(25);
                    rowMap.put(row, mapCols);
                }
                return mapCols;
            }

            public void add(I col, I row, O obj) {
                Map<I, O> columnMap = getColumnMap(row);
                columnMap.put(col, obj);
            }

            public void remove(I col, I row, O obj) {
                if (contains(col, row)) {
                    Map<I, O> columnMap = getColumnMap(row);
                    columnMap.put(col, obj);
                }
            }

            public void removeColumn(I col) {
                for (I row : getRowMap().keySet()) {
                    Map<I, O> columnMap = getRowMap().get(row);
                    if (columnMap != null) {
                        columnMap.remove(col);
                    }
                }
            }

            public void removeRow(I row) {
                getRowMap().remove(row);
            }

            public int getRowCount() {
                return getRowMap().size();
            }

            public int getColumnCount() {
                int max = 0;
                for (I row : getRowMap().keySet()) {
                    Map<I, O> mapColumns = getRowMap().get(row);
                    max = Math.max(mapColumns.size(), max);
                }
                return max;
            }

            protected boolean containsRow(I row) {
                return getRowMap().containsKey(row);
            }

            protected boolean containsColumn(I col) {
                boolean contains = false;
                for (I row : getRowMap().keySet()) {
                    Map<I, O> columnMap = getRowMap().get(row);
                    if (columnMap != null && columnMap.containsKey(col)) {
                        contains = true;
                        break;
                    }
                }
                return contains;
            }

            public boolean contains(I col, I row) {
                boolean contains = false;
                Map<I, O> colMap = getRowMap().get(row);
                if (colMap != null) {
                    if (colMap.containsKey(col)) {
                        contains = true;
                    }
                }

                return contains;
            }

            public O get(I col, I row) {
                O value = null;
                if (contains(col, row)) {
                    Map<I, O> columnMap = getRowMap().get(row);
                    value = columnMap.get(col);
                }
                return value;
            }

            public boolean contains(O value) {
                boolean contains = false;
                for (I row : getRowMap().keySet()) {
                    Map<I, O> mapColumns = getRowMap().get(row);
                    for (I col : mapColumns.keySet()) {
                        if (mapColumns.containsValue(value)) {
                            contains = true;
                            break;
                        }
                    }
                }
                return contains;
            }

            public boolean rowContains(I row, O value) {
                boolean contains = false;
                Map<I, O> mapColumns = getRowMap().get(row);
                for (I col : mapColumns.keySet()) {
                    if (mapColumns.containsValue(value)) {
                        contains = true;
                        break;
                    }
                }
                return contains;
            }

            public boolean columnContains(I column, O value) {
                boolean contains = false;
                for (I row : getRowMap().keySet()) {
                    Map<I, O> mapColumns = getRowMap().get(row);
                    O colValue = mapColumns.get(column);
                    if (colValue == value) {
                        contains = true;
                        break;
                    }
                }
                return contains;
            }

            public O[] rowToArray(I row, O[] values) {
                List<O> lstValues = new ArrayList<O>(25);
                Map<I, O> mapColumns = getRowMap().get(row);
                lstValues.addAll(mapColumns.values());
                return lstValues.toArray(values);
            }

            public O[] columnToArray(I col, O[] values) {
                List<O> lstValues = new ArrayList<O>(25);
                for (I row : getRowMap().keySet()) {
                    Map<I, O> mapCols = getRowMap().get(row);
                    lstValues.add(mapCols.get(col));
                }
                return lstValues.toArray(values);
            }

            public Iterator<O> columnIterator(I col) {
                List<O> lstValues = new ArrayList<O>(25);
                for (I row : getRowMap().keySet()) {
                    Map<I, O> mapCols = getRowMap().get(row);
                    lstValues.add(mapCols.get(col));
                }
                return lstValues.iterator();
            }

            public Iterator<O> rowIterator(I row) {
                List<O> lstValues = new ArrayList<O>(25);
                Map<I, O> mapColumns = getRowMap().get(row);
                lstValues.addAll(mapColumns.values());
                return lstValues.iterator();
            }
        }
    }
}

A: Another approach. The only restriction is the use of a mono-spaced font to maintain the alignment.

import javax.swing.*;   // JFrame, JPanel, JLabel, JButton
import java.awt.*;      // GridBagLayout, GridBagConstraints, Insets, Font

public class Keyboard {
    private final JFrame f = new JFrame("Keyboard");

    private final JPanel keyboard = new JPanel();

    private static final String[][] key = {
        {"`", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=", "Backspace"},
        {"Tab", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]", "\\"},
        {"Caps", "A", "S", "D", "F", "G", "H", "J", "K", "L", ";", "'", "Enter"},
        {"Shift", "Z", "X", "C", "V", "B", "N", "M", ",", ".", "/", "\u2191"},
        {" ", "<", "\u2193", ">"}
    };

    public Keyboard() {
        keyboard.setLayout(new GridBagLayout());

        Insets zeroInset = new Insets(0, 0, 0, 0);
        Font monospace = new Font(Font.MONOSPACED, Font.PLAIN, 12);

        JPanel pRow;
        JButton b;

        GridBagConstraints cRow = new GridBagConstraints(),
                           cButton = new GridBagConstraints();
        cRow.anchor = GridBagConstraints.WEST;
        cButton.ipady = 21;

        // first dimension of the key array
        // representing a row on the keyboard
        for (int row = 0, i = 0; row < key.length; ++row) {
            pRow = new JPanel(new GridBagLayout());

            cRow.gridy = row;

            // second dimension representing each key
            for (int col = 0; col < key[row].length; ++col, ++i) {

                // specify padding and insets for the buttons
                switch (key[row][col]) {
                    case "Backspace":   cButton.ipadx = 0; break;
                    case "Tab":         cButton.ipadx = 17; break;
                    case "Caps":        cButton.ipadx = 10; break;
                    case "Enter":       cButton.ipadx = 27; break;
                    case "Shift":       cButton.ipadx = 27; break;
                    case "/":
                        cButton.insets = new Insets(0, 0, 0, 24);
                        break;
                    case " ":
                        cButton.ipadx = 247;
                        cButton.insets = new Insets(0, 192, 0, 72);
                        break;
                    default:
                        cButton.ipadx = 7;
                        cButton.insets = zeroInset;
                }

                b = new JButton(key[row][col]);
                b.setFont(monospace);
                b.setFocusable(false);
                pRow.add(b, cButton);
            }

            keyboard.add(pRow, cRow);
        }

        f.add(keyboard);
    }

    public void launch() {
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setResizable(false);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        Keyboard ui = new Keyboard();
        ui.launch();
    }
}


text:
Q: Why do we want to use a helper method in Java? I came across this block of code when I was studying for java CS61b, which used a helper method. As to why we use helper method, the explanation I got is that it makes it easier to do the recursive task. But I have trouble visualizing the alternative options where we don't use a helper method because I have difficulting write the solution. Does that mean using a helper method is the only way? I wish I could compare the two solutions and better understand the usage of a helper method.
here's the code in question:
    //Same as get, but uses recursion.
    public int getRecursive(int index) {
        if (index>size-1) {
            return 0;
        }
        node p = sentinel;
        return getRecursiveHelper(p, index);
    }

    public int getRecursiveHelper(node p, int i) {
        if (i==0) {
            return p.next.item;
        } else {
            p = p.next;
            i -= 1;
        }
        return getRecursiveHelper(p, i);

    }

the below is the full code:
public class LinkedListDeque {

    public node sentinel;
    public int size;

    public class node {
        public node prev;
        public int item;
        public node next;

        public node(node p, int i, node n) {
            prev = p;
            item = i;
            next = n;
        }
    }

    // Creates an empty list
    public LinkedListDeque() {
        sentinel = new node(null, 63, null);
        sentinel.prev = sentinel;
        sentinel.next = sentinel;
        size = 0;
    }

    // Adds an item of type T to the front of the deque.
    public void addFirst(int x) {
        sentinel.next = new node(sentinel, x, sentinel.next);
        sentinel.next.next.prev = sentinel.next;
        size += 1;
    }

    // Adds an item of type T to the back of the deque.
    public void addLast(int x) {
        sentinel.prev = new node(sentinel.prev, x, sentinel);
        sentinel.prev.prev.next = sentinel.prev;
        size += 1;
    }

    // Returns true if deque is empty, false otherwise.
    public boolean isEmpty() {
        if (size == 0) {
            return true;
        }
        return false;
    }

    // Returns the number of items in the deque.
    public int size() {
        return size;
    }

    // Prints the items in the deque from first to last, separated by a space. Once all the items have been printed, print out a new line.
    public void printDeque() {
        node p = sentinel.next;
        for (int i=0; i<size; i++) {
            System.out.print(p.item + " ");
            p = p.next;
        }
        System.out.println();
    }

    // Removes and returns the item at the front of the deque. If no such item exists, returns null.
    public int removeFirst() {
        if (size==0) {
            return 0;
        }
        int x = sentinel.next.item;
        sentinel.next = sentinel.next.next;
        sentinel.next.prev = sentinel;
        size -= 1;
        return x;
    }

    // Removes and returns the item at the back of the deque. If no such item exists, returns null.
    public int removeLast() {
        if (size==0) {
            return 0;
        }
        int x = sentinel.prev.item;
        sentinel.prev = sentinel.prev.prev;
        sentinel.prev.next = sentinel;
        size -= 1;
        return x;

    }

    // Gets the item at the given index, where 0 is the front, 1 is the next item, and so forth. If no such item e
    public int get(int index) {
        if (index>size-1) {
            return 0;
        }
        node p = sentinel.next;
        for (int i=0; i<index; i++) {
            p = p.next;

        }
        return p.item;
    }

    //Same as get, but uses recursion.
    public int getRecursive(int index) {
        if (index>size-1) {
            return 0;
        }
        node p = sentinel;
        return getRecursiveHelper(p, index);
    }

    public int getRecursiveHelper(node p, int i) {
        if (i==0) {
            return p.next.item;
        } else {
            p = p.next;
            i -= 1;
        }
        return getRecursiveHelper(p, i);

    }

    public static void main(String[] args) {
        LinkedListDeque L = new LinkedListDeque();
        L.addFirst(2);
        L.addFirst(1);
        L.addFirst(0);
        L.addLast(3);
        L.addLast(4);
        L.addLast(5);
        System.out.println(L.get(7));

    }

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: powershell - how to auto add and remove dhcp reservation with csv my client.csv format is:
ScopeId,Name,ClientId,Ipaddress
10.10.10.0,Computer1,1a-1b-1c-1d-1e-1f,10.10.10.10
10.10.10.0,Computer2,2a-2b-2c-2d-2e-2f,10.10.10.11
10.10.10.0,Computer3,3a-3b-3c-3d-3e-3f,10.10.10.12
my client.csv format (when the user's ClientID is null):
ScopeId,Name,ClientId,Ipaddress
10.10.10.0,Computer1,1a-1b-1c-1d-1e-1f,10.10.10.10
10.10.10.0,Computer2,2a-2b-2c-2d-2e-2f,10.10.10.11
10.10.10.0,Computer3,,10.10.10.12
and then run my powershell with my csv,auto add dhcp server reservations is successful,but when the user's ClientID is null ,powershell could not auto remove dhcp server rereservations,my powershell script has some problem?
$ComputerName="WIN-OO4RE715BV8.test.com"
if (!$args) {
    Write-Host "client.csv"
}
ELSE
{
    $dhcpdata=Import-CSV $args
    foreach ($dhcp in $dhcpdata){

        $ScopeId=$dhcp.ScopeId
        $Name=$dhcp.Name
        $ClientId=$dhcp.ClientId
        $IPAddress=$dhcp.IPAddress
        if ($ClientId -eq $null) {
            Remove-DhcpServerv4Reservation -ScopeId $ScopeId -Name $Name -ClientId $ClientId -IPAddress $IPAddress
        }
        Add-DhcpServerv4Reservation -ScopeId $ScopeId -Name $Name -ClientId $ClientId -IPAddress $IPAddress
    }
}

A:     $ComputerName="WIN-JA5I029SJFM.test.com"
    if(!$args){
    Write-Host "client.csv"
      }
    ELSE
    {

    $dhcpdata=Import-CSV $args
    foreach ($dhcp in $dhcpdata){

    $ScopeId=$dhcp.ScopeId
    $Name=$dhcp.Name
    $ClientId=$dhcp.ClientId
    $IPAddress=$dhcp.IPAddress
    Add-DhcpServerv4Reservation -ScopeId $ScopeId -Name $Name -ClientId $ClientId -
    IPAddress $IPAddress

    if(!$ClientId)
    {
        echo Remove-DhcpServerv4Reservation -ComputerName "$ComputerName" -IPAddress
    $IPAddress
        Remove-DhcpServerv4Reservation -ComputerName "$ComputerName" -IPAddress
    $IPAddress
       }
      }
    }


text:
Q: Intermittent "Failed to load viewstate" error Yes I know this problem has been reported many times, but my case doesn't seem to fit any proposed solutions (unless I miss something).
The ASP.NET page setup (simplified) is: user clicks a link (technically a node of Infragistics WebDataTree) and this action binds a grid (Infragistics WebHierarchicalDataGrid) located in an UpdatePanel.
Now this works fine in a local test system. When deployed to a production server - it also works - most of the times, but sometimes this throws error:

Failed to load viewstate. The control tree into which viewstate is
  being loaded must match the control tree that was used to save
  viewstate during the previous request

This seems to happen more if the production system under heavier load (more users accessing it). Again, I am not building any dynamic controls, just a button and a grid that is populated on button click.
What could be causing this? Why this doesn't happen always, but sometimes? Any idea how to fix it?
UPDATE
Here's confirmed scenario

*

*If one user accesses and uses the page - error doesn't happen

*If two user doing the same (can even be 2 browser sessions from the same client) - error happens.

How could one session affect viewstate of another?
UPDATE 2
Application is deployed to a single Windows 2008/IIS7 server (no web farms/web gardens, no load balancers). No updates rolls out during runtime.
Application works fine if a single users accesses it, but when multiple users hit the server - eventually some of them are getting ViewState error (while others still work fine). They're all doing the same thing - clicking tree nodes that trigger grid rebind inside of UpdatePanel. They use different browser - IE(9-11), FF, Chrome - error could happen to a random user/browser
Oh and we are not encrypting ViewState either.
UPDATE 3
Stack Trace:

at System.Web.UI.Control.LoadViewStateRecursive(Object savedState) at
  System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState)
  at System.Web.UI.Control.LoadViewStateRecursive(Object savedState) at
  System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState)
  at System.Web.UI.Control.LoadViewStateRecursive(Object savedState at
  System.Web.UI.Control.LoadChildViewStateByID(ArrayList childState) at
  System.Web.UI.Control.LoadViewStateRecursive(Object savedState) at
  System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState)
  at System.Web.UI.Control.LoadViewStateRecursive(Object savedState) at
  System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState)
  at System.Web.UI.Control.LoadViewStateRecursive(Object savedState) at
  System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState)
  at System.Web.UI.Control.LoadViewStateRecursive(Object savedState) at
  System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState)
  at System.Web.UI.Control.LoadViewStateRecursive(Object savedState) at
  System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState)
  at System.Web.UI.Control.LoadViewStateRecursive(Object savedState) at
  System.Web.UI.Page.LoadAllState() at
  System.Web.UI.Page.ProcessRequestMain(Boolean
  includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

UPDATE 4
It seems if I reduce size of the data returned with each click (e.g. 20 rows instead of 100) the issue either disappears or appears a lot less often.
I've tried manipulating ViewState - e.g. splitting it into chunks, using session as a ViewState storage to reduce actual posted page size - nothing has effect.

A: After following this advice on how to debug things outside of my code and gaining access to debug symbols for the Infragistics WebHierarchicalDataGrid DLL as well as its source code - turned out exception is thrown by the control - and its not related to the viewstate. Internally in a 1-element array code tries to access second element, throwing "IndexOutOfBound" exception which undergoes magical transformation to "Failed to load viewstate" thrown to the user.
Infragistics is looking into the error and ways to fix it, but since we're really pressed for time we used following workaround: If "view state" error is detected at the end of async postback - we simple reload the page:
Sys.Application.add_load(appLoaded);

function appLoaded(sender, eventArgs) {
   Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequest)
}

function EndRequest(sender, args) {
    if (args.get_error() != undefined) {
        if (args.get_error().message.indexOf('Failed to load viewstate') != -1) {
            setTimeout(function () { location.reload(true) }, 100)
        }
    }
}

Yes I do realize this is as elegant as hammering a nail with a screwdriver, but since the error is sporadic and refresh gets rid of it - this will have to do.

A: How many servers do you have in production? If there is more than one are you setting the machineKey in your web.config so that all servers will be using the same key to sign/validate the ViewState value?
As Michael Liu pointed out in a comment, it's unlikely you would get the control tree error for the machineKey problem. I would still like to know if you have multiple servers in production though because it could still be possible that you are running into an issue where ServerA served up newer version of the code and then the POST back occurred to ServerB which doesn't yet have the new code, so the control trees wouldn't match. This could technically happen even with a single server if you rolled out changes while there are active users on your site.

A: The viewstate are not related with the session state.
But, if you try the websiste with 2 instance of the same browser software, the browsers have the same session. This appends for IE>=8, firefox and chrome.
Try with 2 different browsers (sorry for my bad english)

A: It seems the UpdatePanel is causing a problem with the viewstate.
Update:
To debug, I would try to log the view states that are being sent out to each client and those that are being received back from the client during the partial post back.
You can store them temporariliy on your db server associated with a session, and clear them when the session is over if there was no exception. Then if you encounter this exception mark it in the db and you can compare what your server sent to the client and what was received back on postback. You can also manually load these values in your browser and replay them to see what happens.
Either the view state is being currupted client side or your server is sending out invalid view states.
At least this will help you get some data to debug.

Here is an article about update panels and some alternative ajax methods that might help solve the problem:
http://msdn.microsoft.com/en-us/magazine/cc163413.aspx
Some other possible helps:
http://lachlankeown.blogspot.com/2008/04/firefox-refresh-viewstate-updatepanel.html?m=1
http://weblog.west-wind.com/posts/2005/Jul/16/Invalid-ViewState
http://support.microsoft.com/default.aspx?scid=kb;EN-US;829743

A: If you host this in production using Load balancing, the problem could occur when a user changes from one server to another. The solution here is often to specify the machineKey in web.config. Read more about it here at msdn.
<machineKey
    validationKey="21F090935F6E49C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B"
    decryptionKey="ABAA84D7EC4BB56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F"
    validation="SHA1" decryption="AES" />

A: Are your users actually reporting the problem or are you just seeing it in error logs? I've seen this error before when the user cancelled a request on the browser, causing ASP.NET to error when attempting to parse a partially transmitted request. If the viewstate happened to be partially transmitted, you could see this error. The larger your viewstate & the more users you have the more likely you are to see this error. You can safely ignore this error.
You could test this by loading up a page with lots of viewstate and cancelling a postback.

A: I experienced similar issue sometime back in one of my project. The reason for the problem was that we were adding dynamic controls to a table control, and then on submitting the page the table would be populated by different set of controls. On looking deeply into the issue we found that mostly for the dropdown controls on the previous page if there is some other control at the same location the viewstate would fail.
The solution was extremely simple for us, since we were creating the controls dynamically they were anyways being created everytime, so we simply turned the ViewState=false for the control (in your case a grid control).
Based on your comment I think you need to identify what for you is spanning across the sessions. It may very well be the data that changes for the first user when another user is logged in. In that case also you should consider setting the ViewState=false, or binding the grid at page_Oninit, that way the ViewState would not conflict.
Hope this helps.

A: Try decompiling the dll with ILSpy, save the project, build it, than link that project instead of the dll. This way you will get the full stack trace, and maybe get closer to the exception.

A: I had the same problems when for example: clicking on a button that would redirect me, then press the back button on IE with the "old" viewstate, while some content had changed.
On IE, Chrome, Firefox, i had that problem due to caching.
To avoid browsers from caching your pages, you can use a random parameter in your url :
for ex : "&ran=54921356" that would randomely be generatad.
See if this helps
I don't know how your WebHierarchicalDataGrid is binded, your updatepanel wraping it shouldn't be viewstate enabled if data can change between a post-back and then going back.
I hope this helps !
PS: Also, i think that storing the viewstate in session is a bad idea...


text:
Q: How to apply a function to each row of a dataframe and get the results back This is my data Frame
            3        4        5        6       97       98       99      100
0         1.0      2.0      3.0      4.0     95.0     96.0     97.0     98.0
1     50699.0  16302.0  50700.0  16294.0  50735.0  16334.0  50737.0  16335.0
2     57530.0  33436.0  57531.0  33438.0      NaN      NaN      NaN      NaN
3     24014.0  24015.0  34630.0  24016.0      NaN      NaN      NaN      NaN
4     44933.0   2611.0  44936.0   2612.0  44982.0   2631.0  44972.0   2633.0
1792  46712.0  35340.0  46713.0  35341.0  46759.0  35387.0  46760.0  35388.0
1793  61283.0  40276.0  61284.0  40277.0  61330.0  40323.0  61331.0  40324.0
1794      0.0      0.0      0.0      0.0      0.0      0.0      0.0      0.0
1795      0.0      0.0      0.0      0.0      0.0      0.0      0.0      0.0
1796  27156.0  48331.0  27157.0  48332.0      NaN      NaN      NaN      NaN

--> How do I apply the below function and get the answers back for each row in one run...
values is the array of values of each row and N is 100
def entropy_s(values, N):
    a= scipy.stats.entropy(values,base=2)
    a = round(a,2)
    global CONSTANT_COUNT,RANDOM_COUNT,LOCAL_COUNT,GLOBAL_COUNT,ODD_COUNT
    if(math.isnan(a) == True):
        a = 0.0
    if(a==0.0):
        CONSTANT_COUNT += 1
    elif(a<round(math.log2(N),2)):
        LOCAL_COUNT +=1
        RANDOM_COUNT +=1
    elif(a==round(math.log2(N),2)):
            RANDOM_COUNT +=1
            GLOBAL_COUNT += 1
            LOCAL_COUNT += 1
    else:
        ODD_COUNT +=1

A: I assume that the values are supposed to be rows? in that case, I suggest the following:
rows will be fed to function and you can get the column in each row using row.column_name.
def func(N=100):
  def entropy_s(values):
    a= scipy.stats.entropy(values,base=2)
    a = round(a,2)
    global CONSTANT_COUNT,RANDOM_COUNT,LOCAL_COUNT,GLOBAL_COUNT,ODD_COUNT
    if(math.isnan(a) == True):
        a = 0.0
    if(a==0.0):
        CONSTANT_COUNT += 1
    elif(a<round(math.log2(N),2)):
        LOCAL_COUNT +=1
        RANDOM_COUNT +=1
    elif(a==round(math.log2(N),2)):
            RANDOM_COUNT +=1
            GLOBAL_COUNT += 1
            LOCAL_COUNT += 1
    else:
        ODD_COUNT +=1
  return entropy_s

df.apply(func(100), axis=1)

if you want to have the rows as list you can do this:
df.apply(lambda x: func(100)([k for k in x]), axis=1)

A: import functools
series = df.apply(functool.partial(entropy_s, N=100), axis=1)
# or
series = df.apply(lambda x: entropy_s(x, N=100), axis=1)

axis=1 will push the rows of your df to the first arg of apply.
You will get a pd.Series of None's though, because your function doesn't return anything.
I highly suggest to avoid using globals in your function.
EDIT: If you want meaningful help, you need to ask meaningful questions. Which errors are you getting?
Here is a quick and dirty example that demonstrates what I've suggested. If you have an error, your function likely has a bug (for example, it doesn't return anything), or it doesn't know how to handle NaN.
In [6]: df = pd.DataFrame({1: [1, 2, 3], 2: [3, 4, 5], 3: [6, 7, 8]})

In [7]: df
Out[7]:
   1  2  3
0  1  3  6
1  2  4  7
2  3  5  8

In [8]: df.apply(lambda x: np.sum(x), axis=1)
Out[8]:
0    10
1    13
2    16
dtype: int64


text:
Q: Is there a way to insert a row with no data Using CakePHP 3.3, I have a table that only contains a primary key. This is used as a sequence. In CakePHP, I insert a row with no data and it generates a new row.
Cake 2.7
class Identity extends AppModel {

    function nextVal() {
        $data = [];
        $this->create();
        $this->save($data);
        return $this->id;
    }
}

I am attempting to duplicate this behavior in CakePHP 3.3 and it isn't doing what I expect.
CakePHP 3.3
class IdentityTable extends Table
{
    public function generate() {
        $identity = $this->newEntity();
        if ( $this->save($identity) ) {
            // The $ccn entity contains the id now
            \Cake\Log\Log::debug(__METHOD__. ' success');
            return $identity->id;
        }
        \Cake\Log\Log::debug(__METHOD__. ' failed');
        return false;
    }
    //
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('identity');
        $this->displayField('identityId');
        $this->primaryKey('identityId');
    }
}

MySQL is perfectly happy with this:
INSERT INTO `identity` () VALUES()

I am thinking that the CakePHP 3.x ORM sees that I am not inserting anything and it bailing on the save.
Is there a way in CakePHP 3 to insert a row with no data?

A: You have to tell cake that something is cahenged in the entity and mark it as 'dirty'. i.e.
$identity ->dirty('id', true);

so the resulting query will be
INSERT INTO sic_suppliers (id) VALUES (NULL)

that I guess is ok for you
PS
don't know if this is the best way to achieve this but it seems to work.
Edit: following @ndm suggestion you can also insert the record directly (see the cookbook)
$this->query()->insert(['id'])
    ->values([null])
    ->execute();


text:
Q: Problema com case no script Alguém me explica por qual motivo meu script está retornando apenas a opção "Error"?
#!/bin/bash

#==========================#
DATA=$(date +%T) #Vai mostrar a hora com os mins
CORTE=$(date +%k) #Vai mostrar apenas a hora, tipo 18 ou 12 horas, sem os mins
#==========================#

echo $CORTE #Verificar como ficou o resultado da variável CORTE

case $CORTE in #Dependendo da numeração da variável CORTE irá mostrar diferentes mensagens
    [6-11])
        echo "Bom dia!"
        ;;
    [12-17])
        echo "Boa tarde!"
        ;;
    [18-23])
        echo "Boa noite!"
        ;;
    [0-5])
        echo "Boa noite!"
        ;;
    *)
        echo "Error"
        ;;
esac

echo "Horário: $DATA" #Para finalizar irá mostrar as horas com os mins

A: Pelo que me lembro o case não reconhece ranges, tente assim:
if ((6<=$CORTE && $CORTE<=11)); then
    echo "Bom dia!"
elif ((12<=$CORTE && $CORTE<=17)); then
    echo "Boa tarde!"
elif ((18<=$CORTE && $CORTE<=23)); then
    echo "Boa noite!"
elif ((0<=$CORTE && $CORTE<=5)); then
    echo "Boa madruga! :-)"
else
    echo "Error"
fi

Se vc for obrigado a utilizar o case acho que vai ter que fazer com or, um trabalhão, algo como:
case $CORTE in
    6|7|8|9|10|11) echo 'Bom dia!';;
    12|13|14|15|16|17) echo 'Boa tarde!'
    # ....
esac


text:
Q: javascript break down VIN number I want to use javascript to break down the VIN in an array, probably using a regex and then some kind of loop...
Here's how to read VIN's:
http://forum.cardekho.com/topic/600-decoding-vehicle-identification-number-vin/
I'm really asking about best practice, not a copy+paste solution...I can probably get the regex groups, but after that, how do I use those values to, for example, say first digit is "5", that means USA. I want to output "USA" somewhere...is the best way to use some kind of case loop?
Thanks for the advice!

A: You can simply split up the string and plug it into an associative array.
var origin = { '5': 'USA', "6": 'Other Country' };
var fuel= { 'J': 'GAS', "D": 'Other' };

var VINString = "5 J";
var VINArray = VINString.split(' ');

document.write(origin[VINArray[0]]);
document.write(fuel[VINArray[1]]);

This will allow for keys of both letters (ie 'J') and numbers (ie '5')
I'm not sure why you would use regex.... just cut up the string and send the values directly into the associative array.  The VIN is of pre-defined lengths and values.
Cheers


text:
Q: Constraint to randomize such a way that consecutive 2 bits are set to 1, other bits are 0 for 16-bit variable I need to write a constraint to randomize such a way that consecutive 2 bits are set to 1, other bits are 0 (i.e. 16'b0000_0000_0011, 16'b0000_1100_0000, etc.) for a 16-bit variable.
I tried using $countones.  It is working for two bits but is not working consecutive 2 bits.  Its display is
# Value is 10000000000100
# Value is 10000000010

A: One simple way is to use a random index variable which is constrained between 0 and 14, then use another constraint to set only the 2 bits of your data.
module tb;

class c;
    rand bit [ 3:0] idx;
    rand bit [15:0] data;
    constraint c0 {
        idx < 15;
        data == (3 << idx);
    }
endclass

initial begin
    c c;
    c = new();
    repeat (20) begin
        c.randomize();
        $displayb(c.data);
    end
end

endmodule

Example output:
0000110000000000
0000011000000000
0000110000000000
0110000000000000
0000110000000000
0000000000110000
0000000110000000
0000110000000000
0000110000000000
0000001100000000
0000000000000011
0000001100000000
0000110000000000
0001100000000000
0000110000000000
0000000110000000
0011000000000000
0000000000110000
0000000000110000
0000001100000000


text:
Q: Parsing a specific website crashes the Python process Looking to parse an HTML page for images (from http://www.z-img.com), and when I load the page into BeautifulSoup (bs4), Python crashes. The "problem details" shows that etree.pyd was the "Fault Module Name", which means its probably a parsing error, but so far, I can't quite nail down the cause of it.
Here's the simplest code I can boil it down to, on Python2.7:
import requests, bs4

url = r"http://z-img.com/search.php?&ssg=off&size=large&q=test"
r = requests.get(url)
html = r.content
#or
#import urllib2
#html = urllib2.urlopen(url).read()
soup  = bs4.BeautifulSoup(html)

along with a sample output on PasteBin (http://pastebin.com/XYT9g4Lb), after I had passed it through JsBeautifier.com.

A: This is a bug that was fixed in lxml version 2.3.5. Upgrade to version 2.3.5 or later.

A: Oh, there you go, naturally the first thing I try after I submit the question is the solution: the <!DOCTYPE> tag seems to be at the root of it. I created a new HTML file, temp.html:
<!DOCTYPE>
<html>
</html>

and passed that to BeautifulSoup as an HTML string, and that was enough to crash Python again. So I just need to remove that tag before I pass the HTML to BeautifulSoup in the future:
import requests, bs4

url = r"http://z-img.com/search.php?&ssg=off&size=large&q=test"
r = requests.get(url)
html = r.content
#or
#import urllib2
#html = urllib2.urlopen(url).read()

#replace the declaration with nothing, and my problems are solved
html = html.replace(r"<!DOCTYPE>", "")
soup  = bs4.BeautifulSoup(html)

Hope this saves someone else some time.


text:
Q: How to find .xml link and date only via Regular Expression I am trying to match .xml link and expire date from following string.

| iptv: { 1 } { 8000 } { localhost.test/categories/music.xml } { golden } { 000000 } { 01 02 03 04 05 06 07 08 09 10 11 12 13 14 } { 1 } | msg: { 1 } { 0 } { Welcome expire: 2020-01-20 } { 0 } { 0 } { 00 } { 0 }

I have tried the following rule to match it
/\}\s+\{\s+[^>]*xml\s+\}/igm

Honestly I don't understand regular expression and my try may be totally useless.
My PHP code:
$str = '| iptv: { 1 } { 8000 } { localhost.test/categories/music.xml } { golden } { 000000 } { 01 02 03 04 05 06 07 08 09 10 11 12 13 14 } { 1 } | msg: { 1 } { 0 } { Welcome expire: 2020-01-20 } { 0 } { 0 } { 00 } { 0 }';
$rule = '/\}\s+\{\s+[^>]*xml\s+\}/igm';
preg_match_all('', $str, $matches);

My desire output
localhost.test/categories/music.xml and 2020-01-20

A: The pattern that you use matches from the first closing } until the closing } after .xml
You might use an alternation and a capturing group to match either one. For the date you could use a date like pattern. Note that it does not validate the date itself.
{[^[{}]*\h(\S+\.xml|\d{4}-\d{2}-\d{2})\h}

Explanation

*

*{ Match literally

*[^[{}]*\h Negated character class, match 0+ times not { or }, then a horizontal whitespace char

*( Capture group 1

*

*\S+\.xml Match 1+ times a non whitespace char, . and xml

*| Or

*\d{4}-\d{2}-\d{2} Match a date like pattern using digits and -

*)\h Close group 1 and match a horizontal whitespace char

*} Match literally

Regex demo | Php demo
If you want group 1 and group 2, you might use:
{\h(\S+\.xml)\h}.*?{\h[^:]+:\h(\d{4}-\d{2}-\d{2})\h}

Explanation

*

*{\h Match { and a horizontal whitespace char

*( Capture group 1

*

*\S+\.xml Match 1+ times a non whitespace char, . and xml

*) Close group 1

*

*\h} Match horizontal whitespace char and }

*.*?{ Match any char except a newline 0+ times non greedy and match {

*\h[^:]+:\h Match 1+ times not :, then match :

*( Capture group 2

*

*\d{4}-\d{2}-\d{2} Match a datelike pattern

*) Close group 2

*\h} Match horizontal whitespace char and }
Regex demo | Php demo


text:
Q: AngularJS form validation I have simple form:
<form  class="form-horizontal" name="loginForm" novalidate ng-click="login()" >

and inputs inside with "required":
<input required class="input-xlarge" ng-model="uEmail" placeholder="Email" type="email">

When user load the form always show error on startup.
How to start validation after user interaction?

A: you can simply use
Required input


text:
Q: How to create a UILabel or UITextView with bold and normal text in it? I am trying to create a UILabel or UITextView with bold and normal text inside.
I have gone through the attributedstring but when I am setting this in label of my custom cell it doesn't display any text.
I have also used the UITextView setContentToHTMLString: method, but it is undocumented and app get rejected.
Can anyone give some sort of solution to this?

A: Up until iOS 6.0, you couldn't do this with a normal UILabel or UITextView, but you can use NSAttributedString objects with a few possible open source solutions.
Like TTAttributedLabel or OHAttributedLabel.
One solution built into the iOS SDK, you could also use a CATextLayer which has a string property that can be set to a NSAttributedString.
And, like the commenters below say, yes you can do this with the "attributedText" property.  Horray! (for Apple listening to developer's very often repeated feature requests)

A: Use "NSAttributedString" to set multiple font text in a single label & use CATextLayer to render it:
just #import "NSAttributedString+Attributes.h"
and then implement it like this:
NSString *string1 = @"Hi";

NSString *string2 = @"How are you ?";

NSMutableAttributedString *attr1 = [NSMutableAttributedString attributedStringWithString:string1];

[attr1 setFont:[UIFont systemFontOfSize:20]];

NSMutableAttributedString *attr2 = [NSMutableAttributedString attributedStringWithString:string2]

[attr2 setFont:[UIFont boldSystemFontOfSize:20]];

[attr1 appendAttributedString:attr2]

CATextLayer *textLayer = [CATextLayer layer];

layer.string = attr1;

layer.contentsScale = [[UIScreen mainScreen] scale];

(Your_text_label).layer = textLayer;

OR (if you want to render on a view directly)

[(Your_View_Name).layer addSublayer:textLayer];

A: I know this is an old thread, but this is something I just discovered myself. At least in Xcode version 4.6.3 this is possible by using an attributed textView. What's even better is that it's possible to all be done in Interface Builder!
Here are the steps:
Place your textView at the desired location
Select the textView and open up the Attributes tab under the Utilities panel
Change the textView text to "attributed"
Enter your desired text
Now, highlight whatever text you want bolded, underlined, etc.
Click on the "T" button next to the fontName
In the popup, select your desired typeface (ex: Bold)
You should see the desired typeface displayed in the Utilities panel
Enjoy!

A: The following code is for iOS 6.0 and above. The result is that the text "This is bold" will be in bold and "This is not bold." will be normal text.
if ([self.registrationLabel respondsToSelector:@selector(setAttributedText:)])
{
    // iOS6 and above : Use NSAttributedStrings
    const CGFloat fontSize = 17;
    UIFont *boldFont = [UIFont boldSystemFontOfSize:fontSize];
    UIFont *regularFont = [UIFont systemFontOfSize:fontSize];
    //UIColor *foregroundColor = [UIColor clearColor];

    // Create the attributes
    NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:
                              boldFont, NSFontAttributeName, nil];
    NSDictionary *subAttrs = [NSDictionary dictionaryWithObjectsAndKeys:
                              regularFont, NSFontAttributeName, nil];
    const NSRange range = NSMakeRange(0,12); // range of " 2012/10/14 ". Ideally this should not be hardcoded

    // Create the attributed string (text + attributes)
    NSString *text = @"This is bold and this is not bold.;
    NSMutableAttributedString *attributedText =
    [[NSMutableAttributedString alloc] initWithString:text
                                           attributes:subAttrs];
    [attributedText setAttributes:attrs range:range];

    // Set it in our UILabel and we are done!
    [self.registrationLabel setAttributedText:attributedText];
}

A: If you have an issue with editing the attributed text in the inspector, copy/paste the text into a rich text editor, adjust it, switch the textView Text options to Attributed and paste. Vwala.


text:
Q: How to set tooltips to combobox items @ VB.NET? I have a combobox with a given width.
It may occur that one row of the data is partially hidden (the combobox might be too narrow). I'd like to show the whole line by using a tooltip or right-click context menu.
Currently I can't find how to 'catch' the row that I'm currently holding on or passing over by mouse. Please tell me.
Thanks in advance!

A: Have you tried to increase the DropDownWidth property so that everything is visible?
Edit: To find the ideal width based on the items in the list:
var maxLength = 0;
// using the ComboBox to get a Graphics object:
using (var g = Graphics.FromHwnd(comboBox2.Handle)) {
  foreach (var item in comboBox2.Items.Cast<string>()) {
    var itemLength = g.MeasureString(item, comboBox2.Font);
    maxLength = Math.Max((int) itemLength.Width, maxLength);
  }
}
if (comboBox2.Items.Count > comboBox2.MaxDropDownItems) {
  // correction when ScrollBar is displayed
  maxLength += 15;
}
comboBox2.DropDownWidth = maxLength;

I put this code in the DropDown event of the ComboBox for testing. Maybe you can find a better place for it, like after populating the ComboBox...

A: Going in the same direction that Julien went, here is a generic extension method that will resize the drop down area regardless of how the combobox is filled (manually with strings or via data binding).
<Extension()> _
Public Sub AutosizeDropDownWidth(ByVal combobox As ComboBox)
    Dim longestItem As Integer = 0
    Using g = Graphics.FromHwnd(combobox.Handle)
        Dim itemsAsText = (From item In combobox.Items _
                           Select combobox.GetItemText(item))
        longestItem = CInt(itemsAsText.Max(Function(text) g.MeasureString(text, combobox.Font).Width))
    End Using

    ' Account for scrollbar
    If (combobox.Items.Count > combobox.MaxDropDownItems) Then longestItem += 15

    ' Resize as needed (but never smaller than the default width)
    combobox.DropDownWidth = Math.Max(longestItem, combobox.Width)
End Sub

To use it then you can simply do the following...
Private Sub MyCombobox_DropDown(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyCombobox.DropDown
    MyCombobox.AutosizeDropDownWidth()
End Sub

Note, I didn't test corner cases like an empty combobox in this code example.

A: Your're right, there really isn't a "Item.OnMouseOver", but I suppose you could (off the top of my head, so I've likely forgotten something)...

*

*inherit from ComboBox,

*override OnDrawItem (you may need to turn change .DrawMode to "Owner Drawn").

*

*you will know which item is hovered in the OnDrawItem event/override from the EventArgs.

*Set the tooltip on the control at that point.

*optionally set a timer to manually show the tooltip if the above doesn't work automatically.


text:
Q: how many bytes are reserved for stdin, std_out, stdderror, stdprt, and stdaux? how many bytes are reserved for stdin, std_out, stdderror, stdprt, and stdaux?
every pc seems to describe the std streams as set up by the os, yet i'm trying to build my own os, and that means making my own std streams,
I'D LIKE DETAILS FOR CONSOLE, FILE AND NETWORK
its because i'm using masm and need to give it at least an initial storage size

A: i'm going to use 1048576 bits, i'll adjust this answer if its wrong


text:
Q: Importing module from Github to use in Python I'm a beginner in Python and I have no experience with GitHub at all. I want to import the module semsimlib from the following URL: https://github.com/timvdc/semsimlib
I have looked on the internet for help on how to do this but most of it is very unclear and doesn't seem to work for me. Can anyone provide a detailed explanation on how to do this in a easy way?

A: It looks the repo does not provide appropriate scripts to simply install the package. There is no setup.py file and there is no distribution on pypi.
What you can do is go to site-packages folder inside your python installation or inside your virtual environment. Then run git clone https://github.com/timvdc/semsimlib. You should now be able to import semsimlib. Keep in mind that you will also have to install all the other dependencies your self one by one since there is also no requirements file.
You can also clone the repo into any folder on your computer and at the top of your script put:
import sys
sys.path.append("path/to/semsimlib/folder")

semsimlib will now be importable. However, I would try to get it to work with the first method.


text:
Q: Tensorflow define a operation that builds the product of all tensor components I want to define a operation in tensorflow that calculates something like:

x is provided by a tensor. Finally the operation should be compared to a known value and parameters alpha, beta i and b should be learned.
(I guess) The product of all inputs causes trouble. This is one version that I tried to deploy, with no success.
    # input
    X = tf.placeholder(tf.float32, [None, 2], name="X")
    Y = tf.placeholder(tf.float32, [None, 1], name="Y")
# hidden
beta = tf.get_variable("beta", shape=[2], initializer=tf.contrib.layers.xavier_initializer())
powered = tf.pow(X,beta)
productLayer = tf.contrib.keras.layers.multiply(powered) # bad line

# output
w_o = tf.get_variable("w_o", shape=[1], initializer=tf.contrib.layers.xavier_initializer())
b_o = tf.get_variable("bias", shape=[1], initializer=tf.zeros([1]))

output = tf.add(tf.matmul(productLayer,w_o), b_o)
loss = tf.reduce_sum(tf.square(output - Y)) # tf.nn.l2_loss(yhat - Y)

Running the full script from gist
https://gist.github.com/anonymous/c17d45b4e997bfccb5275dffa44512d6
is resulting in the error message:

File "h2o_test_opti.py", line 13, in
      productLayer = tf.contrib.keras.layers.multiply(powered) ValueError: A merge layer should be called on a list of inputs.

I thought the functionality describtion of tf.contrib.keras.layers.multiply fits to my needs. I also tried to find a naive way like a for-loop to calculate the product of all incoming tensor-elements, but with no success, as I couldn't imagine a way to access the tensor in a right way. Choosing the correct indicies isn't(?) possible, as I don't know the current step and therefore the right tensor to be treated?
I want to test this as an "activation-function" (properly more as optimization/fitting procedure)
Please let me know if there is more information required to help with this problem.

A: I found an working solution to my idea by
changing:
    productLayer = tf.contrib.keras.layers.multiply(powered) # bad line

to:
    productLayer = tf.reshape(tf.reduce_prod(X,1), (-1,1))

It should work. Maybe someone can use this too.


text:
Q: Query() DynamoDB for each value in array on Lambda NodeJS I have the following code in a NodeJS 12x Lambda function:
targetedAliases = ["abc", "efg"]; //Not used yet. But want to replace alias with this array.
alias = "abc" //using this one aka targetedAliases[0].

const dynamoDB = new AWS.DynamoDB({
    apiVersion: "2012-10-08"
});
var aliasScores;

const params = {
    TableName: 'a-table',
    FilterExpression: '#alias = :alias',
    ExpressionAttributeNames: {
        '#alias': 'alias',
    },
    ExpressionAttributeValues: {
        ':alias': {
            S: alias
        },
    }
};

aliasScores = await dynamoDB.scan(params).promise();

console.log("====> ", aliasScores);

The function as is prints the content of aliasScores as expected but I need to execute this n times for each item on the targetedAliases array.
Is there a way I can use a Array.forEach or something similar to execute a query/scan iteratively for each item in an array? Alternatively, can I use an array on the FilterExpression to execute the query/scan just once?
I want store each query/scan result in the aliasScores variable as a concatenation of all returned objects to use it further below.

A: You can use Promise.all with .map to execute these in parallel and get the results in array. Something like this
const targetedAliases = ["abc", "efg"]; //Not used yet. But want to replace alias with this array.
alias = "abc" //using this one aka targetedAliases[0].

const dynamoDB = new AWS.DynamoDB({
    apiVersion: "2012-10-08"
});
var aliasScores;

const result = await Promise.all(targetedAliases.map(alias => {
  const params = {
    TableName: 'a-table',
    FilterExpression: '#alias = :alias',
    ExpressionAttributeNames: {
        '#alias': 'alias',
    },
    ExpressionAttributeValues: {
        ':alias': {
            S: alias
        },
    }
};

return dynamoDB.scan(params).promise();
}));

console.log(result);

A: Your options kinda depend on whether the attribute alias is a primary key or not.  Just knowing this difference will help a lot.
Promise.all() executes one operation for each alias. Consider the batch approach. A single batch for executes in one API invocation which will reduce the number of operations and reduce your DynamoDB API calls. Batching is fun.
When the attribute key 'alias' is the primary key, BatchGetItem a is very efficient operation for up to a dozen or so operations where each operation is a query for one alias.  Just create a single BatchGetItem with one operation for each entry in the array.  The response is a single json dictionary.
When the attribute key 'alias' is not the primary key then it's different because the table must be scanned. A DynamoDB scan() is different than a DynamoDB query(). scan can find items by any attribute and can filter by the value of 'alias.'  The FilterExpression supports OR and it is possible to filter the scan. The scan will check every item and the filter just reduces the returned result set.  The response is a single json dictionary.


text:
Q: saving the numpy image datasets. without increase in size and easy to save and load data i have saved my train test val array into pickle file. but the size of images is 1.5GB ,pickle file is 16GB i.e size increased. is another any another way to save those numpy images array without increase in size?

A: Use numpy.save function (documentation) or numpy.savez_compresion function (documentation).
Read documentation before ask question.
Sample code:
import numpy as np

image = np.random.randint(0, 200, (199818,50,50,3), dtype=np.uint8)
image2 = np.random.randint(0, 200, (1998,50,50,3), dtype=np.uint8)

np.savez_compressed("test.npz", image, img=image2)

img_dkt = np.load("test.npz")

print("First_array:", img_dkt["arr_0"].shape, "equality", np.all(image == img_dkt["arr_0"]))
print("second_array:", img_dkt["img"].shape, "equality", np.all(image2 == img_dkt["img"]))


text:
Q: Selenium Chromedriver timeout issue in Java project I can't figure out how to properly configure selenium tests to run in an Ubuntu VM.
On Windows, where I have eclipse IDE, works properly though.
Here is a part of the java code of the testNGclass:
@BeforeClass(alwaysRun = true)
public void setUp() throws Exception {

    if (SystemUtils.IS_OS_LINUX)
        System.setProperty("webdriver.chrome.driver", "/usr/bin/selenium/chromedriver/chromedriver");

    if(SystemUtils.IS_OS_WINDOWS)
        System.setProperty("webdriver.chrome.driver", ""+System.getProperty("user.dir").toString()+"/lib/chromedriver.exe");

    driver = new ChromeDriver();

    System.out.println(System.getProperty("portletToTest"));
    baseUrl = "http://www.google.it";
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

@Test
public void test() throws Exception {
    driver.get(baseUrl + "/");

The error I keep getting is this, from testNG report  (except for the port of localhost: , which vary everytime I run it)
org.openqa.selenium.WebDriverException: Timed out waiting for driver server to start.
Build info: version: 'unknown', revision: '1969d75', time: '2016-10-18 09:43:45 -0700'
System info: host: 'esvn', ip: '192.168.5.182', os.name: 'Linux', os.arch: 'amd64', os.version: '3.5.0-54-generic', java.version: '1.8.0_121'
Driver info: driver.version: ChromeDriver
    at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:178)
    at org.openqa.selenium.remote.service.DriverService.start(DriverService.java:166)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:78)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:601)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:241)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:128)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:141)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:174)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:163)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:120)
    at Automation.profileuserportlet.setUp(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:104)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:515)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:217)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:144)
    at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:169)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
    at org.testng.TestRunner.privateRun(TestRunner.java:756)
    at org.testng.TestRunner.run(TestRunner.java:610)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:387)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:382)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
    at org.testng.SuiteRunner.run(SuiteRunner.java:289)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1293)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1218)
    at org.testng.TestNG.runSuites(TestNG.java:1133)
    at org.testng.TestNG.run(TestNG.java:1104)
    at org.testng.TestNG.privateMain(TestNG.java:1434)
    at org.testng.TestNG.main(TestNG.java:1403)
Caused by: org.openqa.selenium.net.UrlChecker$TimeoutException: Timed out waiting for [http://localhost:17352/status] to be available after 20008 ms
    at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:107)
    at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:175)
    ... 34 more
Caused by: com.google.common.util.concurrent.UncheckedTimeoutException: java.util.concurrent.TimeoutException
    at com.google.common.util.concurrent.SimpleTimeLimiter.callWithTimeout(SimpleTimeLimiter.java:143)
    at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:80)
    ... 35 more
Caused by: java.util.concurrent.TimeoutException
    at java.util.concurrent.FutureTask.get(FutureTask.java:205)
    at com.google.common.util.concurrent.SimpleTimeLimiter.callWithTimeout(SimpleTimeLimiter.java:130)
    ... 36 more

I've doube checked the chromedriver file path on linux, it's ok and the file has executable permissions.
Do I also have to start the chromedriver executable on the linux machine? Do I have to do something else than running the compiled java project?

A: Your chrome driver should have correct version that matches chrome browser.


text:
Q: Array of objects to array of array came as a string I have JSON object oAtt declared as
var oAtt = MessageStore.message().attachments();
MessageStore.message() is declared in the code available here: https://github.com/RainLoop/rainloop-webmail/blob/master/dev/Model/Message.js
When I output it to the console oArr came as  [object Object],[object Object]. After stringify it came as:
 var oAtt = [
    {"sModelName":"AttachmentModel","disposables":[],"mimeType":"application/pdf","fileName":"sample.pdf","fileNameExt":"pdf","fileType":"pdf","description":null,"estimatedSize":19333,"friendlySize":"19KB","isInline":false,"isLinked":false,"isThumbnail":false,"cid":"","cidWithOutTags":"","contentLocation":"","download":"zyfTZvzczVW6cqlcsIrm3ycmY5soz3DzK5sZhjnSOwaW0wnwGwHtqBvPeo8nVpiWD4yKVIPvAPauJHZufHGRG0Eb4MRmBpkGlvsDGP-gz3CnVp4GorN_xXCI0Gkd2I93IySKMy5iXRt-wML9wxLwTZcrOMLyPp-Kr6b0GlzlHuvk3RqEXRqSlCQTX5piRO6AaRYeMKeq8PSJcId1grMYzFpCnjVSoW_Zj7yTGAsy-D_mzFoCmBdksCweEqPdGhFYFkukblXzaZiTSNGTj1xYOvMIN4XXUZtU0EAPoQ9EFxfPWY_-1Siyge0Gks2zbGs3myxXJg..","folder":"INBOX","uid":"22","mimeIndex":"2","framed":false},
    {"sModelName":"AttachmentModel","disposables":[],"mimeType":"image/jpeg","fileName":"test4.jpg","fileNameExt":"jpg","fileType":"image","description":null,"estimatedSize":26326,"friendlySize":"26KB","isInline":false,"isLinked":false,"isThumbnail":true,"cid":"","cidWithOutTags":"","contentLocation":"","download":"BN0gFmNTTOarHTn7bDrdaLxLQ-HmO36mmT8av0rwGMsO9XeBlK7OWBq4uiR5N3RkgjXBwwDtOcLBTPIx-354pFHsV2BigaNfpvFG7XlkFYyCsOwGQcNS2pR_U53ISNCnDV-bZYNjl6dc-XAPb71qOkkxn-XxWCtfqJl5ngPPQ67owcZUUfIv9ddSsGyX5PhMljxyMq6f_Cz6dp07Xeaex89ED35VTqyJe4C1MyAxq92fJlxBstcj7dM12YbRJzzWeS_B9t6g48mwh-0am6c28uxPAGYc_EP4C3VweITw7Q5uhTtNmycMksTu4CIVepYn","folder":"INBOX","uid":"22","mimeIndex":"3","framed":false}
    ]

When I have tried to convert that object to an array of values array it came as

sample.pdf,test4.jpg

using code below:
var aAtt = oAtt.map(({fileName}) => [fileName]);

When I will access it directly as oAtt[0].fileName I'm getting file name value. Also when I run it off the main code (only declared oAtt and map code line) it works as should.
Any clue what can be wrong?

A: I cannot reproduce your problem. What is oArr tho? You are talking about oAtt and aAtt in your code.

var oAtt = [{
    "sModelName": "AttachmentModel",
    "disposables": [],
    "mimeType": "application/pdf",
    "fileName": "sample.pdf",
    "fileNameExt": "pdf",
    "fileType": "pdf",
    "description": null,
    "estimatedSize": 19333,
    "friendlySize": "19KB",
    "isInline": false,
    "isLinked": false,
    "isThumbnail": false,
    "cid": "",
    "cidWithOutTags": "",
    "contentLocation": "",
    "download": "zyfTZvzczVW6cqlcsIrm3ycmY5soz3DzK5sZhjnSOwaW0wnwGwHtqBvPeo8nVpiWD4yKVIPvAPauJHZufHGRG0Eb4MRmBpkGlvsDGP-gz3CnVp4GorN_xXCI0Gkd2I93IySKMy5iXRt-wML9wxLwTZcrOMLyPp-Kr6b0GlzlHuvk3RqEXRqSlCQTX5piRO6AaRYeMKeq8PSJcId1grMYzFpCnjVSoW_Zj7yTGAsy-D_mzFoCmBdksCweEqPdGhFYFkukblXzaZiTSNGTj1xYOvMIN4XXUZtU0EAPoQ9EFxfPWY_-1Siyge0Gks2zbGs3myxXJg..",
    "folder": "INBOX",
    "uid": "22",
    "mimeIndex": "2",
    "framed": false
  },
  {
    "sModelName": "AttachmentModel",
    "disposables": [],
    "mimeType": "image/jpeg",
    "fileName": "test4.jpg",
    "fileNameExt": "jpg",
    "fileType": "image",
    "description": null,
    "estimatedSize": 26326,
    "friendlySize": "26KB",
    "isInline": false,
    "isLinked": false,
    "isThumbnail": true,
    "cid": "",
    "cidWithOutTags": "",
    "contentLocation": "",
    "download": "BN0gFmNTTOarHTn7bDrdaLxLQ-HmO36mmT8av0rwGMsO9XeBlK7OWBq4uiR5N3RkgjXBwwDtOcLBTPIx-354pFHsV2BigaNfpvFG7XlkFYyCsOwGQcNS2pR_U53ISNCnDV-bZYNjl6dc-XAPb71qOkkxn-XxWCtfqJl5ngPPQ67owcZUUfIv9ddSsGyX5PhMljxyMq6f_Cz6dp07Xeaex89ED35VTqyJe4C1MyAxq92fJlxBstcj7dM12YbRJzzWeS_B9t6g48mwh-0am6c28uxPAGYc_EP4C3VweITw7Q5uhTtNmycMksTu4CIVepYn",
    "folder": "INBOX",
    "uid": "22",
    "mimeIndex": "3",
    "framed": false
  }
];

var aAtt = oAtt.map(({fileName}) => [fileName]);

console.log(oAtt);
console.log(aAtt);

A: No clue why .map is not working when used in the main code but I have ended up with a code below
var aAtt = new Array();

for(var i=0;i<oAtt.length;i++)
{
   aAtt[i] = new Array();

   aAtt[i].push(oAtt[i].fileName);
   aAtt[i].push(oAtt[i].mimeType);
   aAtt[i].push(oAtt[i].download);
}


text:
Q: Combinations of selecting $n$ objects with $k$ different types Suppose that I am buying cakes for a party. There are $k$ different types and I intend to buy a total of $n$ cakes. How many different combinations of cakes could I possibly bring to the party?

A: Let g(n,k) = # combinations of cakes.
Notice that:

*

*g(n,1) = 1. (all the cakes are the same)

*g(n,2) = n+1. (e.g. for 5 cakes, the # of cakes of type 1 can be 0, 1, 2, 3, 4, 5)

*g(1,k) = k.

*g(2,k) = k*(k-1)/2 + k (the first term is two different cakes; the second term is when both cakes are the same), as long as k > 1. (otherwise g(2,1) = 1)

*g(3,k) = k * (k-1) * (k-2)/6 + k*(k-1)/2 * 2 + k (the first term is 3 different cakes; the second term is 2 different cakes, with a *2 since there are two choices for which one to duplicate, the third term is when all 3 cakes are the same), as long as k > 2.

If we think of k as a radix rather than the # of cakes, then this problem is equivalent to expressing the # of distinct n-digit numbers in base k whose digits are in sorted order. (e.g. 1122399 is equivalent to 9921231)
I think I can express it as a nonrecursive sum:
g(n,k) = sum from j=1 to max(n,k) of { (k choose j) * h(n,j) }
where h(n,j) is the # of ways to partition N cakes using j different types. (the term in the sum is when there are j distinct cakes actually chosen.)
But that's about as far as I can get... :/

edit: looks like it's combinations with repetitions = ((k+n-1) choose n). (same as the wikipedia article with n and k swapped)

A: Using a method that's often called "stars and bars":
We draw $n$ stars in a row to represent the cakes, and $k-1$ bars to divide them up. All of the stars to the left of the first bar are cakes of the first type; stars between the first two bars are of the second type; . . . .
**|***||*|

Here's an example with $n=6$ and $k=5$. We're getting 2 of the first type, 3 of the second type, 0 of the third type, 1 of the fourth type, and 0 of the fifth type.
In order to solve the problem, we just need to reorder the stars and bars by choosing the $k-1$ spots for the bars out of the $n+k-1$ total spots, so our answer is:
$$ \binom{n+k-1}{k-1}. $$

A: Let's assume you have $n$ items and $k$ bins. You need $k-1$ separators to get the $n$ items into the $k$ bins. There are $(n + k - 1)!$ permutations of ordering $n$ items and $(k-1)$ separators. The permutations of the $n$ items don't matter, and the permutations of the $(k-1)$ separators don't matter, so you'll need to divide by $n!$ and $(k-1)!$
Thus you have $$\frac{(n + k - 1)!}{n!(k-1)!} = \binom{n+k-1}{k-1}$$

A: Since cakes are involved, I shall solve it using what's called the  "ice-cream parlour" approach.
For each of the $k$ types, go on saying yes, yes, yes... until you don't want any more, and then say no and move on to the next type.
Of course, you may say no straight away to any type if you don't want it, and you don't need to say no after the $k^{th}$ type because there is no next type.
So there will be $n$ of yes and $(k-1)$ of no whichever way you choose, and the only decision you need to take is where to place the no's in the string of $(n+k-1)$ responses,
thus $\dbinom{n+k-1}{k-1}$ different combinations of cakes.


text:
Q: Argument 'controllerLogin' is not a function, got undefined - AngularJs, Karma Testing Hello Fellow Genius Developers,
Currently i am learning AngularJs and doing some basic testing but keep on getting errors.
Please Please help me out with this. I have looked around for the answers but could not find anything. Your any help would be very much appreciated.
Below is the Error.
 `Error: [ng:areq] Argument 'controllerLogin' is not a function, got undefined

I am using WebStrom IDE.
Here is my controllerLogin.js
'use strict';
var loginApp = angular.module('loginApp',[]);

(function() {

    //define this for the minification of javascripts
    var loginScope=['$scope'];
    var loginController = function($scope){
        $scope.hello = "Hello Galaxy";

    };

    loginController.$inject = loginScope;
    angular.module('loginApp').controller('loginController',loginController);

}());

Below is my loginSpec.js
'use strict';

describe("app module", function () {

    beforeEach(module("loginApp"));

    describe("controllerLogin", function () {
        var scope,
            controller;

        beforeEach(inject(function ($rootScope, $controller) {
            scope = $rootScope.$new();
            controller = $controller;
        }));

        it("should assign message to hello world", function () {
            controller("controllerLogin", {$scope: scope});
            expect(scope.message).toBe("Hello Galaxy");
        });
    });
});

Below is my galaxytest.conf.js
 // list of files / patterns to load in the browser
    files: [
        'public/scripts/angular.js',
        'public/scripts/angular-mocks.js',
        'public/src/app/*.js',
        'public/app.js',
        '**/*.js',
        'test/**/*Spec.js'
    ],

Below is my app.js
//Define all the module with no dependencies.
angular.module('loginApp',[]);

//Now Define Main Module of the Application
var galaxyFrontendApp = angular.module('galaxyFrontendApp',['ngRoute','ui.bootstrap','loginApp']);

galaxyFrontendApp.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/login', {templateUrl: 'src/app/modules/login/views/viewLogin.html', action: 'loginApp.loginController'});
  $routeProvider.otherwise({redirectTo: '/login'});
}]);

and Below is my index.js
<body>
        <div ng-view></div>

        <!-- Please refer all the javascript files here -->
        <!-- All the JS files from scripts folder -->
        <script src="scripts/angular.js"></script>
        <script src="scripts/angular-route.js"></script>
        <script src="scripts/ui-bootstrap.js"></script>
        <script src="app.js"></script>

        <!-- All the JS files from App folder -->
        <!-- Module Name - login -->
        <script src="src/app/modules/login/controllerLogin.js"></script>
        <script src="src/app/modules/login/directiveLogin.js"></script>

    </body>

Please guide me through this. Thank you for your time and effort.

A: Finally i was able to get help from @DanWahlin and he found out the problem. It was with my galaxytest.conf.js file.
   files: [
       "public/scripts/angular.js",
       "public/scripts/angular-mocks.js",
       "public/scripts/ui-bootstrap.js",
       "public/scripts/angular-route.js",
       "public/app.js",
       "public/src/app/modules/login/controllerLogin.js",
       "public/test/*Spec.js"
    ],

Thank you developers

A: You shouldn't include the module name in the value provided to action. The module has already been loaded, and all of its controllers are in the shared namespace.
action: 'loginController'


text:
Q: PostgreSQL Grouped Rolling Averages I'm trying to generate rolling averages over set time periods grouped by an item ID column.
Here's the basic layout of the table and some dummy data, with the fluff stripped out:
----------------------------------------------------
| id   | itemid   | isup   | logged                |
----------------------------------------------------
| 1    | 1        | true   | 2017-03-23 12:55:00   |
| 2    | 1        | false  | 2017-03-23 12:57:00   |
| 3    | 1        | true   | 2017-03-23 13:07:00   |
| 4    | 1        | false  | 2017-03-23 13:09:00   |
| 5    | 1        | true   | 2017-03-23 13:50:00   |
| 6    | 2        | false  | 2017-03-23 12:55:00   |
| 7    | 2        | true   | 2017-03-23 14:00:00   |
| 8    | 2        | false  | 2017-03-23 14:03:00   |
----------------------------------------------------

I found an answer to a previous question on rolling averages but I can't quite seem to figure out how to group the averages by the item ID; pretty much all the avenues I've gone down have ended up with the statistics being flat out wrong.
Here's my starting point - I have a feeling that my lack of understanding of ROW_NUMBER() OVER isn't helping matters.
SELECT id, itemid, AVG(isup)
    OVER (PARTITION BY groupnr ORDER BY logged) AS averagehour
FROM (
    SELECT id, itemid, isup, logged, intervalgroup,
        itemid - ROW_NUMBER() OVER (
            partition by intervalgroup ORDER BY logged) AS groupnr
    FROM (
        SELECT id, itemid, logged,
            CASE WHEN isup = TRUE THEN 1 ELSE 0 END AS isup,
           'epoch'::TIMESTAMP + '3600 seconds'::INTERVAL *
                (EXTRACT(EPOCH FROM logged)::INT4 / 3600) AS intervalgroup
        FROM uplog
  ) alias_inner
) alias_outer
ORDER BY logged;

Any help would be much appreciated.

A: The linked answer contains almost everything you need. If you want to "group" further (f.ex. by itemid), you'll just need to add those "groups" to the PARTITION BY clauses of the window functions:
select   *, avg(isup::int) over (partition by itemid, group_nr order by logged) as rolling_avg
from     (
    select *, id - row_number() over (partition by itemid, interval_group order by logged) as group_nr
    from   (
        select *, 'epoch'::timestamp + '3600 seconds'::interval * (extract(epoch from logged)::int4 / 3600) as interval_group
        from   dummy
    ) t1
) t2
order by itemid, logged

Note however that this (and the linked answer) works only because id doesn't have gaps & is in order with the timestamp field of its table. If that's not the case, you'll need
row_number() over (partition by itemid order by logged) - row_number() over (partition by itemid, interval_group order by logged) as group_nr

instead of id - row_number() ....
http://rextester.com/YBSC43615
Also, if you're going to use only hourly groups, you can use:
date_trunc('hour', logged) as interval_group

instead of the more general arithmetic (as @LaurenzAlbe already noticed).

A: My answer assumes

*

*that logged is a timestamp with time zone, which is the only reasonable data type for logging.

*that your complicated date arithmetic is suppose to calculate the value of logged at time zone UTC (else why would you use 'epoch'::timestampas a base?), rounded to the next lower hour.

*that you want to group by that rounded timestamp and itemid.
Here would be an answer:
SELECT *,
       avg(isup::integer)
          OVER (PARTITION BY itemid,
                             date_trunc('hour', logged AT TIME ZONE 'UTC')
               ) average,
       date_trunc('hour', logged AT TIME ZONE 'UTC') avg_interval
FROM uplog
ORDER BY logged;

┌────┬────────┬──────┬────────────────────────┬────────────────────────┬─────────────────────┐
│ id │ itemid │ isup │         logged         │        average         │    avg_interval     │
├────┼────────┼──────┼────────────────────────┼────────────────────────┼─────────────────────┤
│  6 │      2 │ f    │ 2017-03-23 12:55:00+01 │ 0.00000000000000000000 │ 2017-03-23 11:00:00 │
│  1 │      1 │ t    │ 2017-03-23 12:55:00+01 │ 0.50000000000000000000 │ 2017-03-23 11:00:00 │
│  2 │      1 │ f    │ 2017-03-23 12:57:00+01 │ 0.50000000000000000000 │ 2017-03-23 11:00:00 │
│  3 │      1 │ t    │ 2017-03-23 13:07:00+01 │ 0.66666666666666666667 │ 2017-03-23 12:00:00 │
│  4 │      1 │ f    │ 2017-03-23 13:09:00+01 │ 0.66666666666666666667 │ 2017-03-23 12:00:00 │
│  5 │      1 │ t    │ 2017-03-23 13:50:00+01 │ 0.66666666666666666667 │ 2017-03-23 12:00:00 │
│  7 │      1 │ t    │ 2017-03-23 14:00:00+01 │ 0.50000000000000000000 │ 2017-03-23 13:00:00 │
│  8 │      1 │ f    │ 2017-03-23 14:03:00+01 │ 0.50000000000000000000 │ 2017-03-23 13:00:00 │
└────┴────────┴──────┴────────────────────────┴────────────────────────┴─────────────────────┘
(8 rows)


text:
Q: Add class to c++ firemonkey project I have written a small firemonkey mobile app in C++ XE6 using several forms/units which all attempt to read data from a json feed.
I would like to keep the user details in a separate class to pass in the REST request rather than pass them from form to form.
What is the syntax for creating a static class and, other than including a reference to myclass.h, how does one access it's properties please?


text:
Q: Populate database column with drop-down menu item I'm quite new to Apex and Oracle in general, but I would like to know how to populate a database column with the data from
the drop-down list
Currently I'm not getting further than simply creating the drop-down items
What I'm going for is that if the user chooses (e.g.) Company2 and department7 and inserts data into the tabular and pushes submit, then the Company data would populate the company column in the db;  dep would populate department column and same principle for other drop-down items)


text:
Q: Custom image link in WooCommerce product category archive pages Is there an easy way to set Woocommerce 3.x to link to full size image instead of the product details on the category pages (where you see the thumbs of products)?
So basically it will work as a gallery of some sort with an 'add to cart' buttons below each image.
I assume I have to edit the woocommerce_template_loop_product_link_open() function at includes\wc-template-functions.php and change:
esc_url( get_the_permalink() )

To something else…

A:
Important note:  Never override any core file as you can use available hooks
  (or also you can override WooCommerce templates via a Theme)…

To set Woocommerce 3.x to link to full size image on the category archive pages only, use this:
add_action ('woocommerce_before_shop_loop_item', 'custom_loop_product_link_open', 1);
function custom_loop_product_link_open(){
    // For product category archives pages only
    if(is_product_category()){
        // Remove default image link
        remove_action ('woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open', 10);
        // Add custom image link function
        add_action ('woocommerce_before_shop_loop_item', 'change_loop_product_link_open', 10);
    }
}

// Custom image link function
function change_loop_product_link_open(){
    global $product; // Get the WC_Product object

    echo '<a href="' . get_the_post_thumbnail_url( $product->get_id(), 'full' )  . '" class="woocommerce-LoopProduct-link">';
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Tested and works…


text:
Q: Break string into keyword list from scientific article keywords I am trying to split each keyword from a keywords string using comma as separate character, but chemical names are also named with comma, How can I identify chemical names and not separate the name?
Here's some examle:
keywords_string1 = "Forecasting,GM(1,1),Background value"
#expected result1 : [ "Forecasting", "GM(1,1)", "Background value" ]

keywords_string2 = "(3E)-4, 8-Dimethyl-1, 3, 7-nonatriene, ultrasonic sprayer"
#expected result2 : [ "(3E)-4, 8-Dimethyl-1, 3, 7-nonatriene", "ultrasonic sprayer" ]

A: If we can be sure that no name ends with a digit (which, as far as I can see, is the case(?)), you could split on commas (and their eventual surrounding spaces) that are not preceded by a digit.
Using a regex to do that, we could do:
import re

def split_on_commas(s):
    split_pattern = re.compile('(?<=\D) *, *')
    return split_pattern.split(s)

Which gives the expected result on your test cases:
keywords_string1 = "Forecasting,GM(1,1),Background value"
#expected result1 : [ "Forecasting", "GM(1,1)", "Background value" ]

print(split_on_commas(keywords_string1))
# ['Forecasting', 'GM(1,1)', 'Background value']

keywords_string2 = "(3E)-4, 8-Dimethyl-1, 3, 7-nonatriene, ultrasonic sprayer"
#expected result2 : [ "(3E)-4, 8-Dimethyl-1, 3, 7-nonatriene", "ultrasonic sprayer" ]

print(split_on_commas(keywords_string2))
#['(3E)-4, 8-Dimethyl-1, 3, 7-nonatriene', 'ultrasonic sprayer']

Note that we have to use a positive lookbehind assertion (?<=\D) for a non-digit in the regex, so that the non-digit character doesn't get captured as part of the splitting pattern.


text:
Q: How to use ngSwitch with template? I have template with IF statement:

How to write this template with ngSwitch directive?
For example this template has parse error "Components on an embedded template":

    <template [ngSwitchCase]="'Project'" [activity-project-item]="activity"></template>

And this template has parse error "No provider for NgSwitch":
<template [ngSwitch]="activity.entity_name">

</template>

A: One possibility:

  <template [ngSwitchCase]="'Project'">Selected Project</template>
  <template [ngSwitchCase]="'Tooling'">Selected Tooling</template>
  <template ngSwitchDefault>Or else...</template>

Alternate syntax:

Selected Project

Selected Tooling

Or else...

Take a look at the official docs and live demo.

A: template

  <template [ngSwitchCase]="'Project'">Content here</template>
  <template [ngSwitchCase]="'Project2'">Other content here</template>
  <template ngSwitchDefault>Content if nothing matched</template>

Also make sure that the module that owns this component imports CommonModule. Otherwise, ngSwitch will not be recognized.
@NgModule({
    ...
    imports: [CommonModule...],
    declarations: [ThisComponent...],
    ...
})
export default class MyModule {}


text:
Q: Can we concat as well as replace string values in SQL Server (SSMS)?
I executed below query, but I got result as null values.
SELECT CAST(REPLACE(REPLACE(REPLACE(REPLACE(FIRST_NAME,'null',''),'N/A',''),'no',''),'NA','') +' ' + REPLACE(REPLACE(REPLACE(REPLACE(LAST_NAME,'null',''),'N/A',''),'no',''),'NA','')) AS 'FULL_NAME' FROM NAMES

Instead I want my output to be:
FULL_NAME
___________
Ankit Kumar
Mayank Sharma
Puneet Kumar
Rajesh
Narender
Robert
Chahuhan
Jaswinder Singh
Rakesh

A: The more recent versions of SQL Server support concat_ws():
select concat_ws(' ',
                 (case when first_name not in ('na', 'no', 'null') then first_name end),
                 (case when last_name not in ('na', 'no', 'null') then last_name end)
                ) as full_name

In older versions, you can use:
select ltrim( (case when first_name not in ('na', 'no', 'null') then ' ' + first_name else '' end) +
              (case when last_name not in ('na', 'no', 'null') then ' ' + last_name else '' end)
            ) as full_name


text:
Q: Is the NSData a substring of the another NSData? I have two NSData objects
NSData *toScan = /* initialized somehow with "Hello, this world." */;
NSData *toMatch = /* initialized somehow with "this" */;

What is the best way to know the toMatch bytes are the subset of toScan bytes?
I use C-functions for this purposes at this point: something like this
strstr([[toScan identifier] bytes], [[toMatch identifier] bytes]);
// returned bytes are null-terminated

but I think there is not the best way to use C-functions in object-oriented environment...

A: As of Snow Leopard and iOS 4.0, NSData has -rangeOfData:options:range: which should do what you want.
It's also pretty darn fast.

A: In a different question, I wrote an answer containing an NSData category with a rangeOfData: method:
Elegant Algorithm for Parsing Data Stream Into Record
That'll do what you're looking for.