问:
Power BI Python Chart. Error when using loc
I copied a piece of code that is working on vscode to create a chart on power bi. I've attached the first part of the code below.
I'm trying to filter the dataset (called: dataset) and extract a specific row by filtering the name and year columns.

In this example the name of the player is : 'E. Hazard'.
And year is : 2018

An example of the output: [77.0, 78.0, 85.0, 82.0, 89.0, 61.0, 86.0, 82.0, 81.0, 88.0]

Despite this working on vscode I keep receiving the error:
ValueError: 0 is not in range
The above exception was the direct cause of the following exception:
KeyError: 0

I believe the error is from the loc but I can't seem to find a solution.

```<code>radar_data = dataset.copy()

radar_data = radar_data.fillna(0)

player = radar_data[radar_data["Name"] == 'E. Hazard']
player = player[player['Year'] == 2018].reset_index()
player = player[['Crossing',
  'Finishing',
  'ShortPassing',
  'Volleys',
  'Dribbling',
  'HeadingAccuracy',
  'Acceleration',
  'SprintSpeed',
  'LongPassing',
  'BallControl'
]]

player = player.loc[0]
player = list(player)
</code>```
```<code>    Feedback Type:
    Frown (Error)

    Timestamp:
    2022-12-15T04:32:14.9588500Z

    Local Time:
    2022-12-14T23:32:14.9588500-05:00

    Session ID:
    b6f7d653-06b4-4384-9701-ac926ca0ab17

    Release:
    December 2022

    Product Version:
    2.112.603.0 (22.12) (x64)

    Error Message:
    Python script error.
    ValueError: 0 is not in range

    The above exception was the direct cause of the following exception:

    KeyError: 0

    Stack Trace:
    Microsoft.PowerBI.ExploreServiceCommon.ScriptHandlerException: Python script error.
    ValueError: 0 is not in range

    The above exception was the direct cause of the following exception:

    KeyError: 0
     ---> Microsoft.PowerBI.Scripting.Python.Exceptions.PythonScriptRuntimeException: Python script error.
    ValueError: 0 is not in range

    The above exception was the direct cause of the following exception:

    KeyError: 0

       at Microsoft.PowerBI.Scripting.Python.PythonScriptWrapper.RunScript(String originalScript, Int32 timeoutMs)
       at Microsoft.PowerBI.Client.Windows.Python.PythonScriptHandler.GenerateVisual(ScriptHandlerOptions options)
       --- End of inner exception stack trace ---
       at Microsoft.PowerBI.Client.Windows.Python.PythonScriptHandler.GenerateVisual(ScriptHandlerOptions options)
       at Microsoft.PowerBI.ExploreHost.SemanticQuery.ScriptVisualCommandFlow.RunInternal(Stream dataShapeResultStream, QueryBindingDescriptor& bindingDescriptor)
       at Microsoft.PowerBI.ExploreHost.SemanticQuery.ScriptVisualCommandFlow.Run(Stream dataShapeResultStream, QueryBindingDescriptor& bindingDescriptor)
       at Microsoft.PowerBI.ExploreHost.SemanticQuery.ExecuteSemanticQueryFlow.TransformDataShapeResult(QueryCommand transformCommand, SemanticQueryDataShapeCommand command, Stream dataShapeResultStream, QueryBindingDescriptor& bindingDescriptor)
       at Microsoft.PowerBI.ExploreHost.SemanticQuery.ExecuteSemanticQueryFlow.ExecuteDataQuery(IQueryResultDataWriter queryResultDataWriter, EngineDataModel engineDataModel, DataQuery query, Int32 queryId, ServiceErrorStatusCode& serviceErrorStatusCode, CancellationToken cancelToken)
       at Microsoft.PowerBI.ExploreHost.SemanticQuery.ExecuteSemanticQueryFlow.ProcessAndWriteSemanticQueryCommands(IQueryResultsWriter queryResultsWriter, IList`1 queries, HashSet`1 pendingQueriesToCancel, EngineDataModel engineDataModel)

    Invocation Stack Trace:
       at Microsoft.Mashup.Host.Document.ExceptionExtensions.GetCurrentInvocationStackTrace()
       at Microsoft.Mashup.Client.UI.Shared.StackTraceInfo..ctor(String exceptionStackTrace, String invocationStackTrace, String exceptionMessage)
       at Microsoft.PowerBI.Client.Windows.ErrorHostService.GetErrorDetails(ShowErrorDialogArgs args)
       at Microsoft.PowerBI.Client.Windows.ErrorHostService.<>c__DisplayClass5_0.<ShowErrorDialogCore>b__0()
       at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
       at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
       at System.Delegate.DynamicInvokeImpl(Object[] args)
       at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme)
       at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)
       at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme)
       at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
       at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
       at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
       at System.Windows.Forms.WindowsFormsSynchronizationContext.Send(SendOrPostCallback d, Object state)
       at Microsoft.PowerBI.Client.Windows.Services.UIBlockingService.AllowModalDialogs(Action action)
       at Microsoft.PowerBI.Client.Windows.HostServiceDispatcher.<>c__DisplayClass14_0.<ExecuteOnUIThreadAndHandlePromise>b__0()
       at Microsoft.PowerBI.Client.Windows.HostServiceDispatcher.ExecuteOnUIThreadAndHandlePromise[T](Func`1 func, IPromiseStore promiseStore, Int64 promiseHandle)
       at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
       at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
       at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
       at Microsoft.PowerBI.Client.Windows.WebView2.WebView2Interop.InvokeCs(InteropCall call)
       at Microsoft.Mashup.Host.Document.ExceptionHandlerExtensions.HandleExceptions(IExceptionHandler exceptionHandler, Action action)
       at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
       at Microsoft.Mashup.Client.UI.Shared.WindowManager.ShowModal[T](T dialog, Func`1 showModalFunction)
       at Microsoft.PowerBI.Client.Program.<>c__DisplayClass4_1.<Main>b__3()
       at Microsoft.PowerBI.Client.Windows.IExceptionHandlerExtensions.<>c__DisplayClass3_0.<HandleExceptionsWithNestedTasks>b__0()
       at Microsoft.Mashup.Host.Document.ExceptionHandlerExtensions.HandleExceptions(IExceptionHandler exceptionHandler, Action action)
       at Microsoft.PowerBI.Client.Program.Main(String[] args)

    OS Version:
    Microsoft Windows NT 10.0.19045.0 (x64 en-US)

    CLR Version:
    4.8 or later [Release Number = 528372]

    Peak Virtual Memory:
    70.1 GB

    Private Memory:
    587 MB

    Peak Working Set:
    810 MB

    IE Version:
    11.789.19041.0

    User ID:
    d6c92559-82c4-4835-a6da-c07f1161719e

    Workbook Package Info:
    1* - en-GB, Query Groups: 0, fastCombine: Disabled, runBackgroundAnalysis: False.

    Telemetry Enabled:
    True

    Snapshot Trace Logs:
    C:\Users\Nazar\Microsoft\Power BI Desktop Store App\FrownSnapShot9ddefb1a-8e4d-4ca3-9a82-e325f6fd5fa4.zip

    Model Default Mode:
    Import

    Model Version:
    PowerBI_V3

    Performance Trace Logs:
    C:\Users\Nazar\Microsoft\Power BI Desktop Store App\PerformanceTraces.zip

    Enabled Preview Features:
    PBI_enableWebView2
    PBI_sparklines
    PBI_scorecardVisual
    PBI_fieldParametersSuperSwitch
    PBI_horizontalFusion

    Disabled Preview Features:
    PBI_shapeMapVisualEnabled
    PBI_SpanishLinguisticsEnabled
    PBI_qnaLiveConnect
    PBI_azureMapVisual
    PBI_compositeModelsOverAS
    PBI_b2bExternalDatasetSharing
    PBI_enhancedTooltips
    PQ_WebView2Connector
    PBI_NlToDax
    PBI_optimizeTabRibbon
    PBI_relationshipEditPane

    Disabled DirectQuery Options:
    TreatHanaAsRelationalSource

    Cloud:
    GlobalCloud

    DPI Scale:
    125%

    Supported Services:
    Power BI

    Formulas:

    section Section1;

    shared #"All_players (2)" = let
        Source = Excel.Workbook(File.Contents("X:\Python\All Files\Projects\Football\Kaggle Fifa Ratings\Ratings\fifa_rating_dataset.xlsx"), null, true),
        All_players_Sheet = Source{[Item="All_players",Kind="Sheet"]}[Data],
        #"Promoted Headers" = Table.PromoteHeaders(All_players_Sheet, [PromoteAllScalars=true]),
        #"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers",{{"Column1", Int64.Type}, {"Year", Int64.Type}, {"Name", type text}, {"Club", type text}, {"ID", Int64.Type}, {"Overall", Int64.Type}, {"transfer", type any}, {"T-From", type any}, {"T-To", type any}, {"percentage_change", type any}, {"rating_change", type any}})
    in
        #"Changed Type";

    shared #"Club_rating_change (2)" = let
        Source = Excel.Workbook(File.Contents("X:\Python\All Files\Projects\Football\Kaggle Fifa Ratings\Ratings\fifa_rating_dataset.xlsx"), null, true),
        Club_rating_change_Sheet = Source{[Item="Club_rating_change",Kind="Sheet"]}[Data],
        #"Promoted Headers" = Table.PromoteHeaders(Club_rating_change_Sheet, [PromoteAllScalars=true]),
        #"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers",{{"Column1", Int64.Type}, {"Club", type text}, {"Year", Int64.Type}, {"average_rating", type number}, {"club_average_rating_percentage_change", type number}})
    in
        #"Changed Type";

    shared main_df = let
        Source = Excel.Workbook(File.Contents("X:\Python\All Files\Projects\Football\Kaggle Fifa Ratings\Ratings\fifa_rating_dataset.xlsx"), null, true),
        main_df_Sheet = Source{[Item="main_df",Kind="Sheet"]}[Data],
        #"Promoted Headers" = Table.PromoteHeaders(main_df_Sheet, [PromoteAllScalars=true]),
        #"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers",{{"Column1", Int64.Type}, {"ID", Int64.Type}, {"Name", type text}, {"Age", Int64.Type}, {"Photo", type text}, {"Nationality", type text}, {"Flag", type any}, {"Overall", Int64.Type}, {"Potential", Int64.Type}, {"Club", type text}, {"Club Logo", type any}, {"Value", type text}, {"Wage", type text}, {"Special", Int64.Type}, {"Preferred Foot", type text}, {"International Reputation", Int64.Type}, {"Weak Foot", Int64.Type}, {"Skill Moves", Int64.Type}, {"Work Rate", type text}, {"Body Type", type text}, {"Real Face", type text}, {"Position", type text}, {"Jersey Number", Int64.Type}, {"Joined", type date}, {"Loaned From", type text}, {"Contract Valid Until", type text}, {"Height", type text}, {"Weight", type text}, {"Crossing", Int64.Type}, {"Finishing", Int64.Type}, {"HeadingAccuracy", Int64.Type}, {"ShortPassing", Int64.Type}, {"Volleys", Int64.Type}, {"Dribbling", Int64.Type}, {"Curve", Int64.Type}, {"FKAccuracy", Int64.Type}, {"LongPassing", Int64.Type}, {"BallControl", Int64.Type}, {"Acceleration", Int64.Type}, {"SprintSpeed", Int64.Type}, {"Agility", Int64.Type}, {"Reactions", Int64.Type}, {"Balance", Int64.Type}, {"ShotPower", Int64.Type}, {"Jumping", Int64.Type}, {"Stamina", Int64.Type}, {"Strength", Int64.Type}, {"LongShots", Int64.Type}, {"Aggression", Int64.Type}, {"Interceptions", Int64.Type}, {"Positioning", Int64.Type}, {"Vision", Int64.Type}, {"Penalties", Int64.Type}, {"Composure", Int64.Type}, {"Marking", Int64.Type}, {"StandingTackle", Int64.Type}, {"SlidingTackle", Int64.Type}, {"GKDiving", Int64.Type}, {"GKHandling", Int64.Type}, {"GKKicking", Int64.Type}, {"GKPositioning", Int64.Type}, {"GKReflexes", Int64.Type}, {"Best Position", type text}, {"Best Overall Rating", Int64.Type}, {"Release Clause", type text}, {"DefensiveAwareness", Int64.Type}, {"Year", Int64.Type}})
    in
        #"Changed Type";

    shared #"percentage_change_players_moved (2)" = let
        Source = Excel.Workbook(File.Contents("X:\Python\All Files\Projects\Football\Kaggle Fifa Ratings\Ratings\fifa_rating_dataset.xlsx"), null, true),
        percentage_change_players_moved_Sheet = Source{[Item="percentage_change_players_moved",Kind="Sheet"]}[Data],
        #"Promoted Headers" = Table.PromoteHeaders(percentage_change_players_moved_Sheet, [PromoteAllScalars=true]),
        #"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers",{{"Column1", Int64.Type}, {"Club", type text}, {"Year", Int64.Type}, {"percentage_change", type number}})
    in
        #"Changed Type";

    shared #"chelsea_players (2)" = let
        Source = Excel.Workbook(File.Contents("X:\Python\All Files\Projects\Football\Kaggle Fifa Ratings\Ratings\fifa_rating_dataset.xlsx"), null, true),
        chelsea_players_Sheet = Source{[Item="chelsea_players",Kind="Sheet"]}[Data],
        #"Promoted Headers" = Table.PromoteHeaders(chelsea_players_Sheet, [PromoteAllScalars=true]),
        #"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers",{{"Column1", Int64.Type}, {"Year", Int64.Type}, {"Name", type text}, {"Club", type text}, {"ID", Int64.Type}, {"Overall", Int64.Type}, {"transfer", type text}, {"T-From", type text}, {"T-To", type text}, {"percentage_change", type number}, {"rating_change", Int64.Type}, {"Num_of_years_before_joining_chelsea", Int64.Type}})
    in
        #"Changed Type";

</code>```

Body:
I copied a piece of code that is working on vscode to create a chart on power bi. I've attached the first part of the code below.
I'm trying to filter the dataset (called: dataset) and extract a specific row by filtering the name and year columns.

In this example the name of the player is : 'E. Hazard'.
And year is : 2018

An example of the output: [77.0, 78.0, 85.0, 82.0, 89.0, 61.0, 86.0, 82.0, 81.0, 88.0]

Despite this working on vscode I keep receiving the error:
ValueError: 0 is not in range
The above exception was the direct cause of the following exception:
KeyError: 0

I believe the error is from the loc but I can't seem to find a solution.

radar_data = dataset.copy()

radar_data = radar_data.fillna(0)

player = radar_data[radar_data["Name"] == 'E. Hazard']
player = player[player['Year'] == 2018].reset_index()
player = player[['Crossing',
  'Finishing',
  'ShortPassing',
  'Volleys',
  'Dribbling',
  'HeadingAccuracy',
  'Acceleration',
  'SprintSpeed',
  'LongPassing',
  'BallControl'
]]

player = player.loc[0]
player = list(player)

    Feedback Type:
    Frown (Error)

    Timestamp:
    2022-12-15T04:32:14.9588500Z

    Local Time:
    2022-12-14T23:32:14.9588500-05:00

    Session ID:
    b6f7d653-06b4-4384-9701-ac926ca0ab17

    Release:
    December 2022

    Product Version:
    2.112.603.0 (22.12) (x64)

    Error Message:
    Python script error.
    ValueError: 0 is not in range

    The above exception was the direct cause of the following exception:

    KeyError: 0

    Stack Trace:
    Microsoft.PowerBI.ExploreServiceCommon.ScriptHandlerException: Python script error.
    ValueError: 0 is not in range

    The above exception was the direct cause of the following exception:

    KeyError: 0
     ---> Microsoft.PowerBI.Scripting.Python.Exceptions.PythonScriptRuntimeException: Python script error.
    ValueError: 0 is not in range

    The above exception was the direct cause of the following exception:

    KeyError: 0

       at Microsoft.PowerBI.Scripting.Python.PythonScriptWrapper.RunScript(String originalScript, Int32 timeoutMs)
       at Microsoft.PowerBI.Client.Windows.Python.PythonScriptHandler.GenerateVisual(ScriptHandlerOptions options)
       --- End of inner exception stack trace ---
       at Microsoft.PowerBI.Client.Windows.Python.PythonScriptHandler.GenerateVisual(ScriptHandlerOptions options)
       at Microsoft.PowerBI.ExploreHost.SemanticQuery.ScriptVisualCommandFlow.RunInternal(Stream dataShapeResultStream, QueryBindingDescriptor& bindingDescriptor)
       at Microsoft.PowerBI.ExploreHost.SemanticQuery.ScriptVisualCommandFlow.Run(Stream dataShapeResultStream, QueryBindingDescriptor& bindingDescriptor)
       at Microsoft.PowerBI.ExploreHost.SemanticQuery.ExecuteSemanticQueryFlow.TransformDataShapeResult(QueryCommand transformCommand, SemanticQueryDataShapeCommand command, Stream dataShapeResultStream, QueryBindingDescriptor& bindingDescriptor)
       at Microsoft.PowerBI.ExploreHost.SemanticQuery.ExecuteSemanticQueryFlow.ExecuteDataQuery(IQueryResultDataWriter queryResultDataWriter, EngineDataModel engineDataModel, DataQuery query, Int32 queryId, ServiceErrorStatusCode& serviceErrorStatusCode, CancellationToken cancelToken)
       at Microsoft.PowerBI.ExploreHost.SemanticQuery.ExecuteSemanticQueryFlow.ProcessAndWriteSemanticQueryCommands(IQueryResultsWriter queryResultsWriter, IList`1 queries, HashSet`1 pendingQueriesToCancel, EngineDataModel engineDataModel)

    Invocation Stack Trace:
       at Microsoft.Mashup.Host.Document.ExceptionExtensions.GetCurrentInvocationStackTrace()
       at Microsoft.Mashup.Client.UI.Shared.StackTraceInfo..ctor(String exceptionStackTrace, String invocationStackTrace, String exceptionMessage)
       at Microsoft.PowerBI.Client.Windows.ErrorHostService.GetErrorDetails(ShowErrorDialogArgs args)
       at Microsoft.PowerBI.Client.Windows.ErrorHostService.<>c__DisplayClass5_0.<ShowErrorDialogCore>b__0()
       at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
       at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
       at System.Delegate.DynamicInvokeImpl(Object[] args)
       at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme)
       at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)
       at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme)
       at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
       at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
       at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
       at System.Windows.Forms.WindowsFormsSynchronizationContext.Send(SendOrPostCallback d, Object state)
       at Microsoft.PowerBI.Client.Windows.Services.UIBlockingService.AllowModalDialogs(Action action)
       at Microsoft.PowerBI.Client.Windows.HostServiceDispatcher.<>c__DisplayClass14_0.<ExecuteOnUIThreadAndHandlePromise>b__0()
       at Microsoft.PowerBI.Client.Windows.HostServiceDispatcher.ExecuteOnUIThreadAndHandlePromise[T](Func`1 func, IPromiseStore promiseStore, Int64 promiseHandle)
       at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
       at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
       at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
       at Microsoft.PowerBI.Client.Windows.WebView2.WebView2Interop.InvokeCs(InteropCall call)
       at Microsoft.Mashup.Host.Document.ExceptionHandlerExtensions.HandleExceptions(IExceptionHandler exceptionHandler, Action action)
       at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
       at Microsoft.Mashup.Client.UI.Shared.WindowManager.ShowModal[T](T dialog, Func`1 showModalFunction)
       at Microsoft.PowerBI.Client.Program.<>c__DisplayClass4_1.b__3()
       at Microsoft.PowerBI.Client.Windows.IExceptionHandlerExtensions.<>c__DisplayClass3_0.<HandleExceptionsWithNestedTasks>b__0()
       at Microsoft.Mashup.Host.Document.ExceptionHandlerExtensions.HandleExceptions(IExceptionHandler exceptionHandler, Action action)
       at Microsoft.PowerBI.Client.Program.Main(String[] args)

    OS Version:
    Microsoft Windows NT 10.0.19045.0 (x64 en-US)

    CLR Version:
    4.8 or later [Release Number = 528372]

    Peak Virtual Memory:
    70.1 GB

    Private Memory:
    587 MB

    Peak Working Set:
    810 MB

    IE Version:
    11.789.19041.0

    User ID:
    d6c92559-82c4-4835-a6da-c07f1161719e

    Workbook Package Info:
    1* - en-GB, Query Groups: 0, fastCombine: Disabled, runBackgroundAnalysis: False.

    Telemetry Enabled:
    True

    Snapshot Trace Logs:
    C:\Users\Nazar\Microsoft\Power BI Desktop Store App\FrownSnapShot9ddefb1a-8e4d-4ca3-9a82-e325f6fd5fa4.zip

    Model Default Mode:
    Import

    Model Version:
    PowerBI_V3

    Performance Trace Logs:
    C:\Users\Nazar\Microsoft\Power BI Desktop Store App\PerformanceTraces.zip

    Enabled Preview Features:
    PBI_enableWebView2
    PBI_sparklines
    PBI_scorecardVisual
    PBI_fieldParametersSuperSwitch
    PBI_horizontalFusion

    Disabled Preview Features:
    PBI_shapeMapVisualEnabled
    PBI_SpanishLinguisticsEnabled
    PBI_qnaLiveConnect
    PBI_azureMapVisual
    PBI_compositeModelsOverAS
    PBI_b2bExternalDatasetSharing
    PBI_enhancedTooltips
    PQ_WebView2Connector
    PBI_NlToDax
    PBI_optimizeTabRibbon
    PBI_relationshipEditPane

    Disabled DirectQuery Options:
    TreatHanaAsRelationalSource

    Cloud:
    GlobalCloud

    DPI Scale:
    125%

    Supported Services:
    Power BI

    Formulas:

    section Section1;

    shared #"All_players (2)" = let
        Source = Excel.Workbook(File.Contents("X:\Python\All Files\Projects\Football\Kaggle Fifa Ratings\Ratings\fifa_rating_dataset.xlsx"), null, true),
        All_players_Sheet = Source{[Item="All_players",Kind="Sheet"]}[Data],
        #"Promoted Headers" = Table.PromoteHeaders(All_players_Sheet, [PromoteAllScalars=true]),
        #"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers",{{"Column1", Int64.Type}, {"Year", Int64.Type}, {"Name", type text}, {"Club", type text}, {"ID", Int64.Type}, {"Overall", Int64.Type}, {"transfer", type any}, {"T-From", type any}, {"T-To", type any}, {"percentage_change", type any}, {"rating_change", type any}})
    in
        #"Changed Type";

    shared #"Club_rating_change (2)" = let
        Source = Excel.Workbook(File.Contents("X:\Python\All Files\Projects\Football\Kaggle Fifa Ratings\Ratings\fifa_rating_dataset.xlsx"), null, true),
        Club_rating_change_Sheet = Source{[Item="Club_rating_change",Kind="Sheet"]}[Data],
        #"Promoted Headers" = Table.PromoteHeaders(Club_rating_change_Sheet, [PromoteAllScalars=true]),
        #"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers",{{"Column1", Int64.Type}, {"Club", type text}, {"Year", Int64.Type}, {"average_rating", type number}, {"club_average_rating_percentage_change", type number}})
    in
        #"Changed Type";

    shared main_df = let
        Source = Excel.Workbook(File.Contents("X:\Python\All Files\Projects\Football\Kaggle Fifa Ratings\Ratings\fifa_rating_dataset.xlsx"), null, true),
        main_df_Sheet = Source{[Item="main_df",Kind="Sheet"]}[Data],
        #"Promoted Headers" = Table.PromoteHeaders(main_df_Sheet, [PromoteAllScalars=true]),
        #"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers",{{"Column1", Int64.Type}, {"ID", Int64.Type}, {"Name", type text}, {"Age", Int64.Type}, {"Photo", type text}, {"Nationality", type text}, {"Flag", type any}, {"Overall", Int64.Type}, {"Potential", Int64.Type}, {"Club", type text}, {"Club Logo", type any}, {"Value", type text}, {"Wage", type text}, {"Special", Int64.Type}, {"Preferred Foot", type text}, {"International Reputation", Int64.Type}, {"Weak Foot", Int64.Type}, {"Skill Moves", Int64.Type}, {"Work Rate", type text}, {"Body Type", type text}, {"Real Face", type text}, {"Position", type text}, {"Jersey Number", Int64.Type}, {"Joined", type date}, {"Loaned From", type text}, {"Contract Valid Until", type text}, {"Height", type text}, {"Weight", type text}, {"Crossing", Int64.Type}, {"Finishing", Int64.Type}, {"HeadingAccuracy", Int64.Type}, {"ShortPassing", Int64.Type}, {"Volleys", Int64.Type}, {"Dribbling", Int64.Type}, {"Curve", Int64.Type}, {"FKAccuracy", Int64.Type}, {"LongPassing", Int64.Type}, {"BallControl", Int64.Type}, {"Acceleration", Int64.Type}, {"SprintSpeed", Int64.Type}, {"Agility", Int64.Type}, {"Reactions", Int64.Type}, {"Balance", Int64.Type}, {"ShotPower", Int64.Type}, {"Jumping", Int64.Type}, {"Stamina", Int64.Type}, {"Strength", Int64.Type}, {"LongShots", Int64.Type}, {"Aggression", Int64.Type}, {"Interceptions", Int64.Type}, {"Positioning", Int64.Type}, {"Vision", Int64.Type}, {"Penalties", Int64.Type}, {"Composure", Int64.Type}, {"Marking", Int64.Type}, {"StandingTackle", Int64.Type}, {"SlidingTackle", Int64.Type}, {"GKDiving", Int64.Type}, {"GKHandling", Int64.Type}, {"GKKicking", Int64.Type}, {"GKPositioning", Int64.Type}, {"GKReflexes", Int64.Type}, {"Best Position", type text}, {"Best Overall Rating", Int64.Type}, {"Release Clause", type text}, {"DefensiveAwareness", Int64.Type}, {"Year", Int64.Type}})
    in
        #"Changed Type";

    shared #"percentage_change_players_moved (2)" = let
        Source = Excel.Workbook(File.Contents("X:\Python\All Files\Projects\Football\Kaggle Fifa Ratings\Ratings\fifa_rating_dataset.xlsx"), null, true),
        percentage_change_players_moved_Sheet = Source{[Item="percentage_change_players_moved",Kind="Sheet"]}[Data],
        #"Promoted Headers" = Table.PromoteHeaders(percentage_change_players_moved_Sheet, [PromoteAllScalars=true]),
        #"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers",{{"Column1", Int64.Type}, {"Club", type text}, {"Year", Int64.Type}, {"percentage_change", type number}})
    in
        #"Changed Type";

    shared #"chelsea_players (2)" = let
        Source = Excel.Workbook(File.Contents("X:\Python\All Files\Projects\Football\Kaggle Fifa Ratings\Ratings\fifa_rating_dataset.xlsx"), null, true),
        chelsea_players_Sheet = Source{[Item="chelsea_players",Kind="Sheet"]}[Data],
        #"Promoted Headers" = Table.PromoteHeaders(chelsea_players_Sheet, [PromoteAllScalars=true]),
        #"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers",{{"Column1", Int64.Type}, {"Year", Int64.Type}, {"Name", type text}, {"Club", type text}, {"ID", Int64.Type}, {"Overall", Int64.Type}, {"transfer", type text}, {"T-From", type text}, {"T-To", type text}, {"percentage_change", type number}, {"rating_change", Int64.Type}, {"Num_of_years_before_joining_chelsea", Int64.Type}})
    in
        #"Changed Type";


