问:
Error: the entity type requires a primary key
I would like to expand the question asked on this thread

Binding listbox to observablecollection

by giving it an ability to persistent the data. The structure is mostly the same except I installed Entity Framework Core, created a DbContext class to hold the records. I added a button to save the dataset to SQL Server. I did not encounter the compiling error but when I attempted to save the data in the database I got this run time exception:

Message=The entity type 'Fruit' requires a primary key to be defined.

The whole exception in its entirety is listed below

System.InvalidOperationException was unhandled

  HResult=-2146233079

  Message=The entity type 'Fruit' requires a primary key to be defined.

  Source=Microsoft.EntityFrameworkCore

  StackTrace:

  at Microsoft.EntityFrameworkCore.Internal.ModelValidator.ShowError(String message)

  at Microsoft.EntityFrameworkCore.Internal.ModelValidator.EnsureNonNullPrimaryKeys(IModel model)

  at Microsoft.EntityFrameworkCore.Internal.ModelValidator.Validate(IModel model)

  at Microsoft.EntityFrameworkCore.Internal.RelationalModelValidator.Validate(IModel model)

  at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)

  at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.<>c__DisplayClass14_0.b__0(Object k)

  at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory)

  at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)

  at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()

  at Microsoft.EntityFrameworkCore.Internal.LazyRef1.get_Value()

  at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()

  at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServiceCollectionExtensions.<>c.<AddEntityFramework>b__0_6(IServiceProvider p)

  at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactoryService(FactoryService factoryService, ServiceProvider provider)

  at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(IServiceCallSite callSite, TArgument argument)

  at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)

  at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(IServiceCallSite callSite, TArgument argument)

  at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider)

  at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(IServiceCallSite callSite, TArgument argument)

  at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)

  at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(IServiceCallSite callSite, TArgument argument)

  at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider)

  at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)

  at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)

  at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure1 accessor)

  at Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker.get_StateManager()

  at Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker.DetectChanges()

  at Microsoft.EntityFrameworkCore.DbContext.TryDetectChanges()

  at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)

  at Microsoft.EntityFrameworkCore.DbContext.SaveChanges()

  at Fruits.MainWindow.SaveFruitCommandBinding_Executed(Object sender, ExecutedRoutedEventArgs e) in D:\Frank\Test\Fruits\Fruits\MainWindow.xaml.cs:line 50

  at System.Windows.Input.CommandBinding.OnExecuted(Object sender, ExecutedRoutedEventArgs e)

  at System.Windows.Input.CommandManager.ExecuteCommandBinding(Object sender, ExecutedRoutedEventArgs e, CommandBinding commandBinding)

  at System.Windows.Input.CommandManager.FindCommandBinding(CommandBindingCollection commandBindings, Object sender, RoutedEventArgs e, ICommand command, Boolean execute)

  at System.Windows.Input.CommandManager.FindCommandBinding(Object sender, RoutedEventArgs e, ICommand command, Boolean execute)

  at System.Windows.Input.CommandManager.OnExecuted(Object sender, ExecutedRoutedEventArgs e)
             at System.Windows.UIElement.OnExecutedThunk(Object sender, ExecutedRoutedEventArgs e)
             at System.Windows.Input.ExecutedRoutedEventArgs.InvokeEventHandler(Delegate genericHandler, Object target)
             at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
             at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
             at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
             at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
             at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
             at System.Windows.Input.RoutedCommand.ExecuteImpl(Object parameter, IInputElement target, Boolean userInitiated)
             at System.Windows.Input.RoutedCommand.ExecuteCore(Object parameter, IInputElement target, Boolean userInitiated)
             at MS.Internal.Commands.CommandHelpers.CriticalExecuteCommandSource(ICommandSource commandSource, Boolean userInitiated)
             at System.Windows.Controls.Primitives.ButtonBase.OnClick()
             at System.Windows.Controls.Button.OnClick()
             at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
             at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
             at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
             at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
             at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
             at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
             at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
             at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
             at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
             at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
             at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
             at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
             at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
             at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
             at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
             at System.Windows.Input.InputManager.ProcessStagingArea()
             at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
             at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
             at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
             at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
             at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
             at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
             at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
             at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
             at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
             at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
             at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
             at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
             at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
             at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
             at System.Windows.Application.RunDispatcher(Object ignore)
             at System.Windows.Application.RunInternal(Window window)
             at System.Windows.Application.Run(Window window)
             at System.Windows.Application.Run()
             at Fruits.App.Main()
             at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
             at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
             at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
             at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
             at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
             at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
             at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
             at System.Threading.ThreadHelper.ThreadStart()
        InnerException:

This is the updated class Fruit:

```<code>namespace Fruits.ViewModels
{
    [Table("Fruits")]
    public  class Fruit : ViewModelBase
    {
        #region Constractor
        public Fruit()
        {
        }
        public Fruit(string name, String clrString)
        {
            FruitName = name;
            //  Parse colors like so: (Color)ColorConverter.ConvertFromString(clrString);
            FruitColor = clrString;
            _id = Guid.NewGuid();
        }
        public Fruit(string name, Color clr)
        {
            FruitName = name;
            FruitColor = clr.ToString();
            _id = Guid.NewGuid();
        }

        #endregion

        #region Properties
        private Guid _id;
        [Key]
        public Guid ID
        {
            get { return _id; }
        }

        #region FruitName
        private string _fruitname;
        public string FruitName
        {
            get
            {
                return _fruitname;
            }
            set
            {
                if (_fruitname != value)
                {
                    _fruitname = value;
                    OnPropertyChanged("FruitName");
                }
            }
        }
        #endregion

        #region FruitColor
        private String _fruitcolor;
        public String FruitColor
        {
            get
            {
                return _fruitcolor;
            }
            set
            {
                if (_fruitcolor != value)
                {
                    _fruitcolor = value;
                    OnPropertyChanged("FruitColor");
                }
            }
        }
        #endregion

        #region Selected Property
        private bool _isSelected = true;
        //  NOTE: I renamed this property
        public bool IsSelected
        {
            get
            {
                return _isSelected;
            }
            set
            {
                if (_isSelected != value)
                {
                    _isSelected = value;
                    OnPropertyChanged("IsSelected");
                }
            }
        }
        #endregion

        #endregion
    }
}
</code>```

The updated MainWindows xaml (to add a save button)

```<code><Window x:Class="Fruits.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Fruits"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <RoutedCommand x:Key="AddFruit" />
        <RoutedCommand x:Key='SaveFruit' />
    </Window.Resources>
    <Window.CommandBindings>
        <CommandBinding Command='{StaticResource AddFruit}'
                                        Executed='AddFruitCommandBinding_Executed'
                                        CanExecute='AddFruitCommandBinding_CanExecute' />
        <CommandBinding Command='{StaticResource SaveFruit}'
                                        Executed='SaveFruitCommandBinding_Executed'
                                        CanExecute='SaveFruitCommandBinding_CanExecute' />
    </Window.CommandBindings>
    <Grid>
        <StackPanel Orientation='Vertical'
                                Margin='10'>
            <CheckBox IsChecked="{Binding ShowSelectedFruitOnly}">Selected Fruit Only</CheckBox>
            <ListBox x:Name='MyList'
                             ItemsSource="{Binding FruitsView}"
                             ItemTemplate='{StaticResource FruitTemp}' />
            <StackPanel Orientation="Horizontal"
                                    Margin="0,10,0,0">
                <Label Width="100">New Name:</Label>
                <TextBox Width="200"
                                 Text="{Binding NewFruitName, Mode=TwoWay }"
                                 />
            </StackPanel>
            <StackPanel Orientation="Horizontal"
                                    Margin="0,10,0,0">
                <Label Width="100">New Color:</Label>
                <!--<TextBox Width="200"
                                 Text="{Binding NewFruitColor, UpdateSourceTrigger=PropertyChanged}" />-->
                <TextBox Width="200"
                                 Text="{Binding NewFruitColor, Mode=TwoWay }" />

                <ContentControl Style="{StaticResource ColorSwatch}"
                                                Margin="2"
                                                VerticalAlignment="Center"
                                                Content="{Binding NewFruitColor}" />
            </StackPanel>
            <StackPanel Orientation='Horizontal'>
            <Button x:Name='AddFruit'
                            Height='auto'
                            Width='auto'
                            Content='Add New Fruit 2'
                            Margin='0,10,0,0'
                            Command='{StaticResource AddFruit}' />
                <Button x:Name='SaveFruit'
                                Height='auto'
                                Width='auto'
                                Content='Save Fruit'
                                Margin='100,10,0,0'
                                Command='{StaticResource SaveFruit}' />
            </StackPanel>
        </StackPanel>
    </Grid>
</Window>
</code>```

and my code behind the mainwindows (added handler)

