Q: Is it possible to align components horizontally when using WrapLayout/FlowLayout? I use WrapLayout which extends FlowLayout
Now, I have this GUI:

What I want is this:

I tried some things like: label.setVerticalAlignment(JLabel.TOP); but the layout does not seem to respect it. I guess this behavior is inherited from FlowLayout?
Full code:
public class WrapLayoutExample {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(WrapLayoutExample::runGui);
    }

    private static void runGui() {
        JFrame frame = new JFrame("A");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel(new WrapLayout());

        JLabel l = new JLabel("CCC");
        l.setBorder(BorderFactory.createLineBorder(Color.red, 10));
        l.setVerticalAlignment(JLabel.TOP);
        panel.add(l);

        l = new JLabel("BBBB");
        l.setBorder(BorderFactory.createLineBorder(Color.red, 20));
        panel.add(l);

        frame.setLayout(new BorderLayout());
        frame.add(new JScrollPane(panel));

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

A: From @camickr's comment in my question:

You should be able to write your own layout manager. Just copy the FlowLayout and replace the logic that centers the component within the row, to position the component at the top.

In FlowLayout, in moveComponents method, there is this line:
cy = y + (height - m.height) / 2;

Changing the line to:
cy = y;

achieves what I want.
It probably breaks the flowLayout.setAlignOnBaseline functionality. But I don't use it anyway.
Layout code (WrapLayout and custom FlowLayout combined):
public class WrapAndAlignHorizontallyTopLayout implements LayoutManager, java.io.Serializable {

    /**
     * This value indicates that each row of components should be left-justified.
     */
    public static final int LEFT = 0;

    /**
     * This value indicates that each row of components should be centered.
     */
    public static final int CENTER = 1;

    /**
     * This value indicates that each row of components should be right-justified.
     */
    public static final int RIGHT = 2;

    /**
     * This value indicates that each row of components should be justified to the
     * leading edge of the container's orientation, for example, to the left in
     * left-to-right orientations.
     *
     * @see java.awt.Component#getComponentOrientation
     * @see java.awt.ComponentOrientation
     * @since 1.2
     */
    public static final int LEADING = 3;

    /**
     * This value indicates that each row of components should be justified to the
     * trailing edge of the container's orientation, for example, to the right in
     * left-to-right orientations.
     *
     * @see java.awt.Component#getComponentOrientation
     * @see java.awt.ComponentOrientation
     * @since 1.2
     */
    public static final int TRAILING = 4;

    /**
     * align is the property that determines how each row distributes
     * empty space. It can be one of the following values:
     *

     *
LEFT
     *
RIGHT
     *
CENTER
     *

     *
     * @serial
     * @see #getAlignment
     * @see #setAlignment
     */
    int align; // This is for 1.1 serialization compatibility

    /**
     * newAlign is the property that determines how each row
     * distributes empty space for the Java 2 platform, v1.2 and greater. It can be
     * one of the following three values:
     *

     *
LEFT
     *
RIGHT
     *
CENTER
     *
LEADING
     *
TRAILING
     *

     *
     * @serial
     * @since 1.2
     * @see #getAlignment
     * @see #setAlignment
     */
    int newAlign; // This is the one we actually use

    /**
     * The flow layout manager allows a seperation of components with gaps. The
     * horizontal gap will specify the space between components and between the
     * components and the borders of the Container.
     *
     * @serial
     * @see #getHgap()
     * @see #setHgap(int)
     */
    int hgap;

    /**
     * The flow layout manager allows a seperation of components with gaps. The
     * vertical gap will specify the space between rows and between the the rows and
     * the borders of the Container.
     *
     * @serial
     * @see #getHgap()
     * @see #setHgap(int)
     */
    int vgap;

    /**
     * If true, components will be aligned on their baseline.
     */
    private boolean alignOnBaseline;

    /*
     * JDK 1.1 serialVersionUID
     */
    private static final long serialVersionUID = -7262534875583282631L;

    /**
     * Constructs a new FlowLayout with a centered alignment and a
     * default 5-unit horizontal and vertical gap.
     */
    public WrapAndAlignHorizontallyTopLayout() {
        this(CENTER, 5, 5);
    }

    /**
     * Constructs a new FlowLayout with the specified alignment and a
     * default 5-unit horizontal and vertical gap. The value of the alignment
     * argument must be one of FlowLayout.LEFT,
     * FlowLayout.RIGHT, FlowLayout.CENTER,
     * FlowLayout.LEADING, or FlowLayout.TRAILING.
     *
     * @param align the alignment value
     */
    public WrapAndAlignHorizontallyTopLayout(int align) {
        this(align, 5, 5);
    }

    /**
     * Creates a new flow layout manager with the indicated alignment and the
     * indicated horizontal and vertical gaps.
     *

     * The value of the alignment argument must be one of
     * FlowLayout.LEFT, FlowLayout.RIGHT,
     * FlowLayout.CENTER, FlowLayout.LEADING, or
     * FlowLayout.TRAILING.
     *
     * @param align the alignment value
     * @param hgap  the horizontal gap between components and between the components
     *              and the borders of the Container
     * @param vgap  the vertical gap between components and between the components
     *              and the borders of the Container
     */
    public WrapAndAlignHorizontallyTopLayout(int align, int hgap, int vgap) {
        this.hgap = hgap;
        this.vgap = vgap;
        setAlignment(align);
    }

    /**
     * Gets the alignment for this layout. Possible values are
     * FlowLayout.LEFT, FlowLayout.RIGHT,
     * FlowLayout.CENTER, FlowLayout.LEADING, or
     * FlowLayout.TRAILING.
     *
     * @return the alignment value for this layout
     * @see java.awt.FlowLayout#setAlignment
     * @since JDK1.1
     */
    public int getAlignment() {
        return newAlign;
    }

    /**
     * Sets the alignment for this layout. Possible values are
     *

     *
FlowLayout.LEFT
     *
FlowLayout.RIGHT
     *
FlowLayout.CENTER
     *
FlowLayout.LEADING
     *
FlowLayout.TRAILING
     *

     *
     * @param align one of the alignment values shown above
     * @see #getAlignment()
     * @since JDK1.1
     */
    public void setAlignment(int align) {
        this.newAlign = align;

        // this.align is used only for serialization compatibility,
        // so set it to a value compatible with the 1.1 version
        // of the class

        switch (align) {
        case LEADING:
            this.align = LEFT;
            break;
        case TRAILING:
            this.align = RIGHT;
            break;
        default:
            this.align = align;
            break;
        }
    }

    /**
     * Gets the horizontal gap between components and between the components and the
     * borders of the Container
     *
     * @return the horizontal gap between components and between the components and
     *         the borders of the Container
     * @see java.awt.FlowLayout#setHgap
     * @since JDK1.1
     */
    public int getHgap() {
        return hgap;
    }

    /**
     * Sets the horizontal gap between components and between the components and the
     * borders of the Container.
     *
     * @param hgap the horizontal gap between components and between the components
     *             and the borders of the Container
     * @see java.awt.FlowLayout#getHgap
     * @since JDK1.1
     */
    public void setHgap(int hgap) {
        this.hgap = hgap;
    }

    /**
     * Gets the vertical gap between components and between the components and the
     * borders of the Container.
     *
     * @return the vertical gap between components and between the components and
     *         the borders of the Container
     * @see java.awt.FlowLayout#setVgap
     * @since JDK1.1
     */
    public int getVgap() {
        return vgap;
    }

    /**
     * Sets the vertical gap between components and between the components and the
     * borders of the Container.
     *
     * @param vgap the vertical gap between components and between the components
     *             and the borders of the Container
     * @see java.awt.FlowLayout#getVgap
     * @since JDK1.1
     */
    public void setVgap(int vgap) {
        this.vgap = vgap;
    }

    /**
     * Sets whether or not components should be vertically aligned along their
     * baseline. Components that do not have a baseline will be centered. The
     * default is false.
     *
     * @param alignOnBaseline whether or not components should be vertically aligned
     *                        on their baseline
     * @since 1.6
     */
    public void setAlignOnBaseline(boolean alignOnBaseline) {
        this.alignOnBaseline = alignOnBaseline;
    }

    /**
     * Returns true if components are to be vertically aligned along their baseline.
     * The default is false.
     *
     * @return true if components are to be vertically aligned along their baseline
     * @since 1.6
     */
    public boolean getAlignOnBaseline() {
        return alignOnBaseline;
    }

    /**
     * Adds the specified component to the layout. Not used by this class.
     *
     * @param name the name of the component
     * @param comp the component to be added
     */
    @Override
    public void addLayoutComponent(String name, Component comp) {
    }

    /**
     * Removes the specified component from the layout. Not used by this class.
     *
     * @param comp the component to remove
     * @see java.awt.Container#removeAll
     */
    @Override
    public void removeLayoutComponent(Component comp) {
    }

    /**
     * Returns the preferred dimensions for this layout given the visible
     * components in the specified target container.
     *
     * @param target the component which needs to be laid out
     * @return the preferred dimensions to lay out the subcomponents of the
     *         specified container
     */
    @Override
    public Dimension preferredLayoutSize(Container target) {
        return layoutSize(target, true);
    }

    /**
     * Returns the minimum dimensions needed to layout the visible components
     * contained in the specified target container.
     *
     * @param target the component which needs to be laid out
     * @return the minimum dimensions to lay out the subcomponents of the specified
     *         container
     */
    @Override
    public Dimension minimumLayoutSize(Container target) {
        Dimension minimum = layoutSize(target, false);
        minimum.width -= (getHgap() + 1);
        return minimum;
    }

    /**
     * Returns the minimum or preferred dimension needed to layout the target
     * container.
     *
     * @param target    target to get layout size for
     * @param preferred should preferred size be calculated
     * @return the dimension to layout the target container
     */
    private Dimension layoutSize(Container target, boolean preferred) {
        synchronized (target.getTreeLock()) {
            // Each row must fit with the width allocated to the containter.
            // When the container width = 0, the preferred width of the container
            // has not yet been calculated so lets ask for the maximum.

            int targetWidth = target.getSize().width;
            Container container = target;

            while (container.getSize().width == 0 && container.getParent() != null) {
                container = container.getParent();
            }

            targetWidth = container.getSize().width;

            if (targetWidth == 0)
                targetWidth = Integer.MAX_VALUE;

            int hgap = getHgap();
            int vgap = getVgap();
            Insets insets = target.getInsets();
            int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2);
            int maxWidth = targetWidth - horizontalInsetsAndGap;

            // Fit components into the allowed width

            Dimension dim = new Dimension(0, 0);
            int rowWidth = 0;
            int rowHeight = 0;

            int nmembers = target.getComponentCount();

            for (int i = 0; i < nmembers; i++) {
                Component m = target.getComponent(i);

                if (m.isVisible()) {
                    Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize();

                    // Can't add the component to current row. Start a new row.

                    if (rowWidth + d.width > maxWidth) {
                        addRow(dim, rowWidth, rowHeight);
                        rowWidth = 0;
                        rowHeight = 0;
                    }

                    // Add a horizontal gap for all components after the first

                    if (rowWidth != 0) {
                        rowWidth += hgap;
                    }

                    rowWidth += d.width;
                    rowHeight = Math.max(rowHeight, d.height);
                }
            }

            addRow(dim, rowWidth, rowHeight);

            dim.width += horizontalInsetsAndGap;
            dim.height += insets.top + insets.bottom + vgap * 2;

            // When using a scroll pane or the DecoratedLookAndFeel we need to
            // make sure the preferred size is less than the size of the
            // target containter so shrinking the container size works
            // correctly. Removing the horizontal gap is an easy way to do this.

            Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target);

            if (scrollPane != null && target.isValid()) {
                dim.width -= (hgap + 1);
            }

            return dim;
        }
    }

    /*
     * A new row has been completed. Use the dimensions of this row to update the
     * preferred size for the container.
     *
     * @param dim update the width and height when appropriate
     *
     * @param rowWidth the width of the row to add
     *
     * @param rowHeight the height of the row to add
     */
    private void addRow(Dimension dim, int rowWidth, int rowHeight) {
        dim.width = Math.max(dim.width, rowWidth);

        if (dim.height > 0) {
            dim.height += getVgap();
        }

        dim.height += rowHeight;
    }

    /**
     * Centers the elements in the specified row, if there is any slack.
     *
     * @param target      the component which needs to be moved
     * @param x           the x coordinate
     * @param y           the y coordinate
     * @param width       the width dimensions
     * @param height      the height dimensions
     * @param rowStart    the beginning of the row
     * @param rowEnd      the the ending of the row
     * @param useBaseline Whether or not to align on baseline.
     * @param ascent      Ascent for the components. This is only valid if
     *                    useBaseline is true.
     * @param descent     Ascent for the components. This is only valid if
     *                    useBaseline is true.
     * @return actual row height
     */
    private int moveComponents(Container target, int x, int y, int width, int height, int rowStart, int rowEnd,
            boolean ltr, boolean useBaseline, int[] ascent, int[] descent) {
        switch (newAlign) {
        case LEFT:
            x += ltr ? 0 : width;
            break;
        case CENTER:
            x += width / 2;
            break;
        case RIGHT:
            x += ltr ? width : 0;
            break;
        case LEADING:
            break;
        case TRAILING:
            x += width;
            break;
        }
        int maxAscent = 0;
        int nonbaselineHeight = 0;
        int baselineOffset = 0;
        if (useBaseline) {
            int maxDescent = 0;
            for (int i = rowStart; i < rowEnd; i++) {
                Component m = target.getComponent(i);
                if (m.isVisible()) {
                    if (ascent[i] >= 0) {
                        maxAscent = Math.max(maxAscent, ascent[i]);
                        maxDescent = Math.max(maxDescent, descent[i]);
                    } else {
                        nonbaselineHeight = Math.max(m.getHeight(), nonbaselineHeight);
                    }
                }
            }
            height = Math.max(maxAscent + maxDescent, nonbaselineHeight);
            baselineOffset = (height - maxAscent - maxDescent) / 2;
        }
        for (int i = rowStart; i < rowEnd; i++) {
            Component m = target.getComponent(i);
            if (m.isVisible()) {
                int cy;
                if (useBaseline && ascent[i] >= 0) {
                    cy = y + baselineOffset + maxAscent - ascent[i];
                } else {
                    cy = y;
                }
                if (ltr) {
                    m.setLocation(x, cy);
                } else {
                    m.setLocation(target.getWidth() - x - m.getWidth(), cy);
                }
                x += m.getWidth() + hgap;
            }
        }
        return height;
    }

    /**
     * Lays out the container. This method lets each visible component take
     * its preferred size by reshaping the components in the target container in
     * order to satisfy the alignment of this FlowLayout object.
     *
     * @param target the specified component being laid out
     * @see Container
     * @see java.awt.Container#doLayout
     */
    @Override
    public void layoutContainer(Container target) {
        synchronized (target.getTreeLock()) {
            Insets insets = target.getInsets();
            int maxwidth = target.getWidth() - (insets.left + insets.right + hgap * 2);
            int nmembers = target.getComponentCount();
            int x = 0, y = insets.top + vgap;
            int rowh = 0, start = 0;

            boolean ltr = target.getComponentOrientation().isLeftToRight();

            boolean useBaseline = getAlignOnBaseline();
            int[] ascent = null;
            int[] descent = null;

            if (useBaseline) {
                ascent = new int[nmembers];
                descent = new int[nmembers];
            }

            for (int i = 0; i < nmembers; i++) {
                Component m = target.getComponent(i);
                if (m.isVisible()) {
                    Dimension d = m.getPreferredSize();
                    m.setSize(d.width, d.height);

                    if (useBaseline) {
                        int baseline = m.getBaseline(d.width, d.height);
                        if (baseline >= 0) {
                            ascent[i] = baseline;
                            descent[i] = d.height - baseline;
                        } else {
                            ascent[i] = -1;
                        }
                    }
                    if ((x == 0) || ((x + d.width) <= maxwidth)) {
                        if (x > 0) {
                            x += hgap;
                        }
                        x += d.width;
                        rowh = Math.max(rowh, d.height);
                    } else {
                        rowh = moveComponents(target, insets.left + hgap, y, maxwidth - x, rowh, start, i, ltr,
                                useBaseline, ascent, descent);
                        x = d.width;
                        y += vgap + rowh;
                        rowh = d.height;
                        start = i;
                    }
                }
            }
            moveComponents(target, insets.left + hgap, y, maxwidth - x, rowh, start, nmembers, ltr, useBaseline, ascent,
                    descent);
        }
    }

    //
    // the internal serial version which says which version was written
    // - 0 (default) for versions before the Java 2 platform, v1.2
    // - 1 for version >= Java 2 platform v1.2, which includes "newAlign" field
    //
    private static final int currentSerialVersion = 1;
    /**
     * This represent the currentSerialVersion which is bein used. It
     * will be one of two values : 0 versions before Java 2 platform
     * v1.2.. 1 versions after Java 2 platform v1.2..
     *
     * @serial
     * @since 1.2
     */
    private int serialVersionOnStream = currentSerialVersion;

    /**
     * Reads this object out of a serialization stream, handling objects written by
     * older versions of the class that didn't contain all of the fields we use
     * now..
     */
    private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
        stream.defaultReadObject();

        if (serialVersionOnStream < 1) {
            // "newAlign" field wasn't present, so use the old "align" field.
            setAlignment(this.align);
        }
        serialVersionOnStream = currentSerialVersion;
    }

    /**
     * Returns a string representation of this FlowLayout object and
     * its values.
     *
     * @return a string representation of this layout
     */
    @Override
    public String toString() {
        String str = "";
        switch (align) {
        case LEFT:
            str = ",align=left";
            break;
        case CENTER:
            str = ",align=center";
            break;
        case RIGHT:
            str = ",align=right";
            break;
        case LEADING:
            str = ",align=leading";
            break;
        case TRAILING:
            str = ",align=trailing";
            break;
        }
        return getClass().getName() + "[hgap=" + hgap + ",vgap=" + vgap + str + "]";
    }

}

