问:
How to make the content smaller to connect with the footer?
I have a big empty space between the website content and the footer, can someone help me to get this space out and make the content connect the footer?</p>

答: You have few empty paragraph under .wonderplugincarousel-container and big margin-bottom in few divs


来源: stackexchange

问:
Stored Procedures and updating EDMX
I have had endless issues with stored procedures and EDMX. I created a procedure, updated the model from the database, and all worked. I then removed a column and added a new one in the stored procedure. I updated the model, but the EDMX didn't seem to refresh the proc definition.

I dropped the proc, and did an update, but manually had to delete all references to the proc. I ended up just renaming the proc and importing via model update from database.

I just had the same issue. Added a new column, and renamed an existing column. I refreshed the EDMX via update model from database, but there were no changes to the EDMX, and obviously at run time, it fails. How should a stored procedure update be done with Entity Framework?

I removed the proc, regenerated the model, deleted the 'cs' files for the proc, compiled, then added the procedure to the database again, regenerated the model, and bang! It adds the same model 3 times, with only the last one being right. Why does it keep bringing back the old versions?

答:
First of all do refresh your SP through "Update Model from Database", if it is working, fine, if not and throwing the same exception then do follow the steps given below.
1.Double Click on .edmx file.
2. In Model Browser, Delete SP from Complex Types, Function Imports and Stored Procedures/Functions.
3. Save All.
4.Add again your SP through "Update Model from Database".
5.Save All.</p>

ContentLicense: CC BY-SA 3.0

Title: Stored Procedures and updating EDMX


问:
Bad Request accessing Web API from Xamarin.Forms
Here, I explain my scenario -
I have 2 projects - API (storing the Web API) and APP (storing the Xamarin.Forms). I have used EDMX to create Data models from my database in the API project in API.Models folder. I want to access the API from the APP project and hence have created similar data model classes in my APP project. Things work fine when there are no Foreign Keys present in the model class. As soon as a Foreign Key is added to any of the model classes in API project, consuming the API starts giving me a "Bad Request error"

API.Models Code

```<code>namespace API.Models
{
    using System;
    using System.Collections.Generic;

public partial class Lead
{
    public int ID { get; set; }
    public string LeadName { get; set; }
    public Nullable<decimal> AssignedTo { get; set; }
    public virtual User User1 { get; set; } //User is another entity in API.Models
    }
}
</code>```

APP.Models Code

```<code>namespace APP.Models
{
    using System;
    using System.Collections.Generic;

public partial class Lead
{
    public int ID { get; set; }
    public string LeadName { get; set; }
    public Nullable<decimal> AssignedTo { get; set; }
    public virtual User User1 { get; set; }  //User is another entity in APP.Models
    }
}
</code>```

API Code

```<code>namespace APIProject.API
{
    public class IssueLogController : ApiController
    {
        CRMEntities db = new CRMEntities();

        [ResponseType(typeof(Lead))]
        public async Task<IHttpActionResult> PostLead(Lead lead)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Lead.Add(lead);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (LeadExists(lead.ID))
                {
                    return Conflict();
                }
                else
                {
                    throw;
                }
            }
            return CreatedAtRoute("DefaultApi", new { id = lead.ID }, lead);
        }

    }
}
</code>```

Xamarin.Forms code

```<code>Lead lead = new Lead();
            lead.LeadName = txtLead.Text.Trim();

        var uri = Constants.URL + "Lead/PostLead/";
        HttpClient client = new HttpClient(new NativeMessageHandler());

        var s = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat };
        var json = JsonConvert.SerializeObject(lead, s);
        var content = new StringContent(json, Encoding.UTF8, "application/json");

        var response = await client.PostAsync(uri, content);
        if (response.IsSuccessStatusCode)
        {
            await DisplayAlert("Message", "Your Lead has been recorded.", "OK");
        }
</code>```

Any ideas to resolve this?

答:
As mentioned by @Gerald in comments above, here is what I did in the API code to figure out the error - </p>

```<code> if (!ModelState.IsValid)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var state in ModelState)
            {
                foreach (var error in state.Value.Errors)
                {
                    sb.AppendLine(error.ErrorMessage);
                }
            }
            t_app_issueLog.ID = 1;
            t_app_issueLog.Problem = sb.ToString();
            return CreatedAtRoute("DefaultApi", new { id = lead.ID }, lead);
            //return BadRequest(ModelState);
        }
</code>```

Body:
Here, I explain my scenario -
I have 2 projects - API (storing the Web API) and APP (storing the Xamarin.Forms). I have used EDMX to create Data models from my database in the API project in API.Models folder. I want to access the API from the APP project and hence have created similar data model classes in my APP project. Things work fine when there are no Foreign Keys present in the model class. As soon as a Foreign Key is added to any of the model classes in API project, consuming the API starts giving me a "Bad Request error"

API.Models Code

namespace API.Models
{
    using System;
    using System.Collections.Generic;

public partial class Lead
{
    public int ID { get; set; }
    public string LeadName { get; set; }
    public Nullable<decimal> AssignedTo { get; set; }
    public virtual User User1 { get; set; } //User is another entity in API.Models
    }
}

APP.Models Code

namespace APP.Models
{
    using System;
    using System.Collections.Generic;

public partial class Lead
{
    public int ID { get; set; }
    public string LeadName { get; set; }
    public Nullable<decimal> AssignedTo { get; set; }
    public virtual User User1 { get; set; }  //User is another entity in APP.Models
    }
}

API Code

namespace APIProject.API
{
    public class IssueLogController : ApiController
    {
        CRMEntities db = new CRMEntities();

        [ResponseType(typeof(Lead))]
        public async Task<IHttpActionResult> PostLead(Lead lead)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Lead.Add(lead);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (LeadExists(lead.ID))
                {
                    return Conflict();
                }
                else
                {
                    throw;
                }
            }
            return CreatedAtRoute("DefaultApi", new { id = lead.ID }, lead);
        }

    }
}

Xamarin.Forms code

Lead lead = new Lead();
            lead.LeadName = txtLead.Text.Trim();

        var uri = Constants.URL + "Lead/PostLead/";
        HttpClient client = new HttpClient(new NativeMessageHandler());

        var s = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat };
        var json = JsonConvert.SerializeObject(lead, s);
        var content = new StringContent(json, Encoding.UTF8, "application/json");

        var response = await client.PostAsync(uri, content);
        if (response.IsSuccessStatusCode)
        {
            await DisplayAlert("Message", "Your Lead has been recorded.", "OK");
        }

Any ideas to resolve this?

Body:
As mentioned by @Gerald in comments above, here is what I did in the API code to figure out the error -

 if (!ModelState.IsValid)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var state in ModelState)
            {
                foreach (var error in state.Value.Errors)
                {
                    sb.AppendLine(error.ErrorMessage);
                }
            }
            t_app_issueLog.ID = 1;
            t_app_issueLog.Problem = sb.ToString();
            return CreatedAtRoute("DefaultApi", new { id = lead.ID }, lead);
            //return BadRequest(ModelState);
        }


问:
default methods in interface but only static final fields
I understand that all fields in an Inteface is implicitly static and final. And this made sense before Java 8.

But with the introduction of default methods, interfaces also have all the capabilities of an abstract class. And hence non-static and non-final fields are also necessary.

But when I tried declaring a field normally, it became static and final by default.

Is there a way to declare a non-static and non-final field in Interface in Java 8.

Or am I totally misunderstanding something here???

答:
No - In java 8 you can't have not public static final fields in interfaces, unfortunately.

But I hope in the future this will be added to the language.

Scala allows interface with not static fields, and this opens up so many more possibilities for code reuse and composition than available in Java 8

ContentLicense: CC BY-SA 4.0


问:
Specflow with Autofac - Unable to load TechTak.Specflow.Infrastructre.IBindingInstanceResolver Version=2.2.0.0
I have a project that uses Autofac for constructor level injection. For every service instance, repositories are injected to constructor.
Now to start using SpecFlow for the project I am not able to instantiate the service for method calls. I have already added Specflow.Autofac plugin but now I am getting following error. I have checked all referenced assemblies versions and those are correct.

答:
I think you are using SpecFlow.Autofac. Is this correct?
If so, it doesn't work with SpecFlow 2.2 at the moment.

For details have a look at this issue: https://github.com/techtalk/SpecFlow/issues/959


问:
Two nested for with several statements under each in python
I am new in python. I want to write two "for" where each of the has many statements under it. I cannot find how I should differentiate these statement from each other? I need a code like this in python. I appreciate if any one can help.</p>

```<code> for(i=1,i<10,i++){
      statement 1;
      statement 2;
      for(j=1,j<5,j++){
           statement 1;
           statement 1;
      }
      statement 3;
      statement 4;
    }
</code>```

答:
One of the most distinctive features of Python is its use of indentation to mark blocks of code. For example:

```<code>if pwd == 'apple':
    print('Logging on ...')
else:
    print('Incorrect password.')

print('All done!')
</code>```

So your pseudocode will be written like this in python.

```<code>for i in range(1, 11):
    statement 1
    statement 2
    for j in range(1, 6):
        statement 1
        statement 2
    statement 3
    statement 4
</code>```

Body:
I am new in python. I want to write two "for" where each of the has many statements under it. I cannot find how I should differentiate these statement from each other? I need a code like this in python. I appreciate if any one can help.

 for(i=1,i<10,i++){
      statement 1;
      statement 2;
      for(j=1,j<5,j++){
           statement 1;
           statement 1;
      }
      statement 3;
      statement 4;
    }

Body:
One of the most distinctive features of Python is its use of indentation to mark blocks of code. For example:

if pwd == 'apple':
    print('Logging on ...')
else:
    print('Incorrect password.')

print('All done!')

So your pseudocode will be written like this in python.

for i in range(1, 11):
    statement 1
    statement 2
    for j in range(1, 6):
        statement 1
        statement 2
    statement 3
    statement 4


问:
React Native Firebase write user data after account creation
I'm currently working with Firebase and React Native I have come to a slight problem.

Reading the documentation for the: createUserWithEmailAndPassword:

On successful creation of the user account, this user will also be signed in to your application.

