问:
Flutter app with AdMob crash after pushing to another page and moving the app to the background
Now I have a two-page app with the first page to show an adMob banner.

When I move the app to the background, everything is good.

If I navigate to the second page, one logging message is shown.

```<code>E/Surface (12399): getSlotFromBufferLocked: unknown buffer: 0xbc288b10
</code>```

Then I move the app to the background again, while in the second page, the app crashes with the following log.

```<code>E/BufferQueueProducer(12399): [ImageReader-1080x1794f1m3-12399-1](id:306f00000001,api:1,p:12399,c:12399) cancelBuffer: BufferQueue has been abandoned
D/AndroidRuntime(12399): Shutting down VM
E/AndroidRuntime(12399): FATAL EXCEPTION: main
E/AndroidRuntime(12399): Process: com.example.testapp, PID: 12399
E/AndroidRuntime(12399): java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.dispatchWindowVisibilityChanged(int)' on a null object reference
4
E/AndroidRuntime(12399):    at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1614)
E/AndroidRuntime(12399):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2433)
E/AndroidRuntime(12399):    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1952)
E/AndroidRuntime(12399):    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8171)
E/AndroidRuntime(12399):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:972)
E/AndroidRuntime(12399):    at android.view.Choreographer.doCallbacks(Choreographer.java:796)
E/AndroidRuntime(12399):    at android.view.Choreographer.doFrame(Choreographer.java:731)
E/AndroidRuntime(12399):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:957)
E/AndroidRuntime(12399):    at android.os.Handler.handleCallback(Handler.java:938)
E/AndroidRuntime(12399):    at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(12399):    at android.os.Looper.loop(Looper.java:223)
E/AndroidRuntime(12399):    at android.app.ActivityThread.main(ActivityThread.java:7656)
E/AndroidRuntime(12399):    at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(12399):    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
E/AndroidRuntime(12399):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
I/Process (12399): Sending signal. PID: 12399 SIG: 9
Lost connection to device.
</code>```

The first page source

```<code>import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'second_page_screen.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  MobileAds.instance.initialize();
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: const Text("Ads"),
          ),
          body: MainBody()),
    );
  }
}

class MainBody extends StatefulWidget {
  MainBody({Key? key}) : super(key: key);

  @override
  State<MainBody> createState() => _MainBodyState();
}

class _MainBodyState extends State<MainBody> {
  late BannerAd myBanner;
  late BannerAdListener listener;
  late AdWidget adWidget;
  late Container adContainer;

  @override
  void initState() {
    super.initState();

    listener = BannerAdListener(
      onAdLoaded: (Ad ad) => print('Ad loaded.'),
      onAdFailedToLoad: (Ad ad, LoadAdError error) {
        ad.dispose();
        print('Ad failed to load: $error');
      },
      onAdOpened: (Ad ad) => print('Ad opened.'),
      onAdClosed: (Ad ad) => print('Ad closed.'),
      onAdImpression: (Ad ad) => print('Ad impression.'),
    );

    myBanner = BannerAd(
      // final BannerAd myBanner = BannerAd(
      adUnitId: 'ca-app-pub-3940256099942544/6300978111',
      size: AdSize.largeBanner,
      request: const AdRequest(
        keywords: <String>['foo', 'bar'],
        contentUrl: 'http://example.com',
        nonPersonalizedAds: true,
      ),
      listener: listener,
    );

    myBanner.load();
    adWidget = AdWidget(ad: myBanner);

    adContainer = Container(
      alignment: Alignment.center,
      child: adWidget,
      width: myBanner.size.width.toDouble(),
      height: myBanner.size.height.toDouble(),
    );
  }

  @override
  void dispose() {
    super.dispose();
    myBanner.dispose();
  }

  @override
  Widget build(BuildContext context) {
    void _pushPage() {
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => const SecondPageScreen(),
        ),
      );
    }

    return Column(
      children: [
        Container(
          decoration:
              BoxDecoration(border: Border.all(color: Colors.black, width: 2)),
          child: adContainer,
        ),
        TextButton(onPressed: _pushPage, child: Text('Next Page'))
      ],
    );
  }
}
</code>```

[Here is the screenshot of the first page, just for quick reference][1]
[1]: https://i.stack.imgur.com/Mdi67.png

The second page source

```<code>import 'package:flutter/material.dart';

class SecondPageScreen extends StatelessWidget {
  const SecondPageScreen({ Key? key }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('second page')),
      body: Container(

        child: Text('hi')
      ),
    );
  }
}
</code>```

What I have done:

I tried following the AdMob documentation step by step:
https://developers.google.com/admob/flutter/quick-start

And I used the designated test banner ad as shown on the following page:
https://developers.google.com/admob/android/test-ads

I registered the app id in adMob

Quite sure that I made the changes in gradle/androidmanifest/pubspec files correctly.

but in vain...

答: I have this same issue in my application, although I do not fully crash.  I do get getSlotFromBufferLocked every time I push to a page that does not have the ad widget on it.  If I solve this, I will post back here with a solution.</p>

Body:
Now I have a two-page app with the first page to show an adMob banner.

When I move the app to the background, everything is good.

If I navigate to the second page, one logging message is shown.

E/Surface (12399): getSlotFromBufferLocked: unknown buffer: 0xbc288b10

Then I move the app to the background again, while in the second page, the app crashes with the following log.

E/BufferQueueProducer(12399): [ImageReader-1080x1794f1m3-12399-1](id:306f00000001,api:1,p:12399,c:12399) cancelBuffer: BufferQueue has been abandoned
D/AndroidRuntime(12399): Shutting down VM
E/AndroidRuntime(12399): FATAL EXCEPTION: main
E/AndroidRuntime(12399): Process: com.example.testapp, PID: 12399
E/AndroidRuntime(12399): java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.dispatchWindowVisibilityChanged(int)' on a null object reference
4
E/AndroidRuntime(12399):    at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1614)
E/AndroidRuntime(12399):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2433)
E/AndroidRuntime(12399):    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1952)
E/AndroidRuntime(12399):    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8171)
E/AndroidRuntime(12399):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:972)
E/AndroidRuntime(12399):    at android.view.Choreographer.doCallbacks(Choreographer.java:796)
E/AndroidRuntime(12399):    at android.view.Choreographer.doFrame(Choreographer.java:731)
E/AndroidRuntime(12399):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:957)
E/AndroidRuntime(12399):    at android.os.Handler.handleCallback(Handler.java:938)
E/AndroidRuntime(12399):    at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(12399):    at android.os.Looper.loop(Looper.java:223)
E/AndroidRuntime(12399):    at android.app.ActivityThread.main(ActivityThread.java:7656)
E/AndroidRuntime(12399):    at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(12399):    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
E/AndroidRuntime(12399):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
I/Process (12399): Sending signal. PID: 12399 SIG: 9
Lost connection to device.

The first page source

import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'second_page_screen.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  MobileAds.instance.initialize();
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: const Text("Ads"),
          ),
          body: MainBody()),
    );
  }
}

class MainBody extends StatefulWidget {
  MainBody({Key? key}) : super(key: key);

  @override
  State<MainBody> createState() => _MainBodyState();
}

class _MainBodyState extends State<MainBody> {
  late BannerAd myBanner;
  late BannerAdListener listener;
  late AdWidget adWidget;
  late Container adContainer;

  @override
  void initState() {
    super.initState();

    listener = BannerAdListener(
      onAdLoaded: (Ad ad) => print('Ad loaded.'),
      onAdFailedToLoad: (Ad ad, LoadAdError error) {
        ad.dispose();
        print('Ad failed to load: $error');
      },
      onAdOpened: (Ad ad) => print('Ad opened.'),
      onAdClosed: (Ad ad) => print('Ad closed.'),
      onAdImpression: (Ad ad) => print('Ad impression.'),
    );

    myBanner = BannerAd(
      // final BannerAd myBanner = BannerAd(
      adUnitId: 'ca-app-pub-3940256099942544/6300978111',
      size: AdSize.largeBanner,
      request: const AdRequest(
        keywords: <String>['foo', 'bar'],
        contentUrl: 'http://example.com',
        nonPersonalizedAds: true,
      ),
      listener: listener,
    );

    myBanner.load();
    adWidget = AdWidget(ad: myBanner);

    adContainer = Container(
      alignment: Alignment.center,
      child: adWidget,
      width: myBanner.size.width.toDouble(),
      height: myBanner.size.height.toDouble(),
    );
  }

  @override
  void dispose() {
    super.dispose();
    myBanner.dispose();
  }

  @override
  Widget build(BuildContext context) {
    void _pushPage() {
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => const SecondPageScreen(),
        ),
      );
    }

    return Column(
      children: [
        Container(
          decoration:
              BoxDecoration(border: Border.all(color: Colors.black, width: 2)),
          child: adContainer,
        ),
        TextButton(onPressed: _pushPage, child: Text('Next Page'))
      ],
    );
  }
}

[Here is the screenshot of the first page, just for quick reference][1]
[1]: https://i.stack.imgur.com/Mdi67.png

The second page source

import 'package:flutter/material.dart';

class SecondPageScreen extends StatelessWidget {
  const SecondPageScreen({ Key? key }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('second page')),
      body: Container(

        child: Text('hi')
      ),
    );
  }
}

What I have done:

I tried following the AdMob documentation step by step:
https://developers.google.com/admob/flutter/quick-start

And I used the designated test banner ad as shown on the following page:
https://developers.google.com/admob/android/test-ads

I registered the app id in adMob

Quite sure that I made the changes in gradle/androidmanifest/pubspec files correctly.

but in vain...


来源: stackexchange

问:
Obtain the password of ASPNET account
Is there any way to obtain (not change) the password of the ASPNET account on a Windows Server 2003 server?  I need to snyc my workstation's ASPNET account password with the one on the server I am trying to connect to.

I am trying to trouble shoot the following issue with my ASP.NET application.

答:
Essentially No there is no way to retrieve a windows account password.  You can change them with various tools but retrieval is highly unlikely.

You can always create a proxy account on a domain controller and setup an app pool to run under a proxy account so permissions can span across workstations.

OwnerDisplayName: Michael Kniskern

ContentLicense: CC BY-SA 2.5

Title: Obtain the password of ASPNET account

OwnerDisplayName: Quintin Robinson


问:
HRESULT: 0x800A03EC on Worksheet.range
I am getting HRESULT: 0x800A03EC on Worksheet.range method. Number of rows are more than 70K. Office 2007.

Code:

```<code>Microsoft.Office.Interop.Excel.Range neededRange
    = currentWS.Range[cell.Cells[1, 1], cell.Cells[nRowCount, nColumnCount]];
</code>```

Here my rowcount is more than 65530 . Breaks on this function. I have observed that it breaks only when row count goes more than 65530.

答:
This problem occurs if you are using a backwards compatible sheet (a .xls) instead of a .xlsx

To allow sheets to be opened in pre office 2007 version it can't contain more than 65k rows. You can check the number of rows in your sheet by using ctrl+arrowdown till you hit the bottom. If you try to get a range larger than that number of rows it will create an error

ContentLicense: CC BY-SA 3.0

Title: HRESULT: 0x800A03EC on Worksheet.range

Body:
I am getting HRESULT: 0x800A03EC on Worksheet.range method. Number of rows are more than 70K. Office 2007.