Example code:
public class WrapLayoutExample {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(WrapLayoutExample::runGui);
    }

    private static void runGui() {
        JFrame frame = new JFrame("A");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel(new WrapAndAlignHorizontallyTopLayout());

        JLabel l = new JLabel("CCC");
        l.setBorder(BorderFactory.createLineBorder(Color.red, 10));
        l.setVerticalAlignment(JLabel.TOP);

        panel.add(l);

        for (int i = 0; i < 44; i++) {
            l = new JLabel("BBBB");
            l.setBorder(BorderFactory.createLineBorder(Color.red, (int) (Math.random() * 50)));
            panel.add(l);
        }

        frame.setSize(300, 300);
        frame.setLayout(new BorderLayout());
        frame.add(new JScrollPane(panel));
        frame.setVisible(true);
    }
}

Result:


Q: Bootstrap modals not working I am trying to get modals from bootstrap to work but for some reason it is showing up like this:

This is the default code I used from the bootstrap documentation:

<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

        ...

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

Thanks in advance!

A: Have you initialized the modal with javascript? All you need is JQuery, the bootstrap CSS file, and the bootstrap JS file.
Then add this code in a


Q: Multiple for loops to parse XML to CSV not working I want to write a code that can be used on different XML files (all with TEI encoding) to see if specific elements and attributes appear, how often they appear and in what context). To do this I have written the following code:
from logging import root
import xml.etree.ElementTree as ET
import csv

f = open('orestes-elements.csv', 'w', encoding="utf-8")
writer = csv.writer(f)
writer.writerow(["Note Attributes", "Note Text", "Responsibility", "Certainty Element", "Certainty Attributes", "Certainty Text"])

tree = ET.parse(r"C:\Users\noahb\OneDrive\Desktop\Humboldt\Semester 2\Daten\Hausarbeit-TEI\edition-euripides\Orestes.xml")
root = tree.getroot()

try:
    for note in root.findall('.//note'):
        noteat = note.attrib
        notetext = note.text
        print(noteat)
        print(notetext)
    #attribute search
    for responsibility in root.findall(".//*[@resp]"):
        responsibilities = str(responsibility.tag, responsibility.attrib, responsibility.text)
    for certainty in root.findall(".//*[@cert]"):
        certaintytag = certainty.tag
        certaintyat = certainty.attrib
        certaintytext = certainty.text
    writer.writerow([noteat, notetext, responsibilities, certaintytag, certaintyat, certaintytext])
finally:
    f.close()

I get the error "NameError: name 'noteat' is not defined". I can indent writer.writerrow but the information from the other for loop doesnt get added. How do I get the information from the different for loops into my CSV file? Help would be greatly appreciated? (The print() in the for loops gives me the right results and with responsibilities I tried making it all one string but that isnt necessary I am just trying out different solutions - none work until now).
This is an example of my XML file: (some of the elements and attributes will not appear in some of the files - might this be a reason form the errors?)
<?xml version="1.0" encoding="UTF-8"?>

<?oxygen RNGSchema="teiScholiaSchema2021beta.rng" type="xml"?>

