text:
Q: Execute raw SQL query in ASP.NET MVC, database first mode The model of my project is database first, and uses remote access to database on another server.
I need to use raw SQL query because my query is very complex and I feel more comfortable in SQl not LINQ.
This is how I do:
        string query = "select * from Inquiry_TBL where ...";

        using (educationEntities db = new educationEntities())
        {
            var list = db.Database.SqlQuery<Inquiry_TBL>(query);
            ViewData["total"] = list.Count();
        }

The problem is sometimes I get the query result within a second, sometimes it just keep loading for a long time and gives me an error that 'Calling 'Read' when the data reader is closed is not a valid operation.'
Why is that? Is there something wrong with my code, or because I'm using remote access to another server? Will switching to local server solve the problem?

A: The Entity Framework Code First API includes methods that enable you to pass SQL commands directly to the database. You have the following options:
•   Use the DbSet.SqlQuery method for queries that return entity types. The returned objects must be of the type expected by the DbSet object, and they are automatically tracked by the database context unless you turn tracking off. (See the following section about the AsNoTracking method.)
•   Use the Database.SqlQuery method for queries that return types that aren't entities. The returned data isn't tracked by the database context, even if you use this method to retrieve entity types.
•   Use the Database.ExecuteSqlCommand for non-query commands.

Calling a Query that Returns Entities:

public async Task<ActionResult> Details(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    // Commenting out original code to show how to use a raw SQL query.
    //Department department = await db.Departments.FindAsync(id);

    // Create and execute raw SQL query.
    string query = "SELECT * FROM Department WHERE DepartmentID = @p0";
    Department department = await db.Departments.SqlQuery(query, id).SingleOrDefaultAsync();

    if (department == null)
    {
        return HttpNotFound();
    }
    return View(department);
}

Calling a Query that Returns Other Types of Objects:

public ActionResult About()
{
    //Commenting out LINQ to show how to do the same thing in SQL.
    //IQueryable<EnrollmentDateGroup> = from student in db.Students
    //           group student by student.EnrollmentDate into dateGroup
    //           select new EnrollmentDateGroup()
    //           {
    //               EnrollmentDate = dateGroup.Key,
    //               StudentCount = dateGroup.Count()
    //           };

    // SQL version of the above LINQ code.
    string query = "SELECT EnrollmentDate, COUNT(*) AS StudentCount "
        + "FROM Person "
        + "WHERE Discriminator = 'Student' "
        + "GROUP BY EnrollmentDate";
    IEnumerable<EnrollmentDateGroup> data = db.Database.SqlQuery<EnrollmentDateGroup>(query);

    return View(data.ToList());
}

Calling an Update Query:

[HttpPost]
public ActionResult UpdateCourseCredits(int? credit)
{
    if (credit != null)
    {
        ViewBag.RowsAffected = db.Database.ExecuteSqlCommand(
            "UPDATE Course SET Credits = Credits * {0}", credit);
    }
    return View();
}

For more information have a look at Advanced Entity Framework 6 Scenarios for an MVC 5 Web Application (12 of 12).


text:
Q: QEMU "tgc fatal error" on ARM laptop? I'm trying to emulate an x86 Debian machine on an ARM laptop.
I am following the tutorial here:
https://wiki.debian.org/QEMU#Operation
The issue is, when I run this command:
    $ qemu-system-i386 -hda debian.img -cdrom debian-testing-i386-businesscard.iso -boot d -m 256

it throws this error:

/build/buildd/qemu-kvm-1.0+noroms/tcg/arm/tcg-target.c:859: tcg fatal error
Aborted (core dumped)

I have not managed to find any solutions.

A: This looks like a very old QEMU and the error report indicates an internal bug in the TCG translator. Try with a more recent build of QEMU and perhaps raise a bug if the problem is still present.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Latest Kendo Web (2014.1.318) model.set method not working Seems like there's a bug in the latest version of Kendo Web.
I'm using the select event of a drop down list in a custom popup grid editor to set the value of other fields in the model. The code for the select evet looks like:
function select(e) {
  var data = this.dataItem(e.item.index());
  var win = this.element.closest("[data-role=window]");
  var uid = win.data("uid");
  var model = grid.data("kendoGrid").dataSource.getByUid(uid);
  model.set('field', data.value);
}

I can confirm that the dataItem of the selected drop down item is correctly returned, as is the model of the row being edited.
No errors are generated, but the model is not updated. The same code works with version 2013.3.1316.
I don't know if anyone from Telerik looks on these forums?

A: As far as I can see the problem is in data.value. Did you check that it contains the desired value?
I did this:
    select : function (e) {
        var data = this.dataItem(e.item.index());
        var win = this.element.closest("[data-role=window]");
        var uid = win.data("uid");
        var model = grid.data("kendoGrid").dataSource.getByUid(uid);
        model.set('field', data);
    }

trying to reproduce your code and works fine.
Check the code here: http://jsfiddle.net/OnaBai/XNcmt/33/ where I copy the value that you select for City column into City2 column.


text:
Q: Centos 8 split root volume to LVM I am using CentOs 8 and deployed on cloud infrastructure.
It is attached to root disk at /dev/xvda having size 250GB.
Device     Boot Start       End   Sectors  Size Id Type
/dev/xvda1       2048      4095      2048    1M 83 Linux
/dev/xvda2 *     4096 524287966 524283871  250G 83 Linux

This root disk contains around 20GB OS related data and other 230 GB is free. I want to re-partition this 230GB space on same disk /dev/xvda to below like.
Device     Boot Start       End   Sectors  Size Id Type
   /dev/xvda1       2048      4095      2048    1M 83 Linux
   /dev/xvda2      4096 524287966         **  100G 83 Linux
   /dev/xvda3      4096 **                **   50G 83 Linux
   /dev/xvda4      4096 **                **   50G 83 Linux
   /dev/xvda5      4096 **                **   20G 83 Linux
   /dev/xvda6      4096 **          524283871  30G 83 Linux

Does linux provide any best way to achieve this? I have gone through LVM in linux , mostly it is concerned with partitioning unallocated space(creating LVM on disk destroys any data, in my case its OS itself).
Could someone please guide me ?


text:
Q: Scaling data with different importance I have 9 attributes: x1,x2,x3,x4,...,x9 and I know that the attributes x9 must have the same value in a cluster and the attribute X1 have more importance than others (x2,...,x8)
I'm using Euclidean distance and I normalized the data in order to have values between 0 and 1. I'm also using "One-Hot Encode Data" method in attributes x3,x4,x5,x6,x7,x8,x9.
I'm correlating within columns.
What do you recommend to scale my dataset properly?

For clarity here's what some of the input data looks like
Raw Input - Example 0.0.1
          x1,   x2, x3_1, x3_2, x3_3, x3_4, x3_5, x3_6, x3_7, x3_8, x3_9, x3_10, x3_11, x3_12, x3_13, x3_14, x3_15, x4_1, x4_2, x4_3, x4_4, x4_5, x4_6, x4_7, x4_8, x4_9, x5_1, x6_1, x7_1, x7_2, x7_3, x8_1, x8_2, x8_3, x9_1, x9_2, x9_3, x9_4

1553803283.0,  8.0,  1.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,   0.0,   0.0,   0.0,   0.0,  1.0,  0.0,  0.0,  1.0,  1.0,  1.0,  0.0,  0.0,  0.0,  0.0,  1.0,  0.0,  0.0,  0.0,  1.0
1553803286.0,  8.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  1.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,   0.0,   0.0,   0.0,   0.0,  1.0,  0.0,  0.0,  1.0,  1.0,  1.0,  0.0,  0.0,  0.0,  0.0,  1.0,  0.0,  0.0,  0.0,  1.0
1553803287.0,  8.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  1.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,   0.0,   0.0,   0.0,   0.0,  1.0,  0.0,  0.0,  1.0,  1.0,  1.0,  0.0,  0.0,  0.0,  0.0,  1.0,  0.0,  0.0,  0.0,  1.0
1553803343.0, 24.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  1.0,  0.0,  0.0,  0.0,  0.0,  0.0,   0.0,   0.0,   0.0,   0.0,  0.0,  1.0,  0.0,  1.0,  1.0,  0.0,  1.0,  0.0,  0.0,  1.0,  0.0,  0.0,  1.0,  0.0,  0.0
1553803349.0, 24.0,  0.0,  0.0,  0.0,  0.0,  0.0,  1.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,  0.0,   0.0,   0.0,   0.0,   0.0,  0.0,  1.0,  0.0,  1.0,  1.0,  0.0,  1.0,  0.0,  0.0,  1.0,  0.0,  0.0,  1.0,  0.0,  0.0

Abridged Input - Example 0.0.2
          x1,  x2,                 x3,                  x4,                 x5,                 x6,                 x7,                 x8,                 x9

1553803283.0, 8.0, <one-hot-length-15>, <one-hot-length-9>, <one-hot-length-1>, <one-hot-length-1>, <one-hot-length-3>, <one-hot-length-3>, <one-hot-length-4>
1553803286.0, 8.0, <one-hot-length-15>, <one-hot-length-9>, <one-hot-length-1>, <one-hot-length-1>, <one-hot-length-3>, <one-hot-length-3>, <one-hot-length-4>
1553803287.0, 8.0, <one-hot-length-15>, <one-hot-length-9>, <one-hot-length-1>, <one-hot-length-1>, <one-hot-length-3>, <one-hot-length-3>, <one-hot-length-4>

A:
Side note; looks like you've got three extra columns of data... somewhere... oh ya may have got that on the last edit, aside from the slightly wonky spacing it's far more comprehensible.

Recommendations based off information so far provided;

*

*consider leveraging Word-2-Vec for some of the encoding, eg. x3 through x9, as it's a simple way of dealing with novel inputs; there'd still be the same number of columns, but the benefits may outweigh the costs of restructuring the network some.

*in regards to columns x1 and x2, maybe take another glance at the paper linked to the other question I commented about. If I read it correctly they had some special sauce for feeding raw inputs into their network that maybe inspirational.

Information that will likely help with better answers or updates to this one would be;

*

*what are you trying to model, eg. are you trying to predict, recognize/categorize, etc.?

*what's the behavior of the network currently and what are you looking to improve?

*what libraries, if any, are you using?

Simply put, I've found no fool proof, "proper" or the way for massaging inputs, however, depending upon how you frame what you want modeled there maybe options that are an easy fit.
Furthermore it may help in being flexible in what it is that you want modeled, try to frame things from a few different angles so to speak. Or for a more tangible example check this Q&A, in particular how the linked to researchers re-framed genetic data into a time-series problem; by being a bit flexible in mindset they where able to do some interesting things swiftly.

Hopefully with a little more information someone can come along and do better at providing a direct answer with less hand waving.

