问:
WPF how to clear the texbox content in list view using MVVM
I am using below code and MVVM observable, but "Clear" button not clears the content of text boxes.

What I need to do here?

MainWindow.xaml

```<code><Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="30*"/>
        <RowDefinition Height="10*"/>
    </Grid.RowDefinitions>
    <Grid>
        <ListView ItemsSource="{Binding Credentials, Mode=OneWay}">
            <ListView.View>
                <GridView>
                    <GridViewColumn  Header="User Name">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding UserName}" Width="100"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn  Header="Password">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Password}" Width="100"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
    <Grid Grid.Row="1" >
        <Button Grid.Column="0" Content="Clear" Command="{Binding ClearTextBoxCommand}" Width="150"/>
    </Grid>

</Grid>
</code>```

MainWindow.xaml.cs

```<code>public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MyViewModel();
    }
}
</code>```

MyViewModel.cs

```<code>public class MyViewModel : INotifyPropertyChanged
{
    private ObservableCollection<Credential> _credentials;

    public RelayCommand ClearTextBoxCommand { get; }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)
    {
        var handler = PropertyChanged;
        handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public ObservableCollection<Credential> Credentials
    {
        get => _credentials;
        set
        {
            if (value == _credentials)
                return;

            _credentials = value;
            OnPropertyChanged();
        }
    }

    public MyViewModel()
    {
        var data = new List<Credential> {new Credential {UserName = "user1", Password = "password1"}};
        _credentials = new ObservableCollection<Credential>(data);

        ClearTextBoxCommand = new RelayCommand(ClearTextBox);
    }

    private void ClearTextBox()
    {
        var data = new List<Credential> { new Credential { UserName = "", Password = "" } };
        _credentials = new ObservableCollection<Credential>(data);
        MessageBox.Show("clear done!");
    }
}

public class Credential
{
    public string UserName { get; set; }
    public string Password { get; set; }
}
</code>```

答:
This is working at my Application

View:

```<code><UserControl x:Class="PRWSolution.UI.View.MachineView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:PRWSolution.UI.View"
         xmlns:language="clr-namespace:PRWSolution.UI.Properties.Langs"
         xmlns:setting="clr-namespace:PRWSolution.UI.Properties"
         mc:Ignorable="d"
         DataContext="{Binding Machine, Source={StaticResource Locator}}"
         xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
         xmlns:ie="http://schemas.microsoft.com/expression/2010/interactivity"
         xmlns:cmd="http://www.galasoft.ch/mvvmlight"
         TextElement.Foreground="{DynamicResource MaterialDesignBody}"
         Background="{DynamicResource MaterialDesignPaper}"
         TextElement.FontWeight="Medium"
         TextElement.FontSize="14"
         FontFamily="{materialDesign:MaterialDesignFont}">

<Grid>
    <StackPanel Orientation="Vertical">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>

            <Grid Grid.ColumnSpan="2">
                <!--Toolbar for interaction-->
                <ToolBarTray Grid.Column="0" Margin="0,5,0,0">
                    <ToolBar Style="{DynamicResource MaterialDesignToolBar}" ClipToBounds="False">
                        <Button x:Name="SaveMachine" ToolTip="Save" Command="{Binding SaveCommand, Mode=OneWay}">
                            <materialDesign:PackIcon Kind="ContentSave" />
                        </Button>

                        <Button x:Name="EditeMachine" ToolTip="Edit" Command="{Binding UpdateCommand, Mode=OneWay}">
                            <materialDesign:PackIcon Kind="Edit" />
                        </Button>

                        <Button x:Name="DeleteMachine" ToolTip="Delete" Command="{Binding DeleteCommand, Mode=OneWay}">
                            <materialDesign:PackIcon Kind="Delete" />
                        </Button>

                        <Separator />

                        <Button x:Name="ClearForm" ToolTip="Clear Form">
                            <materialDesign:PackIcon Kind="LayersClear" />
                        </Button>
                    </ToolBar>
                </ToolBarTray>

                <ToolBarTray Grid.Column="1" HorizontalAlignment="Right" Margin="0,5,0,0">
                    <ToolBar Style="{DynamicResource MaterialDesignToolBar}" ClipToBounds="False">
                        <Button x:Name="ExportMachine" ToolTip="Export" Click="ExportMachine_Click">
                            <materialDesign:PackIcon Kind="TableExport" />
                        </Button>
                    </ToolBar>
                </ToolBarTray>
            </Grid>
        </Grid>

        <!--Card for input database information-->
        <materialDesign:Card Margin="5">
            <StackPanel>

                <!--Expander general machine information-->
                <Expander Header="{x:Static language:Lang.ExpMachineData }" FontSize="11" HorizontalAlignment="Stretch" Margin="5,5,5,0">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>

                        <Grid Grid.Column="0">
                            <StackPanel Orientation="Vertical">
                                <TextBox x:Name="txtMachineID" Text="{Binding MachineID, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgMachineID}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                                <TextBox x:Name="txtCustomerID" Text="{Binding CustomerID, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgCustomerId}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                            </StackPanel>
                        </Grid>

                        <Grid Grid.Column="1">
                            <StackPanel Orientation="Vertical">
                                <ComboBox x:Name="cmbCustomerName" Width="300" HorizontalAlignment="Left" SelectedValuePath="ClientName" SelectedValue="{Binding CustomerName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ItemsSource="{Binding MachineCustomer.ClientDataContext, Source={StaticResource Locator}}" DisplayMemberPath="ClientName"  materialDesign:HintAssist.Hint="Customer Name" Margin="5"/>
                                <TextBox x:Name="txtCity" Text="{Binding City, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgCity}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                                <TextBox x:Name="txtCountry" Text="{Binding Country, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgCountry}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                            </StackPanel>
                        </Grid>
                    </Grid>
                </Expander>

                <Border Background="{DynamicResource MaterialDesignDivider}" Height="1" HorizontalAlignment="Stretch" SnapsToDevicePixels="True" />

                <!--Expander general part info-->
                <Expander Header="Part Information" FontSize="11" HorizontalAlignment="Stretch" Margin="5,0,5,0">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>

                        <Grid Grid.Column="0">
                            <StackPanel Orientation="Vertical">
                                <TextBox x:Name="txtPartName" Text="{Binding PartName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="Part Name" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                                <TextBox x:Name="txtPartNumber" Text="{Binding PartNumber, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="Part Number" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                                <TextBox x:Name="txtProject" Text="{Binding Project, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="Project" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                            </StackPanel>
                        </Grid>
                    </Grid>
                </Expander>

                <Border Background="{DynamicResource MaterialDesignDivider}" Height="1" HorizontalAlignment="Stretch" SnapsToDevicePixels="True" />

                <!--Expander for Machine Serials-->
                <Expander Header="{x:Static language:Lang.ExpMachineSerials}" FontSize="11" HorizontalAlignment="Stretch" Margin="5,0,5,0">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>

                        <Grid Grid.Column="0">
                            <StackPanel Orientation="Vertical">
                                <TextBox x:Name="txtSpindleC1" Text="{Binding SpindleC1, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgSpindleC1}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                                <TextBox x:Name="txtSpindleC2" Text="{Binding SpindleC2, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgSpindleC2}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                                <TextBox x:Name="txtHoningHead" Text="{Binding HoningHead, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgHoningHead}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                            </StackPanel>
                        </Grid>
                    </Grid>
                </Expander>

                <Border Background="{DynamicResource MaterialDesignDivider}" Height="1" HorizontalAlignment="Stretch" SnapsToDevicePixels="True" />

                <!--Expander for Softwareversion-->
                <Expander Header="{x:Static language:Lang.ExpSoftwareVersion}" FontSize="11" HorizontalAlignment="Stretch" Margin="5,0,5,5">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>

                        <Grid Grid.Column="0">
                            <StackPanel Orientation="Vertical">
                                <TextBox x:Name="txtNCVersion" Text="{Binding NCVersion, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgNCVersion}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                                <TextBox x:Name="txtHMIVersion" Text="{Binding HMIVersion, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgHMIVersion}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                                <TextBox x:Name="txtHRIVersion" Text="{Binding HRIVersion, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgHRIVersion}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                                <TextBox x:Name="txtAHSVersion" Text="{Binding AHSVersion, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgAHSVersion}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                            </StackPanel>
                        </Grid>
                    </Grid>
                </Expander>
            </StackPanel>
        </materialDesign:Card>

        <!--Database datagrid-->
        <DataGrid x:Name="MachineDataGrid" Margin="5" AutoGenerateColumns="False" MaxHeight="700" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" ItemsSource="{Binding DataContext, Mode=TwoWay}" SelectedItem="{Binding Path=MachineSelectedItem, Mode=TwoWay}">
            <ie:Interaction.Triggers>
                <ie:EventTrigger EventName="SelectionChanged">
                    <ie:InvokeCommandAction Command="{Binding SelectionChangedCommand}"  CommandParameter="{Binding ElementName=MachineDataGrid, Path=SelectedItem}"/>
                </ie:EventTrigger>
            </ie:Interaction.Triggers>
            <DataGrid.Columns>
                <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgMachineID}" Binding="{Binding MachineID, Mode=TwoWay}"/>
                <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgCustomerId}" Binding="{Binding CustomerID}"/>
                <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgCustomerName}" Binding="{Binding CustomerName}"/>
                <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgCity}" Binding="{Binding City}"/>
                <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgCountry}" Binding="{Binding Country}"/>
                <materialDesign:DataGridTextColumn Header="Part Name" Binding="{Binding PartName}"/>
                <materialDesign:DataGridTextColumn Header="Part Number" Binding="{Binding PartNumber}"/>
                <materialDesign:DataGridTextColumn Header="Project" Binding="{Binding Project}"/>
                <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgSpindleC1}" Binding="{Binding SpindleC1}"/>
                <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgSpindleC2}" Binding="{Binding SpindleC2}"/>
                <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgHoningHead}" Binding="{Binding HoningHead}"/>
                <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgNCVersion}" Binding="{Binding NCVersion}"/>
                <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgHMIVersion}" Binding="{Binding HMIVersion}"/>
                <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgHRIVersion}" Binding="{Binding HRIVersion}"/>
                <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgAHSVersion}" Binding="{Binding AHSVersion}"/>
            </DataGrid.Columns>
        </DataGrid>
    </StackPanel>
</Grid>
</code>```