Code:

Microsoft.Office.Interop.Excel.Range neededRange
    = currentWS.Range[cell.Cells[1, 1], cell.Cells[nRowCount, nColumnCount]];

Here my rowcount is more than 65530 . Breaks on this function. I have observed that it breaks only when row count goes more than 65530.


问:
How to get igraph to use variables as vertices?
I feel like this is a very stupid question, but here we are.

I'm using igraph for the first time for a network analysis, and the resulting graph has values as vertices instead of the variable names... what is happening?

Thank you.

```<code>data <- read.spss("data.sav", use.value.labels = TRUE, to.data.frame=TRUE, add.undeclared.levels = c("no"))

g <- graph_from_data_frame(data, directed = FALSE)

plot.igraph(g)
</code>```

答:
You'd like the plot to print some feature of the vertices rather than arbitrary numbers. You can specify a vertex.label as shown below.

```<code>plot.igraph(g, vertex.label =  get.vertex.attribute(g, "variable"))
</code>```

Here "variable" is the name of an attribute you would like to print on each vertex.

You can learn more about plotting in the help here: ?igraph.plotting (there's a link to this help page buried in ?plot.igraph)

ContentLicense: CC BY-SA 4.0

Body:
I feel like this is a very stupid question, but here we are.

I'm using igraph for the first time for a network analysis, and the resulting graph has values as vertices instead of the variable names... what is happening?

Thank you.

data <- read.spss("data.sav", use.value.labels = TRUE, to.data.frame=TRUE, add.undeclared.levels = c("no"))

g <- graph_from_data_frame(data, directed = FALSE)

plot.igraph(g)

Body:
You'd like the plot to print some feature of the vertices rather than arbitrary numbers. You can specify a vertex.label as shown below.

plot.igraph(g, vertex.label =  get.vertex.attribute(g, "variable"))

Here "variable" is the name of an attribute you would like to print on each vertex.

You can learn more about plotting in the help here: ?igraph.plotting (there's a link to this help page buried in ?plot.igraph)


问:
Split Regex matches into Groups
I have markdown content with multiple images where each image is:

```<code>![Image Description](/image-path.png)
</code>```

I am selecting all images in the markdown content using Regex:

```<code>var matches = new Regex(@"!\[.*?\]\((.*?)\)").Matches(content);
</code>```

I am getting 2 groups:

```<code>Groups[0] = ![Image Description](/image-path.png);  > (Everything)

Groups[1] = /image-path.png                         > (Image Path)
</code>```

Wouldn't be possible to get instead?

```<code>Groups[0] = Image Description.                      > (Image Description)

Groups[1] = /image-path.png                         > (Image Path)
</code>```

答:
You can capture the relevant sections of your content text by using a capture group.

Compare your regex and mine, where I made a very small change by adding parentheses to capture the Image Description part of your content:

```
!\[.*?\]\((.*?)\)
!\[(.*?)\]\((.*?)\)
```

Capture groups are automatically numbered starting at index 1 so these groups are available as

matches[0].Groups[1]: which contains Image Description and

matches[0].Groups[2]: which contains /image-path.png

matches[0].Group[0] is still the whole match.

```<code>using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
            string content = @"![Image Description](/image-path.png)";
            var matches = new Regex(@"!\[(.*?)\]\((.*?)\)").Matches(content);
            Console.WriteLine(matches[0].Groups[1]);
            Console.WriteLine(matches[0].Groups[2]);
    }
}
</code>```

This outputs:

```
Image Description
/image-path.png
```

Here is a Runnable .NET Fiddle of the above.

Title: Split Regex matches into Groups

Body:
I have markdown content with multiple images where each image is:

![Image Description](/image-path.png)

I am selecting all images in the markdown content using Regex:

var matches = new Regex(@"!\[.*?\]\((.*?)\)").Matches(content);

I am getting 2 groups:

Groups[0] = ![Image Description](/image-path.png);  > (Everything)

Groups[1] = /image-path.png                         > (Image Path)

Wouldn't be possible to get instead?

Groups[0] = Image Description.                      > (Image Description)

Groups[1] = /image-path.png                         > (Image Path)

Body:
You can capture the relevant sections of your content text by using a capture group.

Compare your regex and mine, where I made a very small change by adding parentheses to capture the Image Description part of your content:

!\[.*?\]\((.*?)\)
!\[(.*?)\]\((.*?)\)

Capture groups are automatically numbered starting at index 1 so these groups are available as

matches[0].Groups[1]: which contains Image Description and

matches[0].Groups[2]: which contains /image-path.png

matches[0].Group[0] is still the whole match.

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
            string content = @"![Image Description](/image-path.png)";
            var matches = new Regex(@"!\[(.*?)\]\((.*?)\)").Matches(content);
            Console.WriteLine(matches[0].Groups[1]);
            Console.WriteLine(matches[0].Groups[2]);
    }
}

This outputs:

Image Description
/image-path.png

Here is a Runnable .NET Fiddle of the above.


问:
or logical operator in julia
I'm trying to understand how Julia takes or operator. here is the script that I'm practicing with:

```<code>integer = 52
if length(string(integer)) == 1 || 2
    println("length is 1 or 2")
end
</code>```

but it gives me this error:

```<code>TypeError: non-boolean (Int64) used in boolean context

Stacktrace:
 [1] top-level scope
   @ In[108]:2
 [2] eval
   @ .\boot.jl:373 [inlined]
 [3] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
   @ Base .\loading.jl:1196
</code>```

and I'm sure the problem is where I wrote 1 || 2! how should I specify it in Julia? and how should I interpret TypeError: non-boolean (Int64) used in boolean context error?

答:
You should write:

```<code>length(string(integer)) in [1, 2]
</code>```

or

```<code>1 <= length(string(integer)) <= 2
</code>```

or more verbosely:

```<code>length(string(integer)) == 1 || length(string(integer)) == 2
</code>```

When you write:

```<code>length(string(integer)) == 1 || 2
</code>```

it gets interpreted as "length(string(integer)) == 1" or "2". Since the length of your string is not 1 the value of the whole expression is 2 and 2 is not Bool. You get an error because you try to use non-boolean value in the condition.

You can check that this is indeed what happens by evaluating:

```<code>julia> length(string(integer)) == 1 || 2
2
</code>```

This behavior is explained here in the Julia Manual.

Title: or logical operator in julia

Body:
I'm trying to understand how Julia takes or operator. here is the script that I'm practicing with:

integer = 52
if length(string(integer)) == 1 || 2
    println("length is 1 or 2")
end

but it gives me this error:

TypeError: non-boolean (Int64) used in boolean context

Stacktrace:
 [1] top-level scope
   @ In[108]:2
 [2] eval
   @ .\boot.jl:373 [inlined]
 [3] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
   @ Base .\loading.jl:1196

and I'm sure the problem is where I wrote 1 || 2! how should I specify it in Julia? and how should I interpret TypeError: non-boolean (Int64) used in boolean context error?

Body:
You should write:

length(string(integer)) in [1, 2]

or

1 <= length(string(integer)) <= 2

or more verbosely:

length(string(integer)) == 1 || length(string(integer)) == 2

When you write:

length(string(integer)) == 1 || 2

it gets interpreted as "length(string(integer)) == 1" or "2". Since the length of your string is not 1 the value of the whole expression is 2 and 2 is not Bool. You get an error because you try to use non-boolean value in the condition.

You can check that this is indeed what happens by evaluating:

julia> length(string(integer)) == 1 || 2
2

This behavior is explained here in the Julia Manual.


问:
Stopping Vmmem from using RAM
I am using Docker to run some containers on Windows 10, and when I was done I noticed an application named vmmem was using almost all of my ram: ~12GB. According to this it is because of Docker and it said if I closed all docker images and containers it would stop. So I stopped and removed all Docker containers and images by the following batch file:

```<code>@echo off
FOR /f "tokens=*" %%i IN ('docker ps -aq') DO docker rm %%i
FOR /f "tokens=*" %%i IN ('docker images --format "{{.ID}}"') DO docker rmi %%i
</code>```

from: https://gist.github.com/daredude/045910c5a715c02a3d06362830d045b6

so when you type docker container ls -a & docker image ls -a they both show nothing. However in Task Manager I still see vmmem using about 4 GB of RAM. What else can I do to stop this? Thanks.

答:
Go to Run > Type "services"

Find docker and click stop

Title: Stopping Vmmem from using RAM

Body:
I am using Docker to run some containers on Windows 10, and when I was done I noticed an application named vmmem was using almost all of my ram: ~12GB. According to this it is because of Docker and it said if I closed all docker images and containers it would stop. So I stopped and removed all Docker containers and images by the following batch file:

@echo off
FOR /f "tokens=*" %%i IN ('docker ps -aq') DO docker rm %%i
FOR /f "tokens=*" %%i IN ('docker images --format "{{.ID}}"') DO docker rmi %%i

from: https://gist.github.com/daredude/045910c5a715c02a3d06362830d045b6

so when you type docker container ls -a & docker image ls -a they both show nothing. However in Task Manager I still see vmmem using about 4 GB of RAM. What else can I do to stop this? Thanks.


问:
Issue: aws-encryption-sdk-java version 2.3.3 issues with credentials
We are trying to test decryption login in local using a profile based credentials setup. I was using KMSMasterKeyProvider.withCredentials along with ProfileCredentialsProvider.
In doing so, I realised that aws-encryption-sdk-java 2.3.3 version internally uses aws-java-sdk 1.x version. This is sort of deadlock as we are already on aws-java-sdk 2.x

Any suggestions as to how we can overcome this? Interesting that how Amazon still hasnt migrated aws encryption sdk completely to 2.x.

答:
AWS Encryption SDK for Java IS NOT a part of the AWS SDK for Java. Neither 1.x, nor 2.x. They have different release cycles. Thus, version 2.3.3 of the AWS Encryption SDK for Java doesn't mean that you are using AWS SDK for Java 2.x.

Even in the README they say:

You don't need an Amazon Web Services (AWS) account to use the AWS Encryption SDK, but some of the example code require an AWS account, an AWS KMS key, and the AWS SDK for Java 1.x. (The AWS Encryption SDK for Java does not support the AWS SDK for Java 2.x.)

The docs repeat that:

Prerequisites

Before you install the AWS Encryption SDK for Java, be sure you have
the following prerequisites.

…

AWS SDK for Java (Optional)

The AWS Encryption SDK for Java does not require the AWS SDK for Java.
However, the AWS SDK for Java 1.x is required to use AWS Key Management Service (AWS KMS) as a master key provider.
It's also required for some of the Java code examples in this guide.
The AWS Encryption SDK for Java supports only the 1.x version of the AWS SDK for Java.

To install the AWS SDK for Java 1.x, use Apache Maven.
To import the entire AWS SDK for Java as a dependency, declare it in your pom.xml file.
To create a dependency only for the AWS KMS module, follow the instructions for specifying particular modules, and set the artifactId to aws-java-sdk-kms.

ALAS, you have no choice but to use AWS SDK for Java 1.x. But it should not be a deadlock or a conflict: 1.x and 2.x use different packages.


问:
Rugged can't cherry pick
I'm trying to use rugged (ruby) to cherry pick a commit on a branch like this:

repo.fetch('origin', ['origin/stable/branch_name'],credentials: rugged_credentials)
repo.reset('origin/stable/branch_name', :hard)