```<code>using Fruits.ViewModels;
using System;
using System.Windows;
using System.Windows.Input;

namespace Fruits
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new MainViewModel();

            ViewModel.AddNewFruit("Jackfruit", "Yellow");
            ViewModel.AddNewFruit("Watermelon", "ForestGreen");
            ViewModel.AddNewFruit("Apple", "Red");
            ViewModel.AddNewFruit("Banana", "Yellow");
            ViewModel.AddNewFruit("Orange", "DeepSkyBlue");

            //ViewModel.Fruits[0].IsSelected = false;
            //ViewModel.Fruits[1].IsSelected = false;

            ViewModel.FruitsView.Refresh();
        }

        public MainViewModel ViewModel { get { return DataContext as MainViewModel; } }

        private void AddFruitCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            ViewModel.AddNewFruit();
        }

        private void AddFruitCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute =
                    ViewModel != null
                    && !String.IsNullOrWhiteSpace(ViewModel.NewFruitName)
                    && !String.IsNullOrWhiteSpace(ViewModel.NewFruitColor)
                    ;
        }

        private void SaveFruitCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            using (var db=new FruitDbContext())
            {
                db.SaveChanges();
            }
        }

        private void SaveFruitCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }
    }
}
</code>```

My newly added dbContext:

```<code>namespace Fruits.ViewModels
{
    public class FruitDbContext:DbContext
    {
        public DbSet<Fruit> Fruits { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionBuilder)
        {
            optionBuilder.UseSqlServer(@"Server = xxx; Database=Test; Integrated Security = True");
        }
    }
}
</code>```

Other classes remain unchanged, but I listed them anyway:

ViewModelBase

```<code>    namespace Fruits.ViewModels
    {
        public  class ViewModelBase : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            public void OnPropertyChanged(string name)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(name));
                }
            }
        }
    }

ViewModel

using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Data;
using System.Windows.Media;

namespace Fruits.ViewModels
{

    #region MainViewModel Class
    public class MainViewModel : ViewModelBase
    {
        public  MainViewModel()
        {
            Fruits = new ObservableCollection<Fruit>();

        }
        public ICollectionView FruitsView { get; private set; }

        #region ShowSelectedFruitOnly Property
        private bool _showSelectedFruitOnly = true;
        public bool ShowSelectedFruitOnly
        {
            get { return _showSelectedFruitOnly; }
            set
            {
                if (value != _showSelectedFruitOnly)
                {
                    _showSelectedFruitOnly = value;
                    FruitsView.Refresh();
                    OnPropertyChanged("ShowSelectedFruitOnly");
                }
            }
        }
        #endregion ShowSelectedFruitOnly Property

        #region Add Methods
        public void AddNewFruit()
        {
            Fruits.Add(new Fruit(NewFruitName, NewFruitColor));

            NewFruitName = "";
            NewFruitColor = "";
        }
        public void AddNewFruit(string name, string color)
        {
            Fruits.Add(new Fruit(name, color));
        }
        public void AddNewFruit(string name, Color color)
        {
            Fruits.Add(new Fruit(name, color));
        }
        #endregion Add Methods

        #region NewFruitName Property
        private String _newFruitName = default(String);
        public String NewFruitName
        {
            get { return _newFruitName; }
            set
            {
                if (value != _newFruitName)
                {
                    _newFruitName = value;
                    OnPropertyChanged("NewFruitName");
                }
            }
        }
        #endregion NewFruitName Property

        #region NewFruitColor Property
        private String _newFruitColor = default(String);
        public String NewFruitColor
        {
            get { return _newFruitColor; }
            set
            {
                if (value != _newFruitColor)
                {
                    _newFruitColor = value;
                    OnPropertyChanged("NewFruitColor");
                }
            }
        }
        #endregion NewFruitColor Property

        #region Fruits Property
        private static ObservableCollection<Fruit> _fruits;
        public ObservableCollection<Fruit> Fruits
        {
            get { return _fruits; }
            private set
            {
                if (value != _fruits)
                {
                    _fruits = value;

                    FruitsView = CollectionViewSource.GetDefaultView(Fruits);

                    FruitsView.Filter = FruitFilterPredicate;
                    FruitsView.Refresh();

                    OnPropertyChanged("Fruits");
                }
            }
        }
        protected bool FruitFilterPredicate(Object o)
        {
            if (ShowSelectedFruitOnly)
            {
                return (o as Fruit).IsSelected;
            }

            return true;
        }
        #endregion Fruits Property
    }

    #endregion MainViewModel Class
}
</code>```

App.xaml

```<code><Application x:Class="Fruits.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:Fruits"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <Style x:Key="ColorSwatch"
                     TargetType="ContentControl">
            <Setter Property="Width"
                            Value="24" />
            <Setter Property="Height"
                            Value="24" />
            <Setter Property="IsTabStop"
                            Value="false" />
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <Rectangle HorizontalAlignment="Stretch"
                                             VerticalAlignment="Stretch"
                                             Stroke="Gray"
                                             StrokeThickness="1">
                            <Rectangle.Fill>
                                <SolidColorBrush Color="{Binding}" />
                            </Rectangle.Fill>
                        </Rectangle>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>

        <DataTemplate x:Key='FruitTemp'>
            <StackPanel Orientation='Horizontal'
                                    Margin='5'>
                <TextBlock x:Name='tbName'
                                     Text='{Binding FruitName}'
                                     Margin='10,0,0,0'
                                     Width='100' />
                <TextBlock x:Name='tbColor'
                                     Text='{Binding FruitColor}'
                                     Margin='10,0,0,0'
                                     Width='100' />
                <ContentControl Width="16"
                                                Height="16"
                                                Style="{StaticResource ColorSwatch}"
                                                Content="{Binding FruitColor}" />
                <!-- The problem here was you were trying to bind Checked, an event,
                instead if IsChecked, a bool? property.
                -->
                <CheckBox x:Name='cbSelected'
                                    Content='Selected'
                                    Margin='10,0,0,0'
                                    IsChecked='{Binding IsSelected}' />
            </StackPanel>
        </DataTemplate>
    </Application.Resources>
</Application>
</code>```

The structure of my project

My table in SQL Server:

```<code>CREATE TABLE [dbo].[Fruits]
(
    [ID] [uniqueidentifier] NOT NULL,
    [FruitName] [nvarchar](50) NULL,
    [FruitColor] [nvarchar](50) NULL,
    [IsSelected] [nvarchar](1) NULL,

     CONSTRAINT [PK_Fruit]
        PRIMARY KEY CLUSTERED ([ID] ASC)
                    WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
                          IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
                          ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
</code>```

Please advise why the message said there was no primary key while it does exist

答:
Make sure you have the following condition:

Use [key] if your primary key name is not Id or ID.

Use the public keyword.

Primary key should have getter and setter.

Example:

```<code>public class MyEntity {
   [key]
   public Guid Id {get; set;}
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to expand the question asked on this thread

Binding listbox to observablecollection

by giving it an ability to persistent the data. The structure is mostly the same except I installed Entity Framework Core, created a DbContext class to hold the records. I added a button to save the dataset to SQL Server. I did not encounter the compiling error but when I attempted to save the data in the database I got this run time exception:

Message=The entity type 'Fruit' requires a primary key to be defined.

The whole exception in its entirety is listed below

System.InvalidOperationException was unhandled

  HResult=-2146233079

  Message=The entity type 'Fruit' requires a primary key to be defined.

  Source=Microsoft.EntityFrameworkCore

  StackTrace:

  at Microsoft.EntityFrameworkCore.Internal.ModelValidator.ShowError(String message)

  at Microsoft.EntityFrameworkCore.Internal.ModelValidator.EnsureNonNullPrimaryKeys(IModel model)

  at Microsoft.EntityFrameworkCore.Internal.ModelValidator.Validate(IModel model)

  at Microsoft.EntityFrameworkCore.Internal.RelationalModelValidator.Validate(IModel model)

  at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)

  at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.<>c__DisplayClass14_0.b__0(Object k)

  at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory)

  at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)

  at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()

  at Microsoft.EntityFrameworkCore.Internal.LazyRef1.get_Value()

  at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()

  at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServiceCollectionExtensions.<>c.<AddEntityFramework>b__0_6(IServiceProvider p)

  at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactoryService(FactoryService factoryService, ServiceProvider provider)

  at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(IServiceCallSite callSite, TArgument argument)

  at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)

  at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(IServiceCallSite callSite, TArgument argument)

  at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider)

  at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(IServiceCallSite callSite, TArgument argument)

  at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)

  at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(IServiceCallSite callSite, TArgument argument)

  at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider)

  at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)

  at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)

  at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure1 accessor)

  at Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker.get_StateManager()

  at Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker.DetectChanges()

  at Microsoft.EntityFrameworkCore.DbContext.TryDetectChanges()

  at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)

  at Microsoft.EntityFrameworkCore.DbContext.SaveChanges()

  at Fruits.MainWindow.SaveFruitCommandBinding_Executed(Object sender, ExecutedRoutedEventArgs e) in D:\Frank\Test\Fruits\Fruits\MainWindow.xaml.cs:line 50

  at System.Windows.Input.CommandBinding.OnExecuted(Object sender, ExecutedRoutedEventArgs e)

  at System.Windows.Input.CommandManager.ExecuteCommandBinding(Object sender, ExecutedRoutedEventArgs e, CommandBinding commandBinding)

  at System.Windows.Input.CommandManager.FindCommandBinding(CommandBindingCollection commandBindings, Object sender, RoutedEventArgs e, ICommand command, Boolean execute)

  at System.Windows.Input.CommandManager.FindCommandBinding(Object sender, RoutedEventArgs e, ICommand command, Boolean execute)

  at System.Windows.Input.CommandManager.OnExecuted(Object sender, ExecutedRoutedEventArgs e)
             at System.Windows.UIElement.OnExecutedThunk(Object sender, ExecutedRoutedEventArgs e)
             at System.Windows.Input.ExecutedRoutedEventArgs.InvokeEventHandler(Delegate genericHandler, Object target)
             at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
             at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
             at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
             at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
             at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
             at System.Windows.Input.RoutedCommand.ExecuteImpl(Object parameter, IInputElement target, Boolean userInitiated)
             at System.Windows.Input.RoutedCommand.ExecuteCore(Object parameter, IInputElement target, Boolean userInitiated)
             at MS.Internal.Commands.CommandHelpers.CriticalExecuteCommandSource(ICommandSource commandSource, Boolean userInitiated)
             at System.Windows.Controls.Primitives.ButtonBase.OnClick()
             at System.Windows.Controls.Button.OnClick()
             at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
             at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
             at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
             at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
             at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
             at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
             at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
             at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
             at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
             at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
             at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
             at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
             at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
             at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
             at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
             at System.Windows.Input.InputManager.ProcessStagingArea()
             at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
             at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
             at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
             at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
             at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
             at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
             at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
             at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
             at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
             at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
             at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
             at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
             at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
             at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
             at System.Windows.Application.RunDispatcher(Object ignore)
             at System.Windows.Application.RunInternal(Window window)
             at System.Windows.Application.Run(Window window)
             at System.Windows.Application.Run()
             at Fruits.App.Main()
             at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
             at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
             at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
             at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
             at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
             at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
             at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
             at System.Threading.ThreadHelper.ThreadStart()
        InnerException:

This is the updated class Fruit:

namespace Fruits.ViewModels
{
    [Table("Fruits")]
    public  class Fruit : ViewModelBase
    {
        #region Constractor
        public Fruit()
        {
        }
        public Fruit(string name, String clrString)
        {
            FruitName = name;
            //  Parse colors like so: (Color)ColorConverter.ConvertFromString(clrString);
            FruitColor = clrString;
            _id = Guid.NewGuid();
        }
        public Fruit(string name, Color clr)
        {
            FruitName = name;
            FruitColor = clr.ToString();
            _id = Guid.NewGuid();
        }

        #endregion

        #region Properties
        private Guid _id;
        [Key]
        public Guid ID
        {
            get { return _id; }
        }

        #region FruitName
        private string _fruitname;
        public string FruitName
        {
            get
            {
                return _fruitname;
            }
            set
            {
                if (_fruitname != value)
                {
                    _fruitname = value;
                    OnPropertyChanged("FruitName");
                }
            }
        }
        #endregion

        #region FruitColor
        private String _fruitcolor;
        public String FruitColor
        {
            get
            {
                return _fruitcolor;
            }
            set
            {
                if (_fruitcolor != value)
                {
                    _fruitcolor = value;
                    OnPropertyChanged("FruitColor");
                }
            }
        }
        #endregion

        #region Selected Property
        private bool _isSelected = true;
        //  NOTE: I renamed this property
        public bool IsSelected
        {
            get
            {
                return _isSelected;
            }
            set
            {
                if (_isSelected != value)
                {
                    _isSelected = value;
                    OnPropertyChanged("IsSelected");
                }
            }
        }
        #endregion

        #endregion
    }
}

The updated MainWindows xaml (to add a save button)

<Window x:Class="Fruits.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Fruits"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <RoutedCommand x:Key="AddFruit" />
        <RoutedCommand x:Key='SaveFruit' />
    </Window.Resources>
    <Window.CommandBindings>
        <CommandBinding Command='{StaticResource AddFruit}'
                                        Executed='AddFruitCommandBinding_Executed'
                                        CanExecute='AddFruitCommandBinding_CanExecute' />
        <CommandBinding Command='{StaticResource SaveFruit}'
                                        Executed='SaveFruitCommandBinding_Executed'
                                        CanExecute='SaveFruitCommandBinding_CanExecute' />
    </Window.CommandBindings>
    <Grid>
        <StackPanel Orientation='Vertical'
                                Margin='10'>
            <CheckBox IsChecked="{Binding ShowSelectedFruitOnly}">Selected Fruit Only</CheckBox>
            <ListBox x:Name='MyList'
                             ItemsSource="{Binding FruitsView}"
                             ItemTemplate='{StaticResource FruitTemp}' />
            <StackPanel Orientation="Horizontal"
                                    Margin="0,10,0,0">
                New Name:
                <TextBox Width="200"
                                 Text="{Binding NewFruitName, Mode=TwoWay }"
                                 />
            </StackPanel>
            <StackPanel Orientation="Horizontal"
                                    Margin="0,10,0,0">
                New Color:

                <TextBox Width="200"
                                 Text="{Binding NewFruitColor, Mode=TwoWay }" />

                <ContentControl Style="{StaticResource ColorSwatch}"
                                                Margin="2"
                                                VerticalAlignment="Center"
                                                Content="{Binding NewFruitColor}" />
            </StackPanel>
            <StackPanel Orientation='Horizontal'>
            <Button x:Name='AddFruit'
                            Height='auto'
                            Width='auto'
                            Content='Add New Fruit 2'
                            Margin='0,10,0,0'
                            Command='{StaticResource AddFruit}' />
                <Button x:Name='SaveFruit'
                                Height='auto'
                                Width='auto'
                                Content='Save Fruit'
                                Margin='100,10,0,0'
                                Command='{StaticResource SaveFruit}' />
            </StackPanel>
        </StackPanel>
    </Grid>
</Window>

and my code behind the mainwindows (added handler)

using Fruits.ViewModels;
using System;
using System.Windows;
using System.Windows.Input;

namespace Fruits
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new MainViewModel();

            ViewModel.AddNewFruit("Jackfruit", "Yellow");
            ViewModel.AddNewFruit("Watermelon", "ForestGreen");
            ViewModel.AddNewFruit("Apple", "Red");
            ViewModel.AddNewFruit("Banana", "Yellow");
            ViewModel.AddNewFruit("Orange", "DeepSkyBlue");

            //ViewModel.Fruits[0].IsSelected = false;
            //ViewModel.Fruits[1].IsSelected = false;

            ViewModel.FruitsView.Refresh();
        }

        public MainViewModel ViewModel { get { return DataContext as MainViewModel; } }

        private void AddFruitCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            ViewModel.AddNewFruit();
        }

        private void AddFruitCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute =
                    ViewModel != null
                    && !String.IsNullOrWhiteSpace(ViewModel.NewFruitName)
                    && !String.IsNullOrWhiteSpace(ViewModel.NewFruitColor)
                    ;
        }

        private void SaveFruitCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            using (var db=new FruitDbContext())
            {
                db.SaveChanges();
            }
        }

        private void SaveFruitCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }
    }
}

My newly added dbContext:

namespace Fruits.ViewModels
{
    public class FruitDbContext:DbContext
    {
        public DbSet<Fruit> Fruits { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionBuilder)
        {
            optionBuilder.UseSqlServer(@"Server = xxx; Database=Test; Integrated Security = True");
        }
    }
}

Other classes remain unchanged, but I listed them anyway:

ViewModelBase

    namespace Fruits.ViewModels
    {
        public  class ViewModelBase : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            public void OnPropertyChanged(string name)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(name));
                }
            }
        }
    }

ViewModel

using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Data;
using System.Windows.Media;

namespace Fruits.ViewModels
{

    #region MainViewModel Class
    public class MainViewModel : ViewModelBase
    {
        public  MainViewModel()
        {
            Fruits = new ObservableCollection<Fruit>();

        }
        public ICollectionView FruitsView { get; private set; }

        #region ShowSelectedFruitOnly Property
        private bool _showSelectedFruitOnly = true;
        public bool ShowSelectedFruitOnly
        {
            get { return _showSelectedFruitOnly; }
            set
            {
                if (value != _showSelectedFruitOnly)
                {
                    _showSelectedFruitOnly = value;
                    FruitsView.Refresh();
                    OnPropertyChanged("ShowSelectedFruitOnly");
                }
            }
        }
        #endregion ShowSelectedFruitOnly Property

        #region Add Methods
        public void AddNewFruit()
        {
            Fruits.Add(new Fruit(NewFruitName, NewFruitColor));

            NewFruitName = "";
            NewFruitColor = "";
        }
        public void AddNewFruit(string name, string color)
        {
            Fruits.Add(new Fruit(name, color));
        }
        public void AddNewFruit(string name, Color color)
        {
            Fruits.Add(new Fruit(name, color));
        }
        #endregion Add Methods

        #region NewFruitName Property
        private String _newFruitName = default(String);
        public String NewFruitName
        {
            get { return _newFruitName; }
            set
            {
                if (value != _newFruitName)
                {
                    _newFruitName = value;
                    OnPropertyChanged("NewFruitName");
                }
            }
        }
        #endregion NewFruitName Property

        #region NewFruitColor Property
        private String _newFruitColor = default(String);
        public String NewFruitColor
        {
            get { return _newFruitColor; }
            set
            {
                if (value != _newFruitColor)
                {
                    _newFruitColor = value;
                    OnPropertyChanged("NewFruitColor");
                }
            }
        }
        #endregion NewFruitColor Property

        #region Fruits Property
        private static ObservableCollection<Fruit> _fruits;
        public ObservableCollection<Fruit> Fruits
        {
            get { return _fruits; }
            private set
            {
                if (value != _fruits)
                {
                    _fruits = value;

                    FruitsView = CollectionViewSource.GetDefaultView(Fruits);

                    FruitsView.Filter = FruitFilterPredicate;
                    FruitsView.Refresh();

                    OnPropertyChanged("Fruits");
                }
            }
        }
        protected bool FruitFilterPredicate(Object o)
        {
            if (ShowSelectedFruitOnly)
            {
                return (o as Fruit).IsSelected;
            }

            return true;
        }
        #endregion Fruits Property
    }

    #endregion MainViewModel Class
}

App.xaml

<Application x:Class="Fruits.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:Fruits"
             StartupUri="MainWindow.xaml">
    <Application.Resources>

        <DataTemplate x:Key='FruitTemp'>
            <StackPanel Orientation='Horizontal'
                                    Margin='5'>
                <TextBlock x:Name='tbName'
                                     Text='{Binding FruitName}'
                                     Margin='10,0,0,0'
                                     Width='100' />
                <TextBlock x:Name='tbColor'
                                     Text='{Binding FruitColor}'
                                     Margin='10,0,0,0'
                                     Width='100' />
                <ContentControl Width="16"
                                                Height="16"
                                                Style="{StaticResource ColorSwatch}"
                                                Content="{Binding FruitColor}" />

                <CheckBox x:Name='cbSelected'
                                    Content='Selected'
                                    Margin='10,0,0,0'
                                    IsChecked='{Binding IsSelected}' />
            </StackPanel>
        </DataTemplate>
    </Application.Resources>
</Application>

The structure of my project

My table in SQL Server:

CREATE TABLE [dbo].[Fruits]
(
    [ID] [uniqueidentifier] NOT NULL,
    [FruitName] [nvarchar](50) NULL,
    [FruitColor] [nvarchar](50) NULL,
    [IsSelected] [nvarchar](1) NULL,

     CONSTRAINT [PK_Fruit]
        PRIMARY KEY CLUSTERED ([ID] ASC)
                    WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
                          IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
                          ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

Please advise why the message said there was no primary key while it does exist

Body:
Make sure you have the following condition:

Use [key] if your primary key name is not Id or ID.

Use the public keyword.

Primary key should have getter and setter.

Example:

public class MyEntity {
   [key]
   public Guid Id {get; set;}
}


来源: stackexchange

问:
Adding a number to certain elements of an array
I have an array in numpy:

```<code>[1  2  3]
[4  5  6]
[7  8  9]
[10 11 12]
</code>```

I would like to add 100 to all values that are greater than or equal to 3 and less than or equal to 8. How can I do this?

ContentLicense: CC BY-SA 4.0

Body:
I have an array in numpy:

[1  2  3]
[4  5  6]
[7  8  9]
[10 11 12]

I would like to add 100 to all values that are greater than or equal to 3 and less than or equal to 8. How can I do this?

Body:
Try this :

>>> a[np.where((8>=a) & (a>=3))]+=100
>>> a
array([[  1,   2, 103],
       [104, 105, 106],
       [107, 108,   9],
       [ 10,  11,  12]])

where a is :

array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12]])


问:
How to configure AWS SAM on Eclipse and Window 10
I am using STS 4 (https://spring.io/tools) and added Eclipse AWS toolkit (https://marketplace.eclipse.org/content/aws-toolkit-eclipse) .

After restart STS we can see everything is good.

Now i have installed AWS SAM CLI local

And configured path where we have sam.exe

I have Java 8 and Python 2.7 and  3.6 and docker installed in my local.

Now created AWS Java serverless project  maven install  and try to run sam local

https://aws.amazon.com/blogs/developer/aws-toolkit-for-eclipse-locally-debug-your-lambda-functions-and-api-gateway/

Update :

When i am try to run SAM-CLI its working and returning response.

Template.yaml

```<code>AWSTemplateFormatVersion : '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: AWS Lambda Sample Project

Resources:

  Products:
    Type: AWS::Serverless::Function
    Properties:
      Handler: com.example.handler.LambdaHandler
      CodeUri: ./target/lambda-project-1.0-SNAPSHOT.jar
      Runtime: java8
      Timeout: 300
      Environment:
        Variables:
          ENVIRONMENT: "test"
      Events:
        ListProducts:
          Type: Api
          Properties:
            Path: /lambda
            Method: post
</code>```

And run configuration

```<code>**Maven build :**

[INFO] Scanning for projects...
[INFO]
[INFO] ---------------------< com.example:lambda-project >---------------------
[INFO] Building lambda-project 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ lambda-project ---
[INFO] Deleting C:\Users\vaqua\Documents\code\AWS-Lambda-Example-master\AWS-Lambda-Example-master\target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ lambda-project ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 2 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.6.1:compile (default-compile) @ lambda-project ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 6 source files to C:\Users\vaqua\Documents\code\AWS-Lambda-Example-master\AWS-Lambda-Example-master\target\classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ lambda-project ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 2 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.6.1:testCompile (default-testCompile) @ lambda-project ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 1 source file to C:\Users\vaqua\Documents\code\AWS-Lambda-Example-master\AWS-Lambda-Example-master\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ lambda-project ---
[INFO] Surefire report directory: C:\Users\vaqua\Documents\code\AWS-Lambda-Example-master\AWS-Lambda-Example-master\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.example.handler.LambdaHandlerTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.291 sec

Results :

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ lambda-project ---
[INFO] Building jar: C:\Users\vaqua\Documents\code\AWS-Lambda-Example-master\AWS-Lambda-Example-master\target\lambda-project-1.0-SNAPSHOT.jar
[INFO]
[INFO] --- maven-shade-plugin:3.1.0:shade (default) @ lambda-project ---
[INFO] Including com.amazonaws:aws-lambda-java-events:jar:2.0.2 in the shaded jar.
[INFO] Including joda-time:joda-time:jar:2.6 in the shaded jar.
[INFO] Including com.amazonaws:aws-lambda-java-core:jar:1.2.0 in the shaded jar.
[INFO] Including com.typesafe:config:jar:1.3.1 in the shaded jar.
[INFO] Including org.apache.logging.log4j:log4j-api:jar:2.5 in the shaded jar.
[INFO] Including org.apache.logging.log4j:log4j-core:jar:2.5 in the shaded jar.
[INFO] Including com.google.code.gson:gson:jar:2.8.2 in the shaded jar.
[INFO] Replacing original artifact with shaded artifact.
[INFO] Replacing C:\Users\vaqua\Documents\code\AWS-Lambda-Example-master\AWS-Lambda-Example-master\target\lambda-project-1.0-SNAPSHOT.jar with C:\Users\vaqua\Documents\code\AWS-Lambda-Example-master\AWS-Lambda-Example-master\target\lambda-project-1.0-SNAPSHOT-shaded.jar
[INFO] Dependency-reduced POM written at: C:\Users\vaqua\Documents\code\AWS-Lambda-Example-master\AWS-Lambda-Example-master\dependency-reduced-pom.xml
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.510 s
[INFO] Finished at: 2018-12-25T21:27:10-06:00
[INFO] ------------------------------------------------------------------------
</code>```

Error logs:

Failed to launch SAM Local.
  com.amazonaws.eclipse.core.exceptions.AwsActionException

Logs:

```<code>eclipse.buildId=4.0.2.201811300843-RELEASE
java.version=1.8.0_191
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en_US
Framework arguments:  -product org.springframework.boot.ide.branding.sts4
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.springframework.boot.ide.branding.sts4

com.amazonaws.eclipse.lambda
Error
Tue Dec 25 21:21:52 CST 2018
Failed to launch SAM Local.

com.amazonaws.eclipse.core.exceptions.AwsActionException
    at com.amazonaws.eclipse.lambda.launching.SamLocalDelegate.launch(SamLocalDelegate.java:159)
    at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:862)
    at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:720)
    at org.eclipse.debug.internal.ui.DebugUIPlugin.buildAndLaunch(DebugUIPlugin.java:1029)
    at org.eclipse.debug.internal.ui.DebugUIPlugin$2.run(DebugUIPlugin.java:1243)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63)
Caused by: java.lang.NullPointerException
    at com.amazonaws.eclipse.lambda.launching.SamLocalDelegate.launch(SamLocalDelegate.java:116)
    ... 5 more

eclipse.buildId=4.0.2.201811300843-RELEASE
java.version=1.8.0_191
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en_US
Framework arguments:  -product org.springframework.boot.ide.branding.sts4
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.springframework.boot.ide.branding.sts4