<TEI xml:lang="grc">
 <teiHeader>
  <titleStmt>
    <title cert="high">Scholia on Euripides’ Orestes 1–500</title>
    <author><note>Donald J.</note> Mastronarde</author>
   </titleStmt>
</teiHeader>
 <text>
   <div1 type="subdivisionByPlay" xml:id="Orestes">
    <div2 type="hypotheseis" xml:id="hypOrestes">
     Prefatory material (argumenta/hypotheseis) for Orestes

Orestes, pursuing <note cert="low">(vengeance for)</note> the murder of his father, killed Aegisthus and
        Clytemnestra. Having dared to commit matricide he paid the penalty immediately, becoming
        mad. And after Tyndareus, the father of the murdered woman, brought an accusation, the
        Argives were about to issue a public vote about him, concerning what the man who had acted
        impiously should suffer.

    </div2>
   </div1>
 </text>
</TEI>

Example of what CSV should look like:

A: The values in your writer.writerow() will not be defined if an element is missing. You could just define some default values to avoid this.
Try adding the following after the try statement:
noteat, notetext, responsibilities, certaintytag, certaintyat, certaintytext = [''] * 6

You could of course have 'NA' if preferred.


Q: I can't pass th:object to controller and mapped to pojo using @ModelAttribute I am trying to retrieve object on my controller that mapped to my POJO
My POJO looks like this
public interface InventoryDetailPOJO {
    String getItem_cd();
}

And this is my form

    <button class="btn btn-block btn-options btn-save">Save</button>

<form action="#"
      th:action="@{/stock-list/inventory-detail}"
      method="post"
      th:object="${inventoryDetail}"
      class="pt-3 form-inventory-detail">

         Item No

         <input type="text" class="form-control form-control-sm w-25"
         th:field="*{item_cd}">

</form>

And for my controller
@RequestMapping(value = "/stock-list/inventory-detail", method = RequestMethod.POST)
public ModelAndView InventoryDetailSubmitPage(ModelAndView modelAndView,
    @ModelAttribute("inventoryDetail") InventoryDetailPOJO inventoryDetail,
        @RequestParam("item_cd") String item_cd) {

    System.err.println("InventoryDetail: " + inventoryDetail);
    System.err.println("item_cd: " + item_cd);

    modelAndView.setViewName("redirect:/stock-list");
    return modelAndView;
}

There're no item on inventoryDetail when I tried to log it, but There's a value on item_cd

A: Remove action="#", like this:
<form th:action="@{/stock-list/inventory-detail}"
      method="post"
      th:object="${inventoryDetail}"
      class="pt-3 form-inventory-detail">


Q: Difference in timing when returning a resolved Promise I have a function that does a bunch of work then returns a resolved Promise. Is there a difference in the timing when each will be resolved?
Option 1
function returnPromise() {
  // do a bunch of stuff
  return Promise.resolve();
}

and this way:
Option 2
function returnPromise() {
  return new Promise((resolve, reject) => {
    //do a bunch of stuff
    resolve();
  });
}

Does Option 1 release control after all the work is done, and Option 2 release control as soon as the function is called? I feel like this has root in the fact I don't fully understand the event loop. Thanks in advance for helping me understand this.

A:
Is there a difference with doing it this way?

No, both your examples do the exact same thing.
Promise.resolve and Promise.reject are simply static methods on the Promise Class that help you avoid constructing a whole Promise when you don't really need to.

A:
Is there a difference in the timing when each will be resolved?

No difference.  The Promise executor (the callback you pass to new Promise()) is called immediately and synchronously.  So, in BOTH cases, you are immediately and synchronously returning an already resolved promise and all the code in your function has already executed.
There should be no meaningful difference in execution timing.  Of course, one might take slightly different number of CPU cycles to execute, but both have the exact same outcome and both immediately return a promise that is already resolved so there should be no difference to the calling code at all.
Promise.resolve() is just meant as a more compact (and probably more efficient) means of creating an already resolved promise.

Does Option 1 release control after all the work is done, and Option 2 release control as soon as the function is called?

They both return when all your work is done and they return an already resolved promise.  This is because the executor callback to new Promise() is called synchronously (before your function returns).

I feel like this has root in the fact I don't fully understand the event loop. Thanks in advance for helping me understand this.

In this particular circumstance, all your code is run synchronously so there is no particular involvement of the event loop.  The returnPromise() function returns (in both cases) when your code in the function is done executing synchronously.  There is no async code here.

The event loop gets involved when you do .then() on the returned promise because even though the promise (in both cases) is already resolved, the .then() handler gets queued in the event queue and does not run until the rest of your Javascript after your .then() handler is done executing.
console.log("1");
returnPromise().then(function() {
    console.log("2");
});
console.log("3");

This will generate identical output results:
1
3
2

with both versions of your returnPromise() function because .then() handlers are queued until the next tick of the event loop (e.g. after the rest of your current Javascript thread of execution is done).


Q: Jquery Droppable Center Image in Div After Drop Event Hey there,i'm creating a simple inventory using jQuery droppable. For now, it's like :
$(document).ready(function() {

 $( ".weapon, .helmet" ).draggable({ revert: "invalid", cursor: "move" });
 $( "#weapon_spot" ).droppable({accept: ".weapon"});
 $( "#helmet_spot" ).droppable({accept: ".helmet"});

 // make inventory slots droppable as well

 $( ".inv_slot" ).droppable({accept: ".weapon"});

});

I'm kinda new to JQuery and have some trouble setting an image to be aligned inside a certain div. Everything(.weapon, .helmet etc) is a div. Inside them, there can be images. The divs are 70x70 and the images are of that size as well.
The css is like :
.inv_slot, #weapon_spot, #helmet_spot {
    width: 70px;
    padding: 10px;
    height: 70px;
    margin: 10px;
    border: 1px solid black;
    float: left;
    text-align: center;
}

and the image inside a div is like :

My problem is that when i drop an image to another div, it's not aligned in the center of the div, it's not locked and it can be moved inside it. It seems that i can use Drag.Move somehow to do that, but i can't find some good resource explaining that. Could you please help ? :)
EDIT : I have created a demo at http://jsfiddle.net/kzuRn/2/

A: Add a drop callback to the droppables and apply the style changes necessary. Because right now the item is still positioned absolutely it will not recognize your center css.
Something like this: WRONG (see below)
drop: function(ev, ui) {
        $(this).css({position: 'static'})
}

I updated the fiddle. I was wrong before. this is the droppable, and ui.draggable is the draggable.
drop: function(ev, ui) {
    $(this).append(ui.draggable.css('position','static'))
}


Q: How to detect when an EditText is empty using RxTextView (RxBinding) I'm doing validation on an EditText. I want the CharSequence to be invalid if it's empty or it doesn't begin with "https://". I'm also using RxBinding, specifically RxTextView. The problem is that when there is one character left, and I then delete it leaving no characters left in the the CharSequence the map operator doesn't fire off an emission. In other words I want my map operator to return false when the EditText is empty. I'm beginning to think this may not be possible the way I'm doing it. What would be an alternative?
Here is my Observable / Disposable:
val systemIdDisposable = RxTextView.textChanges(binding.etSystemId)
            .skipInitialValue()
            .map { charSeq ->
                if (charSeq.isEmpty()) {
                    false
                } else {
                    viewModel.isSystemIdValid(charSeq.toString())
                }
            }
            .subscribe { isValid ->
                if (!isValid) {
                    binding.systemIdTextInputLayout.isErrorEnabled = true
                    binding.systemIdTextInputLayout.error = viewModel.authErrorFields.value?.systemId
                } else {
                    binding.systemIdTextInputLayout.isErrorEnabled = false
                    binding.systemIdTextInputLayout.error = viewModel.authErrorFields.value?.systemId
                }
            }

And here is a function in my ViewModel that I pass the CharSequence to for validation:
fun isSystemIdValid(systemId: String?): Boolean {

    return if (systemId != null && systemId.isNotEmpty()) {
        _authErrors.value?.systemId = null
        true
    } else {
        _authErrors.value?.systemId =
            getApplication<Application>().resources.getString(R.string.field_empty_error)
        false
    }
}

A: After sleeping on it, I figured it out.
I changed RxTextView.textChanges to RxTextView.textChangeEvents. This allowed me to query the CharSequence's text value (using text() method provided by textChangeEvents) even if it's empty. Due to some other changes (not really relevant to what I was asking in this question) I was also able to reduce some of the conditional code too. I'm just putting that out there in case someone comes across this and is curious about these changes. The takeaway is that you can get that empty emission using RxTextView.textChangeEvents.
Here is my new Observer:
 val systemIdDisposable = RxTextView.textChangeEvents(binding.etSystemId)
            .skipInitialValue()
            .map { charSeq -> viewModel.isSystemIdValid(charSeq.text().toString()) }
            .subscribe {
                binding.systemIdTextInputLayout.error = viewModel.authErrors.value?.systemId
            }

And here is my validation code from the ViewModel:
fun isSystemIdValid(systemId: String?): Boolean {

        val auth = _authErrors.value

        return if (systemId != null && systemId.isNotEmpty()) {
            auth?.systemId = null
            _authErrors.value = auth
            true
        } else {
            auth?.systemId =
                getApplication<Application>().resources.getString(R.string.field_empty_error)
            _authErrors.value = auth
            false
        }
    }

Lastly, if anyone is curious about how I'm using my LiveData / MutableLiveData objects; I create a private MutableLiveData object and only expose an immutable LiveData object that returns the values of the first object. I do this for better encapsulation / data hiding. Here is an example:
private val _authErrors: MutableLiveData<AuthErrorFields> by lazy {
        MutableLiveData<AuthErrorFields>()
    }
    val authErrors: LiveData<AuthErrorFields>
        get() { return _authErrors }

Hope this helps someone!


Q: How to include the query filter in URL (cloudSearch) I am trying to retrieve data from cloudSearch, searching for the word "Person" and adding the following filter:
(prefix field=claimedgalleryid '')

The problem is that I don't know how to create the URL using that exact filter.
Could someone give me a suggestion or some link to Amazon documentation related to this topic?
What I've tried and didn't work:
...search?q=Gallerist&size=10&start=0&fq=(prefix%20field=claimedgalleryid%20%27%27)
...search?q=Gallerist&size=10&start=0&filter=(prefix%20field=claimedgalleryid%20%27%27)

A: You were close with your first attempt--it looks like you forgot to URI encode the = sign as %3D. Try this instead:
&fq=(prefix+field%3Dclaimedgalleryid+'')
I highly recommend using the "test search" feature to work out the kinks in your query syntax.  You can see the results right there, and then use the "View Raw: JSON" link to copy the full request URL and see how characters get escaped and such.


Q: Show depth on the page edge of the book (Turn.js)
https://github.com/blasten/turn.js/issues/260
http://turnjs.com/#samples/steve-jobs