repo.checkout('origin/stable/branch_name')
repo.cherrypick('929bab12fdf6f4727ba0a8d704df01fe1e780449')
```
<p>But it seems that the cherry pick is producing uncommitted changes, I would expect to have that commit on that branch and just need to push it to the remote reference.</p>
<p>This is the output of <code>git status</code> after cherry-picking:</p>
<pre class="lang-sh prettyprint-override"><code>HEAD detached from 3807abe
You are currently cherry-picking commit 929bab1.
  (all conflicts fixed: run "git cherry-pick --continue")
  (use "git cherry-pick --abort" to cancel the cherry-pick operation)

Changes to be committed:

        modified:   README.md

</code>```

And if I push to the remote after a cherry pick I got:

>
irb(main):033:0> repo.remotes['origin'].push("HEAD:refs/heads/stable/branch_name",credentials: rugged_credentials)
=> {"refs/heads/stable/2021-12-01"=>"internal error"}
```
<p>It seems that cherry-pick is doing something like:</p>
```git cherry-pick 929bab12fdf6f4727ba0a8d704df01fe1e780449 --no-commit
```

But I don't see an option for that in Rugged cherrypick

答: It turns out cherry-pick in rugged does not auto-commit so an explicit manual commit is needed. You can use the author and commit-message from the commit is being picked.</p>

Title: Rugged can't cherry pick

Body:
I'm trying to use rugged (ruby) to cherry pick a commit on a branch like this:

repo.fetch('origin', ['origin/stable/branch_name'],credentials: rugged_credentials)
repo.reset('origin/stable/branch_name', :hard)

repo.checkout('origin/stable/branch_name')
repo.cherrypick('929bab12fdf6f4727ba0a8d704df01fe1e780449')

But it seems that the cherry pick is producing uncommitted changes, I would expect to have that commit on that branch and just need to push it to the remote reference.

This is the output of git status after cherry-picking:

HEAD detached from 3807abe
You are currently cherry-picking commit 929bab1.
  (all conflicts fixed: run "git cherry-pick --continue")
  (use "git cherry-pick --abort" to cancel the cherry-pick operation)

Changes to be committed:

        modified:   README.md

And if I push to the remote after a cherry pick I got:

>
irb(main):033:0> repo.remotes['origin'].push("HEAD:refs/heads/stable/branch_name",credentials: rugged_credentials)
=> {"refs/heads/stable/2021-12-01"=>"internal error"}

It seems that cherry-pick is doing something like:

git cherry-pick 929bab12fdf6f4727ba0a8d704df01fe1e780449 --no-commit

But I don't see an option for that in Rugged cherrypick


答:
We could use rowwise

```<code>library(dplyr)
library(stringr)
 df1  %>%
  rowwise() %>%
  transmute(ID, TRA = sprintf("{%s}",
    str_c(names(.)[-1][c_across(starts_with("P")) == 1],
     collapse=", "))) %>%
 ungroup
</code>```

-output

```<code># A tibble: 3 × 2
     ID TRA
  <int> <chr>
1     1 {P2, P3}
2     2 {P1, P2, P265}
3     3 {P3, P265}
</code>```

Or using base R

```<code>cbind(df1['ID'], TRA = apply(df1[-1], 1,
     \(x) sprintf("{%s}", toString(names(x)[x == 1]))))
  ID            TRA
1  1       {P2, P3}
2  2 {P1, P2, P265}
3  3     {P3, P265}
</code>```

data

```<code>df1 <- structure(list(ID = 1:3, P1 = c(0L, 1L, 0L), P2 = c(1L, 1L, 0L
), P3 = c(1L, 0L, 1L), P265 = c(0L, 1L, 1L)),
class = "data.frame", row.names = c(NA,
-3L))
</code>```

Title: convert data to transaction in Rstudio

Body:
I have a data as follows and I want to convert it to transaction format at Rstudio.Please guide me

ID    P1 P2 P3 ....... p265                 ID     TRA
1     0  1  1  .......  0                   1      {P2,p3,....}
2     1  1  0  .......  1                   2      {P1,P2,...,P265}
3     0  0  1  .......  1                   3      {p3,...,p265}
.     .  .  .           .                   .      .
.     .  .  .           .                   .      .
.     .  .  .           .                   .      .
1000  1  0  1  .......  0                   1000   {p1,p3,...}

Body:
We could use rowwise

library(dplyr)
library(stringr)
 df1  %>%
  rowwise() %>%
  transmute(ID, TRA = sprintf("{%s}",
    str_c(names(.)[-1][c_across(starts_with("P")) == 1],
     collapse=", "))) %>%
 ungroup

-output

# A tibble: 3 × 2
     ID TRA
  <int> <chr>
1     1 {P2, P3}
2     2 {P1, P2, P265}
3     3 {P3, P265}

Or using base R

cbind(df1['ID'], TRA = apply(df1[-1], 1,
     \(x) sprintf("{%s}", toString(names(x)[x == 1]))))
  ID            TRA
1  1       {P2, P3}
2  2 {P1, P2, P265}
3  3     {P3, P265}

data

df1 <- structure(list(ID = 1:3, P1 = c(0L, 1L, 0L), P2 = c(1L, 1L, 0L
), P3 = c(1L, 0L, 1L), P265 = c(0L, 1L, 1L)),
class = "data.frame", row.names = c(NA,
-3L))


问:
How to use the useSound hook with multiple audio files
Hi I'm trying to play a different mp3 sound on hover and then stop the sound when the mouse leaves. I installed the use-sound library but I can't figure out how to use it with more than one audio file.

If I rename the play function into playAudio1 for example I can make useSound play the right audio file, but I can't figure out how to stop the correct audio file. I was thinking is there a way to assign the "stop" function in each hook to a different variable name, so I can reference it below in the onMouseLeave event.

The code below gives me an error because I have two identical "stop" functions.

```<code>import React, { useState} from "react";
import Audio1 from "../public/mp3/audio1.mp3";
import Audio2 from "../public/mp3/audio2.mp3";
import useSound from "use-sound";

function Home() {
   const [hoverAudio1, setHoverAudio1] = useState(false);
   const [hoverAudio2, setHoverAudio2] = useState(false);

   const [playAudio1, { stop }] = useSound(Audio1, {
    volume: 0.5,
   });
   const [playAudio2, { stop }] = useSound(Audio2, {
    volume: 0.5,
   });

   return (
      <div
          onMouseEnter={() => {
            setHoverAudio1(true);
            playAudio1();
          }}
          onMouseLeave={() => {
            setHoverAudio1(false);
            stop();
          }}
        >
      </div>
      <div
          onMouseEnter={() => {
            setHoverAudio2(true);
            playAudio2();
          }}
          onMouseLeave={() => {
            setHoverAudio2(false);
            stop();
          }}
        >
      </div>
    )}
</code>```

答: Instead of [playAudio1, {stop}] you should use [playAudio1, stopAudio1] to get the return values from the hook. Then you can access the stop function with stopAudio1.stop().

Body:
Hi I'm trying to play a different mp3 sound on hover and then stop the sound when the mouse leaves. I installed the use-sound library but I can't figure out how to use it with more than one audio file.

If I rename the play function into playAudio1 for example I can make useSound play the right audio file, but I can't figure out how to stop the correct audio file. I was thinking is there a way to assign the "stop" function in each hook to a different variable name, so I can reference it below in the onMouseLeave event.

The code below gives me an error because I have two identical "stop" functions.

import React, { useState} from "react";
import Audio1 from "../public/mp3/audio1.mp3";
import Audio2 from "../public/mp3/audio2.mp3";
import useSound from "use-sound";

function Home() {
   const [hoverAudio1, setHoverAudio1] = useState(false);
   const [hoverAudio2, setHoverAudio2] = useState(false);

   const [playAudio1, { stop }] = useSound(Audio1, {
    volume: 0.5,
   });
   const [playAudio2, { stop }] = useSound(Audio2, {
    volume: 0.5,
   });

   return (

 {
            setHoverAudio1(true);
            playAudio1();
          }}
          onMouseLeave={() => {
            setHoverAudio1(false);
            stop();
          }}
        >

 {
            setHoverAudio2(true);
            playAudio2();
          }}
          onMouseLeave={() => {
            setHoverAudio2(false);
            stop();
          }}
        >

    )}


问:
Add custom button near Save button Django-admin
I have added a custom button in django admin, however its below the Save and Save and Close buttons, how can I make this custom button on the same line with the 2 buttons above, below is the image:

Then, how I overridden the button with the templates:

```<code>{% extends 'admin/custominlines/change_form.html' %}
{% load i18n %}
 {% block submit_buttons_bottom %}
     {{ block.super }}
       {% if request.GET.edit %}
           <div class="submit-row">
           {% for obj in transitions %}
                <input type="submit" value="{{ obj }}" name="{{ obj }}">
           {% endfor %}
            </div>
     {% endif %}
{% endblock %}
</code>```

答:
You don't have to override change_form.html. Instead, you can just override submit_line.html

```<code>{% extends 'admin/submit_line.html' %}
{% load i18n admin_urls %}

{% block submit-row %}
    {{ block.super }}
    {% for obj in transitions %}
        <input type="submit" value="{{ obj }}" name="{{ obj }}">
    {% endfor %}
{% endblock %}
</code>```

Body:
I have added a custom button in django admin, however its below the Save and Save and Close buttons, how can I make this custom button on the same line with the 2 buttons above, below is the image:

Then, how I overridden the button with the templates:

{% extends 'admin/custominlines/change_form.html' %}
{% load i18n %}
 {% block submit_buttons_bottom %}
     {{ block.super }}
       {% if request.GET.edit %}

           {% for obj in transitions %}
                <input type="submit" value="{{ obj }}" name="{{ obj }}">
           {% endfor %}

     {% endif %}
{% endblock %}

Body:
You don't have to override change_form.html. Instead, you can just override submit_line.html

{% extends 'admin/submit_line.html' %}
{% load i18n admin_urls %}

{% block submit-row %}
    {{ block.super }}
    {% for obj in transitions %}
        <input type="submit" value="{{ obj }}" name="{{ obj }}">
    {% endfor %}
{% endblock %}


问:
Unable to serve flask RESTful API using gunicorn
My application is in the following structure:

```<code>└── wsgi_home
    ├── __init__.py
    ├── __init__.pyc
    └── main.py
</code>```

I import everything from a folder called entry:

```<code>from entry.main import main as flask_app