org.eclipse.m2e.logback.appender
Warning
Tue Dec 25 21:21:47 CST 2018
Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
</code>```

I am wonder if anyone solved that issue ?

答:
Had the same issue.

First you should open the command line and run
   where sam
If you find that the path contains any spaces, for example, if it has 'Program Files' in its path then uninstall samcli and reinstall it. Make sure that its path does not contain any spaces, for example: C:\Amazon\SAMCLI. And when you're done installing samcli rerun the previous code in cmd and copy the path and paste in eclipse.

Secondly, you should follow Dimman's advice by creating a config file. You can do so by using awscli by running
 aws configuration

This will create the file automatically. Save and restart and everything should be fine.

Good luck.

Body:
I am using STS 4 (https://spring.io/tools) and added Eclipse AWS toolkit (https://marketplace.eclipse.org/content/aws-toolkit-eclipse) .

After restart STS we can see everything is good.

Now i have installed AWS SAM CLI local

And configured path where we have sam.exe

I have Java 8 and Python 2.7 and  3.6 and docker installed in my local.

Now created AWS Java serverless project  maven install  and try to run sam local

https://aws.amazon.com/blogs/developer/aws-toolkit-for-eclipse-locally-debug-your-lambda-functions-and-api-gateway/

Update :

When i am try to run SAM-CLI its working and returning response.

Template.yaml

AWSTemplateFormatVersion : '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: AWS Lambda Sample Project

Resources:

  Products:
    Type: AWS::Serverless::Function
    Properties:
      Handler: com.example.handler.LambdaHandler
      CodeUri: ./target/lambda-project-1.0-SNAPSHOT.jar
      Runtime: java8
      Timeout: 300
      Environment:
        Variables:
          ENVIRONMENT: "test"
      Events:
        ListProducts:
          Type: Api
          Properties:
            Path: /lambda
            Method: post

And run configuration

**Maven build :**

[INFO] Scanning for projects...
[INFO]
[INFO] ---------------------< com.example:lambda-project >---------------------
[INFO] Building lambda-project 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ lambda-project ---
[INFO] Deleting C:\Users\vaqua\Documents\code\AWS-Lambda-Example-master\AWS-Lambda-Example-master\target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ lambda-project ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 2 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.6.1:compile (default-compile) @ lambda-project ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 6 source files to C:\Users\vaqua\Documents\code\AWS-Lambda-Example-master\AWS-Lambda-Example-master\target\classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ lambda-project ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 2 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.6.1:testCompile (default-testCompile) @ lambda-project ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 1 source file to C:\Users\vaqua\Documents\code\AWS-Lambda-Example-master\AWS-Lambda-Example-master\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ lambda-project ---
[INFO] Surefire report directory: C:\Users\vaqua\Documents\code\AWS-Lambda-Example-master\AWS-Lambda-Example-master\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.example.handler.LambdaHandlerTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.291 sec

Results :

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ lambda-project ---
[INFO] Building jar: C:\Users\vaqua\Documents\code\AWS-Lambda-Example-master\AWS-Lambda-Example-master\target\lambda-project-1.0-SNAPSHOT.jar
[INFO]
[INFO] --- maven-shade-plugin:3.1.0:shade (default) @ lambda-project ---
[INFO] Including com.amazonaws:aws-lambda-java-events:jar:2.0.2 in the shaded jar.
[INFO] Including joda-time:joda-time:jar:2.6 in the shaded jar.
[INFO] Including com.amazonaws:aws-lambda-java-core:jar:1.2.0 in the shaded jar.
[INFO] Including com.typesafe:config:jar:1.3.1 in the shaded jar.
[INFO] Including org.apache.logging.log4j:log4j-api:jar:2.5 in the shaded jar.
[INFO] Including org.apache.logging.log4j:log4j-core:jar:2.5 in the shaded jar.
[INFO] Including com.google.code.gson:gson:jar:2.8.2 in the shaded jar.
[INFO] Replacing original artifact with shaded artifact.
[INFO] Replacing C:\Users\vaqua\Documents\code\AWS-Lambda-Example-master\AWS-Lambda-Example-master\target\lambda-project-1.0-SNAPSHOT.jar with C:\Users\vaqua\Documents\code\AWS-Lambda-Example-master\AWS-Lambda-Example-master\target\lambda-project-1.0-SNAPSHOT-shaded.jar
[INFO] Dependency-reduced POM written at: C:\Users\vaqua\Documents\code\AWS-Lambda-Example-master\AWS-Lambda-Example-master\dependency-reduced-pom.xml
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.510 s
[INFO] Finished at: 2018-12-25T21:27:10-06:00
[INFO] ------------------------------------------------------------------------

Error logs:

Failed to launch SAM Local.
  com.amazonaws.eclipse.core.exceptions.AwsActionException

Logs:

eclipse.buildId=4.0.2.201811300843-RELEASE
java.version=1.8.0_191
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en_US
Framework arguments:  -product org.springframework.boot.ide.branding.sts4
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.springframework.boot.ide.branding.sts4

com.amazonaws.eclipse.lambda
Error
Tue Dec 25 21:21:52 CST 2018
Failed to launch SAM Local.

com.amazonaws.eclipse.core.exceptions.AwsActionException
    at com.amazonaws.eclipse.lambda.launching.SamLocalDelegate.launch(SamLocalDelegate.java:159)
    at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:862)
    at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:720)
    at org.eclipse.debug.internal.ui.DebugUIPlugin.buildAndLaunch(DebugUIPlugin.java:1029)
    at org.eclipse.debug.internal.ui.DebugUIPlugin$2.run(DebugUIPlugin.java:1243)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63)
Caused by: java.lang.NullPointerException
    at com.amazonaws.eclipse.lambda.launching.SamLocalDelegate.launch(SamLocalDelegate.java:116)
    ... 5 more

eclipse.buildId=4.0.2.201811300843-RELEASE
java.version=1.8.0_191
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en_US
Framework arguments:  -product org.springframework.boot.ide.branding.sts4
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.springframework.boot.ide.branding.sts4

org.eclipse.m2e.logback.appender
Warning
Tue Dec 25 21:21:47 CST 2018
Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!

I am wonder if anyone solved that issue ?


问:
Selenium looking at a class and determine how many elements are in the class, finally executes an action on all elements found
I need to interact with elements under a class but the number of elements in that class is changing every time I run the script.

To give you context the website is a calendar, where I need to pick a day that I'll use as a template for my work. Every time I run the script (Monthly) the webpage with the calendar is updated to show the current month, thus Selenium picks the same day it did in the previous month. But every month the day Selenium picks has different contents and number of elements change every month. Currently, for example, the script is written to interact with 5 elements, but for next month it won't work because the day picked will have a different number of elements. So every month I have to manually change the script to interact with the correct number of elements.

Here's an example of the element structure of the website:

```<code><ul class="list-unstyled tags-list grid_9">
     <li><!-- react-text: 185 -->Text<!-- /react-text --><i data-id="0" class="icon-cancel pointer icon12
      ml5px error"></i></li>
     <li><!-- react-text: 188 -->Text<!-- /react-text --><i data-id="1" class="icon-cancel pointer icon12
      ml5px error"></i></li>
     <li><!-- react-text: 191 -->Text<!-- /react-text --><i data-id="2" class="icon-cancel pointer icon12
      ml5px error"></i></li>
</ul>
</code>```

So the number of elements that I need to interact within the class 'list-unstyled tags-list grid_9' is always changing. The elements with the id's "0", "1" and "2". Sometimes there might be 4 elements with ID's "0", "1", "2", "3" and sometimes there's 2 elements etc.

I've been trying to figure out how to write a script where Selenium looks inside that class ''list-unstyled tags-list grid_9', see's how many elements are in there and executes a -

```<code>driver.find_element_by_(xpath,class,id whatever).click()
</code>```

on all of the elements found in there.

UPDATE:
So I tried this code:

```<code>tab = driver.find_element_by_css_selector('#postForm > div:nth-child(3) > ul.list-unstyled.tags-list.grid_9')
    hashs = tab.find_elements_by_tag_name('li')
    for element in hashs:
        element.find_element_by_tag_name('i').click()
</code>```

And it gave me this error:

```<code>stale element reference: element is not attached to the page document
</code>```

答:
You can use the fact that an element also has all the find_elem... methods that the webdriver has, but with the context of that element  only, that works for you in the following way:

```<code>from selenium import webdriver

