问:
Slow Save in Entity Framework, very specific entity
I have a very interesting (and confusing) issue for quite a while, but cannot get to the bottom of it

I have a WPF Project built on Entity Framework, with about 100 different entities/tables, which all work smoothly. except for one entity type, named SaleProduct

Saving a SaleProduct takes about 5 minutes, sometimes even more (other entities take under 2 seconds usually). And only in the window.

For testing purposes, I put this code in app startup:

```<code>  Using d = GetSystemContext(True)
        Dim sp = d.Find(Of SaleProduct)(66246)
        sp.DiscountAmount += 1
        d.SaveChanges()
  End Using
</code>```

And saving there is OK(11 seconds, bearable).

But when I open a window with the SaleProduct as the DataContext and save there, it takes several minutes.

So, I would like to debug this. Maybe I have some bad code somewhere. But I'm not managing with this either. If I press pause in Visual Studio while the app is stuck saving, it freezes on the SaveChanges line, meaning not some custom code. So what difference should it make if we are in the app startup or in the window?

But lets take this a step further, I disabled Just My Code to get a better picture of whats freezing. And it gets stuck here:

InternalDispatcher.cs

```<code>try
  {
     interceptionContext.MutableData.SetExecuted(operation(target, interceptionContext));
  }
</code>```

Where the target is a pretty simple SQL statement

```<code>UPDATE [dbo].[Sales]
SET [LastEditedOn] = @0
WHERE ([ID] = @1)
SELECT [AutoPurchaseDate], [GrantingDate], [ReceivedOn], [Name], [TotalVatRate]
FROM [dbo].[Sales]
WHERE @@ROWCOUNT > 0 AND [ID] = @1
</code>```

Running this in SSMS takes <1 seconds.

But looking at the complete call stack I see that actually its stuck someplace in System.Data.dll. Though try as I might I cant find its .pdb.

So I tried to use decompile, but I get an error

Unable to compile the module

Even though, in the modules window the status is "Symbols loaded".

So I cannot pinpoint precisely.

For kicks, I tried upgrading to .net 4.8 (from 4.7). same problem.

What can I do? How to proceed? Where more can I Investigate?

NOTES

Tables Sales and SaleProducts both have Clustered Primary Keys.

Running SELECT * FROM sys.sysprocesses WHERE open_tran = 1 in SSMS while the code is stuck, returns 0 rows.

InSaveChanges, ChangeTracker.Entries returns precisely 2 entities. The SaleProduct, and its parent Sale.

I've posted a Profiler Trace here https://pastebin.com/enLgE0Ln

Here's the full StackTrace if it might help someone

```<code>[Managed to Native Transition]
    System.Data.dll!SNINativeMethodWrapper.SNIReadSyncOverAsync(System.Runtime.InteropServices.SafeHandle pConn, ref System.IntPtr packet, int timeout) Unknown
    System.Data.dll!System.Data.SqlClient.TdsParserStateObject.ReadSniSyncOverAsync()   Unknown
    System.Data.dll!System.Data.SqlClient.TdsParserStateObject.TryReadNetworkPacket()   Unknown
    System.Data.dll!System.Data.SqlClient.TdsParserStateObject.TryPrepareBuffer()   Unknown
    System.Data.dll!System.Data.SqlClient.TdsParserStateObject.TryReadByte(out byte value)  Unknown
    System.Data.dll!System.Data.SqlClient.TdsParser.TryRun(System.Data.SqlClient.RunBehavior runBehavior, System.Data.SqlClient.SqlCommand cmdHandler, System.Data.SqlClient.SqlDataReader dataStream, System.Data.SqlClient.BulkCopySimpleResultSet bulkCopyHandler, System.Data.SqlClient.TdsParserStateObject stateObj, out bool dataReady)  Unknown
    System.Data.dll!System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()    Unknown
    System.Data.dll!System.Data.SqlClient.SqlDataReader.MetaData.get()  Unknown
    System.Data.dll!System.Data.SqlClient.SqlCommand.FinishExecuteReader(System.Data.SqlClient.SqlDataReader ds, System.Data.SqlClient.RunBehavior runBehavior, string resetOptionsString, bool isInternal, bool forDescribeParameterEncryption, bool shouldCacheForAlwaysEncrypted)    Unknown
    System.Data.dll!System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(System.Data.CommandBehavior cmdBehavior, System.Data.SqlClient.RunBehavior runBehavior, bool returnStream, bool async, int timeout, out System.Threading.Tasks.Task task, bool asyncWrite, bool inRetry, System.Data.SqlClient.SqlDataReader ds, bool describeParameterEncryptionRequest)  Unknown
    System.Data.dll!System.Data.SqlClient.SqlCommand.RunExecuteReader(System.Data.CommandBehavior cmdBehavior, System.Data.SqlClient.RunBehavior runBehavior, bool returnStream, string method, System.Threading.Tasks.TaskCompletionSource<object> completion, int timeout, out System.Threading.Tasks.Task task, out bool usedCache, bool asyncWrite, bool inRetry)   Unknown
    System.Data.dll!System.Data.SqlClient.SqlCommand.RunExecuteReader(System.Data.CommandBehavior cmdBehavior, System.Data.SqlClient.RunBehavior runBehavior, bool returnStream, string method) Unknown
    System.Data.dll!System.Data.SqlClient.SqlCommand.ExecuteReader(System.Data.CommandBehavior behavior, string method) Unknown
>   EntityFramework.dll!System.Data.Entity.Infrastructure.Interception.InternalDispatcher<System.Data.Entity.Infrastructure.Interception.IDbCommandInterceptor>.Dispatch<System.Data.Common.DbCommand, System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext<System.Data.Common.DbDataReader>, System.Data.Common.DbDataReader>(System.Data.Common.DbCommand target, System.Func<System.Data.Common.DbCommand, System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext<System.Data.Common.DbDataReader>, System.Data.Common.DbDataReader> operation, System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext, System.Action<System.Data.Entity.Infrastructure.Interception.IDbCommandInterceptor, System.Data.Common.DbCommand, System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext<System.Data.Common.DbDataReader>> executing, System.Action<System.Data.Entity.Infrastructure.Interception.IDbCommandInterceptor, System.Data.Common.DbCommand, System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext<System.Data.Common.DbDataReader>> executed) Line 138  C#
    EntityFramework.dll!System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(System.Data.Common.DbCommand command, System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext interceptionContext) Line 103   C#
    EntityFramework.dll!System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(System.Collections.Generic.Dictionary<int, object> identifierValues, System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<System.Data.Entity.Core.Mapping.Update.Internal.PropagatorResult, object>> generatedValues) Line 118  C#
    EntityFramework.dll!System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() Line 532  C#
    EntityFramework.dll!System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction<int>(System.Func<int> func, System.Data.Entity.Infrastructure.IDbExecutionStrategy executionStrategy, bool startLocalTransaction, bool releaseConnectionOnSuccess) Line 2203 C#
    EntityFramework.dll!System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(System.Data.Entity.Core.Objects.SaveOptions options, System.Data.Entity.Infrastructure.IDbExecutionStrategy executionStrategy, bool startLocalTransaction) Line 2148   C#
    EntityFramework.SqlServer.dll!System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute<int>(System.Func<int> operation) Unknown
    EntityFramework.dll!System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(System.Data.Entity.Core.Objects.SaveOptions options, bool executeInExistingTransaction) Line 2046 C#
    EntityFramework.dll!System.Data.Entity.Internal.InternalContext.SaveChanges() Line 483  C#
    Machshevet.dll!Machshevet.Core.RecordContext.SaveChanges() Line 762 Basic
    Machshevet.dll!Machshevet.Windows.RecordWindow.Save() Line 169  Basic
    Machshevet.dll!Machshevet.Windows.RecordWindow.<closure>.<lambda35-0>() Line 44 Basic
    PresentationCore.dll!System.Windows.Input.CommandBinding.OnExecuted(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)  Unknown
    PresentationCore.dll!System.Windows.Input.CommandManager.ExecuteCommandBinding(object sender, System.Windows.Input.ExecutedRoutedEventArgs e, System.Windows.Input.CommandBinding commandBinding)   Unknown
    PresentationCore.dll!System.Windows.Input.CommandManager.FindCommandBinding(System.Windows.Input.CommandBindingCollection commandBindings, object sender, System.Windows.RoutedEventArgs e, System.Windows.Input.ICommand command, bool execute)    Unknown
    PresentationCore.dll!System.Windows.Input.CommandManager.FindCommandBinding(object sender, System.Windows.RoutedEventArgs e, System.Windows.Input.ICommand command, bool execute)   Unknown
    PresentationCore.dll!System.Windows.Input.CommandManager.OnExecuted(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)  Unknown
    PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target)   Unknown
    PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
    PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised)    Unknown
    PresentationCore.dll!System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args)   Unknown
    PresentationCore.dll!System.Windows.Input.RoutedCommand.ExecuteImpl(object parameter, System.Windows.IInputElement target, bool userInitiated)  Unknown
    PresentationCore.dll!System.Windows.Input.CommandManager.TransferEvent(System.Windows.IInputElement newSource, System.Windows.Input.ExecutedRoutedEventArgs e)  Unknown
    PresentationCore.dll!System.Windows.Input.CommandManager.OnExecuted(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)  Unknown
    PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target)   Unknown
    PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
    PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised)    Unknown
    PresentationCore.dll!System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args)   Unknown
    PresentationCore.dll!System.Windows.Input.RoutedCommand.ExecuteImpl(object parameter, System.Windows.IInputElement target, bool userInitiated)  Unknown
    PresentationFramework.dll!MS.Internal.Commands.CommandHelpers.CriticalExecuteCommandSource(System.Windows.Input.ICommandSource commandSource, bool userInitiated)   Unknown
    PresentationFramework.dll!System.Windows.Controls.Primitives.ButtonBase.OnClick()   Unknown
    PresentationFramework.dll!System.Windows.Controls.Button.OnClick()  Unknown
    System.Windows.Controls.Ribbon.dll!System.Windows.Controls.Ribbon.RibbonButton.OnClick()    Unknown
    PresentationFramework.dll!System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs e)    Unknown
    PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target)   Unknown
    PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
    PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised)    Unknown
    PresentationCore.dll!System.Windows.UIElement.ReRaiseEventAs(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args, System.Windows.RoutedEvent newEvent)  Unknown
    PresentationCore.dll!System.Windows.UIElement.OnMouseUpThunk(object sender, System.Windows.Input.MouseButtonEventArgs e)    Unknown
    PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target)   Unknown
    PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
    PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised)    Unknown
    PresentationCore.dll!System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args)   Unknown
    PresentationCore.dll!System.Windows.UIElement.RaiseTrustedEvent(System.Windows.RoutedEventArgs args)    Unknown
    PresentationCore.dll!System.Windows.Input.InputManager.ProcessStagingArea() Unknown
    PresentationCore.dll!System.Windows.Input.InputManager.ProcessInput(System.Windows.Input.InputEventArgs input)  Unknown
    PresentationCore.dll!System.Windows.Input.InputProviderSite.ReportInput(System.Windows.Input.InputReport inputReport)   Unknown
    PresentationCore.dll!System.Windows.Interop.HwndMouseInputProvider.ReportInput(System.IntPtr hwnd, System.Windows.Input.InputMode mode, int timestamp, System.Windows.Input.RawMouseActions actions, int x, int y, int wheel)   Unknown
    PresentationCore.dll!System.Windows.Interop.HwndMouseInputProvider.FilterMessage(System.IntPtr hwnd, MS.Internal.Interop.WindowMessage msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled)   Unknown
    PresentationCore.dll!System.Windows.Interop.HwndSource.InputFilterMessage(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled)    Unknown
    WindowsBase.dll!MS.Win32.HwndWrapper.WndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) Unknown
    WindowsBase.dll!MS.Win32.HwndSubclass.DispatcherCallbackOperation(object o) Unknown
    WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback, object args, int numArgs)  Unknown
    WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.TryCatchWhen(object source, System.Delegate callback, object args, int numArgs, System.Delegate catchHandler) Unknown
    WindowsBase.dll!System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority priority, System.TimeSpan timeout, System.Delegate method, object args, int numArgs)   Unknown
    WindowsBase.dll!MS.Win32.HwndSubclass.SubclassWndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam)  Unknown
    [Native to Managed Transition]
    [Managed to Native Transition]
    WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame)   Unknown
    PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore)   Unknown
    PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window)  Unknown
</code>```