app = flask_app(None, is_wsgi=True)

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=9080)
</code>```

Every time I run this application using gunicorn I get:

```<code>[2022-02-11 09:37:07 +0000] [1406] [INFO] Starting gunicorn 19.10.0
[2022-02-11 09:37:07 +0000] [1406] [INFO] Listening at: http://0.0.0.0:9080 (1406)
[2022-02-11 09:37:07 +0000] [1406] [INFO] Using worker: sync
[2022-02-11 09:37:07 +0000] [1410] [INFO] Booting worker with pid: 1410
Failed to find application object 'main' in 'wsgi_main'
[2022-02-11 09:37:07 +0000] [1410] [INFO] Worker exiting (pid: 1410)
[2022-02-11 09:37:07 +0000] [1406] [INFO] Shutting down: Master
[2022-02-11 09:37:07 +0000] [1406] [INFO] Reason: App failed to load.
</code>```

How do I fix this issue?

答:
plz changes in your file:-

app = Flask(name)

app.run(debug=False)

Procfile
web: gunicorn app:app

Body:
My application is in the following structure:

└── wsgi_home
    ├── __init__.py
    ├── __init__.pyc
    └── main.py

I import everything from a folder called entry:

from entry.main import main as flask_app

app = flask_app(None, is_wsgi=True)

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=9080)

Every time I run this application using gunicorn I get:

[2022-02-11 09:37:07 +0000] [1406] [INFO] Starting gunicorn 19.10.0
[2022-02-11 09:37:07 +0000] [1406] [INFO] Listening at: http://0.0.0.0:9080 (1406)
[2022-02-11 09:37:07 +0000] [1406] [INFO] Using worker: sync
[2022-02-11 09:37:07 +0000] [1410] [INFO] Booting worker with pid: 1410
Failed to find application object 'main' in 'wsgi_main'
[2022-02-11 09:37:07 +0000] [1410] [INFO] Worker exiting (pid: 1410)
[2022-02-11 09:37:07 +0000] [1406] [INFO] Shutting down: Master
[2022-02-11 09:37:07 +0000] [1406] [INFO] Reason: App failed to load.

How do I fix this issue?


问:
Combine smallest elements in one category 'Other' in a pie chart R
I am trying to plot a pie chart with only 3 segments.  I want the 2 largest elements and after that all the smallest elements in one category "Other" .  Is there a way to do this directly from a charting package or do I need to manipulate the data set to combine all the smallest values into one.  And is there a quick function to do that?  Thanks for your answers.</p>

答:
A quick way of doing is this is by slightly formatting your data set. Since you didn't provide an example, I borrowed one from the R Graph Gallery.

Consider a simple data frame with 5 categories (A to E):

```<code>library(tidyverse)

data <- data.frame(
  group=LETTERS[1:5],
  value=c(13,7,9,21,2)
)
</code>```

We can use rank() and ifelse() to format this data into 3 groups: the two with the largest values and 'Other':

```<code>plotting_data <- data %>%
  mutate(rank = rank(-value),
         group = ifelse(rank <= 2, group, 'Other'))
</code>```

And then simply use this data set for creating the pie chart:

```<code>ggplot(plotting_data, aes(x="", y=value, fill=group)) +
  geom_bar(stat="identity", width=1) +
  coord_polar("y", start=0)
</code>```

Body:
A quick way of doing is this is by slightly formatting your data set. Since you didn't provide an example, I borrowed one from the R Graph Gallery.

Consider a simple data frame with 5 categories (A to E):

library(tidyverse)

data <- data.frame(
  group=LETTERS[1:5],
  value=c(13,7,9,21,2)
)

We can use rank() and ifelse() to format this data into 3 groups: the two with the largest values and 'Other':

plotting_data <- data %>%
  mutate(rank = rank(-value),
         group = ifelse(rank <= 2, group, 'Other'))

And then simply use this data set for creating the pie chart:

ggplot(plotting_data, aes(x="", y=value, fill=group)) +
  geom_bar(stat="identity", width=1) +
  coord_polar("y", start=0)


问:
convert time to seconds struct in c
The above code is to convert a time to seconds in c using struct I dont know how to use stdarg in function please help me...

i created a struct called time.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

typedef struct time {
    int hours, minutes, seconds;
} Time;

int printTimeInSeconds(int n,int,...){
    Time res;
    res.t1=time1.hours*3600+time1.minutes*60+time1.seconds;
    res.t2=time2.hours*3600+time2.minutes*60+time2.seconds;
    res.t3=time3.hours*3600+time3.minutes*60+time3.seconds;
    res.t4=time4.hours*3600+time4.minutes*60+time4.seconds;

    return res;
}

int main() {
    Time time1, time2, time3, time4;
    scanf("%d:%d:%d", &time1.hours, &time1.minutes, &time1.seconds);
    scanf("%d:%d:%d", &time2.hours, &time2.minutes, &time2.seconds);
    scanf("%d:%d:%d", &time3.hours, &time3.minutes, &time3.seconds);
    scanf("%d:%d:%d", &time4.hours, &time4.minutes, &time4.seconds);
    printTimeInSeconds(1, time1);
    printTimeInSeconds(2, time1, time2);
    printTimeInSeconds(3, time1, time2, time3);
    printTimeInSeconds(4, time1, time2, time3, time4);
    return 0;
}
</code>```

Input:

```<code>00:00:01
01:00:00
12:59:59
00:01:00
</code>```

Output:

```<code>1
3601
50400
50460
</code>```

I wrote the function part wrongly and please explain how to use stdarg in this function

答:
Here is a link for stdarg with a well explained example.

Explanation for va_list
And an explanation for va_arg, va_start and va_end

I used Visual Studio to Compile.

First you have to decide if your function should print or if you want the result.

I print the result and return it.

In the function printTimeInSeconds() create type va_list(ap) for va_start and va_arg

Initialize type va_list(ap) with va_start for future retrive of passed arguments with va_arg.

va_arg returns value of (ap) as type of second parameter(Time) and changes pointer(ap) to next Argument.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

#pragma warning (disable:4996)

typedef struct {
    int hours, minutes, seconds;
} Time;

int printTimeInSeconds(int n_args,...) {
    int res = 0;
    va_list ap;
    va_start(ap, n_args);
    for (int i = 1; i <= n_args; ++i)
    {
        //Better solution from Jonathan Leffler
        Time t = va_arg(ap, Time);
        res += (t.hours * 60 + t.minutes) * 60 + t.seconds;
        /*My old solution
             //va_arg(ap, int) returns the value of type(int) and moves pointer(ap)+= size of type(int)
        res += va_arg(ap, int) * 3600;      //hours
        res += va_arg(ap, int) * 60;        //minutes
        res += va_arg(ap, int);             //seconds
             //va_arg(ap, int) type is always int because the struct is only int
        */
    }
    //va_end before return of function
    va_end(ap);
    //if you want your function to print
    printf("%d\n", res);
    //if you need the result
    return res;
}

int main() {
    Time time1, time2, time3, time4;
    scanf("%d:%d:%d", &time1.hours, &time1.minutes, &time1.seconds);
    scanf("%d:%d:%d", &time2.hours, &time2.minutes, &time2.seconds);
    scanf("%d:%d:%d", &time3.hours, &time3.minutes, &time3.seconds);
    scanf("%d:%d:%d", &time4.hours, &time4.minutes, &time4.seconds);
    printTimeInSeconds(1, time1);
    printTimeInSeconds(2, time1, time2);
    printTimeInSeconds(3, time1, time2, time3);
    printTimeInSeconds(4, time1, time2, time3, time4);
    return 0;
}
</code>```

Title: convert time to seconds struct in c

Body:
The above code is to convert a time to seconds in c using struct I dont know how to use stdarg in function please help me...

i created a struct called time.

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

typedef struct time {
    int hours, minutes, seconds;
} Time;

int printTimeInSeconds(int n,int,...){
    Time res;
    res.t1=time1.hours*3600+time1.minutes*60+time1.seconds;
    res.t2=time2.hours*3600+time2.minutes*60+time2.seconds;
    res.t3=time3.hours*3600+time3.minutes*60+time3.seconds;
    res.t4=time4.hours*3600+time4.minutes*60+time4.seconds;

    return res;
}

int main() {
    Time time1, time2, time3, time4;
    scanf("%d:%d:%d", &time1.hours, &time1.minutes, &time1.seconds);
    scanf("%d:%d:%d", &time2.hours, &time2.minutes, &time2.seconds);
    scanf("%d:%d:%d", &time3.hours, &time3.minutes, &time3.seconds);
    scanf("%d:%d:%d", &time4.hours, &time4.minutes, &time4.seconds);
    printTimeInSeconds(1, time1);
    printTimeInSeconds(2, time1, time2);
    printTimeInSeconds(3, time1, time2, time3);
    printTimeInSeconds(4, time1, time2, time3, time4);
    return 0;
}

Input:

00:00:01
01:00:00
12:59:59
00:01:00

Output:

1
3601
50400
50460

I wrote the function part wrongly and please explain how to use stdarg in this function

Body:
Here is a link for stdarg with a well explained example.

Explanation for va_list
And an explanation for va_arg, va_start and va_end

I used Visual Studio to Compile.

First you have to decide if your function should print or if you want the result.

I print the result and return it.

In the function printTimeInSeconds() create type va_list(ap) for va_start and va_arg

Initialize type va_list(ap) with va_start for future retrive of passed arguments with va_arg.

va_arg returns value of (ap) as type of second parameter(Time) and changes pointer(ap) to next Argument.

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

#pragma warning (disable:4996)

typedef struct {
    int hours, minutes, seconds;
} Time;

int printTimeInSeconds(int n_args,...) {
    int res = 0;
    va_list ap;
    va_start(ap, n_args);
    for (int i = 1; i <= n_args; ++i)
    {
        //Better solution from Jonathan Leffler
        Time t = va_arg(ap, Time);
        res += (t.hours * 60 + t.minutes) * 60 + t.seconds;
        /*My old solution
             //va_arg(ap, int) returns the value of type(int) and moves pointer(ap)+= size of type(int)
        res += va_arg(ap, int) * 3600;      //hours
        res += va_arg(ap, int) * 60;        //minutes
        res += va_arg(ap, int);             //seconds
             //va_arg(ap, int) type is always int because the struct is only int
        */
    }
    //va_end before return of function
    va_end(ap);
    //if you want your function to print
    printf("%d\n", res);
    //if you need the result
    return res;
}

int main() {
    Time time1, time2, time3, time4;
    scanf("%d:%d:%d", &time1.hours, &time1.minutes, &time1.seconds);
    scanf("%d:%d:%d", &time2.hours, &time2.minutes, &time2.seconds);
    scanf("%d:%d:%d", &time3.hours, &time3.minutes, &time3.seconds);
    scanf("%d:%d:%d", &time4.hours, &time4.minutes, &time4.seconds);
    printTimeInSeconds(1, time1);
    printTimeInSeconds(2, time1, time2);
    printTimeInSeconds(3, time1, time2, time3);
    printTimeInSeconds(4, time1, time2, time3, time4);
    return 0;
}


问:
Check traffic rules in openshift
We've got an OpenShift cluster with Istio in which we want to debug routing rules. But in my container I don't even have iptables utility or iptables config file with rule chains. How can I check traffic rules from within container?

Thanks in advance.

答: First you have to check your istio configs like virtualServices then if you want to go deeper you can  use istioctl proxy-config routes <pod-name>.

Title: Check traffic rules in openshift


问:
How do I set initialValues of useFormik to data returned from an API request
I have an update ProfilePage component and I want to preload the form values with the data received from an Axios API request using useQuery, but it seems the useFormik initialValues render before the request is completed therefore having the initial values to be undefined, can anyone help me ?

```<code>  const { isSuccess, data } = useQuery("author", async () => {
    const endPoint = `${baseURL}/auth/author`;
    return Axios.get(endPoint, {
      headers: {
        "x-auth-token": token,
      },
    })
      .then(({ data }) => {
        return data.author;
      })
      .catch((err) => {
        setErrors(err.response.data.errors[0].msg);
        console.log(errors);
      });
  });

  const formik = useFormik({
    initialValues: {
      firstname: data.firstname,
      lastname: data.lastname,
      gender: data.gender,
      dob: data.dob,
      email: data.email,
      oldPassword: "",
      newPassword: "",
      confirmNewPassword: "",
      profilePic: "",
    },
    validationSchema: Yup.object({
      firstname: Yup.string()
        .max(20, "First Name must not be more that 20 characters")
        .required("Required*"),
      lastname: Yup.string()
        .max(20, "Last Name must not be more that 20 characters")
        .required("Required*"),
      gender: Yup.string().required("Required*"),
      dob: Yup.string().required("Required*"),
      email: Yup.string()
        .email("Must be a Valid Email Address")
        .required("Required*"),
      oldPassword: Yup.string().min(
        6,
        "Your password must be more than 6 characters"
      ),
      newPassword: Yup.string().min(
        6,
        "Your password must be more than 6 characters"
      ),
      confirmNewPassword: Yup.string(),
    }),
    onSubmit: (values) => {
      console.log(values);
    },
  });