I tried to do the same by keeping the .own-size class on the covers, but the "display" gets set to "none" for the 'cover pages' on navigating through the book. Why is it happening like this?

A: adding 'fixed' class to the cover pages solves the problem


Q: Optional overloaded methods when overriding Case :
I have an abstract class A. It contains two methods

*

*abstract void search(Position p);

*abstract void search(Animal a);
Class B and C extends A. I would like class B to implement search(Position p) only and class C to implement search(Animal a) only. However when I do so it gives an error, telling me to implement both of the method overloads.
How could I solve the problem? Any help is greatly appreciated

A: Here are the rules for classes extending Abstract class

*

*First concrete/non-abstract class must implement all methods

*If abstract class extends Abstract class, it can but need not implement
abstract methods.

Option 1: Interface Segregation
separate search(XXX) into two abstract classes

Option 2: Generics. Make search a Generic Type
public abstract class ClassA {

    public abstract <T> void search(T t);

    public static void main(String ...args){
        ClassA classA = new ClassB();
        classA.search(new Animal());
    }
}

class Animal{

}

class ClassB extends ClassA {

    @Override
    public <Animal> void search(Animal t) {
     System.out.println("called");
    }
}

Option 3: Interface
public class ClassA {
    public static void main(String... args) {
        Searchable classA = new ClassB();
        classA.search(new Animal());
    }
}

interface Searchable {
    public <T> void search(T t);
}

class Animal {
}

class ClassB implements Searchable {
    @Override
    public <Animal> void search(Animal t) {
        System.out.println("called");
    }
}

Option 4: Throw UnsupportedOperationException Exception(Not recomended)
class ClassB extends ClassA {

    @Override
    void search(Position p) {
        throw new UnsupportedOperationException("Not Supported");
    }

    @Override
    void search(Animal a) {

    }
}


Q: How to convert "DATASET POLYDATA" vtk file to "DATASET STRUCTURED_GRID"? I have a vtk file with header like:
# vtk DataFile Version 3.0
vtk output
ASCII
DATASET POLYDATA
POINTS 1000 float

now I need to convert it to a structured vtk file with header like:
# vtk DataFile Version 2.0
VTK from Matlab
ASCII
DATASET STRUCTURED_GRID
DIMENSIONS 32 32 1
POINTS 1000 float

is there a program or script to convert between these two types?


Q: how to create a MySQL / PHP sub query to count the number of records matching a value? I am having trouble querying MySQL. I want to actually get the count of records with the value of the current parent_cat_id. So in this case we want a sub_query that will tell us 4 (because there are 4
id  parent_cat_id   cat_name
6   2   Carrot
8   2   Potatoes
7   2   Lettuce
13  2   Asparagus
4   1   Pears
3   1   Banannas
2   1   Apples

the Main $query which produces what I posted and much more information which I will use....
$menu_query = "SELECT c.id AS id, parent_cat_id, cat_name FROM db.category c JOIN db.parent_category pc ON pc.id = c.parent_cat_id WHERE c.is_active = 1 AND c.is_menu = 1 ORDER BY pc.sort_order, c.sort_order;";

$menu_result = mysql_query($menu_query) or die(mysql_error());

while($menu_row = mysql_fetch_array($menu_result)){
    $menu_name = $menu_row['cat_name'];
    $id = $menu_row['id'];
    $parent_cat_id = $menu_row['parent_cat_id'];
            #echo $parent_cat_id;
    #return from database the $count of  records with the same  ['parent_cat_id'] 's

So I was hoping for a $sub_query of some sort so that I know in my php code to build the next menu's items. The first menu should have 4 and the second menu should have 3.
Thanks.
UPDATE FINAL WORKING SUB QUERY
SELECT c.id AS category_id, c.parent_cat_id, cat_name, d.totalCount
FROM category c
INNER JOIN parent_category pc
ON pc.id = c.parent_cat_id
INNER JOIN(
    SELECT parent_cat_id, COUNT(*) totalCount
    FROM category
    WHERE is_menu = 1
    AND parent_cat_id = 2
    ORDER BY parent_cat_id
) d
ON c.parent_cat_id = d.parent_cat_id
WHERE c.is_active = 1
AND c.is_menu = 1
ORDER BY pc.sort_order, c.sort_order;

Thanks again for your help!!!  I just needed to throw in another WHERE clause in the sub query you taught me.

A: you can have extra subquery to count the values for each parent_cat_id
SELECT  c.id AS id,
        pc.parent_cat_id,
        pc.cat_name,
        d.totalCount
FROM    db.category c
        INNER JOIN db.parent_category pc
            ON pc.id = c.parent_cat_id
        INNER JOIN
        (
            SELECT parent_cat_id, COUNT(*) totalCount
            FROM db.parent_category
            GROUP BY parent_cat_id
        ) d ON c.parent_cat_id = d.parent_cat_id
WHERE   c.is_active = 1 AND
        c.is_menu = 1
ORDER   BY  pc.sort_order,
            c.sort_order


Q: UIDatePicker set minimum and maximum time I've got a UIDatePicker with the time only and I need a possibility to set the minimum and the maximum hour is showed. For example, I need it to start at 6 hours and finish at 15 hrs. Is it possible to perform this with UIDatePicker?

A: 1) Use this function to retrieve the minimum and maximum date
func getTimeIntervalForDate()->(min : Date, max : Date){

let calendar = Calendar.current
var minDateComponent = calendar.dateComponents([.hour], from: Date())
minDateComponent.hour = 09 // Start time

let formatter = DateFormatter()
formatter.dateFormat = "h:mma"
let minDate = calendar.date(from: minDateComponent)
print(" min date : \(formatter.string(from: minDate!))")

var maxDateComponent = calendar.dateComponents([.hour], from: date)
maxDateComponent.hour = 17 //EndTime

let maxDate = calendar.date(from: maxDateComponent)
print(" max date : \(formatter.string(from: maxDate!))")

return (minDate!,maxDate!)
}

2) Assign these dated to your pickerview
func createPickerView(textField : UITextField, pickerView : UIDatePicker){
    pickerView.datePickerMode = .time
    textField.delegate = self
    textField.inputView = pickerView
    let dates = getTimeIntervalForDate()

    pickerView.minimumDate = dates.min
    pickerView.maximumDate = dates.max
    pickerView.minuteInterval = 30
    pickerView.addTarget(self, action: #selector(self.datePickerValueChanged(_:)), for: UIControlEvents.valueChanged)
}

That's it :)

A: Just use this:
datePicker.maximumDate = myMaxDate;
datePicker. minimumDate = myMinDate;

Where myMaxDate and myMinDate are NSDate objects

A: As for my problem, the answer with maximumDate and minimumDate isn't what I am looking for. Maybe my solution is not that clear and right, but it worked great for me.
I have changed the UIDatePicker with UIPickerView, wrote a separate delegate for it:
@interface CHMinutesPickerDelegate () <UIPickerViewDelegate, UIPickerViewDataSource>

@property (nonatomic, strong) NSArray *minutesArray;

@end

@implementation CHMinutesPickerDelegate

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:       (NSInteger)component {
    return [self.minutesArray count];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return [self.minutesArray objectAtIndex: row];
}

- (NSArray *)minutesArray {
    if (!_minutesArray) {
        NSMutableArray *temporaryMinutesArray = [NSMutableArray array];
        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 2; j++) {
                [temporaryMinutesArray addObject: [NSString stringWithFormat: @"%i%i", i, j * 5]];
            }
        }
    _minutesArray = temporaryMinutesArray;
}
    return _minutesArray;
}

The minutesArray returns array of: { "05", "10"... etc}. It is an example for custom minutes picker, you can write the same thing for hour or etc, choosing your own maximum and minimum value. This worked nice for me.


Q: Detect text source from accessibility service I'm using an accessibility service to receive text from a view of a specific app. The text can be inserted manually or via voice. Is there any way to check the source? I'd like to change my behavior if the text is inserted manually or not.


Q: Turning a command line app into a Cocoa GUI app on Mac OS X? Is there any tutorials or references, if such thing is possible, to make GUI applications out of command line apps?
What I mean is, having a command line app, wrap it into an app bundle and create a Cocoa GUI app that would have a simple interface to execute the command line app with its flags and parameters.

A: As a matter of fact there are.  Here is the first hit for a Google search:

*

*Cocoa Dev Central: Wrapping UNIX Commands
What you're looking for is the NSTask class.  Check out the documentation for all the information you need.

A: For very simple scripts, I recommend Platypus. For more complicated scenarios, you could try something like Pashua.


Q: Divide one CSS column in 2 rows http://jsfiddle.net/9877/6E2pQ/2/
What I want do is have columncontent1 on the left and columncontent2 and columncontent3 stacked on the right side.  see the jsfiddle.  How do I fix the css? I am running out of ideas. Is the error in the css or the way the div placed in the body:

A: There's a lot going on there, I've simplified the HTML and CSS:
CSS:
.leftCol {
float: left;
width: 50%;
background-color: #ccc;
height: 60px;
}
.rightColContainer {
float: left;
width: 50%;
}
.rightCol1 {
background-color: #333;
height: 30px;
}
.rightCol2 {
background-color: #777;
height: 30px;
}

HTML:

columncontent1

columncontent2

columncontent3

You only need to 'contain' the right hand column to stop the 'stacked column' flowing incorrectly.

A: CSS3 actually allows you to make several columns automatically without having to have all those classes. Check out this generator: http://www.generatecss.com/css3/multi-column/
This is however only if you are trying to make your content have multiple columns like a newspaper.


Q: Pathos multiprocessing pool CPickle error When i tried to run the following code:
from pathos.multiprocessing import ProcessingPool as Pool
list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]
def function1(x,y):
    print x
    print y
if __name__ == '__main__':
    pool = Pool(5)
    pool.map(function1, list1, list2)

It gets the followwing error:
Traceback (most recent call last):
  File "test.py", line 9, in <module>
    pool.map(function1, list1, list2)
  File "C:\Python27\lib\site-packages\pathos\multiprocessing.py", line 136, in map
    return _pool.map(star(f), zip(*args)) # chunksize
  File "C:\Python27\lib\site-packages\multiprocess\pool.py", line 251, in map
    return self.map_async(func, iterable, chunksize).get()
  File "C:\Python27\lib\site-packages\multiprocess\pool.py", line 567, in get
    raise self._value
cPickle.PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed

Isn't pathos.multiprocessing is designed to solve this problem?

A: I'm the pathos author.  When I try your code, I don't get an error.  However,  if you are seeing a CPickle.PicklingError, I'm guessing you have an issue with your install of multiprocess.  You are on windows, so do you have a C compiler?  You need one for multiprocess to get a full install of multiprocess.