来源: stackexchange

问:
Change specific route params without change the other params
I use react and the route base on react-router-dom

```<code><Route path=":groupId">

<Route path="users">
                      <Route index element={<UsersList />} />
                      <Route path=":userId" element={<EditUser />} />
                      <Route path="new" element={<NewUser />} />
                    </Route>
</Route>
</code>```

I want to change the groupId that is the parent of the pages, but not change the other params

For example if I am in the new page I will change the parent groupId and still be in new page
I want to change groupId, but not child params/paths like users, or userId

The select group is in my page header and can be change in all the child's pages

ContentLicense: CC BY-SA 4.0

Body:
I use react and the route base on react-router-dom

<Route path=":groupId">

<Route path="users">
                      <Route index element={<UsersList />} />
                      <Route path=":userId" element={<EditUser />} />
                      <Route path="new" element={<NewUser />} />
                    </Route>
</Route>

I want to change the groupId that is the parent of the pages, but not change the other params

For example if I am in the new page I will change the parent groupId and still be in new page
I want to change groupId, but not child params/paths like users, or userId

The select group is in my page header and can be change in all the child's pages


问:
Mui Datepicker value changes to previous date of selected date in React JS
Expected Behaviour:
The datepicker must be null at initialization and while the user selects a date the value should be the same
const [value, setValue] = useState(null)
Instead of setting initial value as null setting a new Date displays this correct Date
const [value, setValue] = useState(new Date())

