问:
Change child widget of parent | Flutter
I'm coming to the point when state management have to be handled in my applications, even if I just started to learn more about it when I red through the question being similar to my title.

I want to learn state management and the including things by having a clean solution for my following code:

This is my Parent Widget. However I wan't to pass data coming from the SideMenu in order to manage the WidgetDependingOnSideMenu Widget. To be clear: When I press on a SideMenuItem at my SideMenu class, the child (of the second Expanded in my MainScreen) should change to another one given by the SideMenuItem (onClick function).

```<code>class MainScreen extends StatelessWidget {
  // final GlobalKey<SideMenuState> _key = GlobalKey();

  @override
  Widget build(BuildContext context) {
    Size _size = MediaQuery.of(context).size;
    return Scaffold(
      body: Responsive(
        desktop: Row(
          children: [
            Expanded(flex: _size.width > 1340 ? 2 : 4, child: SideMenu()),
            Expanded(
                flex: _size.width > 1340 ? 3 : 5, child: WidgetDependingOnSideMenu()),
            Expanded(flex: _size.width > 1340 ? 8 : 10, child: Container()),
          ],
        ),
      ),
    );
  }
}
</code>```

This is my SideMenuItem. The function toggleActiveState is called when I click on the SideMenuItem. As already explained, at this point the parent should receive the information that it have to change some child in his class.

```<code>            SideMenuItem(
                icon: Icon(
                  Icons.inbox,
                  size: 20,
                  color: isActiveList[0] ? kPrimaryColor : kGrayColor,
                ),
                activeState: isActive,
                textColor: isActiveList[0] ? kTextColor : kGrayColor,
                title: "Bestellungen",
                toggleActiveState: (activeState) {
                  clearIsActiveList();
                  setState(() {
                    isActiveList[0] = !activeState;
                  });
                }),
</code>```

Well, I hope I can turn into that topic by having a clean solution. If you need any more information tell me. Just enough for today, have a nice evening.
Thanks

答:
I found a solution for my problem with the following video:
https://www.youtube.com/watch?v=A1qu8X7f36k

First of all I made use of the Provider Package:
https://pub.dev/packages/provider

Then I created following class with a ChangeNotifier in my SideMenu:

```<code>class ActiveWidgetNotifier extends ChangeNotifier {
  Widget activeWidget = Bestellungen();
  void changeActiveWidget(Widget newWidget) {
    activeWidget = newWidget;
    notifyListeners();
  }
}
</code>```

onPressed at the Button:

```<code>Provider.of<ActiveWidgetNotifier>(context, listen: false)
                      .changeActiveWidget(NewWidgetThatShouldBeDisplayed());
</code>```

Then I added following code at my parent in order to display the changed child:

```<code>            Expanded(
                flex: 3,
                child: Provider.of<ActiveWidgetNotifier>(context).activeWidget),
</code>```

Finally added a ChangeNotifierProvider at my main.dart:

```<code>void main() {
  runApp(ChangeNotifierProvider(
      create: (_) => ActiveWidgetNotifier(), child: App()));
}
</code>```

And all you have to is restarting you application in order to keep errors away. That's worked for me.

Title: Change child widget of parent | Flutter

Body:
I'm coming to the point when state management have to be handled in my applications, even if I just started to learn more about it when I red through the question being similar to my title.

I want to learn state management and the including things by having a clean solution for my following code:

This is my Parent Widget. However I wan't to pass data coming from the SideMenu in order to manage the WidgetDependingOnSideMenu Widget. To be clear: When I press on a SideMenuItem at my SideMenu class, the child (of the second Expanded in my MainScreen) should change to another one given by the SideMenuItem (onClick function).

class MainScreen extends StatelessWidget {
  // final GlobalKey<SideMenuState> _key = GlobalKey();

  @override
  Widget build(BuildContext context) {
    Size _size = MediaQuery.of(context).size;
    return Scaffold(
      body: Responsive(
        desktop: Row(
          children: [
            Expanded(flex: _size.width > 1340 ? 2 : 4, child: SideMenu()),
            Expanded(
                flex: _size.width > 1340 ? 3 : 5, child: WidgetDependingOnSideMenu()),
            Expanded(flex: _size.width > 1340 ? 8 : 10, child: Container()),
          ],
        ),
      ),
    );
  }
}

This is my SideMenuItem. The function toggleActiveState is called when I click on the SideMenuItem. As already explained, at this point the parent should receive the information that it have to change some child in his class.

            SideMenuItem(
                icon: Icon(
                  Icons.inbox,
                  size: 20,
                  color: isActiveList[0] ? kPrimaryColor : kGrayColor,
                ),
                activeState: isActive,
                textColor: isActiveList[0] ? kTextColor : kGrayColor,
                title: "Bestellungen",
                toggleActiveState: (activeState) {
                  clearIsActiveList();
                  setState(() {
                    isActiveList[0] = !activeState;
                  });
                }),

Well, I hope I can turn into that topic by having a clean solution. If you need any more information tell me. Just enough for today, have a nice evening.
Thanks

Body:
I found a solution for my problem with the following video:
https://www.youtube.com/watch?v=A1qu8X7f36k

First of all I made use of the Provider Package:
https://pub.dev/packages/provider

Then I created following class with a ChangeNotifier in my SideMenu:

class ActiveWidgetNotifier extends ChangeNotifier {
  Widget activeWidget = Bestellungen();
  void changeActiveWidget(Widget newWidget) {
    activeWidget = newWidget;
    notifyListeners();
  }
}

onPressed at the Button:

Provider.of<ActiveWidgetNotifier>(context, listen: false)
                      .changeActiveWidget(NewWidgetThatShouldBeDisplayed());

Then I added following code at my parent in order to display the changed child:

            Expanded(
                flex: 3,
                child: Provider.of<ActiveWidgetNotifier>(context).activeWidget),

Finally added a ChangeNotifierProvider at my main.dart:

void main() {
  runApp(ChangeNotifierProvider(
      create: (_) => ActiveWidgetNotifier(), child: App()));
}

And all you have to is restarting you application in order to keep errors away. That's worked for me.


来源: stackexchange

问:
How to detect the language of text using qt?
I have a lot of txt files containing product description written in English or other languages. I'm only interested in the txt files containing English. I do not know all the languages the txt may be written in. Those non-English description may also contain English characters such as a url. Is there any algorithm to calculate the ratio of English characters (excluding punctuation) so that if there are more than 50% non-English characters in the txt file, the file will be discarded.</p>

答:
We had a requirement to detect the language used in a given string.

We chose to use the first 5 characters of the string for determining the language:

Parse the first 5 characters and store the highest Unicode value.

Check this highest Unicode value against the known Unicode ranges of the languages.

Whichever language's range matches with the value, that's the language.

Obviously this solution isn't 100% accurate, but, it solved our purposes.

For your case, choose any length of characters for determining if the language is English.

Find the highest Unicode value of these characters.

Check this highest value against the Unicode ranges of English(Latin).

If it is within the ranges, you may conclude that the language is English.

ContentLicense: CC BY-SA 4.0


问:
How to add copy link location in custom context menu
I'm developing an asp.net mvc 3 web application. Here I need to add custom context menu. So I have disabled the default right click context and added a plugin for custom context menu.

I'm trying to add an item in the custom menu, namely: "Copy link location". Which is available in browsers.

However the problem is, how can I detect that the user right clicked on a html link? Because the context menu appears by clicking anywhere on the webpage. And
also, how can I copy that specific link location? What is the javascript behind getting a link location from a document?

答:
See Dynamic Right Click Context Menu for adding custom right click context menu.

For getting the URL of the link you have selected, all you need to get is

anchor.getAttribute("href")

ContentLicense: CC BY-SA 3.0


问:
java.lang.IllegalStateException - at com.google.common.base.Preconditions.checkState(Preconditions.java:443)
I did not touch my code for months, and today all of a sudden it just don't compile.

Which is marvelous because the client is waiting for my work and I'm in no control of this fault.

I tried the following:

Deleting gradle

Clean project

Rebuild project

Install older Android Studio version

Restart AS

Restart PC

Removing libs

None of these worked.

Please help me if you can.

This is the only error message I get:

```<code>java.lang.IllegalStateException
    at com.google.common.base.Preconditions.checkState(Preconditions.java:443)
    at com.android.build.gradle.internal.BuildSessionImpl.buildFinished(BuildSessionImpl.java:198)
    at com.android.build.gradle.internal.BuildSessionImpl.access$000(BuildSessionImpl.java:61)
    at com.android.build.gradle.internal.BuildSessionImpl$1.buildFinished(BuildSessionImpl.java:172)
    at jdk.internal.reflect.GeneratedMethodAccessor58.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.event.DefaultListenerManager$ListenerDetails.dispatch(DefaultListenerManager.java:370)
    at org.gradle.internal.event.DefaultListenerManager$ListenerDetails.dispatch(DefaultListenerManager.java:352)
    at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:58)
    at org.gradle.internal.event.DefaultListenerManager$EventBroadcast$ListenerDispatch.dispatch(DefaultListenerManager.java:340)
    at org.gradle.internal.event.DefaultListenerManager$EventBroadcast$ListenerDispatch.dispatch(DefaultListenerManager.java:327)
    at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:42)
    at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:230)
    at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:149)
    at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:58)
    at org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:324)
    at org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:234)
    at org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:140)
    at org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:37)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy18.buildFinished(Unknown Source)
    at org.gradle.initialization.DefaultGradleLauncher.finishBuild(DefaultGradleLauncher.java:158)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:144)
    at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:115)
    at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:77)
    at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:74)
    at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:152)
    at org.gradle.internal.work.StopShieldingWorkerLeaseService.withLocks(StopShieldingWorkerLeaseService.java:38)
    at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:96)
    at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:74)
    at org.gradle.tooling.internal.provider.runner.ClientProvidedPhasedActionRunner.run(ClientProvidedPhasedActionRunner.java:61)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
    at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$3.run(RunAsBuildOperationBuildActionRunner.java:47)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:317)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:309)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:185)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:97)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:43)
    at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$1.transform(InProcessBuildActionExecuter.java:50)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$1.transform(InProcessBuildActionExecuter.java:46)
    at org.gradle.composite.internal.DefaultRootBuildState.run(DefaultRootBuildState.java:65)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:46)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:32)
    at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
    at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:80)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:53)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:62)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:34)
    at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
    at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
    at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
    at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
    at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:59)
    at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:31)
    at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:59)
    at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:44)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:46)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:30)
    at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
    at org.gradle.util.Swapper.swap(Swapper.java:38)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:82)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:295)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
</code>```