I was trying to work with the promise as follows:

```<code>firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password)
.then(function(authData){
    this.writeUserData(authData.uid);
}).catch(function(error){
    console.warn(error)
});
</code>```

And my writeUserData() method:

```<code>writeUserData(the_uid) {
    console.warn("Writting data ")
    var today = new Date();
    firebase.database().ref('users/' + authData.uid + '/').set({
        name: this.state.name,
        birthday: this.state.date,
        email: this.state.email,
        registered: today
    });
}
</code>```

In the function however the console.warn is never fired hence the event isn't fired since the user is automatically logged in.

Problem: The .then isn't executed since user is logged in straight away.

Goal: Be able to add the user information (name, birthday, etc) after user creation before sign in.

答:
what i have understand is that you are trying to push (name ,birthday , etc ) to firebase , well with my little experience using firebase , you have to call {firebase.database().ref().child('your path')} to create a path first , then use the push()  , exemple :

{ var ref = firebaseRef.database().ref().child('Clients');
        var ref = ref.push(this.state.username); }

well i m newbie , but this worked for me , hope it help you

Body:
I'm currently working with Firebase and React Native I have come to a slight problem.

Reading the documentation for the: createUserWithEmailAndPassword:

On successful creation of the user account, this user will also be signed in to your application.

I was trying to work with the promise as follows:

firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password)
.then(function(authData){
    this.writeUserData(authData.uid);
}).catch(function(error){
    console.warn(error)
});

And my writeUserData() method:

writeUserData(the_uid) {
    console.warn("Writting data ")
    var today = new Date();
    firebase.database().ref('users/' + authData.uid + '/').set({
        name: this.state.name,
        birthday: this.state.date,
        email: this.state.email,
        registered: today
    });
}

In the function however the console.warn is never fired hence the event isn't fired since the user is automatically logged in.

Problem: The .then isn't executed since user is logged in straight away.

Goal: Be able to add the user information (name, birthday, etc) after user creation before sign in.


问:
Comparing 2 lists (nested with normal)
Compare two lists:

```<code>abc=[[a,b],[c],[x,y,z]]
pqr=[a,b,x,y,z]
</code>```

Print the matched strings.

I want the output to be like:

```<code>z=[a,b,x,y,z]
</code>```

答:
You can try, this also

```<code>from itertools import chain

abc=[['a','b'],['c'],['x','y','z','k']]
pqr = ['a','b','x','y','z','k','l']
result=[x for x in pqr if x in list(chain.from_iterable(abc))]
print result
</code>```

Output

```<code>['a', 'b', 'x', 'y', 'z', 'k']
</code>```

Title: Comparing 2 lists (nested with normal)

Body:
Compare two lists:

abc=[[a,b],[c],[x,y,z]]
pqr=[a,b,x,y,z]

Print the matched strings.

I want the output to be like:

z=[a,b,x,y,z]

Body:
You can try, this also

from itertools import chain

abc=[['a','b'],['c'],['x','y','z','k']]
pqr = ['a','b','x','y','z','k','l']
result=[x for x in pqr if x in list(chain.from_iterable(abc))]
print result

Output

['a', 'b', 'x', 'y', 'z', 'k']


问:
Laravel 4 ReflectionException on DI
I am working on a code as a new developer and after long refactoring I got one error that is bugging me. One method id erroring out, and it is throwing a ReflectionException: Class does not exist. The error is thrown in this line:

```<code>$shippingService = App::make('ShippingServiceInterface');
</code>```

The actual class does of course exist. I've tried running composer dump-autoload, and halting and bringing up vagrant machine up again but no avail.

Interface itself has two methods and is namespaced.

Folder structure is different than regular Laravel app in a way that everything is stored in a lib folder which is autoloaded completely through composer.json.

Any ideas how can I track this issue down?

EDIT:

I tried adding it to an existing service provider and then running dump-autoload, but still the same.

EDIT 2:

Even stranger thing is that in autoload_classmap.php I see the class being loaded after running dump-autoload

答: I found the error being actually that the interface which was injected didn't have any object which implemented it, thus no concrete class could actually be injected. </p>

Title: Laravel 4 ReflectionException on DI

Body:
I am working on a code as a new developer and after long refactoring I got one error that is bugging me. One method id erroring out, and it is throwing a ReflectionException: Class does not exist. The error is thrown in this line:

$shippingService = App::make('ShippingServiceInterface');

The actual class does of course exist. I've tried running composer dump-autoload, and halting and bringing up vagrant machine up again but no avail.

Interface itself has two methods and is namespaced.

Folder structure is different than regular Laravel app in a way that everything is stored in a lib folder which is autoloaded completely through composer.json.

Any ideas how can I track this issue down?

EDIT:

I tried adding it to an existing service provider and then running dump-autoload, but still the same.

EDIT 2:

Even stranger thing is that in autoload_classmap.php I see the class being loaded after running dump-autoload


问:
How can I see a diff between merge commit and what would be an automatic merge of the same parents?
I have a couple of bad merges in history (due to human error). I want a quick way to find out if I have more like these. In order to automate it, I want to see, for every merge commit, the difference between as if the merge would be performed automatically (with a given conflict resolution strategy) and what actually happened in a given merge.

How can I do it?

答:
You must make that automatic merge.

To do so, check out one of the two parents of the suspect merge, giving yourself a "detached HEAD" in the process.  If $suspect_merge contains a suitable name for the suspect merge (e.g., a hash ID):

```<code>git checkout $suspect_merge^1
</code>```

Then, run git merge on the other of the two parents:

```<code>git merge [options] $suspect_merge^2
</code>```

The merge will either finish and make a new commit on your detached HEAD, or fail due to conflicts.  If it fails, you can finish it manually and correctly, and then commit.

Now you have a good merge that you can compare to the suspect merge:

```<code>git diff $suspect_merge HEAD
</code>```

When you git checkout any named branch, the merge you just made on the detached HEAD is abandoned.  It will eventually (typically some time after 30 days, when its reflog entry expires) be garbage collected.  To keep it around, give it a name: a branch or tag name works well.

Body:
You must make that automatic merge.

To do so, check out one of the two parents of the suspect merge, giving yourself a "detached HEAD" in the process.  If $suspect_merge contains a suitable name for the suspect merge (e.g., a hash ID):

git checkout $suspect_merge^1

Then, run git merge on the other of the two parents:

git merge [options] $suspect_merge^2

The merge will either finish and make a new commit on your detached HEAD, or fail due to conflicts.  If it fails, you can finish it manually and correctly, and then commit.

Now you have a good merge that you can compare to the suspect merge:

git diff $suspect_merge HEAD

When you git checkout any named branch, the merge you just made on the detached HEAD is abandoned.  It will eventually (typically some time after 30 days, when its reflog entry expires) be garbage collected.  To keep it around, give it a name: a branch or tag name works well.


问:
WPF Context menu doesn't bind to right databound item
I have a problem when binding a command in a context menu on a usercontrol that is on a tab page.
The first time I use the menu (right-click on the tab) it works great, but if I switch tab the command will use the databound instance that was used the first time.

If I put a button that is bound to the command in the usercontrol it works as expected...

Can someone please tell me what I'm doing wrong??

This is a test project that exposes the problem:

App.xaml.cs:

```<code>public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        CompanyViewModel model = new CompanyViewModel();
        Window1 window = new Window1();
        window.DataContext = model;
        window.Show();
    }
}
</code>```

Window1.xaml:

```<code><Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:vw="clr-namespace:WpfApplication1"
Title="Window1" Height="300" Width="300">

  <Window.Resources>
    <DataTemplate x:Key="HeaderTemplate">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding Path=Name}" />
        </StackPanel>
    </DataTemplate>
    <DataTemplate DataType="{x:Type vw:PersonViewModel}">
        <vw:UserControl1/>
    </DataTemplate>

</Window.Resources>
<Grid>
    <TabControl ItemsSource="{Binding Path=Persons}"
                ItemTemplate="{StaticResource HeaderTemplate}"
                IsSynchronizedWithCurrentItem="True" />
</Grid>
</Window>
</code>```

UserControl1.xaml:

```<code><UserControl x:Class="WpfApplication1.UserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    MinWidth="200">
    <UserControl.ContextMenu>
        <ContextMenu >
            <MenuItem Header="Change" Command="{Binding Path=ChangeCommand}"/>
        </ContextMenu>
    </UserControl.ContextMenu>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="100" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Label Grid.Column="0">The name:</Label>
        <TextBox Grid.Column="1" Text="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged}" />
    </Grid>
</UserControl>
</code>```

CompanyViewModel.cs:

```<code>public class CompanyViewModel
{
    public ObservableCollection<PersonViewModel> Persons { get; set; }
    public CompanyViewModel()
    {
        Persons = new ObservableCollection<PersonViewModel>();
        Persons.Add(new PersonViewModel(new Person { Name = "Kalle" }));
        Persons.Add(new PersonViewModel(new Person { Name = "Nisse" }));
        Persons.Add(new PersonViewModel(new Person { Name = "Jocke" }));
    }
}
</code>```

PersonViewModel.cs:

```<code>public class PersonViewModel : INotifyPropertyChanged
{
    Person _person;
    TestCommand _testCommand;

    public PersonViewModel(Person person)
    {
        _person = person;
        _testCommand = new TestCommand(this);
    }
    public ICommand ChangeCommand
    {
        get
        {
            return _testCommand;
        }
    }
    public string Name
    {
        get
        {
            return _person.Name;
        }
        set
        {
            if (value == _person.Name)
                return;
            _person.Name = value;
            OnPropertyChanged("Name");
        }
    }
    void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = this.PropertyChanged;
        if (handler != null)
        {
            var e = new PropertyChangedEventArgs(propertyName);
            handler(this, e);
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
}
</code>```

TestCommand.cs:

```<code>public class TestCommand : ICommand
{
    PersonViewModel _person;
    public event EventHandler CanExecuteChanged;

    public TestCommand(PersonViewModel person)
    {
        _person = person;
    }
    public bool CanExecute(object parameter)
    {
        return true;
    }
    public void Execute(object parameter)
    {
        _person.Name = "Changed by command";
    }
}
</code>```