Q: Why does slice not work directly on arguments? Tested it out on this fiddle after looking at underscore.
This seems like a hack to call slice on arguments when it is not on the prototype chain.
Why is it not on the prototype chain when it obviously works on arguments.
var slice = Array.prototype.slice;
function test () {
    return slice.call(arguments,1);
    // return arguments.slice(1)
}
var foo = test(1,2,3,4);
_.each(foo, function(val){
    console.log(val)
});

A: >>> Object.prototype.toString.call(arguments)
<<< "[object Arguments]"
>>> Array.isArray(arguments) //is not an array
<<< false
>>> arguments instanceof Array //does not inherit from the Array prototype either
<<< false

arguments is not an Array object, that is, it does not inherit from the Array prototype. However, it contains an array-like structure (numeric keys and a length property), thus Array.prototype.slice can be applied to it. This is called duck typing.
Oh and of course, Array.prototype.slice always returns an array, hence it can be used to convert array-like objects / collections to a new Array. (ref: MDN Array slice method - Array-like objects)

A: arguments is not a "real" array.

The arguments object is a local variable available within all
  functions; arguments as a property of Function can no longer be used.
The arguments object is not an Array. It is similar to an Array, but
  does not have any Array properties except length. For example, it does
  not have the pop method. However it can be converted to a real Array.

You could do:
var args = Array.prototype.slice.call(arguments);

A: Arguments is not an Array. It's an Arguments object.
Fortunately, slice only requires an Array-like object, and since Arguments has length and numerically-indexed properties, slice.call(arguments) still works.
It is a hack, but it's safe everywhere.

A: Referring to MDN: »The arguments object is not an Array. It is similar to an Array, but does not have any Array properties except length. For example, it does not have the pop method. However it can be converted to a real Array:«
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments
In order to call slice, you have to get the slicefunction, from the Array-prototype.


Q: Create Watchkit notification programmatically I'm looking to push a notification to the Apple Watch at a specific time. I was able to display a static message on the simulator using an apns file, but I'd like to set the data and time of the notification in the controller.
I heard I might not be able to do this on a simulator, but if I got a real phone and watch, how would it work?

A: So, you want to do something in the watch app extension and based on the results, schedule a UILocalNotification that will be sent to the phone at some point?
You cannot directly schedule a UILocalNotification from the watch because you don't have access to the UIApplication object. See Apple staff comment here.  However, using Watch Connectivity, you could send a message from the watch to the phone and have the phone app create and schedule it in the background. The watch will display the notification iff the phone is locked at the trigger time. The watch's notification scene will be invoked in that case.

A: Assuming you want to send the notification from the phone to the watch: You can use UILocalNotification to send a notification to the watch - but the watch must be locked to receive it.  There's also no guarantee when the Watch OS will turn on the watch to run the code that receives your notification, so your notification may arrive minutes or hours after it's sent.


Q: How to create an object in a class by passing a token to a constructor? What I am attempting to do is to take a .txt file that has multiple lines of people's information (Last name, First name, phone number, email) and display the information into a listbox so that a user could select a name in the listbox and display all of the selected person's information in a second form.  The instructions for my assignment say that the next thing I should do is Create your object by passing these tokens to your constructor. (Don’t pass the array but rather each element individually.) I have created a class called PersonEntry that constructs 4 strings containing the 4 pieces of information that's included in the .txt file. Here is where I'm at(the first one is my form1.cs code and the second is my PersonEntry.cs class code) and I don't know what to do next. Any help would be much appreciated!
namespace ChalabiMichaelProgram10
{
    public partial class chalabiMichaelProgram10 : Form
    {
        List<PersonEntry> personsList = new List<PersonEntry>;

        public chalabiMichaelProgram10()
        {
            InitializeComponent();
        }

        private void chalabiMichaelProgram10_Load(object sender, EventArgs e)
        {
            try
            {
                StreamReader inputfile;
                string line;
                int count;

                inputfile = File.OpenText("contacts.txt");

                while (!inputfile.EndOfStream)
                {
                    line = inputfile.ReadLine();
                    char[] delimiters = { ',' };
                    string[] tokens;
                    tokens = line.Split(delimiters);

                    for( count = 0; count < 4; count++)
                    {
                        tokens[count] = tokens[count].Trim();

                    }
                }
            }
        }
    }
}

namespace ChalabiMichaelProgram10
{
    class PersonEntry
    {
        //Constructor.
        public PersonEntry()
        {
            lastName = "";
            firstName   = "";
            phoneNumber = "";
            email       = "";
        }
        public string lastName { get; set; }
        public string firstName { get; set; }
        public string phoneNumber { get; set; }
        public string email { get; set; }
    }
}


Q: array used the same memory space? i have an array in the main program like this: (i am using C# to program in asp.net)
double[][] example= new double[][];

for this example lets imagine is an array of 10*2.
so next thing i will do is send this array to another function like this:
usedarray(example);
public double[][] usedarray(double[][]examplearray)
{

}

i know that a double array in each space has only 64 bit floating point number, so the array will have a 1280 bits for this example used memory, but when is send to the function it used the same space of memory? or it use a complete new set of memory space?

A: Arrays are reference types, not value types.  That means that the variable, examplearray doesn't actually contain 1280 bits of data, it just contains a reference (sometimes also referred to as a pointer) to the actual data, which is stored elsewhere (for the purposes of this post, it doesn't matter where "elsewhere" actually is).  Passing that variable to a method, as you have done there, is only copying that reference (which is 32 or 64 bits, depending on the system), not the underlying 1280 bits of data.


Q: onRestart() and onRefresh() Act Different with Same Code I have the exact same methods and calls in onRefresh() and onRestart(), but for some reason onRestart() does what I want exactly, yet onRefresh() acts differently. What I want to happen is for app to understand when the location is disabled while running.
onRestart() does this: I start the app, get the Forecast data, disable location from status bar, press the home button and open the app again. As expected, onRestart() tries to check for GPS status(with gpsTracker.getIsGPSEnabled()), sees that location is disabled, and sends the according Toast message.
onRefresh() does this: I start the app, get the Forecast data, disable location from status bar, even wait few seconds and then refresh the app. Unexpectedly, onRefresh() gives sends the "Data Refreshed" toast, even though it gets "null, null" as location latitude and longitude.
I could provide other codes as well, but if there was a problem with the rest of the code, why would onRestart() act the way I want? I'm not getting any errors. Any help would be highly appreciated. Thanks.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    final GPSTracker gpsTracker = new GPSTracker(this);

    mSwipeRefreshLayout.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.CYAN);
    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mSwipeRefreshLayout.setRefreshing(false);
                    if (gpsTracker.getIsGPSTrackingEnabled()) {
                        gpsTracker.getLocation();
                        getForecast(gpsTracker);
                        Toast.makeText(MainActivity.this, "Data Refreshed", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Location is not enabled", Toast.LENGTH_LONG).show();
                    }
                }
            }, 3000);
        }
    });
}

@Override
protected void onRestart() {
    super.onRestart();
    final GPSTracker gpsTracker = new GPSTracker(this);
    new Handler().postDelayed (new Runnable ()
       @Override public void run() {
            gpsTracker.getLocation();
            if (gpsTracker.getIsGPSTrackingEnabled()) {
                getForecast(gpsTracker);
                Toast.makeText(MainActivity.this, "Data Refreshed", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MainActivity.this, "Location is not enabled", Toast.LENGTH_LONG).show();
            }
        }
}, 3000);
}

A: onRestart you create a new instance of GPSTracker. try updating your GPSTracker handler in onRefresh.
give it a try

A:             @Override
            public void onRefresh() {
            final GPSTracker gpsTracker = new GPSTracker(MainActivity.this);
            new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshLayout.setRefreshing(false);
                if (gpsTracker.getIsGPSTrackingEnabled()) {
                    gpsTracker.getLocation();
                    getForecast(gpsTracker);
                    Toast.makeText(MainActivity.this, "Data Refreshed", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "Location is not enabled", Toast.LENGTH_LONG).show();
                }
            }
        }, 3000);
    }
});


Q: How to use jdt.ast to resolve polymorphism I'm working to get the override method binding through eclipse-jdt-ast.
Just like when we using eclipse, press Ctrl and click the method ,we can jump to the method implenmentation.
Although it's dynamic binging in java, but the following works well:
public class Father{
public void test(){}
}

And Son:
public class Son extends Father{
@Override
public void test(){}

   public static void  main (String[] arg){
    Father f=new Son();
    f.test();
   }
}

When we click the test in main, we can correctly jump to the Son.java
And I'm wondering how to do it. I tried to see the sources but didn't find the location because the code is too many.
And my code now is :
public class Main {
static  String filep="example/Son.java";
static String[] src={"example/"};
static String[] classfile={"example/"};

public static void main(String[] args) throws IOException,Exception{

    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setSource(Files.toString(new File(filep), Charsets.UTF_8).toCharArray());
    // only setEnvironment can we get bindings from char[]
    parser.setEnvironment(classfile, src, null, true);
    parser.setUnitName(filep);
    parser.setResolveBindings(true);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);
    if (compilationUnit.getAST().hasResolvedBindings()) {
        System.out.println("Binding activated.");
    }
    else {
        System.out.println("Binding is not activated.");
    }
    ASTNode node=compilationUnit.findDeclaringNode("f");
    compilationUnit.accept(new Myvisitor(compilationUnit));
}
}

And my visitor is:
public class Myvisitor extends ASTVisitor {
int i=0;
CompilationUnit compilationUnit;
Myvisitor(CompilationUnit compilationUnit){
    this.compilationUnit=compilationUnit;
}

@Override
public boolean visit(MethodInvocation node) {
    i++;
    System.out.println(i);
    IMethodBinding binding=node.resolveMethodBinding();

    ASTNode astNode=compilationUnit.findDeclaringNode(binding);
    System.out.println(astNode);
    return true;
}

}

It's a little long but simple, hope u can read here. Personally I guess the
findDeclaringNode method may do it. However, it returns null when I pass the binding. So do u have any ideas?
Thanks a lot

A: When looking for all implementations of a given super method, the AST is of little help, as even with its bindings it only has references from sub to super but not the opposite direction.
Searching in the opposite direction uses the SearchEngine. If you look at JavaElementImplementationHyperlink the relevant code section can be found around line 218 (as of current HEAD)
You will have to first find the IMethod representing the super method. Then you prepare a SearchRequestor, an IJavaSearchScope, and a SearchPattern before finally calling engine.search(..). Search results are collected in ArrayList<IJavaElement> links.
A good tradition of Eclipse plug-in development is "monkey see, monkey do", so I hope looking at this code will get you started on your pursuit :)