答:
Try to upgrade Gradle and Gradle Plugin versions, like this:</p>
```<code> classpath 'com.android.tools.build:gradle:7.1.1'
 distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
</code>```

Body:
I did not touch my code for months, and today all of a sudden it just don't compile.

Which is marvelous because the client is waiting for my work and I'm in no control of this fault.

I tried the following:

Deleting gradle

Clean project

Rebuild project

Install older Android Studio version

Restart AS

Restart PC

Removing libs

None of these worked.

Please help me if you can.

This is the only error message I get:

java.lang.IllegalStateException
    at com.google.common.base.Preconditions.checkState(Preconditions.java:443)
    at com.android.build.gradle.internal.BuildSessionImpl.buildFinished(BuildSessionImpl.java:198)
    at com.android.build.gradle.internal.BuildSessionImpl.access$000(BuildSessionImpl.java:61)
    at com.android.build.gradle.internal.BuildSessionImpl$1.buildFinished(BuildSessionImpl.java:172)
    at jdk.internal.reflect.GeneratedMethodAccessor58.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.event.DefaultListenerManager$ListenerDetails.dispatch(DefaultListenerManager.java:370)
    at org.gradle.internal.event.DefaultListenerManager$ListenerDetails.dispatch(DefaultListenerManager.java:352)
    at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:58)
    at org.gradle.internal.event.DefaultListenerManager$EventBroadcast$ListenerDispatch.dispatch(DefaultListenerManager.java:340)
    at org.gradle.internal.event.DefaultListenerManager$EventBroadcast$ListenerDispatch.dispatch(DefaultListenerManager.java:327)
    at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:42)
    at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:230)
    at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:149)
    at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:58)
    at org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:324)
    at org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:234)
    at org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:140)
    at org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:37)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy18.buildFinished(Unknown Source)
    at org.gradle.initialization.DefaultGradleLauncher.finishBuild(DefaultGradleLauncher.java:158)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:144)
    at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:115)
    at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:77)
    at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:74)
    at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:152)
    at org.gradle.internal.work.StopShieldingWorkerLeaseService.withLocks(StopShieldingWorkerLeaseService.java:38)
    at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:96)
    at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:74)
    at org.gradle.tooling.internal.provider.runner.ClientProvidedPhasedActionRunner.run(ClientProvidedPhasedActionRunner.java:61)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
    at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$3.run(RunAsBuildOperationBuildActionRunner.java:47)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:317)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:309)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:185)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:97)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:43)
    at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$1.transform(InProcessBuildActionExecuter.java:50)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$1.transform(InProcessBuildActionExecuter.java:46)
    at org.gradle.composite.internal.DefaultRootBuildState.run(DefaultRootBuildState.java:65)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:46)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:32)
    at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
    at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:80)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:53)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:62)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:34)
    at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
    at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
    at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
    at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
    at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:59)
    at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:31)
    at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:59)
    at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:44)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:46)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:30)
    at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
    at org.gradle.util.Swapper.swap(Swapper.java:38)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:82)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:295)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)

Body:
Try to upgrade Gradle and Gradle Plugin versions, like this:

 classpath 'com.android.tools.build:gradle:7.1.1'
 distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip


问:
Azure Devops Wiki Markdown Table Style Background/text color problem
I am trying to color the cells of a table in Azure DevOps Wiki Table
I have this in my markdown

```<code>|Tag|Requied/Optional  |Notes  |Examples  |
|--|--|--|--|
| <td style="background-color:green;color:white;">1</td> | <td style="background-color:green;color:white;">2</td> | <td style="background-color:green;color:white;">3</td> | <td style="background-color:green;color:white;">4</td> |
|  |  |  |  |
|  |  |  |  |
</code>```

but it comes out looking like this

Im trying to figure out why/where the extra cells in between are coming from and how to get rid of them.

答:
You can try it with inline styling

```<code><table style="border:ridge 4px red">
  <tr style="background-color:blue;color:white;" id="ROW1">
    <td style="border:ridge 4px red" >Cell 1.1</td>
    <td style="border:ridge 4px red">Cell 1.2</td>
    <td style="border:ridge 4px red">Cell 1.3</td>
  </tr>
  <tr style="background-color:yellow;color:green;" id="ROW2">
    <td style="border:ridge 4px red">Cell 2.1</td>
    <td style="border:ridge 4px red">Cell 2.2</td>
    <td style="border:ridge 4px red">Cell 2.3</td>
  </tr>
</table>
</code>```

Also please refer this SO thread  How to apply color in Markdown for more information.

Body:
I am trying to color the cells of a table in Azure DevOps Wiki Table
I have this in my markdown

|Tag|Requied/Optional  |Notes  |Examples  |
|--|--|--|--|
| 1	 | 2	 | 3	 | 4	 |
|  |  |  |  |
|  |  |  |  |

but it comes out looking like this

Im trying to figure out why/where the extra cells in between are coming from and how to get rid of them.

Body:
You can try it with inline styling

<table style="border:ridge 4px red">
  <tr style="background-color:blue;color:white;" id="ROW1">
    <td style="border:ridge 4px red" >Cell 1.1</td>
    <td style="border:ridge 4px red">Cell 1.2</td>
    <td style="border:ridge 4px red">Cell 1.3</td>
  </tr>
  <tr style="background-color:yellow;color:green;" id="ROW2">
    <td style="border:ridge 4px red">Cell 2.1</td>
    <td style="border:ridge 4px red">Cell 2.2</td>
    <td style="border:ridge 4px red">Cell 2.3</td>
  </tr>
</table>

Also please refer this SO thread  How to apply color in Markdown for more information.


问:
url path with image variable in image source uri React Native
I am trying to display an Image in which the data was fetch from an api and render into a flatlist, I am trying to concat or connect the sting link with the variable, in the image source uri but did not work, how can I fix it.

```<code><FlatList
data = {data}
keyExtractor={item => item.id}
showsVerticalScrollIndicator = {false}
renderItem={({item}) => {
   return (

    <Image
            source={{ uri: `https://placewave.com/avatar/${item.user_image}` }}
            resizeMode="cover"
            style={styles.userImage}
    />

   )
}}
/>
</code>```

Thanks for the help

答:
Unfortunately it will not work in such way.
Image must not have conditional source prop. Consider moving https://placewave.com/avatar/${item.user_image} to a variable and add condition to display some kind of fallback(like ActivityIndicator) until you will have valid user_image.

Body:
I am trying to display an Image in which the data was fetch from an api and render into a flatlist, I am trying to concat or connect the sting link with the variable, in the image source uri but did not work, how can I fix it.

<FlatList
data = {data}
keyExtractor={item => item.id}
showsVerticalScrollIndicator = {false}
renderItem={({item}) => {
   return (

    <Image
            source={{ uri: `https://placewave.com/avatar/${item.user_image}` }}
            resizeMode="cover"
            style={styles.userImage}
    />

   )
}}
/>

Thanks for the help


问:
Google Doc Api for iPhone App
I have found many links for iPhone project which is implementing the google API but not a single one is in running condition has anyone know the link of any tutorial which can successfully download or upload file from google documents </p>

答:
You can find the Google Docs API over here

The first two sections on that page provide further links to how you can both retrieve and export documents using the API.

You can use any number of third-party libraries such as ASIHttpRequest or AFNetworking to access the API over HTTP, or roll your own using NSURLConnection

Title: Google Doc Api for iPhone App


问:
CXF Enabling GZIP failed at the WSDL loading
I currently have a problem when trying to enable GZIP compression for CXF : the WSDL loading failed because it is compressed and the client part isn't decompressing it.

That means than when I'm doing the following :

```<code>persistenceService = Service.create(
                                new URL(replaceHostAndPort(
                                        getClientServiceConfiguration().getWsMetadataPersistenceService())),
                                new QName("http://metadata.ws.com", "WsMetadataPersistenceService"), gzipFeature);
                        mDefaultMetadataPersistence = persistenceService.getPort(IWsMetadataPersistence.class);
</code>```

The code fail on the Service.create(), so it is not about configuring the ClientProxy.

As far as I could tell in the source code of CFX, the loading of the WSDL doesn't use the feature that I passed on in paramters, neither those that i passed on the default bus using the following configuration :

```<code><bean id="compressGZIPFeature" class="org.apache.cxf.transport.common.gzip.GZIPFeature"/>
<cxf:bus>
    <cxf:features>
         <ref bean="compressGZIPFeature"/>
    </cxf:features>
</cxf:bus>
</code>```

Note : I can see in the instance of bus used by the CXF internal classes that use the bus element, that my feature is there and was propertly initialized (adding in/out interceptors), however I never pass with them when trying to load the WSDL file.

Now I'am a bit stuck : is the WSDL supposed to not be gzipped in the first place ? Then how come it was, or is my problem on the client side ?

On the server side I tried various combinaison of what I could find hoping to only compressed the content of request and not the WSDL to no avail :

@GZIP

XML Bus configuration

@In/OutInterceptors