see image

Actual Behaviour:
Instead of the selected date being set as a value, It sets the incorrect date

see image

Question:
I'm using Mui v5
Is there a way to fix this? Thanks in advance

Here is my Code:

```<code>const [date, setDate] = useState(dayjs());

<LocalizationProvider dateAdapter={AdapterDayjs}>
    <DatePicker
       label="Report Date"
       inputFormat="DD/MMM/YYYY"
       value={date}
       onChange={(newValue) => {
         setDate(newValue);
       }}
       renderInput={(params) => (
         <TextField
          {...params}
          color="info"
          inputProps={{
            ...params.inputProps,
            readOnly: true,
          }}
          />
       )}
       shouldDisableDate={disableWeekends}
    />
</LocalizationProvider>
</code>```

Body:
Expected Behaviour:
The datepicker must be null at initialization and while the user selects a date the value should be the same
const [value, setValue] = useState(null)
Instead of setting initial value as null setting a new Date displays this correct Date
const [value, setValue] = useState(new Date())

see image

Actual Behaviour:
Instead of the selected date being set as a value, It sets the incorrect date

see image

Question:
I'm using Mui v5
Is there a way to fix this? Thanks in advance

Here is my Code:

const [date, setDate] = useState(dayjs());

<LocalizationProvider dateAdapter={AdapterDayjs}>
    <DatePicker
       label="Report Date"
       inputFormat="DD/MMM/YYYY"
       value={date}
       onChange={(newValue) => {
         setDate(newValue);
       }}
       renderInput={(params) => (
         <TextField
          {...params}
          color="info"
          inputProps={{
            ...params.inputProps,
            readOnly: true,
          }}
          />
       )}
       shouldDisableDate={disableWeekends}
    />
</LocalizationProvider>


问:
Budget with Margin Per ticker constraint in the Portfolio Optimization
I'm trying to solve the below problem.

We define a budget for our long short allocation (Sum(W) == 0). Suppose one of the asset in that portfolio get weight of 25% and this means if we are allocating the 10 million then that asset will get 1 Mil but out margin constraints should limit this position to 500k USD. Now if I add a constraint that w[Asset] < 500k USD/ 10 Million. This can assign the weight of Asset as 0.25% but this won't utilize the complete margin. Now to solve this we normalize this weights as W[Assset] / Sum(abs(w)). But this will again break the 500k Usd constraint?
Is there any way to solve above?

I'm expecting to add constraint which will solve this.

Can this problem be solved in the MVO frameworks as complex problem or i have to shift to non convex optimization solvers?


问:
How to specify the referer header in url endpoint of webdriver?
There is a Referer header.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer

In webdriver, I don't see a way to explicitly way to specify Referrer. Is this feature available?

https://www.w3.org/TR/webdriver/#dfn-navigate-to


问:
NPE reading a spark Spark Dataset
I have an RDD that I grouped based on the size of the rows (each row has a different size) in a foreachPartition. then for each of these groups (a list of Strings), I am creating a new Dataset, so I can write them to storage. basically I am trying to split the RDD by size and update the target (controlled by size). Spark's new maxRecordsPerFile won't work for me because each row has a blob that will make the row sizes different. So here is my code, I am getting null pointer exception reading the newly created dataset:

Caller:

JavaRDD<String> stringRDD = xmlDataSet.toJavaRDD().map(xmlRow -> extractXMLBlobToJsonString(xmlRow)).rdd().toJavaRDD();
    GroupBySizeManager mgr = GroupBySizeManager.getInstance();
    jsonRDD.foreachPartition(mgr::splitPartition);
```
<p>Function <code>splitPartition</code> in <code>GroupBySizeManager.java</code></p>
<pre class="lang-java prettyprint-override"><code>public void splitPartition(Iterator<String> rowsInPartition) {
    System.out.println("********Number of groups " + this.getGroups().size());
    SparkSession sparkSession = SparkDataflowConfig.getInstance().getSparkSession();
    while (rowsInPartition.hasNext()) {
        addToGroup(rowsInPartition.next());
    }

    for(List<String> rows: getRows()) {
        System.out.println("******Size of List: " + rows.size());
        Dataset<String> dataset = sparkSession.createDataset(rows, Encoders.STRING());
        Dataset<Row> xmldf = sparkSession.read().json(dataset);// NPE here
         System.out.println("Count of xmlfiltered: " + xmldf.count());
         xmldf.write().format("csv").option("header", "true").save("/home/myfilepath/");
    }
}
</code>```

Receiving the following NPE on the above sparkSession.read().json(dataset). This same code works if I just do it on my initial RDD before I did this grouping and recreating Dataset