Q: Close a MSI file handle after being downloaded from a website I have a vsto add-in for outlook. There is a code where I download a MSI file from a website:
Public Sub DownloadMsiFile()
    Try
        Dim url As String = "https://www.website.com/ol.msi"
        Dim wc As New WebClient()
        wc.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;")
        If File.Exists(My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi") Then
            System.IO.File.Delete(My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi")
        End If
        wc.DownloadFile(url, My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi")
        wc.Dispose()
    Catch ex As Exception
        MessageBox.Show("File couldn't be downloaded: " & ex.Message)
    End Try
End Sub

And then I get the MSI version using the following function:
Function GetMsiVersion() As String
    Try
        Dim oInstaller As WindowsInstaller.Installer
        Dim oDb As WindowsInstaller.Database
        Dim oView As WindowsInstaller.View
        Dim oRecord As WindowsInstaller.Record
        Dim sSQL As String
        oInstaller = CType(CreateObject("WindowsInstaller.Installer"), WindowsInstaller.Installer)
        DownloadMsiFile()
        If File.Exists(My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi") Then
            oDb = oInstaller.OpenDatabase(My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi", 0)
            sSQL = "SELECT `Value` FROM `Property` WHERE `Property`='ProductVersion'"
            oView = oDb.OpenView(sSQL)
            oView.Execute()
            oRecord = oView.Fetch
            Return oRecord.StringData(1).ToString()
        Else
            Return Nothing
        End If
    Catch ex As Exception
        MessageBox.Show("File couldn't be accessed: " & ex.Message)
    End Try
End Function

And then I do the comparison with the current dll version to see if there is a need to download a newer version or not:
Public Sub CheckOLUpdates()
    Dim remoteVersion As String = GetMsiVersion()
    Dim installedVersion As String = Assembly.GetExecutingAssembly().GetName().Version.ToString
    If Not String.IsNullOrEmpty(remoteVersion) Then
        Try
            If String.Compare(installedVersion, remoteVersion) < 0 Then
                Dim Result As DialogResult = MessageBox.Show("A newer version is available for download, do you want to download it now?", "OL", System.Windows.Forms.MessageBoxButtons.OKCancel, MessageBoxIcon.Question)
                If Result = 1 Then
                    System.Diagnostics.Process.Start("http://www.website.com/update")
                Else
                    Exit Sub
                End If
            Else
                MessageBox.Show("You have the latest version installed!", "OL", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Exception

        End Try

    End If

End Sub

This works pretty well if this ran once. However if I try again to check for update, I would get the following error which happens while trying to delete the file in DownloadMsiFile() :

The process cannot access the file %temp%\ol.msi because it is being used by another process

If I use the sysinternals handle.exe utility to check the handles on this file I get the outlook process having a handle lock on this file:
handle.exe %temp%\ol.msi
Nthandle v4.30 - Handle viewer
Copyright (C) 1997-2021 Mark Russinovich
Sysinternals - www.sysinternals.com

OUTLOOK.EXE        pid: 25964  type: File          4FC8: %temp%\ol.msi

I was wondering how can I close the handle to avoid this error? Any help is really appreciated

A: So here is what I have to do to close the handle. I have added the following lines after opening the MSI file:
            Marshal.FinalReleaseComObject(oRecord)
            oView.Close()
            Marshal.FinalReleaseComObject(oView)
            Marshal.FinalReleaseComObject(oDb)
            oRecord = Nothing
            oView = Nothing
            oDb = Nothing

So my final code looked like the following:
Function GetMsiVersion() As String
    Try
        Dim oInstaller As WindowsInstaller.Installer
        Dim oDb As WindowsInstaller.Database
        Dim oView As WindowsInstaller.View
        Dim oRecord As WindowsInstaller.Record
        Dim sSQL As String
        Dim Version As String
        oInstaller = CType(CreateObject("WindowsInstaller.Installer"), WindowsInstaller.Installer)
        DownloadMsiFile()
        If File.Exists(My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi") Then
            oDb = oInstaller.OpenDatabase(My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi", 0)
            sSQL = "SELECT `Value` FROM `Property` WHERE `Property`='ProductVersion'"
            oView = oDb.OpenView(sSQL)
            oView.Execute()
            oRecord = oView.Fetch
            Version = oRecord.StringData(1).ToString()
            Marshal.FinalReleaseComObject(oRecord)
            oView.Close()
            Marshal.FinalReleaseComObject(oView)
            Marshal.FinalReleaseComObject(oDb)
            oRecord = Nothing
            oView = Nothing
            oDb = Nothing
        Else
            Version = Nothing
        End If
        Return Version
    Catch ex As Exception
        MessageBox.Show("File couldn't be accessed: " & ex.Message)
    End Try
End Function


Q: What does this line of code means in javascript? function delay(n){
n = n || 2000
//other stuff
}

what does the first line do?
Thanks.

A: It means that if n, the argument passed to the function, is falsey, 2000 will be assigned to it.
Here, it's probably to allow callers to have the option of either passing an argument, or to not pass any at all and use 2000 as a default:

function delay(n){
  n = n || 2000
  console.log(n);
}

delay();
delay(500);

But it would be more suitable to use default parameter assignments in this case.

function delay(n = 2000){
  console.log(n);
}

delay();
delay(500);


Q: Setting tensorflow rounding mode I am working with small numbers in tensorflow, which sometimes results in numerical instability.
I would like to increase the precision of my results, or at the very least determine bounds on my result.
The following code shows a specific example of numerical errors (it outputs nan instead of 0.0, because float64 is not precise enough to handle 1+eps/2):
import numpy as np
import tensorflow as tf

# setup
eps=np.finfo(np.float64).eps
v=eps/2
x_init=np.array([v,1.0,-1.0],dtype=np.float64)

x=tf.get_variable("x", initializer=tf.constant(x_init))
square=tf.reduce_sum(x)
root=tf.sqrt(square-v)

# run
with tf.Session() as session:
    init = tf.global_variables_initializer()
    session.run(init)

    ret=session.run(root)
    print(ret)

I am assuming there is no way to increase the precision of values in tensorflow. But maybe it is possible to set the rounding mode, as in C++ using std::fesetround(FE_UPWARD)? Then, I could force tensorflow to always round up, which would make sure that I am taking the square root of a non-negative number.

What I tried: I tried to follow this question that outlines how to set the rounding mode for python/numpy. However, this does not seem to work, because the following code still prints nan:
import numpy as np
import tensorflow as tf

import ctypes
FE_TONEAREST = 0x0000 # these constants may be system-specific
FE_DOWNWARD = 0x0400
FE_UPWARD = 0x0800
FE_TOWARDZERO = 0x0c00
libc = ctypes.CDLL('libm.so.6') # may need 'libc.dylib' on some systems

libc.fesetround(FE_UPWARD)

# setup
eps=np.finfo(np.float64).eps
v=eps/2
x_init=np.array([v,1.0,-1.0],dtype=np.float64)

x=tf.get_variable("x", initializer=tf.constant(x_init))
square=tf.reduce_sum(x)
root=tf.sqrt(square-v)

# run
with tf.Session() as session:
    init = tf.global_variables_initializer()
    session.run(init)
    ret=session.run(root)
    print(ret)

A: Replace
ret=session.run(root)

with
ret = tf.where(tf.is_nan(root), tf.zeros_like(root), root).eval()

Refer tf.where


Q: Getting "Error: Invalid or corrupt jarfile corda.jar" while bootstrapping the Corda netwrok While trying to bootstrap the Corda network getting below error.

Error: Invalid or corrupt jarfile corda.jar

Please find more details below.
root@domestic-lc:/home/POC_DomesticLC# java -jar corda-tools-network-bootstrapper-4.0.jar --dir build/nodes
Bootstrapping local test network in /home/POC_DomesticLC/build/nodes
Using corda.jar in root directory
Generating node directory for PartyB
Generating node directory for BankB
Generating node directory for Notary
Generating node directory for BankA
Generating node directory for PartyA
Nodes found in the following sub-directories: [PartyA, PartyB, BankB, BankA, Notary]
Found the following CorDapps: []
Not copying CorDapp JARs as --copy-cordapps is set to FirstRunOnly, and it looks like this network has already been bootstrapped.
Waiting for all nodes to generate their node-info files...
#### Error while generating node info file /home/POC_DomesticLC/build/nodes/PartyA/logs ####
Error: Invalid or corrupt jarfile corda.jar
#### Error while generating node info file /home/POC_DomesticLC/build/nodes/PartyB/logs ####
Error: Invalid or corrupt jarfile corda.jar
#### Error while generating node info file /home/POC_DomesticLC/build/nodes/BankA/logs ####
Error: Invalid or corrupt jarfile corda.jar
#### Error while generating node info file /home/POC_DomesticLC/build/nodes/BankB/logs ####
Error: Invalid or corrupt jarfile corda.jar
#### Error while generating node info file /home/POC_DomesticLC/build/nodes/Notary/logs ####
Error: Invalid or corrupt jarfile corda.jar
Error while generating node info file. Please check the logs in /home/POC_DomesticLC/build/nodes/PartyA/logs.

A: Did you get over this issue?
I've tried with bootstrap 4.0 but I didn't see any issue, so my suggestions are:

*

*check your java version, make sure it is 1.8.171+

*make sure the corda.jar (in your build /nodes/notary/corda.jar) is correct because bad network may cause the incomplete corda.jar downloaded

*make sure you've got the tools from official website instead of copying from other way where the bootstrap jar file might be broken

*last, as always, please try to use the latest version bootstrap: 4.3, to utilise the best Corda:
https://software.r3.com/artifactory/corda-releases/net/corda/corda-tools-network-bootstrapper/4.3/

A: I had a similar problem (not with that particular JAR file, but I'm using that file's name in my examples).  Here's how I worked out what was wrong.
These troubleshooting steps may help others who find this issue (but not the OP as the dates show it can't be this issue).
I started by trying to validate the JAR file by inspecting its contents:
$ jar -tf corda.jar

This showed me that it was indeed invalid.  In my case, I saw:
java.util.zip.ZipException: error in opening zip file
    at java.util.zip.ZipFile.open(Native Method)
    at java.util.zip.ZipFile.<init>(ZipFile.java:225)
    at java.util.zip.ZipFile.<init>(ZipFile.java:155)
    at java.util.zip.ZipFile.<init>(ZipFile.java:126)
    at sun.tools.jar.Main.list(Main.java:1115)
    at sun.tools.jar.Main.run(Main.java:293)
    at sun.tools.jar.Main.main(Main.java:1288)

I then looked at the size of the file:
$ ls -alh corda.jar

In my case, it was 133 bytes, which seems a bit small for a JAR file, so I cated it and saw this:
$ cat corda.jar

501 HTTPS Required.
Use https://repo1.maven.org/maven2/
More information at https://links.sonatype.com/central/501-https-required

It turned out that my script (a Dockerfile in fact) was downloading the file with curl -o but from a URL which was no longer supported.  As https://links.sonatype.com/central/501-https-required says:

Effective January 15, 2020, The Central Repository no longer supports insecure communication over plain HTTP and requires that all requests to the repository are encrypted over HTTPS.
If you're receiving this error, then you need to replace all URL references to Maven Central with their canonical HTTPS counterparts:
Replace http://repo1.maven.org/maven2/ with https://repo1.maven.org/maven2/
Replace http://repo.maven.apache.org/maven2/ with https://repo.maven.apache.org/maven2/
If for any reason your environment cannot support HTTPS, you have the option of using our dedicated insecure endpoint at http://insecure.repo1.maven.org/maven2/
For further context around the move to HTTPS, please see https://blog.sonatype.com/central-repository-moving-to-https.

This is fairly specific, but may help someone.


Q: how to add facebook comment to single page application? i have  website news  (single page application )
this code woks well in aspx page

but how to do  in View in SPA
which doesn't contain html or body tags just div
i use durandal in single page application

A: Late answer, but maybe it will help someone. For me the key to getting unique fb comments to render on a single page application was FB.XFBML.parse();
Each time I want to render unique comments:

*

*Change the url, each fb comments thread is assigned to the specific url
So I might have www.someurl.com/#123, www.someurl.com/#456, www.someurl.com/#789, each with its own fb comment thread. In AngularJs this can be done with $location.hash('123');

*Create a new fb-comments div, where 'number' equals '123', '456' or '789'

*Call a function that executes the fb SDK
function FBfun(path) {
  setTimeout(function() { // I'm executing this just slightly after step 2 completes
    window.fbAsyncInit = function() {
      FB.init({
        appId : '123456789123',
        xfbml      : true,
        version    : 'v2.2'
      });
    };

    (function(d, s, id){
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) {return;}
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

    FB.XFBML.parse(); // This is key for all this to work!
  }, 100);
}

A: i added the script to app.js like
   initializeFB: function () {
        if (!isFBInitialized.isInitialized) {

            FB.init({
                appId: 'xxxxxxxxxxxx',
                appSecret: 'xxxxxxxxxxxxxxx',
                // App ID from the app dashboard
                channelUrl: '//mysite//channel.html', // Channel file for x-domain comms
                status: true,                                 // Check Facebook Login status
                cookie: true, // enable cookies to allow the server to access the session
                xfbml: true                                  // Look for social XFBML plugins on the page to be parsed
            });

            (function (d, s, id) {
                var js, fjs = d.getElementsByTagName(s)[0];
                if (d.getElementById(id)) { return; }
                js = d.createElement(s); js.id = id;
                js.src = "//connect.facebook.net/en_US/all.js";
                fjs.parentNode.insertBefore(js, fjs);
            }(document, 'script', 'facebook-jssdk'));

            // Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
            // for any auth related change, such as login, logout or session refresh. This means that
            // whenever someone who was previously logged out tries to log in again, the correct case below
            // will be handled.
            FB.Event.subscribe('auth.authResponseChange', function (response) {
                // Here we specify what we do with the response anytime this event occurs.
                if (response.status === 'connected') {
                    // The response object is returned with a status field that lets the app know the current
                    // login status of the person. In this case, we're handling the situation where they
                    // have logged in to the app.
                    testFBAPI();
                } else if (response.status === 'not_authorized') {
                    // In this case, the person is logged into Facebook, but not into the app, so we call
                    // FB.login() to prompt them to do so.
                    // In real-life usage, you wouldn't want to immediately prompt someone to login
                    // like this, for two reasons:
                    // (1) JavaScript created popup windows are blocked by most browsers unless they
                    // result from direct user interaction (such as a mouse click)
                    // (2) it is a bad experience to be continually prompted to login upon page load.
                    FB.login();
                } else {
                    // In this case, the person is not logged into Facebook, so we call the login()
                    // function to prompt them to do so. Note that at this stage there is no indication
                    // of whether they are logged into the app. If they aren't then they'll see the Login
                    // dialog right after they log in to Facebook.
                    // The same caveats as above apply to the FB.login() call here.
                    FB.login();
                }
            });

            isFBInitialized.isInitialized = true;
        }
    },

and call it in viewattached
as
             app.initializeFB();

then it works well

A: Step 3 for my React app become (more linter friendly):
componentDidMount() {
    window.fbAsyncInit = () => {
        window.FB.init({
            appId: '572831199822299',
            xfbml: true,
            version: 'v4.0',
        });
    };

    (function (d, s, id) {
        const fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) { return; }
        const js = d.createElement(s);
        js.id = id;
        js.src = '//connect.facebook.net/ru_RU/sdk.js';
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

    setTimeout(() => {
        window.FB.XFBML.parse();
    }, 100);
}


Q: Variable "Name" is not readable, how can I fix it? I was inserting some code to make a registration form, but iIfound this
class User {

    private String Nama;
    private String Kelas;
    private int NIM;

    public String getNama{
        return Nama;
    }
    public String setNama{

    }
}

The error message was all "variable is never read". Can someone explain why there is a message on this, and how I can fix it?

A: Though it is not clear where you use your codes, but the following is a java model class, with setter and getter method. Even it is not the direct answer of you question, but I have used this types of model class in my projects, one can find the idea of setter and getter from the following user class.
For using in various purposes You can create your User class as follows with constructors and setter and getter methods :
public class User {

    private String Nama;
    private String Kelas;
    private int NIM;

    public User() {
    }

    public User(String nama, String kelas, int NIM) {
        Nama = nama;
        Kelas = kelas;
        this.NIM = NIM;
    }

    public String getNama() {
        return Nama;
    }

    public void setNama(String nama) {
        Nama = nama;
    }

    public String getKelas() {
        return Kelas;
    }

    public void setKelas(String kelas) {
        Kelas = kelas;
    }

    public int getNIM() {
        return NIM;
    }

    public void setNIM(int NIM) {
        this.NIM = NIM;
    }
}


Q: Run a javascript on regex pattern match url (Blogger) I'm trying to load a javascript on several pages but I only on pages which the url matches with a specific pattern.
The following code works for specific pages but it doesn't accept any wildcard or regex
<b:if cond='data:blog.url == "https://mywebsite.com/yyyy/mm/article.html"'>
<script src='https://javascritp.js'/>
</b:if>

The closest thing I found is described here but since my website is running on Blogger I don't know how to use that code.
Any suggestion or help please?

A: Blogger conditional statements don't provide pattern matching capability. It would be easier to implement what you require via JavaScript directly in the Blogger template -
An example code would look like -
if(window.location.href.match(/Regex-Condition/){
    var script = document.createElement('script'); script.type = 'text/javascript';
    script.src = 'URL-Of-The-Script-You-Want-To-Load';script.async=true;
    var insertScript = document.getElementsByTagName('script')[0]; insertScript.parentNode.insertBefore(script, insertScript);
}

Other than this, you can also take a look at Lambda expressions (Refer to How to use Google Blogger Lambda Operators )

A: Hi and thank you for your feedback! While I was waiting for some reply I realized I've to use JavaScript as you said.
I was testing this code but it looks something is wrong:
<script type='text/javascript'>

var pattern = new RegExp('mywebsite\.com\/(200[8-9]|201[0-6])\/');
if (pattern.test(document.location.href)) {

}

</script>

I've two main concerns:

*

*if the regex is correct

*between the brackets I've to execute some code which includes Blogger conditional statements, div and plain JavaScript. Does this code need some special attention?

Thanks


Q: Split string using SUBSTR or SPLIT? I'm at a loss and hoping to find help here. What I'm trying to accomplish is the following:
I have a .csv file with 8 columns. The third column contains phone numbers formatted like so:
+45 23455678
+45 12314425
+45 43631678
+45 12345678
(goes on for a while)

What I want is:
+45 2345 5678
+45 1231 4425
+45 4363 1678
+45 1234 5678
(etc)

So just a whitespace after the 8th position (inc the + and whitespace). I've tried various things but it's not working. First I tried it with substr but couldn't get it to work. Then looked at the split function. And then I got confused! I'm new to perl so I'm not sure what I'm looking for but I've tried everything. There's 1 condition, all the numbers begin with (let's say) +45 and then a whitespace and a block of numbers. But not all the numbers have the same length, some have more than 10 digits. What I want it to do is take the first bit "+45 1234" (/+43\s{1}\d{4}/) and then the second part no matter how many digits it has. I figured setting LIMIT to 1 so it just adds the last bit no matter if its 4 digits or 8 long.
I've read http://www.perlmonks.org/?node_id=591988, but the part "Using split versus Regular Expressions" got me confused.
I've been trying for 3 days now and not getting anywhere. I guess it should be simple but I'm just now getting to know the basics of perl. I do have an understanding of regular expression but I don't know what statement to use for a certain task. This is my code:
@ARGV or die "Usage: $0  input-file output-file\n";

$inputfile=$ARGV[0];
$outputfile=$ARGV[1];

open(INFILE,$inputfile) || die "Bestand niet gevonden :$!\n";
open(OUTFILE,">$outputfile") || die "Bestand niet gevonden :$!\n";

$i = 0;

@infile=<INFILE>;

foreach ( @infile ) {
    $infile[$i] =~ s/"//g;
    @elements = split(/;/,$infile[$i]);

    @split = split(/\+43\s{1}\d{4}/, $elements[2], 1);

    @split = join ???

    @elements = join(";",@elements);            # Add ';' to all elements
    print OUTFILE "@elements";
    $i = $i+1;
}

close(INFILE);
close(OUTFILE);

A: There are several issues with your code, but to address your question on how to add a space after the 8th position in a string, I'm going to assume you have stored your phone numbers in an array @phone_numbers. This is a task well suited for a regex:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;

my @phone_numbers = (
    '+45 23455678',
    '+45 12314425',
    '+45 43631678',
    '+45 12345678'
);

s/^(.{8})/$1 / for @phone_numbers;

print Dumper \@phone_numbers;

Output:
$VAR1 = [
      '+45 2345 5678',
      '+45 1231 4425',
      '+45 4363 1678',
      '+45 1234 5678'
    ];

To apply the pattern to your script, just add:
$elements[2] =~ s/^(.{8})/$1 /;

or alternatively
my @chars = split//, $elements[2];
splice @chars, 8, 0, ' ';
$elements[2] = join"", @chars;

to alter phone numbers within your foreach loop.

A: Here is a more idiomatic version of your program.
use strict;
use warnings;

my $inputfile  = shift || die "Need input and output file names!\n";
my $outputfile = shift || die "Need an output file name!\n";

open my $INFILE,  '<', $inputfile   or die "Bestand niet gevonden :$!\n";
open my $OUTFILE, '>', $outputfile  or die "Bestand niet gevonden :$!\n";

my $i = 0;

while (<$INFILE>) {
    # print; # for debugging
    s/"//g;
    my @elements = split /;/, $_;
    print join "%", @elements;
    $elements[2] =~ s/^(.{8})/$1 /;
    my $output_line = join(";", @elements);
    print $OUTFILE $output_line;
    $i = $i+1;
}

close $INFILE;
close $OUTFILE;

exit 0;

A: use substr on left hand side:
use strict;
use warnings;

while (<DATA>) {
    my @elements = split /;/, $_;
    substr($elements[2], 8, 0) = ' ';
    print join(";", @elements);
}

__DATA__
col1;col2;+45 23455678
col1;col2;+45 12314425
col1;col2;+45 43631678
col1;col2;+45 12345678

output:
col1;col2;+45 2345 5678
col1;col2;+45 1231 4425
col1;col2;+45 4363 1678
col1;col2;+45 1234 5678

A: Perl one liner which you can use for multiple .csv files also.
perl -0777 -i -F/;/ -a -pe "s/(\+45\s\d{4})(\d+.*?)/$1 $2/ for @F;$_=join ';',@F;" s_infile.csv

A: This is the basic gist of how its done. The "prefix" to the numeric string is \+45, which is hard coded, and you may change it as needed. \pN means numbers, {4} means exactly 4.
use strict;
use warnings;

while (<DATA>) {
    s/^\+45 \pN{4}\K/ /;
    print;
}

__DATA__
+45 234556780
+45 12314425
+45 436316781
+45 12345678

Your code has numerous other problems:
You do not use use strict; use warnings;. This is a huge mistake. It's like riding a motorcycle and protecting your head by putting on a blindfold instead of a helmet. Often, it is an easy piece of advice to overlook, because it is explained very briefly, so I am being more verbose than I have to in order to make a point: This is the most important thing wrong. If you miss all the rest of your errors, it's better than if you miss this part.

Your open statements are two-argument, and you do not verify your arguments in any way. This is very dangerous, because it allows people to perform arbitrary commands. Use the three-argument open with a lexical file handle and explicit MODE for open:
open my $in, "<", $inputfile or die $!;

You slurp the file into an array: @infile=<INFILE> The idiomatic way to read a file is:
while (<$in>) {  # read line by line
    ...
}

What's even worse, you loop with foreach (@infile), but refer to $infile[$i] and keep a variable counting upwards in the loop. This is mixing two styles of loops, and even though it "works", it certainly looks bad. Looping over an array is done either:
for my $line ( @infile ) {  # foreach style
    $line =~ s/"//g;
    ...
}

for my $index ( 0 .. $#infile ) { # array index style
    $infile[$index] =~ ....
}

But neither of these two loops are what you should use, since the while loop above is much preferred. Also, you don't actually have to use this method at all. The *nix way is to supply your input file name or STDIN, and redirect STDOUT if needed:
perl script.pl inputfile > outputfile

or, using STDIN
some_command | perl script.pl > outputfile

To achieve this, just remove all open commands and use
while (<>) {  # diamond operator, open STDIN or ARGV as needed
    ...
}

However, in this case, since you are using CSV data, you should be using a CSV module to parse your file:
use strict;
use warnings;
use ARGV::readonly;  # safer usage of @ARGV file reading

use Text::CSV;

my $csv = Text::CSV->new({
        sep_char    => ";",
        eol     => $/,
        binary      => 1,
        });

while (my $row = $csv->getline(*DATA)) {  # read input line by line
    if (defined $row->[1]) {              # don't process empty rows
        $row->[1] =~ s/^\+45 *\pN{4}\K/ /;
    }
    $csv->print(*STDOUT, $row);
}

__DATA__
fooo;+45 234556780;bar
1231;+45 12314425;
oh captain, my captain;+45 436316781;zssdasd
"foo;bar;baz";+45 12345678;barbarbar

In the above script, you can replace the DATA file handle (which uses inline data) with ARGV, which will use all script argument as input file names. For this purpose, I added ARGV::readonly, which will force your script to only open files in a safe way.
As you can see, my sample script contains quoted semi-colons, something split would be hard pressed to handle. The specific print statement will enforce some CSV rules to your output, such as adding quotes. See the documentation for more info.

A: To add a space after the eighth character of a string you can use the fourth parameter of substr.
substr $string, 8, 0, ' ';

replaces a zero-length substring starting at offset 8 with a single space.
You may think it's safer to use regular expressions so that only data in the expected format is changed
$string =~ s/^(\+\d{2} \d{4})/$1 /;

or
$str =~ s/^\+\d{2} \d{4}\K/ /;

will achieve the same thing, but will do nothing if the number doesn't look as it should beforehand.
Here is a reworking of your program. Most importantly you should use strict and use warnings at the start of your program, and declare variables with my at the point of their first use. Also use the three-paramaeter form of open and lexical filehandles. Lastly it is best to avoid reading an entire file into an array when a while loop will let you process it a line at a time.
use strict;
use warnings;

@ARGV == 2 or die "Usage: $0 input-file output-file\n";

my ($inputfile, $outputfile) = @ARGV;

open my $in, '<', $inputfile or die "Bestand niet gevonden: $!";
open my $out, '>', $outputfile or die "Bestand niet gevonden: $!";

while (<$in>) {
  tr/"//d;
  my @elements = split /;/;
  substr $elements[2], 8, 0, ' ';
  print $out join ';', @elements;
}


Q: DOM reload after ajax form injection Ive tried similar questions to no avail.
My question is simply how to reload the DOM after an ajax request has been made?
Its not a question regarding event delegation, rather one concerning jquery selectors.
sample:
editUser : function(){
            var editItem = $("a.edit");

            editItem.on('click', function(e){
                e.preventDefault();

               //click the users tab & the edit tab
                var usersjq = $("li#users-jq");
                usersjq.find("a").eq(0).click();
                $("ul.tabs").find("a").eq(2).click();

                var uid = $(this).attr('id').split('_')[1];
                $(".three #users-edit").empty();

                $(".three #users-edit").load(BASE_PATH + 'users/admin/users/edit/' + uid, function(){
                   //loads a form with id of #form-users-edit

                }, 'html');

            });
        },
formEditUsers : function(){

            //#form-users-edit is not selectable

            //all of these just return jQuery ( )
            console.log($(".three #users-edit").find("#form-users-edit"));
            console.log($(document.forms));
            console.log($("form#form-users-edit"));

        }

Regards.

A: Passing formEditUsers() into the ajax success callback seems to work fine.


Q: Not full binding in knockout Knockout doesn't work as expected, im my interface.
I suppose my mistake. But I cannot understand it.
I have an album with genres included tracks with genres:
var initialData = [{
    title: 'Danny',
    genres: [
        {id: 21,
        title: 'Noise'},
        {id: 22,
        title: 'EBM'}],
    tracks: [
        {title: 'Pony',
        genres: [
            {id: 21,
            title: 'Noise'},
            {id: 22,
            title: 'EBM'}]},
        {title: 'Hungry',
        genres: [
            {id: 21,
            title: 'Noise'},
            {id: 22,
            title: 'EBM'}]}
    ]

}];

I want to create 1-way sync between album genres to tracks genres:

*

*If i add genre to album, this genre would be added to all tracks.

*If i delete genre from album, this genre would be deleted from all tracks.

*If i add genre to track, this genre would be added only to this track.

*If i delete genre from track, this genre would be deleted only from this track.

My sync works fine (except one case) with this functions:
self.addGenre = function(album) {
    var id = rand(),
        item = {
            id: id,
            title: ' genre #' + id
        };
    album.genres.push(item);

    if (album.tracks()) {
        $.each(album.tracks(), function (index, track) {
            track.genres.push(item);
        });
    }
};

self.removeGenre = function(genre) {
    $.each(self.albums(), function() {
        this.genres.remove(genre);
        if (this.tracks()) {
            $.each(this.tracks(), function (index, track) {
                track.genres.remove(genre);
            });
        }
    });
};

Exception is if I want to delete default (Noise, EBM, see initialData above ) genre from albums. it doesn't work.
I created an jsFiddle to show this case and include in it a lot of console.log() to debug

A: The problem is that when you use ko-mapping, it turns every property into an observable. The new genres you create are not the same kind of object as the initial objects, because they are just standard vanilla objects. So the genre you are trying to remove from the track is not the same one you removed from the album.
A simple way to fix your issue is to alter the remove function, as in this fiddle.
$.each(this.tracks(), function(index, track) {
    var toRemove = ko.utils.arrayFirst(track.genres(), function(item) {
        return ko.utils.unwrapObservable(genre.id) == ko.utils.unwrapObservable(item.id);
    });
    track.genres.remove(toRemove);
});

A better way would be to be a little more thorough in generating your initial viewmodel, the new genres, or both. This won't be easy.


Q: Transitioning Between Index Paths in a DetailViewController? Swift So using the code below, I've segued my CollectionViewCell indexPath into the new DetailViewController. now each `DetailViewController displays what is contained in the array of the indexPath selected.
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let animal: Animal!
    let anims: [Animal] = dataSource.anims

    animal = anims.filter{ $0.isDefault }[indexPath.row]

    DispatchQueue.main.async {
        self.performSegue(withIdentifier: "DetailVC", sender: animal)
    }
}

So that means the new DetailVCwill be able to pull the data from the array that corresponds with the selected indexPath.row, which it does.
Now here's the issue. Once I'm in the DetailVC, I want to make a button that lets me switch the displayed data to the previous or next indexPath.row. To explain it better, below is some Pseudo-Code that explains what I'm trying to do
@IBAction func nextIndex(_ sender: Any) {
     self.view.indexPath.row = self.view.indexPath.row +1
        or
     self.datasource = next datasource index
}

Now what would I need to do to transition between these indexPaths from inside the DetailViewController? Such as a "go to next" or "go to previous" or "go to [selected path]" button?
I feel there may be a simple answer to this that I'm not getting.

A: Easy solution: You can implement singleton, manager that will be responsible for this. e.g.
class AnimalManager: NSObject {

    static let shared = AnimalManager()

    private var animals = [Animal]()
    private var currentIndex: Int?

    .....
}

Now you can implement such methods like: current animal, next animal, revious, etc.