</code>```

The error I get is Cannot read properties of undefined (reading 'firstname')
if I could get a way make useFormik render just after the API request it'd help

答:
what you can do after api call in useEffect set values
below sample code for further understanding
isEmpty is from lodash you can use some alternate if you want for checking if data is not empty

```<code>useEffect(() => {
    if (!isEmpty(data)) {
      formik.setValues({
        ...data
      });
    }
  }, [data]);
</code>```

Body:
I have an update ProfilePage component and I want to preload the form values with the data received from an Axios API request using useQuery, but it seems the useFormik initialValues render before the request is completed therefore having the initial values to be undefined, can anyone help me ?

  const { isSuccess, data } = useQuery("author", async () => {
    const endPoint = `${baseURL}/auth/author`;
    return Axios.get(endPoint, {
      headers: {
        "x-auth-token": token,
      },
    })
      .then(({ data }) => {
        return data.author;
      })
      .catch((err) => {
        setErrors(err.response.data.errors[0].msg);
        console.log(errors);
      });
  });

  const formik = useFormik({
    initialValues: {
      firstname: data.firstname,
      lastname: data.lastname,
      gender: data.gender,
      dob: data.dob,
      email: data.email,
      oldPassword: "",
      newPassword: "",
      confirmNewPassword: "",
      profilePic: "",
    },
    validationSchema: Yup.object({
      firstname: Yup.string()
        .max(20, "First Name must not be more that 20 characters")
        .required("Required*"),
      lastname: Yup.string()
        .max(20, "Last Name must not be more that 20 characters")
        .required("Required*"),
      gender: Yup.string().required("Required*"),
      dob: Yup.string().required("Required*"),
      email: Yup.string()
        .email("Must be a Valid Email Address")
        .required("Required*"),
      oldPassword: Yup.string().min(
        6,
        "Your password must be more than 6 characters"
      ),
      newPassword: Yup.string().min(
        6,
        "Your password must be more than 6 characters"
      ),
      confirmNewPassword: Yup.string(),
    }),
    onSubmit: (values) => {
      console.log(values);
    },
  });

The error I get is Cannot read properties of undefined (reading 'firstname')
if I could get a way make useFormik render just after the API request it'd help

Body:
what you can do after api call in useEffect set values
below sample code for further understanding
isEmpty is from lodash you can use some alternate if you want for checking if data is not empty

useEffect(() => {
    if (!isEmpty(data)) {
      formik.setValues({
        ...data
      });
    }
  }, [data]);


问:
Add event to all buttons of the same class with jQuery
This might be easy but I've searched SO and tried some suggestions for this none of which work. I'm using an MVC Editor Template that has a div with a standard html button and other fields. When I pass a collection to the template it will render the fields of each item in the collection with unique ids. Then I want to open a dialog box when any of the buttons are clicked. The buttons are rendered as such within the Editor Template:

```<code>@model ProductViewModel
<span>
    <button id="btnSelectTags-@(ViewData.TemplateInfo.HtmlFieldPrefix)" class="sig-button ie-shadowed select-tag" type="button" title="Select tags..." style="margin-right: 10px">Select tags</button>
</span>
// other fields
</code>```

So if I pass a collection with 2 objects to the Editor Template I get the html below:

```<code><button title="Select tags..." class="sig-button ie-shadowed select-tag" id="btnSelectTags-Products[0]" style="margin-right: 10px;" type="button">
// other fields then next item:
<button title="Select tags..." class="sig-button ie-shadowed select-tag" id="btnSelectTags-Products[1]" style="margin-right: 10px;" type="button">
</code>```

This seems fine and gives each button a unique id. They need to have a unique id (I think) as the item in every div can have its own set of tags. So I want to add a click event to each button that will open a dialog box, using this jQuery (I've tried including the other classes in the selector also and tried without "button"):

```<code>if ($("button.select-tag")) {
    $(".select-tag").click(function () {
        showTagDialogBox();
    });
}
</code>```

Here's the div where the tags get rendered:

```<code><div style="display: none">
    <div id="tagDialogBox" title="Add Tags">
        @Html.EditorFor(x => x.ProductViewModels)
    </div>
</div>
</code>```

Here's the showTagDialogBox function:

```<code>function showTagDialogBox() {
    $('#tagDialogBox').dialog({
        autoOpen: false,
        title: "Select Tags",
        modal: true,
        height: 530,
        width: 700,
        buttons: {
            "Save": function () {
                $(this).dialog("close");
            },
            "Cancel": function () {
                $(this).dialog("close");
            }
        }
    });

    return false;
}
</code>```

However when I click any of the buttons nothing happens - I don't get any js errors in Firebug either. Can anyone spot what I might be doing wrong? Here's a pic of what I'm trying to do:

答:
Just a generic answer to your title, i.e. to add click event to all buttons of some class:</p>
```<code>@section scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            // Items that NEED to be set after the page is loaded.
            $('.some-class').on('click', 'button', function (event)
            {
               event.preventDefault();
               someFunction();
            }
            // And so on.
        });

        //Items that DON'T NEED to be called on page load can be put outside document.ready. For eg:
        function someFunction() { // Some logic }
    </script>
}
</code>```

Body:
This might be easy but I've searched SO and tried some suggestions for this none of which work. I'm using an MVC Editor Template that has a div with a standard html button and other fields. When I pass a collection to the template it will render the fields of each item in the collection with unique ids. Then I want to open a dialog box when any of the buttons are clicked. The buttons are rendered as such within the Editor Template:

@model ProductViewModel

    <button id="btnSelectTags-@(ViewData.TemplateInfo.HtmlFieldPrefix)" class="sig-button ie-shadowed select-tag" type="button" title="Select tags..." style="margin-right: 10px">Select tags</button>

// other fields

So if I pass a collection with 2 objects to the Editor Template I get the html below:

<button title="Select tags..." class="sig-button ie-shadowed select-tag" id="btnSelectTags-Products[0]" style="margin-right: 10px;" type="button">
// other fields then next item:
<button title="Select tags..." class="sig-button ie-shadowed select-tag" id="btnSelectTags-Products[1]" style="margin-right: 10px;" type="button">

This seems fine and gives each button a unique id. They need to have a unique id (I think) as the item in every div can have its own set of tags. So I want to add a click event to each button that will open a dialog box, using this jQuery (I've tried including the other classes in the selector also and tried without "button"):

if ($("button.select-tag")) {
    $(".select-tag").click(function () {
        showTagDialogBox();
    });
}

Here's the div where the tags get rendered:

        @Html.EditorFor(x => x.ProductViewModels)

Here's the showTagDialogBox function:

function showTagDialogBox() {
    $('#tagDialogBox').dialog({
        autoOpen: false,
        title: "Select Tags",
        modal: true,
        height: 530,
        width: 700,
        buttons: {
            "Save": function () {
                $(this).dialog("close");
            },
            "Cancel": function () {
                $(this).dialog("close");
            }
        }
    });

    return false;
}

However when I click any of the buttons nothing happens - I don't get any js errors in Firebug either. Can anyone spot what I might be doing wrong? Here's a pic of what I'm trying to do:

Body:
Just a generic answer to your title, i.e. to add click event to all buttons of some class:

@section scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            // Items that NEED to be set after the page is loaded.
            $('.some-class').on('click', 'button', function (event)
            {
               event.preventDefault();
               someFunction();
            }
            // And so on.
        });

        //Items that DON'T NEED to be called on page load can be put outside document.ready. For eg:
        function someFunction() { // Some logic }
    </script>
}


问:
Reordering the results of several asynchronous requests
I need some conceptual help:

I am trying to display a page that contains a single table with a lot of data (moderately big number of rows, very big number of columns), and I want that page to be as fast and smooth as possible from the user's point of view. What I am doing is the following:

Retrieve a list containing the database primary keys of the elements to be displayed in the table.

Iterate through the list, asynchronously request each element given its primary key, and, every time element is retrieved, add it to the table.

Each of these retrieval operations is implemented as a Web service call.

Now my questions are the following:

How can I reorder the elements if they arrive in a different order than they were requested? (It is absolutely essential for me that these elements be inserted in the table in the same positions as their respective primary keys were in the original list.)

Can this strategy be made compatible with any of the main JavaScript grid controls available out there? (Without me having to modify or understand how these controls internally work, of course.)

答: I think you can look into the jQuery DataTables plugin. It is quite a powerful tool to display data in a tabular format. </p>


问:
Counting all descendants in a family tree (python dictionary)
I'm kind of beating my head against a wall here and I'm hoping that someone on stackoverflow can help me.
Let's say I have a python dictionary that looks like:

```<code>{
    'Son1': 'Father',
    'Son2': 'Father',
    'Father': 'Grandfather',
    'Grandfather': 'Great Grandfather',
    'Uncle': 'Grandfather',
    'Cousin': 'Uncle',
}
</code>```

Right, so each key is a person and the corresponding value is that person's parent. All I want to do at the moment is find out how many total descendants a given person has.
I've got a pretty simple function that finds and returns a list of a given person's immediate children.

```<code>def get_kids(person, dictionary):
    kids = []
    for key in dictionary:
        if dictionary[key] == person:
            kids.append(key)
    return kids
</code>```

Which works fine. From there, I keep thinking that all I need to do is write a recursive function that's something like:

```<code>def descendants(person, dictionary, count):
    kids = get_kids(person, dictionary)
    count = count + len(kids)
    for kid in kids:
         descendants(kid, dictionary, count)
    return count
</code>```

But this doesn't work. I think because the 'count' variable resets at the end of a 'line' of descendants, instead of being a running total. e.g. If I run:

```<code>descendants('Grandfather', familydictionary, 0)
</code>```

I get back a value of 2 (instead of the hoped-for 5). Presumably, the count reaches 4 when the function is exploring the 'Father' line, but then drops back down to 3 when it explores the 'Uncle' line, instead. And then, I suppose, the count drops all the way back to 2 when the function finds that 'Cousin' has no kids?
I often struggle with these kinds of recursion problems. What I want to do is pretty straightforward: check if a person has kids and count them, check if their kids have kids and count them, add them to the total ... keep going until there are no more kids. But I get very muddled when I try to actually, well, write the code that does that.
Any help or guidance is appreciated.

答:
You need to actually use the value returned by the recursive call. And passing count in isn't necessary or useful. It's being passed by value, so changing it inside one level of your recursion won't affect the parent calls at all. Rather:

```<code>def descendants(person, dictionary):
    count = 0
    for kid in get_kids(person, dictionary):
         count += 1 + descendants(kid, dictionary)
    return count