java.lang.NullPointerException
at org.apache.spark.sql.execution.SparkPlan.sparkContext(SparkPlan.scala:67)
at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:215)
at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:176)
at org.apache.spark.sql.execution.QueryExecution.toRdd$lzycompute(QueryExecution.scala:132)
at org.apache.spark.sql.execution.QueryExecution.toRdd(QueryExecution.scala:131)
at org.apache.spark.sql.execution.datasources.json.TextInputJsonDataSource$.inferFromDataset(JsonDataSource.scala:104)
at org.apache.spark.sql.DataFrameReader.$anonfun$json$1(DataFrameReader.scala:567)
at scala.Option.getOrElse(Option.scala:189)
at org.apache.spark.sql.DataFrameReader.json(DataFrameReader.scala:567)
at com.bm.xchange.spark.executor.GroupBySizeManager.splitPartition(GroupBySizeManager.java:57)
at org.apache.spark.api.java.JavaRDDLike.$anonfun$foreachPartition$1(JavaRDDLike.scala:219)
at org.apache.spark.api.java.JavaRDDLike.$anonfun$foreachPartition$1$adapted(JavaRDDLike.scala:219)
at org.apache.spark.rdd.RDD.$anonfun$foreachPartition$2(RDD.scala:1020)
```

I have been reading more and I think I know why I am seeing the exception. It seems like we cannot create a dataset in the executor, but only in the driver. So this logic of mine wont work. Is there any better way to do this (split partition based on file size) without causing shuffle or repartition?
Appreciate your help
thank you

Title: NPE reading a spark Spark Dataset

Body:
I have an RDD that I grouped based on the size of the rows (each row has a different size) in a foreachPartition. then for each of these groups (a list of Strings), I am creating a new Dataset, so I can write them to storage. basically I am trying to split the RDD by size and update the target (controlled by size). Spark's new maxRecordsPerFile won't work for me because each row has a blob that will make the row sizes different. So here is my code, I am getting null pointer exception reading the newly created dataset:

Caller:

JavaRDD<String> stringRDD = xmlDataSet.toJavaRDD().map(xmlRow -> extractXMLBlobToJsonString(xmlRow)).rdd().toJavaRDD();
    GroupBySizeManager mgr = GroupBySizeManager.getInstance();
    jsonRDD.foreachPartition(mgr::splitPartition);

Function splitPartition in GroupBySizeManager.java

public void splitPartition(Iterator<String> rowsInPartition) {
    System.out.println("********Number of groups " + this.getGroups().size());
    SparkSession sparkSession = SparkDataflowConfig.getInstance().getSparkSession();
    while (rowsInPartition.hasNext()) {
        addToGroup(rowsInPartition.next());
    }

    for(List<String> rows: getRows()) {
        System.out.println("******Size of List: " + rows.size());
        Dataset<String> dataset = sparkSession.createDataset(rows, Encoders.STRING());
        Dataset<Row> xmldf = sparkSession.read().json(dataset);// NPE here
         System.out.println("Count of xmlfiltered: " + xmldf.count());
         xmldf.write().format("csv").option("header", "true").save("/home/myfilepath/");
    }
}

Receiving the following NPE on the above sparkSession.read().json(dataset). This same code works if I just do it on my initial RDD before I did this grouping and recreating Dataset

java.lang.NullPointerException
at org.apache.spark.sql.execution.SparkPlan.sparkContext(SparkPlan.scala:67)
at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:215)
at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:176)
at org.apache.spark.sql.execution.QueryExecution.toRdd$lzycompute(QueryExecution.scala:132)
at org.apache.spark.sql.execution.QueryExecution.toRdd(QueryExecution.scala:131)
at org.apache.spark.sql.execution.datasources.json.TextInputJsonDataSource$.inferFromDataset(JsonDataSource.scala:104)
at org.apache.spark.sql.DataFrameReader.$anonfun$json$1(DataFrameReader.scala:567)
at scala.Option.getOrElse(Option.scala:189)
at org.apache.spark.sql.DataFrameReader.json(DataFrameReader.scala:567)
at com.bm.xchange.spark.executor.GroupBySizeManager.splitPartition(GroupBySizeManager.java:57)
at org.apache.spark.api.java.JavaRDDLike.$anonfun$foreachPartition$1(JavaRDDLike.scala:219)
at org.apache.spark.api.java.JavaRDDLike.$anonfun$foreachPartition$1$adapted(JavaRDDLike.scala:219)
at org.apache.spark.rdd.RDD.$anonfun$foreachPartition$2(RDD.scala:1020)

I have been reading more and I think I know why I am seeing the exception. It seems like we cannot create a dataset in the executor, but only in the driver. So this logic of mine wont work. Is there any better way to do this (split partition based on file size) without causing shuffle or repartition?
Appreciate your help
thank you


问:
Fatal error: Uncaught Error: Undefined constant "STDIN"PHP

Fatal error: Uncaught Error: Undefined constant "STDIN" in
C:\xampp\htdocs\piramida.php:34 Stack trace: #0 {main} thrown in
C:\xampp\htdocs\piramida.php on line 34

```<code>echo "Masukkan tanggal lahir: ";
$tanggal = trim(fgets(STDIN));