Updates
Okay so with the information now provided from your comments it almost sounds like you may want to train a network to train variations of network parameters. There's many ways that could be modeled; Neuroevolution, Genetic Evolution, etc. and ways of mitigating mutation could even be similar to pruning (or what I think of as intentional brain-damage) so that offspring networks don't get overly complex.
What I'm getting at is that cluster size, scaling factors, and other parameters maybe something that can be sorted through the use of a network higher in the stack that tries fiddling with things for ya; essentially it would be taking the model that you're already happy with, tweak some-thing about it a bit, inbreed those that preformed best, brain damage the mid-age offspring, and repeat.

Side note, if ya add more information (such as what I pointed out) to your question it'll definitely help those writing better answers than I.


text:
Q: Copy 2d array in Python: Confusion My understanding is that:
def copy_2d(p):
    return list(p)

Would make a full copy of p and return it as a result. list( p) seems to do this when I try it in the repl. However it seems like calling the above method like this:
    b = [[1,2,3],[3,4,5]]
    a = copy_2d(b)
    a[0][0] = 0
    if (b[0][0] == 0): print "Huh??"

It prints "Huh??", that is, it appears that b is just a reference to a. I double checked but I might be blind. Can someone clarify please?

A: Your current code for copy_2d returns a shallow copy of the list you pass as its argument. That is, you're creating a new outer list, but the inner values (which may be lists themselves) are not copied. The new list references the same inner lists, so when you mutate one of them, you'll see the same change in the shallow copy as you do in the original list.
You can fix the issue by copying the inner lists as well as creating a new outer list. Try:
def copy_2d(p):
    return map(list, p)   # warning: this only works as intended in Python 2

In Python 2, this works because map returns a list. In Python 3, the map function returns an iterator, so a list comprehension like [list(inner) for inner in p] would be better.
Of course, if you don't need to write your own code to solve this problem, you should just use copy.deepcopy from the standard library.

A: import copy

def copy_2d(p):
    return copy.deepcopy(p)

or
def copy_2d(p):
    return [list(p2) for p2 in p]

What you did copied the array with all the values inside. But inside you had objects with were arrays. Your function did not copied inside lists but their references.
The second solution still copies references, but one layer below.

A: Shallow copy made. Same logic as here?what-does-the-list-function-do-in-python
"list() converts the iterable passed to it to a list. If the iterable is already a list then a shallow copy is returned, i.e only the outermost container is new rest of the objects are still the same."


text:
Q: Cannot manage to update tree cell/item graphics while waiting for a load to complete The initial situation is like this:

Now, the tree is potentially huge (I have a tree with 22 million nodes for instance). What happens here is that I use a jooq/h2 backend to store all the nodes and execute queries to find children.
Which means, in the image above, the node is marked as expandable but its children are not populated yet. It is done on demand. And after expansion I get this:

The problem I have is that of course, expansion can take time; and what I'd like to do is to add a visual clue to the graphic of the TreeItem to show that it is loading...
And I can't do it.

OK, first of all, a general view of the architecture:

*

*it is, in short, "MVP with passive views";

*what JavaFX calls a "controller", which is in my code implemented by *Display classes, are the passive views, whose only role is to capture UI events and forward them to the *Presenter; such classes are "GUI implementation specific";

*the *Presenter reacts to those events by ordering the *View class to update the *Display;

*when tasks require a certain amount of time to complete, too much for the GUI to remain interactive, a BackgroundTaskRunner is used by the *Presenter to:

*

*instruct the *View to modify the UI to acknowledge the task (on the GUI thread);

*perform the task (on a background thread);

*instruct the *View to modify the UI when the task completes (on the GUI thread);

*if the task fails, instruct the *View to modify the UI accordingly (on the GUI thread).

With JavaFX:

*

*the UI is a *Display class; it is defined by, and loaded from, an FXML file;

*the (implementation of) the *View class has visibility over all GUI elements defined in the *Display class.

The *View class is in fact an interface; this allows me to be able to make a webapp version of this program (planned).

Now, the context of this code...
The *Presenter, *View and *Display all relate to the "Parse tree" tab visible in the above images.
Given the architecture above, the problem lies with the implementation of the *View class, and with the *Display class.
The *Display class has an init() method which initializes all relevant JavaFX components, if need be. In this case, the TreeView, called parseTree, is initialized as such:
@Override
public void init()
{
    parseTree.setCellFactory(param -> new ParseTreeNodeCell(this));
}

ParseTreeNodeCell is defined as such:
public final class ParseTreeNodeCell
    extends TreeCell<ParseTreeNode>
{
    // FAILED attempt at showing a progress indicator...
    private final ProgressIndicator indicator = new ProgressIndicator();
    private final Text text = new Text();
    private final HBox hBox = new HBox(text, indicator);

    public ParseTreeNodeCell(final TreeTabDisplay display)
    {
        // FIXME: not sure about the following line...
        indicator.setMaxHeight(heightProperty().doubleValue());
        // ... But this I want: by default, not visible
        indicator.setVisible(false);

        // The whole tree is readonly
        setEditable(false);

        // Some non relevant code snipped away
    }

    public void showIndicator()
    {
        indicator.setVisible(true);
    }

    public void hideIndicator()
    {
        indicator.setVisible(false);
    }

    // What to do when a TreeItem is actually attached...
    @Override
    protected void updateItem(final ParseTreeNode item, final boolean empty)
    {
        super.updateItem(item, empty);
        if (empty) {
            setGraphic(null);
            return;
        }
        final String msg = String.format("%s (%s)",
            item.getRuleInfo().getName(),
            item.isSuccess() ? "SUCCESS" : "FAILURE");
        text.setText(msg);
        setGraphic(hBox);
        // HACK. PUKE. UGLY.
        ((ParseTreeItem) getTreeItem()).setCell(this);
    }
}

ParseTreeItem is this:
public final class ParseTreeItem
    extends TreeItem<ParseTreeNode>
{
    private final boolean leaf;

    private ParseTreeNodeCell cell;

    public ParseTreeItem(final TreeTabDisplay display,
        final ParseTreeNode value)
    {
        super(value);
        leaf = !value.hasChildren();

        // If the item is expanded, we load children.
        // If it is collapsed, we unload them.
        expandedProperty().addListener(new ChangeListener<Boolean>()
        {
            @Override
            public void changed(
                final ObservableValue<? extends Boolean> observable,
                final Boolean oldValue, final Boolean newValue)
            {
                if (oldValue == newValue)
                    return;
                if (!newValue) {
                    getChildren().clear();
                    return;
                }
                display.needChildren(ParseTreeItem.this);
            }
        });
    }

    @Override
    public boolean isLeaf()
    {
        return leaf;
    }

    public void setCell(final ParseTreeNodeCell cell)
    {
        this.cell = cell;
    }

    public void showIndicator()
    {
        cell.showIndicator();
    }

    public void hideIndicator()
    {
        cell.hideIndicator();
    }
}

Now, always in the *Display class, the needChildren() method is defined as such:
ParseTreeItem currentItem;

// ...

public void needChildren(final ParseTreeItem parseTreeItem)
{
    // Keep a reference to the current item so that the *View can act on it
    currentItem = parseTreeItem;
    presenter.needChildren(currentItem.getValue());
}

The presenter does this:
public void needChildren(final ParseTreeNode value)
{
    taskRunner.computeOrFail(
        view::waitForChildren, () -> {
            // FOR TESTING
            TimeUnit.SECONDS.sleep(1L);
            return getNodeChildren(value.getId());
        },
        view::setTreeChildren,
        throwable -> mainView.showError("Tree expand error",
            "Unable to extend parse tree node", throwable)
    );
}

(see here; for the taskRunner)
The corresponding methods in the view member above (JavaFX implementation) do this:
@Override
public void waitForChildren()
{
    // Supposedly shows the indicator in the TreeItemGraphic...
    // Except that it does not.
    display.currentItem.showIndicator();
}

@Override
public void setTreeChildren(final List<ParseTreeNode> children)
{
    final List<ParseTreeItem> items = children.stream()
        .map(node -> new ParseTreeItem(display, node))
        .collect(Collectors.toList());
    // This works fine
    display.currentItem.getChildren().setAll(items);
    // But this does not...
    display.currentItem.hideIndicator();
}

Even though I define methods on the TreeItem to show the progress indicator, it doesn't show at all :/
In fact, my problem is twofold, and all related to ParseTreeItem:

*

*in ParseTreeNodeCell, I need to cast to ParseTreeItem to set the cell;

*even when I do this, well, it doesn't work at all, I can't see the indicator show up at all.

Not only that, but for some reason I need to check (in ParseTreeNodeCell) that I actually have a value, since otherwise I get an NPE. And I can't find a way to get the matching cell from a tree item...
So, all in all, I do many things badly and none correctly.
How do I manage to get the graphic of a TreeItem change in that situation, as long as the loading is still in progress?

EDIT
Solution found, inspited by the code written by @James_D; see my own answer for how I really did it.