</code>```

Body:
I'm kind of beating my head against a wall here and I'm hoping that someone on stackoverflow can help me.
Let's say I have a python dictionary that looks like:

{
    'Son1': 'Father',
    'Son2': 'Father',
    'Father': 'Grandfather',
    'Grandfather': 'Great Grandfather',
    'Uncle': 'Grandfather',
    'Cousin': 'Uncle',
}

Right, so each key is a person and the corresponding value is that person's parent. All I want to do at the moment is find out how many total descendants a given person has.
I've got a pretty simple function that finds and returns a list of a given person's immediate children.

def get_kids(person, dictionary):
    kids = []
    for key in dictionary:
        if dictionary[key] == person:
            kids.append(key)
    return kids

Which works fine. From there, I keep thinking that all I need to do is write a recursive function that's something like:

def descendants(person, dictionary, count):
    kids = get_kids(person, dictionary)
    count = count + len(kids)
    for kid in kids:
         descendants(kid, dictionary, count)
    return count

But this doesn't work. I think because the 'count' variable resets at the end of a 'line' of descendants, instead of being a running total. e.g. If I run:

descendants('Grandfather', familydictionary, 0)

I get back a value of 2 (instead of the hoped-for 5). Presumably, the count reaches 4 when the function is exploring the 'Father' line, but then drops back down to 3 when it explores the 'Uncle' line, instead. And then, I suppose, the count drops all the way back to 2 when the function finds that 'Cousin' has no kids?
I often struggle with these kinds of recursion problems. What I want to do is pretty straightforward: check if a person has kids and count them, check if their kids have kids and count them, add them to the total ... keep going until there are no more kids. But I get very muddled when I try to actually, well, write the code that does that.
Any help or guidance is appreciated.

Body:
You need to actually use the value returned by the recursive call. And passing count in isn't necessary or useful. It's being passed by value, so changing it inside one level of your recursion won't affect the parent calls at all. Rather:

def descendants(person, dictionary):
    count = 0
    for kid in get_kids(person, dictionary):
         count += 1 + descendants(kid, dictionary)
    return count


问:
How to extract all paragraphs that start with a specific word?
I'm practicing working with strings, and I would like some help:
I have a text as a string that I extracted doing web scraping. It's a play where several characters speak. I want to grab only the lines of a specific character. Every character speaks in a new paragraph. Let's say this is the string:

```<code>Character 1: aaaaaaaaaaa.
Character 2: bbbbbbb.
Character 3: ccc.
Character 1: ddddddd.
Character 3: eeee.
</code>```

I only want to grab what Character 1. The string character1 should be:

```<code>aaaaaaaaaaa.ddddddd.
</code>```

As a general example of what I tried:

```<code>def select_lines(text, paragraph_ending, keyword):
    for i in text:
        if text.startswith(keyword):
            text.split(paragraph_ending)

character1 = select_lines(voices, '\n', 'Character 1: ')
print(character1)
</code>```

答:
It first splits the string into a list of paragraphs and checks if each paragraph starts with the keyword. If it does then it removes the keyword from it and adds it to a variable and after that it returns the result variable.</p>
```<code>data = 'Character 1: aaaaaaaaaaa.\nCharacter 2: bbbbbbb.\nCharacter 3: ccc.\nCharacter 1: ddddddd.\nCharacter 3: eeee.'

def select_lines(text, paragraph_ending, keyword):
    paras = text.split(paragraph_ending)
    result = ''
    for para in paras:
        if ( para.startswith( keyword ) ):
            x = para.replace(keyword, '')
            result += x

    return result

character1 = select_lines(data, '\n', 'Character 1: ')
print(character1)
</code>```

Body:
I'm practicing working with strings, and I would like some help:
I have a text as a string that I extracted doing web scraping. It's a play where several characters speak. I want to grab only the lines of a specific character. Every character speaks in a new paragraph. Let's say this is the string:

Character 1: aaaaaaaaaaa.
Character 2: bbbbbbb.
Character 3: ccc.
Character 1: ddddddd.
Character 3: eeee.

I only want to grab what Character 1. The string character1 should be:

aaaaaaaaaaa.ddddddd.

As a general example of what I tried:

def select_lines(text, paragraph_ending, keyword):
    for i in text:
        if text.startswith(keyword):
            text.split(paragraph_ending)

character1 = select_lines(voices, '\n', 'Character 1: ')
print(character1)

Body:
It first splits the string into a list of paragraphs and checks if each paragraph starts with the keyword. If it does then it removes the keyword from it and adds it to a variable and after that it returns the result variable.

data = 'Character 1: aaaaaaaaaaa.\nCharacter 2: bbbbbbb.\nCharacter 3: ccc.\nCharacter 1: ddddddd.\nCharacter 3: eeee.'

def select_lines(text, paragraph_ending, keyword):
    paras = text.split(paragraph_ending)
    result = ''
    for para in paras:
        if ( para.startswith( keyword ) ):
            x = para.replace(keyword, '')
            result += x

    return result

character1 = select_lines(data, '\n', 'Character 1: ')
print(character1)


问:
Deep clone a imported property in Vuejs3
I have obeject which looks like below which is stored in a seperate file and later imported as import from "path"
into the vue component.

```<code>const myTemplate =
{
    a:{
        key11: undefined,
        key12: undefined
    },
    b:{
        key21: undefined,
        key22: undefined
    }

}
</code>```

Inside the component i am using this myTemplate object to create new data property

```<code><script>
    data(){
        getfields: myTemplate
    }
</script>
</code>```

In script i loop over the myTemplate and assign it with the prop coming from the parent component which holds the value of the key11, key12 ,key21 ,...so on

Purpose of myTemplate is to act as base/standard format which collect the data from the incoming prop.

Later on getfields is looped over by v-for in  <template> tag to display the content

I send props {key11: somevalue1, key12: somevalue2} to my child component matches the keys inside the myTemplate object uses the methods inside this child component to update the same  keys in getfields

end result:

```<code>{
    a:{
        key11: somevalue1,
        key12: somevalue2
    },
    b:{
        key21: undefined,
        key22: undefined
    }
}
</code>```

Problem:

In case of objects, JS copies the references and it alters my myTemplate object as well.

I want to have my myTemplate intact and cannot be altered in any way if the getfields gets changed.

What i've  tried:

Deep clone   const getfields : JSON.parse(JSON.stringify(myTemplate)) --> dint work for me because
myTemplate is Object of objects

Tried the dynamic import in the hope that would help but it dint

let self= this
import("path")
.then((data) =>{
self.getfields = data.default
})

答:
I suggest you to use Lodash library to clone the object with _.cloneDeep()

E.g:

```<code>import _ from 'lodash'
</code>```

.
.
.

```<code>const getfields = _.cloneDeep(myTemplate)
</code>```

It's the library I use with Vuejs for preventing those unexpected modifications in the original element because it just clones it.

Official documentation: https://lodash.com/docs/

If you have limited access to internet, you should use VanillaJs to create the clone function, look at this https://medium.com/weekly-webtips/deep-clone-with-vanilla-js-5ef16e0b365c

Body:
I have obeject which looks like below which is stored in a seperate file and later imported as import from "path"
into the vue component.

const myTemplate =
{
    a:{
        key11: undefined,
        key12: undefined
    },
    b:{
        key21: undefined,
        key22: undefined
    }

}

Inside the component i am using this myTemplate object to create new data property

In script i loop over the myTemplate and assign it with the prop coming from the parent component which holds the value of the key11, key12 ,key21 ,...so on

Purpose of myTemplate is to act as base/standard format which collect the data from the incoming prop.

Later on getfields is looped over by v-for in  <template> tag to display the content

I send props {key11: somevalue1, key12: somevalue2} to my child component matches the keys inside the myTemplate object uses the methods inside this child component to update the same  keys in getfields

end result:

{
    a:{
        key11: somevalue1,
        key12: somevalue2
    },
    b:{
        key21: undefined,
        key22: undefined
    }
}

Problem:

In case of objects, JS copies the references and it alters my myTemplate object as well.

I want to have my myTemplate intact and cannot be altered in any way if the getfields gets changed.

What i've  tried:

Deep clone   const getfields : JSON.parse(JSON.stringify(myTemplate)) --> dint work for me because
myTemplate is Object of objects

Tried the dynamic import in the hope that would help but it dint

let self= this
import("path")
.then((data) =>{
self.getfields = data.default
})

Body:
I suggest you to use Lodash library to clone the object with _.cloneDeep()

E.g:

import _ from 'lodash'

.
.
.

const getfields = _.cloneDeep(myTemplate)

It's the library I use with Vuejs for preventing those unexpected modifications in the original element because it just clones it.

Official documentation: https://lodash.com/docs/

If you have limited access to internet, you should use VanillaJs to create the clone function, look at this https://medium.com/weekly-webtips/deep-clone-with-vanilla-js-5ef16e0b365c


问:
DATE_ADD Function
A glitch in code on my website caused the start date and end date in an sql table to be set to the same day for my online member directory.  I have the code glitch corrected, but now need a way to fix the data in the database.  I am trying to add a certain number of months (12, 18, 24, etc) to the end_date column depending on the package column.  I only want to do this when the start_date column is equal to the end_date column.  I have a query started, but keep running into an invalid syntax message.  Can someone help?  My sql is below</p>
```<code>UPDATE porye_jbusinessdirectory_orders
SET end_date = DATE_ADD(months,12,end_date)
WHERE start_date = end_date
AND package_id = 1;
</code>```

答:
SET end_date = DATE_ADD(start_date, INTERVAL 12 MONTH)

This is for MySQL.

Title: DATE_ADD Function

Body:
A glitch in code on my website caused the start date and end date in an sql table to be set to the same day for my online member directory.  I have the code glitch corrected, but now need a way to fix the data in the database.  I am trying to add a certain number of months (12, 18, 24, etc) to the end_date column depending on the package column.  I only want to do this when the start_date column is equal to the end_date column.  I have a query started, but keep running into an invalid syntax message.  Can someone help?  My sql is below

UPDATE porye_jbusinessdirectory_orders
SET end_date = DATE_ADD(months,12,end_date)
WHERE start_date = end_date
AND package_id = 1;


问:
"Has invalid child element" warnings in Microsoft.Common.Targets while building
In my VS2010, when I build my solution, I have over 100 warnings in the file Microsoft.Common.Targets. When I try to build, publish or run my programs, I get just the warnings, but the moment I double click it to get more info, the Microsoft.Common.Targets pops up and then I get all on the warnings.

This file Microsoft.Common.Targets is part of the .net framework and has the MSBuild in-built targets, etc. And it has the approperiate schema associated in the properties window.

Some example warnings (2 out of 100) :

```<code>Warning    2    The element 'PropertyGroup' in namespace 'http://schemas.microsoft.com/developer/msbuild/2003' has invalid child element 'CustomBeforeMicrosoftCommonTargets' in namespace 'http://schemas.microsoft.com/developer/msbuild/2003'. List of possible elements expected: 'Property' in namespace 'http://schemas.microsoft.com/developer/msbuild/2003'.    C:\WINDOWS\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets    22    10    Miscellaneous Files
Warning    3    The element 'PropertyGroup' in namespace 'http://schemas.microsoft.com/developer/msbuild/2003' has invalid child element '_OriginalConfiguration' in namespace 'http://schemas.microsoft.com/developer/msbuild/2003'. List of possible elements expected: 'Property' in namespace 'http://schemas.microsoft.com/developer/msbuild/2003'.    C:\WINDOWS\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets    60    10    Miscellaneous Files
</code>```

Why is this file suddenly in my editor, when it is not part of my project, and how to tell visual studio to ignore this framework file while building.

答:
If you are using VS 2017 or newer version, than you can remove the namespace part and the error will gone.

"The schema link in an MSBuild project file is not required in Visual Studio 2017 and later. If present, it should be http://schemas.microsoft.com/developer/msbuild/2003 regardless of the version of Visual Studio."

Reference: MSBuild project file schema reference

Body:
In my VS2010, when I build my solution, I have over 100 warnings in the file Microsoft.Common.Targets. When I try to build, publish or run my programs, I get just the warnings, but the moment I double click it to get more info, the Microsoft.Common.Targets pops up and then I get all on the warnings.

This file Microsoft.Common.Targets is part of the .net framework and has the MSBuild in-built targets, etc. And it has the approperiate schema associated in the properties window.

Some example warnings (2 out of 100) :

Warning    2    The element 'PropertyGroup' in namespace 'http://schemas.microsoft.com/developer/msbuild/2003' has invalid child element 'CustomBeforeMicrosoftCommonTargets' in namespace 'http://schemas.microsoft.com/developer/msbuild/2003'. List of possible elements expected: 'Property' in namespace 'http://schemas.microsoft.com/developer/msbuild/2003'.    C:\WINDOWS\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets    22    10    Miscellaneous Files
Warning    3    The element 'PropertyGroup' in namespace 'http://schemas.microsoft.com/developer/msbuild/2003' has invalid child element '_OriginalConfiguration' in namespace 'http://schemas.microsoft.com/developer/msbuild/2003'. List of possible elements expected: 'Property' in namespace 'http://schemas.microsoft.com/developer/msbuild/2003'.    C:\WINDOWS\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets    60    10    Miscellaneous Files

Why is this file suddenly in my editor, when it is not part of my project, and how to tell visual studio to ignore this framework file while building.


问:
Is it possible to pass API from some url to openapi-generator in gradle?
I have some consumed.yaml API and now for generating classes with openapi-generator gradle plugin - i need to store this consumed.yaml file in my spring boot project. Short example of gradle task i use:

```<code>task clientApiGenerate(type: GenerateTask) {
    generatorName = "jaxrs-cxf-client"
    inputSpec = "path/to/consumed.yaml"
    ...
}
</code>```

So the question - can i use URL for downloading API file, for example, from gitlab and then use it in this line:

inputSpec = "path/to/consumed.yaml"

The following versions are currently in use, but can be changed, if necessary:

gradle: 6.8.3

openapi-generator gradle plugin: 5.3.0

答: Looks like it's possible, as in this example bellow. Didn't tried it for myself. However it's simpler to have spec along implementation, but that depends on situation :)</p>

Body:
I have some consumed.yaml API and now for generating classes with openapi-generator gradle plugin - i need to store this consumed.yaml file in my spring boot project. Short example of gradle task i use:

task clientApiGenerate(type: GenerateTask) {
    generatorName = "jaxrs-cxf-client"
    inputSpec = "path/to/consumed.yaml"
    ...
}

So the question - can i use URL for downloading API file, for example, from gitlab and then use it in this line:

inputSpec = "path/to/consumed.yaml"

The following versions are currently in use, but can be changed, if necessary:

gradle: 6.8.3

openapi-generator gradle plugin: 5.3.0


问:
Vue 3: component `:is` in for loop fails
I'm trying to loop over a list of component described by strings (I get the name of the component from another , like const componentTreeName = ["CompA", "CompA"].

My code is a simple as:

<template>

Demo

  <template v-for="compName in componentTreeName">
    <component :is="compName"></component>
  </template>
</template>
```