ViewModel:

```<code>public class MachineViewModel : ViewModelBase
{

    #region  public statments Textbox text

    //Public statments to get textbox text
    public string MachineID { get; set; }

    public string CustomerID { get; set; }

    public string CustomerName { get; set; }

    public string City { get; set; }

    public string Country { get; set; }
    public string PartName { get; set; }
    public string PartNumber { get; set; }
    public string Project { get; set; }

    public string SpindleC1 { get; set; }

    public string SpindleC2 { get; set; }

    public string HoningHead { get; set; }

    public string NCVersion { get; set; }

    public string HMIVersion { get; set; }

    public string HRIVersion { get; set; }

    public string AHSVersion { get; set; }
    #endregion

    //DialogService
    private IDialogService _dialogService;

    //Operation button for save, update, delete, selection changed and print
    public ICommand SaveCommand { get; private set; }
    public ICommand UpdateCommand { get; private set; }
    public ICommand DeleteCommand { get; private set; }
    public ICommand ClearCommand { get; private set; }
    public ICommand SelectionChangedCommand { get; set; }

    //observable collection for machine model
    public ObservableCollection<Machine> DataContext { get; set; }

    private Machine machineSelectedItem;
    public Machine MachineSelectedItem
    {
        get { return machineSelectedItem; }
        set { machineSelectedItem = value; }
    }

    public object MachineDataGrid { get; set; }

    public List<MachineClient> cmbclientDetails;

    //PRWContext for general use
    private PRWContext context = new PRWContext();

    public MachineViewModel()
    {
        //Commands for save, update, delete and print
        SaveCommand = new RelayCommand(() => ExecuteSaveCommand());
        UpdateCommand = new RelayCommand(() => ExecuteUpdateCommand());
        DeleteCommand = new RelayCommand(() => ExecuteDeleteCommand());
        ClearCommand = new RelayCommand(() => ExecuteClearCommand());
        SelectionChangedCommand = new RelayCommand(() => ExecuteSelectionChangedCommand());

        //Load the data from PRW Database to datagrid
        LoadData();

        //Normelly done with dependency injection
        _dialogService = new DialogService();
    }

    //execute save
    private void ExecuteSaveCommand()
    {
        Machine machine = new Machine
        {
            //Machine data
            MachineID = MachineID,
            CustomerID = CustomerID,
            CustomerName = CustomerName,
            City = City,
            Country = Country,

            //Part data
            PartName = PartName,
            PartNumber = PartNumber,
            Project = Project,

            //Serial data
            SpindleC1 = SpindleC1,
            SpindleC2 = SpindleC2,
            HoningHead = HoningHead,

            //Softwareversion data
            NCVersion = NCVersion,
            HMIVersion = HMIVersion,
            HRIVersion = HRIVersion,
            AHSVersion = AHSVersion
        };

        context.Machines.Add(machine);
        context.SaveChanges();

        ClearContent();
    }

    //execute update
    private void ExecuteUpdateCommand()
    {
        Machine machine = context.Machines.FirstOrDefault(w => w.MachineID == MachineID);

        machine.CustomerID = CustomerID;
        machine.CustomerName = CustomerName;
        machine.City = City;
        machine.Country = Country;
        machine.PartName = PartName;
        machine.PartNumber = PartNumber;
        machine.Project = Project;
        machine.SpindleC1 = SpindleC1;
        machine.SpindleC2 = SpindleC2;
        machine.HoningHead = HoningHead;
        machine.NCVersion = NCVersion;
        machine.HMIVersion = HMIVersion;
        machine.HRIVersion = HRIVersion;
        machine.AHSVersion = AHSVersion;

        context.Machines.AddOrUpdate(machine);
        context.SaveChanges();
        ClearContent();
    }

    //execute delete
    private void ExecuteDeleteCommand()
    {
        if (machineSelectedItem != null)
        {
            var dialog = new YesNoDialogViewModel("Question", "Your are Sure to Delete the Record?");
            var result = _dialogService.OpenDialog(dialog);
            if (result == DialogResults.Yes)
            {
                Machine machine = context.Machines.FirstOrDefault(w => w.MachineID == MachineID);
                context.Machines.Remove(machine);
                context.SaveChanges();
                ClearContent();
            }
        }
        else
        {
            var dialog = new AlertDialogViewModel("Attention", "Please select a Record!");
            var result = _dialogService.OpenDialog(dialog);
            Console.WriteLine(result);
        }

    }

    //execute clear
    private void ExecuteClearCommand()
    {
        ClearContent();
    }

    // Execute selection changed
    private void ExecuteSelectionChangedCommand()
    {
        if(machineSelectedItem != null)
        {
            MachineID = machineSelectedItem.MachineID?.ToString() ?? "";
            CustomerID = machineSelectedItem.CustomerID?.ToString() ?? "";
            CustomerName = machineSelectedItem.CustomerName?.ToString() ?? "";
            City = machineSelectedItem.City?.ToString() ?? "";
            Country = machineSelectedItem.Country?.ToString() ?? "";
            PartName = machineSelectedItem.PartName?.ToString() ?? "";
            PartNumber = machineSelectedItem.PartNumber?.ToString() ?? "";
            Project = machineSelectedItem.Project?.ToString() ?? "";
            SpindleC1 = machineSelectedItem.SpindleC1?.ToString() ?? "";
            SpindleC2 = machineSelectedItem.SpindleC2?.ToString() ?? "";
            HoningHead = machineSelectedItem.HoningHead?.ToString() ?? "";
            NCVersion = machineSelectedItem.NCVersion?.ToString() ?? "";
            HMIVersion = machineSelectedItem.HMIVersion?.ToString() ?? "";
            HRIVersion = machineSelectedItem.HRIVersion?.ToString() ?? "";
            AHSVersion = machineSelectedItem.AHSVersion?.ToString() ?? "";
        }
        else
        {
            machineSelectedItem = null;
        }

    }

    //Load data from database to grid
    private void LoadData()
    {
        context.Machines.Load();
        this.DataContext = context.Machines.Local;
    }

    //Clear textboxes
    private void ClearContent()
    {
        MachineID = string.Empty;
        CustomerID = string.Empty;
        CustomerName = string.Empty;
        City = string.Empty;
        PartName = string.Empty;
        PartNumber = string.Empty;
        Project = string.Empty;
        Country = string.Empty;
        SpindleC1 = string.Empty;
        SpindleC2 = string.Empty;
        HoningHead = string.Empty;
        NCVersion = string.Empty;
        HMIVersion = string.Empty;
        HRIVersion = string.Empty;
        AHSVersion = string.Empty;
    }
}
</code>```

Body:
I am using below code and MVVM observable, but "Clear" button not clears the content of text boxes.

What I need to do here?

MainWindow.xaml

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="30*"/>
        <RowDefinition Height="10*"/>
    </Grid.RowDefinitions>
    <Grid>
        <ListView ItemsSource="{Binding Credentials, Mode=OneWay}">
            <ListView.View>
                <GridView>
                    <GridViewColumn  Header="User Name">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding UserName}" Width="100"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn  Header="Password">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Password}" Width="100"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
    <Grid Grid.Row="1" >
        <Button Grid.Column="0" Content="Clear" Command="{Binding ClearTextBoxCommand}" Width="150"/>
    </Grid>

</Grid>

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MyViewModel();
    }
}

MyViewModel.cs

public class MyViewModel : INotifyPropertyChanged
{
    private ObservableCollection<Credential> _credentials;