A: First, I admit I didn't go through all your code carefully.
I think the approach to have here is to use a TreeItem subclass that exposes an observable property describing the "loaded status" of the children. Then have the tree cells observe the loaded status of the current tree item, and display a progress bar accordingly.
Here's a SSCCE:
(Updated: apparently if I only observe the treeItem and not the item, the tree fails to remove the disclosure graphics from empty cells... Fixed by using the itemProperty to manage the text.)
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javafx.application.Application;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class LazyTreeCellLoadingExample extends Application {

    // Executor for background tasks:
    private static final ExecutorService exec = Executors.newCachedThreadPool(r -> {
        Thread t = new Thread(r);
        t.setDaemon(true);
        return t ;
    });

    @Override
    public void start(Stage primaryStage) {
        TreeView<Long> tree = new TreeView<>();
        tree.setRoot(new LazyTreeItem(1L));

        // cell factory that displays progress bar when item is loading children:
        tree.setCellFactory(tv ->  {

            // the cell:
            TreeCell<Long> cell = new TreeCell<>();

            // progress bar to display when needed:
            ProgressBar progressBar = new ProgressBar();

            // listener to observe *current* tree item's child loading status:
            ChangeListener<LazyTreeItem.ChildrenLoadedStatus> listener = (obs, oldStatus, newStatus) -> {
                if (newStatus == LazyTreeItem.ChildrenLoadedStatus.LOADING) {
                    cell.setGraphic(progressBar);
                } else {
                    cell.setGraphic(null);
                }
            };

            // listener for tree item property
            // ensures that listener above is attached to current tree item:
            cell.treeItemProperty().addListener((obs, oldItem, newItem) -> {

                // if we were displaying an item, (and no longer are...),
                // stop observing its child loading status:
                if (oldItem != null) {
                    ((LazyTreeItem) oldItem).childrenLoadedStatusProperty().removeListener(listener);
                }

                // if there is a new item the cell is displaying:
                if (newItem != null) {

                    // update graphic to display progress bar if needed:
                    LazyTreeItem lazyTreeItem = (LazyTreeItem) newItem;
                    if (lazyTreeItem.getChildrenLoadedStatus() == LazyTreeItem.ChildrenLoadedStatus.LOADING) {
                        cell.setGraphic(progressBar);
                    } else {
                        cell.setGraphic(null);
                    }

                    // observe loaded status of current item in case it changes
                    // while we are still displaying this item:
                    lazyTreeItem.childrenLoadedStatusProperty().addListener(listener);
                }
            });

            // change text if item changes:
            cell.itemProperty().addListener((obs, oldItem, newItem) -> {
                if (newItem == null) {
                    cell.setText(null);
                    cell.setGraphic(null);
                } else {
                    cell.setText(newItem.toString());
                }
            });

            return cell ;
        });

        Button debugButton = new Button("Debug");
        debugButton.setOnAction(evt -> {
            dumpData(tree.getRoot(), 0);
        });

        primaryStage.setScene(new Scene(new BorderPane(tree, null, null, debugButton, null), 400, 250));
        primaryStage.show();
    }

    private void dumpData(TreeItem<Long> node, int depth) {
        for (int i=0; i<depth; i++) System.out.print(" ");
        System.out.println(node.getValue());
        for (TreeItem<Long> child : node.getChildren()) dumpData(child, depth+1);
    }

    // TreeItem subclass that lazily loads children in background
    // Exposes an observable property specifying current load status of children
    public static class LazyTreeItem extends TreeItem<Long> {

        // possible load statuses:
        enum ChildrenLoadedStatus { NOT_LOADED, LOADING, LOADED }

        // observable property for current load status:
        private final ObjectProperty<ChildrenLoadedStatus> childrenLoadedStatus = new SimpleObjectProperty<>(ChildrenLoadedStatus.NOT_LOADED);

        public LazyTreeItem(Long value) {
            super(value);
        }

        // getChildren() method loads children lazily:
        @Override
        public ObservableList<TreeItem<Long>> getChildren() {
            if (getChildrenLoadedStatus() == ChildrenLoadedStatus.NOT_LOADED) {
                lazilyLoadChildren();
            }
            return super.getChildren() ;
        }

        // load child nodes in background, updating status accordingly:
        private void lazilyLoadChildren() {

            // change current status to "loading":
            setChildrenLoadedStatus(ChildrenLoadedStatus.LOADING);
            long value = getValue();

            // background task to load children:
            Task<List<LazyTreeItem>> loadTask = new Task<List<LazyTreeItem>>() {

                @Override
                protected List<LazyTreeItem> call() throws Exception {
                    List<LazyTreeItem> children = new ArrayList<>();
                    for (int i=0; i<10; i++) {
                        children.add(new LazyTreeItem(10*value + i));
                    }

                    // for testing (loading is so lazy it falls asleep)
                    Thread.sleep(3000);
                    return children;
                }

            };

            // when loading is complete:
            // 1. set actual child nodes to loaded nodes
            // 2. update status to "loaded"
            loadTask.setOnSucceeded(event -> {
                super.getChildren().setAll(loadTask.getValue());
                setChildrenLoadedStatus(ChildrenLoadedStatus.LOADED);
            });

            // execute task in backgroun
            exec.submit(loadTask);
        }

        // is leaf is true only if we *know* there are no children
        // i.e. we've done the loading and still found nothing
        @Override
        public boolean isLeaf() {
            return getChildrenLoadedStatus() == ChildrenLoadedStatus.LOADED && super.getChildren().size()==0 ;
        }

        // normal property accessor methods:

        public final ObjectProperty<ChildrenLoadedStatus> childrenLoadedStatusProperty() {
            return this.childrenLoadedStatus;
        }

        public final LazyTreeCellLoadingExample.LazyTreeItem.ChildrenLoadedStatus getChildrenLoadedStatus() {
            return this.childrenLoadedStatusProperty().get();
        }

        public final void setChildrenLoadedStatus(
                final LazyTreeCellLoadingExample.LazyTreeItem.ChildrenLoadedStatus childrenLoadedStatus) {
            this.childrenLoadedStatusProperty().set(childrenLoadedStatus);
        }

    }

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

Update
After quite a bit of discussion, I came up with a second solution. This is basically similar to the previous solution in the way it manages the progress bar: there is a TreeItem subclass that exposes a BooleanProperty which is true if and only if the item is currently loading its children. The TreeCell observes this property on the TreeItem it is currently displaying - taking care to register a listener with the treeItemProperty so that the listener for the loadingProperty is always registered with the current item.
The difference is in the way the children are loaded, and - in the case of this solution - unloaded. In the previous solution, child nodes were loaded when first requested, and then retained. In this solution, child nodes are loaded when the node is expanded, and then removed when the node is collapsed. This is handled with a simple listener on the expandedProperty.
The first solution behaves slightly more as expected from a user perspective, in that if you collapse a node which is the head of a subtree, and then expand it again, the expanded state of the subtree is retained. In the second solution, collapsing a node has the effect of collapsing all descendent nodes (because they are actually removed).
The second solution is more robust for memory usage. This is actually unlikely to be an issue outside of some extreme use cases. TreeItem objects are purely model - i.e. they store only data, no UI. Thus they probably use no more than a few hundred bytes of memory each. In order to consume significant amounts of memory, the user would have to navigate through hundreds of thousands of nodes, which would probably take days. (That said, I'm typing this into Google Chrome, which I think I've had running for over a month with at least 8-10 hours' active use per day, so such use cases are certainly not impossible.)
Here's the second solution. One note: I don't make any effort to handle a quick expand and collapse of a node (collapsing while the data are still loading). The TreeItem subclass should really keep track of any current Task (or use a Service) and call cancel() if a task is running and the user collapses the node. I didn't want to confuse the logic more than necessary to demonstrate the basic idea.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javafx.application.Application;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class LazyTreeCellLoadingExample2 extends Application {

    private static final ExecutorService EXEC = Executors.newCachedThreadPool((Runnable r) -> {
        Thread t = new Thread(r);
        t.setDaemon(true);
        return t ;
    });

    @Override
    public void start(Stage primaryStage) {
        TreeView<Integer> tree = new TreeView<>();
        tree.setRoot(new LazyTreeItem(1));

        tree.setCellFactory(tv -> createTreeCell()) ;

        primaryStage.setScene(new Scene(new BorderPane(tree), 450, 600));
        primaryStage.show();
    }

    private TreeCell<Integer> createTreeCell() {

        ProgressBar progressBar = new ProgressBar();
        TreeCell<Integer> cell = new TreeCell<>();

        ChangeListener<Boolean> loadingChangeListener =
                (ObservableValue<? extends Boolean> obs, Boolean wasLoading, Boolean isNowLoading) -> {
                   if (isNowLoading) {
                       cell.setGraphic(progressBar);
                   } else {
                       cell.setGraphic(null);
                   }
                };

        cell.treeItemProperty().addListener(
                (ObservableValue<? extends TreeItem<Integer>> obs,
                        TreeItem<Integer> oldItem,
                        TreeItem<Integer> newItem) -> {

                if (oldItem != null) {
                    LazyTreeItem oldLazyTreeItem = (LazyTreeItem) oldItem ;
                    oldLazyTreeItem.loadingProperty().removeListener(loadingChangeListener);
                }

                if (newItem != null) {
                    LazyTreeItem newLazyTreeItem = (LazyTreeItem) newItem ;
                    newLazyTreeItem.loadingProperty().addListener(loadingChangeListener);

                    if (newLazyTreeItem.isLoading()) {
                        cell.setGraphic(progressBar);
                    } else {
                        cell.setGraphic(null);
                    }
                }
        });

        cell.itemProperty().addListener(
                (ObservableValue<? extends Integer> obs, Integer oldItem, Integer newItem) -> {
                   if (newItem == null) {
                       cell.setText(null);
                       cell.setGraphic(null);
                   } else {
                       cell.setText(newItem.toString());
                   }
                });

        return cell ;
    }

    public static class LazyTreeItem extends TreeItem<Integer> {

        private final BooleanProperty loading = new SimpleBooleanProperty(false);

        private boolean leaf = false ;

        public final BooleanProperty loadingProperty() {
            return this.loading;
        }

        public final boolean isLoading() {
            return this.loadingProperty().get();
        }

        public final void setLoading(final boolean loading) {
            this.loadingProperty().set(loading);
        }

        public LazyTreeItem(Integer value) {
            super(value);

            expandedProperty().addListener((ObservableValue<? extends Boolean>obs,  Boolean wasExpanded,  Boolean isNowExpanded) -> {
                if (isNowExpanded) {
                    loadChildrenLazily();
                } else {
                    clearChildren();
                }
            });
        }

        @Override
        public boolean isLeaf() {
            return leaf ;
        }

        private void loadChildrenLazily() {

            setLoading(true);

            int value = getValue();
            Task<List<TreeItem<Integer>>> loadTask = new Task<List<TreeItem<Integer>>>() {

                @Override
                protected List<TreeItem<Integer>> call() throws Exception {
                    List<TreeItem<Integer>> children = new ArrayList<>();
                    for (int i=0; i<10; i++) {
                        children.add(new LazyTreeItem(value * 10 + i));
                    }
                    Thread.sleep(3000);
                    return children ;
                }

            };

            loadTask.setOnSucceeded(event -> {
                List<TreeItem<Integer>> children = loadTask.getValue();
                leaf = children.size() == 0 ;
                getChildren().setAll(children);
                setLoading(false);
            });

            EXEC.submit(loadTask);
        }

        private void clearChildren() {
            getChildren().clear();
        }
    }

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

The "double listener" in for the cell is because we really need to observe a "property of a property". Specifically, the cell has a treeItem property, and the tree item has a loadingProperty. It's the loading property belonging to the current tree item that we're really interested in. Of course, there are two ways this can change: the tree item changes in the cell, or the loading property changes in the tree item. The EasyBind framework includes API specifically for observing "properties of properties". If you use EasyBind, you can replace the (30 or so lines of) code
ChangeListener<Boolean> loadingChangeListener = ... ;

cell.treeItemProperty().addListener(...);

with
    ObservableValue<Boolean> loading = EasyBind.select(cell.treeItemProperty())
    // ugly cast still here:
            .selectObject(treeItem -> ((LazyTreeItem)treeItem).loadingProperty());

    loading.addListener((obs, wasLoading, isNowLoading) -> {
        if (isNowLoading != null && isNowLoading.booleanValue()) {
            cell.setGraphic(progressBar);
        } else {
            cell.setGraphic(null);
        }
    });

A: Problem SOLVED!
Here is how I solved it...
The first thing that I learned with this question is that a TreeCell is in fact a "moving object": it moves from TreeItem to TreeItem; here, the TreeItem is a ParseTreeItem which has a dedicated property, loadingProperty(), and in the cell's treeItemProperty() I make use of this property to update the graphics.
As @James_D suggested in his code, I use EasyBind; the code is basically a ripoff of his, except for the fact that I don't use the cell's text but only a graphic, which is a HorizontalBox.
In addition I also have to listen to the cell's selectedProperty() since when it is selected, I need to update the info box and the text area:
public final class ParseTreeNodeCell
    extends TreeCell<ParseTreeNode>
{
    private final Text text = new Text();
    private final ProgressBar progressBar = new ProgressBar();
    private final HBox hBox = new HBox(text);

    public ParseTreeNodeCell(final TreeTabDisplay display)
    {
        setEditable(false);

        selectedProperty().addListener(new ChangeListener<Boolean>()
        {
            @SuppressWarnings("AutoUnboxing")
            @Override
            public void changed(
                final ObservableValue<? extends Boolean> observable,
                final Boolean oldValue, final Boolean newValue)
            {
                if (!newValue)
                    return;
                final ParseTreeNode node = getItem();
                if (node != null)
                    display.parseTreeNodeShowEvent(node);
            }
        });

        final ObservableValue<Boolean> loading
            = EasyBind.select(treeItemProperty())
            .selectObject(item -> ((ParseTreeItem) item).loadingProperty());

        loading.addListener(new ChangeListener<Boolean>()
        {
            @Override
            public void changed(
                final ObservableValue<? extends Boolean> observable,
                final Boolean oldValue, final Boolean newValue)
            {
                final ObservableList<Node> children = hBox.getChildren();
                if (newValue == null || !newValue.booleanValue()) {
                    children.remove(progressBar);
                    return;
                }

                if (!children.contains(progressBar))
                    children.add(progressBar);
            }
        });

        itemProperty().addListener(new ChangeListener<ParseTreeNode>()
        {
            @Override
            public void changed(
                final ObservableValue<? extends ParseTreeNode> observable,
                final ParseTreeNode oldValue, final ParseTreeNode newValue)
            {
                if (newValue == null) {
                    setGraphic(null);
                    return;
                }
                text.setText(String.format("%s (%s)",
                    newValue.getRuleInfo().getName(),
                    newValue.isSuccess() ? "SUCCESS" : "FAILURE"));
                setGraphic(hBox);
            }
        });
    }
}

Now, the code of ParseTreeItem which extends TreeItem<ParseTreeNode>, is as such:
public final class ParseTreeItem
    extends TreeItem<ParseTreeNode>
{
    private final BooleanProperty loadingProperty
        = new SimpleBooleanProperty(false);

    private final boolean leaf;

    public ParseTreeItem(final TreeTabDisplay display,
        final ParseTreeNode value)
    {
        super(value);
        leaf = !value.hasChildren();
        expandedProperty().addListener(new ChangeListener<Boolean>()
        {
            @Override
            public void changed(
                final ObservableValue<? extends Boolean> observable,
                final Boolean oldValue, final Boolean newValue)
            {
                if (!newValue) {
                    getChildren().clear();
                    return;
                }
                display.needChildren(ParseTreeItem.this);
            }
        });
    }

    public BooleanProperty loadingProperty()
    {
        return loadingProperty;
    }

    @Override
    public boolean isLeaf()
    {
        return leaf;
    }
}

Again, this is nearly a ripoff, except for the fact that I don't want the item to hold the logic to:

*

*fetch the children,

*updating its own loading property.

The "secret" is in display.needChildren(ParseTreeItem.this); this is what it does:
public void needChildren(final ParseTreeItem parseTreeItem)
{
    currentItem = parseTreeItem;
    presenter.needChildren(currentItem.getValue());
}

And, in turn, the code in presenter does:
public void needChildren(final ParseTreeNode value)
{
    taskRunner.computeOrFail(
        view::waitForChildren,
        () -> getNodeChildren(value.getId()),
        view::setTreeChildren,
        throwable -> mainView.showError("Tree expand error",
            "Unable to extend parse tree node", throwable)
    );
}

And is where the view comes in; it is the view which updates currentItem, since it has direct access to the display and its fields:
@Override
public void waitForChildren()
{
    display.currentItem.loadingProperty().setValue(true);
}

@Override
public void setTreeChildren(final List<ParseTreeNode> children)
{
    final List<ParseTreeItem> items = children.stream()
        .map(node -> new ParseTreeItem(display, node))
        .collect(Collectors.toList());
    display.currentItem.getChildren().setAll(items);
    display.currentItem.loadingProperty().setValue(false);
}

As you can see, when waitingForChildren() and setTreeChildren() update the loadingProperty(); and in turn the ParseTreeNodeCell will then update the graphics accordingly.


text:
Q: Get editText value from alertDialog builder I'm new to android. I need to get editText's value to search something. But when I run the program, error comes as null pointer exception.
"EditText etSearch" isn't getting the text of it.
Please help me.
Thanks.
public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_search) {
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    MainActivity.this);
            // Get the layout inflater
            LayoutInflater inflater = MainActivity.this.getLayoutInflater();

            // Inflate and set the layout for the dialog
            // Pass null as the parent view because its going in the dialog
            // layout
            builder.setView(inflater.inflate(R.layout.dialog_save, null))

                    // Add action buttons
                    .setPositiveButton("Search",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    final EditText etSearch = (EditText) findViewById(R.id.etSearchText);
                                    mSearchText = etSearch.getText().toString();

                                }
                            })
                    .setNegativeButton("Cancel",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    dialog.cancel();
                                }
                            });
            // return builder.create();
            AlertDialog alertDialog = builder.create();
            alertDialog.show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

