问:
TreeView auto-selecting parent after user update selected child WPF command
I have a 2 level WPF treeview. When I click on a child item, the correct selectedCommand is triggered and all works well.

But when I click on my details view and update the field of this selected item, it unselect my childItem and fired the parent command because the parent is selected, but I need to just keep my childItem selected.

I have found some topics about the same problem, but I use command for my binding and not just code behind so I don't know how to make this solution work for me.

Dispacher.BeginInvoke method : > Parent TreeView Item ghost selected event!

e.Handled : > WPF TreeviewItem parent selected event fired after selecting a child?

And a topic that said it's a focus problem : TreeView auto-selecting parent after user selects child

Trigger of my command :

```<code><i:Interaction.Triggers>
    <i:EventTrigger EventName="SelectedItemChanged">
        <i:InvokeCommandAction
            Command="{Binding ItemSelectedCommand}"
            CommandParameter="{Binding SelectedItem, ElementName=TreeView}"/>
    </i:EventTrigger>
</i:Interaction.Triggers>
</code>```

My Treeview :

```<code><TreeView x:Name="TreeView"
        ItemsSource="{Binding Modules}">
    <HierarchicalDataTemplate DataType="{x:Type module:ParentViewModel}" ItemsSource="{Binding ChildItems}">
        <TextBlock Text="Parent"/>
    </HierarchicalDataTemplate>

    <HierarchicalDataTemplate DataType="{x:Type module:ChildViewModel}">
        <TextBlock Text="{Binding Path=childName}"/>
    </HierarchicalDataTemplate>
</TreeView>
</code>```

And here is my command which is in my ViewModel file

```<code>public ICommand ItemSelectedCommand
{
   get
   {
        return _itemSelectedCommand ?? (_itemSelectedCommand = new CommandHandler(param => SelectedCommand(param)));
   }
}

public void SelectedCommand(object selectedItem)
{
     //code to activate my details view with prism
    if(selectedItem.GetType().Name == "ParentType")
    {
        ActivateParentView();
    }
    else
    {
        ActivateDetailsView(.....); //activate child view
    }
}
</code>```

So, I trigger the same command when selected an item in my treeview but when I select the child item, the parent event is also triggered so my command is triggered 2 times and activate my parent view and don't stay in my child view. How can I stop propagating the event if I have already pass through child command ? How can I make it working with my command and not in code behind ?

EDIT

Here is my function ActivateDetailsView() which is called by my SelectedCommand
I have 13 modules and I have one detailsView in each module, so when I click on my selected item, I will search using reflexivity for the view I need to activate and I use PRISM library to activate it.

```<code>private void ActivateDetailsView(string nameTypeItem,IRegion tabConfigurationRegion, ModuleItemBaseViewModel selectedItem)
    {
        try
        {
            string viewName = "ModuleItem" + nameTypeItem + "DetailsView";

            string moduleName = "Module" + nameTypeItem;
            string fullViewName = moduleName + ".Views." + viewName + ", " + moduleName;

            var typeOfCurrentView = Type.GetType(fullViewName);
            //var view = Activator.CreateInstance(typeOfCurrentView);
            var view = tabConfigurationRegion.GetView(viewName);
            if (view == null)
            {
                view = _container.Resolve(typeOfCurrentView);

                // Add the view to the main region. This automatically activates the view too.
                tabConfigurationRegion.Add(view, viewName);
            }

            // The view has already been added to the region so just activate it.
            tabConfigurationRegion.Activate(view);

            string viewModelName = "ModuleItem" + nameTypeItem + "DetailsViewModel";
            string fullViewModelName = moduleName + ".ViewModels." + viewModelName + ", " + moduleName;

            var typeOfCurrentViewModel = Type.GetType(fullViewModelName);
            //equivalent to ModuleItemSiemensDetailsViewModel viewModelM = view.DataContext as ModuleItemSiemensDetailsViewModel;
            var propertyInfoDataContext = view.GetType().GetProperty("DataContext");
            var viewModelModuleItem = propertyInfoDataContext.GetValue(view, null);

            if (viewModelModuleItem != null)
            {
                PropertyInfo prop = typeOfCurrentViewModel.GetProperty("CurrentModuleItem");

                //equivalent to viewModelModuleItem.CurrentModuleItem = selectedItem as ModuleItemBaseViewModel;
                prop.SetValue(viewModelModuleItem, selectedItem, null);
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
            Debug.WriteLine(ex.StackTrace);
        }
    }
</code>```

To reproduce the problem : Start a new WPF project, Add one main project in your solution with a view with a treeview and a treeviewviewmodel with the list of ParentViewModel which will be display on your treeview. Define an other project with 2 viewmodels : one class ParentVM with an ObservableCollection and a childViewModel, let one or two property like name, and bind it to the treeview. In the second project, define a detailsView to see properties of your ChildViewModel. On your main project, in the treeviewviewmodel add a SelectedCommandFunction which use prism to activate your detailView. (You need to have a DetailsView when you click on the Parent and an other one when you click on the ChildView.

答:
Every TreeViewItem is in the visual tree of its parent, and the event will bubble down, so if you clicked the tree leaf, and it has two parents, then the event will be called 3 times.

Ways to prevent this:

Bind the IsSelected of the TreeItem directly to IsSelected of your VM, and do your thing OnPropertyChanged of IsSelected property of your VM.

In a roundabout way: in codebehind, when you handle the event, check if the OriginalSource is the same as the sender (similar to here)

Implement your own EventTrigger that marks events as Handled

Body:
I have a 2 level WPF treeview. When I click on a child item, the correct selectedCommand is triggered and all works well.

But when I click on my details view and update the field of this selected item, it unselect my childItem and fired the parent command because the parent is selected, but I need to just keep my childItem selected.

I have found some topics about the same problem, but I use command for my binding and not just code behind so I don't know how to make this solution work for me.

Dispacher.BeginInvoke method : > Parent TreeView Item ghost selected event!

e.Handled : > WPF TreeviewItem parent selected event fired after selecting a child?

And a topic that said it's a focus problem : TreeView auto-selecting parent after user selects child

Trigger of my command :

My Treeview :

<TreeView x:Name="TreeView"
        ItemsSource="{Binding Modules}">
    <HierarchicalDataTemplate DataType="{x:Type module:ParentViewModel}" ItemsSource="{Binding ChildItems}">
        <TextBlock Text="Parent"/>
    </HierarchicalDataTemplate>

    <HierarchicalDataTemplate DataType="{x:Type module:ChildViewModel}">
        <TextBlock Text="{Binding Path=childName}"/>
    </HierarchicalDataTemplate>
</TreeView>

And here is my command which is in my ViewModel file

public ICommand ItemSelectedCommand
{
   get
   {
        return _itemSelectedCommand ?? (_itemSelectedCommand = new CommandHandler(param => SelectedCommand(param)));
   }
}

public void SelectedCommand(object selectedItem)
{
     //code to activate my details view with prism
    if(selectedItem.GetType().Name == "ParentType")
    {
        ActivateParentView();
    }
    else
    {
        ActivateDetailsView(.....); //activate child view
    }
}

So, I trigger the same command when selected an item in my treeview but when I select the child item, the parent event is also triggered so my command is triggered 2 times and activate my parent view and don't stay in my child view. How can I stop propagating the event if I have already pass through child command ? How can I make it working with my command and not in code behind ?

EDIT

Here is my function ActivateDetailsView() which is called by my SelectedCommand
I have 13 modules and I have one detailsView in each module, so when I click on my selected item, I will search using reflexivity for the view I need to activate and I use PRISM library to activate it.

private void ActivateDetailsView(string nameTypeItem,IRegion tabConfigurationRegion, ModuleItemBaseViewModel selectedItem)
    {
        try
        {
            string viewName = "ModuleItem" + nameTypeItem + "DetailsView";

            string moduleName = "Module" + nameTypeItem;
            string fullViewName = moduleName + ".Views." + viewName + ", " + moduleName;

            var typeOfCurrentView = Type.GetType(fullViewName);
            //var view = Activator.CreateInstance(typeOfCurrentView);
            var view = tabConfigurationRegion.GetView(viewName);
            if (view == null)
            {
                view = _container.Resolve(typeOfCurrentView);

                // Add the view to the main region. This automatically activates the view too.
                tabConfigurationRegion.Add(view, viewName);
            }

            // The view has already been added to the region so just activate it.
            tabConfigurationRegion.Activate(view);

            string viewModelName = "ModuleItem" + nameTypeItem + "DetailsViewModel";
            string fullViewModelName = moduleName + ".ViewModels." + viewModelName + ", " + moduleName;

            var typeOfCurrentViewModel = Type.GetType(fullViewModelName);
            //equivalent to ModuleItemSiemensDetailsViewModel viewModelM = view.DataContext as ModuleItemSiemensDetailsViewModel;
            var propertyInfoDataContext = view.GetType().GetProperty("DataContext");
            var viewModelModuleItem = propertyInfoDataContext.GetValue(view, null);

            if (viewModelModuleItem != null)
            {
                PropertyInfo prop = typeOfCurrentViewModel.GetProperty("CurrentModuleItem");

                //equivalent to viewModelModuleItem.CurrentModuleItem = selectedItem as ModuleItemBaseViewModel;
                prop.SetValue(viewModelModuleItem, selectedItem, null);
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
            Debug.WriteLine(ex.StackTrace);
        }
    }

To reproduce the problem : Start a new WPF project, Add one main project in your solution with a view with a treeview and a treeviewviewmodel with the list of ParentViewModel which will be display on your treeview. Define an other project with 2 viewmodels : one class ParentVM with an ObservableCollection and a childViewModel, let one or two property like name, and bind it to the treeview. In the second project, define a detailsView to see properties of your ChildViewModel. On your main project, in the treeviewviewmodel add a SelectedCommandFunction which use prism to activate your detailView. (You need to have a DetailsView when you click on the Parent and an other one when you click on the ChildView.


来源: stackexchange

问:
Assembly Call Stack - Terminology Questions
I'm completely new to Assembly and looking to confirm where, in the following statements, I have a misunderstanding and need to be corrected.

The stack pointer (ESP) refers to the top (lowest memory address) of the stack.

The base Pointer (EBP) is used for temporarily storing various memory addresses when building a stack frame. It normally holds the highest memory address of the current stack frame.

The instruction pointer (EIP) refers to the memory address of a line of code in the text (code) segment of memory

Once something has been pushed to the stack, it can't be changed in-place. ie. If we PUSH EBP to the stack, we are pushing the current value of EBP, not some kind of reference or pointer to it. We can't then change that value in-place.

Arguments being passed into a function are generally moved into an address space which is an offset of the stack pointer. ie. [ESP-12].

When a function is called (using CALL), the following occurs:

The return address is added to the stack (the memory of the address immediately following the current EIP so we know where to return to after the called function has completed

The saved frame pointer is added to the stack, which is normally the stack pointer of the stack frame of the calling function

We would then move into the prologue of the called function

Thanks. I'm trying to get my head around this stuff.

答:
Once something has been pushed to the stack, it can't be changed in-place. ie. If we PUSH EBP to the stack, we are pushing the current value of EBP, not some kind of reference or pointer to it. We can't then change that value in-place.

Sure you can. Stack is ordinary computer memory, there's nothing special about it, except that 99% of code expects valid (read+write access) memory address in esp and some reserved space, so it can push some local things to it, as needed.

```<code>push  ebp    ; store current value in ebp to stack
</code>```

Is almost equivalent to:

```<code>sub   esp,4
mov   [esp],ebp
</code>```

(but the second variant will also modify flags and it is somewhat less atomic)

Now you can overwrite it with anything else, like:

```<code>mov [esp],eax ; overwrite the old_ebp value with current_eax value
</code>```

reference or pointer to it

Well, there's no way to have some kind of reference or pointer to the ebp register, it's a register in CPU, only 32 bits (32x 0 or 1 value) and it has no address, you can work with it only by its name ebp in instructions, which allow usage of it in their encoding.

Upon push ebp those 32 bits (and no other info) are copied into memory (which is then holding those 0/1 values copied in its own 32 bits = 4 bytes). There's no information where the value in memory was written from, when and by what instruction, only value bits are stored.

ContentLicense: CC BY-SA 3.0

Body:
Once something has been pushed to the stack, it can't be changed in-place. ie. If we PUSH EBP to the stack, we are pushing the current value of EBP, not some kind of reference or pointer to it. We can't then change that value in-place.

Sure you can. Stack is ordinary computer memory, there's nothing special about it, except that 99% of code expects valid (read+write access) memory address in esp and some reserved space, so it can push some local things to it, as needed.

push  ebp    ; store current value in ebp to stack

Is almost equivalent to:

sub   esp,4
mov   [esp],ebp

(but the second variant will also modify flags and it is somewhat less atomic)

Now you can overwrite it with anything else, like:

mov [esp],eax ; overwrite the old_ebp value with current_eax value

reference or pointer to it

Well, there's no way to have some kind of reference or pointer to the ebp register, it's a register in CPU, only 32 bits (32x 0 or 1 value) and it has no address, you can work with it only by its name ebp in instructions, which allow usage of it in their encoding.

Upon push ebp those 32 bits (and no other info) are copied into memory (which is then holding those 0/1 values copied in its own 32 bits = 4 bytes). There's no information where the value in memory was written from, when and by what instruction, only value bits are stored.


问:
Two way data binding - ngModel
In the below angular2 component,

```<code>export class HomeComponent implements OnInit {
  homeTitle = "Welcome to the home page";
  myString = "I like red";
  myBoolean = false;

  alertMe(val){
    alert(val);
  }

  obj = {
    name: "Yoshi",
    belt: "Black"
  };

  constructor() { }

  ngOnInit() {
  }

}
</code>```

two way data binding does not work for below view,

```<code><p>
  {{homeTitle}}
</p>

<!--  Property binding -->

<!-- input value="Hai" -->
<input [value]="myString">
<input [required]="myBoolean">

<button (click)="alertMe('I like x')">Click me</button>

<hr>
<!-- All above elements are working fine -->

<!-- 2 way data binding -->
<input [(ngModel)]="obj.name">
<p>{{obj.name}}</p>
<p>{{obj.belt}}</p>
</code>```

Why obj.name does not render in the input element?

答:
in your Module just add FormsModule

```<code>import { FormsModule } from '@angular/forms';
imports: [
  ..
  FormsModule
]
</code>```

Title: Two way data binding - ngModel

Body:
In the below angular2 component,

export class HomeComponent implements OnInit {
  homeTitle = "Welcome to the home page";
  myString = "I like red";
  myBoolean = false;

  alertMe(val){
    alert(val);
  }

  obj = {
    name: "Yoshi",
    belt: "Black"
  };

  constructor() { }

  ngOnInit() {
  }

}

two way data binding does not work for below view,

  {{homeTitle}}

<input [value]="myString">
<input [required]="myBoolean">

<button (click)="alertMe('I like x')">Click me</button>

<input [(ngModel)]="obj.name">

{{obj.name}}

{{obj.belt}}

Why obj.name does not render in the input element?

Body:
in your Module just add FormsModule

import { FormsModule } from '@angular/forms';
imports: [
  ..
  FormsModule
]


问:
EF Core 2.0 - Circular Dependency with required FK on either end
I have a fairly simple data model consisting of two entities:

```<code>public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int CurrentLocationId { get; set; }

    public List<Location> Locations { get; set; }
    public Location CurrentLocation { get; set; }
}
</code>```

and

```<code>public class Location
{
    public int Id { get; set; }
    [Required]
    public int UserId { get; set; }
    public string Address { get; set; }

    public User User { get; set; }
}
</code>```

then in order to get a successful migration to run I needed the following model builder code:

```<code>builder.Entity<Location>()
       .HasOne(x => x.User)
       .WithMany(x => x.Locations)
       .HasForeignKey(x => x.UserId);
</code>```

This has generated a database as I'd expect and how I need it to be. However, I'm unable to save entities due to the following circular dependency error:

InvalidOperationException: Unable to save changes because a circular dependency was detected in the data to be saved: 'ForeignKey: User {'CurrentLocationId'} -> Location {'Id'} ToPrincipal: CurrentLocation, ForeignKey: Location {'UserId'} -> User {'Id'} ToDependent: Locations ToPrincipal: User'.

Is there a way around this in EF Core 2.0?

I have a few options to circumnavigate it by changing my data model, but this is the preferred approach as I can use DB constraints to ensure that all Locations link back to a User, and that every user must have a CurrentLocation set. I know it would solve the issue but I can't really allow nulls on the CurrentLocation field!

The code I'm using to try and store users is as follows (simplified for demo purposes):

```<code>var location = new Location
{
    Address = "Some address"
};

_context.Locations.Add(location);

var user = new User
{
    Name = "Stu"
};

_context.Users.Add(user);

user.Locations = new List<Location>
{
    location
};

user.CurrentLocation = location;

await _context.SaveChangesAsync();
</code>```

and I've also tried

```<code>var location = new Location
{
    Address = "Some address"
};

var user = new User
{
    Name = "Stu",
    Locations = new List<Location>
    {
        location
    },
    CurrentLocation = location
};

_context.Users.Add(user);
await _context.SaveChangesAsync();
</code>```

But the error remains the same. Can this be fixed by some kind of fancy ModelBuilder overrides? Or am I restricted to changing my data model / allowing nulls where I shouldn't really be allowing nulls?

Thanks in advance!

答: To answer my own question - just checked and SQL server doesn't support deferrable constraints, so nothing EF can do anyway! Change to the data model it is.</p>

Body:
I have a fairly simple data model consisting of two entities:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int CurrentLocationId { get; set; }

    public List<Location> Locations { get; set; }
    public Location CurrentLocation { get; set; }
}

and

public class Location
{
    public int Id { get; set; }
    [Required]
    public int UserId { get; set; }
    public string Address { get; set; }

    public User User { get; set; }
}

then in order to get a successful migration to run I needed the following model builder code:

builder.Entity<Location>()
       .HasOne(x => x.User)
       .WithMany(x => x.Locations)
       .HasForeignKey(x => x.UserId);

This has generated a database as I'd expect and how I need it to be. However, I'm unable to save entities due to the following circular dependency error:

InvalidOperationException: Unable to save changes because a circular dependency was detected in the data to be saved: 'ForeignKey: User {'CurrentLocationId'} -> Location {'Id'} ToPrincipal: CurrentLocation, ForeignKey: Location {'UserId'} -> User {'Id'} ToDependent: Locations ToPrincipal: User'.

Is there a way around this in EF Core 2.0?

I have a few options to circumnavigate it by changing my data model, but this is the preferred approach as I can use DB constraints to ensure that all Locations link back to a User, and that every user must have a CurrentLocation set. I know it would solve the issue but I can't really allow nulls on the CurrentLocation field!

The code I'm using to try and store users is as follows (simplified for demo purposes):

var location = new Location
{
    Address = "Some address"
};

_context.Locations.Add(location);

var user = new User
{
    Name = "Stu"
};

_context.Users.Add(user);

user.Locations = new List<Location>
{
    location
};

user.CurrentLocation = location;

await _context.SaveChangesAsync();

and I've also tried

var location = new Location
{
    Address = "Some address"
};

var user = new User
{
    Name = "Stu",
    Locations = new List<Location>
    {
        location
    },
    CurrentLocation = location
};

_context.Users.Add(user);
await _context.SaveChangesAsync();

But the error remains the same. Can this be fixed by some kind of fancy ModelBuilder overrides? Or am I restricted to changing my data model / allowing nulls where I shouldn't really be allowing nulls?

Thanks in advance!


问:
How do I display a random phrase from a list when a button is clicked in a web page?
I am creating a web page where someone can visit it. They type a question in a field and click a button, and a response is passed back to them. (Kind of like a magic 8 ball).

What I'm trying to do is set it up something like this:

http://img585.imageshack.us/img585/997/layoutoi.png

I'm still new to hand-coding things - I have a book on HTML/CSS and one on PHP, which lay still unread, so I'll probably need a step-by-step process. (I have a host and everything, so that's already taken care of.) Thanks in advance!

答:
Dorkitude's answer is a fine example but just as an additional bit of advice I would like to point out that it is usually considered bad practice to hard code data inside your scripts (i.e. $value = 'someValue') unless there is absolutely no other way around it. Instead you would use some kind of data source for your responses instead (plain text file, database, web service etc).

For example lets say you have stored your list in a plain text file called 'randomThings.txt' and placed each response on its own line. You could then adapt Dorkitude's code like so:

```<code><?php
    // Flags set here to ensure integrity
    $randomThings = file('responses.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
?>

<!-- REST OF YOUR PAGE -->

<?php

    echo $randomThings[mt_rand(0,count($randomThings)-1)];

?>
<!-- OTHER STUFF -->
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Dorkitude's answer is a fine example but just as an additional bit of advice I would like to point out that it is usually considered bad practice to hard code data inside your scripts (i.e. $value = 'someValue') unless there is absolutely no other way around it. Instead you would use some kind of data source for your responses instead (plain text file, database, web service etc).

For example lets say you have stored your list in a plain text file called 'randomThings.txt' and placed each response on its own line. You could then adapt Dorkitude's code like so:

<?php
    // Flags set here to ensure integrity
    $randomThings = file('responses.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
?>

<!-- REST OF YOUR PAGE -->

<?php

    echo $randomThings[mt_rand(0,count($randomThings)-1)];

?>
<!-- OTHER STUFF -->


问:
D3 Tree Layout Separation Between Nodes using NodeSize
Right now I am trying to separate my rectangle nodes because they overlap as shown in the picture below:

I took a look and found out that D3 offers a nodeSize and separation method but for some reason it did not work.

I found this blog post talking about the issue but he says

The size property doesn’t exist in nodes, so it will be whatever property you want to control the size of them.

but clearly there is a nodeSize method so I feel like I am simply using the method incorrectly and/or the blog post is out-of-date. I want to shape my nodes to be the size of the rectangle and space them out evenly so they do not overlap each other. Does anyone know how to use the methods properly? The documentation about these methods isn't explained very well and it isn't yielding any difference. I also couldn't find many examples where people changed the nodeSize of trees or needed separation for rectangular objects (there were some examples regarding circular ones but I feel that's too different...)

Here is the relevant code. I will try to prepare a JSFiddle.

```<code>var margin = {top: 20, right: 120, bottom: 20, left: 120},
    height = 960 - margin.right - margin.left,
    width = 800 - margin.top - margin.bottom,
    rectW = 70;
    rectH = 30;
    //bbox = NaN,
    maxTextLength = 0;

var i = 0,
    duration = 750,
    root;

//paths from each node drawn initially here
//changed to d.x, d.y
var diagonal = d3.svg.diagonal()
    .projection(function(d) { return [d.x+rectW/2, d.y+rectH/2];
    //.projection(function(d) { return [d.x+bbox.getBBox().width/2, d.y+bbox.getBBox().height/2];
});

var tree = d3.layout.tree()
    .nodeSize([30,70])
    .separation(function(a, b) { return (a.parent == b.parent ? 1 : 2); })
    .size([width, height]);

var svg = d3.select("body")
            .append("svg")
              .attr("height","100%").attr("width","100%")
              .call(d3.behavior.zoom().on("zoom", redraw))
              .append("g")
                .attr("transform", "translate(" + margin.top + "," + margin.left + ")");
</code>```

答:
First, thanks to all those who posted before, pure gold.
I wanted to add to this post for those that might be struggling with the offset problem associated with a horizontally drawn tree.

The key is, if you switch from .size() to .nodeSize() on a horizontal tree, you'll notice your root node seems to jump/reorient to be located at (0,0).
And per the d3.js documentation this is actually the case (see https://github.com/d3/d3-hierarchy/blob/master/README.md#tree_nodeSize )

However, to adjust you just need to make sure to reorient your viewBox.
That is to say, when you .append your svg you need to explicitly set your viewBox. Here's my hacky little line where it worked for me...

```<code>svg = d3.select("#tree").append("svg")
            .attr("width", width + margin.right + margin.left)
            .attr("height", height + 0 + 0)
            .attr("viewBox", "0 "+(-1*(height-margin.top-margin.bottom)/2)+" "+width+" "+height)
            .append("g")
            .attr("transform", "translate("
                  + margin.left + "," + 0 + ")");
</code>```

Body:
Right now I am trying to separate my rectangle nodes because they overlap as shown in the picture below:

I took a look and found out that D3 offers a nodeSize and separation method but for some reason it did not work.

I found this blog post talking about the issue but he says

The size property doesn’t exist in nodes, so it will be whatever property you want to control the size of them.

but clearly there is a nodeSize method so I feel like I am simply using the method incorrectly and/or the blog post is out-of-date. I want to shape my nodes to be the size of the rectangle and space them out evenly so they do not overlap each other. Does anyone know how to use the methods properly? The documentation about these methods isn't explained very well and it isn't yielding any difference. I also couldn't find many examples where people changed the nodeSize of trees or needed separation for rectangular objects (there were some examples regarding circular ones but I feel that's too different...)

Here is the relevant code. I will try to prepare a JSFiddle.

var margin = {top: 20, right: 120, bottom: 20, left: 120},
    height = 960 - margin.right - margin.left,
    width = 800 - margin.top - margin.bottom,
    rectW = 70;
    rectH = 30;
    //bbox = NaN,
    maxTextLength = 0;

var i = 0,
    duration = 750,
    root;

//paths from each node drawn initially here
//changed to d.x, d.y
var diagonal = d3.svg.diagonal()
    .projection(function(d) { return [d.x+rectW/2, d.y+rectH/2];
    //.projection(function(d) { return [d.x+bbox.getBBox().width/2, d.y+bbox.getBBox().height/2];
});

var tree = d3.layout.tree()
    .nodeSize([30,70])
    .separation(function(a, b) { return (a.parent == b.parent ? 1 : 2); })
    .size([width, height]);

var svg = d3.select("body")
            .append("svg")
              .attr("height","100%").attr("width","100%")
              .call(d3.behavior.zoom().on("zoom", redraw))
              .append("g")
                .attr("transform", "translate(" + margin.top + "," + margin.left + ")");

Body:
First, thanks to all those who posted before, pure gold.
I wanted to add to this post for those that might be struggling with the offset problem associated with a horizontally drawn tree.

The key is, if you switch from .size() to .nodeSize() on a horizontal tree, you'll notice your root node seems to jump/reorient to be located at (0,0).
And per the d3.js documentation this is actually the case (see https://github.com/d3/d3-hierarchy/blob/master/README.md#tree_nodeSize )

However, to adjust you just need to make sure to reorient your viewBox.
That is to say, when you .append your svg you need to explicitly set your viewBox. Here's my hacky little line where it worked for me...

svg = d3.select("#tree").append("svg")
            .attr("width", width + margin.right + margin.left)
            .attr("height", height + 0 + 0)
            .attr("viewBox", "0 "+(-1*(height-margin.top-margin.bottom)/2)+" "+width+" "+height)
            .append("g")
            .attr("transform", "translate("
                  + margin.left + "," + 0 + ")");


问:
Dynamic tabs in TabView nativescript
Is it possible to create tabs dynamically for a tabview in nativescript?

The following example is in the documentation of nativescript

```<code><TabView selectedIndex="0"  (selectedIndexChange)="onIndexChanged($event)" sdkExampleTitle sdkToggleNavButton>
    <StackLayout *tabItem="{title: 'NativeScript'}">
        <Label text="NativeScript" class="m-15 h2 text-left" color="blue"></Label>
        <ScrollView>
            <Label [text]="content" textWrap="true" class="m-15"></Label>
        </ScrollView>
    </StackLayout>
    <StackLayout *tabItem="{title: 'Icon'}">
        <Image class="m-t-30 m-b-15" src="res://icon" width="80" height="80"></Image>
        <Label text="NativeScript" textWrap="true" class="h2 m-x-auto" color="blue"></Label>
    </StackLayout>
</TabView>
</code>```

and it does not allow me to use the ng for since the StackLayout element already has a directive that starts with *

答:
Yes you can ! use *ngFor

```<code><TabView>
    <ng-container *ngFor="let tab of tabList">
       <StackLayout *tabItem="tab">
                .....
       </StackLayout>
    </ng-container>
</TabView>
</code>```

Title: Dynamic tabs in TabView nativescript

Body:
Is it possible to create tabs dynamically for a tabview in nativescript?

The following example is in the documentation of nativescript

<TabView selectedIndex="0"  (selectedIndexChange)="onIndexChanged($event)" sdkExampleTitle sdkToggleNavButton>
    <StackLayout *tabItem="{title: 'NativeScript'}">

        <ScrollView>

        </ScrollView>
    </StackLayout>
    <StackLayout *tabItem="{title: 'Icon'}">
        <Image class="m-t-30 m-b-15" src="res://icon" width="80" height="80"></Image>

    </StackLayout>
</TabView>

and it does not allow me to use the ng for since the StackLayout element already has a directive that starts with *

Body:
Yes you can ! use *ngFor

<TabView>
    <ng-container *ngFor="let tab of tabList">
       <StackLayout *tabItem="tab">
                .....
       </StackLayout>
    </ng-container>
</TabView>


问:
How to integrate Twitter Login using JWT?
I have some application that works with Spring Boot. This is just login/registration page nothing more.

My JWT Filter

```<code>public class JWTFilter extends GenericFilterBean {

    private static final String AUTHORIZATION_HEADER = "X-CustomToken";
    private static final String AUTHORITIES_KEY = "roles";

    /**
     * doFilter method for creating correct token(Bearer has taken from front-end part)
     *
     * @param req
     * @param res
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        String authHeader = request.getHeader(AUTHORIZATION_HEADER);
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            ((HttpServletResponse) res).sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid Authorization header.");
        } else {
            try {
                String token = authHeader.substring(7);
                Claims claims = Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody();
                request.setAttribute("claims", claims);
                SecurityContextHolder.getContext().setAuthentication(getAuthentication(claims));
                filterChain.doFilter(req, res);
            } catch (SignatureException e) {
                ((HttpServletResponse) res).sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
            }

        }
    }

    /**
     * Method for creating Authentication for Spring Security Context Holder
     * from JWT claims
     */
    private Authentication getAuthentication(Claims claims) {
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        List<String> roles = (List<String>) claims.get(AUTHORITIES_KEY);
        for (String role : roles) {
            authorities.add(new SimpleGrantedAuthority(role));
        }
        User principal = new User(claims.getSubject(), "", authorities);
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                principal, "", authorities);
        return usernamePasswordAuthenticationToken;
    }
}
</code>```

My WebSecurityConfig class

```<code>@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * This method is for overriding some configuration of the WebSecurity
     * If you want to ignore some request or request patterns then you can
     * specify that inside this method
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                // ignoring the "/index.html", "/app/**", "/registration",
                // "/favicon.ico"
                .antMatchers("/", "/index.html", "/app/**", "/registration", "/login", "/favicon.ico ", "/confirmRegistration/**")
                .and();
                }

    /**
     * This method is used for override HttpSecurity of the web Application.
     * We can specify our authorization criteria inside this method.
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest().fullyAuthenticated().and()
                .addFilterBefore(new JWTFilter(), UsernamePasswordAuthenticationFilter.class)
                .httpBasic().and()
                .csrf().disable();
    }
}
</code>```

So I have 1 admin hardcoded in data.sql and every user that registers in my app will get User role and save into MySQL. I'd like to add Social Apps Login (such as Twitter, Facebook and Google). The question is how to do that, if I use JWT? As far as I know, Oauth2 is preferable to use social apps, but can I do it in my way?

If I want to start with Twitter, how to do it best?

Get consumer and secret keys from twitter API

Put it into application.properties

Set spring-social dependecies

Create SocialConfig class

Change my html login page file

So, do I need to change my login controller class?

答:
I'm not sure about other social networks, but, if your code is Java and you are planning to work with the Twitter API, the way to go is using the Twitter4J library. It's a de-facto standard in the Java world, and is well documented.

Sure, you need a Twitter Dev Account.You can get more info on the Twitter Dev Portal

Body:
I have some application that works with Spring Boot. This is just login/registration page nothing more.

My JWT Filter

public class JWTFilter extends GenericFilterBean {

    private static final String AUTHORIZATION_HEADER = "X-CustomToken";
    private static final String AUTHORITIES_KEY = "roles";

    /**
     * doFilter method for creating correct token(Bearer has taken from front-end part)
     *
     * @param req
     * @param res
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        String authHeader = request.getHeader(AUTHORIZATION_HEADER);
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            ((HttpServletResponse) res).sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid Authorization header.");
        } else {
            try {
                String token = authHeader.substring(7);
                Claims claims = Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody();
                request.setAttribute("claims", claims);
                SecurityContextHolder.getContext().setAuthentication(getAuthentication(claims));
                filterChain.doFilter(req, res);
            } catch (SignatureException e) {
                ((HttpServletResponse) res).sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
            }

        }
    }

    /**
     * Method for creating Authentication for Spring Security Context Holder
     * from JWT claims
     */
    private Authentication getAuthentication(Claims claims) {
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        List<String> roles = (List<String>) claims.get(AUTHORITIES_KEY);
        for (String role : roles) {
            authorities.add(new SimpleGrantedAuthority(role));
        }
        User principal = new User(claims.getSubject(), "", authorities);
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                principal, "", authorities);
        return usernamePasswordAuthenticationToken;
    }
}

My WebSecurityConfig class

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * This method is for overriding some configuration of the WebSecurity
     * If you want to ignore some request or request patterns then you can
     * specify that inside this method
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                // ignoring the "/index.html", "/app/**", "/registration",
                // "/favicon.ico"
                .antMatchers("/", "/index.html", "/app/**", "/registration", "/login", "/favicon.ico ", "/confirmRegistration/**")
                .and();
                }

    /**
     * This method is used for override HttpSecurity of the web Application.
     * We can specify our authorization criteria inside this method.
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest().fullyAuthenticated().and()
                .addFilterBefore(new JWTFilter(), UsernamePasswordAuthenticationFilter.class)
                .httpBasic().and()
                .csrf().disable();
    }
}

So I have 1 admin hardcoded in data.sql and every user that registers in my app will get User role and save into MySQL. I'd like to add Social Apps Login (such as Twitter, Facebook and Google). The question is how to do that, if I use JWT? As far as I know, Oauth2 is preferable to use social apps, but can I do it in my way?

If I want to start with Twitter, how to do it best?

Get consumer and secret keys from twitter API

Put it into application.properties

Set spring-social dependecies

Create SocialConfig class

Change my html login page file

So, do I need to change my login controller class?


问:
Matching on a variable and using the spread function to reshape data
I have a dataframe (lets call it df1) that looks something like this...

```<code>Date                Price       Product Key
2014-08-06          10          00020e32-3ae8-b7fa-8ecd53a64715
2014-08-06          56          00020e32-3ae8-b7fa-8ecd53a64715
2014-09-15          81          000340b8-9ee5-b2cb-60fb50bacac8
2014-06-04          73          000340b8-9ee5-b2cb-60fb50bacac8
2015-01-19          44          000458f1-1297-a2fd-9304a2fdb6ae
2015-05-23          20          000458f1-1297-a2fd-9304a2fdb6ae
2014-07-21          0.75        ddc8f2e2-3496-8a71-8d1019d2651c
</code>```

There are other variables in the dataframe but we will ignore them for now, as I do not require them.

The dataset has many different dates and product keys, this is just an example. What I want to do is exact match all products with the same product key and then extract all products with that one product key into a column of it's own. (Which should give me back around 100+ columns, each column having their own unique product key but also keeping their respective dates and prices (and other variables that I haven't included), that I can then work with)

My desired output would look something like in the image below:

As you can see each product key in their new column still corresponds to their respective dates/price/other variables. Obviously there would be more than two product keys per column but this is just for an example.

I have tried various grep functions and dplyr functions but I don't seem to be getting anywhere? The main issue for me is the initial matching process within one column and being able to keep product keys next to their relevant dates and prices. I hope this makes sense - please let me know if I can make this any clearer.

```<code>    Date        price_currentday    json_productkey                        pk                 pk_val

    2014-08-06          10          00020e32-3ae8-b7fa-8ecd53a64715        Product_Key_1      00020e32-3ae8-b7fa-8ecd53a64715
    2014-08-06          56          00020e32-3ae8-b7fa-8ecd53a64715        Product_Key_1      00020e32-3ae8-b7fa-8ecd53a64715
    2014-09-15          81          000340b8-9ee5-b2cb-60fb50bacac8        Product_Key_2      000340b8-9ee5-b2cb-60fb50bacac8
    2014-06-04          73          000340b8-9ee5-b2cb-60fb50bacac8        Product_Key_2      000340b8-9ee5-b2cb-60fb50bacac8
    2015-01-19          44          000458f1-1297-a2fd-9304a2fdb6ae        Product_Key_3      000458f1-1297-a2fd-9304a2fdb6ae
    2015-05-23          20          000458f1-1297-a2fd-9304a2fdb6ae        Product_Key_3      000458f1-1297-a2fd-9304a2fdb6ae
    2014-07-21          0.75        ddc8f2e2-3496-8a71-8d1019d2651c        Product_Key_4      ddc8f2e2-3496-8a71-8d1019d2651c
</code>```

Body:
I have a dataframe (lets call it df1) that looks something like this...

Date                Price       Product Key
2014-08-06          10          00020e32-3ae8-b7fa-8ecd53a64715
2014-08-06          56          00020e32-3ae8-b7fa-8ecd53a64715
2014-09-15          81          000340b8-9ee5-b2cb-60fb50bacac8
2014-06-04          73          000340b8-9ee5-b2cb-60fb50bacac8
2015-01-19          44          000458f1-1297-a2fd-9304a2fdb6ae
2015-05-23          20          000458f1-1297-a2fd-9304a2fdb6ae
2014-07-21          0.75        ddc8f2e2-3496-8a71-8d1019d2651c

There are other variables in the dataframe but we will ignore them for now, as I do not require them.

The dataset has many different dates and product keys, this is just an example. What I want to do is exact match all products with the same product key and then extract all products with that one product key into a column of it's own. (Which should give me back around 100+ columns, each column having their own unique product key but also keeping their respective dates and prices (and other variables that I haven't included), that I can then work with)

My desired output would look something like in the image below:

As you can see each product key in their new column still corresponds to their respective dates/price/other variables. Obviously there would be more than two product keys per column but this is just for an example.

I have tried various grep functions and dplyr functions but I don't seem to be getting anywhere? The main issue for me is the initial matching process within one column and being able to keep product keys next to their relevant dates and prices. I hope this makes sense - please let me know if I can make this any clearer.

    Date        price_currentday    json_productkey                        pk                 pk_val

    2014-08-06          10          00020e32-3ae8-b7fa-8ecd53a64715        Product_Key_1      00020e32-3ae8-b7fa-8ecd53a64715
    2014-08-06          56          00020e32-3ae8-b7fa-8ecd53a64715        Product_Key_1      00020e32-3ae8-b7fa-8ecd53a64715
    2014-09-15          81          000340b8-9ee5-b2cb-60fb50bacac8        Product_Key_2      000340b8-9ee5-b2cb-60fb50bacac8
    2014-06-04          73          000340b8-9ee5-b2cb-60fb50bacac8        Product_Key_2      000340b8-9ee5-b2cb-60fb50bacac8
    2015-01-19          44          000458f1-1297-a2fd-9304a2fdb6ae        Product_Key_3      000458f1-1297-a2fd-9304a2fdb6ae
    2015-05-23          20          000458f1-1297-a2fd-9304a2fdb6ae        Product_Key_3      000458f1-1297-a2fd-9304a2fdb6ae
    2014-07-21          0.75        ddc8f2e2-3496-8a71-8d1019d2651c        Product_Key_4      ddc8f2e2-3496-8a71-8d1019d2651c

Body:
df1$pk = paste("Product_Key", as.numeric(factor(
  df1$Product_Key, levels = unique(df1$Product_Key)
)), sep = "_")

df1$pk_val = df1$Product_Key

tidyr::spread(df1, key = pk, value = pk_val)
        Date Price                     Product_Key                   Product_Key_1
# 1 2014-06-04 73.00 000340b8-9ee5-b2cb-60fb50bacac8                            <NA>
# 2 2014-07-21  0.75 ddc8f2e2-3496-8a71-8d1019d2651c                            <NA>
# 3 2014-08-06 10.00 00020e32-3ae8-b7fa-8ecd53a64715 00020e32-3ae8-b7fa-8ecd53a64715
# 4 2014-08-06 56.00 00020e32-3ae8-b7fa-8ecd53a64715 00020e32-3ae8-b7fa-8ecd53a64715
# 5 2014-09-15 81.00 000340b8-9ee5-b2cb-60fb50bacac8                            <NA>
# 6 2015-01-19 44.00 000458f1-1297-a2fd-9304a2fdb6ae                            <NA>
# 7 2015-05-23 20.00 000458f1-1297-a2fd-9304a2fdb6ae                            <NA>
#                     Product_Key_2                   Product_Key_3                   Product_Key_4
# 1 000340b8-9ee5-b2cb-60fb50bacac8                            <NA>                            <NA>
# 2                            <NA>                            <NA> ddc8f2e2-3496-8a71-8d1019d2651c
# 3                            <NA>                            <NA>                            <NA>
# 4                            <NA>                            <NA>                            <NA>
# 5 000340b8-9ee5-b2cb-60fb50bacac8                            <NA>                            <NA>
# 6                            <NA> 000458f1-1297-a2fd-9304a2fdb6ae                            <NA>
# 7                            <NA> 000458f1-1297-a2fd-9304a2fdb6ae                            <NA>

It re-orders your rows, but if you have something to sort by that can be easily fixed.

Using this data:

df1 = read.table(text = "Date                Price       Product_Key
2014-08-06          10          00020e32-3ae8-b7fa-8ecd53a64715
2014-08-06          56          00020e32-3ae8-b7fa-8ecd53a64715
2014-09-15          81          000340b8-9ee5-b2cb-60fb50bacac8
2014-06-04          73          000340b8-9ee5-b2cb-60fb50bacac8
2015-01-19          44          000458f1-1297-a2fd-9304a2fdb6ae
2015-05-23          20          000458f1-1297-a2fd-9304a2fdb6ae
2014-07-21          0.75        ddc8f2e2-3496-8a71-8d1019d2651c",
                 header = T)

Also works with the new data, using a relatively old tidyr version 0.6.3.

df2 = read.table(text = "Date        price_currentday    json_productkey                        pk                 pk_val
    2014-08-06          10          00020e32-3ae8-b7fa-8ecd53a64715        Product_Key_1      00020e32-3ae8-b7fa-8ecd53a64715
    2014-08-06          56          00020e32-3ae8-b7fa-8ecd53a64715        Product_Key_1      00020e32-3ae8-b7fa-8ecd53a64715
    2014-09-15          81          000340b8-9ee5-b2cb-60fb50bacac8        Product_Key_2      000340b8-9ee5-b2cb-60fb50bacac8
    2014-06-04          73          000340b8-9ee5-b2cb-60fb50bacac8        Product_Key_2      000340b8-9ee5-b2cb-60fb50bacac8
    2015-01-19          44          000458f1-1297-a2fd-9304a2fdb6ae        Product_Key_3      000458f1-1297-a2fd-9304a2fdb6ae
    2015-05-23          20          000458f1-1297-a2fd-9304a2fdb6ae        Product_Key_3      000458f1-1297-a2fd-9304a2fdb6ae
    2014-07-21          0.75        ddc8f2e2-3496-8a71-8d1019d2651c        Product_Key_4      ddc8f2e2-3496-8a71-8d1019d2651c",
                 header = T)

tidyr::spread(df2, key = pk, value = pk_val)
#         Date price_currentday                 json_productkey                   Product_Key_1
# 1 2014-06-04            73.00 000340b8-9ee5-b2cb-60fb50bacac8                            <NA>
# 2 2014-07-21             0.75 ddc8f2e2-3496-8a71-8d1019d2651c                            <NA>
# 3 2014-08-06            10.00 00020e32-3ae8-b7fa-8ecd53a64715 00020e32-3ae8-b7fa-8ecd53a64715
# 4 2014-08-06            56.00 00020e32-3ae8-b7fa-8ecd53a64715 00020e32-3ae8-b7fa-8ecd53a64715
# 5 2014-09-15            81.00 000340b8-9ee5-b2cb-60fb50bacac8                            <NA>
# 6 2015-01-19            44.00 000458f1-1297-a2fd-9304a2fdb6ae                            <NA>
# 7 2015-05-23            20.00 000458f1-1297-a2fd-9304a2fdb6ae                            <NA>
#                     Product_Key_2                   Product_Key_3                   Product_Key_4
# 1 000340b8-9ee5-b2cb-60fb50bacac8                            <NA>                            <NA>
# 2                            <NA>                            <NA> ddc8f2e2-3496-8a71-8d1019d2651c
# 3                            <NA>                            <NA>                            <NA>
# 4                            <NA>                            <NA>                            <NA>
# 5 000340b8-9ee5-b2cb-60fb50bacac8                            <NA>                            <NA>
# 6                            <NA> 000458f1-1297-a2fd-9304a2fdb6ae                            <NA>
# 7                            <NA> 000458f1-1297-a2fd-9304a2fdb6ae                            <NA>


问:
Syntax issues in OS detection
I'm working on a script using bash to determine the os being used and print to the screen the version.

The only line giving me issues is this one, could you please help me?:

答:
You can't have spaces between the two sides of the = sign, and you need to execute the right side as a subcommand (using $() syntax).

```<code>current_os=$(cat /etc/*-release | grep CentOS)
</code>```

With spaces like current_os = ... bash will interpret it as you trying to run a command called current_os.

Title: Syntax issues in OS detection

Body:
You can't have spaces between the two sides of the = sign, and you need to execute the right side as a subcommand (using $() syntax).

current_os=$(cat /etc/*-release | grep CentOS)

With spaces like current_os = ... bash will interpret it as you trying to run a command called current_os.


问:
C++ static_cast downcast validity
Is this static_cast downcast valid?

```<code>// non-virtual, may be non-trivially copyable
struct Base{
    int m_object;
};

// Derived class have only non-virtual functions
struct A : Base{
    void arggh(){
        std::cout << "Arrghh " << m_object;
    }
};

int main() {
    Base base{190};
    A& a = static_cast<A&>(base);
    a.arggh();
    return 0;
}
</code>```

I mean, CREATE base class, and then cast to derived.

Live

答:
No.

Not all Base objects are of type A1, although the converse is true, and a static_cast would work in that direction.

1Another translation unit might have a class that inherits from Base.

Title: C++ static_cast downcast validity

Body:
Is this static_cast downcast valid?

// non-virtual, may be non-trivially copyable
struct Base{
    int m_object;
};

// Derived class have only non-virtual functions
struct A : Base{
    void arggh(){
        std::cout << "Arrghh " << m_object;
    }
};

int main() {
    Base base{190};
    A& a = static_cast(base);
    a.arggh();
    return 0;
}

I mean, CREATE base class, and then cast to derived.

Live


问:
.CSV to DataGridView Rows coming up blank in VB.NET
Here is the CSV data I am trying to import into my VB.NET app:

Raw Data

But when I run it through the app it only populates the last row:

Output

Here's the code for the import:

```<code>Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
    DataGridView1.ClearSelection()
    ofd.Filter = "(*csv)|*.csv"
    If ComboBox1.Text = "zVBImportTEST" Then
        If (ofd.ShowDialog() = DialogResult.OK) Then
            txtbxFilePath.Text = ofd.FileName
        End If
        Dim colsexpected As Integer = 6
        Dim thereader As New StreamReader(txtbxFilePath.Text, Encoding.ASCII)
        Dim sline As String = ""
        thereader.ReadLine()
        Do
            sline = thereader.ReadLine
            If sline Is Nothing Then Exit Do
            Dim words() As String = sline.Split(",")
            DataGridView1.Rows.Add("")
            For ix As Integer = 0 To 5
                DataGridView1.Rows(DataGridView1.Rows.Count - 1).Cells(ix).Value = words(ix)
            Next

        Loop
        thereader.Close()
    Else
        MessageBox.Show("Please select a project.", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
    End If
End Sub
</code>```

I can't seem to figure out why the other rows are coming up blank.
If anyone could help me it would be greatly appreciated.

答:
I would not suggest trying to read the data via a StreamReader, instead use the OleDb class while passing the connection string for a CSV file.

Here is a quick example of a function that returns a DataTable based on the contents of the CSV file:

```<code>Private Function ConvertCSVToDataTable(ByVal path As String) As DataTable
    Dim dt As DataTable = New DataTable()
    Using con As OleDb.OleDbConnection = New OleDb.OleDbConnection()
        Try
            con.ConnectionString = String.Format("Provider={0};Data Source={1};Extended Properties=""Text;HDR=YES;FMT=Delimited""", "Microsoft.Jet.OLEDB.4.0", IO.Path.GetDirectoryName(path))
            Using cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM " & IO.Path.GetFileName(path), con)
                Using da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(cmd)
                    con.Open()
                    da.Fill(dt)
                    con.Close()
                End Using
            End Using
        Catch ex As Exception
            Console.WriteLine(ex.ToString())
        Finally
            If con IsNot Nothing AndAlso con.State = ConnectionState.Open Then
                con.Close()
            End If
        End Try
    End Using

    Return dt
End Function
</code>```

Then here is how you'd bind your DataGridView:

```<code>DataGridView1.DataSource = Me.ConvertCSVToDataTable(ofd.FileName)
</code>```

Update

Since you want to specify the data type of the DataColumn, declare a DataTable and assign it to the custom function, but then go in after the fact and change the data type of the specific columns. Here is a quick (free-typed and untested) example:

```<code>Dim csv As DataTable = Me.ConvertCSVToDataTable(ofd.FileName)
With csv.Columns
    .Items(0).DataType = GetType(Int32)
    .Items(1).DataType = GetType(Int32)
    .Items(4).DataType = GetType(Int32)
    .Items(5).DataType = GetType(Int32)
End With

DataGridView1.DataSource = csv
</code>```

Body:
Here is the CSV data I am trying to import into my VB.NET app:

Raw Data

But when I run it through the app it only populates the last row:

Output

Here's the code for the import:

Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
    DataGridView1.ClearSelection()
    ofd.Filter = "(*csv)|*.csv"
    If ComboBox1.Text = "zVBImportTEST" Then
        If (ofd.ShowDialog() = DialogResult.OK) Then
            txtbxFilePath.Text = ofd.FileName
        End If
        Dim colsexpected As Integer = 6
        Dim thereader As New StreamReader(txtbxFilePath.Text, Encoding.ASCII)
        Dim sline As String = ""
        thereader.ReadLine()
        Do
            sline = thereader.ReadLine
            If sline Is Nothing Then Exit Do
            Dim words() As String = sline.Split(",")
            DataGridView1.Rows.Add("")
            For ix As Integer = 0 To 5
                DataGridView1.Rows(DataGridView1.Rows.Count - 1).Cells(ix).Value = words(ix)
            Next

        Loop
        thereader.Close()
    Else
        MessageBox.Show("Please select a project.", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
    End If
End Sub

I can't seem to figure out why the other rows are coming up blank.
If anyone could help me it would be greatly appreciated.

Body:
I would not suggest trying to read the data via a StreamReader, instead use the OleDb class while passing the connection string for a CSV file.

Here is a quick example of a function that returns a DataTable based on the contents of the CSV file:

Private Function ConvertCSVToDataTable(ByVal path As String) As DataTable
    Dim dt As DataTable = New DataTable()
    Using con As OleDb.OleDbConnection = New OleDb.OleDbConnection()
        Try
            con.ConnectionString = String.Format("Provider={0};Data Source={1};Extended Properties=""Text;HDR=YES;FMT=Delimited""", "Microsoft.Jet.OLEDB.4.0", IO.Path.GetDirectoryName(path))
            Using cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM " & IO.Path.GetFileName(path), con)
                Using da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(cmd)
                    con.Open()
                    da.Fill(dt)
                    con.Close()
                End Using
            End Using
        Catch ex As Exception
            Console.WriteLine(ex.ToString())
        Finally
            If con IsNot Nothing AndAlso con.State = ConnectionState.Open Then
                con.Close()
            End If
        End Try
    End Using

    Return dt
End Function

Then here is how you'd bind your DataGridView:

DataGridView1.DataSource = Me.ConvertCSVToDataTable(ofd.FileName)

Update

Since you want to specify the data type of the DataColumn, declare a DataTable and assign it to the custom function, but then go in after the fact and change the data type of the specific columns. Here is a quick (free-typed and untested) example:

Dim csv As DataTable = Me.ConvertCSVToDataTable(ofd.FileName)
With csv.Columns
    .Items(0).DataType = GetType(Int32)
    .Items(1).DataType = GetType(Int32)
    .Items(4).DataType = GetType(Int32)
    .Items(5).DataType = GetType(Int32)
End With

DataGridView1.DataSource = csv


问:
Spring Mongo > How to get list AggregationOperations from Aggregation
I have a function that receive an Aggregation aggregation as a param.

I would like to get all AggregationOperation from aggregation. Is there any way to do it?

```<code>public Aggregation newCustomAggregation(Aggregation aggregation, Criteria c) {
    // How to get list operation aggregation there?
    listOperation.push(Aggregation.match(c));
    return Aggregation
            .newAggregation(listOperations);
}
</code>```

My purpose is new another Aggregation with my custom MatchAggregation.

答:
Short answer: No, there's no GOOD way to do it.

There is no 'easy' way of getting the AggregationOperation list from outside an Aggregation instance - operations is a protected property of Aggregation class.

You could easily get it with reflection but such code would be fragile and expensive to maintain. Probably there's a good reason for this property to remain protected. You could ask about this in Spring-MongoDB's JIRA. I assume that there is an alternative approach to this.

You could of course change your method to take a collection of AggregationOperation as parameter but there's too liitle information in your post to say if this solution is feasible in your case.

Body:
I have a function that receive an Aggregation aggregation as a param.

I would like to get all AggregationOperation from aggregation. Is there any way to do it?

public Aggregation newCustomAggregation(Aggregation aggregation, Criteria c) {
    // How to get list operation aggregation there?
    listOperation.push(Aggregation.match(c));
    return Aggregation
            .newAggregation(listOperations);
}

My purpose is new another Aggregation with my custom MatchAggregation.


问:
How to string format subprocess output?
Below is my nslookup result using subprocess module in Python.

b'Server:  server.internal\r\nAddress:  192.168.0.2\r\n\r\nName:
www.google.com\r\nAddresses:  2404:6800:4007:800::2004\r\n\t
216.58.197.68\r\n\r\n'
```

<p>Could someone please help me to format the result as below.</p>

<pre class="lang-none prettyprint-override"><code>Server: server.internal
Name: www.google.com
DNS:  192.168.0.2
Addresses: 2404:6800:4007:800::2004 , 216.58.197.68
</code>```

答:
You can do it by parsing the lines of the nslookup result into a dictionary, and then using it to format the output.

```<code>nslookup = (b'Server:  server.internal\r\nAddress:  192.168.0.2\r\n\r\n'
            b'Name: www.google.com\r\nAddresses:  2404:6800:4007:800::2004\r\n'
            b'\t216.58.197.68\r\n\r\n')

info = {}
for line in nslookup.decode().splitlines():
    tokens = line.split()
    if len(tokens) == 2:
        if tokens[0] == 'Addresses:':
            info.setdefault('Addresses', []).append(tokens[1])  # Without ":"
        else:
            info[tokens[0].rstrip(':')] = tokens[1]
    elif len(tokens) == 1:
        info['Addresses'].append(tokens[0])

info['Addresses'] = ', '.join(info['Addresses'])  # Format and convert to string.

print('''\
Server: {Server}
Name: {Name}
DNS:  {Address}
Addresses: {Addresses}'''.format(**info))
</code>```

Output:

Server: server.internal
Name: www.google.com
DNS:  192.168.0.2
Addresses: 2404:6800:4007:800::2004, 216.58.197.68
```

Title: How to string format subprocess output?

Body:
Below is my nslookup result using subprocess module in Python.

b'Server:  server.internal\r\nAddress:  192.168.0.2\r\n\r\nName:
www.google.com\r\nAddresses:  2404:6800:4007:800::2004\r\n\t
216.58.197.68\r\n\r\n'

Could someone please help me to format the result as below.

Server: server.internal
Name: www.google.com
DNS:  192.168.0.2
Addresses: 2404:6800:4007:800::2004 , 216.58.197.68

Body:
You can do it by parsing the lines of the nslookup result into a dictionary, and then using it to format the output.

nslookup = (b'Server:  server.internal\r\nAddress:  192.168.0.2\r\n\r\n'
            b'Name: www.google.com\r\nAddresses:  2404:6800:4007:800::2004\r\n'
            b'\t216.58.197.68\r\n\r\n')

info = {}
for line in nslookup.decode().splitlines():
    tokens = line.split()
    if len(tokens) == 2:
        if tokens[0] == 'Addresses:':
            info.setdefault('Addresses', []).append(tokens[1])  # Without ":"
        else:
            info[tokens[0].rstrip(':')] = tokens[1]
    elif len(tokens) == 1:
        info['Addresses'].append(tokens[0])

info['Addresses'] = ', '.join(info['Addresses'])  # Format and convert to string.

print('''\
Server: {Server}
Name: {Name}
DNS:  {Address}
Addresses: {Addresses}'''.format(**info))

Output:

Server: server.internal
Name: www.google.com
DNS:  192.168.0.2
Addresses: 2404:6800:4007:800::2004, 216.58.197.68


问:
Jenkins for monitoring application in prod
While I'm interested in Jenkins as a means to provide continuous build functionality, I'm really even more interested in Jenkins as a means to exercise my application in its prod environment against unexpected changes in infrastructure beyond my control that may effect my application.  I can't find a ton of information on using Jenkins in this way, but I was wondering if there are others out there doing this?  Essentially I have a project that runs maven test parametized with my prod url, but for these projects I don't actually do any building.  Are there other tools besides Jenkins I should be considering to do this?  If so, why?

答:
Jenkins Provides a plugin called Status Monitor Plugin

We have ours set to check a specific URL every 5 mins and email us when something fails. Our problem is that it won't sent emails to cell phone carrier email addresses. However, if regular email will suffice, the setup time for a plugin is less than a half hour and it is reliable as long as the Jenkins server stays up.


问:
Copying Character array into char array
Hi I want to fast copy array of Characters to array of chars I can write a method that copies Character array into char array, by converting every Charater in array to char but is there any ready method which is faster just as Arrays.copyOf for two arrays of same type?

答:
Technical not possible, but you might do with a lazy kind of unboxing Character to char. For instance using a Stream. (Which at the moment might even be additional overhead.)

If the Character array stems from a Collection, a List, then you just might take measures at the source. Though all will not be fast. But an array of Character is not sophisticated, like wrapping every coin in its own piece of paper.

Title: Copying Character array into char array


问:
Selecting path, changing opacity based on legend mouseover
This, I think, is basically a selection question.

Here's my semi-working Plunker.

I'm trying to select a path, and change the opacity of all paths within a chart that are not selected, based on a mouseover of the respective graphic element (a circle) in the chart's legend.

I've set the id of the paths such they'll have the same id as the circles that are activated on mouseover. I've also gotten the circles that are not selected on hover to change opacity. (Currently, however, all of the non-selected circles, in all of the legends, across all of the charts, change opacity. I'm trying to limit mouseover opacity changes to only the relevant chart.)

What I'm trying to achieve:

When I mouseover a circle in the legend of a given chart, the same opacity changes should be applied to the paths of that chart, as if I had hovered over the paths themselves. If I understand my problem correctly, I'm having trouble defining the selection/non-selection of the circles and their respective paths, and limiting those selections to only one chart out of several on the page.

Here's how the paths' groups and ids are defined:

```<code>  var pathGroup = main.append('g').classed('paths', true);
  var paths = pathGroup.selectAll("path")
    .data(dataset)
    .enter()
    .append("path")
    .attr("id", function(d) {
      return d.record
    })
    .attr("data-legend", function(d) {
      return d.record
    })
</code>```

And here's the problematic code, I think:

```<code>  li.selectAll("circle")
    .attr("id",function (d) {return d.key})
    .style("fill",function(d) { return d.value.color})
        .on("mouseover", function(d) {
    // need to define "circleGroup" and "circles" (as is done for "pathGroup" and "paths") so that the legend's non-selected circles are the ones that fade)
    // also need to find a way of limiting "circles" to a circle group within only that state's chart
    //          circles
          d3.selectAll('circle:not(this)')
          .style('opacity', 0.4)
          .style('transition', "opacity 0.1s")
        d3.select(this)
          .classed('hover', true)
          .style('opacity', 0.9)
          .style('transition', "opacity 0.1s")

  d3.select('path:not(this)')
    .style('opacity', 0.4)
    .style('transition', "opacity 0.1s")
  //      d3.select('path data-legend',  function(d) { return d.key})
  d3.select('path id',  function(d) { return d.key})
    .classed('hover', true)
    .style('opacity', 0.9)
    .style('transition', "opacity 0.1s")
  })
      .on('mouseout', function(d) {
        d3.selectAll('circle')
          .style('opacity', 0.9)
          .style('transition', "opacity 0.1s")
      })
</code>```

Here, again, is my semi-working Plunker: http://plnkr.co/edit/mvdqBPMymCt9VAKAPKD1?p=preview

In advance, thanks for any help you can offer in setting this right.

答:
Issues with your code:

d3.selectAll('circle')
  selects all the circles in the body and as far as the paths are concerned:

d3.select('path id') wouldn't work as the selector itself is messed up here. Try console logging the selection here.

Option 1:

Try replacing the legend mouse events with the following code:

```<code>.on("mouseover", function(d) {
    // look for all the circles within the parent node
    d3.select(this.parentNode).selectAll('circle').style('opacity', 0.4);

    // change opacity of current circle
    d3.select(this).style('opacity', 0.9);

    // use parentNode to go until SVG and select all paths
    d3.select(this.parentNode.parentNode.parentNode).select('g.paths').selectAll('path').style('opacity', 0.4);

    // change opacity of path with data-legend = key
    d3.select(this.parentNode.parentNode.parentNode).select('g.paths').selectAll('path[data-legend="'+d.key+'"]').style('opacity', 0.9);
 })
.on('mouseout', function(d) {
  // change all circles' and paths' opacity back to original values
    d3.select(this.parentNode).selectAll('circle').style('opacity', 0.9);
    d3.select(this.parentNode.parentNode.parentNode).select('g.paths').selectAll('path').style('opacity', 0.9);
});
</code>```

I hope the comments are clear enough to understand the code. Just parsing through the parentNodes.

Option 2:

Add a class/id to the legend group representing the "state" i.e. Alabama, California etc.

And search for the SVG with selectedState on every mouseover and change the paths' opacity.

Hope this helps. :)

Body:
This, I think, is basically a selection question.

Here's my semi-working Plunker.

I'm trying to select a path, and change the opacity of all paths within a chart that are not selected, based on a mouseover of the respective graphic element (a circle) in the chart's legend.

I've set the id of the paths such they'll have the same id as the circles that are activated on mouseover. I've also gotten the circles that are not selected on hover to change opacity. (Currently, however, all of the non-selected circles, in all of the legends, across all of the charts, change opacity. I'm trying to limit mouseover opacity changes to only the relevant chart.)

What I'm trying to achieve:

When I mouseover a circle in the legend of a given chart, the same opacity changes should be applied to the paths of that chart, as if I had hovered over the paths themselves. If I understand my problem correctly, I'm having trouble defining the selection/non-selection of the circles and their respective paths, and limiting those selections to only one chart out of several on the page.

Here's how the paths' groups and ids are defined:

  var pathGroup = main.append('g').classed('paths', true);
  var paths = pathGroup.selectAll("path")
    .data(dataset)
    .enter()
    .append("path")
    .attr("id", function(d) {
      return d.record
    })
    .attr("data-legend", function(d) {
      return d.record
    })

And here's the problematic code, I think:

  li.selectAll("circle")
    .attr("id",function (d) {return d.key})
    .style("fill",function(d) { return d.value.color})
        .on("mouseover", function(d) {
    // need to define "circleGroup" and "circles" (as is done for "pathGroup" and "paths") so that the legend's non-selected circles are the ones that fade)
    // also need to find a way of limiting "circles" to a circle group within only that state's chart
    //          circles
          d3.selectAll('circle:not(this)')
          .style('opacity', 0.4)
          .style('transition', "opacity 0.1s")
        d3.select(this)
          .classed('hover', true)
          .style('opacity', 0.9)
          .style('transition', "opacity 0.1s")

  d3.select('path:not(this)')
    .style('opacity', 0.4)
    .style('transition', "opacity 0.1s")
  //      d3.select('path data-legend',  function(d) { return d.key})
  d3.select('path id',  function(d) { return d.key})
    .classed('hover', true)
    .style('opacity', 0.9)
    .style('transition', "opacity 0.1s")
  })
      .on('mouseout', function(d) {
        d3.selectAll('circle')
          .style('opacity', 0.9)
          .style('transition', "opacity 0.1s")
      })

Here, again, is my semi-working Plunker: http://plnkr.co/edit/mvdqBPMymCt9VAKAPKD1?p=preview

In advance, thanks for any help you can offer in setting this right.

Body:
Issues with your code:

d3.selectAll('circle')
  selects all the circles in the body and as far as the paths are concerned:

d3.select('path id') wouldn't work as the selector itself is messed up here. Try console logging the selection here.

Option 1:

Try replacing the legend mouse events with the following code:

.on("mouseover", function(d) {
    // look for all the circles within the parent node
    d3.select(this.parentNode).selectAll('circle').style('opacity', 0.4);

    // change opacity of current circle
    d3.select(this).style('opacity', 0.9);

    // use parentNode to go until SVG and select all paths
    d3.select(this.parentNode.parentNode.parentNode).select('g.paths').selectAll('path').style('opacity', 0.4);

    // change opacity of path with data-legend = key
    d3.select(this.parentNode.parentNode.parentNode).select('g.paths').selectAll('path[data-legend="'+d.key+'"]').style('opacity', 0.9);
 })
.on('mouseout', function(d) {
  // change all circles' and paths' opacity back to original values
    d3.select(this.parentNode).selectAll('circle').style('opacity', 0.9);
    d3.select(this.parentNode.parentNode.parentNode).select('g.paths').selectAll('path').style('opacity', 0.9);
});

I hope the comments are clear enough to understand the code. Just parsing through the parentNodes.

Option 2:

Add a class/id to the legend group representing the "state" i.e. Alabama, California etc.

And search for the SVG with selectedState on every mouseover and change the paths' opacity.

Hope this helps. :)


问:
why php-slim api route is not throwing any error despite email is not being sent
Hi i'm in a situation where i'm unable to send email from PHP-Slim  with PHP Mailer.

this is the my get url => http://localhost/PHP-Slim-Restful/api/sendMail

i'm not getting any kind of error even though my email is not sent.

below is my postman screen shot

RELIEF FOR ME: i'm able to login but failing to send email

```<code><?php
require 'config.php';
require 'Slim/Slim.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();

$app->post('/login','login'); /* User login */
$app->get('sendMail','sendMail');  /* send Email */