答: In the end it seems that the error disappeared after a index rebuild. Even though I cant understand if it was an index issue, how come it worked flawlessly time and again via SSMS and EF without window. But for now its working just dandy. Thanks again for all posters, as you were extremely helpful in narrowing down and focusing.</p>

Body:
I have a very interesting (and confusing) issue for quite a while, but cannot get to the bottom of it

I have a WPF Project built on Entity Framework, with about 100 different entities/tables, which all work smoothly. except for one entity type, named SaleProduct

Saving a SaleProduct takes about 5 minutes, sometimes even more (other entities take under 2 seconds usually). And only in the window.

For testing purposes, I put this code in app startup:

  Using d = GetSystemContext(True)
        Dim sp = d.Find(Of SaleProduct)(66246)
        sp.DiscountAmount += 1
        d.SaveChanges()
  End Using

And saving there is OK(11 seconds, bearable).

But when I open a window with the SaleProduct as the DataContext and save there, it takes several minutes.

So, I would like to debug this. Maybe I have some bad code somewhere. But I'm not managing with this either. If I press pause in Visual Studio while the app is stuck saving, it freezes on the SaveChanges line, meaning not some custom code. So what difference should it make if we are in the app startup or in the window?

But lets take this a step further, I disabled Just My Code to get a better picture of whats freezing. And it gets stuck here:

InternalDispatcher.cs

try
  {
     interceptionContext.MutableData.SetExecuted(operation(target, interceptionContext));
  }

Where the target is a pretty simple SQL statement

UPDATE [dbo].[Sales]
SET [LastEditedOn] = @0
WHERE ([ID] = @1)
SELECT [AutoPurchaseDate], [GrantingDate], [ReceivedOn], [Name], [TotalVatRate]
FROM [dbo].[Sales]
WHERE @@ROWCOUNT > 0 AND [ID] = @1

Running this in SSMS takes <1 seconds.

But looking at the complete call stack I see that actually its stuck someplace in System.Data.dll. Though try as I might I cant find its .pdb.

So I tried to use decompile, but I get an error

Unable to compile the module

Even though, in the modules window the status is "Symbols loaded".

So I cannot pinpoint precisely.

For kicks, I tried upgrading to .net 4.8 (from 4.7). same problem.

What can I do? How to proceed? Where more can I Investigate?

NOTES

Tables Sales and SaleProducts both have Clustered Primary Keys.

Running SELECT * FROM sys.sysprocesses WHERE open_tran = 1 in SSMS while the code is stuck, returns 0 rows.

InSaveChanges, ChangeTracker.Entries returns precisely 2 entities. The SaleProduct, and its parent Sale.

I've posted a Profiler Trace here https://pastebin.com/enLgE0Ln

Here's the full StackTrace if it might help someone

[Managed to Native Transition]
    System.Data.dll!SNINativeMethodWrapper.SNIReadSyncOverAsync(System.Runtime.InteropServices.SafeHandle pConn, ref System.IntPtr packet, int timeout) Unknown
    System.Data.dll!System.Data.SqlClient.TdsParserStateObject.ReadSniSyncOverAsync()   Unknown
    System.Data.dll!System.Data.SqlClient.TdsParserStateObject.TryReadNetworkPacket()   Unknown
    System.Data.dll!System.Data.SqlClient.TdsParserStateObject.TryPrepareBuffer()   Unknown
    System.Data.dll!System.Data.SqlClient.TdsParserStateObject.TryReadByte(out byte value)  Unknown
    System.Data.dll!System.Data.SqlClient.TdsParser.TryRun(System.Data.SqlClient.RunBehavior runBehavior, System.Data.SqlClient.SqlCommand cmdHandler, System.Data.SqlClient.SqlDataReader dataStream, System.Data.SqlClient.BulkCopySimpleResultSet bulkCopyHandler, System.Data.SqlClient.TdsParserStateObject stateObj, out bool dataReady)  Unknown
    System.Data.dll!System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()    Unknown
    System.Data.dll!System.Data.SqlClient.SqlDataReader.MetaData.get()  Unknown
    System.Data.dll!System.Data.SqlClient.SqlCommand.FinishExecuteReader(System.Data.SqlClient.SqlDataReader ds, System.Data.SqlClient.RunBehavior runBehavior, string resetOptionsString, bool isInternal, bool forDescribeParameterEncryption, bool shouldCacheForAlwaysEncrypted)    Unknown
    System.Data.dll!System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(System.Data.CommandBehavior cmdBehavior, System.Data.SqlClient.RunBehavior runBehavior, bool returnStream, bool async, int timeout, out System.Threading.Tasks.Task task, bool asyncWrite, bool inRetry, System.Data.SqlClient.SqlDataReader ds, bool describeParameterEncryptionRequest)  Unknown
    System.Data.dll!System.Data.SqlClient.SqlCommand.RunExecuteReader(System.Data.CommandBehavior cmdBehavior, System.Data.SqlClient.RunBehavior runBehavior, bool returnStream, string method, System.Threading.Tasks.TaskCompletionSource<object> completion, int timeout, out System.Threading.Tasks.Task task, out bool usedCache, bool asyncWrite, bool inRetry)   Unknown
    System.Data.dll!System.Data.SqlClient.SqlCommand.RunExecuteReader(System.Data.CommandBehavior cmdBehavior, System.Data.SqlClient.RunBehavior runBehavior, bool returnStream, string method) Unknown
    System.Data.dll!System.Data.SqlClient.SqlCommand.ExecuteReader(System.Data.CommandBehavior behavior, string method) Unknown