echo "Masukkan bulan lahir: ";
$bulan = trim(fgets(STDIN));
</code>```

Hope this helps solve my error
Sorry I'm just learning

Body:
Fatal error: Uncaught Error: Undefined constant "STDIN" in
C:\xampp\htdocs\piramida.php:34 Stack trace: #0 {main} thrown in
C:\xampp\htdocs\piramida.php on line 34

echo "Masukkan tanggal lahir: ";
$tanggal = trim(fgets(STDIN));

echo "Masukkan bulan lahir: ";
$bulan = trim(fgets(STDIN));

Hope this helps solve my error
Sorry I'm just learning


问:
how to convert rtf to html and html to rtf in angular 12?
i need to convert angular editors html out put to rtf form and render rtf to html while fetching rtf data form server.</p>
```<code>  convert(){
    let rtf = this.htmlToRtf.convertHtmlToRtf(this.html);
    console.log('rtf',rtf)

    console.log('rtfString',JSON.stringify(rtf))

    // const blob = new Blob([rtf], {type: "application/rtf;charset=utf-8"});
    // const link=window.URL.createObjectURL(blob);
    // window.location=link;
  }

  convertToPlain(rtf) {
    rtf = rtf.replace(/\\par[d]?/g, "");
    rtf = rtf.replace(/\{\*?\\[^{}]+}|[{}]|\\\n?[A-Za-z]+\n?(?:-?\d+)?[ ]?/g, "")
    return rtf.replace(/\\'[0-9a-zA-Z]{2}/g, "").trim();
}
``` but does not provide required result.
</code>```

Body:
i need to convert angular editors html out put to rtf form and render rtf to html while fetching rtf data form server.

  convert(){
    let rtf = this.htmlToRtf.convertHtmlToRtf(this.html);
    console.log('rtf',rtf)

    console.log('rtfString',JSON.stringify(rtf))

    // const blob = new Blob([rtf], {type: "application/rtf;charset=utf-8"});
    // const link=window.URL.createObjectURL(blob);
    // window.location=link;
  }

  convertToPlain(rtf) {
    rtf = rtf.replace(/\\par[d]?/g, "");
    rtf = rtf.replace(/\{\*?\\[^{}]+}|[{}]|\\\n?[A-Za-z]+\n?(?:-?\d+)?[ ]?/g, "")
    return rtf.replace(/\\'[0-9a-zA-Z]{2}/g, "").trim();
}
``` but does not provide required result.


问:
I face issue in eas build running. How can i debug eas build running in android device?
i create one react-native project in expo-cli.
which work correctly in expo go and emulator but when i created eas build of that project i face issue in running build on android device.

My app crash when i tried to run eas build in android device.
My app crash after splash screen.


问:
Why is multiplication faster than bitshift
I recently posted an answer where I suggested using bitshift instead of multiplication as a performance boost. It was pointed out to me that this isn't the case with the following example:

```<code>from timeit import repeat
for e in ['x*2 ', 'x<<1'] * 3:
    print(e, min(repeat(e, 'x=5')))

x*2  0.015567475988063961
x<<1 0.024531989998649806
x*2  0.01551242297864519
x<<1 0.024578287004260346
x*2  0.015560572996037081
x<<1 0.02448918900336139
</code>```

This is the case for values of x up to 1,000,000,000. Note that this value decreases as the value by which x is being multiplied/bit-shifted increases as well.

This doesn't make sense to me as bitshift is objectively a simpler and faster operation. And we can see this as the bitshift speeds up as x grows. So, why is it slower for smaller values of x?

Moreover, changing my code up a bit yielded some interesting results:

```<code>for e in ['x*2 ', 'x<<1'] * 3:
     print(e, max(repeat(e, 'x=5')))

x*2  0.054458492988487706
x<<1 0.02453691599657759
x*2  0.015550968993920833
x<<1 0.0246038619952742
x*2  0.015542584005743265
x<<1 0.024583352991612628
</code>```

As we can see from this, the usage of multiplication ran much slower than bitshift on the initial pass, although all subsequent usages had comparable times. It looks like there's some sort of caching operation going on here but I can't fathom why that would result in different runtimes.

Body:
I recently posted an answer where I suggested using bitshift instead of multiplication as a performance boost. It was pointed out to me that this isn't the case with the following example:

from timeit import repeat
for e in ['x*2 ', 'x<<1'] * 3:
    print(e, min(repeat(e, 'x=5')))

x*2  0.015567475988063961
x<<1 0.024531989998649806
x*2  0.01551242297864519
x<<1 0.024578287004260346
x*2  0.015560572996037081
x<<1 0.02448918900336139

This is the case for values of x up to 1,000,000,000. Note that this value decreases as the value by which x is being multiplied/bit-shifted increases as well.

This doesn't make sense to me as bitshift is objectively a simpler and faster operation. And we can see this as the bitshift speeds up as x grows. So, why is it slower for smaller values of x?

Moreover, changing my code up a bit yielded some interesting results:

for e in ['x*2 ', 'x<<1'] * 3:
     print(e, max(repeat(e, 'x=5')))

x*2  0.054458492988487706
x<<1 0.02453691599657759
x*2  0.015550968993920833
x<<1 0.0246038619952742
x*2  0.015542584005743265
x<<1 0.024583352991612628

As we can see from this, the usage of multiplication ran much slower than bitshift on the initial pass, although all subsequent usages had comparable times. It looks like there's some sort of caching operation going on here but I can't fathom why that would result in different runtimes.


问:
Given input size: (512x1x1). Calculated output size: (512x0x0). Output size is too small
There is such an algorithm, I get an error Size of input data: (512x1x1). Estimated output size: (512x0x0). The output size is too small. I understand that the problem is in the AvgPool line. Incompatible sizes. I don't understand how to fix this. Tell me please.

```<code>class AntispoofModel(nn.Module):
    def __init__(self, device="cpu", **kwargs):
        super().__init__()
        resnet = torch.hub.load('pytorch/vision:v0.10.0', 'resnet18', pretrained=True)
        self.resnet = nn.Sequential(*[i for i in list(resnet.children())[:-1]]).to(device)
        for ch in self.resnet.children():
            for param in ch.parameters():
                param.requires_grad = False
        self.gat = GAT(**kwargs).to(device)
        self.device = device
        self.adj = torch.tensor(grid_to_graph(7, 7, return_as=np.ndarray)).to(device)
        self.avg_pool = nn.AvgPool2d(kernel_size=8, stride=8, padding=0, ceil_mode=False,
                                               count_include_pad=False)

    def forward(self, x):
        x = self.resnet(x.to(self.device))
        x = self.avg_pool(x)
        #x = x.view(512, -1)
        #x = x.view(512, 1)
        x = self.gat(x, self.adj)
        return torch.sigmoid(x)

preprocess = transforms.Compose([
    transforms.Resize(256),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])

torch.manual_seed(42)
kwargs = {"nfeat":512, "nhid":64, "nclass":1, "nheads":49, "dropout":0.6, "alpha":0.01}
model = AntispoofModel(**kwargs, device="cpu")

train_dataloader = DataLoader(train_dataset, batch_size=64, shuffle=True)
test_dataloader = DataLoader(test_dataset, batch_size=64, shuffle=True)

</code>```
```<code>RuntimeError: Given input size: (512x1x1). Calculated output size: (512x0x0). Output size is too small
</code>```

Body:
There is such an algorithm, I get an error Size of input data: (512x1x1). Estimated output size: (512x0x0). The output size is too small. I understand that the problem is in the AvgPool line. Incompatible sizes. I don't understand how to fix this. Tell me please.

class AntispoofModel(nn.Module):
    def __init__(self, device="cpu", **kwargs):
        super().__init__()
        resnet = torch.hub.load('pytorch/vision:v0.10.0', 'resnet18', pretrained=True)
        self.resnet = nn.Sequential(*[i for i in list(resnet.children())[:-1]]).to(device)
        for ch in self.resnet.children():
            for param in ch.parameters():
                param.requires_grad = False
        self.gat = GAT(**kwargs).to(device)
        self.device = device
        self.adj = torch.tensor(grid_to_graph(7, 7, return_as=np.ndarray)).to(device)
        self.avg_pool = nn.AvgPool2d(kernel_size=8, stride=8, padding=0, ceil_mode=False,
                                               count_include_pad=False)

    def forward(self, x):
        x = self.resnet(x.to(self.device))
        x = self.avg_pool(x)
        #x = x.view(512, -1)
        #x = x.view(512, 1)
        x = self.gat(x, self.adj)
        return torch.sigmoid(x)

preprocess = transforms.Compose([
    transforms.Resize(256),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])

torch.manual_seed(42)
kwargs = {"nfeat":512, "nhid":64, "nclass":1, "nheads":49, "dropout":0.6, "alpha":0.01}
model = AntispoofModel(**kwargs, device="cpu")

train_dataloader = DataLoader(train_dataset, batch_size=64, shuffle=True)
test_dataloader = DataLoader(test_dataset, batch_size=64, shuffle=True)

RuntimeError: Given input size: (512x1x1). Calculated output size: (512x0x0). Output size is too small


问:
Accessing an external SFP module via I2C not working
I hope this is the correct location for a question like I am asking here (I am new to asking questions on stackoverflow)

I am working on a project with a processor to access the registers of an SFP (connected to the I2C-bus of the processor).

Obviously it is not working (at least not always), but to clarify I want to mention what is working ... The setup fo the processor and the I2C bus is working properly. Other devices on the bus work flawlessly.
At the moment I am using a Raspberry Pi and its I2C capabilities to troubleshoote my project.

The hardware to connect the SFP-interface to the I2C pins of the Raspberry Pi I built myself (and there may be some error in it), but as I am trying different SFPs I see some are working properly.
These are working:
GLC-T, GLC-SX-MM
The following did not work (with an i2detect command from the RPi it does not see any responding device):
GLC-SX-MMD, SFP-10G-SR, PAN-SFP-PLUS-SR-CMT (The last one is from PaloAlto, all others are from Cisco)

I tried to follow the specifications from INF-8074 (https://www.10gtek.com/templates/wzten/pdf/INF-8074.pdf) to make the proper connections and for some SFPs it seems to be working. Even though I cannot verify all the registers' accuracy, there are parts (like the description of the SFP) which show up clearly ... below is the output of the GCL-T:

```<code>mordin@ubuntu:~$ sudo i2cdump -y 1 0x50
No size specified (using byte-data access)
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f    0123456789abcdef
00: 03 04 00 00 00 00 08 00 00 00 00 01 0d 00 00 00    ??....?....??...
10: 00 00 64 00 43 49 53 43 4f 2d 4d 45 54 48 4f 44    ..d.CISCO-METHOD
20: 45 20 20 20 01 00 00 00 53 50 37 30 34 31 5f 52    E   ?...SP7041_R
30: 65 76 5f 46 20 20 20 20 46 20 20 20 41 0c c1 5a    ev_F    F   A??Z
40: 00 10 00 00 30 30 30 30 30 4d 54 43 31 35 33 39    .?..00000MTC1539
50: 30 31 45 51 31 31 30 39 32 31 30 31 00 00 00 3c    01EQ11092101...<
60: 00 00 0e fa 99 1c 0a 21 57 89 b6 80 c0 8a 20 a0    ..?????!W????? ?
70: f7 c2 a9 00 00 00 00 00 00 00 00 00 46 a1 08 57    ???.........F??W
80: 43 4e 53 38 54 55 54 41 41 42 33 30 2d 31 34 31    CNS8TUTAAB30-141
90: 30 2d 30 33 00 00 00 00 00 00 00 00 00 00 00 c3    0-03...........?
a0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00    ................
b0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00    ................
c0: 47 4c 43 2d 54 20 20 20 20 20 20 20 20 20 20 20    GLC-T
d0: 20 20 20 20 ff ff ff ff ff ff ff ff ff ff ff ff        ............
e0: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff    ................
f0: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff    ................
</code>```

There are multiple projects online ... and they all describe their workflow, and it sounds like as long as you make proper physical connections (power, I2C-pins) it should "just work" to have access to the registers of the connected SFP.

Now I am not sure ... did I miss something when I made my physical connections and some SFPs are just working accidently?
Just for "fun" I tried to pin the "TX Disable" to GND (I was thinking maybe the line disables the whole SFP-module and not only the TX-part), but it did not make any difference.

If someone has a suggestion (or a hint what I could try) why I am not able to access many SFPs via I2C while some work just fine, I would be grateful.

Thanks,
Mordin

PS.: apparently I am not allowed to use "sfp" as a tag ... weird

Body:
I hope this is the correct location for a question like I am asking here (I am new to asking questions on stackoverflow)

I am working on a project with a processor to access the registers of an SFP (connected to the I2C-bus of the processor).

Obviously it is not working (at least not always), but to clarify I want to mention what is working ... The setup fo the processor and the I2C bus is working properly. Other devices on the bus work flawlessly.
At the moment I am using a Raspberry Pi and its I2C capabilities to troubleshoote my project.

The hardware to connect the SFP-interface to the I2C pins of the Raspberry Pi I built myself (and there may be some error in it), but as I am trying different SFPs I see some are working properly.
These are working:
GLC-T, GLC-SX-MM
The following did not work (with an i2detect command from the RPi it does not see any responding device):
GLC-SX-MMD, SFP-10G-SR, PAN-SFP-PLUS-SR-CMT (The last one is from PaloAlto, all others are from Cisco)

I tried to follow the specifications from INF-8074 (https://www.10gtek.com/templates/wzten/pdf/INF-8074.pdf) to make the proper connections and for some SFPs it seems to be working. Even though I cannot verify all the registers' accuracy, there are parts (like the description of the SFP) which show up clearly ... below is the output of the GCL-T:

mordin@ubuntu:~$ sudo i2cdump -y 1 0x50
No size specified (using byte-data access)
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f    0123456789abcdef
00: 03 04 00 00 00 00 08 00 00 00 00 01 0d 00 00 00    ??....?....??...
10: 00 00 64 00 43 49 53 43 4f 2d 4d 45 54 48 4f 44    ..d.CISCO-METHOD
20: 45 20 20 20 01 00 00 00 53 50 37 30 34 31 5f 52    E   ?...SP7041_R
30: 65 76 5f 46 20 20 20 20 46 20 20 20 41 0c c1 5a    ev_F    F   A??Z
40: 00 10 00 00 30 30 30 30 30 4d 54 43 31 35 33 39    .?..00000MTC1539
50: 30 31 45 51 31 31 30 39 32 31 30 31 00 00 00 3c    01EQ11092101...<
60: 00 00 0e fa 99 1c 0a 21 57 89 b6 80 c0 8a 20 a0    ..?????!W????? ?
70: f7 c2 a9 00 00 00 00 00 00 00 00 00 46 a1 08 57    ???.........F??W
80: 43 4e 53 38 54 55 54 41 41 42 33 30 2d 31 34 31    CNS8TUTAAB30-141
90: 30 2d 30 33 00 00 00 00 00 00 00 00 00 00 00 c3    0-03...........?
a0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00    ................
b0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00    ................
c0: 47 4c 43 2d 54 20 20 20 20 20 20 20 20 20 20 20    GLC-T
d0: 20 20 20 20 ff ff ff ff ff ff ff ff ff ff ff ff        ............
e0: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff    ................
f0: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff    ................

There are multiple projects online ... and they all describe their workflow, and it sounds like as long as you make proper physical connections (power, I2C-pins) it should "just work" to have access to the registers of the connected SFP.

Now I am not sure ... did I miss something when I made my physical connections and some SFPs are just working accidently?
Just for "fun" I tried to pin the "TX Disable" to GND (I was thinking maybe the line disables the whole SFP-module and not only the TX-part), but it did not make any difference.

If someone has a suggestion (or a hint what I could try) why I am not able to access many SFPs via I2C while some work just fine, I would be grateful.

Thanks,
Mordin

PS.: apparently I am not allowed to use "sfp" as a tag ... weird


问:
How do I open a new window and write pixels to that window in NASM x64?
I am making a simple app that reads from a file and renders an image from that file. The file format is 0 for a blank character and 1 for a full character. Then, my app reads from that file and outputs to the terminal the interpretation of that file.

The only problem with that is that the width and height of my images are limited. I would like to draw each pixel using a window. How can I do that in NASM x64, on Linux, without using other languages like C/C++?

I have looked everywhere and I only found something using the C Windows API in 32-bit, which doesn't answer my question or help me. Help would be appreciated.


问:
Replacements (/.) within Minimize function Mathematica
I want to find the parameter value that minimizes the solution to an ODE at a given x.
For example,the function s(w) solves the ODE at parameter value w. I want to find the w such that y(5) is smallest. Here is the code:

```<code>s[w_] := NDSolve[{y'[x] == y[x] w Cos[x + y[x]], y[0] == 1}, y, {x, 0, 30}]
NMinimize[y[5] /. s[w], {w}]
</code>```

I get the following error:

```<code>ReplaceAll::reps: {NDSolve[{(y^\[Prime])[x]==w Cos[x+y[<<1>>]] y[x],y[0]==1},y,{x,0,30}]} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing.
</code>```

It looks like it does not successfully replace the numeric value of w into the ODE, and therefore s(w) is not solved, and y[5] can not be replaced by the solution. How do I fix this problem to successfully find the minimum?

Body:
I want to find the parameter value that minimizes the solution to an ODE at a given x.
For example,the function s(w) solves the ODE at parameter value w. I want to find the w such that y(5) is smallest. Here is the code:

s[w_] := NDSolve[{y'[x] == y[x] w Cos[x + y[x]], y[0] == 1}, y, {x, 0, 30}]
NMinimize[y[5] /. s[w], {w}]

I get the following error:

ReplaceAll::reps: {NDSolve[{(y^\[Prime])[x]==w Cos[x+y[<<1>>]] y[x],y[0]==1},y,{x,0,30}]} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing.

It looks like it does not successfully replace the numeric value of w into the ODE, and therefore s(w) is not solved, and y[5] can not be replaced by the solution. How do I fix this problem to successfully find the minimum?


问:
Getting error 400 trying to upload a cropped image using fetch in JavaScript
I am a newbie to JavaScript. I am trying to implement a feature to my website that allows the user to upload an image, crop the image, then press a button to upload the cropped image to imgur through the Imgur API. I am able to get the following code to work when I apply it directly to the "upload file" button, before the user crops the image. But when I try to apply it to the "upload to imgur" button, I get error 400. I hope I explained that well. Does anyone have any idea what the issue might be? In this code, 'up' represents the button to upload the file to imgur, and 'cropped' represents the cropped image.

up.addEventListener("click", (ev) => {
  const formdata = new FormData();
  formdata.append("image", cropped);
  fetch("https://api.imgur.com/3/image/", {
    method: "post",
    headers: {
      Authorization: "Client-ID <client ID>",
    },
    body: formdata,
  })
    .then((data) => data.json())
    .then((data) => {
      img_result.src = data.data.link;
      document.getElementById("url").innerText = data.data.link;
    });
});
```


问:
formData HttpContext.Current.Request.Params always null when using react
I am not sure if the problem is from the front end or the back end. I know the backend at least works when using postman, whenever using react HttpContext.Current.Request.Params is always null. when I print it in my react app before sending the POST request it says there are values.

here is my Js fetch

```<code>
export async function uploadFile(file, type) {
  const formData = new FormData();
  formData.append("file", file);
  formData.append("fileType", type);
  console.log(...formData); //print the correct stuff

  try {
    const url = `${auth.getApi()}/FileUpload`;
    const resp = await fetch(url, {
      method: "POST",
      body: formData,
      headers: new Headers({
        Authorization: auth.BasicAuth(),
        "Content-Type": "multipart/form-data",
      }),
    });
    return resp;
  } catch (e) {
    console.log(e);
    return e;
  }
}

</code>```

And the is my c# backend code

```<code>    public class FileUploadController : ApiController
    {
        private static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private const string ALLOWED_CORS_ORIGINS = "*";

        [BasicAuthenticationFilter(true)]
        [HttpPost]
        public async Task<IHttpActionResult> Post()
        {

            try
            {
NameValueCollection formData = HttpContext.Current.Request.Params;
string fileType = formData.Get("fileType"); // it says it's null
                if (string.IsNullOrEmpty(fileType)) //true

</code>```

Body:
I am not sure if the problem is from the front end or the back end. I know the backend at least works when using postman, whenever using react HttpContext.Current.Request.Params is always null. when I print it in my react app before sending the POST request it says there are values.

here is my Js fetch

export async function uploadFile(file, type) {
  const formData = new FormData();
  formData.append("file", file);
  formData.append("fileType", type);
  console.log(...formData); //print the correct stuff

  try {
    const url = `${auth.getApi()}/FileUpload`;
    const resp = await fetch(url, {
      method: "POST",
      body: formData,
      headers: new Headers({
        Authorization: auth.BasicAuth(),
        "Content-Type": "multipart/form-data",
      }),
    });
    return resp;
  } catch (e) {
    console.log(e);
    return e;
  }
}

And the is my c# backend code

    public class FileUploadController : ApiController
    {
        private static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private const string ALLOWED_CORS_ORIGINS = "*";

        [BasicAuthenticationFilter(true)]
        [HttpPost]
        public async Task<IHttpActionResult> Post()
        {

            try
            {
NameValueCollection formData = HttpContext.Current.Request.Params;
string fileType = formData.Get("fileType"); // it says it's null
                if (string.IsNullOrEmpty(fileType)) //true


问:
TinyMCE sticky toolbar with element scroll (not window scroll)
Problem : We are trying to achieve toolbar sticky behavior in tinyMCE. It works when we created a separate application that had a normal window scroll. As soon as we apply it in our application it doesn't work. Our application doesn't have any window-level scroll, we are only applying div/element scrolls.

We are using tinyMCE 5.9.0 version and the following is our init function for tinyMCE

```<code>tinyConfig:
{
   selector: '#' + elementId,
   suffix: '.min',
   base_url: '/app/tinymce',
   skin_url: '/app/tinymce/skins/ui/oxide',
   content_css: '/app/tinymce/skins/ui/oxide/content.min.css',
   theme: 'silver',
   browser_spellcheck: true,
   contextmenu: false,
   toolbar_sticky: true,
   toolbar_sticky_offset: 150
}
</code>```
```<code>// intializing
tinymce.init(this.tinyConfig);
</code>```

Following is the html that we are using:

<rich-text-editor>
</rich-text-editor>

```
<p>How to make tinyMCE toolbar sticky with element <code>scroll</code> (not window <code>scroll</code>)?</p>
<p>We tried adding scroll event listeners and calling <code>ScrollWindow</code> event of tinyMCE. This does make the toolbar sticky but never unsticks the toolbar, also other resizing events are not working properly.<br />
Also tried adding an event listener to the element using:</p>
<pre class="lang-js prettyprint-override"><code>document.getElementById('sectionId').addEventListner();
document.addEventListener('scroll', event => {
    this._tinyMceInstance.fire('ScrollWindow', event);
});
</code>```

Body:
Problem : We are trying to achieve toolbar sticky behavior in tinyMCE. It works when we created a separate application that had a normal window scroll. As soon as we apply it in our application it doesn't work. Our application doesn't have any window-level scroll, we are only applying div/element scrolls.

We are using tinyMCE 5.9.0 version and the following is our init function for tinyMCE

tinyConfig:
{
   selector: '#' + elementId,
   suffix: '.min',
   base_url: '/app/tinymce',
   skin_url: '/app/tinymce/skins/ui/oxide',
   content_css: '/app/tinymce/skins/ui/oxide/content.min.css',
   theme: 'silver',
   browser_spellcheck: true,
   contextmenu: false,
   toolbar_sticky: true,
   toolbar_sticky_offset: 150
}

// intializing
tinymce.init(this.tinyConfig);

Following is the html that we are using:

<rich-text-editor>
</rich-text-editor>

How to make tinyMCE toolbar sticky with element scroll (not window scroll)?

We tried adding scroll event listeners and calling ScrollWindow event of tinyMCE. This does make the toolbar sticky but never unsticks the toolbar, also other resizing events are not working properly.

Also tried adding an event listener to the element using:

document.getElementById('sectionId').addEventListner();
document.addEventListener('scroll', event => {
    this._tinyMceInstance.fire('ScrollWindow', event);
});


问:
How to add details to description column of SLA_MISS metadata table
We have SLA_MISS table in airflow metadata which will be populated to track the SLA_MISS information of task. Documentation for the same are present at https://airflow.apache.org/docs/apache-airflow/stable/_api/airflow/models/slamiss/index.html

However there is no information as to how we can populate custom data in description column and blank values are there for all the rows. Even the notification_sent column is being marked as true for all the rows unsure of where exactly its being notified.

Please suggest possibility of adding custom data to description column and notification sent data interpretation


问:
Elasticsearch - Further filter out results based on match score using Java
We are currently limiting to 50 documents when we are searching in. But score for each document could be very different. eg score of 1st object = 5, score of 50th object = 0.0001. Example:

```<code>record 1 : score = 11.5
record 2 : score = 11.2
record 3 : score = 10.6
record 4 : score = 9.9
record 5 : score = 2.1
record 6 : score = 1.9
....
record 50: score = 0.0001
</code>```

In this case we need to filter out objects with so low score.

Is there a way in elasticsearch to filter out the irrelevant results. To use the min_score query you should know the scores before hand hence that will not be a solution, thus we need to calculate post querying from elasticsearch

What kind of statistical distribution/formula should we use upon querying to the elasticsearch? I am thinking of standard deviation but not so sure? Or is this even possible?

Body:
We are currently limiting to 50 documents when we are searching in. But score for each document could be very different. eg score of 1st object = 5, score of 50th object = 0.0001. Example:

record 1 : score = 11.5
record 2 : score = 11.2
record 3 : score = 10.6
record 4 : score = 9.9
record 5 : score = 2.1
record 6 : score = 1.9
....
record 50: score = 0.0001

In this case we need to filter out objects with so low score.

Is there a way in elasticsearch to filter out the irrelevant results. To use the min_score query you should know the scores before hand hence that will not be a solution, thus we need to calculate post querying from elasticsearch

What kind of statistical distribution/formula should we use upon querying to the elasticsearch? I am thinking of standard deviation but not so sure? Or is this even possible?


问:
Web Automation without browser in Linux Server
Is it possible to do web automation (fill form, click button, download file, etc) from a website within linux server since it hasn't GUI ?

Long story short, I need to do a little web automation work in a Linux server (without GUI). But so far I use Selenium and as I know that we have to run selenium in a machine with GUI that has a browser app installed. I've been wondering that is it possible to run web automation in this such environment I meant not only using headless mode of selenium because this mode still needs a browser app to be installed, moreover, I haven't found any article on the internet that discuss this.


问:
Vue.js and vuex this.$store return undefined after adding it to new Vue({store})
I have gone through the available solutions on here, but none seems to work for my situation.

Vue.js and vuex: this.$store is undefined

Vuex store this.$store is undefined in Vue.js component

https://pinoria.com/how-to-fix-this-store-is-undefined-with-vue-js-and-vuex/

Successfully imported the store object into my main.js. Checked by logging it.

Added store to my vue instance, but I cannot access it through this.$store in my components.

```<code>Error - Error in v-on handler (Promise/async): "TypeError: Cannot read
properties of undefined (reading 'error')"

console.log(this.$store) in my components returns undefined.
</code>```

codesandbox link -  https://codesandbox.io/s/vdr5js

store.js

```<code>import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  strict: true,
  state: {
    token: null,
    user: null,
    isUserLoggedin: false
  },
  mutations: {
    setToken (state, token) {
      state.token = token
      if (token) {
        state.isUserLoggedIn = true
      } else {
        state.isUserLoggedIn = false
      }
    },
    setUser (state, user) {
      state.user = user
    }
  },
  actions: {
    setToken ({commit}, token) {
      commit('setToken', token)
    },
    setUser ({commit}, user) {
      commit('setUser', user)
    }
  }
})
</code>```

main.js

```<code>// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an
alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import Vuetify from 'vuetify'
import { sync } from 'vuex-router-sync'
import 'vuetify/dist/vuetify.min.css'
import store from '@/store/store'

Vue.config.productionTip = false

console.log(store) // returns store object

Vue.use(Vuetify)

sync(store, router)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,
  router,
  vuetify: new Vuetify(),
  components: { App },
  template: '<App/>'
})
</code>```

Login component

```<code><script>
import AuthenticationService from '@/services/AuthenticationService'
export default {
  data () {
    return {
      email: '',
      password: '',
      error: null
    }
  },
  methods: {
    async login () {
      try {
        const response = await AuthenticationService.login({
          email: this.email,
          password: this.password
        })
        this.$store.dispatch('setToken', response.data.token) //throw error
        this.$store.dispatch('setUser', response.data.user)
      } catch (error) {
        this.error = error.responsedata.error
      }
    }
  }
}
</script>
</code>```

I can access this.$router and this.$store in the Header.vue component
Please tell me if I am doing something wrong.

Body:
I have gone through the available solutions on here, but none seems to work for my situation.

Vue.js and vuex: this.$store is undefined

Vuex store this.$store is undefined in Vue.js component

https://pinoria.com/how-to-fix-this-store-is-undefined-with-vue-js-and-vuex/

Successfully imported the store object into my main.js. Checked by logging it.

Added store to my vue instance, but I cannot access it through this.$store in my components.

Error - Error in v-on handler (Promise/async): "TypeError: Cannot read
properties of undefined (reading 'error')"

console.log(this.$store) in my components returns undefined.

codesandbox link -  https://codesandbox.io/s/vdr5js

store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  strict: true,
  state: {
    token: null,
    user: null,
    isUserLoggedin: false
  },
  mutations: {
    setToken (state, token) {
      state.token = token
      if (token) {
        state.isUserLoggedIn = true
      } else {
        state.isUserLoggedIn = false
      }
    },
    setUser (state, user) {
      state.user = user
    }
  },
  actions: {
    setToken ({commit}, token) {
      commit('setToken', token)
    },
    setUser ({commit}, user) {
      commit('setUser', user)
    }
  }
})

main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an
alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import Vuetify from 'vuetify'
import { sync } from 'vuex-router-sync'
import 'vuetify/dist/vuetify.min.css'
import store from '@/store/store'

Vue.config.productionTip = false

console.log(store) // returns store object

Vue.use(Vuetify)

sync(store, router)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,
  router,
  vuetify: new Vuetify(),
  components: { App },
  template: '<App/>'
})

Login component

I can access this.$router and this.$store in the Header.vue component
Please tell me if I am doing something wrong.


问:
HTML not updating when rendering tubostream in Rails 7 for a custom controller method
I am running Rails 7.0.4 and attempting to use turboframe/tubostream with a customer controller. I am trying to add an error message to the screen when the field from the form is not updated. The custom controller update method is triggered by a stimulus function when the user clicks out of a form field. The controller methods works in that the controller receives that data and the database is updated, however the changes to the page never occur.

I do not receive any errors in my development log. In fact I think what I'm seeing is what I think should likely be seeing - that it's rendering the turbostream and the partial referenced in the turbostream file. One thing I'm wondering though is why it says it's rendering the turbostream file twice:

```<code>20:55:37 web.1    |   TRANSACTION (0.2ms)  ROLLBACK
20:55:37 web.1    |   ↳ app/controllers/organization_controller.rb:34:in `api_update'
20:55:37 web.1    |   Rendering organization/organization_edit_form_error.turbo_stream.erb
20:55:37 web.1    |   Rendered organization/_error.html.erb (Duration: 0.5ms | Allocations: 134)
20:55:37 web.1    |   Rendered organization/organization_edit_form_error.turbo_stream.erb (Duration: 0.9ms | Allocations: 272)
20:55:37 web.1    | Completed 200 OK in 37ms (Views: 1.6ms | ActiveRecord: 4.0ms | Allocations: 10991)
</code>```

In my Network tab in my developer console, I see this which is also what I believe I should be seeing:

```<code><turbo-stream action="replace" target="organization_715728df-0095-4dae-b2c4-9b6911003bfd_error"><template>    test
    <div role="alert">
      Could not edit organization due to the following issues:
      <ul>
          <li>Website is not a valid URL</li>
      </ul>
    </div>
</template></turbo-stream>

</code>```

The concerned files that I'm working with:

controllers/organization_controller.rb (abbreviated)

```<code>  class OrganizationController < ApplicationController
    def api_update
      if organization.update(api_organization_params)
        respond_to do |format|
          format.html { render :edit, organization: @organization }
        end
      else
        respond_to do |format|
          format.turbo_stream { render :organization_edit_form_error }
        end
      end
    end
  end
</code>```

/views/organization/edit.html.erb

```<code><div data-controller="organizations" class="mt-10">

    <%= turbo_frame_tag "#{dom_id(@organization)}_error" do %>
      <%= render partial: 'error', organization: @organization %>
    <% end %>

    <%= render 'form', organization: @organization %>
</div>

</code>```

/views/organization/organization_edit_form_error.turbo_stream.erb

```<code><%= turbo_stream.replace "#{dom_id(@organization)}_error", partial: "error", organization: @organization %>
</code>```

/views/organization/_error.html.erb

```<code>  <% if @organization.errors.any? %>
    <div role="alert">
      Could not edit organization due to the following issues:
      <ul>
        <% @organization.errors.each do |error| %>
          <li><%= error.full_message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>
</code>```

I tried adding a test output into the _error.html.erb partial within the if @organization.errors.any? block and seeing if the @organization is actually present and contains errors. It is indeed outputting to the Organization errors as expected in my development logs as expected.

I also tried a few different patterns of implementing turbostream from tutorials I saw. In particular, I tried just replacing the element without a turboform wrapper which was of course unsuccessful. I also tried adding the format.html to the respond_to block in my controller since I noticed that many implementations used this, however I'm assuming it's as a fallback.

I am quite new to turbostreams/turboforms and any help would be appreciated.

Body:
I am running Rails 7.0.4 and attempting to use turboframe/tubostream with a customer controller. I am trying to add an error message to the screen when the field from the form is not updated. The custom controller update method is triggered by a stimulus function when the user clicks out of a form field. The controller methods works in that the controller receives that data and the database is updated, however the changes to the page never occur.

I do not receive any errors in my development log. In fact I think what I'm seeing is what I think should likely be seeing - that it's rendering the turbostream and the partial referenced in the turbostream file. One thing I'm wondering though is why it says it's rendering the turbostream file twice:

20:55:37 web.1    |   TRANSACTION (0.2ms)  ROLLBACK
20:55:37 web.1    |   ↳ app/controllers/organization_controller.rb:34:in `api_update'
20:55:37 web.1    |   Rendering organization/organization_edit_form_error.turbo_stream.erb
20:55:37 web.1    |   Rendered organization/_error.html.erb (Duration: 0.5ms | Allocations: 134)
20:55:37 web.1    |   Rendered organization/organization_edit_form_error.turbo_stream.erb (Duration: 0.9ms | Allocations: 272)
20:55:37 web.1    | Completed 200 OK in 37ms (Views: 1.6ms | ActiveRecord: 4.0ms | Allocations: 10991)

In my Network tab in my developer console, I see this which is also what I believe I should be seeing:

<turbo-stream action="replace" target="organization_715728df-0095-4dae-b2c4-9b6911003bfd_error"><template>    test

      Could not edit organization due to the following issues:

Website is not a valid URL

</template></turbo-stream>

The concerned files that I'm working with:

controllers/organization_controller.rb (abbreviated)

  class OrganizationController < ApplicationController
    def api_update
      if organization.update(api_organization_params)
        respond_to do |format|
          format.html { render :edit, organization: @organization }
        end
      else
        respond_to do |format|
          format.turbo_stream { render :organization_edit_form_error }
        end
      end
    end
  end

/views/organization/edit.html.erb

    <%= turbo_frame_tag "#{dom_id(@organization)}_error" do %>
      <%= render partial: 'error', organization: @organization %>
    <% end %>

    <%= render 'form', organization: @organization %>

/views/organization/organization_edit_form_error.turbo_stream.erb

<%= turbo_stream.replace "#{dom_id(@organization)}_error", partial: "error", organization: @organization %>

/views/organization/_error.html.erb

  <% if @organization.errors.any? %>

      Could not edit organization due to the following issues:

        <% @organization.errors.each do |error| %>

<%= error.full_message %>

        <% end %>

  <% end %>

I tried adding a test output into the _error.html.erb partial within the if @organization.errors.any? block and seeing if the @organization is actually present and contains errors. It is indeed outputting to the Organization errors as expected in my development logs as expected.

I also tried a few different patterns of implementing turbostream from tutorials I saw. In particular, I tried just replacing the element without a turboform wrapper which was of course unsuccessful. I also tried adding the format.html to the respond_to block in my controller since I noticed that many implementations used this, however I'm assuming it's as a fallback.

I am quite new to turbostreams/turboforms and any help would be appreciated.


问:
How to get dimensions from a stp (AP242) file?
I have created dimensions in creo for a prt and successfully exported step files using AP242 protocol and I able to see dimension both in creo file and step file (refer image  )

I want to read dimension from creo and stp file and below is the logic and apis used to get dimensions from creo

Note:

Could you please let me know does the API ProSolidDimensionVisit gives the dimension for step file If not
If not then could please let me know which API I should use to get dimension for both Creo and Step files.

I have used ProSolidDimensionVisit  API to get the dimensions.
This API gives a callback to test_DimVisitAction callback function whenever any dimension is found in the model.

test_DimVisitAction - A self written callback function,
whenever we get a dimension this callback function gets called. APIs used inside these functions are:

ProAnnotationIsShown

ProDimensionSymbolGet

ProDimensionValueGet

ProDimensionTypeGet

The idea in general is that if someone sends to me an STP file, I should be able to extract the dimensions automatically in this file


问:
Below piece of code is not deleting records but the records are deleted from the query when run manually
```<code>  def complete_stage_purge_process(self, target_cnxn, stage_table, process_cd):
    self.logger.debug(datetime.now())
    self.logger.debug('complete_stage_purge_process')
    delete_dt = datetime.today() - timedelta(days=30)
    delete_dt = str(delete_dt)
    run_pk_sql = "select run_pk from " + schemaName.PROCESS.value + "." + tableName.RUN_LOG.value + " where " + ProcessRunlog.ETL_MODIFIED_DTM.value + " <= '" + delete_dt + "' and " + \
        ProcessRunlog.PROCESS_PK.value + " =  (select " + ProcessRunlog.PROCESS_PK.value + " from " + schemaName.PROCESS.value + "." + \
        tableName.PROCESS.value + " where " + \
        Process.PROCESS_CODE.value + " =  '" + process_cd + "') "
    delete_sql = "delete from " + schemaName.STAGE.value + "." + stage_table + " where run_pk in (" + run_pk_sql + ")"
    print(delete_sql)
    print(target_cnxn)
    try:
        trgt_cursor = target_cnxn.cursor()
        trgt_cursor.execute(delete_sql)
        self.logger.debug("deletes processed successfully ")
    except:
        self.logger.exception('Error in processing deletes')
        raise
</code>```

But when added commit after trgt_cursor.execute(delete_sql) then below error is thrown. Could someone please help on how to handle this
AttributeError: 'psycopg2.extensions.cursor' object has no attribute 'commit'

Body:
  def complete_stage_purge_process(self, target_cnxn, stage_table, process_cd):
    self.logger.debug(datetime.now())
    self.logger.debug('complete_stage_purge_process')
    delete_dt = datetime.today() - timedelta(days=30)
    delete_dt = str(delete_dt)
    run_pk_sql = "select run_pk from " + schemaName.PROCESS.value + "." + tableName.RUN_LOG.value + " where " + ProcessRunlog.ETL_MODIFIED_DTM.value + " <= '" + delete_dt + "' and " + \
        ProcessRunlog.PROCESS_PK.value + " =  (select " + ProcessRunlog.PROCESS_PK.value + " from " + schemaName.PROCESS.value + "." + \
        tableName.PROCESS.value + " where " + \
        Process.PROCESS_CODE.value + " =  '" + process_cd + "') "
    delete_sql = "delete from " + schemaName.STAGE.value + "." + stage_table + " where run_pk in (" + run_pk_sql + ")"
    print(delete_sql)
    print(target_cnxn)
    try:
        trgt_cursor = target_cnxn.cursor()
        trgt_cursor.execute(delete_sql)
        self.logger.debug("deletes processed successfully ")
    except:
        self.logger.exception('Error in processing deletes')
        raise

But when added commit after trgt_cursor.execute(delete_sql) then below error is thrown. Could someone please help on how to handle this
AttributeError: 'psycopg2.extensions.cursor' object has no attribute 'commit'


问:
Echarts in the Windows on the touch screen computer, double refers to zoom
Echarts how to implement used on Windows touch-screen computer like in the mobile terminal can double refers to the zoom function

```<code> dataZoom: [
          {
            xAxisIndex: [0, 1],
            type: 'inside',
          }
}
</code>```

The pattern on the Windows touch-screen computer can not use a touch screen zoom function, in the mobile terminal is normal use, how to implement this feature in Windows touch-screen computer?

Body:
Echarts how to implement used on Windows touch-screen computer like in the mobile terminal can double refers to the zoom function

 dataZoom: [
          {
            xAxisIndex: [0, 1],
            type: 'inside',
          }
}

The pattern on the Windows touch-screen computer can not use a touch screen zoom function, in the mobile terminal is normal use, how to implement this feature in Windows touch-screen computer?


问:
Why is my TextInput out of sync with state when I give rapid inputs?
I'm creating a typing race game with React Native which is producing an unexpected bug on Android.

When the user finishes typing a word/spacebar, I set the input state to an empty string.

However, if the user finishes typing a word/spacebar then immediately presses the first letter of the next word/spacebar, the onChangeText event returns the state which existed prior to setting it to a empty string, along with the new letter. It should instead return the new letter by itself.

The bug only occurs when typing very quickly on Android (emulator and real device), IOS hasn't been tested, and the web app works fine typing at any speed.

Snack to try it yourself with complete code: https://snack.expo.dev/@ariato/typing-race-bug-example?platform=android

```<code>const Race = () => {
  const [input, setInput] = useState("");
  const [wordIndex, setWordIndex] = useState(0);
  const [letterIndex, setLetterIndex] = useState(0);
  const [errorLength, setErrorLength] = useState(0);

  const totalIndex = getTotalIndex(wordIndex, letterIndex);

  const onChange = (val: string) => {
    setInput(val);
    checkInput(val);
  };

  const checkInput = (val: string) => {
    const inputLength: number = val.length;
    const answer = wordList[wordIndex].substring(0, inputLength);

    if (val === answer) {
      setErrorLength(0);
      if (val === wordList[wordIndex]) {
        const isLastWord = wordIndex === wordList.length - 1;
        if (isLastWord) {
          setWordIndex(0);
        } else {
          setWordIndex((wordIndex) => wordIndex + 1);
        }
        setLetterIndex(0);
        setInput("");
      } else {
        setLetterIndex(inputLength);
      }
    } else {
      setErrorLength(inputLength - letterIndex);
    }
  };

  return (
    <KeyboardAvoidingView
      style={styles.container}
      behavior={Platform.OS === "ios" ? "padding" : "height"}
    >
      <View style={styles.textContainer}>
        {wordList.map((word, wordIdx) => (
          <Text key={wordIdx}>
            {word.split("").map((letter, letterIdx) => (
              <Text key={letterIdx} style={getStyles(wordIdx, letterIdx)}>
                {letter}
              </Text>
            ))}
          </Text>
        ))}
      </View>
      <TextInput
        value={input}
        onChangeText={onChange}
        autoCapitalize="none"
        autoComplete="off"
        autoCorrect={false}
        spellCheck={false}
        importantForAutofill="no"
        autoFocus
        keyboardType="visible-password"
        style={styles.textInput}
      />
    </KeyboardAvoidingView>
  );
};

export default Race;
</code>```

This screenshot is after typing It', and then typing s and a spacebar in rapid succession. The next character to type is underlined. For each incorrect character in the input there is a red letter.

These logs show how the input state is set to an empty string, then becomes It's_ in one key stroke, as though the internal state of the TextInput did not get changed to an empty string.

I tried:

Moving the first setInput() in the onChange() to the if/else statements in checkInput() so that it would only trigger once per event, in case something strange was happening with setState() batching. No change, as expected.

Body:
I'm creating a typing race game with React Native which is producing an unexpected bug on Android.

When the user finishes typing a word/spacebar, I set the input state to an empty string.

However, if the user finishes typing a word/spacebar then immediately presses the first letter of the next word/spacebar, the onChangeText event returns the state which existed prior to setting it to a empty string, along with the new letter. It should instead return the new letter by itself.

The bug only occurs when typing very quickly on Android (emulator and real device), IOS hasn't been tested, and the web app works fine typing at any speed.

Snack to try it yourself with complete code: https://snack.expo.dev/@ariato/typing-race-bug-example?platform=android

const Race = () => {
  const [input, setInput] = useState("");
  const [wordIndex, setWordIndex] = useState(0);
  const [letterIndex, setLetterIndex] = useState(0);
  const [errorLength, setErrorLength] = useState(0);

  const totalIndex = getTotalIndex(wordIndex, letterIndex);

  const onChange = (val: string) => {
    setInput(val);
    checkInput(val);
  };

  const checkInput = (val: string) => {
    const inputLength: number = val.length;
    const answer = wordList[wordIndex].substring(0, inputLength);

    if (val === answer) {
      setErrorLength(0);
      if (val === wordList[wordIndex]) {
        const isLastWord = wordIndex === wordList.length - 1;
        if (isLastWord) {
          setWordIndex(0);
        } else {
          setWordIndex((wordIndex) => wordIndex + 1);
        }
        setLetterIndex(0);
        setInput("");
      } else {
        setLetterIndex(inputLength);
      }
    } else {
      setErrorLength(inputLength - letterIndex);
    }
  };

  return (
    <KeyboardAvoidingView
      style={styles.container}
      behavior={Platform.OS === "ios" ? "padding" : "height"}
    >
      <View style={styles.textContainer}>
        {wordList.map((word, wordIdx) => (
          <Text key={wordIdx}>
            {word.split("").map((letter, letterIdx) => (
              <Text key={letterIdx} style={getStyles(wordIdx, letterIdx)}>
                {letter}
              </Text>
            ))}
          </Text>
        ))}
      </View>
      <TextInput
        value={input}
        onChangeText={onChange}
        autoCapitalize="none"
        autoComplete="off"
        autoCorrect={false}
        spellCheck={false}
        importantForAutofill="no"
        autoFocus
        keyboardType="visible-password"
        style={styles.textInput}
      />
    </KeyboardAvoidingView>
  );
};

export default Race;

This screenshot is after typing It', and then typing s and a spacebar in rapid succession. The next character to type is underlined. For each incorrect character in the input there is a red letter.

These logs show how the input state is set to an empty string, then becomes It's_ in one key stroke, as though the internal state of the TextInput did not get changed to an empty string.

I tried:

Moving the first setInput() in the onChange() to the if/else statements in checkInput() so that it would only trigger once per event, in case something strange was happening with setState() batching. No change, as expected.


Title: How can I output a shiny interactive plot to RMarkdown HTML

Body:
I am looking at the distribution of multiple invoice types for 5 financial years and want to filter the histogram by the financial year while the plot is separated by invoice type via facet_grid

I have included the mean as a geom_vline to understand the distribution better, and by creating a static graph through ggplot and manually filtering the financial year, the plot is accurate.

The plot acts as intended in the RStudio Viewer, yet the html document output does not show the plot, and the end users do not have access to RStudio to view through the viewer

library(tidyverse)
library(shiny)

**test data**

test <- structure(list(`FY Year` = structure(c(22L, 21L, 20L, 22L, 19L,
19L, 19L, 18L, 21L, 19L, 21L, 21L, 20L, 18L, 20L, 21L, 19L, 20L,
18L, 19L, 21L, 20L, 21L, 18L, 20L, 19L, 18L, 18L, 18L, 20L, 19L,
18L, 21L, 21L, 19L, 19L, 20L, 19L, 18L, 20L, 21L, 20L, 19L, 20L,
21L, 18L, 21L, 19L, 20L, 21L, 19L, 20L, 18L, 21L, 20L, 21L, 19L,
20L, 21L, 21L, 20L, 21L, 18L, 18L, 19L, 19L, 20L, 21L, 20L, 18L,
18L, 21L, 18L, 20L, 21L, 19L, 18L, 18L, 21L, 22L, 18L, 20L, 20L,
19L, 20L, 20L, 20L, 20L, 19L, 18L, 21L, 20L, 21L, 21L, 21L, 19L,
19L, 20L, 20L, 18L, 19L, 20L, 22L, 20L, 18L, 21L, 18L, 21L, 20L,
19L, 19L, 20L, 19L, 21L, 20L, 21L, 20L, 20L, 18L, 20L, 21L, 18L,
20L, 22L, 20L, 22L, 19L, 18L, 21L, 20L, 21L, 21L, 21L, 21L, 20L,
19L, 21L, 19L, 21L, 19L, 21L, 21L, 21L, 19L, 21L, 21L, 22L, 18L,
21L, 18L, 19L, 19L, 19L, 21L, 22L, 21L, 18L, 22L, 18L, 20L, 21L,
18L, 20L, 20L, 21L, 18L, 20L, 19L, 21L, 22L, 20L, 19L, 19L, 18L,
20L, 20L, 22L, 18L, 22L, 21L, 21L, 19L, 21L, 21L, 19L, 21L, 21L,
21L, 21L, 22L, 20L, 18L, 18L, 21L, 18L, 21L, 22L, 18L, 21L, 21L
), levels = c("1900", "2003", "2004", "2005", "2006", "2007",
"2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015",
"2016", "2017", "2018", "2019", "2020", "2021", "2022", "2023"
), class = "factor"), number_of_days = c(2, 3, 0, 3, 21, 14,
0, 0, 5, 5, 13, 19, 3, 14, 3, 6, 0, 32, 0, 4, 2, 13, 1, 4, 11,
12, 22, 4, 1, 16, -1, 12, 7, 5, 14, 0, 0, 4, 0, 7, 4, 0, 8, 0,
6, 1, 29, 35, 3, 0, -7, 0, 1, 0, 19, 13, 5, 6, -1, 1, 14, 25,
0, 7, 3, 2, 1, 10, 6, 5, 0, 38, 25, 3, 3, -1, 18, 7, 13, 10,
26, 7, 0, 6, 4, 7, 7, 3, 0, 0, 7, 5, 0, 0, -2, 0, 3, 0, 33, 9,
36, 12, 4, 0, 3, 35, 20, 7, 0, 4, 6, 1, 5, 7, 10, 2, 16, 37,
0, 0, 12, 43, 3, 4, 14, 0, 3, 7, 1, 0, 5, 4, 4, 3, 11, 5, 0,
10, 4, 21, 9, 17, 19, 0, 3, 13, 4, 35, 6, 7, 18, 1, 1, 14, 3,
7, 10, 1, 14, 1, -1, -1, 6, -15, 3, 10, 24, 1, 3, -1, 33, 6,
11, 40, 11, 10, 3, 4, 12, 13, 8, 8, -2, 4, 7, 0, 25, 35, 20,
3, 4, 0, 6, 11, 0, 38, 7, 10, 6, 21), Invoice_type_name = c("Other",
"Footings", "Final", "Contract Signing", "Final", "Footings",
"Contract Signing", "Contract Signing", "Roofing", "Framing",
"Roofing", "Footings", "Framing", "Framing", "Initial Work Deposit",
"2nd Fix Carpentry", "Final", "2nd Fix Carpentry", "Final", "Framing",
"Contract Signing", "Framing", "Contract Signing", "Linings",
"Roofing", "Framing", "Other", "Footings", "Initial Work Deposit",
"Final", "Contract Signing", "Framing", "Linings", "Framing",
"Framing", "Contract Signing", "Initial Work Deposit", "Footings",
"Initial Work Deposit", "Linings", "Contract Signing", "Initial Work Deposit",
"Initial Work Deposit", "Contract Signing", "Framing", "Contract Signing",
"Other", "Framing", "Roofing", "Contract Signing", "Initial Work Deposit",
"Linings", "Contract Signing", "Framing", "Framing", "Roofing",
"Linings", "Linings", "Contract Signing", "Initial Work Deposit",
"Footings", "2nd Fix Carpentry", "2nd Fix Carpentry", "Initial Work Deposit",
"Footings", "Contract Signing", "Final", "Framing", "Initial Work Deposit",
"Initial Work Deposit", "Contract Signing", "Footings", "Footings",
"2nd Fix Carpentry", "2nd Fix Carpentry", "Initial Work Deposit",
"Contract Signing", "Linings", "Footings", "Roofing", "Roofing",
"Footings", "Initial Work Deposit", "Roofing", "Framing", "Framing",
"Contract Signing", "Footings", "Initial Work Deposit", "Initial Work Deposit",
"Contract Signing", "Linings", "Initial Work Deposit", "Contract Signing",
"Contract Signing", "Initial Work Deposit", "Initial Work Deposit",
"Initial Work Deposit", "Linings", "Final", "Final", "2nd Fix Carpentry",
"Initial Work Deposit", "Initial Work Deposit", "Linings", "2nd Fix Carpentry",
"Linings", "Footings", "Initial Work Deposit", "Linings", "Linings",
"Initial Work Deposit", "Linings", "Framing", "Framing", "2nd Fix Carpentry",
"Framing", "Final", "Initial Work Deposit", "Initial Work Deposit",
"2nd Fix Carpentry", "Final", "Initial Work Deposit", "Contract Signing",
"2nd Fix Carpentry", "Initial Work Deposit", "Initial Work Deposit",
"Footings", "Initial Work Deposit", "Contract Signing", "Roofing",
"Framing", "Footings", "Initial Work Deposit", "Framing", "Footings",
"Initial Work Deposit", "Footings", "Roofing", "Framing", "Roofing",
"Linings", "Linings", "Contract Signing", "Framing", "Initial Work Deposit",
"Footings", "Final", "Contract Signing", "Footings", "Footings",
"Initial Work Deposit", "Initial Work Deposit", "Linings", "Roofing",
"Framing", "Linings", "Initial Work Deposit", "Framing", "Final",
"Initial Work Deposit", "Contract Signing", "2nd Fix Carpentry",
"Contract Signing", "Footings", "Linings", "Roofing", "Initial Work Deposit",
"2nd Fix Carpentry", "Contract Signing", "Final", "Linings",
"Linings", "Linings", "Roofing", "Final", "Framing", "Final",
"Linings", "Footings", "Final", "Contract Signing", "Initial Work Deposit",
"Linings", "Initial Work Deposit", NA, "Roofing", "Linings",
"Footings", "Footings", "2nd Fix Carpentry", "Initial Work Deposit",
"Framing", "Footings", "Contract Signing", "Roofing", "Linings",
"Linings", "Linings", "Footings")), row.names = c(NA, -200L), class = "data.frame")

stat <- test %>%
  group_by(Invoice_type_name, `FY Year`) %>%
  summarise(
    mean = mean(number_of_days)
  )

selectInput("financialYear", label = "Financial Year", selected = "2019",
            choices = c("2019", "2020", "2021", "2022", "2023"))

renderPlot({
  test %>%
    filter(`FY Year` == input$financialYear) %>%
    ggplot(aes(x = `number_of_days`)) +
    geom_histogram() +

    geom_vline(data = (stat %>%
                 filter(`FY Year` == input$financialYear)),
               aes(xintercept = mean),
               linewidth = 1) +
    facet_grid(rows = vars(Invoice_type_name), scales = "free")},

  outputArgs = list(width = "100%", height = "1000px")
  )

Manually entered the financial year filter

Shiny interactive plot, selecting the filtered year

HTML output after rendering