    public RelayCommand ClearTextBoxCommand { get; }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)
    {
        var handler = PropertyChanged;
        handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public ObservableCollection<Credential> Credentials
    {
        get => _credentials;
        set
        {
            if (value == _credentials)
                return;

            _credentials = value;
            OnPropertyChanged();
        }
    }

    public MyViewModel()
    {
        var data = new List<Credential> {new Credential {UserName = "user1", Password = "password1"}};
        _credentials = new ObservableCollection<Credential>(data);

        ClearTextBoxCommand = new RelayCommand(ClearTextBox);
    }

    private void ClearTextBox()
    {
        var data = new List<Credential> { new Credential { UserName = "", Password = "" } };
        _credentials = new ObservableCollection<Credential>(data);
        MessageBox.Show("clear done!");
    }
}

public class Credential
{
    public string UserName { get; set; }
    public string Password { get; set; }
}

Body:
This is working at my Application

View:

<UserControl x:Class="PRWSolution.UI.View.MachineView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:PRWSolution.UI.View"
         xmlns:language="clr-namespace:PRWSolution.UI.Properties.Langs"
         xmlns:setting="clr-namespace:PRWSolution.UI.Properties"
         mc:Ignorable="d"
         DataContext="{Binding Machine, Source={StaticResource Locator}}"
         xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
         xmlns:ie="http://schemas.microsoft.com/expression/2010/interactivity"
         xmlns:cmd="http://www.galasoft.ch/mvvmlight"
         TextElement.Foreground="{DynamicResource MaterialDesignBody}"
         Background="{DynamicResource MaterialDesignPaper}"
         TextElement.FontWeight="Medium"
         TextElement.FontSize="14"
         FontFamily="{materialDesign:MaterialDesignFont}">

<Grid>
    <StackPanel Orientation="Vertical">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>

            <Grid Grid.ColumnSpan="2">
                <!--Toolbar for interaction-->
                <ToolBarTray Grid.Column="0" Margin="0,5,0,0">
                    <ToolBar Style="{DynamicResource MaterialDesignToolBar}" ClipToBounds="False">
                        <Button x:Name="SaveMachine" ToolTip="Save" Command="{Binding SaveCommand, Mode=OneWay}">
                            <materialDesign:PackIcon Kind="ContentSave" />
                        </Button>

                        <Button x:Name="EditeMachine" ToolTip="Edit" Command="{Binding UpdateCommand, Mode=OneWay}">
                            <materialDesign:PackIcon Kind="Edit" />
                        </Button>

                        <Button x:Name="DeleteMachine" ToolTip="Delete" Command="{Binding DeleteCommand, Mode=OneWay}">
                            <materialDesign:PackIcon Kind="Delete" />
                        </Button>

                        <Separator />

                        <Button x:Name="ClearForm" ToolTip="Clear Form">
                            <materialDesign:PackIcon Kind="LayersClear" />
                        </Button>
                    </ToolBar>
                </ToolBarTray>

                <ToolBarTray Grid.Column="1" HorizontalAlignment="Right" Margin="0,5,0,0">
                    <ToolBar Style="{DynamicResource MaterialDesignToolBar}" ClipToBounds="False">
                        <Button x:Name="ExportMachine" ToolTip="Export" Click="ExportMachine_Click">
                            <materialDesign:PackIcon Kind="TableExport" />
                        </Button>
                    </ToolBar>
                </ToolBarTray>
            </Grid>
        </Grid>

        <!--Card for input database information-->
        <materialDesign:Card Margin="5">
            <StackPanel>

                <!--Expander general machine information-->
                <Expander Header="{x:Static language:Lang.ExpMachineData }" FontSize="11" HorizontalAlignment="Stretch" Margin="5,5,5,0">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>

                        <Grid Grid.Column="0">
                            <StackPanel Orientation="Vertical">
                                <TextBox x:Name="txtMachineID" Text="{Binding MachineID, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgMachineID}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                                <TextBox x:Name="txtCustomerID" Text="{Binding CustomerID, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgCustomerId}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                            </StackPanel>
                        </Grid>

                        <Grid Grid.Column="1">
                            <StackPanel Orientation="Vertical">
                                <ComboBox x:Name="cmbCustomerName" Width="300" HorizontalAlignment="Left" SelectedValuePath="ClientName" SelectedValue="{Binding CustomerName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ItemsSource="{Binding MachineCustomer.ClientDataContext, Source={StaticResource Locator}}" DisplayMemberPath="ClientName"  materialDesign:HintAssist.Hint="Customer Name" Margin="5"/>
                                <TextBox x:Name="txtCity" Text="{Binding City, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgCity}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                                <TextBox x:Name="txtCountry" Text="{Binding Country, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgCountry}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                            </StackPanel>
                        </Grid>
                    </Grid>
                </Expander>

                <Border Background="{DynamicResource MaterialDesignDivider}" Height="1" HorizontalAlignment="Stretch" SnapsToDevicePixels="True" />

                <!--Expander general part info-->
                <Expander Header="Part Information" FontSize="11" HorizontalAlignment="Stretch" Margin="5,0,5,0">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>

                        <Grid Grid.Column="0">
                            <StackPanel Orientation="Vertical">
                                <TextBox x:Name="txtPartName" Text="{Binding PartName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="Part Name" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                                <TextBox x:Name="txtPartNumber" Text="{Binding PartNumber, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="Part Number" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                                <TextBox x:Name="txtProject" Text="{Binding Project, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="Project" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                            </StackPanel>
                        </Grid>
                    </Grid>
                </Expander>

                <Border Background="{DynamicResource MaterialDesignDivider}" Height="1" HorizontalAlignment="Stretch" SnapsToDevicePixels="True" />

                <!--Expander for Machine Serials-->
                <Expander Header="{x:Static language:Lang.ExpMachineSerials}" FontSize="11" HorizontalAlignment="Stretch" Margin="5,0,5,0">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>

                        <Grid Grid.Column="0">
                            <StackPanel Orientation="Vertical">
                                <TextBox x:Name="txtSpindleC1" Text="{Binding SpindleC1, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgSpindleC1}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                                <TextBox x:Name="txtSpindleC2" Text="{Binding SpindleC2, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgSpindleC2}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                                <TextBox x:Name="txtHoningHead" Text="{Binding HoningHead, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgHoningHead}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                            </StackPanel>
                        </Grid>
                    </Grid>
                </Expander>

                <Border Background="{DynamicResource MaterialDesignDivider}" Height="1" HorizontalAlignment="Stretch" SnapsToDevicePixels="True" />

                <!--Expander for Softwareversion-->
                <Expander Header="{x:Static language:Lang.ExpSoftwareVersion}" FontSize="11" HorizontalAlignment="Stretch" Margin="5,0,5,5">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>

                        <Grid Grid.Column="0">
                            <StackPanel Orientation="Vertical">
                                <TextBox x:Name="txtNCVersion" Text="{Binding NCVersion, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgNCVersion}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                                <TextBox x:Name="txtHMIVersion" Text="{Binding HMIVersion, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgHMIVersion}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                                <TextBox x:Name="txtHRIVersion" Text="{Binding HRIVersion, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgHRIVersion}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                                <TextBox x:Name="txtAHSVersion" Text="{Binding AHSVersion, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgAHSVersion}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
                            </StackPanel>
                        </Grid>
                    </Grid>
                </Expander>
            </StackPanel>
        </materialDesign:Card>

        <!--Database datagrid-->
        <DataGrid x:Name="MachineDataGrid" Margin="5" AutoGenerateColumns="False" MaxHeight="700" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" ItemsSource="{Binding DataContext, Mode=TwoWay}" SelectedItem="{Binding Path=MachineSelectedItem, Mode=TwoWay}">
            <ie:Interaction.Triggers>
                <ie:EventTrigger EventName="SelectionChanged">
                    <ie:InvokeCommandAction Command="{Binding SelectionChangedCommand}"  CommandParameter="{Binding ElementName=MachineDataGrid, Path=SelectedItem}"/>
                </ie:EventTrigger>
            </ie:Interaction.Triggers>
            <DataGrid.Columns>
                <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgMachineID}" Binding="{Binding MachineID, Mode=TwoWay}"/>
                <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgCustomerId}" Binding="{Binding CustomerID}"/>
                <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgCustomerName}" Binding="{Binding CustomerName}"/>
                <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgCity}" Binding="{Binding City}"/>
                <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgCountry}" Binding="{Binding Country}"/>
                <materialDesign:DataGridTextColumn Header="Part Name" Binding="{Binding PartName}"/>
                <materialDesign:DataGridTextColumn Header="Part Number" Binding="{Binding PartNumber}"/>
                <materialDesign:DataGridTextColumn Header="Project" Binding="{Binding Project}"/>
                <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgSpindleC1}" Binding="{Binding SpindleC1}"/>
                <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgSpindleC2}" Binding="{Binding SpindleC2}"/>
                <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgHoningHead}" Binding="{Binding HoningHead}"/>
                <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgNCVersion}" Binding="{Binding NCVersion}"/>
                <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgHMIVersion}" Binding="{Binding HMIVersion}"/>
                <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgHRIVersion}" Binding="{Binding HRIVersion}"/>
                <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgAHSVersion}" Binding="{Binding AHSVersion}"/>
            </DataGrid.Columns>
        </DataGrid>
    </StackPanel>