Demo here

EDIT

I tried this with not much success.

答:
When using script setup, you need to reference the component and not the name or key.

To get it to work, I would use an object where the string can be used as a key to target the component from an object like this:

<template>

Demo

  <template v-for="compName in componentTreeName">
    <component :is="components[compName]"></component>
  </template>
</template>
```
<p>To use a global component, you could assign components by pulling them from the app context. But this would require the <code>app</code> context to be available and the keys known.</p>
<p>example:</p>
<pre class="lang-js prettyprint-override"><code>import { app } from '../MyApp.js'
const components = {
  CompA: app.component('CompA')
}
</code>```

I haven't tested this, but this might be worth a try to check with getCurrentInstance

import { ref,getCurrentInstance } from 'vue'
const components = getCurrentInstance().appContext.components;
```

Body:
I'm trying to loop over a list of component described by strings (I get the name of the component from another , like const componentTreeName = ["CompA", "CompA"].

My code is a simple as:

<template>

Demo

  <template v-for="compName in componentTreeName">
    <component :is="compName"></component>
  </template>
</template>

<a href="https://sfc.vuejs.org/#eyJBcHAudnVlIjoiPHNjcmlwdCBzZXR1cD5cblx0aW1wb3J0IENvbXBBIGZyb20gJy4vQ29tcEEudnVlJ1xuXHRpbXBvcnQgeyByZWYgfSBmcm9tICd2dWUnXG5cbiAgLy8gSSBkbyBOT1Qgd2FudCB0byB1c2UgW0NvbXBBLCBDb21wQV0gYmVjYXVzZSBteSBpbnB1dHMgYXJlIHN0cmluZ3Ncblx0Y29uc3QgY29tcG9uZW50VHJlZU5hbWUgPSBbXCJDb21wQVwiLCBcIkNvbXBBXCJdXG48L3NjcmlwdD5cblxuPHRlbXBsYXRlPlxuICA8aDE+RGVtbzwvaDE+XG4gIDx0ZW1wbGF0ZSB2LWZvcj1cImNvbXBOYW1lIGluIGNvbXBvbmVudFRyZWVOYW1lXCI+XG4gICAgPGNvbXBvbmVudCA6aXM9XCJjb21wTmFtZVwiPjwvY29tcG9uZW50PlxuICA8L3RlbXBsYXRlPlxuPC90ZW1wbGF0ZT4iLCJpbXBvcnQtbWFwLmpzb24iOiJ7XG4gIFwiaW1wb3J0c1wiOiB7XG4gICAgXCJ2dWVcIjogXCJodHRwczovL3NmYy52dWVqcy5vcmcvdnVlLnJ1bnRpbWUuZXNtLWJyb3dzZXIuanNcIlxuICB9XG59IiwiQ29tcEEudnVlIjoiPHNjcmlwdCBzZXR1cD5cbmltcG9ydCB7IHJlZiB9IGZyb20gJ3Z1ZSdcblxuY29uc3QgbXNnID0gcmVmKCdQdXQgdGl0bGUgc2xpZGUgaGVyZScpXG48L3NjcmlwdD5cblxuPHRlbXBsYXRlPlxuICA8aDI+e3sgbXNnIH19PC9oMj5cbiAgPGlucHV0IHYtbW9kZWw9XCJtc2dcIj5cbjwvdGVtcGxhdGU+IiwiVGFibGUudnVlIjoiPHNjcmlwdCBzZXR1cD5cbmltcG9ydCB7IHJlZiB9IGZyb20gJ3Z1ZSdcbmluamVjdChcIm1haW5EYXRhXCIpXG5jb25zdCBtc2cgPSByZWYoJ0hlbGxvIFdvcmxkIScpXG48L3NjcmlwdD5cblxuPHRlbXBsYXRlPlxuICA8aDI+XG4gICAgVGFibGUgZGVzIG1hdGnDqHJlc1xuICA8L2gyPlxuICBcbjwvdGVtcGxhdGU+In0=" rel="nofollow noreferrer">Demo here

EDIT

I tried <a href="https://sfc.vuejs.org/#eyJBcHAudnVlIjoiPHNjcmlwdCBzZXR1cD5cblx0aW1wb3J0IENvbXBBIGZyb20gJy4vQ29tcEEudnVlJ1xuXHRpbXBvcnQgeyByZWYsIGdldEN1cnJlbnRJbnN0YW5jZSB9IGZyb20gJ3Z1ZSdcblxuICBjb25zdCBjb21wb25lbnRzID0gZ2V0Q3VycmVudEluc3RhbmNlKCkuYXBwQ29udGV4dC5jb21wb25lbnRzO1xuICAvLyBJIGRvIE5PVCB3YW50IHRvIHVzZSBbQ29tcEEsIENvbXBBXSBiZWNhdXNlIG15IGlucHV0cyBhcmUgc3RyaW5nc1xuXHRjb25zdCBjb21wb25lbnRUcmVlTmFtZSA9IFtcIkNvbXBBXCIsIFwiQ29tcEFcIl1cbjwvc2NyaXB0PlxuXG48dGVtcGxhdGU+XG4gIDxoMT5EZW1vPC9oMT5cbiAgPHRlbXBsYXRlIHYtZm9yPVwiY29tcE5hbWUgaW4gY29tcG9uZW50VHJlZU5hbWVcIj5cbiAgICA8Y29tcG9uZW50IDppcz1cImNvbXBvbmVudHNbY29tcE5hbWVdXCI+PC9jb21wb25lbnQ+XG4gIDwvdGVtcGxhdGU+XG48L3RlbXBsYXRlPiIsImltcG9ydC1tYXAuanNvbiI6IntcbiAgXCJpbXBvcnRzXCI6IHtcbiAgICBcInZ1ZVwiOiBcImh0dHBzOi8vc2ZjLnZ1ZWpzLm9yZy92dWUucnVudGltZS5lc20tYnJvd3Nlci5qc1wiXG4gIH1cbn0iLCJDb21wQS52dWUiOiI8c2NyaXB0IHNldHVwPlxuaW1wb3J0IHsgcmVmIH0gZnJvbSAndnVlJ1xuXG5jb25zdCBtc2cgPSByZWYoJ1B1dCB0aXRsZSBzbGlkZSBoZXJlJylcbjwvc2NyaXB0PlxuXG48dGVtcGxhdGU+XG4gIDxoMj57eyBtc2cgfX08L2gyPlxuICA8aW5wdXQgdi1tb2RlbD1cIm1zZ1wiPlxuPC90ZW1wbGF0ZT4iLCJUYWJsZS52dWUiOiI8c2NyaXB0IHNldHVwPlxuaW1wb3J0IHsgcmVmIH0gZnJvbSAndnVlJ1xuaW5qZWN0KFwibWFpbkRhdGFcIilcbmNvbnN0IG1zZyA9IHJlZignSGVsbG8gV29ybGQhJylcbjwvc2NyaXB0PlxuXG48dGVtcGxhdGU+XG4gIDxoMj5cbiAgICBUYWJsZSBkZXMgbWF0acOocmVzXG4gIDwvaDI+XG4gIFxuPC90ZW1wbGF0ZT4ifQ==" rel="nofollow noreferrer">this with not much success.

Body:
When using script setup, you need to reference the component and not the name or key.

To get it to work, I would use an object where the string can be used as a key to target the component from an object like this:

<script setup>
    import CompA from './CompA.vue'
    import { ref } from 'vue'
    const components = {CompA};

    // I do NOT want to use [CompA, CompA] because my inputs are strings
    const componentTreeName = ["CompA", "CompA"]
</script>

<template>
  <h1>Demo</h1>
  <template v-for="compName in componentTreeName">
    <component :is="components[compName]"></component>
  </template>
</template>

To use a global component, you could assign components by pulling them from the app context. But this would require the app context to be available and the keys known.

example:

import { app } from '../MyApp.js'
const components = {
  CompA: app.component('CompA')
}

I haven't tested this, but this might be worth a try to check with getCurrentInstance

import { ref,getCurrentInstance } from 'vue'
const components = getCurrentInstance().appContext.components;


问:
Can you alter a Custom Attribute's enum list in Maya?
I'm adding a custom attribute that is an enum list to some of my nodes. I can easily do this with addAttr. But I don't see a way to later add a new enum value or change the enum list.  Is that possible?

I have found a way to do this but it seems there should be an easier way. For my workaround, if the attribute exists I grab its value and delete the attribute.  Then I add the revised attribute back into the node and set its value to the old value.  By changing $enumValues I can edit the list of enums. (Note I only plan to add values not delete values) This script demonstrates my workaround:

```<code>string $attrName = "MaterialType";
string $enumValues = "Water:Sky:Terrain:Building:Road:";
string $selected[] = `ls -sl`;
if(`size $selected` == 1)
{
    string $attrFullName = $selected[0]+"."+$attrName;
    $existingValue = 0;
    if(attributeExists($attrName, $selected[0]))
    {
        $existingValue = `getAttr $attrFullName`;
        deleteAttr $attrFullName;
    }
    addAttr -ln $attrName -at "enum" -en $enumValues $selected;
    setAttr $attrFullName $existingValue;
}
else
{
    print "You must have 1 object and only 1 object selected\n";
};
</code>```

Worth mentioning, if I run this script it does change the enum's values but these changes don't show up in Maya's interface until I close the file and reopen the file.

Any suggestions on how to do this more gracefully would be appreciated.

答:
I might be a bit late, but you can use the "-edit" flag in addAttr.

```<code>addAttr -edit -enumNames "A:B:C" "node.enumAttrName"
</code>```

However, you still need to refresh manually or with refreshEditorTemplates

Edit:
You might also want to consider optionMenuGrp. You can add menuItems via the -parent flag. You can remove a specific child with the deleteUI command or remove all children with the -deleteAllItems flag in edit mode on the optionsMenuGrp.

Body:
I'm adding a custom attribute that is an enum list to some of my nodes. I can easily do this with addAttr. But I don't see a way to later add a new enum value or change the enum list.  Is that possible?

I have found a way to do this but it seems there should be an easier way. For my workaround, if the attribute exists I grab its value and delete the attribute.  Then I add the revised attribute back into the node and set its value to the old value.  By changing $enumValues I can edit the list of enums. (Note I only plan to add values not delete values) This script demonstrates my workaround:

string $attrName = "MaterialType";
string $enumValues = "Water:Sky:Terrain:Building:Road:";
string $selected[] = `ls -sl`;
if(`size $selected` == 1)
{
    string $attrFullName = $selected[0]+"."+$attrName;
    $existingValue = 0;
    if(attributeExists($attrName, $selected[0]))
    {
        $existingValue = `getAttr $attrFullName`;
        deleteAttr $attrFullName;
    }
    addAttr -ln $attrName -at "enum" -en $enumValues $selected;
    setAttr $attrFullName $existingValue;
}
else
{
    print "You must have 1 object and only 1 object selected\n";
};

Worth mentioning, if I run this script it does change the enum's values but these changes don't show up in Maya's interface until I close the file and reopen the file.

Any suggestions on how to do this more gracefully would be appreciated.

Body:
I might be a bit late, but you can use the "-edit" flag in addAttr.

addAttr -edit -enumNames "A:B:C" "node.enumAttrName"

However, you still need to refresh manually or with refreshEditorTemplates

Edit:
You might also want to consider optionMenuGrp. You can add menuItems via the -parent flag. You can remove a specific child with the deleteUI command or remove all children with the -deleteAllItems flag in edit mode on the optionsMenuGrp.


问:
How to convert PascalCase to snake_case?
If I had:

```<code>$string = "PascalCase";
</code>```

I need

```<code>"pascal_case"
</code>```

Does PHP offer a function for this purpose?

答:
Use Symfony String

composer require symfony/string
```
<pre class="lang-php prettyprint-override"><code>use function Symfony\Component\String\u;