>   EntityFramework.dll!System.Data.Entity.Infrastructure.Interception.InternalDispatcher<System.Data.Entity.Infrastructure.Interception.IDbCommandInterceptor>.Dispatch<System.Data.Common.DbCommand, System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext<System.Data.Common.DbDataReader>, System.Data.Common.DbDataReader>(System.Data.Common.DbCommand target, System.Func<System.Data.Common.DbCommand, System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext<System.Data.Common.DbDataReader>, System.Data.Common.DbDataReader> operation, System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext, System.Action<System.Data.Entity.Infrastructure.Interception.IDbCommandInterceptor, System.Data.Common.DbCommand, System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext<System.Data.Common.DbDataReader>> executing, System.Action<System.Data.Entity.Infrastructure.Interception.IDbCommandInterceptor, System.Data.Common.DbCommand, System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext<System.Data.Common.DbDataReader>> executed) Line 138  C#
    EntityFramework.dll!System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(System.Data.Common.DbCommand command, System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext interceptionContext) Line 103   C#
    EntityFramework.dll!System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(System.Collections.Generic.Dictionary<int, object> identifierValues, System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<System.Data.Entity.Core.Mapping.Update.Internal.PropagatorResult, object>> generatedValues) Line 118  C#
    EntityFramework.dll!System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() Line 532  C#
    EntityFramework.dll!System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction<int>(System.Func<int> func, System.Data.Entity.Infrastructure.IDbExecutionStrategy executionStrategy, bool startLocalTransaction, bool releaseConnectionOnSuccess) Line 2203 C#
    EntityFramework.dll!System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(System.Data.Entity.Core.Objects.SaveOptions options, System.Data.Entity.Infrastructure.IDbExecutionStrategy executionStrategy, bool startLocalTransaction) Line 2148   C#
    EntityFramework.SqlServer.dll!System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute<int>(System.Func<int> operation) Unknown
    EntityFramework.dll!System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(System.Data.Entity.Core.Objects.SaveOptions options, bool executeInExistingTransaction) Line 2046 C#
    EntityFramework.dll!System.Data.Entity.Internal.InternalContext.SaveChanges() Line 483  C#
    Machshevet.dll!Machshevet.Core.RecordContext.SaveChanges() Line 762 Basic
    Machshevet.dll!Machshevet.Windows.RecordWindow.Save() Line 169  Basic
    Machshevet.dll!Machshevet.Windows.RecordWindow.<closure>.<lambda35-0>() Line 44 Basic
    PresentationCore.dll!System.Windows.Input.CommandBinding.OnExecuted(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)  Unknown
    PresentationCore.dll!System.Windows.Input.CommandManager.ExecuteCommandBinding(object sender, System.Windows.Input.ExecutedRoutedEventArgs e, System.Windows.Input.CommandBinding commandBinding)   Unknown
    PresentationCore.dll!System.Windows.Input.CommandManager.FindCommandBinding(System.Windows.Input.CommandBindingCollection commandBindings, object sender, System.Windows.RoutedEventArgs e, System.Windows.Input.ICommand command, bool execute)    Unknown
    PresentationCore.dll!System.Windows.Input.CommandManager.FindCommandBinding(object sender, System.Windows.RoutedEventArgs e, System.Windows.Input.ICommand command, bool execute)   Unknown
    PresentationCore.dll!System.Windows.Input.CommandManager.OnExecuted(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)  Unknown
    PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target)   Unknown
    PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
    PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised)    Unknown
    PresentationCore.dll!System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args)   Unknown
    PresentationCore.dll!System.Windows.Input.RoutedCommand.ExecuteImpl(object parameter, System.Windows.IInputElement target, bool userInitiated)  Unknown
    PresentationCore.dll!System.Windows.Input.CommandManager.TransferEvent(System.Windows.IInputElement newSource, System.Windows.Input.ExecutedRoutedEventArgs e)  Unknown
    PresentationCore.dll!System.Windows.Input.CommandManager.OnExecuted(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)  Unknown
    PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target)   Unknown
    PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
    PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised)    Unknown
    PresentationCore.dll!System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args)   Unknown
    PresentationCore.dll!System.Windows.Input.RoutedCommand.ExecuteImpl(object parameter, System.Windows.IInputElement target, bool userInitiated)  Unknown
    PresentationFramework.dll!MS.Internal.Commands.CommandHelpers.CriticalExecuteCommandSource(System.Windows.Input.ICommandSource commandSource, bool userInitiated)   Unknown
    PresentationFramework.dll!System.Windows.Controls.Primitives.ButtonBase.OnClick()   Unknown
    PresentationFramework.dll!System.Windows.Controls.Button.OnClick()  Unknown
    System.Windows.Controls.Ribbon.dll!System.Windows.Controls.Ribbon.RibbonButton.OnClick()    Unknown
    PresentationFramework.dll!System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs e)    Unknown
    PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target)   Unknown
    PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
    PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised)    Unknown
    PresentationCore.dll!System.Windows.UIElement.ReRaiseEventAs(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args, System.Windows.RoutedEvent newEvent)  Unknown
    PresentationCore.dll!System.Windows.UIElement.OnMouseUpThunk(object sender, System.Windows.Input.MouseButtonEventArgs e)    Unknown
    PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target)   Unknown
    PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
    PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised)    Unknown
    PresentationCore.dll!System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args)   Unknown
    PresentationCore.dll!System.Windows.UIElement.RaiseTrustedEvent(System.Windows.RoutedEventArgs args)    Unknown
    PresentationCore.dll!System.Windows.Input.InputManager.ProcessStagingArea() Unknown
    PresentationCore.dll!System.Windows.Input.InputManager.ProcessInput(System.Windows.Input.InputEventArgs input)  Unknown
    PresentationCore.dll!System.Windows.Input.InputProviderSite.ReportInput(System.Windows.Input.InputReport inputReport)   Unknown
    PresentationCore.dll!System.Windows.Interop.HwndMouseInputProvider.ReportInput(System.IntPtr hwnd, System.Windows.Input.InputMode mode, int timestamp, System.Windows.Input.RawMouseActions actions, int x, int y, int wheel)   Unknown
    PresentationCore.dll!System.Windows.Interop.HwndMouseInputProvider.FilterMessage(System.IntPtr hwnd, MS.Internal.Interop.WindowMessage msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled)   Unknown
    PresentationCore.dll!System.Windows.Interop.HwndSource.InputFilterMessage(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled)    Unknown
    WindowsBase.dll!MS.Win32.HwndWrapper.WndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) Unknown
    WindowsBase.dll!MS.Win32.HwndSubclass.DispatcherCallbackOperation(object o) Unknown
    WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback, object args, int numArgs)  Unknown
    WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.TryCatchWhen(object source, System.Delegate callback, object args, int numArgs, System.Delegate catchHandler) Unknown
    WindowsBase.dll!System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority priority, System.TimeSpan timeout, System.Delegate method, object args, int numArgs)   Unknown
    WindowsBase.dll!MS.Win32.HwndSubclass.SubclassWndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam)  Unknown
    [Native to Managed Transition]
    [Managed to Native Transition]
    WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame)   Unknown
    PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore)   Unknown
    PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window)  Unknown


来源: stackexchange

问:
How to join the two dataframe by condition in PySpark?
I am having two dataframe like described below

Dataframe 1

```<code>P_ID     P_Name     P_Description   P_Size

100      Moto          Mobile         16

200      Apple         Mobile         15

300      Oppo          Mobile         18
</code>```

Dataframe 2

```<code>P_ID     List_Code      P_Amount

100      ALPHA           20000

100      BETA            60000

300      GAMMA           15000
</code>```

Requirement :
Need to join the two dataframe by P_ID.

Information about the dataframe :
In dataframe 1 P_ID is a primary key and dataframe 2 does't have any primary attribute.

How to join the dataframe
Need to create new columns in dataframe 1 from the value of dataframe 2 List_Code appends with "_price". If dataframe 2 List_Code contains 20 unique values we need to create 20 column in dataframe 1. Then, we have fill the value in newly created column in dataframe 1 from the dataframe 2 P_Amount column based on P_ID if present else fills with zero. After creation of dataframe we need to join the dataframe based on the P_ID. If we add the column with the expected value in dataframe 1 we can join the dataframe. My problem is creating new columns with the expected value.

The expected dataframe is shown below

Expected dataframe

```<code>   P_ID     P_Name     P_Description   P_Size   ALPHA_price   BETA_price    GAMMA_price

    100      Moto          Mobile         16       20000       60000           0

    200      Apple         Mobile         15         0            0            0

    300      Oppo          Mobile         18         0            0           15000
</code>```

Can you please help me to solve the problem, thanks in advance.

答:
For you application, you need to pivot the second dataframe and then join the first dataframe on to the pivoted result on P_ID using left join.

See the code below.

```<code>df_1 = pd.DataFrame({'P_ID' : [100, 200, 300], 'P_Name': ['Moto', 'Apple', 'Oppo'], 'P_Size' : [16, 15, 18]})
sdf_1 = sc.createDataFrame(df_1)

df_2 = pd.DataFrame({'P_ID' : [100, 100, 300], 'List_Code': ['ALPHA', 'BETA', 'GAMMA'], 'P_Amount' : [20000, 60000, 10000]})
sdf_2 = sc.createDataFrame(df_2)

sdf_pivoted = sdf_2.groupby('P_ID').pivot('List_Code').agg(f.sum('P_Amount')).fillna(0)

sdf_joined = sdf_1.join(sdf_pivoted, on='P_ID', how='left').fillna(0)
sdf_joined.show()

+----+------+------+-----+-----+-----+
|P_ID|P_Name|P_Size|ALPHA| BETA|GAMMA|
+----+------+------+-----+-----+-----+
| 300|  Oppo|    18|    0|    0|10000|
| 200| Apple|    15|    0|    0|    0|
| 100|  Moto|    16|20000|60000|    0|
+----+------+------+-----+-----+-----+
</code>```

You can change the column names or ordering of the dataframe as needed.

ContentLicense: CC BY-SA 4.0

Body:
I am having two dataframe like described below

Dataframe 1

P_ID     P_Name     P_Description   P_Size

100      Moto          Mobile         16

200      Apple         Mobile         15

300      Oppo          Mobile         18

Dataframe 2

P_ID     List_Code      P_Amount

100      ALPHA           20000

100      BETA            60000

300      GAMMA           15000

Requirement :
Need to join the two dataframe by P_ID.

Information about the dataframe :
In dataframe 1 P_ID is a primary key and dataframe 2 does't have any primary attribute.

How to join the dataframe
Need to create new columns in dataframe 1 from the value of dataframe 2 List_Code appends with "_price". If dataframe 2 List_Code contains 20 unique values we need to create 20 column in dataframe 1. Then, we have fill the value in newly created column in dataframe 1 from the dataframe 2 P_Amount column based on P_ID if present else fills with zero. After creation of dataframe we need to join the dataframe based on the P_ID. If we add the column with the expected value in dataframe 1 we can join the dataframe. My problem is creating new columns with the expected value.

The expected dataframe is shown below

Expected dataframe

   P_ID     P_Name     P_Description   P_Size   ALPHA_price   BETA_price    GAMMA_price

    100      Moto          Mobile         16       20000       60000           0

    200      Apple         Mobile         15         0            0            0

    300      Oppo          Mobile         18         0            0           15000

Can you please help me to solve the problem, thanks in advance.

Body:
For you application, you need to pivot the second dataframe and then join the first dataframe on to the pivoted result on P_ID using left join.

See the code below.

df_1 = pd.DataFrame({'P_ID' : [100, 200, 300], 'P_Name': ['Moto', 'Apple', 'Oppo'], 'P_Size' : [16, 15, 18]})
sdf_1 = sc.createDataFrame(df_1)

df_2 = pd.DataFrame({'P_ID' : [100, 100, 300], 'List_Code': ['ALPHA', 'BETA', 'GAMMA'], 'P_Amount' : [20000, 60000, 10000]})
sdf_2 = sc.createDataFrame(df_2)

sdf_pivoted = sdf_2.groupby('P_ID').pivot('List_Code').agg(f.sum('P_Amount')).fillna(0)

sdf_joined = sdf_1.join(sdf_pivoted, on='P_ID', how='left').fillna(0)
sdf_joined.show()

+----+------+------+-----+-----+-----+
|P_ID|P_Name|P_Size|ALPHA| BETA|GAMMA|
+----+------+------+-----+-----+-----+
| 300|  Oppo|    18|    0|    0|10000|
| 200| Apple|    15|    0|    0|    0|
| 100|  Moto|    16|20000|60000|    0|
+----+------+------+-----+-----+-----+

You can change the column names or ordering of the dataframe as needed.


问:
how to change view constraint top margin programmatically in Android?
I am using constraint layout and I have a view like this

```<code><View
           android:id="@+id/view_separator_line"
           android:layout_width="0dp"
           android:layout_height="1dp"
           android:layout_marginTop="32dp"
           android:background="@color/grey_dark_low"
           app:layout_constraintEnd_toEndOf="@+id/imageView_gear_setting_user_information"
           app:layout_constraintStart_toStartOf="@+id/imageView_following_profile_picture"
           app:layout_constraintTop_toBottomOf="@+id/imageView_following_profile_picture" />
</code>```

as you can see from the xml above, top of this view is constrained to the bottom of another view, and the layout margin top is 32dp, I want to change it programmatically to be 24dp, how to do that ?

答:
try this below code</p>

```<code>ConstraintLayout.LayoutParams newLayoutParams = (ConstraintLayout.LayoutParams) toolbar.getLayoutParams();
     newLayoutParams.topMargin = 0;
     newLayoutParams.leftMargin = 0;
     newLayoutParams.rightMargin = 0;
     toolbar.setLayoutParams(newLayoutParams););
</code>```

Body:
I am using constraint layout and I have a view like this

<View
           android:id="@+id/view_separator_line"
           android:layout_width="0dp"
           android:layout_height="1dp"
           android:layout_marginTop="32dp"
           android:background="@color/grey_dark_low"
           app:layout_constraintEnd_toEndOf="@+id/imageView_gear_setting_user_information"
           app:layout_constraintStart_toStartOf="@+id/imageView_following_profile_picture"
           app:layout_constraintTop_toBottomOf="@+id/imageView_following_profile_picture" />