Form what I understood on the client code of CXF, the InputStream from the HttpUrlConnection is directly handed to the XMLReader to read the WSDL, without using the interceptors (also, the GZIPInterceptor ignore message coming from a GET requests so it should ignore the GET [...]?wsdl aniway. See WSDLManagerImpl.loadDefinition() if you want to check the code.

I'am not sure if it is relevant, I'm under adopte-openjdk 8 and cxf 3.1.7.

答:
I found the solution : I added the compression on the HTTP Conduit, which would make even wsdl request request for GZIP version. The problem is that the WSDL reader doesn't handle the GZIP stream received.

So I had to remove the compression configuration on the client side and use the following code to make sure only SOAP request would be compressed :

```<code>public <T> T createAndConfigureService(Class<? extends T> theServiceClass, Service service){
    T theWebService = service.getPort(theServiceClass);
    Map<String, Object> requestHeaders = new HashMap<>();
    requestHeaders.put("Accept-Encoding", new ArrayList<>(Arrays.asList("gzip")));
    ((BindingProvider)theWebService).getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, requestHeaders);
    Client client = ClientProxy.getClient(theWebService);
    client.getInInterceptors().add(new GZIPInInterceptor());
    return theWebService;
}
</code>```

Body:
I currently have a problem when trying to enable GZIP compression for CXF : the WSDL loading failed because it is compressed and the client part isn't decompressing it.

That means than when I'm doing the following :

persistenceService = Service.create(
                                new URL(replaceHostAndPort(
                                        getClientServiceConfiguration().getWsMetadataPersistenceService())),
                                new QName("http://metadata.ws.com", "WsMetadataPersistenceService"), gzipFeature);
                        mDefaultMetadataPersistence = persistenceService.getPort(IWsMetadataPersistence.class);

The code fail on the Service.create(), so it is not about configuring the ClientProxy.

As far as I could tell in the source code of CFX, the loading of the WSDL doesn't use the feature that I passed on in paramters, neither those that i passed on the default bus using the following configuration :

<bean id="compressGZIPFeature" class="org.apache.cxf.transport.common.gzip.GZIPFeature"/>
<cxf:bus>
    <cxf:features>
         <ref bean="compressGZIPFeature"/>
    </cxf:features>
</cxf:bus>

Note : I can see in the instance of bus used by the CXF internal classes that use the bus element, that my feature is there and was propertly initialized (adding in/out interceptors), however I never pass with them when trying to load the WSDL file.

Now I'am a bit stuck : is the WSDL supposed to not be gzipped in the first place ? Then how come it was, or is my problem on the client side ?

On the server side I tried various combinaison of what I could find hoping to only compressed the content of request and not the WSDL to no avail :

@GZIP

XML Bus configuration

@In/OutInterceptors

Form what I understood on the client code of CXF, the InputStream from the HttpUrlConnection is directly handed to the XMLReader to read the WSDL, without using the interceptors (also, the GZIPInterceptor ignore message coming from a GET requests so it should ignore the GET [...]?wsdl aniway. See WSDLManagerImpl.loadDefinition() if you want to check the code.

I'am not sure if it is relevant, I'm under adopte-openjdk 8 and cxf 3.1.7.

Body:
I found the solution : I added the compression on the HTTP Conduit, which would make even wsdl request request for GZIP version. The problem is that the WSDL reader doesn't handle the GZIP stream received.

So I had to remove the compression configuration on the client side and use the following code to make sure only SOAP request would be compressed :

public <T> T createAndConfigureService(Class<? extends T> theServiceClass, Service service){
    T theWebService = service.getPort(theServiceClass);
    Map<String, Object> requestHeaders = new HashMap<>();
    requestHeaders.put("Accept-Encoding", new ArrayList<>(Arrays.asList("gzip")));
    ((BindingProvider)theWebService).getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, requestHeaders);
    Client client = ClientProxy.getClient(theWebService);
    client.getInInterceptors().add(new GZIPInInterceptor());
    return theWebService;
}


问:
'While' loop is running infinitely even though the condition is false
There is a while loop in line 14. Even if I enter M or F, it still gives the input. It doesn’t continue.

```<code>import array

# Declaration of variables
Constnostudents = int(3)
StudentName = []
StudentGender = []

# Declaration of arrays
StudentMarkTest1 = array.array ("i", range(Constnostudents))
StudentMarktest2 = array.array ("i", range(Constnostudents))

for Counter in range(0, Constnostudents):
    StudentName.append (input("Please enter name of student"))
    StudentGender.append (input("Please enter your gender"))
    while (StudentName[Counter] !="M" or StudentName[Counter] != "F"):
        input("Please enter valid ")

    StudentMarkTest1[Counter] = int(input("Please enter marks for test 1"))
    StudentMarktest2[Counter] = int(input("Please enter marks for test 2"))

print(StudentName)
print(StudentGender)
print(StudentMarkTest1)
print(StudentMarktest2)
</code>```

答:
If you are trying to check if the gender they provided is a valid one, you are giving the wrong value to the while loop. You need to give the "StudentGender" variable and not the "StudentName" variable. Also you are not reassigning the " StudentGender", so it doesn't matter if they are going to provide a valid answer. The loop will continue to run...

You should do:

```<code>while (StudentGender[Counter] !="M" and StudentGender[Counter] != "F"):
       StudentGender[Counter] = input("Please enter valid gender").upper()
</code>```

I also added .upper() to the gender.

For the reason of the "and" instead of "or", look at the comments in your question.

Body:
There is a while loop in line 14. Even if I enter M or F, it still gives the input. It doesn’t continue.

import array

# Declaration of variables
Constnostudents = int(3)
StudentName = []
StudentGender = []

# Declaration of arrays
StudentMarkTest1 = array.array ("i", range(Constnostudents))
StudentMarktest2 = array.array ("i", range(Constnostudents))

for Counter in range(0, Constnostudents):
    StudentName.append (input("Please enter name of student"))
    StudentGender.append (input("Please enter your gender"))
    while (StudentName[Counter] !="M" or StudentName[Counter] != "F"):
        input("Please enter valid ")

    StudentMarkTest1[Counter] = int(input("Please enter marks for test 1"))
    StudentMarktest2[Counter] = int(input("Please enter marks for test 2"))

print(StudentName)
print(StudentGender)
print(StudentMarkTest1)
print(StudentMarktest2)

Body:
If you are trying to check if the gender they provided is a valid one, you are giving the wrong value to the while loop. You need to give the "StudentGender" variable and not the "StudentName" variable. Also you are not reassigning the " StudentGender", so it doesn't matter if they are going to provide a valid answer. The loop will continue to run...

You should do:

while (StudentGender[Counter] !="M" and StudentGender[Counter] != "F"):
       StudentGender[Counter] = input("Please enter valid gender").upper()

I also added .upper() to the gender.

For the reason of the "and" instead of "or", look at the comments in your question.


问:
Eloquent. Cast select's as integer within relationship?
i'm trying to create a re-useable method which can get the minimum and maximum values from a table, but for any column I ask for.

So for example below I want to min and max of price. However this value is being returned as a string:

$result = [
    "price" => [
        "min" => "2200.00",
        "max" => "45340.00"
    ]
];
```
<p>I want to return this, and avoid additional manipulation of the data:</p>
<pre class="lang-php prettyprint-override"><code>$result = [
    "price" => [
        "min" => 2200,
        "max" => 45340
    ]
];
</code>```

This is my current method.

public function vehiclesMinMax($column)
{
    return $this->hasOne(Vehicle::class)
        ->selectRaw(new Expression("MIN({$column}) AS min, MAX({$column}) AS max"))
        ->where($column, '>', 0)
        ->first();
}
```
<p>What I tried to do is use <code>withCasts</code>, however this doesn't appear to be available for <code>database/Query/Builder.php</code></p>
<pre class="lang-php prettyprint-override"><code>public function vehiclesMinMax($column)
{
    return $this->hasOne(Vehicle::class)
        ->selectRaw(new Expression("MIN({$column}) AS min, MAX({$column}) AS max"))
        ->withCasts([
            'min' => 'integer',
        ])
        ->where($column, '>', 0)
        ->first();
}
</code>```

答:
Managed to do this another way, just added the the result to a collection so I can use map. Arrow functions on available 7.4+.

public function vehiclesMinMax($column)
{
    return collect($this->hasOne(Vehicle::class)
        ->selectRaw(new Expression("MIN({$column}) AS min, MAX({$column}) AS max"))
        ->where($column, '>', 0)
        ->first())
        ->map(fn($item) => (int) $item);
}
```

Body:
i'm trying to create a re-useable method which can get the minimum and maximum values from a table, but for any column I ask for.

So for example below I want to min and max of price. However this value is being returned as a string:

$result = [
    "price" => [
        "min" => "2200.00",
        "max" => "45340.00"
    ]
];

I want to return this, and avoid additional manipulation of the data:

$result = [
    "price" => [
        "min" => 2200,
        "max" => 45340
    ]
];

This is my current method.

public function vehiclesMinMax($column)
{
    return $this->hasOne(Vehicle::class)
        ->selectRaw(new Expression("MIN({$column}) AS min, MAX({$column}) AS max"))
        ->where($column, '>', 0)
        ->first();
}

What I tried to do is use withCasts, however this doesn't appear to be available for database/Query/Builder.php

public function vehiclesMinMax($column)
{
    return $this->hasOne(Vehicle::class)
        ->selectRaw(new Expression("MIN({$column}) AS min, MAX({$column}) AS max"))
        ->withCasts([
            'min' => 'integer',
        ])
        ->where($column, '>', 0)
        ->first();
}


问:
how do I drive the width of span class with variable
Please where am I mistaking?
I am trying to change the progress bar base on variable and it is not working.</p>
```<code>    <script>
        function grafWidth(GtempPar) {
         var GtempPar = 30;

        document.getElementById('progress-in').style.width = GtempPar + "px";
        }
    </script>

    <div class="progress">
        <a class="majko">Temp_G_back</a>
        <span class="progress-val"><div id="Gtemp"></div>°C</span>
        <span class="progress-bar"><span class="progress-in".style.width =" 80px"></span></span>
    </div>
</code>```

答:
The most likely reason is that the span is an inline element and as such you can't specify a width (or margins / padding / height etc). In order to apply the styling try - making the span display y: inline-block and you should be able to apply width changes as expected.

Also the span has an id not a class and you have to call the function with an argument that you are wanting the pass into the function. and the var inside the function is redundant.

function grafWidth(GtempPar) {
   document.getElementById('progress-in').style.width = GtempPar + "px";
}

grafWidth(150); // this calls the function and passes 150 in to set the width of the progress bar to 150px (out of 200)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>span {
  display: inline-block;
}

.progress-bar  {
  border: solid 1px blue;
  width: 200px;
  height: 32px
}

#progress-in {
  background: red;
  position: relative;
  z-index: 1;
  width: 100px;
  height: 32px;
}</code>```

    Temp_G_back

°C

```

Body:
Please where am I mistaking?
I am trying to change the progress bar base on variable and it is not working.

        Temp_G_back

°C

Body:
The most likely reason is that the span is an inline element and as such you can't specify a width (or margins / padding / height etc). In order to apply the styling try - making the span display y: inline-block and you should be able to apply width changes as expected.

Also the span has an id not a class and you have to call the function with an argument that you are wanting the pass into the function. and the var inside the function is redundant.

function grafWidth(GtempPar) {
   document.getElementById('progress-in').style.width = GtempPar + "px";
}

grafWidth(150); // this calls the function and passes 150 in to set the width of the progress bar to 150px (out of 200)

span {
  display: inline-block;
}

.progress-bar  {
  border: solid 1px blue;
  width: 200px;
  height: 32px
}

#progress-in {
  background: red;
  position: relative;
  z-index: 1;
  width: 100px;
  height: 32px;
}

<div class="progress">
    <a class="majko">Temp_G_back</a>
    <span class="progress-val"><div id="Gtemp"></div>°C</span>
    <span class="progress-bar"><span id="progress-in"></span></span>
</div>


问:
Can I force the use of 'this' keyword in c# .NET?
Is there a way to force the use of the this keyword in Visual Studio when referencing current instance members?

Example with a bug in the constructor:

```<code>class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        Foo = Foo; // this should of course be lowercase but it's easy to miss
    }
}
</code>```

This code will probably generate the infamous 'object reference not set to an instance of an object' exception somewhere later on.

How to make it work but still It's easy to miss:

```<code>class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        Foo = foo; // Valid syntax but unclear.
    }
}
</code>```

This is valid syntax but it's easy to miss.

The syntax I'd like visual studio enforce:

```<code>class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        this.Foo = foo; // this is "safe".
    }
}
</code>```

If this convention is enforced i would have to type this.Foo = this.Foo to create the same type of bug as in the first example.

I always use the this keyword anyway since it makes my life easier while switching between c# and other languages so there wouldn't be any disadvantages at all.

答: You can create custom warnings and errors using FXCop\Visual Studio Code Analysis</p>

Body:
Is there a way to force the use of the this keyword in Visual Studio when referencing current instance members?

Example with a bug in the constructor:

class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        Foo = Foo; // this should of course be lowercase but it's easy to miss
    }
}

This code will probably generate the infamous 'object reference not set to an instance of an object' exception somewhere later on.

How to make it work but still It's easy to miss:

class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        Foo = foo; // Valid syntax but unclear.
    }
}

This is valid syntax but it's easy to miss.

The syntax I'd like visual studio enforce:

class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        this.Foo = foo; // this is "safe".
    }
}

If this convention is enforced i would have to type this.Foo = this.Foo to create the same type of bug as in the first example.

I always use the this keyword anyway since it makes my life easier while switching between c# and other languages so there wouldn't be any disadvantages at all.


问:
How to match range intervals and one condition between data frames and add values from one to the other data frame
I have two data frames. First, saves coordinates and places

```<code>data = [['xx1', 1,10,'Madrid'], ['xx2',15,20,'London']]
df1 = pd.DataFrame(data, columns = ['precode', 'start', 'stop','city'])
</code>```

The second

```<code>data2 = [['xx1', 3,11,'location1',], ['xx2',9,17,'location2'],['xx2',21,30,'location3'],['xx5',1,19,'location4']]
df2 = pd.DataFrame(data2, columns = ['precode', 'start', 'stop','locations'],)
</code>```

I want to check if locations are in city. If so add in df2 the name of the cities

```<code>precode  start   stop     location       city
xx1      3       11       location1      Madrid
xx2      9       17       location2      Madrid;London # If more than one city affected, add as many as cities affected as found
xx2      21      30       location3      NaN
xx5      1       19       location4      NaN
</code>```

I don't even know how to start. Shall I convert column into a dict to do the checking process or can shall I itinerate values of one column to the column of the other data frame. df1 is much bigger than df2. Both data frames have more columns. The final output need to be an identical as was df2 but with the new column city.

答:
Use cross merge then keep values within the range then aggregate cities:

```<code>df2['city'] = (
    df2.loc[df2['precode'].isin(df1['precode'])]
       .reset_index().merge(df1, how='cross', suffixes=('', '_'))
       .query('start.between(start_, stop_) | stop.between(start_, stop_)')
       .groupby('index')['city'].apply(list).str.join(';')
)
</code>```

Output:

```<code>>>> df2
  precode  start  stop  locations           city