$app->run();

/************************* USER LOGIN *************************************/
/* ### User login ### */
function login() {
      // Code for login API route, it is there with slim api folder
 }

/* ### send email test ### */

function sendMail()
{

    // below credential is my actual mailtrap credential

    $mail = new PHPMailer(true);
try {
    //Server settings
    $mail->SMTPDebug = 2;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.mailtrap.io';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = '1fd562fc56d940';                 // SMTP username
    $mail->Password = 'af5ec48a984df1';                           // SMTP password
    $mail->SMTPSecure = 'PLAIN';                          // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 2525;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('from@example.com', 'Mailer');
    $mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient
    // $mail->addAddress('ellen@example.com');               // Name is optional
    // $mail->addReplyTo('info@example.com', 'Information');
    // $mail->addCC('cc@example.com');
    // $mail->addBCC('bcc@example.com');

    //Attachments
    // $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    // $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    //Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
}

}

?>
</code>```

below is my whole project folder with mailtrap email credentials

(DROPBOX Link) : https://www.dropbox.com/s/rrl8j198nd1rfqh/PHP-Slim-Restful.zip?dl=0

please use the above dropbox link of my project.

I think my API route is not hitting the function but i'm able to hit login route why?.

Even echo "hello world" is not displaying. i think postman is not hitting the route?why

答:
You missed out somethings..
add the following </p>

```<code>$mailer->isSMTP();
$mailer->SMTPDebug = 2;
$mailer->Debugoutput = 'html';
$mailer->SMTPOptions = array(
    'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    )
);
</code>```

Body:
Hi i'm in a situation where i'm unable to send email from PHP-Slim  with PHP Mailer.

this is the my get url => http://localhost/PHP-Slim-Restful/api/sendMail

i'm not getting any kind of error even though my email is not sent.

below is my postman screen shot

RELIEF FOR ME: i'm able to login but failing to send email

<?php
require 'config.php';
require 'Slim/Slim.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();

$app->post('/login','login'); /* User login */
$app->get('sendMail','sendMail');  /* send Email */

$app->run();

/************************* USER LOGIN *************************************/
/* ### User login ### */
function login() {
      // Code for login API route, it is there with slim api folder
 }

/* ### send email test ### */

function sendMail()
{

    // below credential is my actual mailtrap credential

    $mail = new PHPMailer(true);
try {
    //Server settings
    $mail->SMTPDebug = 2;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.mailtrap.io';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = '1fd562fc56d940';                 // SMTP username
    $mail->Password = 'af5ec48a984df1';                           // SMTP password
    $mail->SMTPSecure = 'PLAIN';                          // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 2525;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('from@example.com', 'Mailer');
    $mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient
    // $mail->addAddress('ellen@example.com');               // Name is optional
    // $mail->addReplyTo('info@example.com', 'Information');
    // $mail->addCC('cc@example.com');
    // $mail->addBCC('bcc@example.com');

    //Attachments
    // $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    // $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    //Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body in bold!';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
}

}

?>

below is my whole project folder with mailtrap email credentials

(DROPBOX Link) : https://www.dropbox.com/s/rrl8j198nd1rfqh/PHP-Slim-Restful.zip?dl=0

please use the above dropbox link of my project.

I think my API route is not hitting the function but i'm able to hit login route why?.

Even echo "hello world" is not displaying. i think postman is not hitting the route?why

Body:
You missed out somethings..
add the following

$mailer->isSMTP();
$mailer->SMTPDebug = 2;
$mailer->Debugoutput = 'html';
$mailer->SMTPOptions = array(
    'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    )
);