as you can see from the xml above, top of this view is constrained to the bottom of another view, and the layout margin top is 32dp, I want to change it programmatically to be 24dp, how to do that ?

Body:
try this below code

ConstraintLayout.LayoutParams newLayoutParams = (ConstraintLayout.LayoutParams) toolbar.getLayoutParams();
     newLayoutParams.topMargin = 0;
     newLayoutParams.leftMargin = 0;
     newLayoutParams.rightMargin = 0;
     toolbar.setLayoutParams(newLayoutParams););


问:
Weighted random bearing for wandering point
```<code>var latlon = new LatLon(50,-0.075);
setInterval(function(){
    latlon = latlon.destinationPoint(randomBetween(0,360),0.001);
},1000);
</code>```

Here is my very basic wandering point. It creates a geospatial point then moves one metre in a random direction every second. However, this is too random. How can I give my wandering point some direction so that it actually moves somewhere? Are the any good examples out there of a wandering geospatial point?

答:
You could store last wandering coefficient (as I undestand that would be randomBetween(...) value) in a variable, and next time use a weighted average of this value and new random value.

```<code>var latlon = new LatLon(50,-0.075);
var oldValue = randomBetween(0,360);
var weights = [0.5, 0.5];  // Here you can influece the level of 'randomness'.
// Just make sure to weights sum up to 1
setInterval(function(){
    var newValue = oldValue * weights[0] + randomBetween(0,360) * weights[1];
    latlon = latlon.destinationPoint(newValue, 0.001);
    oldValue = newValue;
},1000);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
var latlon = new LatLon(50,-0.075);
setInterval(function(){
    latlon = latlon.destinationPoint(randomBetween(0,360),0.001);
},1000);

Here is my very basic wandering point. It creates a geospatial point then moves one metre in a random direction every second. However, this is too random. How can I give my wandering point some direction so that it actually moves somewhere? Are the any good examples out there of a wandering geospatial point?

Body:
You could store last wandering coefficient (as I undestand that would be randomBetween(...) value) in a variable, and next time use a weighted average of this value and new random value.

var latlon = new LatLon(50,-0.075);
var oldValue = randomBetween(0,360);
var weights = [0.5, 0.5];  // Here you can influece the level of 'randomness'.
// Just make sure to weights sum up to 1
setInterval(function(){
    var newValue = oldValue * weights[0] + randomBetween(0,360) * weights[1];
    latlon = latlon.destinationPoint(newValue, 0.001);
    oldValue = newValue;
},1000);


问:
python3: how to convert "\u3000" (ideographic space) to "　"?
japanese.txt

```<code>あかさ
あいうえ　お
いい
</code>```

mycode.py

```<code>with open('japanese.txt', 'r', encoding='utf-8') as f:
    old = [line.strip() for line in f.readlines()]

send_mail(from, to, title, message=f"hello {old}!")
</code>```

Then I receive mail like this

```<code>hello ['あかさ', 'あいうえ\u3000お', 'いい']!
</code>```

What I want to mail is this

```<code>hello ['あかさ', 'あいうえ　お', 'いい']!
</code>```

How can I achieve this?

答:
list's __str__ method uses repr on elements, therefore you're seeing \u3000 in your mail. Just convert list to string yourself:

```<code>In [28]: l = ['あかさ', 'あいうえ\u3000お', 'いい']

In [29]: print(', '.join(map(str, l)))
あかさ, あいうえ　お, いい
</code>```

If you're sure all your list elements are strings, you can omit map(str, ...) and just use ', '.join(l)

Body:
japanese.txt

あかさ
あいうえ　お
いい

mycode.py

with open('japanese.txt', 'r', encoding='utf-8') as f:
    old = [line.strip() for line in f.readlines()]

send_mail(from, to, title, message=f"hello {old}!")

Then I receive mail like this

hello ['あかさ', 'あいうえ\u3000お', 'いい']!

What I want to mail is this

hello ['あかさ', 'あいうえ　お', 'いい']!

How can I achieve this?

Body:
list's __str__ method uses repr on elements, therefore you're seeing \u3000 in your mail. Just convert list to string yourself:

In [28]: l = ['あかさ', 'あいうえ\u3000お', 'いい']

In [29]: print(', '.join(map(str, l)))
あかさ, あいうえ　お, いい

If you're sure all your list elements are strings, you can omit map(str, ...) and just use ', '.join(l)


问:
Remove duplicates and show recent dates
I have data on an excel worksheet in column A cells(23,i) and A celles(24,i) ordered like this
d like this

I want to show the data in a listbox without duplicates and showing only recent dates for each value (N IT) like this:

To show the list I created a button, and set this code :

```<code>Private Sub CommandButton1_Click()
  If Me.ListBox_Pers.ListIndex = -1 Then
       MsgBox ("Vous n'avez pas selectionner une personne")
  Else

      Acrtu_IT
      Load UF_Profil_Edit1
      UF_Profil_Edit1.Show
     'UF_Choix_Pers_Edit.ListBox_Pers.Clear

  End If
End Sub
</code>```

Where:
    Private Sub Actu_IT()

```<code>Personne = UF_Profil_Edit1.TextBox_Nom & " " & UF_Profil_Edit1.TextBox_Prenom.Value
Set ws = ActiveWorkbook.Worksheets(Personne)
UF_Profil_Edit1.ListBox_IT.Clear
Fin_Col_IT = ws.Cells(23, 256).End(xlToLeft).Column
UF_Profil_Edit1.ListBox_IT.ColumnCount = 4
UF_Profil_Edit1.ListBox_IT.ColumnWidths = "50;450;60;20"

Set Plage = ws.Rows(23)
Set Plage2 = ws_Liste_IT.Columns(2)
For i = 2 To Fin_Col_IT
   Val_Cherch = ws.Cells(23, i).Value
   Set Trouve = Plage.Cells.Find(what:=Val(Val_Cherch))
   If Trouve Is Nothing Then
   Else

      Set Trouve2 = Plage2.Cells.Find(what:=Val(Val_Cherch))
      If Trouve2 Is Nothing Then
      Else

         UF_Profil_Edit1.ListBox_IT.AddItem Trouve2.Offset(, 2)
         '---------------Nom de l'IT------------------------------
         UF_Profil_Edit1.ListBox_IT.List(UF_Profil_Edit1.ListBox_IT.ListCount - 1, 1) = Trouve2.Offset(, 1)
         '---------------Date de fin de la formation------------------------------
        UF_Profil_Edit1.ListBox_IT.List(UF_Profil_Edit1.ListBox_IT.ListCount - 1, 2) = ws.Cells(24, Trouve.Column)
 '---------------n° IT---------------------
        UF_Profil_Edit1.ListBox_IT.List(UF_Profil_Edit1.ListBox_IT.ListCount - 1, 3) = Trouve2
       '-----------°DE-------------------

     End If
  End If
Next i

'---sorting data in alphabetic order-----------------
    Dim a()
    a = UF_Profil_Edit1.ListBox_IT.List
If UBound(a, 1) > 1 Then
    Module2.Tri a(), LBound(a), UBound(a), 0
    UF_Profil_Edit1.ListBox_IT.List = a
Else
End If
</code>```

How can show only recent dates for each value in celle A(23,i), Thank you

答:
Please use the next function, to process your list box as (I understood) you need:

```<code>Private Function arrangeListBox(lst As MSForms.ListBox)
 Dim i As Long, refDate As Date, j As Long
Beginning:
 For i = 0 To lst.ListCount - 1
    refDate = DateValue(lst.list(i, 2))
    For j = 0 To lst.ListCount - 1
        If lst.list(i, 0) = lst.list(j, 0) And _
            DateValue(lst.list(j, 2)) < refDate Then
            lst.RemoveItem (j): GoTo Beginning
        End If
    Next j
 Next i
End Function
</code>```

The function must be called at the end of your code as:

```<code>arrangeListBox UF_Profil_Edit1.ListBox_IT
</code>```

Please, confirm that it does what you need. If you would like to load the list box only with the appropriate lines (respecting the rule of most recent date) you must provide both sheets involved in processing (with relevant data, to make them able to be understood)...

Title: Remove duplicates and show recent dates

Body:
I have data on an excel worksheet in column A cells(23,i) and A celles(24,i) ordered like this
d like this

I want to show the data in a listbox without duplicates and showing only recent dates for each value (N IT) like this:

To show the list I created a button, and set this code :

Private Sub CommandButton1_Click()
  If Me.ListBox_Pers.ListIndex = -1 Then
       MsgBox ("Vous n'avez pas selectionner une personne")
  Else

      Acrtu_IT
      Load UF_Profil_Edit1
      UF_Profil_Edit1.Show
     'UF_Choix_Pers_Edit.ListBox_Pers.Clear

  End If
End Sub

Where:
    Private Sub Actu_IT()

Personne = UF_Profil_Edit1.TextBox_Nom & " " & UF_Profil_Edit1.TextBox_Prenom.Value
Set ws = ActiveWorkbook.Worksheets(Personne)
UF_Profil_Edit1.ListBox_IT.Clear
Fin_Col_IT = ws.Cells(23, 256).End(xlToLeft).Column
UF_Profil_Edit1.ListBox_IT.ColumnCount = 4
UF_Profil_Edit1.ListBox_IT.ColumnWidths = "50;450;60;20"

Set Plage = ws.Rows(23)
Set Plage2 = ws_Liste_IT.Columns(2)
For i = 2 To Fin_Col_IT
   Val_Cherch = ws.Cells(23, i).Value
   Set Trouve = Plage.Cells.Find(what:=Val(Val_Cherch))
   If Trouve Is Nothing Then
   Else

      Set Trouve2 = Plage2.Cells.Find(what:=Val(Val_Cherch))
      If Trouve2 Is Nothing Then
      Else

         UF_Profil_Edit1.ListBox_IT.AddItem Trouve2.Offset(, 2)
         '---------------Nom de l'IT------------------------------
         UF_Profil_Edit1.ListBox_IT.List(UF_Profil_Edit1.ListBox_IT.ListCount - 1, 1) = Trouve2.Offset(, 1)
         '---------------Date de fin de la formation------------------------------
        UF_Profil_Edit1.ListBox_IT.List(UF_Profil_Edit1.ListBox_IT.ListCount - 1, 2) = ws.Cells(24, Trouve.Column)
 '---------------n° IT---------------------
        UF_Profil_Edit1.ListBox_IT.List(UF_Profil_Edit1.ListBox_IT.ListCount - 1, 3) = Trouve2
       '-----------°DE-------------------

     End If
  End If
Next i

'---sorting data in alphabetic order-----------------
    Dim a()
    a = UF_Profil_Edit1.ListBox_IT.List
If UBound(a, 1) > 1 Then
    Module2.Tri a(), LBound(a), UBound(a), 0
    UF_Profil_Edit1.ListBox_IT.List = a
Else
End If

How can show only recent dates for each value in celle A(23,i), Thank you

Body:
Please use the next function, to process your list box as (I understood) you need:

Private Function arrangeListBox(lst As MSForms.ListBox)
 Dim i As Long, refDate As Date, j As Long
Beginning:
 For i = 0 To lst.ListCount - 1
    refDate = DateValue(lst.list(i, 2))
    For j = 0 To lst.ListCount - 1
        If lst.list(i, 0) = lst.list(j, 0) And _
            DateValue(lst.list(j, 2)) < refDate Then
            lst.RemoveItem (j): GoTo Beginning
        End If
    Next j
 Next i
End Function

The function must be called at the end of your code as:

arrangeListBox UF_Profil_Edit1.ListBox_IT

Please, confirm that it does what you need. If you would like to load the list box only with the appropriate lines (respecting the rule of most recent date) you must provide both sheets involved in processing (with relevant data, to make them able to be understood)...


问:
How to check if coordinates valid or invalid without using google api?
Is there a way to check if map coordinates valid or invalid? I have a scenario that my latitude and longitude entered might got swapped so I have to check if its existing in globe coordinates. So far I need to use API just to check whether if its a valid coordinates or not.

On this example, this origin could not find in google map. I can't find any question similar similar to this.

```<code>const origin = {
        latitude:   106.892775, //parseFloat(res.pickuplat),
        longitude:  -6.163772 //parseFloat(res.pickuplong),
      };