driver = webdriver.Firefox()
calendar_day_element = driver.find_element_by_css_selector('ul.list-unstyled.tags-list.grid_9')
day_events = calendar_day_element.find_elements_by_tag_name('li')
</code>```

Now day_events is a list of all li elements inside the selected day and you can iterate over it.

Edit:
Given your needs to click the  element I changed the last line to:

```<code>day_events = calendar_day_element.find_elements_by_css_selector('li > i')
</code>```

The li > i selector means give me all  elements that are direct child of a
 element

Body:
I need to interact with elements under a class but the number of elements in that class is changing every time I run the script.

To give you context the website is a calendar, where I need to pick a day that I'll use as a template for my work. Every time I run the script (Monthly) the webpage with the calendar is updated to show the current month, thus Selenium picks the same day it did in the previous month. But every month the day Selenium picks has different contents and number of elements change every month. Currently, for example, the script is written to interact with 5 elements, but for next month it won't work because the day picked will have a different number of elements. So every month I have to manually change the script to interact with the correct number of elements.

Here's an example of the element structure of the website:

Text

Text

Text

So the number of elements that I need to interact within the class 'list-unstyled tags-list grid_9' is always changing. The elements with the id's "0", "1" and "2". Sometimes there might be 4 elements with ID's "0", "1", "2", "3" and sometimes there's 2 elements etc.

I've been trying to figure out how to write a script where Selenium looks inside that class ''list-unstyled tags-list grid_9', see's how many elements are in there and executes a -

driver.find_element_by_(xpath,class,id whatever).click()

on all of the elements found in there.

UPDATE:
So I tried this code:

tab = driver.find_element_by_css_selector('#postForm > div:nth-child(3) > ul.list-unstyled.tags-list.grid_9')
    hashs = tab.find_elements_by_tag_name('li')
    for element in hashs:
        element.find_element_by_tag_name('i').click()

And it gave me this error:

stale element reference: element is not attached to the page document

Body:
You can use the fact that an element also has all the find_elem... methods that the webdriver has, but with the context of that element  only, that works for you in the following way:

from selenium import webdriver

driver = webdriver.Firefox()
calendar_day_element = driver.find_element_by_css_selector('ul.list-unstyled.tags-list.grid_9')
day_events = calendar_day_element.find_elements_by_tag_name('li')

Now day_events is a list of all li elements inside the selected day and you can iterate over it.

Edit:
Given your needs to click the <i> element I changed the last line to:

day_events = calendar_day_element.find_elements_by_css_selector('li > i')

The li > i selector means give me all <i> elements that are direct child of a <li> element


问:
Object creation order with class having containment of other objects
```<code>#include "iostream"
using namespace std;
class C
{
    public:
    C() { cout << "C's Constructor Called " << endl;  }
};

class A
{
    public:
    A() { cout << "A's Constructor Called " << endl;  }
    A(int) {  cout << "A's int Constructor Called " << endl;  }
};

class B
{
    public:
    A a;
    B() { cout << "B's Constructor Called " << endl; }
    B(int i) : a(i) { cout << "B's int Constructor Called " << endl; }
    C c;
};

int main()
{
    B b1(1);
    return 0;
}
</code>```

Output:

    A's int Constructor Called

    C's Constructor Called

    B's int Constructor Called

Question :

Why output does not contain "A's Constructor Called"

According to me i thought Output would be like below :

    A's Constructor Called

    C's Constructor Called

    B's int Constructor Called

Wondering why A a does not lead to constructor A() being called but only A(int) because of a(i)

答:
Wondering why A a does not lead to constructor A() being called but only A(int) because of a(i)

A a; is only a declaration of a field member of class B. This does not initialize the variable in the same way a local declaration would. Instead, the initialization occurs in the B() constructor when you do a(i). This calls the A(int) constructor. The no-argument constructor will never be called here.

Body:
#include "iostream"
using namespace std;
class C
{
    public:
    C() { cout << "C's Constructor Called " << endl;  }
};

class A
{
    public:
    A() { cout << "A's Constructor Called " << endl;  }
    A(int) {  cout << "A's int Constructor Called " << endl;  }
};

class B
{
    public:
    A a;
    B() { cout << "B's Constructor Called " << endl; }
    B(int i) : a(i) { cout << "B's int Constructor Called " << endl; }
    C c;
};

int main()
{
    B b1(1);
    return 0;
}

Output:

    A's int Constructor Called

    C's Constructor Called

    B's int Constructor Called

Question :

Why output does not contain "A's Constructor Called"

According to me i thought Output would be like below :

    A's Constructor Called

    C's Constructor Called

    B's int Constructor Called

Wondering why A a does not lead to constructor A() being called but only A(int) because of a(i)


问:
How to throw exception if script is run with Python 2?
I have a script that should only be run with Python 3. I want to give a nice error message saying that this script should not be run with python2 if a user tries to run it with Python 2.x

How do I do this? When I try checking the Python version, it still throws an error, as Python parses the whole file before executing my if condition.

If possible, I'd rather not make another script.

答:
You can use the fact that in Python 2 strings are byte strings, while in Python 3 they are unicode strings. So any of

```<code>if ' ' == b' ':
    raise Exception ('Running this script with Python 2 is not supported')
</code>```

or

```<code>if isinstance (b' ', str):
    raise Exception ('Running this script with Python 2 is not supported')
</code>```

will do. Note that this does not need any imports - just language features.

Body:
You can use the fact that in Python 2 strings are byte strings, while in Python 3 they are unicode strings. So any of

if ' ' == b' ':
    raise Exception ('Running this script with Python 2 is not supported')

or

if isinstance (b' ', str):
    raise Exception ('Running this script with Python 2 is not supported')

will do. Note that this does not need any imports - just language features.


问:
MySQL - I have an issue with blank space
I have a drop down list on a form with values:

```<code>Value One
Value Two
Value Three
</code>```

The values go into a db.

I have another db with columns

```<code>Value One
Value Two
Value Three
</code>```

I have an IF statement that if form Value One to get records in db from Colum Value One.

But getting error message Unknown column 'Value' in 'field list'

I think it has to do with the space? Can I have spaces in the names in MYSQL? If I change it to Value_One, Value_Two, Value_Three can I change the form input Value to be Value%One, Value%Two, Value%Three etc will that work? Ideas?

答:
It's always a little harder to debug without seeing your code -- the offending SQL statement for example -- but you might benefit from referring to the column as `Value One` (note the backtick quote marks).

Update: response to comment

This works for me:

```<code>INSERT INTO `test_db` ( `Value One` ) VALUES ( 'Test data' );
</code>```

Body:
I have a drop down list on a form with values:

Value One
Value Two
Value Three

The values go into a db.

I have another db with columns

Value One
Value Two
Value Three

I have an IF statement that if form Value One to get records in db from Colum Value One.

But getting error message Unknown column 'Value' in 'field list'

I think it has to do with the space? Can I have spaces in the names in MYSQL? If I change it to Value_One, Value_Two, Value_Three can I change the form input Value to be Value%One, Value%Two, Value%Three etc will that work? Ideas?

Body:
It's always a little harder to debug without seeing your code -- the offending SQL statement for example -- but you might benefit from referring to the column as `Value One` (note the backtick quote marks).

Update: response to comment

This works for me:

INSERT INTO `test_db` ( `Value One` ) VALUES ( 'Test data' );


问:
How do I install tensorflow_text?
I'm trying to reproduce the notebook on Google Multilingual Universal Encoder. However by downloading the necessary libraries as tensorflow_text:

```<code>%%capture
#@title Setup Environment
# Install the latest Tensorflow version.
!pip3 install tensorflow_text
</code>```

or

```<code>!python -m pip install tensorflow_text
</code>```

And I get in jupyter:

```<code>---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-48-399dd4157896> in <module>
      8 import tensorflow.compat.v2 as tf
      9 import tensorflow_hub as hub
---> 10 from tensorflow_text import SentencepieceTokenizer
     11 import sklearn.metrics.pairwise
     12

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

I tried to install it with python -m pip install tensorflow-text, but it gave me:

```<code>(seg_env) C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>python -m pip install tensorflow-text
Collecting tensorflow-text
  ERROR: Could not find a version that satisfies the requirement tensorflow-text (from versions: none)
ERROR: No matching distribution found for tensorflow-text
WARNING: You are using pip version 19.2.3, however version 20.0.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
</code>```

I also tried conda install -c conda-forge tensorflow

```<code>(seg_env) C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment> conda install -c conda-forge tensorflow
Collecting package metadata (current_repodata.json): done
Solving environment: done

# All requested packages already installed.

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>set "KERAS_BACKEND="

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>python C:\Users\antoi\.conda\envs\seg_env\etc\keras\load_config.py  1>temp.txt

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>set /p KERAS_BACKEND= 0<temp.txt

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>del temp.txt

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>python -c "import keras"  1>nul 2>&1

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>if errorlevel 1 (
ver  1>nul
 set "KERAS_BACKEND=theano"
 python -c "import keras"  1>nul 2>&1
)

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>SET DISTUTILS_USE_SDK=1

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>SET MSSdk=1

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>SET platform=

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>IF /I [AMD64] == [amd64] set "platform=true"

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>IF /I [] == [amd64] set "platform=true"

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>if defined platform (set "VSREGKEY=HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\14.0" )  ELSE (set "VSREGKEY=HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\14.0" )

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>for /F "skip=2 tokens=2,*" %A in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\14.0" /v InstallDir') do SET "VSINSTALLDIR=%B"
ERROR: The system was unable to find the specified registry key or value.

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>if "" == "" (set "VSINSTALLDIR=" )

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>if "" == "" (
ECHO "WARNING: Did not find VS in registry or in VS140COMNTOOLS env var - your compiler may not work"
 GOTO End
)
"WARNING: Did not find VS in registry or in VS140COMNTOOLS env var - your compiler may not work"
The system cannot find the batch label specified - End
</code>```

Versions

```<code>(seg_env) C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation>python -m pip list | findstr tensorflow
tensorflow           2.1.0
tensorflow-estimator 2.1.0
</code>```

And python:

```<code>(seg_env) C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation>python
Python 3.6.7 (default, Dec  6 2019, 07:03:06) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
</code>```

I'm on Windows 10

答: This should work: pip install tensorflow-text

Title: How do I install tensorflow_text?

Body:
I'm trying to reproduce the notebook on Google Multilingual Universal Encoder. However by downloading the necessary libraries as tensorflow_text:

%%capture
#@title Setup Environment
# Install the latest Tensorflow version.
!pip3 install tensorflow_text

or

!python -m pip install tensorflow_text

And I get in jupyter:

---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-48-399dd4157896> in <module>
      8 import tensorflow.compat.v2 as tf
      9 import tensorflow_hub as hub
---> 10 from tensorflow_text import SentencepieceTokenizer
     11 import sklearn.metrics.pairwise
     12

ModuleNotFoundError: No module named 'tensorflow_text'

I tried to install it with python -m pip install tensorflow-text, but it gave me:

(seg_env) C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>python -m pip install tensorflow-text
Collecting tensorflow-text
  ERROR: Could not find a version that satisfies the requirement tensorflow-text (from versions: none)
ERROR: No matching distribution found for tensorflow-text
WARNING: You are using pip version 19.2.3, however version 20.0.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

I also tried conda install -c conda-forge tensorflow

(seg_env) C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment> conda install -c conda-forge tensorflow
Collecting package metadata (current_repodata.json): done
Solving environment: done

# All requested packages already installed.

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>set "KERAS_BACKEND="

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>python C:\Users\antoi\.conda\envs\seg_env\etc\keras\load_config.py  1>temp.txt

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>set /p KERAS_BACKEND= 0<temp.txt

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>del temp.txt

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>python -c "import keras"  1>nul 2>&1

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>if errorlevel 1 (
ver  1>nul
 set "KERAS_BACKEND=theano"
 python -c "import keras"  1>nul 2>&1
)

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>SET DISTUTILS_USE_SDK=1

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>SET MSSdk=1

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>SET platform=

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>IF /I [AMD64] == [amd64] set "platform=true"

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>IF /I [] == [amd64] set "platform=true"

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>if defined platform (set "VSREGKEY=HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\14.0" )  ELSE (set "VSREGKEY=HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\14.0" )

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>for /F "skip=2 tokens=2,*" %A in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\14.0" /v InstallDir') do SET "VSINSTALLDIR=%B"
ERROR: The system was unable to find the specified registry key or value.

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>if "" == "" (set "VSINSTALLDIR=" )

C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation\sentiment>if "" == "" (
ECHO "WARNING: Did not find VS in registry or in VS140COMNTOOLS env var - your compiler may not work"
 GOTO End
)
"WARNING: Did not find VS in registry or in VS140COMNTOOLS env var - your compiler may not work"
The system cannot find the batch label specified - End

Versions

(seg_env) C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation>python -m pip list | findstr tensorflow
tensorflow           2.1.0
tensorflow-estimator 2.1.0

And python:

(seg_env) C:\Users\antoi\Documents\Programming\Covent Garden\Segmentation>python
Python 3.6.7 (default, Dec  6 2019, 07:03:06) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

I'm on Windows 10


问:
Increment all entries in an array by 'n' without a for loop
I have an array:

arr = [5,5,5,5,5,5]

I want to increment a particular range in the arr by 'n'. So if n=2 and the range is [2,5].
The array should look like this:

arr = [5,5,7,7,7,5]

Needed to do this without a for loop, for a problem im trying to solve.

Tried:

arr[2:5] = [n]*3

but that obviously replaces the entries and becomes:

arr = [5,5,3,3,3,5]

Any suggestions would be highly appriciated.

答:
You have basically two options (for code see below):

Use slice assignment via a list comprehension (a[:] = [x+1 for x in a]),