</Grid>

ViewModel:

public class MachineViewModel : ViewModelBase
{

    #region  public statments Textbox text

    //Public statments to get textbox text
    public string MachineID { get; set; }

    public string CustomerID { get; set; }

    public string CustomerName { get; set; }

    public string City { get; set; }

    public string Country { get; set; }
    public string PartName { get; set; }
    public string PartNumber { get; set; }
    public string Project { get; set; }

    public string SpindleC1 { get; set; }

    public string SpindleC2 { get; set; }

    public string HoningHead { get; set; }

    public string NCVersion { get; set; }

    public string HMIVersion { get; set; }

    public string HRIVersion { get; set; }

    public string AHSVersion { get; set; }
    #endregion

    //DialogService
    private IDialogService _dialogService;

    //Operation button for save, update, delete, selection changed and print
    public ICommand SaveCommand { get; private set; }
    public ICommand UpdateCommand { get; private set; }
    public ICommand DeleteCommand { get; private set; }
    public ICommand ClearCommand { get; private set; }
    public ICommand SelectionChangedCommand { get; set; }

    //observable collection for machine model
    public ObservableCollection<Machine> DataContext { get; set; }

    private Machine machineSelectedItem;
    public Machine MachineSelectedItem
    {
        get { return machineSelectedItem; }
        set { machineSelectedItem = value; }
    }

    public object MachineDataGrid { get; set; }

    public List<MachineClient> cmbclientDetails;

    //PRWContext for general use
    private PRWContext context = new PRWContext();

    public MachineViewModel()
    {
        //Commands for save, update, delete and print
        SaveCommand = new RelayCommand(() => ExecuteSaveCommand());
        UpdateCommand = new RelayCommand(() => ExecuteUpdateCommand());
        DeleteCommand = new RelayCommand(() => ExecuteDeleteCommand());
        ClearCommand = new RelayCommand(() => ExecuteClearCommand());
        SelectionChangedCommand = new RelayCommand(() => ExecuteSelectionChangedCommand());

        //Load the data from PRW Database to datagrid
        LoadData();

        //Normelly done with dependency injection
        _dialogService = new DialogService();
    }

    //execute save
    private void ExecuteSaveCommand()
    {
        Machine machine = new Machine
        {
            //Machine data
            MachineID = MachineID,
            CustomerID = CustomerID,
            CustomerName = CustomerName,
            City = City,
            Country = Country,

            //Part data
            PartName = PartName,
            PartNumber = PartNumber,
            Project = Project,

            //Serial data
            SpindleC1 = SpindleC1,
            SpindleC2 = SpindleC2,
            HoningHead = HoningHead,

            //Softwareversion data
            NCVersion = NCVersion,
            HMIVersion = HMIVersion,
            HRIVersion = HRIVersion,
            AHSVersion = AHSVersion
        };

        context.Machines.Add(machine);
        context.SaveChanges();

        ClearContent();
    }

    //execute update
    private void ExecuteUpdateCommand()
    {
        Machine machine = context.Machines.FirstOrDefault(w => w.MachineID == MachineID);

        machine.CustomerID = CustomerID;
        machine.CustomerName = CustomerName;
        machine.City = City;
        machine.Country = Country;
        machine.PartName = PartName;
        machine.PartNumber = PartNumber;
        machine.Project = Project;
        machine.SpindleC1 = SpindleC1;
        machine.SpindleC2 = SpindleC2;
        machine.HoningHead = HoningHead;
        machine.NCVersion = NCVersion;
        machine.HMIVersion = HMIVersion;
        machine.HRIVersion = HRIVersion;
        machine.AHSVersion = AHSVersion;

        context.Machines.AddOrUpdate(machine);
        context.SaveChanges();
        ClearContent();
    }

    //execute delete
    private void ExecuteDeleteCommand()
    {
        if (machineSelectedItem != null)
        {
            var dialog = new YesNoDialogViewModel("Question", "Your are Sure to Delete the Record?");
            var result = _dialogService.OpenDialog(dialog);
            if (result == DialogResults.Yes)
            {
                Machine machine = context.Machines.FirstOrDefault(w => w.MachineID == MachineID);
                context.Machines.Remove(machine);
                context.SaveChanges();
                ClearContent();
            }
        }
        else
        {
            var dialog = new AlertDialogViewModel("Attention", "Please select a Record!");
            var result = _dialogService.OpenDialog(dialog);
            Console.WriteLine(result);
        }

    }

    //execute clear
    private void ExecuteClearCommand()
    {
        ClearContent();
    }

    // Execute selection changed
    private void ExecuteSelectionChangedCommand()
    {
        if(machineSelectedItem != null)
        {
            MachineID = machineSelectedItem.MachineID?.ToString() ?? "";
            CustomerID = machineSelectedItem.CustomerID?.ToString() ?? "";
            CustomerName = machineSelectedItem.CustomerName?.ToString() ?? "";
            City = machineSelectedItem.City?.ToString() ?? "";
            Country = machineSelectedItem.Country?.ToString() ?? "";
            PartName = machineSelectedItem.PartName?.ToString() ?? "";
            PartNumber = machineSelectedItem.PartNumber?.ToString() ?? "";
            Project = machineSelectedItem.Project?.ToString() ?? "";
            SpindleC1 = machineSelectedItem.SpindleC1?.ToString() ?? "";
            SpindleC2 = machineSelectedItem.SpindleC2?.ToString() ?? "";
            HoningHead = machineSelectedItem.HoningHead?.ToString() ?? "";
            NCVersion = machineSelectedItem.NCVersion?.ToString() ?? "";
            HMIVersion = machineSelectedItem.HMIVersion?.ToString() ?? "";
            HRIVersion = machineSelectedItem.HRIVersion?.ToString() ?? "";
            AHSVersion = machineSelectedItem.AHSVersion?.ToString() ?? "";
        }
        else
        {
            machineSelectedItem = null;
        }

    }

    //Load data from database to grid
    private void LoadData()
    {
        context.Machines.Load();
        this.DataContext = context.Machines.Local;
    }

    //Clear textboxes
    private void ClearContent()
    {
        MachineID = string.Empty;
        CustomerID = string.Empty;
        CustomerName = string.Empty;
        City = string.Empty;
        PartName = string.Empty;
        PartNumber = string.Empty;
        Project = string.Empty;
        Country = string.Empty;
        SpindleC1 = string.Empty;
        SpindleC2 = string.Empty;
        HoningHead = string.Empty;
        NCVersion = string.Empty;
        HMIVersion = string.Empty;
        HRIVersion = string.Empty;
        AHSVersion = string.Empty;
    }
}


来源: stackexchange

问:
My kubernetes pods keep crashing with "CrashLoopBackOff" but I can't find any log
This is what I keep getting:

```<code>[root@centos-master ~]# kubectl get pods
NAME               READY     STATUS             RESTARTS   AGE
nfs-server-h6nw8   1/1       Running            0          1h
nfs-web-07rxz      0/1       CrashLoopBackOff   8          16m
nfs-web-fdr9h      0/1       CrashLoopBackOff   8          16m
</code>```

Below is output from describe pods
kubectl describe pods

```<code>Events:
  FirstSeen LastSeen    Count   From                SubobjectPath       Type        Reason      Message
  --------- --------    -----   ----                -------------       --------    ------      -------
  16m       16m     1   {default-scheduler }                    Normal      Scheduled   Successfully assigned nfs-web-fdr9h to centos-minion-2
  16m       16m     1   {kubelet centos-minion-2}   spec.containers{web}    Normal      Created     Created container with docker id 495fcbb06836
  16m       16m     1   {kubelet centos-minion-2}   spec.containers{web}    Normal      Started     Started container with docker id 495fcbb06836
  16m       16m     1   {kubelet centos-minion-2}   spec.containers{web}    Normal      Started     Started container with docker id d56f34ae4e8f
  16m       16m     1   {kubelet centos-minion-2}   spec.containers{web}    Normal      Created     Created container with docker id d56f34ae4e8f
  16m       16m     2   {kubelet centos-minion-2}               Warning     FailedSync  Error syncing pod, skipping: failed to "StartContainer" for "web" with CrashLoopBackOff: "Back-off 10s restarting failed container=web pod=nfs-web-fdr9h_default(461c937d-d870-11e6-98de-005056040cc2)"
</code>```

I have two pods: nfs-web-07rxz, nfs-web-fdr9h, but if I do kubectl logs nfs-web-07rxz or with -p option I don't see any log in both pods.

```<code>[root@centos-master ~]# kubectl logs nfs-web-07rxz -p
[root@centos-master ~]# kubectl logs nfs-web-07rxz
</code>```

This is my replicationController yaml file:
replicationController yaml file

```<code>apiVersion: v1 kind: ReplicationController metadata:   name: nfs-web spec:   replicas: 2   selector:
    role: web-frontend   template:
    metadata:
      labels:
        role: web-frontend
    spec:
      containers:
      - name: web
        image: eso-cmbu-docker.artifactory.eng.vmware.com/demo-container:demo-version3.0
        ports:
          - name: web
            containerPort: 80
        securityContext:
          privileged: true
</code>```

My Docker image was made from this simple docker file:

```<code>FROM ubuntu
RUN apt-get update
RUN apt-get install -y nginx
RUN apt-get install -y nfs-common
</code>```

I am running my kubernetes cluster on CentOs-1611, kube version:

```<code>[root@centos-master ~]# kubectl version
Client Version: version.Info{Major:"1", Minor:"3", GitVersion:"v1.3.0", GitCommit:"86dc49aa137175378ac7fba7751c3d3e7f18e5fc", GitTreeState:"clean", BuildDate:"2016-12-15T16:57:18Z", GoVersion:"go1.6.3", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"3", GitVersion:"v1.3.0", GitCommit:"86dc49aa137175378ac7fba7751c3d3e7f18e5fc", GitTreeState:"clean", BuildDate:"2016-12-15T16:57:18Z", GoVersion:"go1.6.3", Compiler:"gc", Platform:"linux/amd64"}
</code>```

If I run the docker image by docker run I was able to run the image without any issue, only through kubernetes I got the crash.

Can someone help me out, how can I debug without seeing any log?

答:
In your yaml file, add command and args lines:

```<code>...
containers:
      - name: api
        image: localhost:5000/image-name
        command: [ "sleep" ]
        args: [ "infinity" ]
...
</code>```

Works for me.

ContentLicense: CC BY-SA 4.0

Body:
This is what I keep getting:

[root@centos-master ~]# kubectl get pods
NAME               READY     STATUS             RESTARTS   AGE
nfs-server-h6nw8   1/1       Running            0          1h
nfs-web-07rxz      0/1       CrashLoopBackOff   8          16m
nfs-web-fdr9h      0/1       CrashLoopBackOff   8          16m

Below is output from describe pods
kubectl describe pods

Events:
  FirstSeen LastSeen    Count   From                SubobjectPath       Type        Reason      Message
  --------- --------    -----   ----                -------------       --------    ------      -------
  16m       16m     1   {default-scheduler }                    Normal      Scheduled   Successfully assigned nfs-web-fdr9h to centos-minion-2
  16m       16m     1   {kubelet centos-minion-2}   spec.containers{web}    Normal      Created     Created container with docker id 495fcbb06836
  16m       16m     1   {kubelet centos-minion-2}   spec.containers{web}    Normal      Started     Started container with docker id 495fcbb06836
  16m       16m     1   {kubelet centos-minion-2}   spec.containers{web}    Normal      Started     Started container with docker id d56f34ae4e8f
  16m       16m     1   {kubelet centos-minion-2}   spec.containers{web}    Normal      Created     Created container with docker id d56f34ae4e8f
  16m       16m     2   {kubelet centos-minion-2}               Warning     FailedSync  Error syncing pod, skipping: failed to "StartContainer" for "web" with CrashLoopBackOff: "Back-off 10s restarting failed container=web pod=nfs-web-fdr9h_default(461c937d-d870-11e6-98de-005056040cc2)"

I have two pods: nfs-web-07rxz, nfs-web-fdr9h, but if I do kubectl logs nfs-web-07rxz or with -p option I don't see any log in both pods.

[root@centos-master ~]# kubectl logs nfs-web-07rxz -p
[root@centos-master ~]# kubectl logs nfs-web-07rxz

This is my replicationController yaml file:
replicationController yaml file

apiVersion: v1 kind: ReplicationController metadata:   name: nfs-web spec:   replicas: 2   selector:
    role: web-frontend   template:
    metadata:
      labels:
        role: web-frontend
    spec:
      containers:
      - name: web
        image: eso-cmbu-docker.artifactory.eng.vmware.com/demo-container:demo-version3.0
        ports:
          - name: web
            containerPort: 80
        securityContext:
          privileged: true

My Docker image was made from this simple docker file:

FROM ubuntu
RUN apt-get update
RUN apt-get install -y nginx
RUN apt-get install -y nfs-common

I am running my kubernetes cluster on CentOs-1611, kube version:

[root@centos-master ~]# kubectl version
Client Version: version.Info{Major:"1", Minor:"3", GitVersion:"v1.3.0", GitCommit:"86dc49aa137175378ac7fba7751c3d3e7f18e5fc", GitTreeState:"clean", BuildDate:"2016-12-15T16:57:18Z", GoVersion:"go1.6.3", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"3", GitVersion:"v1.3.0", GitCommit:"86dc49aa137175378ac7fba7751c3d3e7f18e5fc", GitTreeState:"clean", BuildDate:"2016-12-15T16:57:18Z", GoVersion:"go1.6.3", Compiler:"gc", Platform:"linux/amd64"}

If I run the docker image by docker run I was able to run the image without any issue, only through kubernetes I got the crash.

Can someone help me out, how can I debug without seeing any log?

Body:
In your yaml file, add command and args lines:

...
containers:
      - name: api
        image: localhost:5000/image-name
        command: [ "sleep" ]
        args: [ "infinity" ]
...

Works for me.


问:
How can i trim spaces in object.values?
my object.values(article.data) returns

```<code>[' This is ']
['is ']
['a']
['sentence ']
</code>```

how can i trim and remove the spaces so it becomes

```<code>['Thisis']
['is']
['a']
['sentence']
</code>```

答:
With map you can achive it by trimming it:

var data=[['    This is    '],['is '],['a '],['   sentence']];
var result = data.map(val=>[val[0].trim()]);
console.log(result);```

Title: How can i trim spaces in object.values?

Body:
my object.values(article.data) returns

[' This is ']
['is ']
['a']
['sentence ']

how can i trim and remove the spaces so it becomes

['Thisis']
['is']
['a']
['sentence']


问:
Uncaught Reference Error : $ is not defined?
I am beginner in JavaScript and Html. Currently I am learning to make chrome extensions.

My manifest.json file is like  this:

```<code>{
    "manifest_version": 2,
    "name": "Hello World",
    "version": "1.0",
    "description": "A Hello world extensions",
    "icons": {
        "128": "128chat.png",
        "48": "48chat.png",
        "16": "16chat.png"
    },
    "browser_action": {
        "default_icon": "16chat.png",
        "default_popup": "popup.html"
    }
}
</code>```

My popup.html file  is :

```<code><html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World</title>

    <script src="popup.js"></script>
    <script src="jquery-3.5.1.min.js"></script>

</head>

<body>
    <h1 id="greet">Hello</h1>
    <input type="text" id="name">
</body>

</html>
</code>```

My popup.js file is :

```<code>$(function () {
    $('#name').keyup(function () {
        $('#greet').text("hello " + $('#name').val());
    });
});
</code>```

I am using "jquery-3.5.1.min.js" jquery file in my project.

But while running extension I am getting "Uncaught Reference Error : $ is not defined"

Can you please tell me what is wrong in my code?

答:
The HTML page is parsed sequentially from beginning to end.

So In your code popup.js file is loading before jquery-3.5.1.min.js.

You should first load jquery-3.5.1.min.js and then popup.js.

```<code><html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World</title>

    <script src="jquery-3.5.1.min.js"></script>
    <script src="popup.js"></script>

</head>

<body>
    <h1 id="greet">Hello</h1>
    <input type="text" id="name">
</body>

</html>
</code>```

Hope this will help you.

Body:
I am beginner in JavaScript and Html. Currently I am learning to make chrome extensions.

My manifest.json file is like  this:

{
    "manifest_version": 2,
    "name": "Hello World",
    "version": "1.0",
    "description": "A Hello world extensions",
    "icons": {
        "128": "128chat.png",
        "48": "48chat.png",
        "16": "16chat.png"
    },
    "browser_action": {
        "default_icon": "16chat.png",
        "default_popup": "popup.html"
    }
}

My popup.html file  is :

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World</title>

Hello

    <input type="text" id="name">

My popup.js file is :

$(function () {
    $('#name').keyup(function () {
        $('#greet').text("hello " + $('#name').val());
    });
});

I am using "jquery-3.5.1.min.js" jquery file in my project.

But while running extension I am getting "Uncaught Reference Error : $ is not defined"

Can you please tell me what is wrong in my code?

Body:
The HTML page is parsed sequentially from beginning to end.

So In your code popup.js file is loading before jquery-3.5.1.min.js.

You should first load jquery-3.5.1.min.js and then popup.js.

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World</title>

    <script src="jquery-3.5.1.min.js"></script>
    <script src="popup.js"></script>

</head>

<body>
    <h1 id="greet">Hello</h1>
    <input type="text" id="name">
</body>

</html>

Hope this will help you.


问:
Joining 2 tables for value comparision
I have 2 tables which contain data as follows:

```<code>Table1-
Col1.  Col2
A1.     B1
A1.     B2

Table2-
Col1.  Col2
A1.     C1
A1.     C2
</code>```

Now when I am joining these 2 tables to compare col2, sometimes I get the output like A1-B1-C1;A1-B2-C2 and some time I get it as A1-B1-C2;A1-B2-C1.
But I don't want it to come in the second form ever.can anyone suggest any query which will help me achieve this.
Thanks in advance

答:
Yet another option is to use the RANK windows function as follows:

```<code>SELECT T1C1, T1C2, T2C2 FROM
(SELECT T1.COL1 T1C1, T1.COL2 T1C2, T2.COL1 T2C1, T2.COL2 T2C2,
       RANK() OVER (PARTITION BY T1.COL1 ORDER BY T1.COL2) AS T1RN,
       RANK() OVER (PARTITION BY T1.COL1 ORDER BY T2.COL2) AS T2RN
FROM TABLE1 T1 JOIN TABLE2 T2 ON T1.COL1 = T2.COL1)
WHERE T1RN = T2RN;
</code>```

Title: Joining 2 tables for value comparision

Body:
I have 2 tables which contain data as follows:

Table1-
Col1.  Col2
A1.     B1
A1.     B2

Table2-
Col1.  Col2
A1.     C1
A1.     C2

Now when I am joining these 2 tables to compare col2, sometimes I get the output like A1-B1-C1;A1-B2-C2 and some time I get it as A1-B1-C2;A1-B2-C1.
But I don't want it to come in the second form ever.can anyone suggest any query which will help me achieve this.
Thanks in advance

Body:
Yet another option is to use the RANK windows function as follows:

SELECT T1C1, T1C2, T2C2 FROM
(SELECT T1.COL1 T1C1, T1.COL2 T1C2, T2.COL1 T2C1, T2.COL2 T2C2,
       RANK() OVER (PARTITION BY T1.COL1 ORDER BY T1.COL2) AS T1RN,
       RANK() OVER (PARTITION BY T1.COL1 ORDER BY T2.COL2) AS T2RN
FROM TABLE1 T1 JOIN TABLE2 T2 ON T1.COL1 = T2.COL1)
WHERE T1RN = T2RN;


问:
Can someone please point out what's wrong here
I made sure to have all the exceptions I think are needed but it keeps giving me this error:

exception FileNotFoundException has already been caught
catch(FileNotFoundException fnfe)

```<code>public class SNIDDb
{
  private char delimiter;
  private String name;
  private BufferedReader br;

  public SNIDDb(String name, char delimiter)
  {
    this.name=name;
    this.delimiter=delimiter;
    try
    {
      FileReader fr= new FileReader(name);
      br= new BufferedReader(fr);
    }
    catch(IOException i)
    {
      System.out.println(i.getMessage());
    }
    catch(FileNotFoundException fnfe)
    {
      System.out.print(fnfe.getMessage());
    }
  }
</code>```

答: Since FileNotFoundException extends IOException, you can choose either FileNotFoundException or IOException based on your needs.</p>

Body:
I made sure to have all the exceptions I think are needed but it keeps giving me this error:

exception FileNotFoundException has already been caught
catch(FileNotFoundException fnfe)

public class SNIDDb
{
  private char delimiter;
  private String name;
  private BufferedReader br;

  public SNIDDb(String name, char delimiter)
  {
    this.name=name;
    this.delimiter=delimiter;
    try
    {
      FileReader fr= new FileReader(name);
      br= new BufferedReader(fr);
    }
    catch(IOException i)
    {
      System.out.println(i.getMessage());
    }
    catch(FileNotFoundException fnfe)
    {
      System.out.print(fnfe.getMessage());
    }
  }


问:
Sending an audio file WCF to WP7
HI,

I want to send an audio file from WCF service to Windows Phone 7 application.

I wanted to know what audio format is best handled in this case and also some links that could help me make the application play that audio file.

The audio file would be downloaded via GPRS/3G

Thanks

答: I actually just created a music player that did that very thing. I recommend using a stream and using MediaElement to play the stream. Or, you can do as I did and turn the sound file to a URL. Then, use the XNA MediaPlayer to play the URL. It is very capable and even buffers the song enough to play without waiting for the whole file to download.</p>

ContentLicense: CC BY-SA 2.5

Title: Sending an audio file WCF to WP7

ContentLicense: CC BY-SA 3.0


问:
Android sockets not reveving data from server
I am trying to send data from python server to android client but it is not accepting any data from the server. but it is showing that it is connected with the server. i cant recognize any error.

here is my client code in android java.

```<code>package com.example.socketinput;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {
    Thread Thread1 = null;
    String SERVER_IP="192.168.1.6";
    int SERVER_PORT=9857;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Thread1 = new Thread(new Thread1());
        Thread1.start();
    }
    private PrintWriter output;
    private BufferedReader input;
    class Thread1 implements Runnable {
        public void run() {
            Socket socket;
            try {
                socket = new Socket(SERVER_IP, SERVER_PORT);
                output = new PrintWriter(socket.getOutputStream());
                input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.i("Server", "Connected");
                    }
                });
                new Thread(new Thread2()).start();
            } catch (IOException e) {
                Log.i("Server", "Error in thread 1");
            }
        }
    }
    class Thread2 implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    final String message = input.readLine();
                    if (message != null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Log.i("Server", message);
                            }
                        });
                    } else {
                        Thread1 = new Thread(new Thread1());
                        Thread1.start();
                        return;
                    }
                } catch (IOException e) {
                    Log.i("Server", "Error in thread 2");
                    e.printStackTrace();
                }
            }
        }
    }
}
</code>```

here is my python server code .

```<code>#!/usr/bin/env python
# coding: utf-8

# In[1]:

import socket

# In[2]:
socket.gethostname()

s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 9857))
s.listen(5)

# In[ ]:

while True:
    clientsocket, address = s.accept()
    print(f"connection from {address} has been established!")
    clientsocket.send(bytes("welcome to the server!","utf-8"))

    while True:
        msg=input()
        clientsocket.send(bytes(msg,"utf-8"))
</code>```

android manifent file is-:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.socketinput">
    <uses-permission android:name = "android.permission.INTERNET" />
    <uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

Note-Android app and python code is connected on same server.

答:
In this code:

s.bind(('', 9857))

You should also pass the host.

s.bind(('192.168.1.6', 9857))

Body:
I am trying to send data from python server to android client but it is not accepting any data from the server. but it is showing that it is connected with the server. i cant recognize any error.

here is my client code in android java.

package com.example.socketinput;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {
    Thread Thread1 = null;
    String SERVER_IP="192.168.1.6";
    int SERVER_PORT=9857;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Thread1 = new Thread(new Thread1());
        Thread1.start();
    }
    private PrintWriter output;
    private BufferedReader input;
    class Thread1 implements Runnable {
        public void run() {
            Socket socket;
            try {
                socket = new Socket(SERVER_IP, SERVER_PORT);
                output = new PrintWriter(socket.getOutputStream());
                input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.i("Server", "Connected");
                    }
                });
                new Thread(new Thread2()).start();
            } catch (IOException e) {
                Log.i("Server", "Error in thread 1");
            }
        }
    }
    class Thread2 implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    final String message = input.readLine();
                    if (message != null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Log.i("Server", message);
                            }
                        });
                    } else {
                        Thread1 = new Thread(new Thread1());
                        Thread1.start();
                        return;
                    }
                } catch (IOException e) {
                    Log.i("Server", "Error in thread 2");
                    e.printStackTrace();
                }
            }
        }
    }
}

here is my python server code .

#!/usr/bin/env python
# coding: utf-8

# In[1]:

import socket

# In[2]:
socket.gethostname()

s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 9857))
s.listen(5)

# In[ ]:

while True:
    clientsocket, address = s.accept()
    print(f"connection from {address} has been established!")
    clientsocket.send(bytes("welcome to the server!","utf-8"))

    while True:
        msg=input()
        clientsocket.send(bytes(msg,"utf-8"))

android manifent file is-:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.socketinput">
    <uses-permission android:name = "android.permission.INTERNET" />
    <uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Note-Android app and python code is connected on same server.


答:
```<code><script src="jquery-3.5.1.min.js"></script>
<script src="popup.js"></script>
</code>```

You should declare jQuery script first then your script file

Title: Uncaught Reference Error : $ is not defined?

Body:
<script src="jquery-3.5.1.min.js"></script>
<script src="popup.js"></script>

You should declare jQuery script first then your script file


问:
How to call other python script in another python script?
I am trying to call other python script to another python script using import but it is giving some error. Can you please help me how to do this?

Example:

case.py is my one script which have one one function generate_case('rule_id'). This function is returning some value.

final.py is my another script in which I am trying to call above script and store return value into a variable.

I am trying to do in python :

```<code>import case as f_case