try{
        const address = await Location.reverseGeocodeAsync(origin)
      }catch(err){
        console.log(err)
      }
</code>```

答:
I think the simplest way to verify our coordinate is to check

latitude must be a value between -90 and 90

and longitude must be between -180 and 180

Body:
Is there a way to check if map coordinates valid or invalid? I have a scenario that my latitude and longitude entered might got swapped so I have to check if its existing in globe coordinates. So far I need to use API just to check whether if its a valid coordinates or not.

On this example, this origin could not find in google map. I can't find any question similar similar to this.

const origin = {
        latitude:   106.892775, //parseFloat(res.pickuplat),
        longitude:  -6.163772 //parseFloat(res.pickuplong),
      };

try{
        const address = await Location.reverseGeocodeAsync(origin)
      }catch(err){
        console.log(err)
      }


问:
how to remove the line if it contain the "word"? in python
I have an input file looks like this

```<code>test.txt
CAT 396 NUM 59
X          Y
4.7642     28.4443
4.7643     28.3640
6.2216     29.0680
6.2217     29.2841
6.4080     28.6427
6.6484     28.6484

CAT 397 NUM 592
X          Y
7.0442     23.8320
7.0994     25.9161
7.0995     25.1801
</code>```

I only need the X and Y coordinate information.

How would I be able to only get the coordinates?

答:
You can use readlines()[2:] to skip first two lines and then parse numbers. For example: like this

lines = open('test.txt').readlines()[2:]
coords = []
for line in lines:
    try:
        coords.append(list(map(float, line.split())), lines))
    except ValueError:
        print(f'ValueError in line: {line}')
print(coords)
```

<p>It returns:</p>

```[[7.0442, 23.832], [7.0994, 25.9161], [7.0995, 25.1801]]
```

Body:
I have an input file looks like this

test.txt
CAT 396 NUM 59
X          Y
4.7642     28.4443
4.7643     28.3640
6.2216     29.0680
6.2217     29.2841
6.4080     28.6427
6.6484     28.6484

CAT 397 NUM 592
X          Y
7.0442     23.8320
7.0994     25.9161
7.0995     25.1801

I only need the X and Y coordinate information.

How would I be able to only get the coordinates?

Body:
You can use readlines()[2:] to skip first two lines and then parse numbers. For example: like this

lines = open('test.txt').readlines()[2:]
coords = []
for line in lines:
    try:
        coords.append(list(map(float, line.split())), lines))
    except ValueError:
        print(f'ValueError in line: {line}')
print(coords)

It returns:

[[7.0442, 23.832], [7.0994, 25.9161], [7.0995, 25.1801]]


问:
How can I alternate "visible" rows in an html table using jQuery
I have this code that does alternating rows for a html in jQuery:

```<code>function AlternateRowColors() {

    $("table.altRow1 tr").filter(function() {
    return true;
    }).filter(':even').addClass('alt');

    $("tr.alt td[rowspan]").each(function() {
    $(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass('alt');
    });

    $('ins').css("background-color", "#cfc")
}
</code>```

This works great (feel free to add suggestions if anything is inefficient above).

The issue that I have now is that I have code that hides a bunch of rows (details on why are not really relevant for this question), the main point is that I want to have a function that can do alternative row colors to current visible rows.

I am hiding rows by simply adding a class to certain rows and them calling .hide() on that class.

Is there any suggestion to get alternative row colors (like the above code) but have it work on the visible rows so no matter what is hidden, the table always looks correct in terms of alt row coloring.

答:
i wound up using this which seemed to work:

```<code>function UpdateTable() {
$('table.altRow1 tr:visible').removeClass('odd').filter(':odd').addClass('odd');
</code>```

with this css:

```<code>.altRow1 tr {
     background-color: #FFFFFF;
 }
 .altRow1 tr.odd {
     background-color: #DEDEDE;
 }
</code>```

Body:
I have this code that does alternating rows for a html in jQuery:

function AlternateRowColors() {

    $("table.altRow1 tr").filter(function() {
    return true;
    }).filter(':even').addClass('alt');

    $("tr.alt td[rowspan]").each(function() {
    $(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass('alt');
    });

    $('ins').css("background-color", "#cfc")
}

This works great (feel free to add suggestions if anything is inefficient above).

The issue that I have now is that I have code that hides a bunch of rows (details on why are not really relevant for this question), the main point is that I want to have a function that can do alternative row colors to current visible rows.

I am hiding rows by simply adding a class to certain rows and them calling .hide() on that class.

Is there any suggestion to get alternative row colors (like the above code) but have it work on the visible rows so no matter what is hidden, the table always looks correct in terms of alt row coloring.

Body:
i wound up using this which seemed to work:

function UpdateTable() {
$('table.altRow1 tr:visible').removeClass('odd').filter(':odd').addClass('odd');

with this css:

.altRow1 tr {
     background-color: #FFFFFF;
 }
 .altRow1 tr.odd {
     background-color: #DEDEDE;
 }


问:
Prime numbers upto 10^8 using sieve
Why this code is working only number less than 10^4? i need to find all the  prime numbers less than 10^8 but this is showing arrayindexoutofbound exception? why? i know we can only create array till size10^8(correct me if i am wrong)  but this is not even working for 10^5.  </p>

```<code> class Prime
    {
        public static void main (String[] args) throws java.lang.Exception
        {
            boolean[] prime = new boolean[100000000];
            prime[2]=true;
            int i;
            for(i=3; i<100000000; i+=2)
                prime[i]=true;
            for(i=3; i<100000000; i++)
            {
                if(prime[i]==true)
                    for(int j=i*i; j<100000000; j=j+i)
                        prime[j]=false;
            }
            for(i=1; i<100000000; i++)
            {
                if(prime[i]==true)
                System.out.println(i);
            }
        }
    }
</code>```

答:
```<code>for(int j=i*i; j<10000; j=j+i)
</code>```

if i is 10^5, then the j would be 10^10, which would cause overflow for int type (max value of int type is 2^31 - 1 = 2147483647)

Title: Prime numbers upto 10^8 using sieve

Body:
Why this code is working only number less than 10^4? i need to find all the  prime numbers less than 10^8 but this is showing arrayindexoutofbound exception? why? i know we can only create array till size10^8(correct me if i am wrong)  but this is not even working for 10^5.

 class Prime
    {
        public static void main (String[] args) throws java.lang.Exception
        {
            boolean[] prime = new boolean[100000000];
            prime[2]=true;
            int i;
            for(i=3; i<100000000; i+=2)
                prime[i]=true;
            for(i=3; i<100000000; i++)
            {
                if(prime[i]==true)
                    for(int j=i*i; j<100000000; j=j+i)
                        prime[j]=false;
            }
            for(i=1; i<100000000; i++)
            {
                if(prime[i]==true)
                System.out.println(i);
            }
        }
    }

Body:
for(int j=i*i; j<10000; j=j+i)

if i is 10^5, then the j would be 10^10, which would cause overflow for int type (max value of int type is 2^31 - 1 = 2147483647)


问:
Yii2 multiple instances of the same model with javascript
I am trying to use multiple instances of the same model using javascript append. However, I do not know how to do that. Therefore, I create the following code.

javascript

```<code>var div_input = $('#input');
div_input.append('<input type="hidden" name="'+c+'_round" value="'+c+'" />');
</code>```

variable "c" is a increasing running number. for example, first time i append the name will be "1_round". and second time will be "2_round" and so on.

Controller

```<code> $loop = true;
    $i = 0;
    do{
        $i++;
        if (!empty($_POST[$i . "_round"]))
        {
            $round = $_POST[$i . "_round"];
            $model->model_round= $round;
            $model->save();
        }else{
            $loop = false;
        }
    }while($loop);
</code>```

The problem here is it will always only save the last loop of data and not every loop of data. Please help me with this. New to Yii2. Thanks!

答:
Why don't you use input name as array

```<code><input name="round[]">
</code>```

Then loop it

```<code>$round = $_POST['round'];
foreach( $round as $key => $n ) {
// code here
}
</code>```

Body:
I am trying to use multiple instances of the same model using javascript append. However, I do not know how to do that. Therefore, I create the following code.

javascript

var div_input = $('#input');
div_input.append('<input type="hidden" name="'+c+'_round" value="'+c+'" />');

variable "c" is a increasing running number. for example, first time i append the name will be "1_round". and second time will be "2_round" and so on.

Controller

 $loop = true;
    $i = 0;
    do{
        $i++;
        if (!empty($_POST[$i . "_round"]))
        {
            $round = $_POST[$i . "_round"];
            $model->model_round= $round;
            $model->save();
        }else{
            $loop = false;
        }
    }while($loop);

The problem here is it will always only save the last loop of data and not every loop of data. Please help me with this. New to Yii2. Thanks!

Body:
Why don't you use input name as array

<input name="round[]">

Then loop it

$round = $_POST['round'];
foreach( $round as $key => $n ) {
// code here
}


问:
How to update Auto generated time stamp in Spring boot
I am making use of Auditing with Spring Data JPA to automatically update the created by time stamp. I have a requirement, where i have to migrate some data for which the created by date should be updated with the value am setting through the application. I have debugged the code, the values are setting properly. But while calling

fooRepository.save(fooEntity)

The created by is getting overridden by the auto generated time stamp.
Is it possible to override the value?

I am also having a @Transactional annotation in Service level. While debugging i can see the date is getting replaced on the Entity returned by the save repository method.

答:
Create new enity without @CreatedDate and new repository for that new entity.

Only use that new repository when you need to edit CreatedDate or LastModifiedDate

This seems to be a bad solution but is the only solution I can think of now.

I am looking for better solution to this problem


问:
Crop and extract text from PDF
I have cropped a PDF using the following command.

```<code>gswin32c.exe ^
-o cropped.pdf ^
-sDEVICE=pdfwrite ^
-c "[/CropBox [64 418 348 803] /PAGE pdfmark" ^
-f original.pdf
</code>```

The PDF is getting cropped. I used the following command to extract the text from the cropped PDF.

```<code>gswin32c.exe ^
-q ^
-sFONTPATH=c:/windows/fonts ^
-dNODISPLAY ^
-dSAFER ^
-dDELAYBIND ^
-dWRITESYSTEMDICT ^
-dSIMPLE ^
-f ps2ascii.ps ^
-dFirstPage=1 ^
-dLastPage=1 ^
cropped.pdf ^
-> c:\output.txt ^
-dQUIET
</code>```

The output contains the text of the original PDF and not the cropped PDF.

Can someone help to extract the text only from the cropped PDF.

Thanks
Nazeer

答:
You may be more lucky, if you try a different means to convert the cropped.pdf to text:

Open it in Acrobat/Adobe Reader.

Click 'File --> Save as Text...'

Title: Crop and extract text from PDF

Body:
I have cropped a PDF using the following command.

gswin32c.exe ^
-o cropped.pdf ^
-sDEVICE=pdfwrite ^
-c "[/CropBox [64 418 348 803] /PAGE pdfmark" ^
-f original.pdf

The PDF is getting cropped. I used the following command to extract the text from the cropped PDF.

gswin32c.exe ^
-q ^
-sFONTPATH=c:/windows/fonts ^
-dNODISPLAY ^
-dSAFER ^
-dDELAYBIND ^
-dWRITESYSTEMDICT ^
-dSIMPLE ^
-f ps2ascii.ps ^
-dFirstPage=1 ^
-dLastPage=1 ^
cropped.pdf ^
-> c:\output.txt ^
-dQUIET

The output contains the text of the original PDF and not the cropped PDF.

Can someone help to extract the text only from the cropped PDF.

Thanks
Nazeer


问:
Beautiful Soup how to decode html json data in
```

Can anyone identify this encoding format? How can I decode it with Python / Beautiful Soup?

答:
In line with my comment: The "ng- in the script id already gives it away: the encoding is Angular's custom encoding of HTML. Since you are after the content of the entire article, a simple search and replace won't do - you'll need to find a way to get Angular to decode it for you.

The easiest way is probably to get Python to load a JavaScript-capable engine and have it render out the HTML you see in the browser and then use Python to access the resulting document, like using Selenium or PyV8. Those are heavy solutions though, don't use them if you need to run this script frequently or using few resources.

The code below uses Selenium, prepare your virtual environment by:

installing selenium pip install selenium

installing the appropriate browser driver, in this case ChromeDriver, from here: https://sites.google.com/a/chromium.org/chromedriver/home
(I just drop the executable in my script folder, on Windows)

Run this:

```<code>from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://www.londonstockexchange.com/news-article/RGD/year-end-trading-and-covid-19-update/14495760")
elem = driver.find_element_by_class_name('news-article-content-body')
print(elem.text)
</code>```

You can get this to work with other supported browsers as well, of course, as long as you get the driver as well. And it works similarly on other OSes.

If you do need to run this frequently, there's ways to get Selenium to run on a server to more quickly create the session and render the page repeatedly, but that's well beyond a single StackOverflow answer.

Title: Beautiful Soup how to decode html json data in <script> object

Body:
I collect text from a website which publishes short news updates. Recently the site's front-end was upgraded and now uses Angular. The historical documents load within a  element within a new Angular "news" page.

The data within this script element is html stored as JSON. It is encoded in a format that I am unfamiliar with. I have not been able to decode it. However, a Chrome Browser interprets the elements within the  element.

Extracts from the  element storing each old document is shown below:

Can anyone identify this encoding format? How can I decode it with Python / Beautiful Soup?

Body:
In line with my comment: The "ng- in the script id already gives it away: the encoding is Angular's custom encoding of HTML. Since you are after the content of the entire article, a simple search and replace won't do - you'll need to find a way to get Angular to decode it for you.

The easiest way is probably to get Python to load a JavaScript-capable engine and have it render out the HTML you see in the browser and then use Python to access the resulting document, like using Selenium or PyV8. Those are heavy solutions though, don't use them if you need to run this script frequently or using few resources.

The code below uses Selenium, prepare your virtual environment by:

installing selenium pip install selenium

installing the appropriate browser driver, in this case ChromeDriver, from here: https://sites.google.com/a/chromium.org/chromedriver/home
(I just drop the executable in my script folder, on Windows)

Run this:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://www.londonstockexchange.com/news-article/RGD/year-end-trading-and-covid-19-update/14495760")
elem = driver.find_element_by_class_name('news-article-content-body')
print(elem.text)

You can get this to work with other supported browsers as well, of course, as long as you get the driver as well. And it works similarly on other OSes.

If you do need to run this frequently, there's ways to get Selenium to run on a server to more quickly create the session and render the page repeatedly, but that's well beyond a single StackOverflow answer.


问:
Replace duplicate spaces with a single space in T-SQL
I need to ensure that a given field does not have more than one space (I am not concerned about all white space, just space) between characters.

So

```<code>'single    spaces   only'
</code>```

needs to be turned into

```<code>'single spaces only'
</code>```

The below will not work

```<code>select replace('single    spaces   only','  ',' ')
</code>```

as it would result in

```<code>'single  spaces  only'
</code>```

I would really prefer to stick with native T-SQL rather than a CLR based solution.

Thoughts?

答:
Please Find below code

```<code>select trim(string_agg(value,' ')) from STRING_SPLIT('  single    spaces   only  ',' ')
where value<>' '
</code>```

This worked for me..
Hope this helps...

ContentLicense: CC BY-SA 2.5

Body:
I need to ensure that a given field does not have more than one space (I am not concerned about all white space, just space) between characters.

So

'single    spaces   only'

needs to be turned into

'single spaces only'

The below will not work

select replace('single    spaces   only','  ',' ')

as it would result in

'single  spaces  only'

I would really prefer to stick with native T-SQL rather than a CLR based solution.

Thoughts?

Body:
Please Find below code

select trim(string_agg(value,' ')) from STRING_SPLIT('  single    spaces   only  ',' ')
where value<>' '

This worked for me..
Hope this helps...


问:
Unordered list items wont align in the center while using flexbox/flex direction column in a sidebar, also is there a better way to achieve this?
I am trying to align an image and a text under it in the center in an unordered list using display:flexbox, in a sidebar.
however the image and the text are always displayed to the very left of the sidebar.i tried assign the flexbox to the "li" as well but that didn't change anything.
also is there a better way to achieve this than using flexbox?

* {
  margin: 0;
  padding: 0;
  list-style: none;
  text-decoration: none;
  box-sizing: border-box;
}

.grid {
  width: 100vw;
  height: 100vh;
  display: grid;
  grid-template-columns: 5% 95%;
  grid-template-rows: 5% 91% 4%;
  grid-template-areas: "sidebar header" "sidebar content" "footer footer";
}

.header {
  grid-area: header;
  background-color: #4792e6;
}

.sidebar {
  grid-area: sidebar;
  background-color: #4792e6;
}

.content {
  grid-area: content;
  background-color: #f7f7f7;
  display: grid;
  width: 100%;
  height: 100%;
}

.footer {
  grid-area: footer;
  background-color: #4792e6;
}

.img-circle {
  width: 70%;
  background: #fff;
  margin-left: 15%;
  z-index: 1000;
  position: inherit;
  margin-top: 20px;
  border: 1px solid rgba(52, 73, 94, .44);
  padding: 4px;
  border-radius: 50%;
}

.maintenance {
  background-color: black;
  display: grid;
  grid-template-rows: 15% 85%;
  grid-template-areas: "maintenance-nav" "maintenance-info"
}

.maintenance-nav {
  grid-area: maintenance-nav;
  background-color: #ededed;
  display: flex;
  justify-content: center;
  align-items: center;
}

.maintenance-info {
  grid-area: maintenance-info;
  background-color: blue;
}

.components {
  display: grid;
  grid-template-columns: 30% 70%;
  grid-template-rows: 10% 90%;
  grid-template-areas: "components-tree components-nav" "components-tree components-data";
  width: 100%;
  height: 100%;
}

.components-tree {
  grid-area: components-tree;
  background-color: white;
}

.components-nav {
  grid-area: components-nav;
  display: flex;
  justify-content: space-around;
  align-items: center;
  background-color: #ededed;
}

.components-data {
  grid-area: components-data;
  background-color: yellow;
}

.maintenance-nav>div {
  display: inline-block;
  height: 60px;
  background-color: white;
  text-align: center;
  margin: 30px;
  border-radius: 10px;
  width: 13%;
  font-family: "Helvetica Neue", Roboto, Arial, "Droid Sans", sans-serif;
}

.components-nav-links li {
  list-style: none;
  display: inline-block;
  padding: 0px 25px;
  margin-right: 2rem;
}

.components-nav-links li a {
  color: black;
  transition: all 0.3s ease 0s;
}

.components-nav-links li a:hover {
  padding: 13px;
  border: 2px solid #4792e6;
  border-radius: 10px;
  color: #419C99;
}

.sidebar-navbar {
  width: 100%;
  height: 100%;
}

.sidebar-navlist {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.sidebar-navitem img {
  width: 50%;
}

.sidebar-navitem {
  width: 100%;
  height: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/custom.css') }}">
  <title></title>
</head>

<body>
  <!--Layout grid -->
  <div class="grid">
    <!--header grid-->
    <div class="header">Header</div>
    <!--sidebar grid-->
    <div class="sidebar">
      <nav class="sidebar-navbar">
        <ul class="sidebar-navlist">
          <li class="sidebar-navitem">
            <img src="{{ url_for('static', filename='images/maintenance.svg') }}">
            <span>Main.</span>
          </li>
          <li class="sidebar-navitem">
            <img src="{{ url_for('static', filename='images/maintenance.svg') }}">
            <span>Purchase</span>
          </li>
        </ul>
      </nav>
    </div>

    <!--contenant grid-->
    <div class="content">
      {% block content %}{% endblock %}
    </div>
    <!--footer grid-->
    <div class="footer">Footer</div>
  </div>
</body>

</html></code>```

答:
I have a more good solution for the problem:

```<code>.sidebar-navitem {
width: 100%;
height: 50px;
display: flex;
flex-direction: column;
align-items: center;
}
</code>```

align-items:center was not working because it is required to set this property on a li not on ul.

If you apply this property to ul, the lis inside that are centered not the items inside li.

Body:
I am trying to align an image and a text under it in the center in an unordered list using display:flexbox, in a sidebar.
however the image and the text are always displayed to the very left of the sidebar.i tried assign the flexbox to the "li" as well but that didn't change anything.
also is there a better way to achieve this than using flexbox?

* {
  margin: 0;
  padding: 0;
  list-style: none;
  text-decoration: none;
  box-sizing: border-box;
}

.grid {
  width: 100vw;
  height: 100vh;
  display: grid;
  grid-template-columns: 5% 95%;
  grid-template-rows: 5% 91% 4%;
  grid-template-areas: "sidebar header" "sidebar content" "footer footer";
}

.header {
  grid-area: header;
  background-color: #4792e6;
}

.sidebar {
  grid-area: sidebar;
  background-color: #4792e6;
}

.content {
  grid-area: content;
  background-color: #f7f7f7;
  display: grid;
  width: 100%;
  height: 100%;
}

.footer {
  grid-area: footer;
  background-color: #4792e6;
}

.img-circle {
  width: 70%;
  background: #fff;
  margin-left: 15%;
  z-index: 1000;
  position: inherit;
  margin-top: 20px;
  border: 1px solid rgba(52, 73, 94, .44);
  padding: 4px;
  border-radius: 50%;
}

.maintenance {
  background-color: black;
  display: grid;
  grid-template-rows: 15% 85%;
  grid-template-areas: "maintenance-nav" "maintenance-info"
}

.maintenance-nav {
  grid-area: maintenance-nav;
  background-color: #ededed;
  display: flex;
  justify-content: center;
  align-items: center;
}

.maintenance-info {
  grid-area: maintenance-info;
  background-color: blue;
}

.components {
  display: grid;
  grid-template-columns: 30% 70%;
  grid-template-rows: 10% 90%;
  grid-template-areas: "components-tree components-nav" "components-tree components-data";
  width: 100%;
  height: 100%;
}

.components-tree {
  grid-area: components-tree;
  background-color: white;
}

.components-nav {
  grid-area: components-nav;
  display: flex;
  justify-content: space-around;
  align-items: center;
  background-color: #ededed;
}

.components-data {
  grid-area: components-data;
  background-color: yellow;
}

.maintenance-nav>div {
  display: inline-block;
  height: 60px;
  background-color: white;
  text-align: center;
  margin: 30px;
  border-radius: 10px;
  width: 13%;
  font-family: "Helvetica Neue", Roboto, Arial, "Droid Sans", sans-serif;
}

.components-nav-links li {
  list-style: none;
  display: inline-block;
  padding: 0px 25px;
  margin-right: 2rem;
}

.components-nav-links li a {
  color: black;
  transition: all 0.3s ease 0s;
}

.components-nav-links li a:hover {
  padding: 13px;
  border: 2px solid #4792e6;
  border-radius: 10px;
  color: #419C99;
}

.sidebar-navbar {
  width: 100%;
  height: 100%;
}

.sidebar-navlist {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.sidebar-navitem img {
  width: 50%;
}

.sidebar-navitem {
  width: 100%;
  height: 50px;
}

<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/custom.css') }}">
  <title></title>

Header

            Main.

            Purchase

      {% block content %}{% endblock %}

Footer

Body:
I have a more good solution for the problem:

.sidebar-navitem {
width: 100%;
height: 50px;
display: flex;
flex-direction: column;
align-items: center;
}

align-items:center was not working because it is required to set this property on a li not on ul.

If you apply this property to ul, the lis inside that are centered not the items inside li.


问:
Store a value in redis store using Nestjs
I have a simple nestjs application, where I have set up a CacheModule using Redis store as follows:

import * as redisStore from 'cache-manager-redis-store';

CacheModule.register({
      store: redisStore,
      host: 'redis',
      port: 6379,
    }),
```

I would like to use it to store a single value, however, I do not want to do it the built-in way by attaching an interceptor to a controller method, but instead I want to control it manually and be able to set and retrieve the value in the code.

How would I go about doing that and would I even use cache manager for that?

答:
Building on Ahmad's comment above, I used the following to enable redis in my nestjs application:

Install and setup nestjs-redis https://www.npmjs.com/package/nestjs-redis per docs.

See the docs here on how to write and read values in a Redis store:
https://github.com/NodeRedis/node-redis

Body:
I have a simple nestjs application, where I have set up a CacheModule using Redis store as follows:

import * as redisStore from 'cache-manager-redis-store';

CacheModule.register({
      store: redisStore,
      host: 'redis',
      port: 6379,
    }),

I would like to use it to store a single value, however, I do not want to do it the built-in way by attaching an interceptor to a controller method, but instead I want to control it manually and be able to set and retrieve the value in the code.

How would I go about doing that and would I even use cache manager for that?


问:
Turning PHP String variable into PHP Script
I would like to learn how can I turn PHP String into a PHP script.

e.g.

```<code>$var = "echo 'Hello';";
</code>```

and execute as

```<code>echo 'Hello';
</code>```

If you need more detail or similar post exist please let me know.

答: Just use eval function see this link https://www.w3schools.com/php/func_misc_eval.asp</p>

Body:
I would like to learn how can I turn PHP String into a PHP script.

e.g.

$var = "echo 'Hello';";

and execute as

echo 'Hello';

If you need more detail or similar post exist please let me know.


答:
You can do it by the PHP function eval. https://www.php.net/manual/en/function.eval.php

e.g:

```<code>$var = "echo 'Hello';";
eval($var);

// output:
// Hello
</code>```

But take care it is an big security issue (it is not save and not good).

Title: Turning PHP String variable into PHP Script

Body:
You can do it by the PHP function eval. https://www.php.net/manual/en/function.eval.php

e.g:

$var = "echo 'Hello';";
eval($var);

// output:
// Hello

But take care it is an big security issue (it is not save and not good).


问:
How to send a Get request in iOS?
I am making a library to get response from a particular URL with specified data and method type. For this, I am making a request with url. But when I set its method type, it shows an exception of unrecognized selector send in [NSURLRequest setHTTPMethod:]
I am setting it as

```<code>[requestObject setHTTPMethod:@"GET"];
</code>```

Tell me what could be the problem. Also provide me the code if you have.

答:
```<code>NSString *getString = [NSString stringWithFormat:@"parameter=%@",yourvalue];
NSData *getData = [getString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];<br>
NSString *getLength = [NSString stringWithFormat:@"%d", [getData length]];<br>
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];<br>
[request setURL:[NSURL URLWithString:@"https:yoururl"]];<br>
[request setHTTPMethod:@"GET"];<br>
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];<br>
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];<br>
[request setHTTPBody:getData];<br>
self.urlConnection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];<br>
NSAssert(self.urlConnection != nil, @"Failure to create URL connection.");<br>
// show in the status bar that network activity is starting
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
```</code></p>

Title: How to send a Get request in iOS?

Body:
I am making a library to get response from a particular URL with specified data and method type. For this, I am making a request with url. But when I set its method type, it shows an exception of unrecognized selector send in [NSURLRequest setHTTPMethod:]
I am setting it as

[requestObject setHTTPMethod:@"GET"];

Tell me what could be the problem. Also provide me the code if you have.

Body:
NSString *getString = [NSString stringWithFormat:@"parameter=%@",yourvalue];
NSData *getData = [getString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *getLength = [NSString stringWithFormat:@"%d", [getData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];

[request setURL:[NSURL URLWithString:@"https:yoururl"]];

[request setHTTPMethod:@"GET"];

[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

[request setHTTPBody:getData];

self.urlConnection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];

NSAssert(self.urlConnection != nil, @"Failure to create URL connection.");

// show in the status bar that network activity is starting
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;


问:
How to print next letters until Z and continue to A?
This code prints the next letters of what I input.
For example, I input "v", it will show vwxyz, but I want it to print the others too, like vwxyzabc.....

```<code>int main()
{
   char a;
   int flag = 0;
   scanf("%c", &a);

   while (a <= 'z')
   {
      printf("%c", a);
      a++;
   }

   printf("\n");
   return 0;
}