A: For find view from Diloag then you have to give refference of that view of Dialog.
 LayoutInflater inflater = MainActivity.this.getLayoutInflater();
            View mView = inflater.inflate(R.layout.dialog_save, null);
            final EditText etSearch = (EditText)mView.findViewById(R.id.etSearchText);
            builder.setView(mView)

Full Code :
public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_search) {
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    MainActivity.this);
            // Get the layout inflater
            LayoutInflater inflater = MainActivity.this.getLayoutInflater();
            View mView = inflater.inflate(R.layout.dialog_save, null);
            final EditText etSearch = (EditText)mView.findViewById(R.id.etSearchText);
            builder.setView(mView)

                    // Add action buttons
                    .setPositiveButton("Search",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                        int id) {

                                    mSearchText = etSearch.getText().toString();

                                }
                            })
                    .setNegativeButton("Cancel",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    dialog.cancel();
                                }
                            });
            // return builder.create();
            AlertDialog alertDialog = builder.create();
            alertDialog.show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

A: Replace this code:
final EditText etSearch = (EditText) findViewById(R.id.etSearchText);

with
final EditText etSearch = (EditText)dialog. findViewById(R.id.etSearchText);

A: View v=   inflater.inflate(R.layout.dialog_save, null);
    builder.setView(v)
                // Add action buttons
                .setPositiveButton("Search",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                    int id) {
                                final EditText etSearch = (EditText) v.findViewById(R.id.etSearchText);
                                mSearchText = etSearch.getText().toString();

                            }
                        })
                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int id) {
                                dialog.cancel();
                            }
                        });


text:
Q: Undead form is still generating events I have a form that the user can open from another form:
  private void btnEditTemplate_Click(object sender, EventArgs e)
  {
     using (frmReport EditReport = new frmReport())
     {
        EditReport.ShowDialog();
        EditReport.Close();
        EditReport.Dispose();
     }
  }

As you can see, I've called close, dispose, and even placed the form in a using block. The form has some controls bound to static BindingLists that are maintained outside the form, and changing those lists triggers events.
Despite everything, if the user later opens another copy of this form, I am finding that events for the original form are still being run, even though it is closed and disposed.
What to do I need to do to KILL this thing? Stakes through the heart?
Update: as was indicated in the comments, the problem was the static BindingList objects were maintaining databindings to the old form. For me the solution was to get rid of the BindingList objects as I wasn't making any (intentional) use of their databinding properties anyway.

A: Ignoring the event handlers and data bindings at the moment, your code is little bit overkill at the moment. You could get away just this:
using (frmReport EditReport = new frmReport())
{
    EditReport.ShowDialog();
}

As you are showing it as a dialog by the time it got to your .Close() call the form was closed anyway. And the using statement calls .Dispose() for you.
Now, when you dispose a form you are basically removing the form from its parent, if you have one, disposing of all child controls, and freeing up the Windows handle.
However, it does not know how to detach your event handlers and it does not know how to remove data bindings. Since these things are references into your form the garbage collector will count the form as a live object and won't try to collect it.
So if you have any handlers within your form listening to external events and they fire then your form will try to handle them.
You need to make sure that when your form closes that you detach all handlers and unbind all data bindings.
Opening the form a second time has no direct relationship to the first, but it is likely that it caused your data source to start raising events or updating values and that's what tripped your original form.

A: In general, I find it good practice to write event subscription code to be tolerant of being called after you unsubscribe from the event.  This can happen in a variety of ways.
I don't know what experimentation you did, but for example, if you wrote this:
private void btnEditTemplate_Click(object sender, EventArgs e)
{
  using (frmReport EditReport = new frmReport())
  {
    EditReport.ShowDialog();
    EditReport.Close();
    EditReport.Dispose();
  }
  using (frmReport EditReport2 = new frmReport())
  {
    EditReport2.ShowDialog();
    EditReport2.Close();
    EditReport2.Dispose();
  }
}

then there may still be events in the message queue for the first dialog that will not get processed until you enter the modal message loop in the ShowDialog() call on the second instance.
Even with the Dispose() you have, the Garbage Collector will not reclaim the first object, because of the references to it in these subscriptions in the message queue. If you write your event subscriptions to do nothing if the object they are delivered to is already disposed, then there will be no harm done.  what to check varies depending on what base class you are using.  Worst case, you implement your own IsDisposed or IsClosed instance variable.


text:
Q: Can I share my internet connection and redirect clients to my web server? I often share my internet connection with other Macs and devices and want to know if I can redirect client's web requests to my local web server.
Is it as simple as having them use my client's IP address or do I need to set up a proxy or otherwise configure things on my Mac or my client's devices?

A: If you really want to configure your network in such a way,
here are a few bricks I'd advise to start with:

*

*Install Squid version 3 and configure it in transparent
mode. You may use MacPorts to build, configure and install it.
With MacPorts you would do it with: port install squid3.

*Install Apache. With the same Macports, you would have to
do it with: port install apache2.
You will find many documents on the web to help to build this, but I didn't find any one complete and good enough to recommand it.


text:
Q: Some web sites hang on TLS handshake I just changed from a Centurylink-provided wireless access point to using a Linux server to connect to Centurylink's network.
Some web sites seem to hang on TLS handshakes, notably kahoot.it and duckduckgo.com. Firefox on Linux, Lynx on Linux, Chrome on Windows and curl all hang. This curl command is the most info I can get:
135 % curl -v https://duckduckgo.com
*   Trying 40.89.244.232:443...
* Connected to duckduckgo.com (40.89.244.232) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*  CAfile: /etc/ssl/certs/ca-certificates.crt
*  CApath: none
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* OpenSSL SSL_connect: Connection reset by peer in connection to duckduckgo.com:443
* Closing connection 0
curl: (35) OpenSSL SSL_connect: Connection reset by peer in connection to duckduckgo.com:443

Oddly, openssl s_client kahoot.it:443 works.
https://kahoot.com works, https://google.com works, most other web sites work.
What on earth is going on here?
Here's some server details: Arch linux, 5.9.16.a-1-hardened kernel.
Because it's Centurylink, I had to set the VLAN ID to 201:
ip link add link eno3 name eno3.201 type vlan id 201.
I've got the server using PPPoE as per the Arch linux wiki on PPPoE.
I have IPv4 forwarding turned on, and IPv4 NAT enabled, here's an excerpt from the systemd unit file for getting the networking going:
ExecStart=/usr/bin/modprobe iptable_nat
ExecStart=/usr/bin/sysctl net.ipv4.ip_forward=1
ExecStart=/usr/bin/iptables -t nat -A POSTROUTING -s 10.0.0.0/24 -j MASQUERADE
ExecStart=/usr/bin/iptables -A FORWARD -o eno3 -i eno1 -s 10.0.0.0/24 -m conntrack --ctstate NEW -j ACCEPT
ExecStart=/usr/bin/iptables -t nat -A POSTROUTING -s 10.0.10.0/24 -j MASQUERADE
ExecStart=/usr/bin/iptables -A FORWARD -o eno3 -i eno2 -s 10.0.10.0/24 -m conntrack --ctstate NEW -j ACCEPT
ExecStart=/usr/bin/iptables -A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

The server has network devices eno1, eno2, eno3, eno4. Nothing is connected to eno4 eno3 is the device on which I have pppd doing its work:
# ip -br l
lo               UNKNOWN        00:00:00:00:00:00 <LOOPBACK,UP,LOWER_UP>
eno1             UP             44:a8:42:2d:c2:55 <BROADCAST,MULTICAST,UP,LOWER_UP>
eno2             UP             44:a8:42:2d:c2:56 <BROADCAST,MULTICAST,UP,LOWER_UP>
eno3             UP             44:a8:42:2d:c2:57 <BROADCAST,MULTICAST,UP,LOWER_UP>
eno4             DOWN           44:a8:42:2d:c2:58 <BROADCAST,MULTICAST>
eno3.201@eno3    UP             44:a8:42:2d:c2:57 <BROADCAST,MULTICAST,UP,LOWER_UP>
ppp0             UNKNOWN        <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP>
[root@monarch ~]# ip -br a
lo               UNKNOWN        127.0.0.1/8 ::1/128
eno1             UP             10.0.0.1/24 fe80::46a8:42ff:fe2d:c255/64
eno2             UP             10.0.10.1/24 fe80::46a8:42ff:fe2d:c256/64
eno3             UP             fe80::46a8:42ff:fe2d:c257/64
eno4             DOWN
eno3.201@eno3    UP             fe80::46a8:42ff:fe2d:c257/64
ppp0             UNKNOWN        71.33.205.38 peer 207.225.112.2/32

A: I found an idea in the Arch Linux wiki, entry for ppp:

The MTU under pppoe is 1492 bytes. Most sites use an MTU of 1500. So
your connection sends an ICMP 3:4 (fragmentation needed) packet,
asking for a smaller MTU, but some sites have their firewall blocking
that.

The command to implement PMTU clamping in iptables is:
iptables -I FORWARD -o ppp0 -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu

This worked for my setup, where pppd creates the ppp0 network device.


text: Q: Correlation between signalR and RTVS? I am new to asp.net signal R and RTVS. My question is, are by any chance signal R and RTVS related in any way or are they totally different platforms used for different needs?


text:
Q: Derivatives of Approximate Matrix inverses I have a question concerning the derivatives of approximate matrix inverses. I have a system, $$Ax = b$$ which I solve approximately (and with an iterative method) with:   $$\Delta x = x - \tilde{A}^{-1}b$$   I would like to take the derivative of this process, i.e. find $$\frac{d\Delta x}{dD} = \frac{dx}{dD} - \frac{d\tilde{A}^{-1}}{dD}b - \tilde{A}^{-1}\frac{db}{dD}$$ I know that if I had an ideal inverse, my expression would be without tildes as I'd have the exact result: $$\frac{d\Delta x}{dD} = \frac{dx}{dD} - {A}^{-1}\frac{dA}{dD}{A}^{-1}b - \tilde{A}^{-1}\frac{db}{dD}$$ But for this, I cannot start with the typical assumption that $$AA^{-1} = I$$ and instead have $$A\tilde{A}^{-1} = C \neq I$$ Does anyone have any ideas for resources or techniques for such problems?
Thank you.


text:
Q: Can't get piping to work in my simple linux shell Here is the code and I am not sure what makes it not function as expected. When i type in "ls | wc" it give me this error:
> ls | wc
`v> wc: 'standard input': Bad file descriptor
      0       0       0
      0       0       0

Here is the code for the program... I think it has something to do woth how I am using the pipes?
void pipeTest2(Command *cmd)
{

struct c *currentProgram = cmd->pgm;

  int pipefd[2];
  pipe(pipefd); //insert error correction, if pipe fails,return

 // printf(cmd->pgm->pgmlist[i]);
 // printf(cmd->pgm->pgmlist);

  while (currentProgram != NULL)
  {

    //if fork is 0, go back to parent process.
    if (!fork())
    {
      dup2(pipefd[1], cmd->rstdout); // remap output back to parent
      if (execvp(cmd->pgm->pgmlist[0], cmd->pgm->pgmlist) < 0)
      {
        printf("Failed to execute child process.");
      }

    }

    // remap output from previous child to input
    dup2(pipefd[0], cmd->rstdin);
    close(pipefd[1]);

    currentProgram = currentProgram->next;
    printf(currentProgram);
  }
  return;

}
´´´


text:
Q: When is there an UB because the best overload match was not found by ADL at the point of instantiation? When a function body is instantiated, dependent function call overload resolution should find the best match in associated namespace through ADL, otherwise the behavior is undefined, [temp.dep.candidate]§1

If the call would be ill-formed or would find a better match had the lookup within the associated namespaces considered all the function declarations with external linkage introduced in those namespaces in all translation units, not just considering those declarations found in the template definition and template instantiation contexts, then the program has undefined behavior.

For exemple:
struct A {
    friend void f(A a){};
};

struct B : A {};

template <class T>
void g (T a) {
    f(a);
}

void h(B b){
    g(b);//undefined behavior (UB)
}
 //TU2.cpp
 //...
void f(B){}

I have 2 doubts about which functions could be one of all the function declarations with external linkage introduced in those namespaces
Question 1
Does inline friend function considered to be introduced in the enclosing namespace?
Exemple:
struct A {
    friend void f(A a){};
};

struct B : A {};

template <class T>
void g (T a) {
    f(a);
}

void h(B b){
    g(b);//undefined behavior ??
}
//TU2.cpp
//....
struct C {
   operator B();
   friend void f(B){}
   };

Question 2
Could function template specialization also trigger this undefined behavior? (Potentialy instantiated or instantiated function template specialization)
Exemple:
struct A {
    friend void f(A a){};
};

struct B : A {};

template <class T>
void g (T a) {
    f(a);
}

void h(B b){
    g(b);//undefined behavior ??
}
//TU2.cpp
//...
template <class T> void f(T){}

// optionaly also with:
// template void f(B);


text:
Q: Delete all but numerical values in a column(s) using Pandas I have a dataframe, df
        Size                  Total           ID

        110 TB                200 TB          A
        110 G                 300 G           B
        500 A                 700 A           C

Desired output:
        Size                  Total         ID

        110                   200           A
        110                   300           B
        500                   700           C

What I am doing:
  df[['Size','Total']] = df[['Size','Total']].apply(lambda x:
  x.str.strip(' TB', 'G'))

This specifies the exact value, but how would I remove any value that is not a number value? (Just in case I do not know what the specific value is)
Any suggestion is appreciated

A: Could you please try following, I have written this on mobile couldn't test it should work though.
import pandas as pd
df.replace(to_replace=r'[^0-9]+', value='', regex=True)

Simply substituting everything apart from digits with null.

A: Just an extra information, I did like this and got the opposite :D
import pandas as pd
df.replace(to_replace=r'[^a-zA-Z#]', value='', regex=True)

    Size    Total
  0   TB    TB
  1   G      G
  2   A      A

Since you changed your question, I did like this, maybe someone could have a better answer.
df['Size'] = df['Size'].str.replace("[^[^0-9]+", " ")
df['Total'] = df['Total'].str.replace("[^[^0-9]+", " ")
df

output:

   Size Total   ID
0   110  200    A
1   100  300    B
2   500  700    C


text:
Q: How to match only whole words with Aho corasick? Our ruby on rails app uses aho corasick gem to find if any given text contains any of the prelisted bad words (these are picked from a static config when loading the app).
But, using this is giving a few false positives. For example if my bad word from config is "abc", then the text containing "habcd" is also being flagged, which is not the intent.
So, I tried changing the config word from "abc" to " abc " (space added before and after the word).
However, this has another drawback that a text like "abc is xyz" will not be flagged, where as it is supposed to be. So, i have to add another 2 words - "abc " and " abc" to my config as well, similarly i would need to add "-abc", "abc-", ":abc", etc. to my config, making the config pretty big, as there are many such words, apart from abc.
So, I was thinking if there is some kind of regular expression that I can enter in my config like [",-" "]abc[",-" "] so that all the above cases would be covered and no false positives will be found.
We use gem 'aho_corasick', '0.1.0' , with ruby - 1.9.3 and rails - 3.2.8
Any help is greatly appreciated. Thanks in advance!! :)

A: The simplest way to solve this problem is to use the standard implementation to get all the matches, then remove matches which don't have a word delimiter before and after the first and last character. In the average case, there won't be a significant performance hit because you will have few matches.


text:
Q: Linux page cache / buffer cache - unified or not As far as i've read discussion on LKML, around 2010, thus ~ 2.2.x kernel there was supposed to be a great unification of pagecache and buffer cache.

*

*Did it happen ? Do we have SINGLE memory space referenced by both?

I've browsed through filemap.c and buffer.c and unfortunately had not found ANY patches that would actually merge two buffers. Nothing actually indicating that any unification after 2010 took place. Perhaps i've missed something.

*

*LKML is very usernotfriendly - anyone knows site simmilar to lkml.indiana.edu/hypermail/linux/kernel/ that has clear "tree like" overview of whole some-thread in LKML and does not loose subthreads that emerge to another branch, and first of all allow flat view of multiple messages (without tiring clicking)?

*pagecache vs buffer. Lets imagine that they are separated. Can someone explain what is main reason we need to have two of them, instead of for example focusing on one?
Say - buffer caching, that caches every IO, FIFO or even takes most frequently used sectors into consideration and caches them separately from queue.
Or quite opposite, just page cache, leave write ahead, read 1+X read ahead sectors from slow IO into memory, decide what stays according to free memory and some other fancy algorithm?

*Lets imagine that buffer cache and page cache are unified. How this unification actually helps(still leaving two different source files), given that buffer cache stores pointers to memory cached pages? Eventually both serve same purpose - store X data in memory. Only obvious difference would be -buffer-buffering with read ahead, several "predicted" neraby sectors, and -cache- store in memory frequently demanded io sectors.


text:
Q: I am not able to connect tomcat with eclipse My eclipse used to work fine but now I am no longer the administrator of my computer(I no longer have administrator priveledges) and i see that my already installed and working eclipse is now showing errors in my jsp files of the application which it didn't used to show before..
also I am not able to connect to tomcat server which seperately can be started normally but not inside eclipse.....
Is this something to do with my not being administrator anymore of is it something else....
would highly appreciate the help.....
I have now been able to run my tomcat server without admin previledge but problem of many files showing error still persists.........
the below written jsp code is showing error in all the files....:
<%
pageContext.getRequest().setCharacterEncoding("UTF-8");
String label =  pageContext.getRequest().getParameter("rswitb1");
if(label==null)label="";
else label = label.replaceAll("<", "<").replaceAll(">", ">");
%>
I am not able to get what the problem ....
if anyone could help...

A: The connection to the external tomcat should be using only TCP/IP port 8080, there is no reason why a non-admin user should not be able to do that.
It's possible that your tomcat password has changed (or hasn't been set up at all)
There is a troubleshooting section at the eclipse wiki (if you are using WTP, that is)

A: First,check out the tomcat server is on:    "netstat -an"  to
find that whether the port8080 is used(if you didn't assign another server port.).

A: check out  whether the server is on(netstat -an).
Maybe 8080 is used by tomcat.
You'd better reinstall tomcat as non administrator.


text:
Q: bash: environment variable lost after su root? I defined some aliases in /etc/bash.bashrc.
When I login using herbert, I can use these aliases.
But after I su root, these aliases can't be used anymore.
This is very strange because configs in /etc/bash.bashrc should be global and can be used by all users.
Everything worked fine before but went strange these days. What I can remember is that I upgraded my Bash, from 4.2.25 to 4.3.30, but I am not sure whether this version change is the reason.
Is this due to Bash versions?

A: When you do su root (or just su), the user ID is changed to that of the superuser but the default environment isn't loaded. Instead, try su -.
Paraphrasing the manual (man su), the option -, -l or --login provides a similar environment to what you would get if you logged in directly as that user. This means that things such as profiles will be loaded.

A: If you built bash 4.3.30 yourself, you probably forgot to configure it the same way your OS configured it. Many Linux distributions modify bash to source a file like /etc/bash.bashrc in addition to ~/.bashrc for interactive shells. Vanilla bash only sources ~/.bashrc.
The configuration is done by modifying config-top.h if I remember correctly.
Also see Dot Files.


text:
Q: Subtracting time from current time I have 2 strings, that have the minute and hour that a function needs to occur at.
I want to check, if the minute and hour which are specified in string format, and from my database are within 5 minutes of the current time, call this function.
My original thought was something like:
(today.minute is the current minute)
today.minute:
minute = "55"
hour = "14"
var today = new Date();
var time = today.getMinutes(), today.getHours()

if (today.getMinutes() - 5 == minute) {
   myFunc()
}

But that isn't going to work, because I need the hour and minute - 5 minutes... how can I do this?

A: Is this what you are looking for?

let minute = "55"
let hour = "14"
let today = new Date();
//var time = today.getMinutes(), today.getHours()

if (Math.abs(today.getMinutes() - Number(minute)) <= 5) {
   myFunc()
}

function myFunc() {
  console.log('myFunc called', today.getMinutes());
 }


text: Q: AceFEM MacOS not responding I just upgraded to v7.114 of AceFEM running on MacOS 10.15.5 and Mathematica 12.0.0.0. I was running v7.101 without a problem. AceGEN seems to work but all AceFEM code starts but does nothing. The notebook states running but nothing is happening. Tried multiple notebooks - same problem.


text:
Q: Get day name based on a given date I want to get the day name based on the date selected from the fields. I have the code as below:
from datetime import datetime, date
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
import calendar

class HrPublicHolidayHolidays(models.Model):
    _name = 'hr.public.holiday.holidays'
    _description = 'Public Holidays Dates'

    name = fields.Char('Holiday Name', required=True)
    date = fields.Date('Holiday Date', required=True)
    date_day = fields.Char('Day')
    year_id = fields.Many2one('hr.public.holiday', 'Calendar Year', required=True)
    variable = fields.Boolean('Date may change')

    @api.onchange('date')
    def _get_day_of_date(self):
        for r in self:
            selected = fields.Datetime.from_string(r.date)
            r.date_day = calendar.day_name[selected.weekday()]

Then when I run the code, when I click on the add an item
After I clicked the button it shows me the error result:
But if I try to select the date, it will show the day of the date that I've selected like:
So basically the code will run, but the error just keeps on showing and I have no idea why.

A: First, get the current date by default, e.g.:
date = fields.Date(string='Date', default=fields.Date.context_today, required=True)

after that write this bellow function to get the name of the day
@api.multi
@api.depends('date')
def _get_day(self):
    self.day = self.date and (datetime.strptime(self.date, '%Y-%m-%d').date()).strftime('%A') or ''


text:
Q: Вывод текста из базы данных mysql php Я пытаюсь вывести из базы данных текст, который там есть, но почему то выводится пустая переменная.

See here:

            <?php
                $link = mysqli_connect("localhost", "root", "root", "test");

                if($link === false){
                    die("ERROR: Could not connect. " . mysqli_connect_error());
                }

                $result = mysqli_query("SELECT 'tex' FROM 'example' WHERE id = '1'");
                echo "
 $result
";

                mysqli_close($link);
            ?>

Ошибок в консоли никаких нет. Страница тоже появляется.

Железнодорожная станция

A: У вас ошибка в самом запросе.

*

*имя поля и таблицы пишутся без кавычек

*необходимо выполнить mysqli_fetch_array - выбирает одну строку из результирующего набора и помещает в массив

Попробуйте отправить запрос вот так:
$query = mysqli_query($link, "SELECT tex FROM example WHERE id = '1'");
$deskRow = mysqli_fetch_array($query);
$result = $deskRow['tex'];
echo $result;


text:
Q: Android NDK: Why is AAssetManager_open returning NULL I have some code:
AAsset* pAsset = AAssetManager_open(pAssetManager, "asset_test.txt", AASSET_MODE_STREAMING);
DebugPrint(pAsset?"pAsset not NULL\n":"pAsset NULL");
if (pAsset)
{
    char buf[1024];
    AAsset_read(pAsset, buf, sizeof(buf));
    DebugPrint(buf);
    AAsset_close(pAsset);
}

This code always prints "pAsset NULL" in logcat.
I put the asset_test.txt file in my assets directory, and I looked in the .apk to make sure it exists by renaming the .apk to .zip and opening it with 7zip.
I have some more code:
AAssetDir* pAssetDir = AAssetManager_openDir(pAssetManager, sDirectory.c_str());

if (!pAssetDir)
{
    DebugPrint("pAssetDir NULL\n");
    return;
}

const char* pszDir;
while ((pszDir = AAssetDir_getNextFileName(pAssetDir)) != NULL)
{
    DebugPrint(pszDir);
}

AAssetDir_close(pAssetDir);

This code prints nothing. In other words, no files are ever found in the assets directory, regardless of what paths I pass into it.
Note: DebugPrint is just a prettier looking wrapper around __android_log_print().

A: I passed the Activity into AAssetManager_fromJava(), while I should have passed the AssetManager in. If you pass the wrong class into AAssetManager_fromJava() it will fail without printing anything to logcat.
How to get the asset manager with JNI:
    JNIEnv* env = (JNIEnv*)SDL_AndroidGetJNIEnv();

    jobject activity = (jobject)SDL_AndroidGetActivity();

    jclass activity_class = env->GetObjectClass(activity);

    jmethodID activity_class_getAssets = env->GetMethodID(activity_class, "getAssets", "()Landroid/content/res/AssetManager;");
    jobject asset_manager = env->CallObjectMethod(activity, activity_class_getAssets); // activity.getAssets();
    global_asset_manager = env->NewGlobalRef(asset_manager);

    pAssetManager = AAssetManager_fromJava(env, global_asset_manager);

Stash that asset manager pointer somewhere and use it for all your AAssetManager_*() functions from now on.

A: In my case AAssetDir_getNextFileName call returned NULL because I expected list of directories.
But AAssetDir_getNextFileName does not iterate over directories.
See https://github.com/android/ndk-samples/issues/603 for more details


text:
Q: What score should i put in boost field of elasticsearch In my doc, I have a field called Tag and SuperTag. Whenever a Tag matches it will boost some score, but if a match on SuperTag it will boost significantly to make it 1st choice. In your opinion, what value should I put in boost field for Tag and SuperTag? Thanks.

A: That's quite difficult to be answered, It depends so much in the data that both field contains and the analyzers that they have.
Obviously if the data is going to be pretty much the same for both I would set a boost in supertag field to 2.0.
In case they don't hold the same data we can imagine scenarios like this:
{tag: 'tagnice tagnice tagnice'}

{supertag: 'tagnice'}

even with the boosted supertag, tag could be more relevant just because tf-idf gives it bigger score.
To solve that for example, an analyzer setted to both with filter unique will help.
So as said, it depends so much in the data and how you store it in lucene. At first sight, without knowing that much, doubling the boost would work.


text:
Q: Does the dihedral group $D_{12}$ have a subgroup of order $4$? Let the dihedral group $D_{12}=\{xy\mid x^6=y^2=1,xy=yx^{-1}=yx^5\}$
Order 2 subgroups are: $\{1, x^3\}$, $\{1, y\}$, $\{1, xy\}$, $\{1, x^2 y\}$,$\{1, x^3 y\}$, $\{1, x^4 y\}$,$\{1, x^5y\}$.
Order 3 subgroups are: $\{1, x, x^5\}$, $\{1, x^2, x^4\}$.
Order 6 subgroups are: $\{1, x, x^2, x^3, x^4, x^5\}$.
Does $D_{12}$ have a subgroup of order 4?

A: Yes. $\{1,x^3,y,x^3y\}$, i.e. the group generated by a reflection and a rotation by 180 degrees.

A: $D_{12} \cong S_3 \times C_2$. Hence $C_2 \times C_2$, the Klein $4$-group, is a subgroup of order $4$.


text:
Q: How does node.js know where I placed the script? I've tried the most recepies for making a "hello world" example in node.js to work. I have tried both on mac and now windows. With no luck.

*

*I install the node.msi

*run cmd.exe

*I type: node in command shell, then enter.

*A new line appear with > sign , so now I assume I'm in "node mode"

*I type : node test.js,
the content in test.js is console.log.("hello"), then I press enter

*three dots "..." appear in the output.

In similar tutorials the expected output is a string "hello", I just get ... And I dont know what ... signifies. Does it imply a server is running?
I run cmd.exe as administrator. The ... output is similar when I tested on a mac btw.
I also do not understand how I just can reference the js script without a full path. How does node know where i placed the script?

A: There are two ways to use node. You can use it as a REPL like you discovered by simply typing "node" into the command line and then you can issue commands in a linear format. However, the most common way to run node, and the way that you are missing, is to run a file containing your javascript directly from the command line.
So, from a clean command line without entering the Node REPL, simply type "node test.js" and you will have the expected "Hello World" output. Node looks for the script in the current directory. You will need to provide a relative or absolute path if the file resides elsewhere. Think of node as being no different then running any standard Unix/Linux command like "cp" or "ls"
Hope that helps!

A: Just adding one or two things to what was said before.
A moment ago I was stuck with the same problem (getting started with node.js in Windows 7, I was trying to open files and all I've seen were three dots - "...") and I've discovered that you can easily load scripts in node REPL by simply writing:
.load yourFileName.js
in node terminal REPL.
When the js script that I wanted to load was not in default node folder, I had to add relative path to it. So if file is in folder node/node_modules/example.js on your computer you have to write:
.load node_modules/example.js

I've discovered that by simply typing .help in node.
This just supplements the answer above which is otherwise perfectly valid.


text:
Q: Cache Control Working Differently for Different Browsers? Serving a bunch of images.
I set Cache-Control: max-age:3000 and specifiy ETag in HTTP my response headers.
When the client requests for the same file, I respond with 304 because they are just image files and will be the same.
Perhaps I misunderstood caching, but:

*

*Isn't the client only supposed to check for new file after the
max-age period is complete ?

*Shouldn't the client have cached the image and display it from cache when it receives 304 from server ?

In Firefox it's doing neither. In Chome, it requests for the file, before the max-age, but when it receives 304 response, it displays the image from cache.
Server is a node server. I can share the relevant code, if you think it would help answer better. Although, at this point I am looking for pointers/hints as to what might have gone wrong.
I m doing something wrong, but can't seem to figure out what.

A: You've got the syntax wrong; it's "max-age=3000"

A: If you are using HTTPS and have an old version of Firefox the problem could be caused by the lack of Cache-Control: public in your response headers. However, this was fixed a few years ago:
https://bugzilla.mozilla.org/show_bug.cgi?id=531801
The Cache-Control: no-cache in the request headers indicates a forced refresh in Firefox (e.g. using Ctrl+F5 on Windows). Are you forcing a reload of the page or just revisiting the page in a fresh instance of Firefox?
You can check the state of the image in the Firefox cache by going to 'about:cache' or using a tool like HttpWatch.


text:
Q: Display JSON object using DataTables I'm trying to display JSON results using DataTables, however I get blank table in the end. When I check browser console logs, I can see array of objects is being passed to display function but after that, nothing happens.
HTML Part:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap 101 Template</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

        <form>

              Search For Food Label

                <input class="form-control" type="search" id="foodLabel">

                    <button class="btn btn-default" type="submit" id="submit" onclick="getFormData(); return false;">Submit</button>

        </form>

                Name

JS Part:
function getFormData(){
    var foodLabel=document.getElementById('foodLabel').value;
    document.getElementById('foodLabel').value = "";
    var searchURL = buildSearchURL(foodLabel);
    console.log(searchURL);

    $.getJSON(searchURL, function(data){
        //console.log(data);
        //console.log(data.list.item);
        display(data.list.item);
    });

}

function buildSearchURL(label){
    var searchURL = "http://api.nal.usda.gov/ndb/search/?format=json&q=" + label + "&sort=n&max=25&offset=0&api_key=DEMO_KEY";
    return searchURL;
}

function display(data){
    console.log(data);
    $(document).ready(function() {
        $('#example').DataTable( {
            "json": data,
            "columns": [
                {"item": "name"}
            ]
        } );
    } );
}

It must be something completely obvious that I'm missing here.
I managed to figure this one out, apparently, Datatables library makes a call on it's, so I changed my display function:
function display(searchURL){
    //console.log(data);
    $(document).ready(function() {
        $('#example').DataTable( {
            ajax: {
                url: searchURL,
                dataSrc: 'list.item'
            },
            columns: [
                {data: "name"}
            ]
        } );
    } );
}

A: You can not access the variable searchURL in display function, try this:
function display(searchURL){
    //console.log(data);
    $(document).ready(function() {
        $('#example').DataTable( {
            ajax: {
                 url:buildSearchURL(document.getElementById('foodLabel').value),
                dataSrc: 'list.item'
            },
            columns: [
                {data: "name"}
            ]
        } );
    } );
}


text:
Q: Google Earth Engine: Sampling through image collection I am trying to get samples from each image in an image collection and merge them into a single feature collection. So, I wrote the following code (https://code.earthengine.google.com/6797070d93452804e9e0003233039ad8), but It keeps returning the sample from the first image and avoiding the rest.
Do you have any suggestions?

A: I used flatten() to merge the features, otherwise, they weren't showing up:
https://code.earthengine.google.com/1198f828bf885142985d41ad19f3b0c3


text:
Q: Infinite Loop Newton Raphson Very new matlab user here. The code you see below works great for solving EQUATION 2 but when I switch to EQUATION 1 matlab becomes "busy" and nothing seems to work.
ctrl+c, ctrl+d, ctrl+ dont seem to work but I would like to solve the underlying problem anyway
function [x1, relErr] = NewtonRaphson(x0, TOL, MAX)

    x = sym('x');
    f(x) = x*exp(-x); %EQUATION 1
    %f(x) = x^2-6 %EQUATION 2
    df = diff(f);
    relErr = 1:MAX;

    for i = 1:MAX,

       x1 = double(x0 - f(x0) / df(x0));

       % Compute relative approximated error
       relErr(i) = abs(x1-x0)/abs(x1);

       if( abs(x0-x1) < TOL )
           char(x1);
           fprintf('Newton: Solution %0.5f in %d iterations\n',x1,i);
           relErr = relErr(1:i);
           plot(relErr);
           lambda = abs(x1-6)/((abs(x0-6))^2);
           char(lambda);
           fprintf('Newton: Lamda = %0.5f\n',lambda);
           return;
       end
       x0 = x1   ;
    end

    display('Method failed, hit max iterations');

end

A: This is a classic kind of problem for teaching numerical analysis. Have a look at the plot of this function x*exp(-x) (via FooPlot).
You can see there is a zero to find at x=0 (and this is obvious by inspection). But the function also decays out towards positive infinity.
Thus, the Newton-Raphson algorithm can get stuck trying to walk its way out to the zero that lives far out at infinity. This problem is mentioned in the Wikipedia article on this method.
You can try different initial conditions (in this case, things to the left of x=0 should work). You can also try an approach called successive over-relaxation, which basically means you choose a fraction between 0 and 1, call it w and you set x0 = w*x1 + (1-w)*x0 at the end of your loop, shading yourself to stay a little close to the point you're already at instead of fully jumping to the calculated x1.

A: The reason you get an infinite loop is that Newton-Raphson for the function
f(x) = x * exp(-x)

doesn't converge for initial guesses greater than 1.
To see why not, look at the following chart, where the blue curve is x * exp(-x), the dotted line is at x = 1 and the red lines show successive Newton-Raphson iterations, starting at x = 3.

You can see that each iteration moves further away from the root at x = 0 and towards the "fake root" at x = +infinity as described in EMS's answer.

A: To elaborate on the answer of EMS:
For f(x)=x*exp(-x) one gets f'(x)=(1-x)*exp(-x), so that the Newton iteration reads as
x[n+1]=N(x[n])=x[n]-x[n]/(1-x[n])=-x[n]**2/(1-x[n])

but also equally as
x[n+1]=N(x[n])=x[n]+x[n]/(x[n]-1)=x[n]+1+1/(x[n]-1)

From the first form you see the quadratic convergence towards x=0 for small values of x, say |x|<0.5.
But from the second form you see that for x[n]>1 the next value will be bigger, and the increment will always be larger than 1, so you do not even get some kind of pseudo-convergence.

A: Try:
relErr(i) = abs(x1-x0)/abs(x0);

so you compare relative to previous value as opposed to current value. The other pitfall with NR method is near when df=0 the steps become too large. I suggest you bound the solution and do not allow the steps to go outside the bounds.


text:
Q: Logical Volume Partitions I am trying to incorporate Logical Volumes into the paritioning scheme for the VM I am creating, in Red Hat Enterprise Linux 6.1.  I am booting from an ISO Image and I have a Kickstart Script that runs the installation.  The script references a Hard Drive Configuration file that has the following outlined in it:
# Partitioning scheme for 60 GB HD

# Partition clearing information
clearpart --all --initlabel
# Clear the Master Boot Record
zerombr
# Disk partitioning information
part /boot --fstype="ext4" --size=256
part swap --fstype="swap" --size=16384
part /PV --fstype="ext4" – size=1 --grow --encrypted --passphrase=password
volgroup sysvg PV
logvol / --vgname=sysvg --size=5120 --name=root
logvol /tmp --vgname=sysvg --size=2048 --name=tmp
logvol /usr --vgname=sysvg --size=4096 --name=usr
logvol /home --vgname=sysvg --size=20480 --name=home
logvol /opt --vgname=sysvg --size=5120 --name=opt
logvol /var --vgname=sysvg --size=5120 --name=var
logvol /var/log --vgname=sysvg --size=10240 --name=log
logvol /var/log/audit --vgname=sysvg --size=5120 --name=audit

The kickstart.cfg file has the following information:
    #platform=x86, AMD64, or Intel EM64T
#version=DEVEL
# Firewall configuration
firewall --enabled
# Install OS instead of upgrade
install
# Use CDROM installation media
cdrom
# Root password
rootpw --iscrypted $1$gkOgiLQh$ARiChNQJU0Goj6uQbkQhZ/
# System authorization information
auth  --useshadow  --passalgo=sha512
# Use text mode install
text
# System keyboard
keyboard us
# System language
lang en_US
# SELinux configuration
selinux --disabled
# Do not configure the X Window System
skipx
# Installation logging level
logging --level=info
# Reboot after installation
reboot --eject
# System timezone
timezone  America/New_York
# System bootloader configuration
bootloader --location=mbr
# Disk partitioning information
%include /tmp/part-include
# Repositories for package installation
repo --name=cdg-disk --baseurl=file:///mnt/source/Packages --cost=0
repo --name=cdg-repo --baseurl=file:///mnt/source/extras/cdg-repo --cost=0
repo --name=cdg-updates --baseurl=file:///mnt/source/extras/cdg-updates --cost=0
repo --name=cdg-epel --baseurl=file:///mnt/source/extras/cdg-epel --cost=0
# Package selection
# TODO: create our own cdg-core, cdg-management groups
%packages
@base
@core
@perl-runtime
@server-platform
@postgresql
@nfs
# TODO: remove this when our own RPMs depend on jre?
jre
%end

# Pre-installation Scripts
%pre

/mnt/stage2/extras/scripts/configurePartition.sh

%end

%post --nochroot

exec < /dev/tty6 > /dev/tty6 2> /dev/tty6
chvt 6

cp -r /mnt/source/extras /mnt/sysimage/tmp

chvt 1
exec < /dev/tty1 > /dev/tty1 2> /dev/tty1

%end
# Post-installation Scripts
%post

exec < /dev/tty6 > /dev/tty6 2> /dev/tty6
chvt 6

/tmp/extras/scripts/main.sh

chvt 1
exec < /dev/tty1 > /dev/tty1 2> /dev/tty1
%end

When I start up the installation.  I get an error saying theres a problem with line 10 of the kickstart Mount Point Required.  (Line 10 is where rootpw)
I have been stuck on this and am a newbie can someone please help me?

A: It looks to me like the top file is what is being used by Kickstart. If so, then I'd say line 10 is indeed in error. The format of the partition name in the part command is "pv.XXX" not "/PV".
Then, again, I still can't get this style of partitioning to work.


text:
Q: How to add my bnd jars dependencies to my eclipse RCP application? I have some core plugins created in my workspace that are built with BND tools in eclipse. Now I have to reference those core plugins in my eclipse RCP application which is developed with PDE tool in eclipse. But there is no visibility to the BND generated plugins inside the RCP application. May be I can manually copy those plugins to a folder and add the folder to the target. But I want to get rid of such manual task.
Is there any easy way to add the BND generated plugins as dependencies to my RCP application?
Thanks in advance.

A: I didn't try with recent version of eclipse and bndtools
But you can try my experiment done 4 year ago
https://github.com/filippor/bndPdeTarget


text:
Q: How to add http logging interceptor along with another interceptor in android with kotlin? I'm struggling with making 2 different interceptors to my retrofit client
i have already one interceptor to add my query api_key into the request and im trying to add the

HttpLoggingInterceptor

with the same retrofit instance is there a way to do this ?
this is my code
import com.example.tvapptest.Services.MovieService
import com.example.tvapptest.Services.ShowService
import com.example.tvapptest.Utils.Constants
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object RetrofitConfig {

private val interceptor : HttpLoggingInterceptor = HttpLoggingInterceptor().apply {
    this.level = HttpLoggingInterceptor.Level.BODY
}

private val client : OkHttpClient = OkHttpClient.Builder().apply {
    this.addInterceptor(interceptor)
}.build()

private val clientapi : OkHttpClient = OkHttpClient.Builder().apply {
    this.addNetworkInterceptor(ApiInterceptor())
}.build()

// use lazy to insure that only one instance of retrofit will be used - no duplication
private val retrofit : Retrofit by lazy {
    Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create())
        .baseUrl(Constants.BASE_URL)
         // the issue is here how can i add another interceptor to the same client here
        //.client(client)
        .client(clientapi)
        .build()
}

val movieService : MovieService by lazy {
    retrofit.create(MovieService::class.java)
}

val showService : ShowService by lazy {
    retrofit.create(ShowService::class.java)
}
}

and this is my ApiInterceptor class
package com.example.tvapptest.Network

import com.example.tvapptest.Utils.Constants
import okhttp3.Interceptor
import okhttp3.Response

// this class is used to intercept the request and add the query param api_key
class ApiInterceptor() : Interceptor {

override fun intercept(chain: Interceptor.Chain): Response {
    val original = chain.request()
    val originalHttpUrl  = original.url
    val requestBuilder = original.newBuilder().url(originalHttpUrl.newBuilder().addQueryParameter("api_key",Constants.API_KEY).build())
    return  chain.proceed(requestBuilder.build())
}
}

A: Is there any reasons for wanting two different clients?
Seems like you would be fine with using just one and adding both the interceptors to the same client.
This is something in the lines of what it looks like in kotlin.
OkHttpClient.Builder()
    .addInterceptor(interceptor)
    .addNetworkInterceptor(ApiInterceptor())
    .build()
}

A: As stated you can add multiple interceptors to the same OkHttpClient
OkHttpClient client = new OkHttpClient.Builder()
 .addInterceptor(authInterceptor)
 .addInterceptor(appendInterceptor)
 .addInterceptor(loggingInterceptor)
 .readTimeout(20, TimeUnit.SECONDS)
.build();

I just want to add that you need to add the logging interceptor last if you also want to incl. the potential changes from the previous interceptors.
Also if you are logging your API requests/responses, the live logging/monitor feature we have at appviewer.io might be of interest. It's way easier to read, is available to your whole team, and it generates versioned docs as well.


text:
Q: Windows Live ID/Live connect, how to get current logged in user's email First, I am using Live connect, as documents says live id will be obsolete
When a user log in my site with Live connect, I want to get the email address which he/she input when he log in.
I can not find a way to get such information, it's so weird.
From /me URL, i can get user's name, id, local and so on, but can not get email address.
Could somebody help me?

A: Success by add scope wl.emails


text:
Q: Can I connect my PC to a 2nd router? I'm no professional in this and am just trying to seek advice.
I recently bought a new router(Nokia beacon 1 wi-fi mesh) but it apparently only has 1 LAN port and so
-I can only connect either my ethernet(It's  blue) cable from PC to router
-or another white ethernet cable from my TV set-up box to the router

Is this a possible solution?
1)Buy another Nokia beacon 1
2)Add it to the network, apparently, there's an app that I can just download and click "Add to Network"
3)Connect my PC's cable to the 2nd router's LAN port. Connect set-up box's cable to 1st router's LAN port

A: Please do read up on some networking basics. Google "introduction to networking" or something similar. You'll need the background, and the Q&A on this site is not suitable to give a complete background.
A switch is a networking device that connects multiple computers "passively". In the simplest variant, packets that go into one port ("housing for an internet cable") will go out through all other ports.
Think of it as some kind of "power strip" for networking, but there's no dedicated cable where the power goes "in".
So yes,

a switch is just house for multiple Ethernet cables and then you connect the switch to the router?

You connect the switch to the router and to all your computing devices, and then the router will tell all computing devices that they are in your home network (the protocol for that is called DHCP). Then the computing devices can connect to the internet through the switch and the router, and connect to each other through the switch.


text:
Q: R - Splitting character vector so that every unique element is added to a new character vector I have a character vector where single elements contain multiple strings separated by commas. I have obtained this list by extracting it from a data frame, and it looks like this:
 [1] "Acworth, Crescent Lake, East Acworth, Lynn, South Acworth"
 [2] "Ferncroft, Passaconaway, Paugus Mill"
 [3] "Alexandria, South Alexandria"
 [4] "Allenstown, Blodgett, Kenison Corner, Suncook (part)"
 [5] "Alstead, Alstead Center, East Alstead, Forristalls Corner, Mill Hollow"
 [6] "Alton, Alton Bay, Brookhurst, East Alton, Loon Cove, Mount Major, South Alton, Spring Haven, Stockbridge Corners, West Alton, Woodlands"
 [7] "Amherst, Baboosic Lake, Cricket Corner, Ponemah"
 [8] "Andover, Cilleyville, East Andover, Halcyon Station, Potter Place, West Andover"
 [9] "Antrim, Antrim Center, Clinton Village, Loverens Mill, North Branch"
[10] "Ashland"

I would like to obtain a new character vector whereby every single string is an element within this character vector, i.e.:
 [1] "Acworth", "Crescent Lake", "East Acworth", "Lynn", "South Acworth"
 [6] "Ferncroft", "Passaconaway", "Paugus Mill", "Alexandria", "South Alexandria"

I used the strsplit() function, however this returns a list. When I try to turn it into a character vector, it reverts to the old state.
I'm sure this is a really simple problem - any help would be greatly appreciated! thanks!

A: You may get rid of the spaces and split the character vector with the "\\s*,\\s*" regex and then unlist the result:
v <- c("Acworth, Crescent Lake, East Acworth, Lynn, South Acworth", "Ferncroft, Passaconaway, Paugus Mill", "Alexandria, South Alexandria",  "Allenstown, Blodgett, Kenison Corner, Suncook (part)", "Alstead, Alstead Center, East Alstead, Forristalls Corner, Mill Hollow", "Alton, Alton Bay, Brookhurst, East Alton, Loon Cove, Mount Major, South Alton, Spring Haven, Stockbridge Corners, West Alton, Woodlands", "Amherst, Baboosic Lake, Cricket Corner, Ponemah",  "Andover, Cilleyville, East Andover, Halcyon Station, Potter Place, West Andover",  "Antrim, Antrim Center, Clinton Village, Loverens Mill, North Branch",  "Ashland" )
s <- unlist(strsplit(v, "\\s*,\\s*"))

See the IDEONE demo
The regex matches zero or more whitespace symbols (\s*) on both sides of ,, thus trimming the values. This will handle cases even when there is a "wild" space before a comma in the initial character vector.

A: Your post title suggests you want unique strings, so
unique(unlist(strsplit(myvec, split=",")))

or
unique(unlist(strsplit(myvec, split=", ")))

if you always have a space following the comma.

A: As an alternative, you can also use scan, like this:
unique(scan(what = "", text = v, sep = ",", strip.white = TRUE))

The strip.white = TRUE part takes care of any leading or trailing whitespace you may have.
Note: "v" comes from this other answer.