Person.cs:

```<code>public class Person
{
    public string Name { get; set; }
}
</code>```

答:
I know this is already an old post, but I would like to add another solution for those one who are looking for different ways to do it.

I could not make the same solution to work in my case, since I was trying to do something else: open the context menu with a mouse click (just like a toolbar with a submenu attached to it) and also bind commands to my model. Since I was using an Event Trigger, the PlacementTarget object was null.

This is the solution I found to make it work only using XAML:

```<code><!-- This is an example with a button, but could be other control -->
<Button>
  <...>

  <!-- This opens the context menu and binds the data context to it -->
  <Button.Triggers>
    <EventTrigger RoutedEvent="Button.Click">
      <EventTrigger.Actions>
        <BeginStoryboard>
          <Storyboard>
            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="ContextMenu.DataContext">
              <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{Binding}"/>
            </ObjectAnimationUsingKeyFrames>
            <BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="ContextMenu.IsOpen">
              <DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True"/>
            </BooleanAnimationUsingKeyFrames>
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger.Actions>
    </EventTrigger>
  </Button.Triggers>

  <!-- Here it goes the context menu -->
  <Button.ContextMenu>
    <ContextMenu>
      <MenuItem Header="Item 1" Command="{Binding MyCommand1}"/>
      <MenuItem Header="Item 2" Command="{Binding MyCommand2}"/>
    </ContextMenu>
  </Button.ContextMenu>

</Button>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a problem when binding a command in a context menu on a usercontrol that is on a tab page.
The first time I use the menu (right-click on the tab) it works great, but if I switch tab the command will use the databound instance that was used the first time.

If I put a button that is bound to the command in the usercontrol it works as expected...

Can someone please tell me what I'm doing wrong??

This is a test project that exposes the problem:

App.xaml.cs:

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        CompanyViewModel model = new CompanyViewModel();
        Window1 window = new Window1();
        window.DataContext = model;
        window.Show();
    }
}

Window1.xaml:

<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:vw="clr-namespace:WpfApplication1"
Title="Window1" Height="300" Width="300">

  <Window.Resources>
    <DataTemplate x:Key="HeaderTemplate">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding Path=Name}" />
        </StackPanel>
    </DataTemplate>
    <DataTemplate DataType="{x:Type vw:PersonViewModel}">
        <vw:UserControl1/>
    </DataTemplate>

</Window.Resources>
<Grid>
    <TabControl ItemsSource="{Binding Path=Persons}"
                ItemTemplate="{StaticResource HeaderTemplate}"
                IsSynchronizedWithCurrentItem="True" />
</Grid>
</Window>

UserControl1.xaml:

<UserControl x:Class="WpfApplication1.UserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    MinWidth="200">
    <UserControl.ContextMenu>
        <ContextMenu >
            <MenuItem Header="Change" Command="{Binding Path=ChangeCommand}"/>
        </ContextMenu>
    </UserControl.ContextMenu>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="100" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        The name:
        <TextBox Grid.Column="1" Text="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged}" />
    </Grid>
</UserControl>

CompanyViewModel.cs:

public class CompanyViewModel
{
    public ObservableCollection<PersonViewModel> Persons { get; set; }
    public CompanyViewModel()
    {
        Persons = new ObservableCollection<PersonViewModel>();
        Persons.Add(new PersonViewModel(new Person { Name = "Kalle" }));
        Persons.Add(new PersonViewModel(new Person { Name = "Nisse" }));
        Persons.Add(new PersonViewModel(new Person { Name = "Jocke" }));
    }
}

PersonViewModel.cs:

public class PersonViewModel : INotifyPropertyChanged
{
    Person _person;
    TestCommand _testCommand;

    public PersonViewModel(Person person)
    {
        _person = person;
        _testCommand = new TestCommand(this);
    }
    public ICommand ChangeCommand
    {
        get
        {
            return _testCommand;
        }
    }
    public string Name
    {
        get
        {
            return _person.Name;
        }
        set
        {
            if (value == _person.Name)
                return;
            _person.Name = value;
            OnPropertyChanged("Name");
        }
    }
    void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = this.PropertyChanged;
        if (handler != null)
        {
            var e = new PropertyChangedEventArgs(propertyName);
            handler(this, e);
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

TestCommand.cs:

public class TestCommand : ICommand
{
    PersonViewModel _person;
    public event EventHandler CanExecuteChanged;

    public TestCommand(PersonViewModel person)
    {
        _person = person;
    }
    public bool CanExecute(object parameter)
    {
        return true;
    }
    public void Execute(object parameter)
    {
        _person.Name = "Changed by command";
    }
}

Person.cs:

public class Person
{
    public string Name { get; set; }
}

Body:
I know this is already an old post, but I would like to add another solution for those one who are looking for different ways to do it.

I could not make the same solution to work in my case, since I was trying to do something else: open the context menu with a mouse click (just like a toolbar with a submenu attached to it) and also bind commands to my model. Since I was using an Event Trigger, the PlacementTarget object was null.

This is the solution I found to make it work only using XAML:

<!-- This is an example with a button, but could be other control -->
<Button>
  <...>

  <!-- This opens the context menu and binds the data context to it -->
  <Button.Triggers>
    <EventTrigger RoutedEvent="Button.Click">
      <EventTrigger.Actions>
        <BeginStoryboard>
          <Storyboard>
            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="ContextMenu.DataContext">
              <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{Binding}"/>
            </ObjectAnimationUsingKeyFrames>
            <BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="ContextMenu.IsOpen">
              <DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True"/>
            </BooleanAnimationUsingKeyFrames>
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger.Actions>
    </EventTrigger>
  </Button.Triggers>

  <!-- Here it goes the context menu -->
  <Button.ContextMenu>
    <ContextMenu>
      <MenuItem Header="Item 1" Command="{Binding MyCommand1}"/>
      <MenuItem Header="Item 2" Command="{Binding MyCommand2}"/>
    </ContextMenu>
  </Button.ContextMenu>

</Button>


问:
select statement
what select statement would I use to add the excel spreadsheet to an existing table, as i am getting an error trying to create a new table on the database? please can you assist me.
Thanks</p>

答:
Fiona --

You're probably using the wrong tools here.  You probably want to use a tool called SQL Server Integration Services to get your data into SQL Server.  You can do this by right-clicking on your database in SQL Server Enterprise Manager, selecting "Tasks". then "Import Data".  You'll probably need to do some more research on what you're doing in order to accomplish what you want.

OwnerDisplayName: Fiona

Title: select statement

OwnerDisplayName: Dave Markle


问:
ASP.NET - Page.Form.Action error
On my local development server, I am running version 2.0.50727.4955 on the live server I am running 2.0.50727.42.

On my live server I get:

Compiler Error Message: CS0117: 'System.Web.UI.HtmlControls.HtmlForm' does not contain a definition for 'Action'

On my development server everything works fine. Is this a .NET version issue or something else? Is there a way to make this work on my liver server with its current .Net version? Is there a way to upgrade from 2.0.50727.42 to 2.0.50727.4955?

Thanks

EDIT (Code):

```<code>    if (Request.PathInfo.Length != 0)
    {
        string reqPath = Request.PathInfo;
        string raw = Request.RawUrl;
        string url = Request.Url.ToString();
        if (reqPath.Length > 0)
            url = url.Replace(reqPath, "");
        if (raw.Length > 0)
            url = url.Replace(raw, "");

        litBasePath.Text = "<base href=\"" + url + "\">";
        Page.Form.Attributes["Action"] = raw;
    }
</code>```

EDIT (Local Setup)

This is my local setup. I am not getting any compile errors when i run this locally.

答:
Version number clarification (this doesn't directly address your question, but is a bit too lengthy for a comment).

There are two .NET version numbers in play: one for the .NET framework (v2, v3.5, v4), and one for the ASP.NET ISAPI DLL (v2 or v4).

You have to set the .NET framework version used for compilation in Visual Studio in your project properties, and the ASP.NET DLL version used by IIS in the website or application pool configuration in the IIS manager (inetmgr.exe).

So, even though your websites are configured to use ASP.NET v2, the applications may (and probably will) use the .NET framework v3.5 or v4.

Title: ASP.NET - Page.Form.Action error

Body:
On my local development server, I am running version 2.0.50727.4955 on the live server I am running 2.0.50727.42.

On my live server I get:

Compiler Error Message: CS0117: 'System.Web.UI.HtmlControls.HtmlForm' does not contain a definition for 'Action'

On my development server everything works fine. Is this a .NET version issue or something else? Is there a way to make this work on my liver server with its current .Net version? Is there a way to upgrade from 2.0.50727.42 to 2.0.50727.4955?

Thanks

EDIT (Code):

    if (Request.PathInfo.Length != 0)
    {
        string reqPath = Request.PathInfo;
        string raw = Request.RawUrl;
        string url = Request.Url.ToString();
        if (reqPath.Length > 0)
            url = url.Replace(reqPath, "");
        if (raw.Length > 0)
            url = url.Replace(raw, "");

        litBasePath.Text = "<base href=\"" + url + "\">";
        Page.Form.Attributes["Action"] = raw;
    }

EDIT (Local Setup)

This is my local setup. I am not getting any compile errors when i run this locally.


问:
lldb: How to remove a symbolic breakpoint?
I've created breakpoint per this
lldb breakpoint on all methods in class objective c

(lldb) breakpoint set -r '[UINavigationController popViewControllerAnimated:]'
  Breakpoint 100: 5 locations.

but

(lldb) breakpoint delete '[UINavigationController popViewControllerAnimated:]'
  0 breakpoints deleted; 0 breakpoint locations disabled.

The newly created breakpoint[s] does not appear in the list
of breakpoints in xcode.

How could I get rid of it[them]??????

答:
had to remove by breakpoint #
after listing breakpoints

breakpoint list


问:
jgitflow maven plugin: Merge release to remote-dev and remote-master branch?
I have started using the jgitflow-maven-plugin and I am trying to automate releases with bamboo.

Basically the plugin is working. We are using a development-branch and the master-branch.

Running jgitflow:release-start and jgitflow:release-finish updates the version numbers correctly for the releases.

What I am missing is that the changes

incrementing SNAPSHOT version on development-branch

incrementing major-release number on master-branch

creating a tag on the master-branch

are not pushed and merged to the remote repository.

The merges only seem to be done in the local repositories on bamboo.
I would have expected the plugin to handle the push as well.

Below my pom-plugin configuration:

```<code><plugin>
  <groupId>external.atlassian.jgitflow</groupId>
  <artifactId>jgitflow-maven-plugin</artifactId>
  <version>1.0-m5.1</version>
  <configuration>
    <flowInitContext>
      <masterBranchName>master</masterBranchName>
      <developBranchName>development</developBranchName>
      <releaseBranchPrefix>release-</releaseBranchPrefix>
    </flowInitContext>
    <useReleaseProfile>false</useReleaseProfile>
    <alwaysUpdateOrigin>true</alwaysUpdateOrigin>
    <defaultOriginUrl>ssh://git@my-remote-repo.com/app.git</defaultOriginUrl>
  </configuration>