qry = ''
qry += f_case.generate_case('R162')
print(qry)
</code>```

Error:

```<code>ModuleNotFoundError: No module named 'case'
</code>```

Both the scripts are available in the same location.

答:
Try this   </p>

```<code>import os
import sys

scriptpath=''
sys.path.append(os.path.abspath(scriptpath))

# Do the import
import case as f_case
</code>```

Body:
I am trying to call other python script to another python script using import but it is giving some error. Can you please help me how to do this?

Example:

case.py is my one script which have one one function generate_case('rule_id'). This function is returning some value.

final.py is my another script in which I am trying to call above script and store return value into a variable.

I am trying to do in python :

import case as f_case

qry = ''
qry += f_case.generate_case('R162')
print(qry)

Error:

ModuleNotFoundError: No module named 'case'

Both the scripts are available in the same location.

Body:
Try this

import os
import sys

scriptpath=''
sys.path.append(os.path.abspath(scriptpath))

# Do the import
import case as f_case


问:
How to remove a particular word in an Excel cell?
How do you remove a particular word in a column of one cell that's in another cell in Excel.

Example: if

A1 = *1603 Ad street New York*,

B1 = *New York*

then in C1 I want = *1603 Ad street*

答:
Use the Substitute function:

```<code>=SUBSTITUTE(A1,B1,"")
</code>```

EDIT: Per brettdj's suggestion, added TRIM to get rid of leading or trailing spaces:

```<code>=TRIM(SUBSTITUTE(A1,B1,""))
</code>```

Body:
Use the Substitute function:

=SUBSTITUTE(A1,B1,"")

EDIT: Per brettdj's suggestion, added TRIM to get rid of leading or trailing spaces:

=TRIM(SUBSTITUTE(A1,B1,""))


问:
Vus.js Actions or Global Methods
I'm using nuxt.js and I just learning about store actions. Currently I have made a global mixin where I'm putting all my global methods and computed properties.

I have a bunch or Axios requests that get certain products that I have in my gobal methods in my global mixin.

Is this where I should now move my axios requests to my store actions?

Would I Dispach to my action that uses axios to fetch my data and then commit the returned promise to my store?

Also for best use, would keep your store actions inside the store... eg:products only stuff? Or could you use your action inside of products to get the products, commit it to the store and then send the products to Google Analyitics?

I'd just like a bit of clarification around Actions and the best use of them vs creating global methods or having methods inside of components.

答:
You are spot-on! Dispatch an action, do async axios requests in the action and commit mutations when the axios Promise resolves.

I did not get the second part of your question, if you clarify that I can edit this answer.

Title: Vus.js Actions or Global Methods


问:
Copy files to directory if they are not in another directory
I have four files file1, file2, file3, file4.

A directory /All contains all four files, a directory /A contains file1, file2. Now I want to copy the rest file3, file4 to another directory /B. How can I do this in the command line?

Thank you for the help.

答:
The following solution (in bash) will support spaces in filenames if you need, although not subdirectories.

```<code>diff <(\ls /A) <(\ls /All) | egrep '^> ' | cut -b 3- | xargs -d'\n' -I {}  cp "/All/{}" "/B/{}"
</code>```

Body:
The following solution (in bash) will support spaces in filenames if you need, although not subdirectories.

diff <(\ls /A) <(\ls /All) | egrep '^> ' | cut -b 3- | xargs -d'\n' -I {}  cp "/All/{}" "/B/{}"


问:
ModuleNotFoundError: No Module Named cant figure out why
going to retrieve a simple httpresponse from view at nested app, but some how having this error which cant figure out what the problem.

project urls.py

```<code>from django.contrib import admin
from django.urls import path, include
from django.http import HttpResponse, HttpRequest
# from .corex import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('corex.urls')),
]
</code>```

app[corex] urls.py

```<code>from django.urls import path, include
from . import views

urlpatterns = [
    path('', views.testcorex, name='testcorex'),
]
</code>```

app views.py

```<code>from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def testcorex(request):
    return HttpResponse('module passed')
</code>```

traceback error

```<code>File "/home/differentmonster/App/x_house_project/x_house_backend/x_house_cms/urls.py", line 11, in <module>
    path('', include('corex.urls')),
  File "/root/.cache/pypoetry/virtualenvs/x-house-cms-p6EwdKv_-py3.8/lib/python3.8/site-packages/django/urls/conf.py", line 34, in include
    urlconf_module = import_module(urlconf_module)
  File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'corex
</code>```

the installedApp should be no problem cause, if i import corex.views directly into root urls.py, the response works. but after i added the url.py into app, the module cant be found. and i am using poetry for venveniroment and django 3.0.6.

thanks guys

答:
Firsteval, you should check if corex is in your INSTALLED_APPS in you settings.py.

Next, be careful about your file name, you are calling corex.urls, but in your post, you name your file url.py (without the plural).

Body:
going to retrieve a simple httpresponse from view at nested app, but some how having this error which cant figure out what the problem.

project urls.py

from django.contrib import admin
from django.urls import path, include
from django.http import HttpResponse, HttpRequest
# from .corex import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('corex.urls')),
]

app[corex] urls.py

from django.urls import path, include
from . import views

urlpatterns = [
    path('', views.testcorex, name='testcorex'),
]

app views.py

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def testcorex(request):
    return HttpResponse('module passed')

traceback error

File "/home/differentmonster/App/x_house_project/x_house_backend/x_house_cms/urls.py", line 11, in <module>
    path('', include('corex.urls')),
  File "/root/.cache/pypoetry/virtualenvs/x-house-cms-p6EwdKv_-py3.8/lib/python3.8/site-packages/django/urls/conf.py", line 34, in include
    urlconf_module = import_module(urlconf_module)
  File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'corex

the installedApp should be no problem cause, if i import corex.views directly into root urls.py, the response works. but after i added the url.py into app, the module cant be found. and i am using poetry for venveniroment and django 3.0.6.

thanks guys


问:
Potentially long loop and declaring variables inside
I've recently written a dynamic program that calculates the similarity (modified edit distance) between two sequences of DNA strands (can be lengthy).

My code is like (not actual code since its an assignment):

```<code>while(!file.eof){
   string line;
   int sizeY, sizeX;

   //get first strand
   getline(db, line)

   //second strand
   getline(db, line)

   double ** ary = new double[sizeY];
   //loop to initialize array

   for(i to sizeY)
   {
      for(i to sizex)
      {
            pair<string,string> p,d;
            p.first = "A";
            p.second = "T";
            d.first = "G";
            d.second = "C";
            //do some comparisons
      }
   }
}
</code>```

The code above will take approximately 40 minutes to complete on a file with ~2400 lines.
If I move the pair p,d and assignments outside the nested for-loop and run the exact same file, it will complete in about ~1 minute.

I've read in other threads that the performance is pretty much the same. I've also compiled it with -O2.

Why is the code above so much slower?

答:
It is probably becouse the variable is an object. Since p and d are not a primitive type, unless the compiler inline it's constructor and destructor (which may happen if you use -O3 instead of -O2), it will construct and destruct the two std::pair (and as consequence four std::string) each iteration. If it was a primitive variable (like int), the compiler could optimize this even if you don't have inline optimization enabled.

EDIT:
Note that since std::string internally use heap allocations, not even inline would optimize those allocations (but you still save some overhead with the inline). For a std::pair of int, with -O3, the performance should be the same inside or outside the loop.

Body:
I've recently written a dynamic program that calculates the similarity (modified edit distance) between two sequences of DNA strands (can be lengthy).

My code is like (not actual code since its an assignment):

while(!file.eof){
   string line;
   int sizeY, sizeX;

   //get first strand
   getline(db, line)

   //second strand
   getline(db, line)

   double ** ary = new double[sizeY];
   //loop to initialize array

   for(i to sizeY)
   {
      for(i to sizex)
      {
            pair<string,string> p,d;
            p.first = "A";
            p.second = "T";
            d.first = "G";
            d.second = "C";
            //do some comparisons
      }
   }
}

The code above will take approximately 40 minutes to complete on a file with ~2400 lines.
If I move the pair p,d and assignments outside the nested for-loop and run the exact same file, it will complete in about ~1 minute.

I've read in other threads that the performance is pretty much the same. I've also compiled it with -O2.

Why is the code above so much slower?


问:
How to create random numbers a specific number of times?
How can i create a random number a specific numbers of time?

```<code>public class Feld  {
    public static void main(String[] args) {
        double k = (int)(Math.random()*1000001);
        int n = 1000000;
        int arr[] = new int[n];
        int i = 0;
        for(i = 0;i<n;i++){
            arr[i] = i;
        }
        boolean found = false;
        i=0;
        while (i < arr.length) {
            if (arr[i] == k) {
                found = true;
                break;
            }
            i++;
        }
        if (found) {
            i++;
            System.out.println(i);
        }
        else {
            System.out.println((arr.length + 1));
        }
    }
}
</code>```

My problem is, that if i put k into a loop to create it more than one time i'll get an error at:

```<code>if (arr[i] == k)
</code>```

!!I just found out that i made a mistake explaining my problem. The array should be filled with values from 0-1.000.000 and i am supposed to print out the position of a random generated number for a specific amount of times.

答:
If you want to have an array full of random numbers, I suggest using the following:

```<code>int n = 1000000;
int arr[] = new int[n];
for(int i = 0; i < n; i++){
    arr[i] = (int)(Math.random() * 1000001);
}
</code>```

That will work and you don't even need the variable k.

Edit:

If you want to print at what position you find a specific value (for example x = 543), you can use the following code:

```<code>int x = 543;
int n = 1000000;
int arr[] = new int[n];
for(int i = 0; i < n; i++){
    arr[i] = (int)(Math.random() * 1000001);
    if(arr[i] == x) {
        System.out.println(i);
        break;
    }
}
</code>```

Edit2

One possible solution to your new problem looks like this:

```<code>public class Feld  {
    public static void main(String[] args) {
        int n = 1000000;
        int arr[] = new int[n];
        int i = 0;
        for(i = 0; i < n; i++){
            arr[i] = i; //Filling array with values 0-1000000
        }
        int number = 20;    //Print out position of a random generated number a specific amount of times
        int randomNumber = (int)(Math.random()*1000001); //The random number

        for(int j = 0; j < number; j++) { //Find number for a specific amount of times
            for(int k = 0; k < arr.length; k++) { //Find number in array
                if(arr[k] == randomNumber) {
                    System.out.println(arr[k]); //Print
                    break; //Number found, don't have to search anymore
                }
            }
        }
    }
}
</code>```

Body:
How can i create a random number a specific numbers of time?

public class Feld  {
    public static void main(String[] args) {
        double k = (int)(Math.random()*1000001);
        int n = 1000000;
        int arr[] = new int[n];
        int i = 0;
        for(i = 0;i<n;i++){
            arr[i] = i;
        }
        boolean found = false;
        i=0;
        while (i < arr.length) {
            if (arr[i] == k) {
                found = true;
                break;
            }
            i++;
        }
        if (found) {
            i++;
            System.out.println(i);
        }
        else {
            System.out.println((arr.length + 1));
        }
    }
}

My problem is, that if i put k into a loop to create it more than one time i'll get an error at:

if (arr[i] == k)

!!I just found out that i made a mistake explaining my problem. The array should be filled with values from 0-1.000.000 and i am supposed to print out the position of a random generated number for a specific amount of times.

Body:
If you want to have an array full of random numbers, I suggest using the following:

int n = 1000000;
int arr[] = new int[n];
for(int i = 0; i < n; i++){
    arr[i] = (int)(Math.random() * 1000001);
}

That will work and you don't even need the variable k.

Edit:

If you want to print at what position you find a specific value (for example x = 543), you can use the following code:

int x = 543;
int n = 1000000;
int arr[] = new int[n];
for(int i = 0; i < n; i++){
    arr[i] = (int)(Math.random() * 1000001);
    if(arr[i] == x) {
        System.out.println(i);
        break;
    }
}

Edit2

One possible solution to your new problem looks like this:

public class Feld  {
    public static void main(String[] args) {
        int n = 1000000;
        int arr[] = new int[n];
        int i = 0;
        for(i = 0; i < n; i++){
            arr[i] = i; //Filling array with values 0-1000000
        }
        int number = 20;    //Print out position of a random generated number a specific amount of times
        int randomNumber = (int)(Math.random()*1000001); //The random number

        for(int j = 0; j < number; j++) { //Find number for a specific amount of times
            for(int k = 0; k < arr.length; k++) { //Find number in array
                if(arr[k] == randomNumber) {
                    System.out.println(arr[k]); //Print
                    break; //Number found, don't have to search anymore
                }
            }
        }
    }
}


问:
Triangular multiplication table in java
I'm trying to create a program in java that would create a 10 (row) by 15 (column) triangular multiplication table for an assignment. In the assignment we have to use constants IMAX= 10 and JMAX=15. I have attached a picture below of what the table should look like. I've gotten the jist of the table but am having trouble trying to stop the math and row 10 and also adding a border in the column numbers. Help would be appreciated.

Also to do this problem, we are permitted to use if/else statements, for loop and/or while loop

Multiplication table link

```<code>public class Question2 {
    public static void main(String[] args) {
            // TODO Auto-generated method stub

        final int IMAX= 15, JMAX=10;

        for (int i = 1; i <= JMAX; i++)
        {
            System.out.print( i + "  ");
        }

        System.out.println();
        System.out.print("--------------------------------------------------------" );
        System.out.println();

        for (int i = 1; i <= IMAX; i++){
            for (int j = 1; j <= i; j++)
            {
                System.out.print(i*j + " " );
            }
            System.out.println();
        }
    }
}
</code>```

答:
Here is multiplication table in java

```<code>import java.util.*;
public class table
{
    public static void main()
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number");
        int a = sc.nextInt();
        for (int i=1; i <=12; i++)
        System.out.println(a+ "    x    " +i + "   =   " +a*i);
    }
}
</code>```

You can change the variable names whatever you want

Title: Triangular multiplication table in java

Body:
I'm trying to create a program in java that would create a 10 (row) by 15 (column) triangular multiplication table for an assignment. In the assignment we have to use constants IMAX= 10 and JMAX=15. I have attached a picture below of what the table should look like. I've gotten the jist of the table but am having trouble trying to stop the math and row 10 and also adding a border in the column numbers. Help would be appreciated.

Also to do this problem, we are permitted to use if/else statements, for loop and/or while loop

Multiplication table link

public class Question2 {
    public static void main(String[] args) {
            // TODO Auto-generated method stub

        final int IMAX= 15, JMAX=10;

        for (int i = 1; i <= JMAX; i++)
        {
            System.out.print( i + "  ");
        }

        System.out.println();
        System.out.print("--------------------------------------------------------" );
        System.out.println();

        for (int i = 1; i <= IMAX; i++){
            for (int j = 1; j <= i; j++)
            {
                System.out.print(i*j + " " );
            }
            System.out.println();
        }
    }
}

Body:
Here is multiplication table in java

import java.util.*;
public class table
{
    public static void main()
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number");
        int a = sc.nextInt();
        for (int i=1; i <=12; i++)
        System.out.println(a+ "    x    " +i + "   =   " +a*i);
    }
}

You can change the variable names whatever you want


问:
Post request of a form returns empty ImmutableMultiDict to Flask
I'm sending a request from a webpage :

```<code><script>
  function sendGenre() {
    let form = document.getElementById("genreForm");
    form.value = document.getElementById("genre").value;
    console.log(form.value);
    form.submit();
  }
</script>
</code>```

```<code>  <form class="adminPlaylistMainForm" action="createlist" id="genreForm" method="POST">
    <div class="playlistGenre">
      <p>From what genre ?</p>
      <select class="adminPlaylistGenreButton" id="genre">
        <option value="all">All</option>
        <option value="jazz">Jazz</option>
        <option value="punk">Punk</option>
        <option value="rock">Rock</option>
      </select>
      <p><input type="button" onclick="sendGenre();" value="Send form" /></p>
    </div>
  </form>
</code>```

The back end is:

```<code>@app.route('/createlist', methods=['POST', 'GET'])
def create_list():
    if request.method == "POST":
        print("/createlist request.method == POST")
        print(request.form)
    return render_template("tools/createlist.html")
</code>```

The console.log(form.value) in the function prints the value, console.log(form) prints the full <form> and its content but in the terminal on the backend side I get:

```<code>/createlist request.method == POST
ImmutableMultiDict([])
</code>```

Do you have any idea what the problem is ?

答:
The problem is how you are submitting the form. You need to add a name attribute to your select tag. Like this: <select class="adminPlaylistGenreButton" id="genre" name="genre">

If you chose HTML form then you don't need JavaScript. Replace your submit button with <input type="submit" value="Send form">

Body:
I'm sending a request from a webpage :

  <form class="adminPlaylistMainForm" action="createlist" id="genreForm" method="POST">

From what genre ?

      <select class="adminPlaylistGenreButton" id="genre">
        <option value="all">All</option>
        <option value="jazz">Jazz</option>
        <option value="punk">Punk</option>
        <option value="rock">Rock</option>
      </select>

<input type="button" onclick="sendGenre();" value="Send form" />

  </form>

The back end is:

@app.route('/createlist', methods=['POST', 'GET'])
def create_list():
    if request.method == "POST":
        print("/createlist request.method == POST")
        print(request.form)
    return render_template("tools/createlist.html")

The console.log(form.value) in the function prints the value, console.log(form) prints the full <form> and its content but in the terminal on the backend side I get:

/createlist request.method == POST
ImmutableMultiDict([])

Do you have any idea what the problem is ?