u($string)->snake()->toString()
</code>```

Body:
If I had:

$string = "PascalCase";

I need

"pascal_case"

Does PHP offer a function for this purpose?

Body:
Use Symfony String

composer require symfony/string

use function Symfony\Component\String\u;

u($string)->snake()->toString()


问:
Using django queryset update function with User foreignkey
In summary: I have a mysql db table that holds pdf objects. When a user prints one of them, I want the table to update with the time, date, printed boolean value, and the user that printed the pdf object. This user information should write the value for the user currently logged in. I have all of these currently updating when a pdf is printed with the exception of user. I have tried using request.user but that does not seem to work within a queryset or else I am missing something. I have also tried using methodology similar to how I have defined get_user, which allows me to manually set the user, but again, that is not within the queryset to update automatically. Any help is much appreciated! My admin.py file is as follows:</p>

```<code>from django.contrib import admin
from django.contrib.auth.models import User
from djangostuff.pdf.models import ABC
from django.http import HttpResponse
import datetime, time

class ABCAdmin(admin.ModelAdmin):

    actions = ['print_selected_pdf']

    def get_user(self):
        return '%s'%(self.user.username)

    def create_pdf(self, queryset):
        response = HttpResponse(mimetype="application/pdf")
        response['Content-Disposition'] = 'attachment; filename=form.pdf'
        for obj in queryset:
            response.write(obj.form)
            ABC.objects.filter(pk=obj.pk).update(pdf_printed="1",request_time=time.strftime("%H:%M:%S"),request_date=datetime.datetime.today())
            ABC.objects.filter(pk=obj.pk).update(user=request.user)

        return response

    def print_selected_pdf(self, request, queryset):
        # prints the pdfs for those that are selected,
        # regardless if the pdf_printed field is true or false
        qs = queryset.filter(pdf_printed__exact=0)
        return self.create_pdf(qs)

    print_selected_pdf.short_description = "Print Selected PDF"

    get_user.short_description='Printed By'

    list_display=('form_no',get_user,'request_date','request_time','pdf_printed')

admin.site.register(ABC, ABCAdmin)
</code>```

答:
Why not just pass request as an argument to create_pdf?

```<code>def create_pdf(self, request, queryset):
    ...

def print_selected_pdf(self, request, queryset):
    qs = queryset.filter(pdf_printed__exact=0)
    return self.create_pdf(request, qs)
</code>```

Body:
In summary: I have a mysql db table that holds pdf objects. When a user prints one of them, I want the table to update with the time, date, printed boolean value, and the user that printed the pdf object. This user information should write the value for the user currently logged in. I have all of these currently updating when a pdf is printed with the exception of user. I have tried using request.user but that does not seem to work within a queryset or else I am missing something. I have also tried using methodology similar to how I have defined get_user, which allows me to manually set the user, but again, that is not within the queryset to update automatically. Any help is much appreciated! My admin.py file is as follows:

from django.contrib import admin
from django.contrib.auth.models import User
from djangostuff.pdf.models import ABC
from django.http import HttpResponse
import datetime, time

class ABCAdmin(admin.ModelAdmin):

    actions = ['print_selected_pdf']

    def get_user(self):
        return '%s'%(self.user.username)

    def create_pdf(self, queryset):
        response = HttpResponse(mimetype="application/pdf")
        response['Content-Disposition'] = 'attachment; filename=form.pdf'
        for obj in queryset:
            response.write(obj.form)
            ABC.objects.filter(pk=obj.pk).update(pdf_printed="1",request_time=time.strftime("%H:%M:%S"),request_date=datetime.datetime.today())
            ABC.objects.filter(pk=obj.pk).update(user=request.user)

        return response

    def print_selected_pdf(self, request, queryset):
        # prints the pdfs for those that are selected,
        # regardless if the pdf_printed field is true or false
        qs = queryset.filter(pdf_printed__exact=0)
        return self.create_pdf(qs)

    print_selected_pdf.short_description = "Print Selected PDF"

    get_user.short_description='Printed By'

    list_display=('form_no',get_user,'request_date','request_time','pdf_printed')

admin.site.register(ABC, ABCAdmin)

Body:
Why not just pass request as an argument to create_pdf?

def create_pdf(self, request, queryset):
    ...

def print_selected_pdf(self, request, queryset):
    qs = queryset.filter(pdf_printed__exact=0)
    return self.create_pdf(request, qs)


问:
How could I extract two numbers from a df column?
I have a dataframe, and there are columns (Height, Width and Life Span) with minimal and maximal values. What I want is to create another column with average values (27 for Height etc.), but to do it I need to extract two values - 26 and 28. And I didn't manage to succeed in this task - for example, with regex (df['Height'].replace('\D', '', regex=True)) I could only extract all numbers together, which isn't right. Or I could use re.findall(r'\d+', df['Height'][0]) which gives me what I need, but it applies only for the first row and not for any others (there are 400 rows in original dataset, I pasted only the first one). So, if you could help me I'll be very glad.

Code for df below.

```<code>import pandas as pd

pd.DataFrame({'Dog Breed Group': 'Working Dogs',
 'Height': '26 to 28 inches at the shoulder',
 'Weight': '80 to 140 pounds',
 'Life Span': '10 to 11 years'}, index=[0])
</code>```

答:
Thanks to the answer, I managed to do this (although not elegant and too complicated):

```<code>df2 = df.copy()

e = df2.Height.str.extractall('(\d+)').astype(int).reset_index().groupby('level_0').mean()

df2['mean_height'] = e.iloc[:, 1]

df2.head()
</code>```

Same apply to other columns.

Body:
I have a dataframe, and there are columns (Height, Width and Life Span) with minimal and maximal values. What I want is to create another column with average values (27 for Height etc.), but to do it I need to extract two values - 26 and 28. And I didn't manage to succeed in this task - for example, with regex (df['Height'].replace('\D', '', regex=True)) I could only extract all numbers together, which isn't right. Or I could use re.findall(r'\d+', df['Height'][0]) which gives me what I need, but it applies only for the first row and not for any others (there are 400 rows in original dataset, I pasted only the first one). So, if you could help me I'll be very glad.

Code for df below.

import pandas as pd

pd.DataFrame({'Dog Breed Group': 'Working Dogs',
 'Height': '26 to 28 inches at the shoulder',
 'Weight': '80 to 140 pounds',
 'Life Span': '10 to 11 years'}, index=[0])

Body:
Thanks to the answer, I managed to do this (although not elegant and too complicated):

df2 = df.copy()

e = df2.Height.str.extractall('(\d+)').astype(int).reset_index().groupby('level_0').mean()

df2['mean_height'] = e.iloc[:, 1]

df2.head()

Same apply to other columns.