</code>```

I am new to c++, can someone help me?

答:
If the incremented character is not an alphabet, deduct 26 to go back to the starting and do the loop until you see the entered character.

```<code>#include <cctype> // std::isalpha

char curr = a;
do
{
   printf("%c", curr);
   ++curr;
   if (!std::isalpha(static_cast<unsigned char>(curr)))
      curr -= 26;

} while (curr != a);
</code>```

(See live demo)

Body:
This code prints the next letters of what I input.
For example, I input "v", it will show vwxyz, but I want it to print the others too, like vwxyzabc.....

int main()
{
   char a;
   int flag = 0;
   scanf("%c", &a);

   while (a <= 'z')
   {
      printf("%c", a);
      a++;
   }

   printf("\n");
   return 0;
}

I am new to c++, can someone help me?

Body:
If the incremented character is not an alphabet, deduct 26 to go back to the starting and do the loop until you see the entered character.

#include <cctype> // std::isalpha

char curr = a;
do
{
   printf("%c", curr);
   ++curr;
   if (!std::isalpha(static_cast<unsigned char>(curr)))
      curr -= 26;

} while (curr != a);

(See live demo)


问:
How to determine how many times '0' to '9' have been used in a specific range instantly
I want to count how many times '0' to '9' have been used in a specific range

e.g. 112 has two '1' and one '2'

Thanks for your advices, I changed my code now.

But it is not efficient as I want.

```<code>num = int(input('n : '))
start_time = time.time()
num_arr = [0] * 10
progress_arr = ['%d' % (num * (i / 100)) for i in range(1, 101)]

for i in range(1, num + 1):
    if str(i) in progress_arr:
        print(str(progress_arr.index(str(i)) + 1) + '%')
    for digit in str(i):
        num_arr[int(digit)] += 1