</plugin>
</code>```

Any ideas what I am missing?

答: I guess you could try to add <pushReleases>true</pushReleases> to the configuration at least that is what the documentation says or just add a shell script task to your Bamboo build plan which does a git push ...

Body:
I have started using the jgitflow-maven-plugin and I am trying to automate releases with bamboo.

Basically the plugin is working. We are using a development-branch and the master-branch.

Running jgitflow:release-start and jgitflow:release-finish updates the version numbers correctly for the releases.

What I am missing is that the changes

incrementing SNAPSHOT version on development-branch

incrementing major-release number on master-branch

creating a tag on the master-branch

are not pushed and merged to the remote repository.

The merges only seem to be done in the local repositories on bamboo.
I would have expected the plugin to handle the push as well.

Below my pom-plugin configuration:

<plugin>
  <groupId>external.atlassian.jgitflow</groupId>
  <artifactId>jgitflow-maven-plugin</artifactId>
  <version>1.0-m5.1</version>
  <configuration>
    <flowInitContext>
      <masterBranchName>master</masterBranchName>
      <developBranchName>development</developBranchName>
      <releaseBranchPrefix>release-</releaseBranchPrefix>
    </flowInitContext>
    <useReleaseProfile>false</useReleaseProfile>
    <alwaysUpdateOrigin>true</alwaysUpdateOrigin>
    <defaultOriginUrl>ssh://git@my-remote-repo.com/app.git</defaultOriginUrl>
  </configuration>
</plugin>

Any ideas what I am missing?


问:
How do I allow cross origin request
I am a backend developer and i am providing a spring boot rest API with JWT security to consume for a front end developer who calls the api from local host.So when he calls a POST request he says he gets an CORS error.So I added the part

```<code> @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");

        chain.doFilter(request, response);
    }
</code>```

But still he gets the error.What may be the cause.Any help is appreciated

```<code>OPTIONS https:my.domain/url 401 (Unauthorized)
</code>```

when it is a POST request.

Controller code:

```<code>@RestController
public class RegistrationController {

    @Autowired
    @Qualifier("restTemplateUserRegitration")
    private RestTemplate restTemplateUserRegitration;
@RequestMapping(value="${user.endpoint}",produces={MediaType.APPLICATION_JSON_VALUE},method=RequestMethod.POST)
    public ResponseEntity<?> registerUser(@RequestBody Model ModelRequest){

                Map<String, Object> Status=new HashMap<String, Object>();
                FeedBackStatus = restTemplateUserRegitration.postForObject("http:serviceurl",registration/single",Model.class,Map.class );
                return ResponseEntity.ok(Status);
    }
}
</code>```

答:
You should implement a filter like this:

```<code>public class CORSFilter extends OncePerRequestFilter {

    private final Logger LOG = LoggerFactory.getLogger(CORSFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException {
        LOG.info("Adding CORS Headers ........................");
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        res.setHeader("Access-Control-Max-Age", "3600");
        res.setHeader("Access-Control-Allow-Headers", "X-PINGOTHER,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
        res.addHeader("Access-Control-Expose-Headers", "xsrf-token");
        if ("OPTIONS".equals(req.getMethod())) {
         res.setStatus(HttpServletResponse.SC_OK);
        } else {
         chain.doFilter(req, res);
        }
    }
}
</code>```

Found this from the post Cross Origin Request Blocked Spring MVC Restful Angularjs

Hope this help!

Title: How do I allow cross origin request

Body:
I am a backend developer and i am providing a spring boot rest API with JWT security to consume for a front end developer who calls the api from local host.So when he calls a POST request he says he gets an CORS error.So I added the part

 @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");

        chain.doFilter(request, response);
    }

But still he gets the error.What may be the cause.Any help is appreciated

OPTIONS https:my.domain/url 401 (Unauthorized)

when it is a POST request.

Controller code:

@RestController
public class RegistrationController {

    @Autowired
    @Qualifier("restTemplateUserRegitration")
    private RestTemplate restTemplateUserRegitration;
@RequestMapping(value="${user.endpoint}",produces={MediaType.APPLICATION_JSON_VALUE},method=RequestMethod.POST)
    public ResponseEntity<?> registerUser(@RequestBody Model ModelRequest){

                Map<String, Object> Status=new HashMap<String, Object>();
                FeedBackStatus = restTemplateUserRegitration.postForObject("http:serviceurl",registration/single",Model.class,Map.class );
                return ResponseEntity.ok(Status);
    }
}

Body:
You should implement a filter like this:

public class CORSFilter extends OncePerRequestFilter {

    private final Logger LOG = LoggerFactory.getLogger(CORSFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException {
        LOG.info("Adding CORS Headers ........................");
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        res.setHeader("Access-Control-Max-Age", "3600");
        res.setHeader("Access-Control-Allow-Headers", "X-PINGOTHER,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
        res.addHeader("Access-Control-Expose-Headers", "xsrf-token");
        if ("OPTIONS".equals(req.getMethod())) {
         res.setStatus(HttpServletResponse.SC_OK);
        } else {
         chain.doFilter(req, res);
        }
    }
}

Found this from the post Cross Origin Request Blocked Spring MVC Restful Angularjs

Hope this help!


问:
Retrive image file from folder and display into Image Control
I have save my Image using Below code In a Folder in my source file..
now I have to retrvive the same saved Image on my Form

```<code>string filename = Path.GetFileName(fileupload1.PostedFile.FileName);
    string strtemp = System.DateTime.Now.ToString("ddMMyyhhmmss_") + filename;
    fileupload1.SaveAs(Server.MapPath("Image/" + strtemp));
</code>```

So how should i give a Path to my Image Control
I have tried something like this to get a path of file and folder but simply i cant fetch the image from it into my image folder

```<code>Image2.ImageUrl = (Server.MapPath("Image/" + strtemp));
</code>```

答:
```<code>if(!(DropDownList1.SelectedItem.Text==""))
{
    string a = DropDownList1.SelectedItem.Text;
    string [] q  = a.Split('/');

    string qq  =    q[1];
    Image1.Visible = true;
    Image1.ImageUrl = "~/Images1/" + qq;
}
</code>```

Body:
I have save my Image using Below code In a Folder in my source file..
now I have to retrvive the same saved Image on my Form

string filename = Path.GetFileName(fileupload1.PostedFile.FileName);
    string strtemp = System.DateTime.Now.ToString("ddMMyyhhmmss_") + filename;
    fileupload1.SaveAs(Server.MapPath("Image/" + strtemp));

So how should i give a Path to my Image Control
I have tried something like this to get a path of file and folder but simply i cant fetch the image from it into my image folder

Image2.ImageUrl = (Server.MapPath("Image/" + strtemp));


问:
403 error on axios head request
When I make a head request from axios to this url, it returns a 403 Forbidden response. It works fine when I make a get request or even when I make a head request from other REST clients like postman. I am guessing it's because CloudFront is trying to deny access from bots. Can I do some workaround so I can get this request to work properly?

```<code>const axios = require('axios')
axios.head('https://images-na.ssl-images-amazon.com/images/I/415%2BC2ZrYqL.jpg')
  .then(console.log)
  .catch(console.log)
</code>```

答:
I dont see a problem in getting the image from stack snippet. Not sure why you are getting 403

axios.get('https://images-na.ssl-images-amazon.com/images/I/415%2BC2ZrYqL.jpg', {
      responseType: 'arraybuffer'
    })
    .then(response => {
    console.log(response.data);
    var arrayBuffer = response.data;
    var bytes = new Uint8Array(arrayBuffer);

    var image = document.getElementById('image');
    image.src = "data:image/jpg;base64," + encode(bytes);
    });

// public method for encoding an Uint8Array to base64
function encode (input) {
    var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;

    while (i < input.length) {
        chr1 = input[i++];
        chr2 = i < input.length ? input[i++] : Number.NaN; // Not sure if the index
        chr3 = i < input.length ? input[i++] : Number.NaN; // checks are needed here

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }
        output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
                  keyStr.charAt(enc3) + keyStr.charAt(enc4);
    }
    return output;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<img id="image"/></code>```

Title: 403 error on axios head request

Body:
When I make a head request from axios to this url, it returns a 403 Forbidden response. It works fine when I make a get request or even when I make a head request from other REST clients like postman. I am guessing it's because CloudFront is trying to deny access from bots. Can I do some workaround so I can get this request to work properly?

const axios = require('axios')
axios.head('https://images-na.ssl-images-amazon.com/images/I/415%2BC2ZrYqL.jpg')
  .then(console.log)
  .catch(console.log)

Body:
I dont see a problem in getting the image from stack snippet. Not sure why you are getting 403

axios.get('https://images-na.ssl-images-amazon.com/images/I/415%2BC2ZrYqL.jpg', {
      responseType: 'arraybuffer'
    })
    .then(response => {
    console.log(response.data);
    var arrayBuffer = response.data;
    var bytes = new Uint8Array(arrayBuffer);

    var image = document.getElementById('image');
    image.src = "data:image/jpg;base64," + encode(bytes);
    });

// public method for encoding an Uint8Array to base64
function encode (input) {
    var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;

    while (i < input.length) {
        chr1 = input[i++];
        chr2 = i < input.length ? input[i++] : Number.NaN; // Not sure if the index
        chr3 = i < input.length ? input[i++] : Number.NaN; // checks are needed here

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }
        output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
                  keyStr.charAt(enc3) + keyStr.charAt(enc4);
    }
    return output;
}

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<img id="image"/>


问:
Importing library once for a python module
I want to structure imports of my python module/package, namely I have several *.py files in my module. All of them use:

```<code> import numpy as np
</code>```

in some pf them I use:

```<code>import pandas as pd
</code>```

can I set the global import for my python module, and say that it uses numpy as np in all the *.py files of the module.
I tried something in __init__.py but it didn't work as expected. Is it anyhow reasonable to make global imports?

答:
Warning:- Do not use this at home.Not a good practice

You can Do it by importing all your libraries into a single file. For example:-

library.py

```<code>import numpy as np
import os
import json
import pandas as pd
</code>```

And then import this file in your code files

main.py

```<code>from library import *

a = np.array([1, 2, 3])
</code>```

Body:
I want to structure imports of my python module/package, namely I have several *.py files in my module. All of them use:

 import numpy as np

in some pf them I use:

import pandas as pd

can I set the global import for my python module, and say that it uses numpy as np in all the *.py files of the module.
I tried something in __init__.py but it didn't work as expected. Is it anyhow reasonable to make global imports?

Body:
Warning:- Do not use this at home.Not a good practice

You can Do it by importing all your libraries into a single file. For example:-

library.py

import numpy as np
import os
import json
import pandas as pd

And then import this file in your code files

main.py

from library import *

a = np.array([1, 2, 3])


问:
content classification API for the google cloud?
I am trying to use the google cloud platform to classify text much like what is done with the text classification example in Python SciKit Learn.  Does anyone know if this capability exists?  I've found the NL API, but can't seem to find anything for classification.

Thanks,
Marc

答:
Its now avialable but as beta feature:
https://cloud.google.com/natural-language/docs/classifying-text</p>


问:
How to filter Flat File Source using script component
I have the following scenario:
I have thousands of text files with the below format.The column names are written in separate lines where as the row values are delimited by Pipe(|).

```<code>START-OF-FILE
PROGRAMNAME=getdata
DATEFORMAT=yyyymmdd

#Some Text
#Some Text
#Some Text
#Some Text
#Some Text
START-OF-FIELDS
Field1
Field2
Field3
------
FieldN
END-OF-FIELDS
TIMESTARTED=Tue May 12 16:04:42 JST 2015
START-OF-DATA
Field1Value|Field2value|Field3Value|...|Field N Value
Field1Value|Field2value|Field3Value|...|Field N Value
------|...........|----|-------
END-OF-DATA
DATARECORDS=30747
TIMEFINISHED=Tue May 12 16:11:53 JST 2015
END-OF-FILE
</code>```

Now I have a corresponding SQL Server table, where I can easily load the data as destination.
Since I am new to SSIS, having trouble as to how to write the Script Component so that I can filter the Source Text files and easily load into sql server table.

Thanks in advance!

答:
USE Below VB Script in your SSIS SCript Component Task as source

```<code>enter code here

Imports System
Imports System.Data
Imports System.Math
Imports System.IO
Imports Microsoft.SqlServer.Dts.Runtime
Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper
Imports Microsoft.SqlServer.Dts.Runtime.Wrapper

<Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute()> _
<CLSCompliant(False)> _
Public Class ScriptMain
    Inherits UserComponent
    'Private strSourceDirectory As String
    'Private strSourceFileName As String
    Private strSourceSystem As String
    Private strSourceSubSystem As String
    Private dtBusinessDate As Date

    Public Overrides Sub PreExecute()
        MyBase.PreExecute()
        '
        ' Add your code here for preprocessing or remove if not needed
        ''

    End Sub

    Public Overrides Sub PostExecute()
        MyBase.PostExecute()
        '
        ' Add your code here for postprocessing or remove if not needed
        ' You can set read/write variables here, for example:
        Dim strSourceDirectory As String = Me.Variables.GLOBALSourceDirectory.ToString()
        Dim strSourceFileName As String = Me.Variables.GLOBALSourceFileName.ToString()
        'Dim strSourceSystem As String = Me.Variables.GLOBALSourceSystem.ToString()
        'Dim strSourceSubSystem As String = Me.Variables.GLOBALSourceSubSystem.ToString()
        'Dim dtBusinessDate As Date = Me.Variables.GLOBALBusinessDate.Date

    End Sub

    Public Overrides Sub CreateNewOutputRows()
        '
        ' Add rows by calling the AddRow method on the member variable named "<Output Name>Buffer".
        ' For example, call MyOutputBuffer.AddRow() if your output was named "MyOutput".
        '
        Dim sr As System.IO.StreamReader
        Dim strSourceDirectory As String = Me.Variables.GLOBALSourceDirectory.ToString()
        Dim strSourceFileName As String = Me.Variables.GLOBALSourceFileName.ToString()
        'Dim strSourceSystem As String = Me.Variables.GLOBALSourceSystem.ToString()
        'Dim strSourceSubSystem As String = Me.Variables.GLOBALSourceSubSystem.ToString()
        'Dim dtBusinessDate As Date = Me.Variables.GLOBALBusinessDate.Date

        'sr = New System.IO.StreamReader("C:\QRM_SourceFiles\BBG_BONDS_OUTPUT_YYYYMMDD.txt")
        sr = New System.IO.StreamReader(strSourceDirectory & strSourceFileName)
        Dim lineIndex As Integer = 0
        While (Not sr.EndOfStream)
            Dim line As String = sr.ReadLine()
            If (lineIndex <> 0) Then 'remove header row
                Dim columnArray As String() = line.Split(Convert.ToChar("|"))
                If (columnArray.Length > 1) Then
                    Output0Buffer.AddRow()
                    Output0Buffer.Col0 = columnArray(0).ToString()
                    Output0Buffer.Col3 = columnArray(3).ToString()
                    Output0Buffer.Col4 = columnArray(4).ToString()
                    Output0Buffer.Col5 = columnArray(5).ToString()
                    Output0Buffer.Col6 = columnArray(6).ToString()
                    Output0Buffer.Col7 = columnArray(7).ToString()
                    Output0Buffer.Col8 = columnArray(8).ToString()
                    Output0Buffer.Col9 = columnArray(9).ToString()
                    Output0Buffer.Col10 = columnArray(10).ToString()
                    Output0Buffer.Col11 = columnArray(11).ToString()
                    Output0Buffer.Col12 = columnArray(12).ToString()
                    Output0Buffer.Col13 = columnArray(13).ToString()
                    Output0Buffer.Col14 = columnArray(14).ToString()
                    Output0Buffer.Col15 = columnArray(15).ToString()
                    Output0Buffer.Col16 = columnArray(16).ToString()
                    Output0Buffer.Col17 = columnArray(17).ToString()
                    Output0Buffer.Col18 = columnArray(18).ToString()
                    Output0Buffer.Col19 = columnArray(19).ToString()
                    Output0Buffer.Col20 = columnArray(20).ToString()
                    Output0Buffer.Col21 = columnArray(21).ToString()
                    Output0Buffer.Col22 = columnArray(22).ToString()
                    Output0Buffer.Col23 = columnArray(23).ToString()
                    Output0Buffer.Col24 = columnArray(24).ToString()

                End If
            End If
            lineIndex = lineIndex + 1
        End While
        sr.Close()

    End Sub

End Class
</code>```

Code End

Body:
I have the following scenario:
I have thousands of text files with the below format.The column names are written in separate lines where as the row values are delimited by Pipe(|).

START-OF-FILE
PROGRAMNAME=getdata
DATEFORMAT=yyyymmdd

#Some Text
#Some Text
#Some Text
#Some Text
#Some Text
START-OF-FIELDS
Field1
Field2
Field3
------
FieldN
END-OF-FIELDS
TIMESTARTED=Tue May 12 16:04:42 JST 2015
START-OF-DATA
Field1Value|Field2value|Field3Value|...|Field N Value
Field1Value|Field2value|Field3Value|...|Field N Value
------|...........|----|-------
END-OF-DATA
DATARECORDS=30747
TIMEFINISHED=Tue May 12 16:11:53 JST 2015
END-OF-FILE

Now I have a corresponding SQL Server table, where I can easily load the data as destination.
Since I am new to SSIS, having trouble as to how to write the Script Component so that I can filter the Source Text files and easily load into sql server table.

Thanks in advance!

Body:
USE Below VB Script in your SSIS SCript Component Task as source

enter code here

Imports System
Imports System.Data
Imports System.Math
Imports System.IO
Imports Microsoft.SqlServer.Dts.Runtime
Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper
Imports Microsoft.SqlServer.Dts.Runtime.Wrapper

<Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute()> _
<CLSCompliant(False)> _
Public Class ScriptMain
    Inherits UserComponent
    'Private strSourceDirectory As String
    'Private strSourceFileName As String
    Private strSourceSystem As String
    Private strSourceSubSystem As String
    Private dtBusinessDate As Date

    Public Overrides Sub PreExecute()
        MyBase.PreExecute()
        '
        ' Add your code here for preprocessing or remove if not needed
        ''

    End Sub

    Public Overrides Sub PostExecute()
        MyBase.PostExecute()
        '
        ' Add your code here for postprocessing or remove if not needed
        ' You can set read/write variables here, for example:
        Dim strSourceDirectory As String = Me.Variables.GLOBALSourceDirectory.ToString()
        Dim strSourceFileName As String = Me.Variables.GLOBALSourceFileName.ToString()
        'Dim strSourceSystem As String = Me.Variables.GLOBALSourceSystem.ToString()
        'Dim strSourceSubSystem As String = Me.Variables.GLOBALSourceSubSystem.ToString()
        'Dim dtBusinessDate As Date = Me.Variables.GLOBALBusinessDate.Date

    End Sub

    Public Overrides Sub CreateNewOutputRows()
        '
        ' Add rows by calling the AddRow method on the member variable named "<Output Name>Buffer".
        ' For example, call MyOutputBuffer.AddRow() if your output was named "MyOutput".
        '
        Dim sr As System.IO.StreamReader
        Dim strSourceDirectory As String = Me.Variables.GLOBALSourceDirectory.ToString()
        Dim strSourceFileName As String = Me.Variables.GLOBALSourceFileName.ToString()
        'Dim strSourceSystem As String = Me.Variables.GLOBALSourceSystem.ToString()
        'Dim strSourceSubSystem As String = Me.Variables.GLOBALSourceSubSystem.ToString()
        'Dim dtBusinessDate As Date = Me.Variables.GLOBALBusinessDate.Date

        'sr = New System.IO.StreamReader("C:\QRM_SourceFiles\BBG_BONDS_OUTPUT_YYYYMMDD.txt")
        sr = New System.IO.StreamReader(strSourceDirectory & strSourceFileName)
        Dim lineIndex As Integer = 0
        While (Not sr.EndOfStream)
            Dim line As String = sr.ReadLine()
            If (lineIndex <> 0) Then 'remove header row
                Dim columnArray As String() = line.Split(Convert.ToChar("|"))
                If (columnArray.Length > 1) Then
                    Output0Buffer.AddRow()
                    Output0Buffer.Col0 = columnArray(0).ToString()
                    Output0Buffer.Col3 = columnArray(3).ToString()
                    Output0Buffer.Col4 = columnArray(4).ToString()
                    Output0Buffer.Col5 = columnArray(5).ToString()
                    Output0Buffer.Col6 = columnArray(6).ToString()
                    Output0Buffer.Col7 = columnArray(7).ToString()
                    Output0Buffer.Col8 = columnArray(8).ToString()
                    Output0Buffer.Col9 = columnArray(9).ToString()
                    Output0Buffer.Col10 = columnArray(10).ToString()
                    Output0Buffer.Col11 = columnArray(11).ToString()
                    Output0Buffer.Col12 = columnArray(12).ToString()
                    Output0Buffer.Col13 = columnArray(13).ToString()
                    Output0Buffer.Col14 = columnArray(14).ToString()
                    Output0Buffer.Col15 = columnArray(15).ToString()
                    Output0Buffer.Col16 = columnArray(16).ToString()
                    Output0Buffer.Col17 = columnArray(17).ToString()
                    Output0Buffer.Col18 = columnArray(18).ToString()
                    Output0Buffer.Col19 = columnArray(19).ToString()
                    Output0Buffer.Col20 = columnArray(20).ToString()
                    Output0Buffer.Col21 = columnArray(21).ToString()
                    Output0Buffer.Col22 = columnArray(22).ToString()
                    Output0Buffer.Col23 = columnArray(23).ToString()
                    Output0Buffer.Col24 = columnArray(24).ToString()

                End If
            End If
            lineIndex = lineIndex + 1
        End While
        sr.Close()

    End Sub

End Class

Code End


问:
Invoke "Verify it's you" authentication page from a Firebase application
In my Firebase application users can remove their accounts. I want to do the same thing which Google do when you're trying to remove your account: ask the user's password once more.

Is it possible to invoke this dialog using Firebase Auth API? Or in some other way?

答:
You can ask the user to reauthenticate. This is actually common practice for certain sensitive operations like deleting a Firebase user, updating a password or email. You would reauthenticate and check the auth_time in the new ID token is recent.
So to reauthenticate with email/password in JS:

```<code>firebase.auth().currentUser.reauthenticateWithCredential(firebase.auth.EmailAuthProvider.credential(email, password))...
</code>```

If you want to reauthenticate with a Google provider:

```<code>var customParams = {login_hint: firebase.auth().currentUser.email, prompt: 'consent'};
firebase.auth().currentUser.reauthenticateWithPopup(new firebase.auth.GoogleAuthProvider().setCustomParameters(customParams))...
</code>```

Body:
You can ask the user to reauthenticate. This is actually common practice for certain sensitive operations like deleting a Firebase user, updating a password or email. You would reauthenticate and check the auth_time in the new ID token is recent.
So to reauthenticate with email/password in JS:

firebase.auth().currentUser.reauthenticateWithCredential(firebase.auth.EmailAuthProvider.credential(email, password))...

If you want to reauthenticate with a Google provider:

var customParams = {login_hint: firebase.auth().currentUser.email, prompt: 'consent'};
firebase.auth().currentUser.reauthenticateWithPopup(new firebase.auth.GoogleAuthProvider().setCustomParameters(customParams))...


问:
Laravel: retrieve count of value in JSON array
Iv currently taken over a project where the developer has stored has many relationships in json array columns in certain tables.

product table

```<code>----------------------------
id | product | colour
----------------------------
 1   iPhone    ["8","4","1"]
 2   iPad      ["8","1"]
 3   Macbook   ["8"]
</code>```

This is an example of the relationships stored between a product and product colours available.

I need to be able to get the count of products, related to a certian colour.
So in this example... colour: 8 would return 3 products

I am use to Eloquent relationships utilising $product->colours() but unfortunately in this instance i can't do that, and i am unable to change the current db structure.

How would i be able to get the amount of products per certain colour using eloquent where or whereIn clauses?

What i have tried so far...

```<code>$count = $products->where('colour', '[$colour->id]')->count();
----
$count = $products->whereIn('colour', $colour->id)->count();
</code>```

Any help would be greatly appreciated. Thanks in advance.

答:
This is ugly, but I guess it works:</p>

```<code>\App\Product::where('colour','like','%"' .$colour->id '"%')->distinct()->count()
</code>```

Body:
Iv currently taken over a project where the developer has stored has many relationships in json array columns in certain tables.

product table

----------------------------
id | product | colour
----------------------------
 1   iPhone    ["8","4","1"]
 2   iPad      ["8","1"]
 3   Macbook   ["8"]

This is an example of the relationships stored between a product and product colours available.

I need to be able to get the count of products, related to a certian colour.
So in this example... colour: 8 would return 3 products

I am use to Eloquent relationships utilising $product->colours() but unfortunately in this instance i can't do that, and i am unable to change the current db structure.

How would i be able to get the amount of products per certain colour using eloquent where or whereIn clauses?

What i have tried so far...

$count = $products->where('colour', '[$colour->id]')->count();
----
$count = $products->whereIn('colour', $colour->id)->count();

Any help would be greatly appreciated. Thanks in advance.

Body:
This is ugly, but I guess it works:

\App\Product::where('colour','like','%"' .$colour->id '"%')->distinct()->count()


问:
Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0
So this morning I started updating to the latest version of my project libraries.

I'm trying to update GCM to the latest version 9.2.0, but I get this error:

Error:Execution failed for task ':app:processDebugGoogleServices'.
  Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 9.0.0.

This is how I have my code:

```<code>dependencies {
    classpath 'com.android.tools.build:gradle:2.1.2'
    classpath 'com.google.gms:google-services:3.0.0'
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
</code>```

And then:

```<code>dependencies {
    ...

    compile "com.google.android.gms:play-services-gcm:9.2.0"

    ...
}
</code>```

Anyone having the same issue/fixed the same issue?

Thanks.

EDIT

Apparently you have to apply your GSM plugin at the bottom of your app/build.gradle file. Else, version 9.2.0 will cause conflict in your project.

For reference, this is how my app/build.gradle file looks like now:

```<code>apply plugin: "com.android.application"
apply plugin: "com.neenbedankt.android-apt"

android {
    ...
}

dependencies {
    ...

    // Google Cloud Messaging
    compile "com.google.android.gms:play-services-gcm:9.2.0"

    ...
}

apply plugin: "com.google.gms.google-services"
</code>```

答:
Add this line at the bottom of the gradle.

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

because it the top it does not work.I was facing similar problem.

Body:
So this morning I started updating to the latest version of my project libraries.

I'm trying to update GCM to the latest version 9.2.0, but I get this error:

Error:Execution failed for task ':app:processDebugGoogleServices'.
  Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 9.0.0.

This is how I have my code:

dependencies {
    classpath 'com.android.tools.build:gradle:2.1.2'
    classpath 'com.google.gms:google-services:3.0.0'
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}

And then:

dependencies {
    ...

    compile "com.google.android.gms:play-services-gcm:9.2.0"

    ...
}

Anyone having the same issue/fixed the same issue?

Thanks.

EDIT

Apparently you have to apply your GSM plugin at the bottom of your app/build.gradle file. Else, version 9.2.0 will cause conflict in your project.

For reference, this is how my app/build.gradle file looks like now:

apply plugin: "com.android.application"
apply plugin: "com.neenbedankt.android-apt"

android {
    ...
}

dependencies {
    ...

    // Google Cloud Messaging
    compile "com.google.android.gms:play-services-gcm:9.2.0"

    ...
}

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


问:
Remove NaN from input while calculation
I have a javascript function in which I need to remove the NaN from textbox after calculation ?

```<code>function calculateInterest() {

    var repay_period = parseInt(document.getElementById("emp_loan_repayment_method_id").value);
    var loan_amount = parseInt(document.getElementById("maximum_loan_amount").value);
    var rate_of_interest = parseInt(document.getElementById("rate_of_interest").value);
    var no_of_months = parseInt(document.getElementById("repayment_periods").value);
    var repay_month_amount = parseInt(document.getElementById("repayment_amount").value);
    var no_of_periods = no_of_months / 12;

    {
        var payable_interest = (loan_amount * no_of_periods * rate_of_interest) / 100;

        var pay_interest = payable_interest.toFixed(2);

        document.getElementById("total_payable_interest").value = pay_interest;

        var repay_amount = (loan_amount / no_of_months).toFixed(2);

        document.getElementById("repayment_amount").value = repay_amount;

        var total_payable_amount = (payable_interest + loan_amount).toFixed(2);

        document.getElementById("total_payable_amount").value = total_payable_amount;

    }
}
</code>```

答:
When assigning a value to a textbox, check if it is NaN or not:</p>

```<code>if(!isNaN(parseInt(value_to_test)))
    document.getElementById("yout_input").value = value_to_test;
else
    document.getElementById("yout_input").value = '0'; // or anything you want to show here
</code>```

Title: Remove NaN from input while calculation

Body:
I have a javascript function in which I need to remove the NaN from textbox after calculation ?

function calculateInterest() {

    var repay_period = parseInt(document.getElementById("emp_loan_repayment_method_id").value);
    var loan_amount = parseInt(document.getElementById("maximum_loan_amount").value);
    var rate_of_interest = parseInt(document.getElementById("rate_of_interest").value);
    var no_of_months = parseInt(document.getElementById("repayment_periods").value);
    var repay_month_amount = parseInt(document.getElementById("repayment_amount").value);
    var no_of_periods = no_of_months / 12;

    {
        var payable_interest = (loan_amount * no_of_periods * rate_of_interest) / 100;

        var pay_interest = payable_interest.toFixed(2);

        document.getElementById("total_payable_interest").value = pay_interest;

        var repay_amount = (loan_amount / no_of_months).toFixed(2);

        document.getElementById("repayment_amount").value = repay_amount;

        var total_payable_amount = (payable_interest + loan_amount).toFixed(2);

        document.getElementById("total_payable_amount").value = total_payable_amount;

    }
}

Body:
When assigning a value to a textbox, check if it is NaN or not:

if(!isNaN(parseInt(value_to_test)))
    document.getElementById("yout_input").value = value_to_test;
else
    document.getElementById("yout_input").value = '0'; // or anything you want to show here


问:
remove white space before after of data in text area
I input string to textarea such as below:

```<code>         email1@gmail.com
   email@gmail.com
 email3@gmail.com
      email4@gmail.com
</code>```

How to format they to:

```<code>email1@gmail.com
email@gmail.com
email3@gmail.com
email4@gmail.com
</code>```

One email in one line in textarea. I want use PHP to make it.
Please help me about solution, thanks you.

答:
this should work in php
str_replace(' ','',$yourText)

Body:
I input string to textarea such as below:

         email1@gmail.com
   email@gmail.com
 email3@gmail.com
      email4@gmail.com

How to format they to:

email1@gmail.com
email@gmail.com
email3@gmail.com
email4@gmail.com

One email in one line in textarea. I want use PHP to make it.
Please help me about solution, thanks you.


问:
How to make Ansible execute a shell script if a package is not installed
How can I make Ansible execute a shell script if a (rpm) package is not installed? Is it somehow possible to leverage the yum module?</p>

答:
I find using shell or command module is not "ansiblic".

I prefer to use yum module and json_query filter to check if a package is already installed. E.g. httpd package :

```<code>    - yum:
        list: httpd
      register: apache_service

    - assert:
        that:
          - "'installed' in apache_service|json_query('results[*].yumstate')"
      msg: 'httpd is not installed'
</code>```

Body:
I find using shell or command module is not "ansiblic".

I prefer to use yum module and json_query filter to check if a package is already installed. E.g. httpd package :

    - yum:
        list: httpd
      register: apache_service

    - assert:
        that:
          - "'installed' in apache_service|json_query('results[*].yumstate')"
      msg: 'httpd is not installed'


问:
C# - Add common behaviour in abstract class after calling individual behaviours in subclasses
I'm quite new to abstract classes. Usually you can create a member in a base-class and then extend its logic by calling it in the subclasses using base.Member. But can I do it the other way around?

I have an abstract class A with a property of type IEnumerable<T>:

```<code>abstract class A
{
    IEnumerable<int> Foo { get; }
}
</code>```

I want the derived classes of A to return an individual IEnumerable and want to "filter" them using .Where by the same condition. I did following:

```<code>abstract class A
{
    public IEnumerable<int> Foo => Bar.Where(x => true);
    protected abstract IEnumerable<int> Bar { get; }
}
abstract class B : A
{
    protected override IEnumerable<int> Bar {
        get { yield return 1; }
    }
}
</code>```

It works, but is this the right approach? Or can I do the same thing using only one property? It feels especially clunky if I have some classes between which also have to filter it because I'd just have to add more and more members based on the amount of layers I have.

答:
What you have here is effectively the Template Method Pattern. This is especially suited when you have more than one protected abstract method, where the abstract class controls the flow of those methods.

For what you are trying to do, it is fine, and you can keep it if you want. However, it is not the only solution.

The Strategy Pattern

When you only have 1 method, injecting an object that does that 1 thing is sometimes advised. This is easier to extend, since for every new B you only need to test the specifics of it, and not the parts the abstraction does.

Lastly, I think your situation is best suited for The Decorator Pattern.

```<code>class B
{
    public IEnumerable<int> Foo => yield return 1;
}
class A : B
{
    private B b;
    public IEnumerable<int> Foo => b.Foo.Where(x => true);

    public A(B b)
    {
        this.b = b;
    }
}
</code>```

This is somewhat a simplification, you might want an actual interface that both A and B implements. This really scales well when you talk about adding other classes that filter as well. Your classes can then be instantiated to do the filtering you want.

Body:
I'm quite new to abstract classes. Usually you can create a member in a base-class and then extend its logic by calling it in the subclasses using base.Member. But can I do it the other way around?

I have an abstract class A with a property of type IEnumerable<T>:

abstract class A
{
    IEnumerable<int> Foo { get; }
}

I want the derived classes of A to return an individual IEnumerable and want to "filter" them using .Where by the same condition. I did following:

abstract class A
{
    public IEnumerable<int> Foo => Bar.Where(x => true);
    protected abstract IEnumerable<int> Bar { get; }
}
abstract class B : A
{
    protected override IEnumerable<int> Bar {
        get { yield return 1; }
    }
}

It works, but is this the right approach? Or can I do the same thing using only one property? It feels especially clunky if I have some classes between which also have to filter it because I'd just have to add more and more members based on the amount of layers I have.

Body:
What you have here is effectively the Template Method Pattern. This is especially suited when you have more than one protected abstract method, where the abstract class controls the flow of those methods.

For what you are trying to do, it is fine, and you can keep it if you want. However, it is not the only solution.

The Strategy Pattern

When you only have 1 method, injecting an object that does that 1 thing is sometimes advised. This is easier to extend, since for every new B you only need to test the specifics of it, and not the parts the abstraction does.

Lastly, I think your situation is best suited for The Decorator Pattern.

class B
{
    public IEnumerable<int> Foo => yield return 1;
}
class A : B
{
    private B b;
    public IEnumerable<int> Foo => b.Foo.Where(x => true);

    public A(B b)
    {
        this.b = b;
    }
}

This is somewhat a simplification, you might want an actual interface that both A and B implements. This really scales well when you talk about adding other classes that filter as well. Your classes can then be instantiated to do the filtering you want.


问:
Select entire group if one selection has the given value
```<code> datetime                                label            option_title option_value  lead difference

 1 2016-07-22                                   GE  3 - Commercial Review            3     2         -1
 2 2017-02-20                                   GE    2 - Solution Review            2     1         -1
 3 2017-02-20                                   GE 1 - Opportunity Review            1     2          1
 4 2017-04-18                                   GE    2 - Solution Review            2     3          1
 5 2017-04-19                                   GE  3 - Commercial Review            3     4          1
 6 2017-04-19                                   GE    4 - Submit Proposal            4     5          1
 7 2017-08-08                                   GE   5 - Proposal Awarded            5    NA         NA
 8 2016-08-02                                 HSBC   5 - Proposal Awarded            5     6          1
 9 2016-12-13                                 HSBC   6 - Delivery Phase 1            6     7          1
10 2017-08-07                                 HSBC       7 - Phase 1 Live            7    NA         NA
11 2016-07-22                                Lowes      Pre-Qualification            0    NA         NA
12 2016-08-02                          Danske Bank   6 - Delivery Phase 1            6    NA         NA
13 2016-07-22 AP Moller Maersk (IT Transformation)  3 - Commercial Review            3    NA         NA
14 2016-07-22                   BHP Billiton - APJ      Pre-Qualification            0     2          2
15 2016-07-26                   BHP Billiton - APJ    2 - Solution Review            2     0         -2
16 2016-07-26                   BHP Billiton - APJ      Pre-Qualification            0     2          2
</code>```

I would like to create a new data frame off of this one that selects only the "labels" that have a negative "difference" value. However, I want to select ALL of the similar "labels" like so:

```<code> datetime                                label            option_title option_value  lead difference

 1 2016-07-22                                   GE  3 - Commercial Review            3     2         -1
 2 2017-02-20                                   GE    2 - Solution Review            2     1         -1
 3 2017-02-20                                   GE 1 - Opportunity Review            1     2          1
 4 2017-04-18                                   GE    2 - Solution Review            2     3          1
 5 2017-04-19                                   GE  3 - Commercial Review            3     4          1
 6 2017-04-19                                   GE    4 - Submit Proposal            4     5          1
 7 2017-08-08                                   GE   5 - Proposal Awarded            5    NA         NA
 8 2016-07-22                   BHP Billiton - APJ      Pre-Qualification            0     2          2
 9 2016-07-26                   BHP Billiton - APJ    2 - Solution Review            2     0         -2
10 2016-07-26                   BHP Billiton - APJ      Pre-Qualification            0     2          2
</code>```

I'm not sure how to do this in dplyr....would SQL be better for this? (I haven't used the sql package in R much)

答:
You could use an in clause on a subselect  </p>

```<code>select * from my_table
where label in (
  select label form my_table
  where difference <0
)
</code>```

<p>or  a join on a subselect  </p>

```<code>select * from my_table m
INNER JOIN (
  select label form my_table
  where difference <0
) t on m-label = t.lable
</code>```

Body:
 datetime                                label            option_title option_value  lead difference