Use a for-loop (even though you exclude this in your question, I don't see a legitimate reason for doing so).

They come with pros and cons. Let's assume you are going to replace some fraction of the list items (as opposed to a fixed number of items). The for-loop runs in Python and hence might be slower but it has O(1) memory usage. The list comprehension and slice assignment both operate in C (assuming you are using CPython) but it has O(N) memory usage due to the temporary list.

Using a generator doesn't buy anything since it is converted to a list anyway before the assignment happens (this is necessary because if the generator had fewer or more items than the slice, the list would need to be resized accordingly; see the source code).

Using a map adds even more overhead since it needs to call the mapped function on every item.

The following is a performance comparison of the different methods. The for-loop is fastest for very small lists since it has minimal overhead (just the range object). For more than about a dozen items, the list comprehension clearly outperforms the other methods and especially for larger lists (len(a) > 3e5) the difference to the generator becomes noticeable (the generator cannot provide information about its size, so the generated list needs to be resized as more items are fetched). For very large lists the difference between for-loop and list comprehension seems to shrink again since the memory overhead tends to outweigh the loop cost, but reaching that point would require unusually large lists (where you'd be better off using something like Numpy anyway).

This is the code using the perfplot package:

```<code>import numpy
import perfplot

def use_generator(a):
    i = slice(0, len(a)//2)
    a[i] = (x+1 for x in a[i])

def use_map(a):
    i = slice(0, len(a)//2)
    a[i] = map(lambda x: x+1, a[i])

def use_list(a):
    i = slice(0, len(a)//2)
    a[i] = [x+1 for x in a[i]]

def use_loop(a):
    for i in range(len(a)//2):
        a[i] += 1

perfplot.show(
    setup=lambda n: [0]*n,
    kernels=[use_generator, use_map, use_list, use_loop],
    n_range=[2**k for k in range(1, 26)],
    xlabel="len(a)",
    equality_check=None,
)
</code>```

Body:
You have basically two options (for code see below):

Use slice assignment via a list comprehension (a[:] = [x+1 for x in a]),

Use a for-loop (even though you exclude this in your question, I don't see a legitimate reason for doing so).

They come with pros and cons. Let's assume you are going to replace some fraction of the list items (as opposed to a fixed number of items). The for-loop runs in Python and hence might be slower but it has O(1) memory usage. The list comprehension and slice assignment both operate in C (assuming you are using CPython) but it has O(N) memory usage due to the temporary list.

Using a generator doesn't buy anything since it is converted to a list anyway before the assignment happens (this is necessary because if the generator had fewer or more items than the slice, the list would need to be resized accordingly; see the source code).

Using a map adds even more overhead since it needs to call the mapped function on every item.

The following is a performance comparison of the different methods. The for-loop is fastest for very small lists since it has minimal overhead (just the range object). For more than about a dozen items, the list comprehension clearly outperforms the other methods and especially for larger lists (len(a) > 3e5) the difference to the generator becomes noticeable (the generator cannot provide information about its size, so the generated list needs to be resized as more items are fetched). For very large lists the difference between for-loop and list comprehension seems to shrink again since the memory overhead tends to outweigh the loop cost, but reaching that point would require unusually large lists (where you'd be better off using something like Numpy anyway).

This is the code using the perfplot package:

import numpy
import perfplot

def use_generator(a):
    i = slice(0, len(a)//2)
    a[i] = (x+1 for x in a[i])

def use_map(a):
    i = slice(0, len(a)//2)
    a[i] = map(lambda x: x+1, a[i])

def use_list(a):
    i = slice(0, len(a)//2)
    a[i] = [x+1 for x in a[i]]

def use_loop(a):
    for i in range(len(a)//2):
        a[i] += 1

perfplot.show(
    setup=lambda n: [0]*n,
    kernels=[use_generator, use_map, use_list, use_loop],
    n_range=[2**k for k in range(1, 26)],
    xlabel="len(a)",
    equality_check=None,
)


问:
Best way to syncing two different database
I have two database(SQL Server) one database has 2.5 million records and the other one is empty, i want to transfer data from first one to the second one and after that every time first database has been changed the second database must sync. And we must do it in offline way with excel file for example(there is no online way between them) , Can anyone show me a guideline to do this?</p>

答:
There is only one out-of-the-box solution for offline replication, ie that doesn't require a network connection from the the distributor to the publisher and from the subscriber to the distributor or distributor to subscriber.

Snapshot Replication with Alternate Snapshot Location.  You take a snapshot of the published tables, copy the snapshot somehow to a location visible to the subscriber, and then apply the snapshot from the new location.


问:
NativeScript refuses to detect my avdmanager emulator
Trying to create a NativeScript app, but having started up my emulator, tns device android --available-devices won't detect it:

My Android SDK is installed at /usr/local/android/sdk, and I've made sure to delete every other installation of it that exists. tns doctor returns no errors, so I assume that this isn't the issue.

It's probably worth mentioning that I'm using Kubuntu, which I'm pretty sure is the reason the emulator crashes if I click one of the side menu buttons, but I think that's unrelated. The emulator definitely exists too:

If anyone has any ideas or needs anymore information, please don't hesitate to ask. Thank you so much!

答:
I'm on a mac, but i have the following set:</p>

```<code># ANDROID ENVS
export ANDROID_HOME=/Users/$USER/Library/Android/sdk.
export ANDROID_SDK_ROOT=/Users/$USER/Library/Android/sdk
export ANDROID_AVD_HOME=/Users/$USER/.android/avd
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
export PATH=${PATH}:$ANDROID_HOME/tools/gradle/bin
</code>```

Body:
I'm on a mac, but i have the following set:

# ANDROID ENVS
export ANDROID_HOME=/Users/$USER/Library/Android/sdk.
export ANDROID_SDK_ROOT=/Users/$USER/Library/Android/sdk
export ANDROID_AVD_HOME=/Users/$USER/.android/avd
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
export PATH=${PATH}:$ANDROID_HOME/tools/gradle/bin


问:
How to separate a string of character and read it in R as a vector?
I have a database with a column that contains species name in a string of characters:

```<code>plant.first.id$sp.lst[42]
</code>```

Returns:

```<code>[1] ['Trema lamarckianum', 'Parasponia rigida', 'Trema tomentosum', 'Trema micranthum', 'Cannabis sativa']
</code>```

I'd like to take the whole column of plant.first.id$sp.lst and turn the values into a vector that I'll be able to manipulate.

For example, I want this:

```<code>> plant.first.id$sp.lst[3:5]
[1] []
[2] ['Ficus carica', 'Aphananthe philippinensis', 'Ficus insipida', 'Aphananthe monoica', 'Castilla elastica', 'Maclura cochinchinensis', 'Maclura fruticosa']
[3] ['Artocarpus tamaran']

dput(plant.first.id$sp.lst[3:5])
structure(c(14L, 7L, 1L), .Label = c("['Artocarpus tamaran']",
"['Artocarpus thailandicus']", "['Boronia algida', 'Zanthoxylum coreanum', 'Citrus reticulata']",
"['Cissus integrifolia', 'Cissus populnea', 'Cissus hastata', 'Cissus trianae', 'Cissus penninervis', 'Cissus assamica']",
"['Cryptandra amara', 'Broussonetia papyrifera', 'Serichonus gracilipes', 'Colubrina asiatica', 'Artocarpus tamaran', 'Artocarpus chama', 'Artocarpus thailandicus', 'Artocarpus rubrovenius', 'Gouania mauritiana']",
"['Enterolobium gummiferum']", "['Ficus carica', 'Aphananthe philippinensis', 'Ficus insipida', 'Aphananthe monoica', 'Castilla elastica', 'Maclura cochinchinensis', 'Maclura fruticosa']",
"['Maclura cochinchinensis']", "['Pouteria multiflora', 'Diospyros toposia', 'Van-royena castanosperma', 'Micropholis guyanensis', 'Pycnandra comptonii', 'Chrysophyllum venezuelanense']",
"['Pouteria multiflora', 'Van-royena castanosperma', 'Chrysophyllum venezuelanense', 'Pycnandra comptonii', 'Micropholis guyanensis']",
"['Trema lamarckianum', 'Cannabis sativa', 'Trema tomentosum', 'Parasponia rigida', 'Ficus annulata', 'Trema micranthum', 'Celtis iguanaea', 'Artocarpus thailandicus']",
"['Trema lamarckianum', 'Ficus annulata', 'Parasponia rigida', 'Trema tomentosum', 'Trema micranthum', 'Cannabis sativa']",
"['Trema lamarckianum', 'Parasponia rigida', 'Trema tomentosum', 'Trema micranthum', 'Cannabis sativa']",
"[]"), class = "factor")
</code>```

To be something like:

```<code>c("")
c('Ficus carica', 'Aphananthe philippinensis', 'Ficus insipida', 'Aphananthe monoica', 'Castilla elastica', 'Maclura cochinchinensis', 'Maclura fruticosa')
c('Artocarpus tamaran')
</code>```

in a list form.

I've tried this:

```<code>strsplit(as.vector(plant.first.id$sp.lst[42]),split = ",")
</code>```

But it's not usable:

```<code>[[1]]
[1] "['Trema lamarckianum'" " 'Parasponia rigida'"  " 'Trema tomentosum'"   " 'Trema micranthum'"   " 'Cannabis sativa']"
</code>```

Also this:

```<code>gsub("[[(]", "(", plant.first.id$sp.lst[[42]])
gsub("]", ")", plant.first.id$sp.lst[[42]])
</code>```

But still not very helpful...

```<code>[1] "('Trema lamarckianum', 'Parasponia rigida', 'Trema tomentosum', 'Trema micranthum', 'Cannabis sativa']"
[1] "['Trema lamarckianum', 'Parasponia rigida', 'Trema tomentosum', 'Trema micranthum', 'Cannabis sativa')"
</code>```

答:
Using strplit to remove the extra space and apostrophe

```<code>y <- sapply(x, gsub, pattern = "^\\['?|'?]$", replacement = "")
strsplit(y, "', '")

[[1]]
character(0)

[[2]]
[1] "Ficus carica"              "Aphananthe philippinensis" "Ficus insipida"            "Aphananthe monoica"
[5] "Castilla elastica"         "Maclura cochinchinensis"   "Maclura fruticosa"

[[3]]
[1] "Artocarpus tamaran"
</code>```

Body:
I have a database with a column that contains species name in a string of characters:

plant.first.id$sp.lst[42]

Returns:

[1] ['Trema lamarckianum', 'Parasponia rigida', 'Trema tomentosum', 'Trema micranthum', 'Cannabis sativa']

I'd like to take the whole column of plant.first.id$sp.lst and turn the values into a vector that I'll be able to manipulate.

For example, I want this:

> plant.first.id$sp.lst[3:5]
[1] []
[2] ['Ficus carica', 'Aphananthe philippinensis', 'Ficus insipida', 'Aphananthe monoica', 'Castilla elastica', 'Maclura cochinchinensis', 'Maclura fruticosa']
[3] ['Artocarpus tamaran']

dput(plant.first.id$sp.lst[3:5])
structure(c(14L, 7L, 1L), .Label = c("['Artocarpus tamaran']",
"['Artocarpus thailandicus']", "['Boronia algida', 'Zanthoxylum coreanum', 'Citrus reticulata']",
"['Cissus integrifolia', 'Cissus populnea', 'Cissus hastata', 'Cissus trianae', 'Cissus penninervis', 'Cissus assamica']",
"['Cryptandra amara', 'Broussonetia papyrifera', 'Serichonus gracilipes', 'Colubrina asiatica', 'Artocarpus tamaran', 'Artocarpus chama', 'Artocarpus thailandicus', 'Artocarpus rubrovenius', 'Gouania mauritiana']",
"['Enterolobium gummiferum']", "['Ficus carica', 'Aphananthe philippinensis', 'Ficus insipida', 'Aphananthe monoica', 'Castilla elastica', 'Maclura cochinchinensis', 'Maclura fruticosa']",
"['Maclura cochinchinensis']", "['Pouteria multiflora', 'Diospyros toposia', 'Van-royena castanosperma', 'Micropholis guyanensis', 'Pycnandra comptonii', 'Chrysophyllum venezuelanense']",
"['Pouteria multiflora', 'Van-royena castanosperma', 'Chrysophyllum venezuelanense', 'Pycnandra comptonii', 'Micropholis guyanensis']",
"['Trema lamarckianum', 'Cannabis sativa', 'Trema tomentosum', 'Parasponia rigida', 'Ficus annulata', 'Trema micranthum', 'Celtis iguanaea', 'Artocarpus thailandicus']",
"['Trema lamarckianum', 'Ficus annulata', 'Parasponia rigida', 'Trema tomentosum', 'Trema micranthum', 'Cannabis sativa']",
"['Trema lamarckianum', 'Parasponia rigida', 'Trema tomentosum', 'Trema micranthum', 'Cannabis sativa']",
"[]"), class = "factor")

To be something like:

c("")
c('Ficus carica', 'Aphananthe philippinensis', 'Ficus insipida', 'Aphananthe monoica', 'Castilla elastica', 'Maclura cochinchinensis', 'Maclura fruticosa')
c('Artocarpus tamaran')

in a list form.

I've tried this:

strsplit(as.vector(plant.first.id$sp.lst[42]),split = ",")

But it's not usable:

[[1]]
[1] "['Trema lamarckianum'" " 'Parasponia rigida'"  " 'Trema tomentosum'"   " 'Trema micranthum'"   " 'Cannabis sativa']"

Also this:

gsub("[[(]", "(", plant.first.id$sp.lst[[42]])
gsub("]", ")", plant.first.id$sp.lst[[42]])

But still not very helpful...

[1] "('Trema lamarckianum', 'Parasponia rigida', 'Trema tomentosum', 'Trema micranthum', 'Cannabis sativa']"
[1] "['Trema lamarckianum', 'Parasponia rigida', 'Trema tomentosum', 'Trema micranthum', 'Cannabis sativa')"

Body:
Using strplit to remove the extra space and apostrophe

y <- sapply(x, gsub, pattern = "^\\['?|'?]$", replacement = "")
strsplit(y, "', '")

[[1]]
character(0)

[[2]]
[1] "Ficus carica"              "Aphananthe philippinensis" "Ficus insipida"            "Aphananthe monoica"
[5] "Castilla elastica"         "Maclura cochinchinensis"   "Maclura fruticosa"

[[3]]
[1] "Artocarpus tamaran"