print('Time : %.2f' % (time.time() - start_time))
print(num_arr)
</code>```

When I input 1000 as n, my program will print this arr instantly

[192, 301, 300, 300, 300, 300, 300, 300, 300, 300]

It means for 1 to 1000,
'0' has been used 192 times and '1' has been used 301 times and ···

But when I input 2,000,000,000 as n, my program will print the result after
11 minutes(Using pypy3, Ryzen 2600).

So I want to change my code as efficient to get the result of a very large number instantly.

And in my previous question, I mentioned the time complexity of O(N), which confused you because of my poor understanding of algorithm and time complexity. So I deleted it.

What I want to know is just the efficient algorithm.

I'm trying to find a specific rule by analyzing the difference in the results of increment, but it's not easy.

答:
Finally I did it!

```<code>def main():
    n = int(input('n : '))
    num_arr = [0] * 10
    w = 1

    for step in range(len(str(n))):
        remaining = 9 - int(str(n)[-1:])

        for i in range(len(num_arr)):
            num_arr[i] += (n // 10 + 1) * w

        for i in range(10 - remaining, 10):
            num_arr[i] -= w
        num_arr[0] -= w

        for number in str(n)[:-1]:
            num_arr[int(number)] -= remaining * w

        n //= 10
        w *= 10

    print(num_arr)

if __name__ == '__main__':
    main()
</code>```

Now I cant get the result of 2 billion faster than 1 second! LOL

Body:
I want to count how many times '0' to '9' have been used in a specific range

e.g. 112 has two '1' and one '2'

Thanks for your advices, I changed my code now.

But it is not efficient as I want.

num = int(input('n : '))
start_time = time.time()
num_arr = [0] * 10
progress_arr = ['%d' % (num * (i / 100)) for i in range(1, 101)]

for i in range(1, num + 1):
    if str(i) in progress_arr:
        print(str(progress_arr.index(str(i)) + 1) + '%')
    for digit in str(i):
        num_arr[int(digit)] += 1

print('Time : %.2f' % (time.time() - start_time))
print(num_arr)

When I input 1000 as n, my program will print this arr instantly

[192, 301, 300, 300, 300, 300, 300, 300, 300, 300]

It means for 1 to 1000,
'0' has been used 192 times and '1' has been used 301 times and ···

But when I input 2,000,000,000 as n, my program will print the result after
11 minutes(Using pypy3, Ryzen 2600).

So I want to change my code as efficient to get the result of a very large number instantly.

And in my previous question, I mentioned the time complexity of O(N), which confused you because of my poor understanding of algorithm and time complexity. So I deleted it.

What I want to know is just the efficient algorithm.

I'm trying to find a specific rule by analyzing the difference in the results of increment, but it's not easy.

Body:
Finally I did it!

def main():
    n = int(input('n : '))
    num_arr = [0] * 10
    w = 1

    for step in range(len(str(n))):
        remaining = 9 - int(str(n)[-1:])

        for i in range(len(num_arr)):
            num_arr[i] += (n // 10 + 1) * w

        for i in range(10 - remaining, 10):
            num_arr[i] -= w
        num_arr[0] -= w

        for number in str(n)[:-1]:
            num_arr[int(number)] -= remaining * w

        n //= 10
        w *= 10

    print(num_arr)

if __name__ == '__main__':
    main()

Now I cant get the result of 2 billion faster than 1 second! LOL


问:
How to do "static overloaded const" in C#?
I'm creating a game in C#. Each level is made up of several tiles. Each tile is of a certain type e.g. grass floor, wooden wall, etc.

Ideally I would like to have one base class "Tile" and inherit from it to create classes for each type of tile. I would like to have the properties of the tile some kind of static/const/etc member of the sub-class since each type of tile is only ever going to have the same properties. I.e. I don't want 100 Tiles have a property which all have the same value, that seems rather inefficient.

The problem is you can't do that in C#. Are there any ways to achieve what I want?

My alternative idea was to separate it all into to trees, one with only the class "Tile" which represents an instance and another "TileType" from which I instanciate one object for each type and maybe access them through some kind of "TileTypeCollection". This feels strange though and I would rather do it in the first way.

Are there any general guidelines when dealing with a situation like this?

答:
You are looking for the FlyWeight design pattern:

http://en.wikipedia.org/wiki/Flyweight_pattern

Flyweight is a software design
  pattern. A flyweight is an object that
  minimizes memory use by sharing as
  much data as possible with other
  similar objects; it is a way to use
  objects in large numbers when a simple
  repeated representation would use an
  unacceptable amount of memory.

You have some C# samples here: http://www.dofactory.com/Patterns/PatternFlyweight.aspx#_self2


问:
R function for calculating a 'cumulative difference'
I have a vector like

```<code>v <- c(76, 31, 33, 7)
</code>```

and need to calculate its 'cumulative difference' resulting in

```<code>cumdiff <- c(45, 12, 5)
</code>```

which is 76 - 31 = 45 and 45 - 33 = 12 and 12 - 7 = 5.

Is there an R function like cumsum or do I need to use a loop?

Thank you very much for your help on this.

答:
An option using Reduce:

```<code>Reduce(`-`, v, accumulate=TRUE)[-1L]
#[1] 45 12  5
</code>```

Or using negative of cumsum

```<code>v[1L] - cumsum(v[-1L])
</code>```

Body:
I have a vector like

v <- c(76, 31, 33, 7)

and need to calculate its 'cumulative difference' resulting in

cumdiff <- c(45, 12, 5)

which is 76 - 31 = 45 and 45 - 33 = 12 and 12 - 7 = 5.

Is there an R function like cumsum or do I need to use a loop?

Thank you very much for your help on this.

Body:
An option using Reduce:

Reduce(`-`, v, accumulate=TRUE)[-1L]
#[1] 45 12  5

Or using negative of cumsum

v[1L] - cumsum(v[-1L])


问:
WPF Data Binding to Bool Property
On MainWindow.xaml

```<code><Label Content="{Binding ActEna,Mode=OneWay}"/>
<Button Content="Toggle" Click="Button_Click"/>
</code>```

On MainWindow.xaml.cs

```<code>public partial class MainWindow : Window
    {
        public bool ActEna { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
            ActEna=true;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ActEna = !ActEna;
        }
    }
</code>```

When application was launched Label value is True.

When the user click's on Toggle button the label was not updating.

How to fix this problem ?

答:
You would need to implement INotifyPropertyChanged for the data binding to work correctly. Have a look here, it explains it quite well https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifypropertychanged?view=netcore-3.1 .

You would have something similar to this :

```<code>public partial class MainWindow : Window, INotifyPropertyChanged

private bool _actEna;
public bool ActEna
{
   get
       {
        return _actEna;
       }
   set
       {
        _actEna = value;
        RaisePropertyChanged();
       }

private void Button_Click(object sender, RoutedEventArgs e)
{
   ActEna = !ActEna;

}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged([CallerMemberName] String propertyName = "")
{
   PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

</code>```

Title: WPF Data Binding to Bool Property

Body:
On MainWindow.xaml

<Button Content="Toggle" Click="Button_Click"/>

On MainWindow.xaml.cs

public partial class MainWindow : Window
    {
        public bool ActEna { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
            ActEna=true;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ActEna = !ActEna;
        }
    }

When application was launched Label value is True.

When the user click's on Toggle button the label was not updating.

How to fix this problem ?

Body:
You would need to implement INotifyPropertyChanged for the data binding to work correctly. Have a look here, it explains it quite well https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifypropertychanged?view=netcore-3.1 .

You would have something similar to this :

public partial class MainWindow : Window, INotifyPropertyChanged

private bool _actEna;
public bool ActEna
{
   get
       {
        return _actEna;
       }
   set
       {
        _actEna = value;
        RaisePropertyChanged();
       }

private void Button_Click(object sender, RoutedEventArgs e)
{
   ActEna = !ActEna;

}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged([CallerMemberName] String propertyName = "")
{
   PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}


问:
SwiftUI ZStack alignment bug
Here is a simple code that produces a strange top alignment and shrunk text of the second element inside ZStack.

BUT if you change the second text a bit (replace text2 by text2Alt1 or by text2Alt2) making it longer or shorter everything becomes correct.

What is the reason for this behavior?

struct VCardView: View {
    let text: String
    let color: UIColor

    var body: some View {
        VStack {
            Rectangle()
                .fill(Color(self.color))
                .frame(idealWidth: 800, idealHeight: 500)
                .aspectRatio(contentMode: .fit)

            Text(self.text)
        }
    }
}

struct ContentView: View {
    var body: some View {
        ZStack(alignment: .topLeading) {
            VCardView(text: text1, color: .blue)
                .frame(width: 180, height: nil)
                .alignmentGuide(.leading) { _ in 180 }
                .alignmentGuide(.top) { _ in 0 }

            //Replace text2 by text2Alt1 or text2Alt2 here:
            VCardView(text: text2, color: .green)
                .frame(width: 180, height: nil)
                .alignmentGuide(.leading) { _ in 0 }
                .alignmentGuide(.top) { _ in 0 }
        }
    }

    let text1 = "1Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidu!"

    let text2 = "2Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis nat!"

    let text2Alt1 = "2Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. C"

    let text2Alt2 = "2Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis nat! Cum sociis nat!"
}

```

Also, you could replace Rectangle() by Image() with appropriate proportions because it was the initial state. Rectangle with the ideal size is just for demonstration.

Here I use ZStack with explicit alignment guides (not HStack) because it's a part of another library. It is essential.

XCode 11.5
iOS 13.5 iPhone SE 2020

Bug looks like this:

Expected layout:

答:
it doesn't look like a ZStack problem. Try to remove .aspectRatio(contentMode: .fit) from Rectangle() in VCardView.

For rectangle proportion check something like this.

Title: SwiftUI ZStack alignment bug

Body:
Here is a simple code that produces a strange top alignment and shrunk text of the second element inside ZStack.

BUT if you change the second text a bit (replace text2 by text2Alt1 or by text2Alt2) making it longer or shorter everything becomes correct.

What is the reason for this behavior?

struct VCardView: View {
    let text: String
    let color: UIColor

    var body: some View {
        VStack {
            Rectangle()
                .fill(Color(self.color))
                .frame(idealWidth: 800, idealHeight: 500)
                .aspectRatio(contentMode: .fit)

            Text(self.text)
        }
    }
}

struct ContentView: View {
    var body: some View {
        ZStack(alignment: .topLeading) {
            VCardView(text: text1, color: .blue)
                .frame(width: 180, height: nil)
                .alignmentGuide(.leading) { _ in 180 }
                .alignmentGuide(.top) { _ in 0 }

            //Replace text2 by text2Alt1 or text2Alt2 here:
            VCardView(text: text2, color: .green)
                .frame(width: 180, height: nil)
                .alignmentGuide(.leading) { _ in 0 }
                .alignmentGuide(.top) { _ in 0 }
        }
    }

    let text1 = "1Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidu!"

    let text2 = "2Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis nat!"

    let text2Alt1 = "2Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. C"

    let text2Alt2 = "2Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis nat! Cum sociis nat!"
}

Also, you could replace Rectangle() by Image() with appropriate proportions because it was the initial state. Rectangle with the ideal size is just for demonstration.

Here I use ZStack with explicit alignment guides (not HStack) because it's a part of another library. It is essential.

XCode 11.5
iOS 13.5 iPhone SE 2020

Bug looks like this:

Expected layout: