问:
Flutter | How to use Provider with GridView.builder to prevent children rebuilds
Situation

I am trying to create a list which paginates data from Firestore using provider. Every item which is loaded into the GridView is a widget with an Image.memory component which downloads the image from Firebase Storage when the item is built. My problem is that as the provider adds more items to the list and notifies(), GridView obviously rebuilds as it is wrapped in a Selector, which rebuilds all children which causes them to download the images again, which is not desired.

Provider

```<code>class PaginateFirestoreProvider extends ChangeNotifier {
  Query query;
  int documentLimit;

  PaginateFirestoreProvider(
      {required this.query, required this.documentLimit}) {
    fetch();
  }

  bool isLoading = false;
  bool isLoadingMore = false;
  bool hasMore = true;
  List<QueryDocumentSnapshot> items = [];
  DocumentSnapshot? lastDocument;

  bool get isListEmpty {
    return items.isEmpty;
  }

  Future fetch() async {
    if (!hasMore || isLoading) return;

    isLoading = true;
    notifyListeners();

    QuerySnapshot querySnapshot = await query.limit(documentLimit).get();
    if (querySnapshot.docs.length < documentLimit) {
      hasMore = false;
    }
    lastDocument = querySnapshot.docs[querySnapshot.docs.length - 1];
    items.addAll(querySnapshot.docs);
    isLoading = false;
    notifyListeners();
  }

  Future fetchMore() async {
    if (!hasMore || isLoadingMore || lastDocument == null) return;

    isLoadingMore = true;
    notifyListeners();

    QuerySnapshot querySnapshot = await query
        .limit(documentLimit)
        .startAfterDocument(lastDocument!)
        .get();

    if (querySnapshot.docs.length < documentLimit) {
      hasMore = false;
    }
    lastDocument = querySnapshot.docs[querySnapshot.docs.length - 1];
    items.addAll(querySnapshot.docs);
    isLoadingMore = false;
    notifyListeners();
  }
}
</code>```

GridView widget

```<code>class PaginateFirestore extends StatefulWidget {
  Widget Function({required dynamic data}) itemBuilder;
  Widget emptyBuilder;
  Widget errorBuilder;
  Widget loadingBuilder;
  Widget loadingMoreBuilder;
  Query query;
  int pageSize;

  PaginateFirestore(
      {required this.itemBuilder,
      required this.query,
      required this.pageSize,
      required this.emptyBuilder,
      required this.errorBuilder,
      required this.loadingBuilder,
      required this.loadingMoreBuilder});

  @override
  State<PaginateFirestore> createState() => _PaginateFirestoreState();
}

class _PaginateFirestoreState extends State<PaginateFirestore> {
  late PaginateFirestoreProvider _paginateFirestoreProvider;

  bool isLoading = false;
  bool isLoadingMore = false;
  bool hasMore = true;
  List<QueryDocumentSnapshot> items = [];
  DocumentSnapshot? lastDocument;

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<PaginateFirestoreProvider>(
      create: (context) {
        _paginateFirestoreProvider = PaginateFirestoreProvider(
            query: widget.query, documentLimit: widget.pageSize);
        return _paginateFirestoreProvider;
      },
      child: _buildPaginator(),
    );
  }

  Widget _buildPaginator() =>
      Selector<PaginateFirestoreProvider, Tuple2<bool, bool>>(
          selector: (context, value) =>
              Tuple2(value.isLoading, value.isListEmpty),
          builder: (context, value, child) => value.item1
              ? widget.loadingBuilder
              : value.item2
                  ? widget.emptyBuilder
                  : _buildList());

  Widget _buildList() => Column(
        children: [
          Selector<PaginateFirestoreProvider, List<QueryDocumentSnapshot>>(
              shouldRebuild: (previous, next) => true,
              selector: (context, value) => value.items,
              builder: (context, value, child) => GridView.builder(
                  shrinkWrap: true,
                  itemCount: value.length,
                  physics: NeverScrollableScrollPhysics(),
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 3,
                      crossAxisSpacing: 1,
                      mainAxisSpacing: 1),
                  itemBuilder: (context, index) =>
                      widget.itemBuilder(data: value[index].data()))),
          Selector<PaginateFirestoreProvider, bool>(
              selector: (context, value) => value.hasMore,
              builder: (context, value, child) => value
                  ? VisibilityDetector(
                      key: Key('my-widget-key'),
                      onVisibilityChanged: (visibilityInfo) {
                        if (visibilityInfo.visibleFraction > 0) {
                          _paginateFirestoreProvider.fetchMore();
                        }
                      },
                      child: widget.loadingMoreBuilder)
                  : SizedBox.shrink()),
        ],
      );
</code>```

List item (passed as the itemBuilder parameter)

```<code>FutureBuilder(
              future: databaseService.getFileToMemory(
                  ref: pathToFile),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done &&
                    snapshot.data != null) {
                  return Image.memory(
                    snapshot.data!,
                    width: double.infinity,
                    height: double.infinity,
                    fit: BoxFit.cover,
                    errorBuilder: (context, error, stackTrace) =>
                        _buildListItemError(),
                  );
                } else {
                  return _buildListItemError();
                }
              }),
</code>```

Question

I need someway of adding the newly fetched items to the GridView without rebuilding all of them, while still using provider. Is this possible???

Body:
Situation

I am trying to create a list which paginates data from Firestore using provider. Every item which is loaded into the GridView is a widget with an Image.memory component which downloads the image from Firebase Storage when the item is built. My problem is that as the provider adds more items to the list and notifies(), GridView obviously rebuilds as it is wrapped in a Selector, which rebuilds all children which causes them to download the images again, which is not desired.

Provider

class PaginateFirestoreProvider extends ChangeNotifier {
  Query query;
  int documentLimit;

  PaginateFirestoreProvider(
      {required this.query, required this.documentLimit}) {
    fetch();
  }

  bool isLoading = false;
  bool isLoadingMore = false;
  bool hasMore = true;
  List<QueryDocumentSnapshot> items = [];
  DocumentSnapshot? lastDocument;

  bool get isListEmpty {
    return items.isEmpty;
  }

  Future fetch() async {
    if (!hasMore || isLoading) return;

    isLoading = true;
    notifyListeners();

    QuerySnapshot querySnapshot = await query.limit(documentLimit).get();
    if (querySnapshot.docs.length < documentLimit) {
      hasMore = false;
    }
    lastDocument = querySnapshot.docs[querySnapshot.docs.length - 1];
    items.addAll(querySnapshot.docs);
    isLoading = false;
    notifyListeners();
  }

  Future fetchMore() async {
    if (!hasMore || isLoadingMore || lastDocument == null) return;

    isLoadingMore = true;
    notifyListeners();

    QuerySnapshot querySnapshot = await query
        .limit(documentLimit)
        .startAfterDocument(lastDocument!)
        .get();

    if (querySnapshot.docs.length < documentLimit) {
      hasMore = false;
    }
    lastDocument = querySnapshot.docs[querySnapshot.docs.length - 1];
    items.addAll(querySnapshot.docs);
    isLoadingMore = false;
    notifyListeners();
  }
}

GridView widget

class PaginateFirestore extends StatefulWidget {
  Widget Function({required dynamic data}) itemBuilder;
  Widget emptyBuilder;
  Widget errorBuilder;
  Widget loadingBuilder;
  Widget loadingMoreBuilder;
  Query query;
  int pageSize;

  PaginateFirestore(
      {required this.itemBuilder,
      required this.query,
      required this.pageSize,
      required this.emptyBuilder,
      required this.errorBuilder,
      required this.loadingBuilder,
      required this.loadingMoreBuilder});

  @override
  State<PaginateFirestore> createState() => _PaginateFirestoreState();
}

class _PaginateFirestoreState extends State<PaginateFirestore> {
  late PaginateFirestoreProvider _paginateFirestoreProvider;

  bool isLoading = false;
  bool isLoadingMore = false;
  bool hasMore = true;
  List<QueryDocumentSnapshot> items = [];
  DocumentSnapshot? lastDocument;

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<PaginateFirestoreProvider>(
      create: (context) {
        _paginateFirestoreProvider = PaginateFirestoreProvider(
            query: widget.query, documentLimit: widget.pageSize);
        return _paginateFirestoreProvider;
      },
      child: _buildPaginator(),
    );
  }

  Widget _buildPaginator() =>
      Selector<PaginateFirestoreProvider, Tuple2<bool, bool>>(
          selector: (context, value) =>
              Tuple2(value.isLoading, value.isListEmpty),
          builder: (context, value, child) => value.item1
              ? widget.loadingBuilder
              : value.item2
                  ? widget.emptyBuilder
                  : _buildList());

  Widget _buildList() => Column(
        children: [
          Selector<PaginateFirestoreProvider, List<QueryDocumentSnapshot>>(
              shouldRebuild: (previous, next) => true,
              selector: (context, value) => value.items,
              builder: (context, value, child) => GridView.builder(
                  shrinkWrap: true,
                  itemCount: value.length,
                  physics: NeverScrollableScrollPhysics(),
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 3,
                      crossAxisSpacing: 1,
                      mainAxisSpacing: 1),
                  itemBuilder: (context, index) =>
                      widget.itemBuilder(data: value[index].data()))),
          Selector<PaginateFirestoreProvider, bool>(
              selector: (context, value) => value.hasMore,
              builder: (context, value, child) => value
                  ? VisibilityDetector(
                      key: Key('my-widget-key'),
                      onVisibilityChanged: (visibilityInfo) {
                        if (visibilityInfo.visibleFraction > 0) {
                          _paginateFirestoreProvider.fetchMore();
                        }
                      },
                      child: widget.loadingMoreBuilder)
                  : SizedBox.shrink()),
        ],
      );

List item (passed as the itemBuilder parameter)

FutureBuilder(
              future: databaseService.getFileToMemory(
                  ref: pathToFile),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done &&
                    snapshot.data != null) {
                  return Image.memory(
                    snapshot.data!,
                    width: double.infinity,
                    height: double.infinity,
                    fit: BoxFit.cover,
                    errorBuilder: (context, error, stackTrace) =>
                        _buildListItemError(),
                  );
                } else {
                  return _buildListItemError();
                }
              }),

Question

I need someway of adding the newly fetched items to the GridView without rebuilding all of them, while still using provider. Is this possible???


来源: stackexchange

问:
I can not figure out how to install Raylib-Lua on Debian
I am trying to install a lua binding of raylib, but I cannot install it.

Nowhere online can I find instructions, hours of digging haven't helped. Wondering if anybody knows how to install on a fresh install of Debian 11 (Bullseye)

Thank you!

ContentLicense: CC BY-SA 4.0


问:
Processmaker 4 Validation Rules: Require a field to be filled in if another field has been filled in
On a form with optional line inputs, how do I require input on a field if another field was filled in?

In my example I have a page of multiple rows of name input fields with each name field having an associated age input field.

Any help would be appreciated.

I know you can set the age field with a required validation rule and use a visibility rule to hide the control until a name is typed in but I'm trying to keep all of the input boxes visible.

I've tried using a required if name field is not null but that doesn't work.  I've also tried using a required unless and having the name field as the checked variable and nothing as the checked value.  This worked but when deleting the name field, the age field is still required.


问:
github action wrongly thinks output is a secret
I have a github action workflow job that has a couple of outputs that github is detecting as secrets by they are not at all. One is the first 7 chars of github.sha and the another is random UUID that I generate using uuidgen.

These outputs are used by multiple other jobs in the same workflow, so I can't just move the steps in the job where I used them because then I have to duplicate the code.

This is the warning I am getting:

How does github assume that it may contain a secret? Is it because of the property name and/or value?

So if I try to read these outputs from another job, they are empty and break the logic of the workflow.

Is there a way to force to not skip these outputs?

EDITS:

I added now the sha_short but the other output was already exported and used before. It was working, now it's detected as secret. I am doing some attempt to fix it and sometime sha_short is exported. It seems quite random.

I tried to change the name of the variables and generate values with a different format using nanoid. At moment it looks like pretty random. Sometime one is skipped and sometime the other is skipped. So yeah, the ideal it would be something that tells the runner to never skip these two outputs.

Output:

```<code>   **mecho "docker_build_image_trigger=eff63***95-***ef***-***68c-9edb-***6570a8eb79c" >> $GITHUB_OUTPUT
  **mecho "sha_short=dba69ba" >> $GITHUB_OUTPUT
</code>```

Steps:

```<code>steps:
  - name: Setup AWS
    if: env.SHOULD_REBUILD_DOCKER_IMAGES == 'false'
    uses: aws-actions/configure-aws-credentials@v1
    with:
      aws-access-key-id: ${{ env.TF_VAR_AWS_ACCESS_KEY_ID }}
      aws-secret-access-key: ${{ env.TF_VAR_AWS_SECRET_ACCESS_KEY }}
      aws-region: ${{ env.TF_VAR_AWS_REGION }}

  - name: Write secrets
    if: env.SHOULD_REBUILD_DOCKER_IMAGES == 'false'
    run: |
      aws secretsmanager get-secret-value --secret-id puck-legacy-${{ needs.get-environment-info.outputs.environment }}-secrets --output text --query SecretString >> aws-secrets.json

  - name: Get docker build image trigger
    id: docker-build-image-trigger
    if: env.SHOULD_REBUILD_DOCKER_IMAGES == 'false'
    uses: sergeysova/jq-action@v2
    with:
      cmd: cat aws-secrets.json | jq -r .INFRA_REBUILD_TRIGGER

  - name: Get sha short
    id: sha-short
    if: env.SHOULD_REBUILD_DOCKER_IMAGES == 'false'
    uses: sergeysova/jq-action@v2
    with:
      cmd: cat aws-secrets.json | jq -r .ACTION_CURRENT_COMMIT

  - name: nanoid
    id: nanoid
    if: env.SHOULD_REBUILD_DOCKER_IMAGES == 'true'
    run: |
      echo "nanoid=$(npx nanoid -s 8 -a 1234567890abcdef)" >> $GITHUB_OUTPUT

  - name: Current commit
    id: current-commit
    if: env.SHOULD_REBUILD_DOCKER_IMAGES == 'true'
    run: |
      SHA=${{ github.sha }}
      echo "hash=${SHA:0:7}" >> $GITHUB_OUTPUT

  - name: Get outputs
    id: get-outputs
    run: |
      echo "rebuild_trigger=${{ steps.docker-build-image-trigger.outcome == 'success' && steps.docker-build-image-trigger.outputs.value || steps.nanoid.outputs.nanoid }}" >> $GITHUB_OUTPUT
      echo "current_commit=${{ steps.sha-short.outcome == 'success' && steps.sha-short.outputs.value || steps.current-commit.outputs.hash }}" >> $GITHUB_OUTPUT
</code>```

In the tests that I am running SHOULD_REBUILD_DOCKER_IMAGES is 'true', so many of the steps are skipped and outputs are always new.

Another job in the workflow where I want read those outputs:

```<code>  infrastructure:
    ...
    needs: [get-environment-info, get-dependent-info]
    env:
      ...
      TF_VAR_ACTION_CURRENT_COMMIT: ${{ needs.get-dependent-info.outputs.current_commit }}
      TF_VAR_INFRA_REBUILD_TRIGGER: ${{ needs.get-dependent-info.outputs.rebuild_trigger }}

    steps:
      - name: Job info
        run: |
          echo "TF_VAR_ACTION_CURRENT_COMMIT=${{ env.TF_VAR_ACTION_CURRENT_COMMIT }}"
          echo "TF_VAR_INFRA_REBUILD_TRIGGER=${{ env.TF_VAR_INFRA_REBUILD_TRIGGER }}"
</code>```

The output is:

```<code>TF_VAR_ACTION_CURRENT_COMMIT=
TF_VAR_INFRA_REBUILD_TRIGGER=
</code>```

Body:
I have a github action workflow job that has a couple of outputs that github is detecting as secrets by they are not at all. One is the first 7 chars of github.sha and the another is random UUID that I generate using uuidgen.

These outputs are used by multiple other jobs in the same workflow, so I can't just move the steps in the job where I used them because then I have to duplicate the code.

This is the warning I am getting:

How does github assume that it may contain a secret? Is it because of the property name and/or value?

So if I try to read these outputs from another job, they are empty and break the logic of the workflow.

Is there a way to force to not skip these outputs?

EDITS:

I added now the sha_short but the other output was already exported and used before. It was working, now it's detected as secret. I am doing some attempt to fix it and sometime sha_short is exported. It seems quite random.

I tried to change the name of the variables and generate values with a different format using nanoid. At moment it looks like pretty random. Sometime one is skipped and sometime the other is skipped. So yeah, the ideal it would be something that tells the runner to never skip these two outputs.

Output:

   **mecho "docker_build_image_trigger=eff63***95-***ef***-***68c-9edb-***6570a8eb79c" >> $GITHUB_OUTPUT
  **mecho "sha_short=dba69ba" >> $GITHUB_OUTPUT

Steps:

steps:
  - name: Setup AWS
    if: env.SHOULD_REBUILD_DOCKER_IMAGES == 'false'
    uses: aws-actions/configure-aws-credentials@v1
    with:
      aws-access-key-id: ${{ env.TF_VAR_AWS_ACCESS_KEY_ID }}
      aws-secret-access-key: ${{ env.TF_VAR_AWS_SECRET_ACCESS_KEY }}
      aws-region: ${{ env.TF_VAR_AWS_REGION }}

  - name: Write secrets
    if: env.SHOULD_REBUILD_DOCKER_IMAGES == 'false'
    run: |
      aws secretsmanager get-secret-value --secret-id puck-legacy-${{ needs.get-environment-info.outputs.environment }}-secrets --output text --query SecretString >> aws-secrets.json

  - name: Get docker build image trigger
    id: docker-build-image-trigger
    if: env.SHOULD_REBUILD_DOCKER_IMAGES == 'false'
    uses: sergeysova/jq-action@v2
    with:
      cmd: cat aws-secrets.json | jq -r .INFRA_REBUILD_TRIGGER

  - name: Get sha short
    id: sha-short
    if: env.SHOULD_REBUILD_DOCKER_IMAGES == 'false'
    uses: sergeysova/jq-action@v2
    with:
      cmd: cat aws-secrets.json | jq -r .ACTION_CURRENT_COMMIT

  - name: nanoid
    id: nanoid
    if: env.SHOULD_REBUILD_DOCKER_IMAGES == 'true'
    run: |
      echo "nanoid=$(npx nanoid -s 8 -a 1234567890abcdef)" >> $GITHUB_OUTPUT

  - name: Current commit
    id: current-commit
    if: env.SHOULD_REBUILD_DOCKER_IMAGES == 'true'
    run: |
      SHA=${{ github.sha }}
      echo "hash=${SHA:0:7}" >> $GITHUB_OUTPUT

  - name: Get outputs
    id: get-outputs
    run: |
      echo "rebuild_trigger=${{ steps.docker-build-image-trigger.outcome == 'success' && steps.docker-build-image-trigger.outputs.value || steps.nanoid.outputs.nanoid }}" >> $GITHUB_OUTPUT
      echo "current_commit=${{ steps.sha-short.outcome == 'success' && steps.sha-short.outputs.value || steps.current-commit.outputs.hash }}" >> $GITHUB_OUTPUT

In the tests that I am running SHOULD_REBUILD_DOCKER_IMAGES is 'true', so many of the steps are skipped and outputs are always new.

Another job in the workflow where I want read those outputs:

  infrastructure:
    ...
    needs: [get-environment-info, get-dependent-info]
    env:
      ...
      TF_VAR_ACTION_CURRENT_COMMIT: ${{ needs.get-dependent-info.outputs.current_commit }}
      TF_VAR_INFRA_REBUILD_TRIGGER: ${{ needs.get-dependent-info.outputs.rebuild_trigger }}

    steps:
      - name: Job info
        run: |
          echo "TF_VAR_ACTION_CURRENT_COMMIT=${{ env.TF_VAR_ACTION_CURRENT_COMMIT }}"
          echo "TF_VAR_INFRA_REBUILD_TRIGGER=${{ env.TF_VAR_INFRA_REBUILD_TRIGGER }}"

The output is:

TF_VAR_ACTION_CURRENT_COMMIT=
TF_VAR_INFRA_REBUILD_TRIGGER=


问:
Is it possible to import files from a swift package that are not in the Sources directory?
I am using a swift package in my iOS project that happens to have various files in a Tests directory. Tests exists the same parent directory as its Sources folder. I can see and use all the classes defined in the Sources directory, but see no way to use the ones in the Tests directory.

Is there a way for me to import and/or use those classes in my application's test target?


问:
Does Kotlin Moshi Codegen work with Modules?
In a project (a library) using moshi (moshi.kotlin.codegen:1.14.0) as dependency, as soon as i try to add a module-info.java file, the compilation fails (while it works as soon as i remove it again).
The modules-info i tried it with was automatically generated by my IDE (i just added the opens), and i'm not sure why the compilation fails since that addition. I am using @JsonClass(generateAdapter = true) for my data classes.

What does the addition of module-info.java to the project change, how does this affect moshi, and how can this be fixed?

```<code>    <plugin>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-maven-plugin</artifactId>
        <version>${kotlin.version}</version>
        <executions>
            <execution>
                <id>kapt</id>
                <goals>
                    <goal>kapt</goal>
                </goals>
                <configuration>
                    <sourceDirs>
                        <sourceDir>src/main/java</sourceDir>
                    </sourceDirs>
                    <annotationProcessorPaths>
                        <annotationProcessorPath>
                            <groupId>com.squareup.moshi</groupId>
                            <artifactId>moshi-kotlin-codegen</artifactId>
                            <version>1.14.0</version>
                        </annotationProcessorPath>
                    </annotationProcessorPaths>
                </configuration>
            </execution>
            <execution>
                <id>compile</id>
                <phase>compile</phase>
                <goals>
                    <goal>compile</goal>
                </goals>
            </execution>
            <execution>
                <id>test-compile</id>
                <phase>test-compile</phase>
                <goals>
                    <goal>test-compile</goal>
                </goals>
            </execution>
        </executions>
        <configuration>
            <jvmTarget>1.8</jvmTarget>
        </configuration>
    </plugin>
</code>```
```<code>
module grade.loader {
requires annotations;
requires kotlin.stdlib;
requires moshi;
requires moshi.kotlin.codegen;
requires okio;

    exports com.example.package;

    opens com.example.package;

}
</code>```
```<code>
Compilation failure
java.lang.IllegalStateException: failed to analyze: java.lang.reflect.InvocationTargetException
at org.jetbrains.kotlin.analyzer.AnalysisResult.throwIfError(AnalysisResult.kt:56)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli(KotlinToJVMBytecodeCompiler.kt:93)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli$default(KotlinToJVMBytecodeCompiler.kt:47)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:167)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:53)
at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:101)
at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:47)
at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:101)
at org.jetbrains.kotlin.maven.KotlinCompileMojoBase.execCompiler(KotlinCompileMojoBase.java:228)
at org.jetbrains.kotlin.maven.K2JVMCompileMojo.execCompiler(K2JVMCompileMojo.java:237)
at org.jetbrains.kotlin.maven.kapt.KaptJVMCompilerMojo.execCompiler(KaptJVMCompilerMojo.java:152)
at org.jetbrains.kotlin.maven.kapt.KaptJVMCompilerMojo.execCompiler(KaptJVMCompilerMojo.java:44)
at org.jetbrains.kotlin.maven.KotlinCompileMojoBase.execute(KotlinCompileMojoBase.java:209)
at org.jetbrains.kotlin.maven.K2JVMCompileMojo.execute(K2JVMCompileMojo.java:222)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:137)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:210)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:156)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:148)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:56)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:305)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:192)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:105)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:957)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:289)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:193)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:578)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:282)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:225)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:406)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:347)
at org.codehaus.classworlds.Launcher.main(Launcher.java:47)
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:119)
at java.base/java.lang.reflect.Method.invoke(Method.java:578)
at org.jetbrains.kotlin.kapt3.base.AnnotationProcessingKt.doAnnotationProcessing(annotationProcessing.kt:90)
at org.jetbrains.kotlin.kapt3.base.AnnotationProcessingKt.doAnnotationProcessing$default(annotationProcessing.kt:31)
at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.runAnnotationProcessing(Kapt3Extension.kt:236)
at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.analysisCompleted(Kapt3Extension.kt:199)
at org.jetbrains.kotlin.kapt3.ClasspathBasedKapt3Extension.analysisCompleted(Kapt3Extension.kt:106)
at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM$analyzeFilesWithJavaIntegration$2.invoke(TopDownAnalyzerFacadeForJVM.kt:115)
at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(TopDownAnalyzerFacadeForJVM.kt:125)
at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration$default(TopDownAnalyzerFacadeForJVM.kt:99)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:257)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:42)
at org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport.analyzeAndReport(AnalyzerWithCompilerReport.kt:115)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.analyze(KotlinToJVMBytecodeCompiler.kt:248)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli(KotlinToJVMBytecodeCompiler.kt:88)
... 33 more
Caused by: com.sun.tools.javac.processing.AnnotationProcessingError: java.lang.NullPointerException: Cannot invoke "javax.lang.model.element.TypeElement.getEnclosedElements()" because "this.jvmNameType" is null
at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment$ProcessorState.\<init\>(JavacProcessingEnvironment.java:745)
at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment$DiscoveredProcessors$ProcessorStateIterator.next(JavacProcessingEnvironment.java:823)
at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment.discoverAndRunProcs(JavacProcessingEnvironment.java:919)
at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment$Round.run(JavacProcessingEnvironment.java:1262)
at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment.doProcessing(JavacProcessingEnvironment.java:1377)
at jdk.compiler/com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1234)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
... 47 more
Caused by: java.lang.NullPointerException: Cannot invoke "javax.lang.model.element.TypeElement.getEnclosedElements()" because "this.jvmNameType" is null
at com.squareup.moshi.kotlinpoet.metadata.classinspectors.ElementsClassInspector.\<init\>(ElementsClassInspector.kt:102)
at com.squareup.moshi.kotlinpoet.metadata.classinspectors.ElementsClassInspector.\<init\>(ElementsClassInspector.kt)
at com.squareup.moshi.kotlinpoet.metadata.classinspectors.ElementsClassInspector$Companion.create(ElementsClassInspector.kt:580)
at com.squareup.moshi.kotlin.codegen.apt.JsonClassCodegenProcessor.init(JsonClassCodegenProcessor.kt:87)
at org.jetbrains.kotlin.kapt3.base.incremental.IncrementalProcessor.init(incrementalProcessors.kt:36)
at org.jetbrains.kotlin.kapt3.base.ProcessorWrapper.init(annotationProcessing.kt:207)
at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment$ProcessorState.\<init\>(JavacProcessingEnvironment.java:696)
... 53 more
</code>```

Body:
In a project (a library) using moshi (moshi.kotlin.codegen:1.14.0) as dependency, as soon as i try to add a module-info.java file, the compilation fails (while it works as soon as i remove it again).
The modules-info i tried it with was automatically generated by my IDE (i just added the opens), and i'm not sure why the compilation fails since that addition. I am using @JsonClass(generateAdapter = true) for my data classes.

What does the addition of module-info.java to the project change, how does this affect moshi, and how can this be fixed?

    <plugin>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-maven-plugin</artifactId>
        <version>${kotlin.version}</version>
        <executions>
            <execution>
                <id>kapt</id>
                <goals>
                    <goal>kapt</goal>
                </goals>
                <configuration>
                    <sourceDirs>
                        <sourceDir>src/main/java</sourceDir>
                    </sourceDirs>
                    <annotationProcessorPaths>
                        <annotationProcessorPath>
                            <groupId>com.squareup.moshi</groupId>
                            <artifactId>moshi-kotlin-codegen</artifactId>
                            <version>1.14.0</version>
                        </annotationProcessorPath>
                    </annotationProcessorPaths>
                </configuration>
            </execution>
            <execution>
                <id>compile</id>
                <phase>compile</phase>
                <goals>
                    <goal>compile</goal>
                </goals>
            </execution>
            <execution>
                <id>test-compile</id>
                <phase>test-compile</phase>
                <goals>
                    <goal>test-compile</goal>
                </goals>
            </execution>
        </executions>
        <configuration>
            <jvmTarget>1.8</jvmTarget>
        </configuration>
    </plugin>

module grade.loader {
requires annotations;
requires kotlin.stdlib;
requires moshi;
requires moshi.kotlin.codegen;
requires okio;

    exports com.example.package;

    opens com.example.package;

}

Compilation failure
java.lang.IllegalStateException: failed to analyze: java.lang.reflect.InvocationTargetException
at org.jetbrains.kotlin.analyzer.AnalysisResult.throwIfError(AnalysisResult.kt:56)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli(KotlinToJVMBytecodeCompiler.kt:93)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli$default(KotlinToJVMBytecodeCompiler.kt:47)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:167)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:53)
at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:101)
at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:47)
at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:101)
at org.jetbrains.kotlin.maven.KotlinCompileMojoBase.execCompiler(KotlinCompileMojoBase.java:228)
at org.jetbrains.kotlin.maven.K2JVMCompileMojo.execCompiler(K2JVMCompileMojo.java:237)
at org.jetbrains.kotlin.maven.kapt.KaptJVMCompilerMojo.execCompiler(KaptJVMCompilerMojo.java:152)
at org.jetbrains.kotlin.maven.kapt.KaptJVMCompilerMojo.execCompiler(KaptJVMCompilerMojo.java:44)
at org.jetbrains.kotlin.maven.KotlinCompileMojoBase.execute(KotlinCompileMojoBase.java:209)
at org.jetbrains.kotlin.maven.K2JVMCompileMojo.execute(K2JVMCompileMojo.java:222)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:137)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:210)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:156)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:148)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:56)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:305)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:192)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:105)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:957)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:289)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:193)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:578)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:282)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:225)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:406)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:347)
at org.codehaus.classworlds.Launcher.main(Launcher.java:47)
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:119)
at java.base/java.lang.reflect.Method.invoke(Method.java:578)
at org.jetbrains.kotlin.kapt3.base.AnnotationProcessingKt.doAnnotationProcessing(annotationProcessing.kt:90)
at org.jetbrains.kotlin.kapt3.base.AnnotationProcessingKt.doAnnotationProcessing$default(annotationProcessing.kt:31)
at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.runAnnotationProcessing(Kapt3Extension.kt:236)
at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.analysisCompleted(Kapt3Extension.kt:199)
at org.jetbrains.kotlin.kapt3.ClasspathBasedKapt3Extension.analysisCompleted(Kapt3Extension.kt:106)
at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM$analyzeFilesWithJavaIntegration$2.invoke(TopDownAnalyzerFacadeForJVM.kt:115)
at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(TopDownAnalyzerFacadeForJVM.kt:125)
at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration$default(TopDownAnalyzerFacadeForJVM.kt:99)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:257)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:42)
at org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport.analyzeAndReport(AnalyzerWithCompilerReport.kt:115)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.analyze(KotlinToJVMBytecodeCompiler.kt:248)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli(KotlinToJVMBytecodeCompiler.kt:88)
... 33 more
Caused by: com.sun.tools.javac.processing.AnnotationProcessingError: java.lang.NullPointerException: Cannot invoke "javax.lang.model.element.TypeElement.getEnclosedElements()" because "this.jvmNameType" is null
at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment$ProcessorState.\<init\>(JavacProcessingEnvironment.java:745)
at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment$DiscoveredProcessors$ProcessorStateIterator.next(JavacProcessingEnvironment.java:823)
at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment.discoverAndRunProcs(JavacProcessingEnvironment.java:919)
at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment$Round.run(JavacProcessingEnvironment.java:1262)
at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment.doProcessing(JavacProcessingEnvironment.java:1377)
at jdk.compiler/com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1234)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
... 47 more
Caused by: java.lang.NullPointerException: Cannot invoke "javax.lang.model.element.TypeElement.getEnclosedElements()" because "this.jvmNameType" is null
at com.squareup.moshi.kotlinpoet.metadata.classinspectors.ElementsClassInspector.\<init\>(ElementsClassInspector.kt:102)
at com.squareup.moshi.kotlinpoet.metadata.classinspectors.ElementsClassInspector.\<init\>(ElementsClassInspector.kt)
at com.squareup.moshi.kotlinpoet.metadata.classinspectors.ElementsClassInspector$Companion.create(ElementsClassInspector.kt:580)
at com.squareup.moshi.kotlin.codegen.apt.JsonClassCodegenProcessor.init(JsonClassCodegenProcessor.kt:87)
at org.jetbrains.kotlin.kapt3.base.incremental.IncrementalProcessor.init(incrementalProcessors.kt:36)
at org.jetbrains.kotlin.kapt3.base.ProcessorWrapper.init(annotationProcessing.kt:207)
at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment$ProcessorState.\<init\>(JavacProcessingEnvironment.java:696)
... 53 more


问:
Excel file imported incomplete in Shiny app
I made a Shiny app that takes as input several excel files, and one of those has 30000+rows.

For some reason, when importing the file using the read_excel() function, only 23000 rows are imported with no error/warning whatsover... When I import the file outside of the Shiny app, the full 30000+ rows are imported with no problems

Is there any memory constraint in Shiny perhaps? Any idea of what might be happening?

Thanks in advance!


问:
Why can i create unit tests with assert for 'invalid response' when its a returned value but not for side effects or simply return 'n' for no?
I have the following unit test, with the commented out lines not working:

```<code>def test_yes_no_indexer():
    assert yes_no_indexer(0) == 'Invalid Response'
    assert yes_no_indexer('cat') == 'Invalid Response'
    #assert yes_no_indexer('n') == 'Type in a fullname for indexing\n -  '
    #assert yes_no_indexer('y') == "Type a nickname for the person\n - "
    #assert yes_no_indexer('n') == 'n'
</code>```

Now pay attention to how returning yes or no in the same exact way that 'invalid response' is returned does not work. See last commented line yes_no_indexer('n') == 'n' to catch my drift. Something that simple should work.
Here is the mock example of the function yes_no_indexer to look at:

```<code>def yes_no_indexer(y_n):
    i = 0
    other = 'Invalid Response'
    no = 'n'
    yes = 'y'
    temp_dic = {}
    if y_n == 'y':
         fullname = input('Type their fullname\n - ').strip()
         return yes

    elif y_n == 'n':
        search_full_name1 = input("Type in a fullname for indexing\n- ")
        return no
    else:
        return other
</code>```

Now I realize that the else statement at the bottom returns other and since other is a string 'Invalid Response' I can use assert to test it. Does anybody know a way that i can test for the 'y' and 'n', (the if and elif parts), in order to demonstrate that the code continues to flow to a question if you choose something valid to input to the yes_no question?

Body:
I have the following unit test, with the commented out lines not working:

def test_yes_no_indexer():
    assert yes_no_indexer(0) == 'Invalid Response'
    assert yes_no_indexer('cat') == 'Invalid Response'
    #assert yes_no_indexer('n') == 'Type in a fullname for indexing\n -  '
    #assert yes_no_indexer('y') == "Type a nickname for the person\n - "
    #assert yes_no_indexer('n') == 'n'

Now pay attention to how returning yes or no in the same exact way that 'invalid response' is returned does not work. See last commented line yes_no_indexer('n') == 'n' to catch my drift. Something that simple should work.
Here is the mock example of the function yes_no_indexer to look at:

def yes_no_indexer(y_n):
    i = 0
    other = 'Invalid Response'
    no = 'n'
    yes = 'y'
    temp_dic = {}
    if y_n == 'y':
         fullname = input('Type their fullname\n - ').strip()
         return yes

    elif y_n == 'n':
        search_full_name1 = input("Type in a fullname for indexing\n- ")
        return no
    else:
        return other

Now I realize that the else statement at the bottom returns other and since other is a string 'Invalid Response' I can use assert to test it. Does anybody know a way that i can test for the 'y' and 'n', (the if and elif parts), in order to demonstrate that the code continues to flow to a question if you choose something valid to input to the yes_no question?


问:
libcurl link-time version (7.76.1) is older than compile-time version (7.86.0)
Whenever I start celery worker in my django project, it fails to start with the following error:

"Unrecoverable error: ImportError('The curl client requires the pycurl library.')

I have visited all the github issues and questions posted on stackoverflow but unable to pinpoint this issue. My pycurl installation is done successfully and if I run python -c 'import pycurl' && echo "Success". It returns me success but whenever I run celery worker it still gives me the pycurl error.

I was expecting celery to run successfully but in return I get an import error.

If I go to the kombu package which is installed and try to print traceback value then it outputs:

pycurl: libcurl link-time version (7.76.1) is older than compile-time version (7.86.0)

brew info openssl output is as follow:

```<code>openssl@3 is keg-only, which means it was not symlinked into /usr/local,
because macOS provides LibreSSL.

If you need to have openssl@3 first in your PATH, run:
  echo 'export PATH="/usr/local/opt/openssl@3/bin:$PATH"' >> /Users/<>/.bash_profile

For compilers to find openssl@3 you may need to set:
  export LDFLAGS="-L/usr/local/opt/openssl@3/lib"
  export CPPFLAGS="-I/usr/local/opt/openssl@3/include"

For pkg-config to find openssl@3 you may need to set:
  export PKG_CONFIG_PATH="/usr/local/opt/openssl@3/lib/pkgconfig"
</code>```

brew info curl output is as follows:

```<code>curl is keg-only, which means it was not symlinked into /usr/local,
because macOS already provides this software and installing another version in
parallel can cause all kinds of trouble.

If you need to have curl first in your PATH, run:
  echo 'export PATH="/usr/local/opt/curl/bin:$PATH"' >> /Users/<>/.bash_profile

For compilers to find curl you may need to set:
  export LDFLAGS="-L/usr/local/opt/curl/lib"
  export CPPFLAGS="-I/usr/local/opt/curl/include"

For pkg-config to find curl you may need to set:
  export PKG_CONFIG_PATH="/usr/local/opt/curl/lib/pkgconfig"
</code>```

Body:
Whenever I start celery worker in my django project, it fails to start with the following error:

"Unrecoverable error: ImportError('The curl client requires the pycurl library.')

I have visited all the github issues and questions posted on stackoverflow but unable to pinpoint this issue. My pycurl installation is done successfully and if I run python -c 'import pycurl' && echo "Success". It returns me success but whenever I run celery worker it still gives me the pycurl error.

I was expecting celery to run successfully but in return I get an import error.

If I go to the kombu package which is installed and try to print traceback value then it outputs:

pycurl: libcurl link-time version (7.76.1) is older than compile-time version (7.86.0)

brew info openssl output is as follow:

openssl@3 is keg-only, which means it was not symlinked into /usr/local,
because macOS provides LibreSSL.

If you need to have openssl@3 first in your PATH, run:
  echo 'export PATH="/usr/local/opt/openssl@3/bin:$PATH"' >> /Users/<>/.bash_profile

For compilers to find openssl@3 you may need to set:
  export LDFLAGS="-L/usr/local/opt/openssl@3/lib"
  export CPPFLAGS="-I/usr/local/opt/openssl@3/include"

For pkg-config to find openssl@3 you may need to set:
  export PKG_CONFIG_PATH="/usr/local/opt/openssl@3/lib/pkgconfig"

brew info curl output is as follows:

curl is keg-only, which means it was not symlinked into /usr/local,
because macOS already provides this software and installing another version in
parallel can cause all kinds of trouble.

If you need to have curl first in your PATH, run:
  echo 'export PATH="/usr/local/opt/curl/bin:$PATH"' >> /Users/<>/.bash_profile

For compilers to find curl you may need to set:
  export LDFLAGS="-L/usr/local/opt/curl/lib"
  export CPPFLAGS="-I/usr/local/opt/curl/include"

For pkg-config to find curl you may need to set:
  export PKG_CONFIG_PATH="/usr/local/opt/curl/lib/pkgconfig"


问:
Is there support for average aggregation using System.Diagnostics.Metrics and OpenTelmetry
Previously when using Microsoft.ApplicationInsights and reporting custom metrics I'm used to do something like _telemetryClient.GetMetric("Foo").TrackValue(0) in order to get various aggregations that I can view in Application Insights. Such as sum, max and average.

Now I'm getting into OpenTelemetry which uses System.Diagnostics.Metrics and I'm having a hard time getting similar behaviour.
For instance, look at the following API:

```<code>using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using System.Diagnostics.Metrics;

var builder = WebApplication.CreateBuilder(args);

var resource = ResourceBuilder.CreateDefault().AddService("WebApplication2");
var meterName = "WebApplication2Meter";
var meter = new Meter(meterName, "1.0");
var requestCounter = meter.CreateCounter<long>("Foo");

builder.Services.AddOpenTelemetryMetrics(opts =>
{
    opts.SetResourceBuilder(resource);
    opts.AddConsoleExporter();
    opts.AddMeter(meterName);
});
var app = builder.Build();
var random = new Random();
app.MapGet("/", () =>
{
    int val = random.Next() % 2 == 0 ? 1 : 0;
    requestCounter.Add(val);
});

app.Run();

</code>```

If I would run this code and call the API a couple of times I would get something like this in the Console output:

```<code>Export Foo, Meter: WebApplication2Meter/1.0
(2022-12-14T22:48:19.5592153Z, 2022-12-14T22:48:29.5516028Z] LongSum
Value: 18
</code>```

Here the default aggregation for the Counter is Sum. Let's say I'm interested in the average, or both, how would I go about this?

The endgame here is to export this to an OTLP collector and in the end export it to something like Datadog. I'm basically looking for the same experience as I would get with Microsoft.ApplicationInsights and its TrackValue() functionality.

I've looked into adding Views which sounds useful but didn't get it to work. Also read through the docs of .NET OpenTelemetry Client but didn't find explicitly what would help my usecase.

Body:
Previously when using Microsoft.ApplicationInsights and reporting custom metrics I'm used to do something like _telemetryClient.GetMetric("Foo").TrackValue(0) in order to get various aggregations that I can view in Application Insights. Such as sum, max and average.

Now I'm getting into OpenTelemetry which uses System.Diagnostics.Metrics and I'm having a hard time getting similar behaviour.
For instance, look at the following API:

using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using System.Diagnostics.Metrics;

var builder = WebApplication.CreateBuilder(args);

var resource = ResourceBuilder.CreateDefault().AddService("WebApplication2");
var meterName = "WebApplication2Meter";
var meter = new Meter(meterName, "1.0");
var requestCounter = meter.CreateCounter<long>("Foo");

builder.Services.AddOpenTelemetryMetrics(opts =>
{
    opts.SetResourceBuilder(resource);
    opts.AddConsoleExporter();
    opts.AddMeter(meterName);
});
var app = builder.Build();
var random = new Random();
app.MapGet("/", () =>
{
    int val = random.Next() % 2 == 0 ? 1 : 0;
    requestCounter.Add(val);
});

app.Run();

If I would run this code and call the API a couple of times I would get something like this in the Console output:

Export Foo, Meter: WebApplication2Meter/1.0
(2022-12-14T22:48:19.5592153Z, 2022-12-14T22:48:29.5516028Z] LongSum
Value: 18

Here the default aggregation for the Counter is Sum. Let's say I'm interested in the average, or both, how would I go about this?

The endgame here is to export this to an OTLP collector and in the end export it to something like Datadog. I'm basically looking for the same experience as I would get with Microsoft.ApplicationInsights and its TrackValue() functionality.

I've looked into adding Views which sounds useful but didn't get it to work. Also read through the docs of .NET OpenTelemetry Client but didn't find explicitly what would help my usecase.


问:
Python how to detect a change in executed code
I have a Python package with an entry point at __main__. I will be running a nightly Cron job, and I want the Cron job to execute the package if it detects a change in the execution of the package. I will be using git hashes to perform the comparison between files and commits.

However, if I commit a change that affects a function that is NOT used based on the current execution from the __main__ entry point, then I don't want the package to execute that night. How can I get around this issue?


问:
How to speedup df.apply() when my_func takes in col name and value
I am working on speeding up an upsert method which takes a Pandas DF and executes a query to insert all the data from the DF into a postgres DB. The slowest part of my method is a for loop which calls a cast function to transform all python datatypes to their respective postgresql types using a map and creates a string of all these values (called vals) to be inserted in my query later on.

```<code>cdef str vals = ''
df['row_statement'] = '('
cdef str c
for c in cols:
    df.row_statement += df[c].apply(lambda x: self.cast(c, x)).astype(str) + ', '

df.row_statement = df.row_statement.str[:-2] + ')'
df.row_statement += ','
vals = df.row_statement.str.cat()
vals = vals[1:-2]
df = df.drop('row_statement', axis=1)
</code>```
```<code>def cast(self, column_name, value, emptyList=False):
    cdef n = sqlalchemy.sql.null()
    if not isinstance(value, list):
        if pd.isnull(value) or value == '':
            return n
    elif emptyList and not value:
        return n
    cdef str typ = self._data_types[column_name]
    return self._cast_map[typ\(value)
</code>```

My _cast_map is basically a dictionary of lambda functions like this

```<code>'text': lambda x: f"'{x}'",
'date': lambda x: f"'{x}'::date",
'timestamp without time zone': lambda x: f"'{x}'::timestamp",
</code>```

This is my query string

```<code> qry = f"""
            INSERT INTO {self.schema}.{self.table} ({','.join(df.columns.tolist())})
            VALUES ({vals})
            {self._conflict if self._conflict else ''}
    """
</code>```

When researching for a faster method than apply I keep hearing about vectorization. Is it possible for me to vectorize in this case because my cast function requires the column name as well as the value? What would be the best way to go about speeding up a function like this? Is there a better way to cast each value other than a dictionary of lambda functions?

Ive tried iterating through the dataframe as numpy arrays but this seems to be slower even after cythonizing as much as I can. I also tried using Numba as well as pandarellel and swiftly with no luck :(

```<code>cdef int r
cdef int c
cdef int c_max = df_arr.shape[1]
cdef int r_max = df_arr.shape[0]

for r in range(r_max):
    vals += '('
    for c in range(c_max):
        vals += str(self.cast(index[c], df_arr[r, c])) + ','
    vals = vals[:-1]
    vals += '),'
vals = vals[1:-2]
</code>```

Body:
I am working on speeding up an upsert method which takes a Pandas DF and executes a query to insert all the data from the DF into a postgres DB. The slowest part of my method is a for loop which calls a cast function to transform all python datatypes to their respective postgresql types using a map and creates a string of all these values (called vals) to be inserted in my query later on.

cdef str vals = ''
df['row_statement'] = '('
cdef str c
for c in cols:
    df.row_statement += df[c].apply(lambda x: self.cast(c, x)).astype(str) + ', '

df.row_statement = df.row_statement.str[:-2] + ')'
df.row_statement += ','
vals = df.row_statement.str.cat()
vals = vals[1:-2]
df = df.drop('row_statement', axis=1)

def cast(self, column_name, value, emptyList=False):
    cdef n = sqlalchemy.sql.null()
    if not isinstance(value, list):
        if pd.isnull(value) or value == '':
            return n
    elif emptyList and not value:
        return n
    cdef str typ = self._data_types[column_name]
    return self._cast_map[typ\(value)

My _cast_map is basically a dictionary of lambda functions like this

'text': lambda x: f"'{x}'",
'date': lambda x: f"'{x}'::date",
'timestamp without time zone': lambda x: f"'{x}'::timestamp",

This is my query string

 qry = f"""
            INSERT INTO {self.schema}.{self.table} ({','.join(df.columns.tolist())})
            VALUES ({vals})
            {self._conflict if self._conflict else ''}
    """

When researching for a faster method than apply I keep hearing about vectorization. Is it possible for me to vectorize in this case because my cast function requires the column name as well as the value? What would be the best way to go about speeding up a function like this? Is there a better way to cast each value other than a dictionary of lambda functions?

Ive tried iterating through the dataframe as numpy arrays but this seems to be slower even after cythonizing as much as I can. I also tried using Numba as well as pandarellel and swiftly with no luck :(

cdef int r
cdef int c
cdef int c_max = df_arr.shape[1]
cdef int r_max = df_arr.shape[0]

for r in range(r_max):
    vals += '('
    for c in range(c_max):
        vals += str(self.cast(index[c], df_arr[r, c])) + ','
    vals = vals[:-1]
    vals += '),'
vals = vals[1:-2]


问:
VBA Connection to a querytable requires my credentials to refresh. Is there a way to reference the Web Query window to enter my credentials?
Window I am trying to reference

I am using Microsoft Dynamics to import a query table to a specific view I have set up using this: Link to workaround with this deprecated feature

Every new session of the workbook requires me to enter my company credentials before I can refresh the query.

I do this by clicking "Edit Query" in the Connection Properties Window, and it redirects me to our website to validate.

Can I reference these windows and input my credentials as part of a Macro?

My goal is to call a subroutine every day to refresh this connection and load it to another file, but if I have to log in everyday anyway, it kind of defeats the purpose.

I tried this solution but it is trying to open a browser session to input my credentials separate from the query which doesn't really solve my problem.

I can't find any way to reference the properties of these windows and recording a macro skips this step entirely.


问:
AWS Athena: A Way to Solve this OOP loop/dynamic SQL type problem (or a better approach?)
Table:

SKU
Amount
start_date
end_date

A
4
2022-02-20
2022-05-17

A
2
2022-05-18
2099-12-31

B
11
2022-04-14
2099-12-31

The following query allows me to put in any date and get the amount per sku on that date

```<code>select  SKU, Amount
from    myTable
where   date('2022-04-30') between start_date and end_date;
</code>```

Results:

SKU
Amount

A
4

B
11

Note that we have 4 for SKU A because 2022-04-30 is between 2022-02-20 and 2022-05-17 (the first record).

but if the query had:

```<code> where  date('2023-01-01') between start_date and end_date;
</code>```

Then we would get an amount of 2 for SKU A (The second record is "chosen"(2022-05-18 to 2099-12-31))

But I want this for every month. So I just need a way to run this query for each date (unless you have a better approach)

AWS Athena does not support dynamic sql, so that's not an option

I could of course just copy paste the query, change the year/month, and UNION the results, but then I would have 12*years*lines of code. This would be tedious and seems like a very bad practice (imagine if I needed it at a finer grain)

I was able to get a list of the dates I want with the following query:

```<code>with oneRowPerMonth as(
select sequence(date('2019-01-15'), date('2030-01-15'), interval '1' month) as seq
)
select date_trunc('month', date(midMonth)) + interval '1' month - interval '1' day as LastDayOfMonth
from oneRowPerMonth
cross join unnest(seq) as t(midMonth)
</code>```

...but that's as far as I've made it.

Obviously when I have multiple months I will need a date column... so I'm trying to get to something like this:

SKU
Amount
Date of Record

A
4
2022-04-30

B
11
2022-04-30

A
2
2022-05-31

B
11
2022-05-31

A
2
2022-06-31

B
11
2022-06-31

...
...
...

Body:
Table:

SKU
Amount
start_date
end_date

A
4
2022-02-20
2022-05-17

A
2
2022-05-18
2099-12-31

B
11
2022-04-14
2099-12-31

The following query allows me to put in any date and get the amount per sku on that date

select  SKU, Amount
from    myTable
where   date('2022-04-30') between start_date and end_date;

Results:

SKU
Amount

A
4

B
11

Note that we have 4 for SKU A because 2022-04-30 is between 2022-02-20 and 2022-05-17 (the first record).

but if the query had:

 where  date('2023-01-01') between start_date and end_date;

Then we would get an amount of 2 for SKU A (The second record is "chosen"(2022-05-18 to 2099-12-31))

But I want this for every month. So I just need a way to run this query for each date (unless you have a better approach)

AWS Athena does not support dynamic sql, so that's not an option

I could of course just copy paste the query, change the year/month, and UNION the results, but then I would have 12*years*lines of code. This would be tedious and seems like a very bad practice (imagine if I needed it at a finer grain)

I was able to get a list of the dates I want with the following query:

with oneRowPerMonth as(
select sequence(date('2019-01-15'), date('2030-01-15'), interval '1' month) as seq
)
select date_trunc('month', date(midMonth)) + interval '1' month - interval '1' day as LastDayOfMonth
from oneRowPerMonth
cross join unnest(seq) as t(midMonth)

...but that's as far as I've made it.

Obviously when I have multiple months I will need a date column... so I'm trying to get to something like this:

SKU
Amount
Date of Record

A
4
2022-04-30

B
11
2022-04-30

A
2
2022-05-31

B
11
2022-05-31

A
2
2022-06-31

B
11
2022-06-31

...
...
...


问:
How to catch hibernate exceptions in controller class?
I've read a lot and also tried a lot already and I'm confused and stuck so I will probably add to much information... sorry upfront.

I'm working with micronaut and want to build a backend for a small website. I decided to package by feature mostly so my package structure looks like:

```<code>site
└───server
    │   Application.java
    │
    ├───api
    │       LayoutLinkController.java
    │
    ├───configuration
    │       DatabaseConfiguration.java
    │       DatabaseConfigurationProperties.java
    │
    ├───layout
       ├───dao
       │       LinkRepository.java
       │       LinkRepositoryImpl.java
       │
       └───model
               Link.java
               LinkType.java
</code>```

My Controller directly relies on Link and LinkRepository where I use the Model Class Link as body parameter for my post and put calls, respectively saving and updating the same through the repository, like so:

```<code>@ExecuteOn(TaskExecutors.IO)
@Controller(ApiUriGenerator.LAYOUT_URI)
@Secured(SecurityRule.IS_ANONYMOUS)
public class LayoutLinkController {

    private static Logger LOGGER = LoggerFactory.getLogger(LayoutLinkController.class);

    /**
     * the suffix of this endpoint
     */
    private static final String ENDPOINT_NAME = "/links";

    private final LinkRepository linkRepository;

    LayoutLinkController(LinkRepository linkRepository) {
        this.linkRepository = linkRepository;
    }

    /**
     * Gets the link with the given id
     *
     * @author deckerdent
     * @since 0.0.1
     * @version 0.0.1
     *
     * @param id a link id
     * @return a link
     */
    @Get(ENDPOINT_NAME + "({id})")
    @Secured(SecurityRule.IS_ANONYMOUS)
    HttpResponse<?> getById(long id) {
        Link link = linkRepository.findById(id).orElse(null);
        return link != null ? HttpResponse.ok(link) : HttpResponse.notFound();
    }

    /**
     * Gets a list of all available footer links
     *
     * @author deckerdent
     * @since 0.0.1
     * @version 0.0.1
     *
     * @return an array of links
     */
    @Get(ENDPOINT_NAME)
    @Secured(SecurityRule.IS_ANONYMOUS)
    HttpResponse<?> getAll() {
        return HttpResponse.ok(linkRepository.findAll());
    }

    /**
     * Creates a link
     *
     * @author deckerdent
     * @since 0.0.1
     * @version 0.0.1
     *
     * @return the created link
     */
    @Post(ENDPOINT_NAME)
    @Secured(SecurityRule.IS_ANONYMOUS)
    HttpResponse<?> create(@Body @Valid Link link) {
        if (link.getId() != 0) {
            return HttpResponse.badRequest(new Exception("nope").getMessage());
        }
        link = linkRepository.save(link);
        return HttpResponse.created(link, URI.create(ApiUriGenerator.LAYOUT_URI + ENDPOINT_NAME + "/" + link.getId()));
    }

    /**
     * Updates a link
     *
     * @author deckerdent
     * @since 0.0.1
     * @version 0.0.1
     *
     * @return the updated link
     */
    @Put(ENDPOINT_NAME)
    @Secured(SecurityRule.IS_ANONYMOUS)
    HttpResponse<?> update(@Body @Valid Link link) {
        link = linkRepository.update(link);
        return HttpResponse.ok(link);
    }

    /**
     * Deletes a link
     *
     * @author deckerdent
     * @since 0.0.1
     * @version 0.0.1
     *
     * @param id the id of the link
     * @return 200
     */
    @Delete(ENDPOINT_NAME)
    @Secured(SecurityRule.IS_ANONYMOUS)
    HttpResponse<?> delete(long id) {
        linkRepository.deleteById(id);
        return HttpResponse.ok();
    }

}
</code>```

This is the Model

```<code>@Entity
@Table(name = "layout_links")
public class Link {

    @Id
    @GeneratedValue(strategy = AUTO)
    private long id;

    @NotNull
    @Column(name = "title", nullable = false, unique = true)
    private String title;

    @NotNull
    @Column(name = "type", nullable = false)
    private LinkType type;

    @NotNull
    @Column(name = "url", nullable = false)
    private String url;

    public Link() {
    }

    public Link(String title, LinkType type, String url) throws MalformedURLException, URISyntaxException {
        boolean isValid = this.validateUrl(url);

        if (isValid) {
            this.title = title;
            this.type = type;
            this.url = url;
        }
    }

    public long getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public LinkType getType() {
        return type;
    }

    public void setType(LinkType type) {
        this.type = type;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) throws MalformedURLException, URISyntaxException {
        boolean isValid = this.validateUrl(url);
        if (isValid) {
            this.url = url;
        }
    }

    private boolean validateUrl(String url) throws MalformedURLException, URISyntaxException {
        new URL(url).toURI();//throws exception if url is not valid.
        return true;
    }
}
</code>```

Now I get hibernate exceptions as responses in postman if I e.g. send a post request with an ID given (PersistentObjectException) or if one of the unique columns already hold the value I try to insert/update (ContraintViolationException). And I'm trying to catch these exceptions but couldn't and I guess for the same reason as here. I don't want the exception message be printed as a response with http code 500 but respond with more speaking messages.

I didn't wrap the repository into a service class yet as I thought it's just not more than persisting and reading data and there will no additional logic be in the service which only means redundand code. Also, if I go with a service class this should be my single API to everything else in the package and then using the model class Link in my controller which is in another package would be breaking this pattern, which means I would have to either create a dto class for my Link class outside my layout feature package which I feel is not a good practice or I'd have to put the controller within my feature package which I don't like as well. But I'm unsure about what good architecture is here and this is actually why I started the project. Learning patterns, architecture and stuff as I already now how to write code. I could easily find work arounds with additional database calls (e.g. a select to test if an object exists and if it equals the object to update to avoid Constraint Violation) but this is all hackish and I want to work on quality.

So what's the recommended way to go here? Is there a way to catch the hibernate exceptions right in the controller? Should I wrap the repository into a service class first even if it seems unnecessary only to then be able to catch the exceptions? Should I manually test e.g. with additional database calls?

Body:
I've read a lot and also tried a lot already and I'm confused and stuck so I will probably add to much information... sorry upfront.

I'm working with micronaut and want to build a backend for a small website. I decided to package by feature mostly so my package structure looks like:

site
└───server
    │   Application.java
    │
    ├───api
    │       LayoutLinkController.java
    │
    ├───configuration
    │       DatabaseConfiguration.java
    │       DatabaseConfigurationProperties.java
    │
    ├───layout
       ├───dao
       │       LinkRepository.java
       │       LinkRepositoryImpl.java
       │
       └───model
               Link.java
               LinkType.java

My Controller directly relies on Link and LinkRepository where I use the Model Class Link as body parameter for my post and put calls, respectively saving and updating the same through the repository, like so:

@ExecuteOn(TaskExecutors.IO)
@Controller(ApiUriGenerator.LAYOUT_URI)
@Secured(SecurityRule.IS_ANONYMOUS)
public class LayoutLinkController {

    private static Logger LOGGER = LoggerFactory.getLogger(LayoutLinkController.class);

    /**
     * the suffix of this endpoint
     */
    private static final String ENDPOINT_NAME = "/links";

    private final LinkRepository linkRepository;

    LayoutLinkController(LinkRepository linkRepository) {
        this.linkRepository = linkRepository;
    }

    /**
     * Gets the link with the given id
     *
     * @author deckerdent
     * @since 0.0.1
     * @version 0.0.1
     *
     * @param id a link id
     * @return a link
     */
    @Get(ENDPOINT_NAME + "({id})")
    @Secured(SecurityRule.IS_ANONYMOUS)
    HttpResponse<?> getById(long id) {
        Link link = linkRepository.findById(id).orElse(null);
        return link != null ? HttpResponse.ok(link) : HttpResponse.notFound();
    }

    /**
     * Gets a list of all available footer links
     *
     * @author deckerdent
     * @since 0.0.1
     * @version 0.0.1
     *
     * @return an array of links
     */
    @Get(ENDPOINT_NAME)
    @Secured(SecurityRule.IS_ANONYMOUS)
    HttpResponse<?> getAll() {
        return HttpResponse.ok(linkRepository.findAll());
    }

    /**
     * Creates a link
     *
     * @author deckerdent
     * @since 0.0.1
     * @version 0.0.1
     *
     * @return the created link
     */
    @Post(ENDPOINT_NAME)
    @Secured(SecurityRule.IS_ANONYMOUS)
    HttpResponse<?> create(@Body @Valid Link link) {
        if (link.getId() != 0) {
            return HttpResponse.badRequest(new Exception("nope").getMessage());
        }
        link = linkRepository.save(link);
        return HttpResponse.created(link, URI.create(ApiUriGenerator.LAYOUT_URI + ENDPOINT_NAME + "/" + link.getId()));
    }

    /**
     * Updates a link
     *
     * @author deckerdent
     * @since 0.0.1
     * @version 0.0.1
     *
     * @return the updated link
     */
    @Put(ENDPOINT_NAME)
    @Secured(SecurityRule.IS_ANONYMOUS)
    HttpResponse<?> update(@Body @Valid Link link) {
        link = linkRepository.update(link);
        return HttpResponse.ok(link);
    }

    /**
     * Deletes a link
     *
     * @author deckerdent
     * @since 0.0.1
     * @version 0.0.1
     *
     * @param id the id of the link
     * @return 200
     */
    @Delete(ENDPOINT_NAME)
    @Secured(SecurityRule.IS_ANONYMOUS)
    HttpResponse<?> delete(long id) {
        linkRepository.deleteById(id);
        return HttpResponse.ok();
    }

}

This is the Model

@Entity
@Table(name = "layout_links")
public class Link {

    @Id
    @GeneratedValue(strategy = AUTO)
    private long id;

    @NotNull
    @Column(name = "title", nullable = false, unique = true)
    private String title;

    @NotNull
    @Column(name = "type", nullable = false)
    private LinkType type;

    @NotNull
    @Column(name = "url", nullable = false)
    private String url;

    public Link() {
    }

    public Link(String title, LinkType type, String url) throws MalformedURLException, URISyntaxException {
        boolean isValid = this.validateUrl(url);

        if (isValid) {
            this.title = title;
            this.type = type;
            this.url = url;
        }
    }

    public long getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public LinkType getType() {
        return type;
    }

    public void setType(LinkType type) {
        this.type = type;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) throws MalformedURLException, URISyntaxException {
        boolean isValid = this.validateUrl(url);
        if (isValid) {
            this.url = url;
        }
    }

    private boolean validateUrl(String url) throws MalformedURLException, URISyntaxException {
        new URL(url).toURI();//throws exception if url is not valid.
        return true;
    }
}

Now I get hibernate exceptions as responses in postman if I e.g. send a post request with an ID given (PersistentObjectException) or if one of the unique columns already hold the value I try to insert/update (ContraintViolationException). And I'm trying to catch these exceptions but couldn't and I guess for the same reason as here. I don't want the exception message be printed as a response with http code 500 but respond with more speaking messages.

I didn't wrap the repository into a service class yet as I thought it's just not more than persisting and reading data and there will no additional logic be in the service which only means redundand code. Also, if I go with a service class this should be my single API to everything else in the package and then using the model class Link in my controller which is in another package would be breaking this pattern, which means I would have to either create a dto class for my Link class outside my layout feature package which I feel is not a good practice or I'd have to put the controller within my feature package which I don't like as well. But I'm unsure about what good architecture is here and this is actually why I started the project. Learning patterns, architecture and stuff as I already now how to write code. I could easily find work arounds with additional database calls (e.g. a select to test if an object exists and if it equals the object to update to avoid Constraint Violation) but this is all hackish and I want to work on quality.

So what's the recommended way to go here? Is there a way to catch the hibernate exceptions right in the controller? Should I wrap the repository into a service class first even if it seems unnecessary only to then be able to catch the exceptions? Should I manually test e.g. with additional database calls?


问:
Amazon SNS issue on uploading files with big sizes
Does someone get the problem on Amazon SNS on uploading files with the big size.
E.g: I'm able to upload 17MB file to S3 bucket and handle SNS notification ObjectCreated:Put properly

However, if I upload 24MB file to S3 bucket (file uploaded successfully), it seems the system gets SNS notification with the eventName ObjectRemoved:Delete, which is weird.

Is there some limits on uploading to AWS bucket?
The Standard Storage class mode is used during file uploading process.

Thanks!


问:
hostname "imgur.com" is not configured under images in your `next.config.js` but it is configured correctly on my next.config.js, what is wrong?
I'm trying to upload an image stored in MongoDB.

```<code>{ '_id': 1, 'type': 'shirt', 'price': 20, 'pic': 'https://imgur.com/6D53pAF'}
</code>```

The error is saying my next.config.js is not configured properly but it is configured exactly how it would suggest.

```<code>module.exports = {
    images: {
      remotePatterns: [
        {
          protocol: "https",
          hostname: "imgur.com",
          port: '3000',
          pathname: ""},
      ],
    },
  }
</code>```

What am I doing wrong or is there a better way of doing this?

I originally had the image stored over my github in an issues section on my project and it worked but once I change databases it will no longer pull up the image.

Body:
I'm trying to upload an image stored in MongoDB.

{ '_id': 1, 'type': 'shirt', 'price': 20, 'pic': 'https://imgur.com/6D53pAF'}

The error is saying my next.config.js is not configured properly but it is configured exactly how it would suggest.

module.exports = {
    images: {
      remotePatterns: [
        {
          protocol: "https",
          hostname: "imgur.com",
          port: '3000',
          pathname: ""},
      ],
    },
  }

What am I doing wrong or is there a better way of doing this?

I originally had the image stored over my github in an issues section on my project and it worked but once I change databases it will no longer pull up the image.


问:
How do I, in iOS 16.1.2, restrict access to the participants of a share to be able to be changed by only the owner of the share?
How do I implement UICloudSharingController so that in iOS 16.1.2, only the owner of the share can add or remove participants of the share, with the exception that a participant can remove himself from the share. When I set availablePermissions to [.allowPrivate, .allowReadOnly], when in iOS 16.1.2, UICloudSharingController says at the top that anyone who has access to the link can edit.

When I set availablePermissions to [.allowPrivate], there is no text at the top under Collaboration, and when I try to share, I get an error says "An Error Occurred" and "Unable to start collaboration".


问:
VBA Folder contents Empty Move to next Folder path
I've written a VBA to copy files from a list of directory over to a specific folder.
The code works fine and what I now need to do is add an IF statement for the VBA to move to the next folder when one folder is empty and copy any files in the next folder.

below is the current vba

```<code>Sub ExtractChecklistData()

Dim FSO As Object
Dim SourcePath As String

Dim DestinationPath As String
Dim FileExtn As String

'Starters
SourcePath = Sheet4.Range("B2")
SourcePath2 = Sheet4.Range("B4")
SourcePath3 = Sheet4.Range("B6")
SourcePath4 = Sheet4.Range("B8")
SourcePath5 = Sheet4.Range("B10")
SourcePath6 = Sheet4.Range("B12")
SourcePath7 = Sheet4.Range("B14")
SourcePath8 = Sheet4.Range("B16")
SourcePath9 = Sheet4.Range("B18")
SourcePath10 = Sheet4.Range("B20")
SourcePath11 = Sheet4.Range("B22")
SourcePath12 = Sheet4.Range("B24")
SourcePath13 = Sheet4.Range("B26")
SourcePath14 = Sheet4.Range("B28")
SourcePath15 = Sheet4.Range("B30")

DestinationPath = "C:\Users\kov4n\OneDrive\Documents\Excel Templates\Management Reports\Data
Extract Folder\"

FileExtn = "*.xlsx*"

Set FSO = CreateObject("scripting.filesystemobject")

FSO.CopyFile Source:=SourcePath & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath2 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath3 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath4 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath5 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath6 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath7 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath8 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath9 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath10 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath11 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath12 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath13 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath14 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath15 & FileExtn, Destination:=DestinationPath
</code>```

The user selects the month on the dashboard sheet and sheet4 holds the file path names which changes based on the selected month. The folders are already set up and each month the team will add files to the area they are working on. Some months, some areas would not have any work so the folder related to that area will not have any files.

Testing this brings up the error message 'run-time error 53 - file not found'
So it copies the first file into the assigned folder moves to the next file path and as it has no files it brings up the above error.
What I need is possible an IF statement that will move to the next folder path when a folder is empty...

Hope someone can help further

Body:
I've written a VBA to copy files from a list of directory over to a specific folder.
The code works fine and what I now need to do is add an IF statement for the VBA to move to the next folder when one folder is empty and copy any files in the next folder.

below is the current vba

Sub ExtractChecklistData()

Dim FSO As Object
Dim SourcePath As String

Dim DestinationPath As String
Dim FileExtn As String

'Starters
SourcePath = Sheet4.Range("B2")
SourcePath2 = Sheet4.Range("B4")
SourcePath3 = Sheet4.Range("B6")
SourcePath4 = Sheet4.Range("B8")
SourcePath5 = Sheet4.Range("B10")
SourcePath6 = Sheet4.Range("B12")
SourcePath7 = Sheet4.Range("B14")
SourcePath8 = Sheet4.Range("B16")
SourcePath9 = Sheet4.Range("B18")
SourcePath10 = Sheet4.Range("B20")
SourcePath11 = Sheet4.Range("B22")
SourcePath12 = Sheet4.Range("B24")
SourcePath13 = Sheet4.Range("B26")
SourcePath14 = Sheet4.Range("B28")
SourcePath15 = Sheet4.Range("B30")

DestinationPath = "C:\Users\kov4n\OneDrive\Documents\Excel Templates\Management Reports\Data
Extract Folder\"

FileExtn = "*.xlsx*"

Set FSO = CreateObject("scripting.filesystemobject")

FSO.CopyFile Source:=SourcePath & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath2 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath3 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath4 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath5 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath6 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath7 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath8 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath9 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath10 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath11 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath12 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath13 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath14 & FileExtn, Destination:=DestinationPath
FSO.CopyFile Source:=SourcePath15 & FileExtn, Destination:=DestinationPath

The user selects the month on the dashboard sheet and sheet4 holds the file path names which changes based on the selected month. The folders are already set up and each month the team will add files to the area they are working on. Some months, some areas would not have any work so the folder related to that area will not have any files.

Testing this brings up the error message 'run-time error 53 - file not found'
So it copies the first file into the assigned folder moves to the next file path and as it has no files it brings up the above error.
What I need is possible an IF statement that will move to the next folder path when a folder is empty...

Hope someone can help further


问:
Why deque.append appears to be slower than list when performing extra calculations?
As shown below, where I try to implement a memory with max length.

a uses a list that pops the first item when reaches the maximum length, b uses deque and relies on its built-in management of maxlen

```<code>import time
import numpy as np
import collections

a = [np.ones((64, 64), dtype=np.int64) + i for i in range(100000)]
b = collections.deque(a, maxlen=100000)
element = np.ones((64, 64), dtype=np.int64)

time.sleep(0.5)  # stimulates more initialization and preprocessing

t = time.time()
for i in range(10000):
    temp = element * i - i  # stimulate some calculation on the fly
    b.append(temp)
print(time.time() - t)

t = time.time()
for i in range(10000):
    temp = element * i - i  # stimulate some calculation on the fly
    if len(a) == 100000:
        a.pop(0)
    a.append(temp)
print(time.time() - t)
print(len(a))
print(len(b))
</code>```

Expected: b should take less time running since it has O(1) for popleft and append, while a has O(n) for popleft and O(1) for append. Since their stimulated calculation is the same, deque should take less time.

Surprisingly, it outputs this:

```<code>0.6613483428955078  # time for deque
0.24213624000549316  # time for list
100000  # check length and make sure they are doing what I want
100000
</code>```

Even more surprisingly, if I remove the calculation temp = element * i - i for both implementations, the result changed significantly

```<code>0.0010280609130859375  # time for deque
0.16035985946655273  # time for list
100000
100000
</code>```

What went wrong in the above code? Why do calculations unrelated to append make such a difference?

Body:
As shown below, where I try to implement a memory with max length.

a uses a list that pops the first item when reaches the maximum length, b uses deque and relies on its built-in management of maxlen

import time
import numpy as np
import collections

a = [np.ones((64, 64), dtype=np.int64) + i for i in range(100000)]
b = collections.deque(a, maxlen=100000)
element = np.ones((64, 64), dtype=np.int64)

time.sleep(0.5)  # stimulates more initialization and preprocessing

t = time.time()
for i in range(10000):
    temp = element * i - i  # stimulate some calculation on the fly
    b.append(temp)
print(time.time() - t)

t = time.time()
for i in range(10000):
    temp = element * i - i  # stimulate some calculation on the fly
    if len(a) == 100000:
        a.pop(0)
    a.append(temp)
print(time.time() - t)
print(len(a))
print(len(b))

Expected: b should take less time running since it has O(1) for popleft and append, while a has O(n) for popleft and O(1) for append. Since their stimulated calculation is the same, deque should take less time.

Surprisingly, it outputs this:

0.6613483428955078  # time for deque
0.24213624000549316  # time for list
100000  # check length and make sure they are doing what I want
100000

Even more surprisingly, if I remove the calculation temp = element * i - i for both implementations, the result changed significantly

0.0010280609130859375  # time for deque
0.16035985946655273  # time for list
100000
100000

What went wrong in the above code? Why do calculations unrelated to append make such a difference?


问:
Error : Problem does not follow DCP rules. while solving CVXPY
I'm trying to solve the problem using cvxpy. but got the error which says

```<code>Problem does not follow DCP rules. Specifically:
The following constraints are not DCP:
1.0 <= quad_over_lin(var633, 1.0) , because the following subexpressions are not:
|--  1.0 <= quad_over_lin(var633, 1.0)"
</code>```

Does anyone know what's gone wrong?

```<code># 4. Define the input variables for the optimization problem
# Define the support vector machine model
w = cp.Variable(X.shape[1])
b = cp.Variable()

margin = cp.sum_squares(w)
constraints = [cp.multiply(y_train, X_train @ w + b) >= margin, margin >= 1]
objective = cp.Minimize(0.5 * cp.sum_squares(w) + cp.sum(cp.pos(1 - cp.multiply(y_train, X_train @ w + b))))
problem = cp.Problem(objective, constraints)

# Train the support vector machine model

try:
    problem.solve()
    print("status:"+ prob.status)
except Exception as e:
    print(e)

# y_train shape = (19244, 19)
# X_train shape = (19244,)
# X.shape[1] = 19
</code>```

Body:
I'm trying to solve the problem using cvxpy. but got the error which says

Problem does not follow DCP rules. Specifically:
The following constraints are not DCP:
1.0 <= quad_over_lin(var633, 1.0) , because the following subexpressions are not:
|--  1.0 <= quad_over_lin(var633, 1.0)"

Does anyone know what's gone wrong?

# 4. Define the input variables for the optimization problem
# Define the support vector machine model
w = cp.Variable(X.shape[1])
b = cp.Variable()

margin = cp.sum_squares(w)
constraints = [cp.multiply(y_train, X_train @ w + b) >= margin, margin >= 1]
objective = cp.Minimize(0.5 * cp.sum_squares(w) + cp.sum(cp.pos(1 - cp.multiply(y_train, X_train @ w + b))))
problem = cp.Problem(objective, constraints)

# Train the support vector machine model

try:
    problem.solve()
    print("status:"+ prob.status)
except Exception as e:
    print(e)

# y_train shape = (19244, 19)
# X_train shape = (19244,)
# X.shape[1] = 19


问:
Excel Add-In Requires Re-Installation to Update Files even when Cache is being Updated
I currently have a few users setup to use my Add-In via sideloading from a network share. Today I made some changes to a JS file and tested with a user to see if their computer/Add-In updated and it did not.

First I tried just running the Add-In, that didn't work

Then I tried hitting "refresh" --> "Add" to "re-install" Add-In but that didn't work.

I had to completely wipe the users installation and start from scratch, that worked.

I figured this was something I could set/adjust in my nginx webserver so I set out to read/test but during my testing, I noted in dev tools that it was in fact getting 200 response and fetching updated files when they were updated on the nginx server.

This tells me that somehow Excel itself is caching the files outside of the browsers awareness or something and I'm at a loss what to do.

I will NOT change my file names for each deployment as that is no good for git and I prefer having the same file names.

Is there some other way I can ensure/push users Excel to fetch updated code?

Note: Users are 100% Windows Clients w/ Office 365

Update:

I need a server side solution, I don't have the ability to run a script on end users computer to clear the cache/re-install with each update


问:
How to add widget to entire column in a QTableWidget?
New to PyQt5. I'm trying to create a Table using QTableWidget where certain columns are spin box or drop down widgets. I am able to add create a widget and it to a particular cell. I have the following questions:

How do I automatically add these widgets when a user add a new row to a table? From reading the documentation, it seems I can use itemDelegateForRow, but I'm not sure which methods to implement from the QAbstractItemDelegate class. Can someone point me to a small example on how to use this?

The column Parent is a combo box whose values need to get updated with a list of all other values in column Block. By default, it has a single item 'top'. When a row is added with say, Block=A, then in the 2nd row the list of valid choices for Parent shoudl be A, top, etc. What signal should I monitor/connect to update the combox box and how?

Right now, I have the following code to create a 5x5 table.

```<code>hier_blocks = QTableWidget(5, 5)
hier_blocks.verticalHeader().setDefaultSectionSize(25)

hdrs = ['Block', 'Parent', 'Library', 'Freq (MHz)', 'Qty']
hier_blocks.setHorizontalHeaderLabels(hdrs)

parent_box = QComboBox(hier_blocks)
parent_box.addItem('top')
hier_blocks.setCellWidget(0, 1, parent_box)

lib_box = QComboBox(hier_blocks)
hier_blocks.setCellWidget(0, 2, lib_box)
freq_box = QSpinBox(hier_blocks)
freq_box.setRange(1, 4000)
hier_blocks.setCellWidget(0, 3, freq_box)
qty_box = QSpinBox(hier_blocks)
qty_box.setRange(1, 20)
hier_blocks.setCellWidget(0, 4, qty_box)

hier_layout = QVBoxLayout()
hier_layout.addWidget(hier_blocks)
</code>```

Body:
New to PyQt5. I'm trying to create a Table using QTableWidget where certain columns are spin box or drop down widgets. I am able to add create a widget and it to a particular cell. I have the following questions:

How do I automatically add these widgets when a user add a new row to a table? From reading the documentation, it seems I can use itemDelegateForRow, but I'm not sure which methods to implement from the QAbstractItemDelegate class. Can someone point me to a small example on how to use this?

The column Parent is a combo box whose values need to get updated with a list of all other values in column Block. By default, it has a single item 'top'. When a row is added with say, Block=A, then in the 2nd row the list of valid choices for Parent shoudl be A, top, etc. What signal should I monitor/connect to update the combox box and how?

Right now, I have the following code to create a 5x5 table.

hier_blocks = QTableWidget(5, 5)
hier_blocks.verticalHeader().setDefaultSectionSize(25)

hdrs = ['Block', 'Parent', 'Library', 'Freq (MHz)', 'Qty']
hier_blocks.setHorizontalHeaderLabels(hdrs)

parent_box = QComboBox(hier_blocks)
parent_box.addItem('top')
hier_blocks.setCellWidget(0, 1, parent_box)

lib_box = QComboBox(hier_blocks)
hier_blocks.setCellWidget(0, 2, lib_box)
freq_box = QSpinBox(hier_blocks)
freq_box.setRange(1, 4000)
hier_blocks.setCellWidget(0, 3, freq_box)
qty_box = QSpinBox(hier_blocks)
qty_box.setRange(1, 20)
hier_blocks.setCellWidget(0, 4, qty_box)

hier_layout = QVBoxLayout()
hier_layout.addWidget(hier_blocks)