 1 2016-07-22                                   GE  3 - Commercial Review            3     2         -1
 2 2017-02-20                                   GE    2 - Solution Review            2     1         -1
 3 2017-02-20                                   GE 1 - Opportunity Review            1     2          1
 4 2017-04-18                                   GE    2 - Solution Review            2     3          1
 5 2017-04-19                                   GE  3 - Commercial Review            3     4          1
 6 2017-04-19                                   GE    4 - Submit Proposal            4     5          1
 7 2017-08-08                                   GE   5 - Proposal Awarded            5    NA         NA
 8 2016-08-02                                 HSBC   5 - Proposal Awarded            5     6          1
 9 2016-12-13                                 HSBC   6 - Delivery Phase 1            6     7          1
10 2017-08-07                                 HSBC       7 - Phase 1 Live            7    NA         NA
11 2016-07-22                                Lowes      Pre-Qualification            0    NA         NA
12 2016-08-02                          Danske Bank   6 - Delivery Phase 1            6    NA         NA
13 2016-07-22 AP Moller Maersk (IT Transformation)  3 - Commercial Review            3    NA         NA
14 2016-07-22                   BHP Billiton - APJ      Pre-Qualification            0     2          2
15 2016-07-26                   BHP Billiton - APJ    2 - Solution Review            2     0         -2
16 2016-07-26                   BHP Billiton - APJ      Pre-Qualification            0     2          2

I would like to create a new data frame off of this one that selects only the "labels" that have a negative "difference" value. However, I want to select ALL of the similar "labels" like so:

 datetime                                label            option_title option_value  lead difference

 1 2016-07-22                                   GE  3 - Commercial Review            3     2         -1
 2 2017-02-20                                   GE    2 - Solution Review            2     1         -1
 3 2017-02-20                                   GE 1 - Opportunity Review            1     2          1
 4 2017-04-18                                   GE    2 - Solution Review            2     3          1
 5 2017-04-19                                   GE  3 - Commercial Review            3     4          1
 6 2017-04-19                                   GE    4 - Submit Proposal            4     5          1
 7 2017-08-08                                   GE   5 - Proposal Awarded            5    NA         NA
 8 2016-07-22                   BHP Billiton - APJ      Pre-Qualification            0     2          2
 9 2016-07-26                   BHP Billiton - APJ    2 - Solution Review            2     0         -2
10 2016-07-26                   BHP Billiton - APJ      Pre-Qualification            0     2          2

I'm not sure how to do this in dplyr....would SQL be better for this? (I haven't used the sql package in R much)

Body:
You could use an in clause on a subselect

select * from my_table
where label in (
  select label form my_table
  where difference <0
)

or  a join on a subselect

select * from my_table m
INNER JOIN (
  select label form my_table
  where difference <0
) t on m-label = t.lable


答:
You can do it with R, no need to use the SQL package for this.

Sample data

```<code>difference <- c(1, -2, 3, -5)
labels <- c("a", "b", "c", "d")
df <- data.frame(a, b)
</code>```

You can do a simple subset, in which you select the values with a negative difference:

```<code>minus_df <- subset(df, difference<0)
</code>```

Finally, you create a list of the labels (you could do this directly in the previous step but it's always better to check whether the data is correct.

```<code>m_labels <- minus_df$labels
</code>```

Title: Select entire group if one selection has the given value

Body:
You can do it with R, no need to use the SQL package for this.

Sample data

difference <- c(1, -2, 3, -5)
labels <- c("a", "b", "c", "d")
df <- data.frame(a, b)

You can do a simple subset, in which you select the values with a negative difference:

minus_df <- subset(df, difference<0)

Finally, you create a list of the labels (you could do this directly in the previous step but it's always better to check whether the data is correct.

m_labels <- minus_df$labels


问:
How to create a child iteration using TFS API?
I have to create a child iteration in Team Foundation Server 2017 (on premise). In my current Visual Studio project I am using then NuGet packages "Microsoft.TeamFoundationServer.Client" and "Microsoft.VisualStudio.Services.Client". None of the APIs offer a method to create a child iteration. I also didn't find any documentation on how to achieve this task. Anyone out there who knows how to create a child iteration?</p>

答:
You could use below sample to create a child iteration using the TFS API:</p>

```<code>using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
using System;

namespace _AddIteration
{
    class Program
    {
        static void Main(string[] args)
        {
            string iterationName = "TestIteration";
            string collection = @"http://server:8080/tfs/DefaultCollection";
            var tfsServer = new Uri(collection);
            var tpc = new TfsTeamProjectCollection(tfsServer);
            tpc.Authenticate();
            var css = tpc.GetService<ICommonStructureService>();
            string rootNodePath = string.Format("\\{0}\\Iteration", "ProjectName");
            var pathRoot = css.GetNodeFromPath(rootNodePath);
            css.CreateNode(iterationName, pathRoot.Uri);

        }
    }
}
</code>```

Body:
You could use below sample to create a child iteration using the TFS API:

using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
using System;

namespace _AddIteration
{
    class Program
    {
        static void Main(string[] args)
        {
            string iterationName = "TestIteration";
            string collection = @"http://server:8080/tfs/DefaultCollection";
            var tfsServer = new Uri(collection);
            var tpc = new TfsTeamProjectCollection(tfsServer);
            tpc.Authenticate();
            var css = tpc.GetService<ICommonStructureService>();
            string rootNodePath = string.Format("\\{0}\\Iteration", "ProjectName");
            var pathRoot = css.GetNodeFromPath(rootNodePath);
            css.CreateNode(iterationName, pathRoot.Uri);

        }
    }
}


问:
extracting a variable from the redux store
I need to extract the props from the store in the calculate component and pass the calculation results in the app. I just started using redux.

app.js

```<code>    import React, { Component } from 'react';
    import { connect } from 'react-redux';
    import principalChanged from './src/actions';
    import { Input, Card } from './src/components/common';
    import  { principal2, principal3 } from './src/components/calculate';

      class App extends Component {
        onPrincipalChange(text) {
          this.props.principalChanged(text);
        }
      render() {
        return (
            <Card>
               <Input
                 placeholder="Placeholder"
                 label="Label"
                 onChangeText={this.onPrincipalChange.bind(this)}
                 value={this.props.principal}
                />
              `Current state of the variable: ${this.props.principal}`{/n}
              `New variable: ${principal2}`
              `New variable: ${principal3}`
            </Card>
        );
       }
       }
const mapStateToProps = state => {
   return {
      principal: state.form.principal
   };
};
export default connect(mapStateToProps, {
    principalChanged
})(App);
</code>```

calculate.js

```<code>// call the { principal } variable from the store
// somehow
// maybe I should use mergeProps
export const principal2 = (principal) => {
     return ( { principal * 2 } ); // calculating
};

export const principal3 = () => {
     return ( { principal2 / 4 } ); // calculating
};
</code>```

I don't know how to connect state.principal.props to calculate.js. Maybe I should use mergeProps?

答:
You need to use actions and reducers

Basically, in some part of your code you need to dispatch an action and resolve it with your reducer.

So you will need to create the action file and the reducer file for solve calculate and the root reducer to import this reducer and another that you will have.

Obs.: consider use some eslint rule to improve your code.

For example:

```<code>const mapStateToProps = state => {
   return {
      principal: state.form.principal
   };
};
</code>```

could be:

```<code>const mapStateToProps = state => ({
   principal: state.form.principal
});
</code>```

And the statefull class could be stateless class:

```<code>const App = ({ principal, principalChanged }) => (
            <Card>
               <Input
                 placeholder="Placeholder"
                 label="Label"
                 onChangeText={principalChanged}
                 value={principal}
                />
              `Current state of the variable: ${principal}`{/n}
              `New variable: ${principal2}`
              `New variable: ${principal3}`
            </Card>
        );
</code>```

Body:
I need to extract the props from the store in the calculate component and pass the calculation results in the app. I just started using redux.

app.js

    import React, { Component } from 'react';
    import { connect } from 'react-redux';
    import principalChanged from './src/actions';
    import { Input, Card } from './src/components/common';
    import  { principal2, principal3 } from './src/components/calculate';

      class App extends Component {
        onPrincipalChange(text) {
          this.props.principalChanged(text);
        }
      render() {
        return (
            <Card>
               <Input
                 placeholder="Placeholder"
                 label="Label"
                 onChangeText={this.onPrincipalChange.bind(this)}
                 value={this.props.principal}
                />
              `Current state of the variable: ${this.props.principal}`{/n}
              `New variable: ${principal2}`
              `New variable: ${principal3}`
            </Card>
        );
       }
       }
const mapStateToProps = state => {
   return {
      principal: state.form.principal
   };
};
export default connect(mapStateToProps, {
    principalChanged
})(App);

calculate.js

// call the { principal } variable from the store
// somehow
// maybe I should use mergeProps
export const principal2 = (principal) => {
     return ( { principal * 2 } ); // calculating
};

export const principal3 = () => {
     return ( { principal2 / 4 } ); // calculating
};

I don't know how to connect state.principal.props to calculate.js. Maybe I should use mergeProps?

Body:
You need to use actions and reducers

Basically, in some part of your code you need to dispatch an action and resolve it with your reducer.

So you will need to create the action file and the reducer file for solve calculate and the root reducer to import this reducer and another that you will have.

Obs.: consider use some eslint rule to improve your code.

For example:

const mapStateToProps = state => {
   return {
      principal: state.form.principal
   };
};

could be:

const mapStateToProps = state => ({
   principal: state.form.principal
});

And the statefull class could be stateless class:

const App = ({ principal, principalChanged }) => (
            <Card>
               <Input
                 placeholder="Placeholder"
                 label="Label"
                 onChangeText={principalChanged}
                 value={principal}
                />
              `Current state of the variable: ${principal}`{/n}
              `New variable: ${principal2}`
              `New variable: ${principal3}`
            </Card>
        );


问:
Open a local PDF file on  tag
I'm running create-react-app, and I want to open a local PDF file stored inside my repo with a relative path.

```<code><a href="../file.pdf" target="_blank">
    <button name="Click here" />
</a>
</code>```

After I click it, it takes me to localhost:3000/file.pdf. How do I open up a new window with a PDF?

答:
you need to include the type</p>

```<code><a href="../file.pdf" type="application/pdf" target="_blank">
</code>```

Title: Open a local PDF file on <a> tag

Body:
I'm running create-react-app, and I want to open a local PDF file stored inside my repo with a relative path.

    <button name="Click here" />

After I click it, it takes me to localhost:3000/file.pdf. How do I open up a new window with a PDF?

Body:
you need to include the type

<a href="../file.pdf" type="application/pdf" target="_blank">