0     xx1      3    11  location1         Madrid
1     xx2      9    17  location2  Madrid;London
2     xx2     21    30  location3            NaN
3     xx5      1    19  location4            NaN
</code>```

Step by step:

```<code>>>> out = df2.loc[df2['precode'].isin(df1['precode'])]
  precode  start  stop  locations
0     xx1      3    11  location1
1     xx2      9    17  location2
2     xx2     21    30  location3

>>> out = out.reset_index().merge(df1, how='cross', suffixes=('', '_'))
   index precode  start  stop  locations precode_  start_  stop_    city
0      0     xx1      3    11  location1      xx1       1     10  Madrid
1      0     xx1      3    11  location1      xx2      15     20  London
2      1     xx2      9    17  location2      xx1       1     10  Madrid
3      1     xx2      9    17  location2      xx2      15     20  London
4      2     xx2     21    30  location3      xx1       1     10  Madrid
5      2     xx2     21    30  location3      xx2      15     20  London

>>> out = out.query('start.between(start_, stop_) | stop.between(start_, stop_)')
   index precode  start  stop  locations precode_  start_  stop_    city
0      0     xx1      3    11  location1      xx1       1     10  Madrid
2      1     xx2      9    17  location2      xx1       1     10  Madrid
3      1     xx2      9    17  location2      xx2      15     20  London

>>> out = out.groupby('index')['city'].apply(list).str.join(';')
index
0           Madrid
1    Madrid;London
Name: city, dtype: object
</code>```

Body:
I have two data frames. First, saves coordinates and places

data = [['xx1', 1,10,'Madrid'], ['xx2',15,20,'London']]
df1 = pd.DataFrame(data, columns = ['precode', 'start', 'stop','city'])

The second

data2 = [['xx1', 3,11,'location1',], ['xx2',9,17,'location2'],['xx2',21,30,'location3'],['xx5',1,19,'location4']]
df2 = pd.DataFrame(data2, columns = ['precode', 'start', 'stop','locations'],)

I want to check if locations are in city. If so add in df2 the name of the cities

precode  start   stop     location       city
xx1      3       11       location1      Madrid
xx2      9       17       location2      Madrid;London # If more than one city affected, add as many as cities affected as found
xx2      21      30       location3      NaN
xx5      1       19       location4      NaN

I don't even know how to start. Shall I convert column into a dict to do the checking process or can shall I itinerate values of one column to the column of the other data frame. df1 is much bigger than df2. Both data frames have more columns. The final output need to be an identical as was df2 but with the new column city.

Body:
Use cross merge then keep values within the range then aggregate cities:

df2['city'] = (
    df2.loc[df2['precode'].isin(df1['precode'])]
       .reset_index().merge(df1, how='cross', suffixes=('', '_'))
       .query('start.between(start_, stop_) | stop.between(start_, stop_)')
       .groupby('index')['city'].apply(list).str.join(';')
)

Output:

>>> df2
  precode  start  stop  locations           city
0     xx1      3    11  location1         Madrid
1     xx2      9    17  location2  Madrid;London
2     xx2     21    30  location3            NaN
3     xx5      1    19  location4            NaN

Step by step:

>>> out = df2.loc[df2['precode'].isin(df1['precode'])]
  precode  start  stop  locations
0     xx1      3    11  location1
1     xx2      9    17  location2
2     xx2     21    30  location3

>>> out = out.reset_index().merge(df1, how='cross', suffixes=('', '_'))
   index precode  start  stop  locations precode_  start_  stop_    city
0      0     xx1      3    11  location1      xx1       1     10  Madrid
1      0     xx1      3    11  location1      xx2      15     20  London
2      1     xx2      9    17  location2      xx1       1     10  Madrid
3      1     xx2      9    17  location2      xx2      15     20  London
4      2     xx2     21    30  location3      xx1       1     10  Madrid
5      2     xx2     21    30  location3      xx2      15     20  London

>>> out = out.query('start.between(start_, stop_) | stop.between(start_, stop_)')
   index precode  start  stop  locations precode_  start_  stop_    city
0      0     xx1      3    11  location1      xx1       1     10  Madrid
2      1     xx2      9    17  location2      xx1       1     10  Madrid
3      1     xx2      9    17  location2      xx2      15     20  London

>>> out = out.groupby('index')['city'].apply(list).str.join(';')
index
0           Madrid
1    Madrid;London
Name: city, dtype: object


问:
Paytm - Checksum provided is invalid
While creating the transaction token for paytm business, I am receiving the below error as response from paytm.

CURL request ( as per docs, https://developer.paytm.com/docs/initiate-transaction-api/?ref=payments )

```<code>curl -X POST 'https://securegw-stage.paytm.in/theia/api/v1/initiateTransaction?mid=hkmbcA45014017456710&orderId=ORDERID_2' \
--header 'Content-Type: application/json' \
--data '{"body":{"requestType":"Payment","mid":"hkmbcA45014017456710","websiteName":"WEBSTAGING","orderId":"ORDERID_2","txnAmount":{"value":"1.00","currency":"INR"},"userInfo":{"custId":"CUST_001"},"callbackUrl":"https://merchant.com/callback"},"head":{"signature":"E3g+4XifD5/XwcD/tJ9ePYJTlJGZL7BneqY4Vf32faqEJ8zkSvgM+pMWfCAfmb0VwQaT3M4p6e+grMXjeqsRScF7en86MjLY1ieA9WRf4w="}}'
</code>```

Response

```<code>{"head":{"requestId":null,"responseTimestamp":"1596714537669","version":"v1"},"body":{"extraParamsMap":null,"resultInfo":{"resultStatus":"F","resultCode":"2005","resultMsg":"Checksum provided is invalid"}}}
</code>```

I have generated the checksum in ruby using https://github.com/paytm/Paytm_Ruby_Checksum/blob/master/PaytmChecksum.rb

Answers and small suggestions also are most welcome !!!

答:
```<code>When I removed website name and callback URL its working fine.
</code>```

Just replace the MID with your and its working fine

Title: Paytm - Checksum provided is invalid

Body:
While creating the transaction token for paytm business, I am receiving the below error as response from paytm.

CURL request ( as per docs, https://developer.paytm.com/docs/initiate-transaction-api/?ref=payments )

curl -X POST 'https://securegw-stage.paytm.in/theia/api/v1/initiateTransaction?mid=hkmbcA45014017456710&orderId=ORDERID_2' \
--header 'Content-Type: application/json' \
--data '{"body":{"requestType":"Payment","mid":"hkmbcA45014017456710","websiteName":"WEBSTAGING","orderId":"ORDERID_2","txnAmount":{"value":"1.00","currency":"INR"},"userInfo":{"custId":"CUST_001"},"callbackUrl":"https://merchant.com/callback"},"head":{"signature":"E3g+4XifD5/XwcD/tJ9ePYJTlJGZL7BneqY4Vf32faqEJ8zkSvgM+pMWfCAfmb0VwQaT3M4p6e+grMXjeqsRScF7en86MjLY1ieA9WRf4w="}}'

Response

{"head":{"requestId":null,"responseTimestamp":"1596714537669","version":"v1"},"body":{"extraParamsMap":null,"resultInfo":{"resultStatus":"F","resultCode":"2005","resultMsg":"Checksum provided is invalid"}}}

I have generated the checksum in ruby using https://github.com/paytm/Paytm_Ruby_Checksum/blob/master/PaytmChecksum.rb

Answers and small suggestions also are most welcome !!!

Body:
When I removed website name and callback URL its working fine.

Just replace the MID with your and its working fine


问:
Swashbuckle Error - 404 for 'swagger.json' when running in IIS
I have a basic asp.net core 5.0 web API. I installed Swashbuckle.ASPNetCore swagger-5.6.3 nuget package.

here is my startup.cs.

startup.cs:

```<code>public void ConfigureServices(IServiceCollection services)
{
    #region Api Versioning
    services.AddVersioning();
    #endregion
    #region Swagger
    services.AddSwagger();
    #endregion
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider, IApiVersionDescriptionProvider provider, UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager)
{
    app.UseMiddleware<ExceptionMiddleware>();
    app.UseStatusCodePagesWithReExecute("/errors/{0}");
    #region Swagger
    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseVersionedSwagger(provider);
    #endregion
    #region CORS
    app.UseCors("AllowAllOrigins");
    #endregion
    app.UseHttpsRedirection();
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}
</code>```

Here are the details:

```<code>public static class ApiVersioningExtension
{
    public static IServiceCollection AddVersioning(this IServiceCollection services)
    {
        services.AddApiVersioning(
            options =>
            {
                options.ReportApiVersions = true;
            });
        services.AddVersionedApiExplorer(
            options =>
            {
                options.GroupNameFormat = "'v'VVV";
                options.SubstituteApiVersionInUrl = true;
            });

        return services;
    }
}

private static string XmlCommentsFilePath
{
    get
    {
        var basePath = PlatformServices.Default.Application.ApplicationBasePath;
        var fileName = typeof(Startup).GetTypeInfo().Assembly.GetName().Name + ".xml";
        return Path.Combine(basePath, fileName);
    }
}

public static IServiceCollection AddSwagger(this IServiceCollection services)
{
    services.AddTransient<IConfigureOptions<SwaggerGenOptions>, ConfigureSwaggerOptions>();

    services.AddSwaggerGen(options =>
    {
        options.OperationFilter<SwaggerDefaultValues>();

        options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
        {
            Scheme = "Bearer",
            Description = @"JWT Authorization header using the Bearer scheme. <br><br>
              Enter 'Bearer' [space] and then your token in the text input below.
              <br><br>Example: 'Bearer 12345abcdef'",
            Name = "Authorization",
            In = ParameterLocation.Header,
            Type = SecuritySchemeType.Http
        });

        options.OperationFilter<SwaggerAuthorizeCheckOperationFilter>();

        // integrate xml comments
        options.IncludeXmlComments(XmlCommentsFilePath);
    });

    return services;
}

public static IApplicationBuilder UseVersionedSwagger(this IApplicationBuilder app, IApiVersionDescriptionProvider provider)
{
    app.UseSwagger();
    app.UseSwaggerUI(
        options =>
        {
            foreach (var description in provider.ApiVersionDescriptions)
            {
                options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant());
            }
        });

    return app;
}

public class SwaggerDefaultValues : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        var apiDescription = context.ApiDescription;

        operation.Deprecated |= apiDescription.IsDeprecated();

        if (operation.Parameters == null)
        {
            return;
        }

        foreach (var parameter in operation.Parameters)
        {
            var description = apiDescription.ParameterDescriptions.First(p => p.Name == parameter.Name);

            if (parameter.Description == null)
            {
                parameter.Description = description.ModelMetadata?.Description;
            }

            if (parameter.Schema.Default == null && description.DefaultValue != null)
            {
                parameter.Schema.Default = new OpenApiString(description.DefaultValue.ToString());
            }

            parameter.Required |= description.IsRequired;
        }
    }
}
</code>```

When I run this on IIS Express, swagger is working fine. Then I deployed this to IIS, I am getting 404 not found.

This works:

http://localhost/myapp/swagger/v1/swagger.json

But,

http://localhost/myapp/swagger/index.html

gives the error:

Errors Hide Fetch errorNot Found /swagger/v1/swagger.json

How do I resolve this?

答:
Regarding your case, you can do this to configure your Swagger for IIS:

```<code>options.SwaggerEndpoint($"../swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant());
</code>```

Body:
I have a basic asp.net core 5.0 web API. I installed Swashbuckle.ASPNetCore swagger-5.6.3 nuget package.

here is my startup.cs.

startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    #region Api Versioning
    services.AddVersioning();
    #endregion
    #region Swagger
    services.AddSwagger();
    #endregion
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider, IApiVersionDescriptionProvider provider, UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager)
{
    app.UseMiddleware<ExceptionMiddleware>();
    app.UseStatusCodePagesWithReExecute("/errors/{0}");
    #region Swagger
    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseVersionedSwagger(provider);
    #endregion
    #region CORS
    app.UseCors("AllowAllOrigins");
    #endregion
    app.UseHttpsRedirection();
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

Here are the details:

public static class ApiVersioningExtension
{
    public static IServiceCollection AddVersioning(this IServiceCollection services)
    {
        services.AddApiVersioning(
            options =>
            {
                options.ReportApiVersions = true;
            });
        services.AddVersionedApiExplorer(
            options =>
            {
                options.GroupNameFormat = "'v'VVV";
                options.SubstituteApiVersionInUrl = true;
            });

        return services;
    }
}

private static string XmlCommentsFilePath
{
    get
    {
        var basePath = PlatformServices.Default.Application.ApplicationBasePath;
        var fileName = typeof(Startup).GetTypeInfo().Assembly.GetName().Name + ".xml";
        return Path.Combine(basePath, fileName);
    }
}

public static IServiceCollection AddSwagger(this IServiceCollection services)
{
    services.AddTransient<IConfigureOptions<SwaggerGenOptions>, ConfigureSwaggerOptions>();

    services.AddSwaggerGen(options =>
    {
        options.OperationFilter<SwaggerDefaultValues>();

        options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
        {
            Scheme = "Bearer",
            Description = @"JWT Authorization header using the Bearer scheme.

              Enter 'Bearer' [space] and then your token in the text input below.

Example: 'Bearer 12345abcdef'",
            Name = "Authorization",
            In = ParameterLocation.Header,
            Type = SecuritySchemeType.Http
        });

        options.OperationFilter<SwaggerAuthorizeCheckOperationFilter>();

        // integrate xml comments
        options.IncludeXmlComments(XmlCommentsFilePath);
    });

    return services;
}

public static IApplicationBuilder UseVersionedSwagger(this IApplicationBuilder app, IApiVersionDescriptionProvider provider)
{
    app.UseSwagger();
    app.UseSwaggerUI(
        options =>
        {
            foreach (var description in provider.ApiVersionDescriptions)
            {
                options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant());
            }
        });

    return app;
}

public class SwaggerDefaultValues : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        var apiDescription = context.ApiDescription;

        operation.Deprecated |= apiDescription.IsDeprecated();

        if (operation.Parameters == null)
        {
            return;
        }

        foreach (var parameter in operation.Parameters)
        {
            var description = apiDescription.ParameterDescriptions.First(p => p.Name == parameter.Name);

            if (parameter.Description == null)
            {
                parameter.Description = description.ModelMetadata?.Description;
            }

            if (parameter.Schema.Default == null && description.DefaultValue != null)
            {
                parameter.Schema.Default = new OpenApiString(description.DefaultValue.ToString());
            }

            parameter.Required |= description.IsRequired;
        }
    }
}

When I run this on IIS Express, swagger is working fine. Then I deployed this to IIS, I am getting 404 not found.

This works:

http://localhost/myapp/swagger/v1/swagger.json

But,

http://localhost/myapp/swagger/index.html

gives the error:

Errors Hide Fetch errorNot Found /swagger/v1/swagger.json

How do I resolve this?

Body:
Regarding your case, you can do this to configure your Swagger for IIS:

options.SwaggerEndpoint($"../swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant());


问:
dataweave 1.0 to 2.0 migration in mulesoft
I'm trying to convert the below dataweave from 1.0 to 2.0, but everything I've tried gives the following errors like evaluating-expression Error, Invalid input "reduce" and replace.

Mule 3 Dataweave 1.0:

```<code>%dw 1.0
%output application/xml
%var basicPolicy = payload.DTOApplication.DTOBasicPolicy
%var insuredInfo = payload.DTOApplication.DTOInsured
%var insuredPrimaryAddr = insuredInfo.*PartyInfo[?($.@PartyTypeCd == "InsuredParty")].*Addr[?($.@AddrTypeCd == "InsuredPrimaryBusAddr")][0]
%var lineLiability = payload.DTOApplication.*DTOLine[?($.@StatusCd == "Active" and $.@LineCd == "Liability")][0]
%var lineProperty = payload.DTOApplication.*DTOLine[?($.@StatusCd == "Active" and $.@LineCd == "CommercialProperty")][0]
%var lineProductLiability = payload.DTOApplication.*DTOLine[?($.@StatusCd == "Active" and $.@LineCd == "ProductLiability")][0]
%var primaryClassTotalExposure = lineLiability.*DTORisk[?($.@Status == "Active" and $.@TypeCd == "Exposure")].*DTOGLClass[?($.@GLClassCode == primaryExposure)].@Exposure default [] reduce ((val,acc=0) -> acc + (val replace "\$" with "" replace "," with "") as :number)
%var primaryClassPLTotalExposure = lineProductLiability.*DTORisk[?($.@Status == "Active" and $.@TypeCd == "Exposure")].*DTOGLClass[?($.@GLClassCode == primaryExposurePL)].@Exposure default [] reduce ((val,acc=0) -> acc + (val replace "\$" with "" replace "," with "") as :number)
---
{

    Policy: {
        PolType: basicPolicy.@SubTypeCd default "",
        Zip: insuredPrimaryAddr.@PostalCode[0..4] default "",
        EffDate: basicPolicy.@EffectiveDt default "",
        ExpDate: basicPolicy.@ExpirationDt default "",
        EBCov: lineProperty.@EquipmentBreakdown default "No",
        PolFeeOR2: payload.DTOApplication.*DTOFee[?($.@Status == "Active" and $.@RateDRCFeeInd == "No")][0].@FullTermAmt default "",
        PolFeeOR: (payload.DTOApplication.DTOFeeOverrides.*DTOFeeOverride[?($.@Code == "POLF" and $.@OverrideInd == "Yes")][0].@Amount default "") when payload.DTOApplication.DTOFeeOverrides.*DTOFeeOverride[?($.@Code == "POLF" and $.@OverrideInd == "Yes")][0].@Amount != null
                    otherwise (payload.DTOApplication.*DTOFee[?($.@Status == "Active" and $.@RateDRCFeeInd == "No")][0].@FullTermAmt default "")  when payload.DTOApplication.*DTOFee[?($.@Status == "Active" and $.@RateDRCFeeInd == "No")][0].@FullTermAmt != null
                    otherwise "",
        LiabExp: primaryClassTotalExposure,
        ProdExp: primaryClassPLTotalExposure
    }
}
</code>```

Input payload : https://github.com/Manikandan99/rate-dtostep/blob/master/request.xml

Expected output: https://github.com/Manikandan99/rate-dtostep/blob/master/policy_response.xml

I tried dataweave 2.0:

```<code>%dw 2.0
output application/xml
var basicPolicy = payload.DTOApplication.DTOBasicPolicy
var insuredInfo = payload.DTOApplication.DTOInsured
var insuredPrimaryAddr = insuredInfo.*PartyInfo[?($.@PartyTypeCd == "InsuredParty")].*Addr[?($.@AddrTypeCd == "InsuredPrimaryBusAddr")][0]
var lineLiability = payload.DTOApplication.*DTOLine[?($.@StatusCd == "Active" and $.@LineCd == "Liability")][0]
var lineProperty = payload.DTOApplication.*DTOLine[?($.@StatusCd == "Active" and $.@LineCd == "CommercialProperty")][0]
var lineProductLiability = payload.DTOApplication.*DTOLine[?($.@StatusCd == "Active" and $.@LineCd == "ProductLiability")][0]
var primaryClassTotalExposure = lineLiability.*DTORisk[?($.@Status == "Active" and $.@TypeCd == "Exposure")].*DTOGLClass[?($.@GLClassCode == primaryExposure)].@Exposure default [] reduce ((val,acc=0) -> acc + (val replace "\$" with "" replace "," with "") as :number)
var primaryClassPLTotalExposure = lineProductLiability.*DTORisk[?($.@Status == "Active" and $.@TypeCd == "Exposure")].*DTOGLClass[?($.@GLClassCode == primaryExposurePL)].@Exposure default [] reduce ((val,acc=0) -> acc + (val replace "\$" with "" replace "," with "") as :number)
---
{

    Policy: {
        PolType: basicPolicy.@SubTypeCd default "",
        Zip: insuredPrimaryAddr.@PostalCode[0 to 4] default "",
        EffDate: basicPolicy.@EffectiveDt default "",
        ExpDate: basicPolicy.@ExpirationDt default "",
        EBCov: lineProperty.@EquipmentBreakdown default "No",
        PolFeeOR2: payload.DTOApplication.*DTOFee[?($.@Status == "Active" and $.@RateDRCFeeInd == "No")][0].@FullTermAmt default "",
        PolFeeOR: (payload.DTOApplication.DTOFeeOverrides.*DTOFeeOverride[?($.@Code == "POLF" and $.@OverrideInd == "Yes")][0].@Amount default "") when payload.DTOApplication.DTOFeeOverrides.*DTOFeeOverride[?($.@Code == "POLF" and $.@OverrideInd == "Yes")][0].@Amount != null
                    otherwise (payload.DTOApplication.*DTOFee[?($.@Status == "Active" and $.@RateDRCFeeInd == "No")][0].@FullTermAmt default "")  when payload.DTOApplication.*DTOFee[?($.@Status == "Active" and $.@RateDRCFeeInd == "No")][0].@FullTermAmt != null
                    otherwise "",
        LiabExp: primaryClassTotalExposure,
        ProdExp: primaryClassPLTotalExposure
    }
}
</code>```

Any ideas please on how to write the same in dataweave 2.0?

答:
Adding few more points to @AnuragSharma's comments

if-else-if

In your dw you have GLClassCode == primaryExposure , primaryExposure is not present in your input payload hence this will result in a null value and you cant use replace function along with null

Since you are trying to cast to number , you can give a default value. Here I have set it to 0.

Added encoding="UTF-8" as required in output

To test your code I have passed GLClasscode as CANDIS as you had that in your payload.

Note - > Please check your parenthesis as well.

```<code>%dw 2.0
output application/xml encoding="UTF-8"
var basicPolicy = payload.DTOApplication.DTOBasicPolicy
var insuredInfo = payload.DTOApplication.DTOInsured
var insuredPrimaryAddr = insuredInfo.*PartyInfo[?($.@PartyTypeCd == "InsuredParty")].*Addr[?($.@AddrTypeCd == "InsuredPrimaryBusAddr")][0]
var lineLiability = payload.DTOApplication.*DTOLine[?($.@StatusCd == "Active" and $.@LineCd == "Liability")][0]
var lineProperty = payload.DTOApplication.*DTOLine[?($.@StatusCd == "Active" and $.@LineCd == "CommercialProperty")][0]
var lineProductLiability = payload.DTOApplication.*DTOLine[?($.@StatusCd == "Active" and $.@LineCd == "ProductLiability")][0]
var primaryClassTotalExposure = lineLiability.*DTORisk[?($.@Status == "Active" and $.@TypeCd == "Exposure")].*DTOGLClass[?($.@GLClassCode == "CANDIS")].@Exposure default [] reduce ($$++$) replace "\$" with "" replace "," with "" default 0  as Number
var primaryClassPLTotalExposure = lineProductLiability.*DTORisk[?($.@Status == "Active" and $.@TypeCd == "Exposure")].*DTOGLClass[?($.@GLClassCode == "CANDIS")].@Exposure default []  reduce ($$++$) replace "\$" with "" replace "," with "" default 0 as Number
---
{

    Policy: {
        PolType: basicPolicy.@SubTypeCd default "",
        Zip: insuredPrimaryAddr.@PostalCode[0 to 4] default "",
        EffDate: basicPolicy.@EffectiveDt default "",
        ExpDate: basicPolicy.@ExpirationDt default "",
        EBCov: lineProperty.@EquipmentBreakdown default "No",
        PolFeeOR2: payload.DTOApplication.*DTOFee[?($.@Status == "Active" and $.@RateDRCFeeInd == "No")][0].@FullTermAmt default "",
        PolFeeOR: if (payload.DTOApplication.DTOFeeOverrides.*DTOFeeOverride[?($.@Code == "POLF" and $.@OverrideInd == "Yes")][0].@Amount != null)
                        (payload.DTOApplication.DTOFeeOverrides.*DTOFeeOverride[?($.@Code == "POLF" and $.@OverrideInd == "Yes")][0].@Amount default "")
                else if (payload.DTOApplication.*DTOFee[?($.@Status == "Active" and $.@RateDRCFeeInd == "No")][0].@FullTermAmt != null)
                    (payload.DTOApplication.*DTOFee[?($.@Status == "Active" and $.@RateDRCFeeInd == "No")][0].@FullTermAmt default "")
                    else "",
        LiabExp: primaryClassTotalExposure,
        ProdExp: primaryClassPLTotalExposure
    }
}
</code>```

Output

```<code><?xml version='1.0' encoding='UTF-8'?>
<Policy>
  <PolType>CNPK</PolType>
  <Zip>80003</Zip>
  <EffDate>20211117</EffDate>
  <ExpDate>20221117</ExpDate>
  <EBCov>Yes</EBCov>
  <PolFeeOR2/>
  <PolFeeOR/>
  <LiabExp>2000000</LiabExp>
  <ProdExp>0</ProdExp>
</Policy>
</code>```

Body:
I'm trying to convert the below dataweave from 1.0 to 2.0, but everything I've tried gives the following errors like evaluating-expression Error, Invalid input "reduce" and replace.

Mule 3 Dataweave 1.0:

%dw 1.0
%output application/xml
%var basicPolicy = payload.DTOApplication.DTOBasicPolicy
%var insuredInfo = payload.DTOApplication.DTOInsured
%var insuredPrimaryAddr = insuredInfo.*PartyInfo[?($.@PartyTypeCd == "InsuredParty")].*Addr[?($.@AddrTypeCd == "InsuredPrimaryBusAddr")][0]
%var lineLiability = payload.DTOApplication.*DTOLine[?($.@StatusCd == "Active" and $.@LineCd == "Liability")][0]
%var lineProperty = payload.DTOApplication.*DTOLine[?($.@StatusCd == "Active" and $.@LineCd == "CommercialProperty")][0]
%var lineProductLiability = payload.DTOApplication.*DTOLine[?($.@StatusCd == "Active" and $.@LineCd == "ProductLiability")][0]
%var primaryClassTotalExposure = lineLiability.*DTORisk[?($.@Status == "Active" and $.@TypeCd == "Exposure")].*DTOGLClass[?($.@GLClassCode == primaryExposure)].@Exposure default [] reduce ((val,acc=0) -> acc + (val replace "\$" with "" replace "," with "") as :number)
%var primaryClassPLTotalExposure = lineProductLiability.*DTORisk[?($.@Status == "Active" and $.@TypeCd == "Exposure")].*DTOGLClass[?($.@GLClassCode == primaryExposurePL)].@Exposure default [] reduce ((val,acc=0) -> acc + (val replace "\$" with "" replace "," with "") as :number)
---
{

    Policy: {
        PolType: basicPolicy.@SubTypeCd default "",
        Zip: insuredPrimaryAddr.@PostalCode[0..4] default "",
        EffDate: basicPolicy.@EffectiveDt default "",
        ExpDate: basicPolicy.@ExpirationDt default "",
        EBCov: lineProperty.@EquipmentBreakdown default "No",
        PolFeeOR2: payload.DTOApplication.*DTOFee[?($.@Status == "Active" and $.@RateDRCFeeInd == "No")][0].@FullTermAmt default "",
        PolFeeOR: (payload.DTOApplication.DTOFeeOverrides.*DTOFeeOverride[?($.@Code == "POLF" and $.@OverrideInd == "Yes")][0].@Amount default "") when payload.DTOApplication.DTOFeeOverrides.*DTOFeeOverride[?($.@Code == "POLF" and $.@OverrideInd == "Yes")][0].@Amount != null
                    otherwise (payload.DTOApplication.*DTOFee[?($.@Status == "Active" and $.@RateDRCFeeInd == "No")][0].@FullTermAmt default "")  when payload.DTOApplication.*DTOFee[?($.@Status == "Active" and $.@RateDRCFeeInd == "No")][0].@FullTermAmt != null
                    otherwise "",
        LiabExp: primaryClassTotalExposure,
        ProdExp: primaryClassPLTotalExposure
    }
}

Input payload : https://github.com/Manikandan99/rate-dtostep/blob/master/request.xml

Expected output: https://github.com/Manikandan99/rate-dtostep/blob/master/policy_response.xml

I tried dataweave 2.0:

%dw 2.0
output application/xml
var basicPolicy = payload.DTOApplication.DTOBasicPolicy
var insuredInfo = payload.DTOApplication.DTOInsured
var insuredPrimaryAddr = insuredInfo.*PartyInfo[?($.@PartyTypeCd == "InsuredParty")].*Addr[?($.@AddrTypeCd == "InsuredPrimaryBusAddr")][0]
var lineLiability = payload.DTOApplication.*DTOLine[?($.@StatusCd == "Active" and $.@LineCd == "Liability")][0]
var lineProperty = payload.DTOApplication.*DTOLine[?($.@StatusCd == "Active" and $.@LineCd == "CommercialProperty")][0]
var lineProductLiability = payload.DTOApplication.*DTOLine[?($.@StatusCd == "Active" and $.@LineCd == "ProductLiability")][0]
var primaryClassTotalExposure = lineLiability.*DTORisk[?($.@Status == "Active" and $.@TypeCd == "Exposure")].*DTOGLClass[?($.@GLClassCode == primaryExposure)].@Exposure default [] reduce ((val,acc=0) -> acc + (val replace "\$" with "" replace "," with "") as :number)
var primaryClassPLTotalExposure = lineProductLiability.*DTORisk[?($.@Status == "Active" and $.@TypeCd == "Exposure")].*DTOGLClass[?($.@GLClassCode == primaryExposurePL)].@Exposure default [] reduce ((val,acc=0) -> acc + (val replace "\$" with "" replace "," with "") as :number)
---
{

    Policy: {
        PolType: basicPolicy.@SubTypeCd default "",
        Zip: insuredPrimaryAddr.@PostalCode[0 to 4] default "",
        EffDate: basicPolicy.@EffectiveDt default "",
        ExpDate: basicPolicy.@ExpirationDt default "",
        EBCov: lineProperty.@EquipmentBreakdown default "No",
        PolFeeOR2: payload.DTOApplication.*DTOFee[?($.@Status == "Active" and $.@RateDRCFeeInd == "No")][0].@FullTermAmt default "",
        PolFeeOR: (payload.DTOApplication.DTOFeeOverrides.*DTOFeeOverride[?($.@Code == "POLF" and $.@OverrideInd == "Yes")][0].@Amount default "") when payload.DTOApplication.DTOFeeOverrides.*DTOFeeOverride[?($.@Code == "POLF" and $.@OverrideInd == "Yes")][0].@Amount != null
                    otherwise (payload.DTOApplication.*DTOFee[?($.@Status == "Active" and $.@RateDRCFeeInd == "No")][0].@FullTermAmt default "")  when payload.DTOApplication.*DTOFee[?($.@Status == "Active" and $.@RateDRCFeeInd == "No")][0].@FullTermAmt != null
                    otherwise "",
        LiabExp: primaryClassTotalExposure,
        ProdExp: primaryClassPLTotalExposure
    }
}

Any ideas please on how to write the same in dataweave 2.0?

Body:
Adding few more points to @AnuragSharma's comments

if-else-if

In your dw you have GLClassCode == primaryExposure , primaryExposure is not present in your input payload hence this will result in a null value and you cant use replace function along with null

Since you are trying to cast to number , you can give a default value. Here I have set it to 0.

Added encoding="UTF-8" as required in output

To test your code I have passed GLClasscode as CANDIS as you had that in your payload.

Note - > Please check your parenthesis as well.

%dw 2.0
output application/xml encoding="UTF-8"
var basicPolicy = payload.DTOApplication.DTOBasicPolicy
var insuredInfo = payload.DTOApplication.DTOInsured
var insuredPrimaryAddr = insuredInfo.*PartyInfo[?($.@PartyTypeCd == "InsuredParty")].*Addr[?($.@AddrTypeCd == "InsuredPrimaryBusAddr")][0]
var lineLiability = payload.DTOApplication.*DTOLine[?($.@StatusCd == "Active" and $.@LineCd == "Liability")][0]
var lineProperty = payload.DTOApplication.*DTOLine[?($.@StatusCd == "Active" and $.@LineCd == "CommercialProperty")][0]
var lineProductLiability = payload.DTOApplication.*DTOLine[?($.@StatusCd == "Active" and $.@LineCd == "ProductLiability")][0]
var primaryClassTotalExposure = lineLiability.*DTORisk[?($.@Status == "Active" and $.@TypeCd == "Exposure")].*DTOGLClass[?($.@GLClassCode == "CANDIS")].@Exposure default [] reduce ($$++$) replace "\$" with "" replace "," with "" default 0  as Number
var primaryClassPLTotalExposure = lineProductLiability.*DTORisk[?($.@Status == "Active" and $.@TypeCd == "Exposure")].*DTOGLClass[?($.@GLClassCode == "CANDIS")].@Exposure default []  reduce ($$++$) replace "\$" with "" replace "," with "" default 0 as Number
---
{

    Policy: {
        PolType: basicPolicy.@SubTypeCd default "",
        Zip: insuredPrimaryAddr.@PostalCode[0 to 4] default "",
        EffDate: basicPolicy.@EffectiveDt default "",
        ExpDate: basicPolicy.@ExpirationDt default "",
        EBCov: lineProperty.@EquipmentBreakdown default "No",
        PolFeeOR2: payload.DTOApplication.*DTOFee[?($.@Status == "Active" and $.@RateDRCFeeInd == "No")][0].@FullTermAmt default "",
        PolFeeOR: if (payload.DTOApplication.DTOFeeOverrides.*DTOFeeOverride[?($.@Code == "POLF" and $.@OverrideInd == "Yes")][0].@Amount != null)
                        (payload.DTOApplication.DTOFeeOverrides.*DTOFeeOverride[?($.@Code == "POLF" and $.@OverrideInd == "Yes")][0].@Amount default "")
                else if (payload.DTOApplication.*DTOFee[?($.@Status == "Active" and $.@RateDRCFeeInd == "No")][0].@FullTermAmt != null)
                    (payload.DTOApplication.*DTOFee[?($.@Status == "Active" and $.@RateDRCFeeInd == "No")][0].@FullTermAmt default "")
                    else "",
        LiabExp: primaryClassTotalExposure,
        ProdExp: primaryClassPLTotalExposure
    }
}

Output

<?xml version='1.0' encoding='UTF-8'?>
<Policy>
  <PolType>CNPK</PolType>
  <Zip>80003</Zip>
  <EffDate>20211117</EffDate>
  <ExpDate>20221117</ExpDate>
  <EBCov>Yes</EBCov>
  <PolFeeOR2/>
  <PolFeeOR/>
  <LiabExp>2000000</LiabExp>
  <ProdExp>0</ProdExp>
</Policy>


问:
How to map an array of data in reactjs?
I am having trouble on getting the latitude ,  what i've tried so far is searchLocation.findLocationByAddress.geoCode.latitude and i get this error

error

LocationAdd.js:288 Uncaught (in promise) TypeError: Cannot read
properties of undefined (reading 'latitude')

here is my code

```<code> const { data: searchLocation } = await getLocations({
    variables: {
      placeSearch: {
        address: value
      },
    },
  });
  console.log(searchLocation.findLocationByAddress)
  geoCode = {
    latitude: searchLocation.findLocationByAddress.geoCode.latitude,
    longitude: searchLocation.findLocationByAddress.geoCode.longitude,
  };
</code>```

答: findLocationByAddress returns an array, I think you should call .map() or access an element with [].</p>

Title: How to map an array of data in reactjs?

Body:
I am having trouble on getting the latitude ,  what i've tried so far is searchLocation.findLocationByAddress.geoCode.latitude and i get this error

error

LocationAdd.js:288 Uncaught (in promise) TypeError: Cannot read
properties of undefined (reading 'latitude')

here is my code

 const { data: searchLocation } = await getLocations({
    variables: {
      placeSearch: {
        address: value
      },
    },
  });
  console.log(searchLocation.findLocationByAddress)
  geoCode = {
    latitude: searchLocation.findLocationByAddress.geoCode.latitude,
    longitude: searchLocation.findLocationByAddress.geoCode.longitude,
  };


问:
I was reading a book on Deep learning and I am not able to understand this part about Conv2D
```<code>Layer (type) Output Shape Param #
================================================================
conv2d_4 (Conv2D) (None, 26, 26, 32) 320
________________________________________________________________
conv2d_5 (Conv2D) (None, 24, 24, 64) 18496
________________________________________________________________
conv2d_6 (Conv2D) (None, 22, 22, 64) 36928
================================================================
Total params: 55,744
Trainable params: 55,744
Non-trainable params: 0
</code>```

The author says:

The 3 × 3 windows
in the third layer will only contain information coming from 7 × 7 windows in
the initial input. The high-level patterns learned by the convnet will still be very
small with regard to the initial input, which may not be enough to learn to classify digits (try recognizing a digit by only looking at it through windows that are
7 × 7 pixels!). We need the features from the last convolution layer to contain
information about the totality of the input.

Now where did this 7x7 window come from?Isnt the window in first layer also 3X3 ? What am I missing?

答:
Let us consider this example:

```<code>        model = tf.keras.models.Sequential([
        tf.keras.layers.Conv2D(32, (3, 3), activation='relu',input_shape=(28,28,3)),
        tf.keras.layers.Conv2D(20, (3, 3), activation='relu'),
        tf.keras.layers.Conv2D(10, (3, 3), activation='relu')])
</code>```

Here is the output of the model.summary():

```<code>        Model: "sequential_1"
        _________________________________________________________________
        Layer (type)                Output Shape              Param #
        =================================================================
        conv2d_3 (Conv2D)           (None, 26, 26, 32)        896

        conv2d_4 (Conv2D)           (None, 24, 24, 20)        5780

        conv2d_5 (Conv2D)           (None, 22, 22, 10)        1810

        =================================================================
        Total params: 8,486
        Trainable params: 8,486
        Non-trainable params: 0
        _________________________________________________________________

</code>```

To calculate the output shape you could use this formula:

```<code>O = (W - K + 2P)/S + 1
</code>```

where O is the output height/width, W is the input height/width, K is the filter size, P is the padding and S is the stride size.

To calculate the Parameter Number for conv_layer you could use this formula:

param_number_for_conv_layer = output_channel_number * (input_channel_number * kernel_height * kernel_width + 1)

Please refer this for 'None' in the output shape

Body:
Layer (type) Output Shape Param #
================================================================
conv2d_4 (Conv2D) (None, 26, 26, 32) 320
________________________________________________________________
conv2d_5 (Conv2D) (None, 24, 24, 64) 18496
________________________________________________________________
conv2d_6 (Conv2D) (None, 22, 22, 64) 36928
================================================================
Total params: 55,744
Trainable params: 55,744
Non-trainable params: 0

The author says:

The 3 × 3 windows
in the third layer will only contain information coming from 7 × 7 windows in
the initial input. The high-level patterns learned by the convnet will still be very
small with regard to the initial input, which may not be enough to learn to classify digits (try recognizing a digit by only looking at it through windows that are
7 × 7 pixels!). We need the features from the last convolution layer to contain
information about the totality of the input.

Now where did this 7x7 window come from?Isnt the window in first layer also 3X3 ? What am I missing?

Body:
Let us consider this example:

        model = tf.keras.models.Sequential([
        tf.keras.layers.Conv2D(32, (3, 3), activation='relu',input_shape=(28,28,3)),
        tf.keras.layers.Conv2D(20, (3, 3), activation='relu'),
        tf.keras.layers.Conv2D(10, (3, 3), activation='relu')])

Here is the output of the model.summary():

        Model: "sequential_1"
        _________________________________________________________________
        Layer (type)                Output Shape              Param #
        =================================================================
        conv2d_3 (Conv2D)           (None, 26, 26, 32)        896

        conv2d_4 (Conv2D)           (None, 24, 24, 20)        5780

        conv2d_5 (Conv2D)           (None, 22, 22, 10)        1810

        =================================================================
        Total params: 8,486
        Trainable params: 8,486
        Non-trainable params: 0
        _________________________________________________________________

To calculate the output shape you could use this formula:

O = (W - K + 2P)/S + 1

where O is the output height/width, W is the input height/width, K is the filter size, P is the padding and S is the stride size.

To calculate the Parameter Number for conv_layer you could use this formula:

param_number_for_conv_layer = output_channel_number * (input_channel_number * kernel_height * kernel_width + 1)

Please refer this for 'None' in the output shape


问:
Unable to generate release builds Android Studio Bumblebee
Unable to generate release builds on Android Studio Bumblebee 2021.1.1 Patch 1

I have macOS 12.2, Gradle version 7.0.4, Intel processor

Do anyone solved the issue? Ideas?

The issue is not reproductible on Arctic Fox

UPDATE:

It is a gradle 7.0.4 issue, Upgrading to 7.1.1 solves the issue

答: I was able to reproduce the issue by using AGP version 7.0.2 but was able to fix it after upgrading to 7.1.0</p>


问:
What does "no error" mean when writing to a file in Lua?
I am writing a script to add one line in a .txt per video while using MPV.

However, I am getting a weird error on line 68 with the for loop.
It merely tells me: no error. If I add an error parameter to file:write(message, error), it gives me another error message, stating: bad argument #2 to 'write' (string expected, got function). Any help would be appreciated.

```<code>function on_file_end(event)
    if not paused then totaltime = totaltime + os.clock() - lasttime end
    local message = (totaltime .. "s, " .. timeloaded .. ", " .. filename)
    local lines = {}
    local file = io.open(logpath, "r+")
    if file_exists(logpath) then
        for l in file:lines() do
            if not l:find(message, 1, true) then
                lines[#lines+1] = 1
                file:write(message)
            end
        end
        file:close()
    end
end
</code>```

答:
bad argument #2 to 'write' (string expected, got function)

error is not an "error parameter" it is a global function that allows to raise your own errors in Lua.

See https://www.lua.org/manual/5.4/manual.html#pdf-error

Body:
I am writing a script to add one line in a .txt per video while using MPV.

However, I am getting a weird error on line 68 with the for loop.
It merely tells me: no error. If I add an error parameter to file:write(message, error), it gives me another error message, stating: bad argument #2 to 'write' (string expected, got function). Any help would be appreciated.

function on_file_end(event)
    if not paused then totaltime = totaltime + os.clock() - lasttime end
    local message = (totaltime .. "s, " .. timeloaded .. ", " .. filename)
    local lines = {}
    local file = io.open(logpath, "r+")
    if file_exists(logpath) then
        for l in file:lines() do
            if not l:find(message, 1, true) then
                lines[#lines+1] = 1
                file:write(message)
            end
        end
        file:close()
    end
end


问:
Reusable workflows with local actions
Reusable workflows with local actions are not working. Reusable workflow is trying to locate the local action in the main repo

Created sample repositories to reproduce the issue

Repo with reusable workflows and local action - https://github.com/vinodsai-a/github-reusable-workflow-sample

Sample repo which uses above reusable workflows - https://github.com/vinodsai-a/github-example-repo

This is the PR link -> https://github.com/vinodsai-a/github-example-repo/pull/1

Error -> https://github.com/vinodsai-a/github-example-repo/pull/1/checks

答:
The issue here is that you can't call a local action on a repository without using the actions/checkout action to access the files in the repository.

on: [workflow_call]

jobs:
  local-action-testing:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2.3.4 # Necessary to access local action
      - uses: ./actions/local-action
```

I've got some proofs of concept here if you want to take a look:

local action workflow and workflow run

reusable workflow using a local action, triggered by this workflow call, performing this workflow run

Title: Reusable workflows with local actions

Body:
The issue here is that you can't call a local action on a repository without using the actions/checkout action to access the files in the repository.

on: [workflow_call]

jobs:
  local-action-testing:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2.3.4 # Necessary to access local action
      - uses: ./actions/local-action

I've got some proofs of concept here if you want to take a look:

local action workflow and workflow run

reusable workflow using a local action, triggered by this workflow call, performing this workflow run