问:
How to resolve project build failure in android studio
I am developing a mobile application in Android studio which was working ok until I ran a pod install and upgrade. Now the application build fails with the following message.

Can anyone advise how to clear the error??

Error output from Xcode build:
↳
** BUILD FAILED **

Xcode's output:
↳
Writing result bundle at path:
/var/folders/ps/pgrhgf817_30hnjb7xx03v980000gn/T/flutter_tools.b4u9ug/flutter_ios_build_temp_dirXreP3Q/temporary_xcresult_bundle

```<code>../../.pub-cache/hosted/pub.dartlang.org/agora_uikit-1.1.0/lib/controllers/rtc_event_handlers.dart:140:6: Error: No named parameter with the name 'onMediaDeviceChanged'.
  }, onMediaDeviceChanged: (deviceType) {
     ^^^^^^^^^^^^^^^^^^^^
../../.pub-cache/hosted/pub.dartlang.org/agora_rtc_engine-6.1.0/lib/src/agora_rtc_engine.dart:1537:9: Context: Found this candidate, but the arguments don't match.
  const RtcEngineEventHandler({
        ^^^^^^^^^^^^^^^^^^^^^
Failed to package /Users/md/src/app.mobile.test-app-ui.
Command PhaseScriptExecution failed with a nonzero exit code
note: Building targets in dependency order
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 9.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'abseil' from project 'Pods')
warning: Run script build phase 'Create Symlinks to Header Folders' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target 'abseil' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 9.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'PromisesObjC' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'FMDB' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 10.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'FirebaseAppCheckInterop' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 9.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'CocoaAsyncSocket' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 9.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'BoringSSL-GRPC' from project 'Pods')
warning: Run script build phase 'Create Symlinks to Header Folders' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target 'BoringSSL-GRPC' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 10.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'GTMSessionFetcher' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 9.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'nanopb' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 10.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'flutter_sound_core' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 9.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'Libuv-gRPC' from project 'Pods')
warning: Run script build phase 'Create Symlinks to Header Folders' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target 'Libuv-gRPC' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'KTVCocoaHTTPServer' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 9.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'GoogleUtilities' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'KTVHTTPCache' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 9.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'gRPC-Core' from project 'Pods')
warning: Run script build phase 'Create Symlinks to Header Folders' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target 'gRPC-Core' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 10.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'FirebaseCoreInternal' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 10.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'FirebaseCore' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 10.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'FirebaseCoreExtension' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 9.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'gRPC-C++' from project 'Pods')
warning: Run script build phase 'Create Symlinks to Header Folders' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target 'gRPC-C++' from project 'Pods')
warning: Run script build phase 'Run Script' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target 'Runner' from project 'Runner')
warning: Run script build phase 'Thin Binary' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target 'Runner' from project 'Runner')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'leveldb-library' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'AgoraIrisEventFlutter_iOS' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'AgoraIrisRTC_iOS' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'AgoraRtm_iOS' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 9.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'gRPC-C++-gRPCCertificates-Cpp' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'AgoraRtcEngine_iOS' from project 'Pods')

Result bundle written to path:
    /var/folders/ps/pgrhgf817_30hnjb7xx03v980000gn/T/flutter_tools.b4u9ug/flutter_ios_build_temp_dirXreP3Q/temporary_xcresult_bundle
</code>```

Could not build the application for the simulator.
Error launching application on iPhone 14 Pro Max.

Body:
I am developing a mobile application in Android studio which was working ok until I ran a pod install and upgrade. Now the application build fails with the following message.

Can anyone advise how to clear the error??

Error output from Xcode build:
↳
** BUILD FAILED **

Xcode's output:
↳
Writing result bundle at path:
/var/folders/ps/pgrhgf817_30hnjb7xx03v980000gn/T/flutter_tools.b4u9ug/flutter_ios_build_temp_dirXreP3Q/temporary_xcresult_bundle

../../.pub-cache/hosted/pub.dartlang.org/agora_uikit-1.1.0/lib/controllers/rtc_event_handlers.dart:140:6: Error: No named parameter with the name 'onMediaDeviceChanged'.
  }, onMediaDeviceChanged: (deviceType) {
     ^^^^^^^^^^^^^^^^^^^^
../../.pub-cache/hosted/pub.dartlang.org/agora_rtc_engine-6.1.0/lib/src/agora_rtc_engine.dart:1537:9: Context: Found this candidate, but the arguments don't match.
  const RtcEngineEventHandler({
        ^^^^^^^^^^^^^^^^^^^^^
Failed to package /Users/md/src/app.mobile.test-app-ui.
Command PhaseScriptExecution failed with a nonzero exit code
note: Building targets in dependency order
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 9.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'abseil' from project 'Pods')
warning: Run script build phase 'Create Symlinks to Header Folders' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target 'abseil' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 9.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'PromisesObjC' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'FMDB' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 10.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'FirebaseAppCheckInterop' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 9.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'CocoaAsyncSocket' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 9.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'BoringSSL-GRPC' from project 'Pods')
warning: Run script build phase 'Create Symlinks to Header Folders' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target 'BoringSSL-GRPC' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 10.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'GTMSessionFetcher' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 9.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'nanopb' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 10.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'flutter_sound_core' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 9.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'Libuv-gRPC' from project 'Pods')
warning: Run script build phase 'Create Symlinks to Header Folders' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target 'Libuv-gRPC' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'KTVCocoaHTTPServer' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 9.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'GoogleUtilities' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'KTVHTTPCache' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 9.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'gRPC-Core' from project 'Pods')
warning: Run script build phase 'Create Symlinks to Header Folders' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target 'gRPC-Core' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 10.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'FirebaseCoreInternal' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 10.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'FirebaseCore' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 10.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'FirebaseCoreExtension' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 9.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'gRPC-C++' from project 'Pods')
warning: Run script build phase 'Create Symlinks to Header Folders' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target 'gRPC-C++' from project 'Pods')
warning: Run script build phase 'Run Script' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target 'Runner' from project 'Runner')
warning: Run script build phase 'Thin Binary' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target 'Runner' from project 'Runner')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'leveldb-library' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'AgoraIrisEventFlutter_iOS' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'AgoraIrisRTC_iOS' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'AgoraRtm_iOS' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 9.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'gRPC-C++-gRPCCertificates-Cpp' from project 'Pods')
/Users/md/src/app.mobile.test-app-ui/ios/Pods/Pods.xcodeproj: warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 11.0 to 16.1.99. (in target 'AgoraRtcEngine_iOS' from project 'Pods')

Result bundle written to path:
    /var/folders/ps/pgrhgf817_30hnjb7xx03v980000gn/T/flutter_tools.b4u9ug/flutter_ios_build_temp_dirXreP3Q/temporary_xcresult_bundle

Could not build the application for the simulator.
Error launching application on iPhone 14 Pro Max.


来源: stackexchange

问:
Type 'Promise<[RowDataPacket[] |RowDataPacket[][] |OkPacket |OkPacket[] | ResultSetHeader, FieldPacket[]]>' is not assignable to type 'Promise<Post>'
I have the following codes:

This isdb.ts:

```<code>import dotenv from "dotenv";
dotenv.config();
import mysql from "mysql2";

const pool = mysql.createPool({
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  database: process.env.DB_NAME,
  password: process.env.DB_PASSWORD,
});

export default pool.promise();
</code>```

This is Post.ts:

```<code>import db from "../config/db";

class Post {
  title;
  body;
  yyyy:any;
  mm:any;
  dd:any;
  constructor(title: any, body: any) {
    this.title = title;
    this.body = body;
  }

  save() {
    const d = new Date();
    const yyyy = d.getFullYear();
    const mm = d.getMonth() + 1;
    const dd = d.getDate();

    const createdAtDate = `${yyyy}-${mm}-${dd}`;

    const sql = `
    INSERT INTO posts(
      title,
      body,
      created_at
    )
    VALUES(
      '${this.title}',
      '${this.body}',
      '${createdAtDate}'
    )
    `;

    return db.execute(sql);
  }

  static findAll() {
    const sql = "SELECT * FROM posts;";

    return db.execute(sql);
  }

  static findById(id:any): Promise<Post> {
    const sql = `SELECT * FROM posts WHERE id = ${id};`;

    return db.execute(sql);
  }
}

export default Post;
</code>```

And the following is postControllers.ts:

```<code>import { Request, Response, NextFunction } from "express";
import Post from "../models/Post";

const getAllPosts = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const [posts , _] = await Post.findAll();

    res.status(200).json({ count: (posts as any).length, posts });
  } catch (error) {
    next(error);
  }
};

const createNewPost = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { title, body } = req.body;
    const post = new Post(title, body);

    await post.save();

    res.status(201).json({ message: "Post created" });
  } catch (error) {
    next(error);
  }
};

const getPostById = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const postId = req.params.id;

    const [post, _] = await Post.findById(postId);

    res.status(200).json({ post: post[0] });
  } catch (error) {
    next(error);
  }
};

export {getAllPosts , createNewPost, getPostById };
</code>```

This code was a JavaScript project and was working before. I am trying to convert it to a TypeScript project. I have a problem with MySQL responses in the following line inside the findById function:

```<code>return db.execute(sql);
</code>```

The ERROR says:

```<code>Type 'Promise<[RowDataPacket[] | RowDataPacket[][] | OkPacket | OkPacket[] | ResultSetHeader, FieldPacket[]]>' is not assignable to type 'Promise<Post>'.
</code>```

Also another related problem here:

```<code>const [post, _] = await Post.findById(postId);
</code>```

The ERROR:

Type 'Post' must have a 'Symbol.iterator' method that returns an
iterator.ts(2488)

ContentLicense: CC BY-SA 4.0

Body:
I have the following codes:

This isdb.ts:

import dotenv from "dotenv";
dotenv.config();
import mysql from "mysql2";

const pool = mysql.createPool({
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  database: process.env.DB_NAME,
  password: process.env.DB_PASSWORD,
});

export default pool.promise();

This is Post.ts:

import db from "../config/db";

class Post {
  title;
  body;
  yyyy:any;
  mm:any;
  dd:any;
  constructor(title: any, body: any) {
    this.title = title;
    this.body = body;
  }

  save() {
    const d = new Date();
    const yyyy = d.getFullYear();
    const mm = d.getMonth() + 1;
    const dd = d.getDate();

    const createdAtDate = `${yyyy}-${mm}-${dd}`;

    const sql = `
    INSERT INTO posts(
      title,
      body,
      created_at
    )
    VALUES(
      '${this.title}',
      '${this.body}',
      '${createdAtDate}'
    )
    `;

    return db.execute(sql);
  }

  static findAll() {
    const sql = "SELECT * FROM posts;";

    return db.execute(sql);
  }

  static findById(id:any): Promise<Post> {
    const sql = `SELECT * FROM posts WHERE id = ${id};`;

    return db.execute(sql);
  }
}

export default Post;

And the following is postControllers.ts:

import { Request, Response, NextFunction } from "express";
import Post from "../models/Post";

const getAllPosts = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const [posts , _] = await Post.findAll();

    res.status(200).json({ count: (posts as any).length, posts });
  } catch (error) {
    next(error);
  }
};

const createNewPost = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { title, body } = req.body;
    const post = new Post(title, body);

    await post.save();

    res.status(201).json({ message: "Post created" });
  } catch (error) {
    next(error);
  }
};

const getPostById = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const postId = req.params.id;

    const [post, _] = await Post.findById(postId);

    res.status(200).json({ post: post[0] });
  } catch (error) {
    next(error);
  }
};

export {getAllPosts , createNewPost, getPostById };

This code was a JavaScript project and was working before. I am trying to convert it to a TypeScript project. I have a problem with MySQL responses in the following line inside the findById function:

return db.execute(sql);

The ERROR says:

Type 'Promise<[RowDataPacket[] | RowDataPacket[][] | OkPacket | OkPacket[] | ResultSetHeader, FieldPacket[]]>' is not assignable to type 'Promise<Post>'.

Also another related problem here:

const [post, _] = await Post.findById(postId);

The ERROR:

Type 'Post' must have a 'Symbol.iterator' method that returns an
iterator.ts(2488)


问:
Custom built opencv 4..7.0 python import problem
I built opencv 4.7.0 from source

I have a folder cv2 with cv2.so in it

If I call import cv2 within the folder -- all ok

If I call from without from cv2 import cv2 or similar stuff, nothing will work with error:

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: Bindings generation error. Submodule name should always start with a parent module name. Parent name: cv2.cv2. Submodule name: cv2
</code>```

Everything worked with opencv 4.5.5

I've seen similar problems with opencv-python: https://github.com/opencv/opencv-python/issues/676

Does anyone knows how to solve this import issue?

Body:
I built opencv 4.7.0 from source

I have a folder cv2 with cv2.so in it

If I call import cv2 within the folder -- all ok

If I call from without from cv2 import cv2 or similar stuff, nothing will work with error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: Bindings generation error. Submodule name should always start with a parent module name. Parent name: cv2.cv2. Submodule name: cv2

Everything worked with opencv 4.5.5

I've seen similar problems with opencv-python: https://github.com/opencv/opencv-python/issues/676

Does anyone knows how to solve this import issue?


问:
ffmpeg crashing server working with fpm-php
I'm running a wordpress bitnami stack consisting of apache, mariadb and fpm-php.
I have cron jobs fulfilling encoding of one video at a time using ffmpeg, so while fpm-php is serving http requests ffmpeg works in parallel encoding videos.
When encoding starts everything seems to work fine, as shown here:

But eventually after around an hour the server crashes due to lack of memory space. I've read that when CPU can't handle ffmpeg, ffmpeg will start consuming RAM until it exhausts it so that might be what causes the sudden spike in memory usage.

The image bellow illustrates what happens when the server crashes, kswapd0 creates virtual memory out of disk space to cope with lack of memory:

The server has 4vCPU and 8GB RAM. Website traffic is just me and a colleague, so it should be able to handle ffmpeg taking up around 1vCPU to encode videos.

I use the following configuration for fpm-php:

```<code>pm=ondemand
pm.max_children=5
pm.start_servers=2
pm.min_spare_servers=1
pm.max_spare_servers=3
pm.max_requests = 500
</code>```

Has anyone had this issue before?

Thank you.

I've tried changing around the configuration of fpm-php, but the issue still happens. I don't see how ffpmeg can crash the server when it's taking up about 25% of the CPU only, when there's no traffic to the server.

Body:
I'm running a wordpress bitnami stack consisting of apache, mariadb and fpm-php.
I have cron jobs fulfilling encoding of one video at a time using ffmpeg, so while fpm-php is serving http requests ffmpeg works in parallel encoding videos.
When encoding starts everything seems to work fine, as shown here:

But eventually after around an hour the server crashes due to lack of memory space. I've read that when CPU can't handle ffmpeg, ffmpeg will start consuming RAM until it exhausts it so that might be what causes the sudden spike in memory usage.

The image bellow illustrates what happens when the server crashes, kswapd0 creates virtual memory out of disk space to cope with lack of memory:

The server has 4vCPU and 8GB RAM. Website traffic is just me and a colleague, so it should be able to handle ffmpeg taking up around 1vCPU to encode videos.

I use the following configuration for fpm-php:

pm=ondemand
pm.max_children=5
pm.start_servers=2
pm.min_spare_servers=1
pm.max_spare_servers=3
pm.max_requests = 500

Has anyone had this issue before?

Thank you.

I've tried changing around the configuration of fpm-php, but the issue still happens. I don't see how ffpmeg can crash the server when it's taking up about 25% of the CPU only, when there's no traffic to the server.


问:
From a cyber security point of view, what cipher algorithm and digest is safer to use if you want to store a salted password file?
I assume the most important factor for anyone making this choice would be security itself. Ie if someone hacks into your server and steals the file, they will have to crack the password file in order to use it so choosing an obscure algorithm or combination of algorithms would be preferred?

Also what are other factors that might influence my choice? I can think of:

Speed and performance

Availability of algorithms in different languages and platforms

Easiness to use and maintain due to tooling


问:
useContext not updating useState variable globally
The user variable in AuthContext is updating locally but when I try to print it outside of the value, it returns with an empty array. Basically im trying to retrieve the user variable from AuthContext in various components, one being login.js, and when I try to use it in that component, its an empty object.

AuthContext.js

```<code>import React, { useEffect, useState, createContext } from 'react'
import { auth, onAuthStateChanged} from '../firebase'

export const AuthContext = createContext()

export const AuthContextProvider = ({ children }) => {

    const [user, setUser] = useState({})
    useEffect(() => {
        const unsub = onAuthStateChanged(auth, (user) => {
          setUser(user);
          console.log(user);
        });
        }
    )
  return (
    <AuthContext.Provider value={{setUser, user}}>
        {children}
    </AuthContext.Provider>
  )
}

</code>```

Login

```<code>import React, { useEffect, useState, useContext } from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faGoogle} from '@fortawesome/free-brands-svg-icons'
import { faHeart } from '@fortawesome/free-solid-svg-icons'
import { auth, provider, signInWithPopup, GoogleAuthProvider, onAuthStateChanged, signOut, setDoc } from '../firebase'
import { AuthContext } from '../Context/AuthContext'
import { useNavigate } from 'react-router-dom'
import { collection, doc, addDoc, db } from '../firebase'

const Login = () => {

  const {user} = useContext(AuthContext)
  const navigate = useNavigate()

  const googleSignIn = async() =>{
    await signInWithPopup(auth, provider)
    await addToUsers()
    navigate('/')
  }

  const addToUsers = async() =>{
    // const usersRef = await setDoc(doc(db, 'users', user?.uid), {
    //   displayName: user?.displayName,
    //   photoURL : user?.photoURL,
    // })
    console.log(user)
  }

  return (
        <div class="loginWrapper">
        <h1 className='title'>Monkey With The <br/> IMS.</h1>
        <button class="loginButton" onClick={()=>googleSignIn()} >Sign in With  <FontAwesomeIcon icon={faGoogle} /> </button>
        <p>Made with <FontAwesomeIcon icon={faHeart} style={{color: 'black'}} />, by Het Patel</p>
        </div>
  )
}

export default Login
</code>```

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.scss';
import App from './App';
import { AuthContextProvider } from './Context/AuthContext';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <AuthContextProvider>
        <App />
    </AuthContextProvider>
);
</code>```

Body:
The user variable in AuthContext is updating locally but when I try to print it outside of the value, it returns with an empty array. Basically im trying to retrieve the user variable from AuthContext in various components, one being login.js, and when I try to use it in that component, its an empty object.

AuthContext.js

import React, { useEffect, useState, createContext } from 'react'
import { auth, onAuthStateChanged} from '../firebase'

export const AuthContext = createContext()

export const AuthContextProvider = ({ children }) => {

    const [user, setUser] = useState({})
    useEffect(() => {
        const unsub = onAuthStateChanged(auth, (user) => {
          setUser(user);
          console.log(user);
        });
        }
    )
  return (
    <AuthContext.Provider value={{setUser, user}}>
        {children}
    </AuthContext.Provider>
  )
}

Login

import React, { useEffect, useState, useContext } from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faGoogle} from '@fortawesome/free-brands-svg-icons'
import { faHeart } from '@fortawesome/free-solid-svg-icons'
import { auth, provider, signInWithPopup, GoogleAuthProvider, onAuthStateChanged, signOut, setDoc } from '../firebase'
import { AuthContext } from '../Context/AuthContext'
import { useNavigate } from 'react-router-dom'
import { collection, doc, addDoc, db } from '../firebase'

const Login = () => {

  const {user} = useContext(AuthContext)
  const navigate = useNavigate()

  const googleSignIn = async() =>{
    await signInWithPopup(auth, provider)
    await addToUsers()
    navigate('/')
  }

  const addToUsers = async() =>{
    // const usersRef = await setDoc(doc(db, 'users', user?.uid), {
    //   displayName: user?.displayName,
    //   photoURL : user?.photoURL,
    // })
    console.log(user)
  }

  return (

Monkey With The
 IMS.

        <button class="loginButton" onClick={()=>googleSignIn()} >Sign in With  <FontAwesomeIcon icon={faGoogle} /> </button>

Made with <FontAwesomeIcon icon={faHeart} style={{color: 'black'}} />, by Het Patel

  )
}

export default Login

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.scss';
import App from './App';
import { AuthContextProvider } from './Context/AuthContext';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <AuthContextProvider>
        <App />
    </AuthContextProvider>
);


问:
Mars single-layer raster basemap from OpenPlanetaryMap not correctly shown with React & Leaflet
I am using this mars basemap from OpenPlanetrayMap to display it with react-leaflet on my website. The map is not correctly shown:
.

I couldn't figure out how to fix it.

See my code in Sandbox.

It works when I use a multiple-layer raster like this one.


问:
Getting Wiktionary Term from DBPedia Sparql Endpoint with RDFSharp
I am trying to return dbpedia entries for Wiktionary terms by searching for the term using the RDFSharp library. (Once I have the term, I'll get additional properties, but for now I just need to know if I'm approaching this the right way.)

My current implementation (below) only returns empty result sets.

How can I modify my RDFQuery and the dependent object instances to return get the dbpedia entry for a specific Wiktionary term by matching part of speech and the term string?

I used a related example SPARQL query from SO  (How to get all nouns in a certain language from Wiktionary using SPARQL) and the RDFSharp query docs as a starting point.

...

```<code>//spaql generated by rdfsharp
PREFIX terms: <http://wiktionary.dbpedia.org/terms/>
PREFIX dc: <http://purl.org/dc/elements/1.1/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>

SELECT *
WHERE {
  {
    ?TERM terms:hasPoS terms: Noun .
    FILTER ( ?TERMLABEL = "dog" )
  }
}
LIMIT 5
//end sparql fragment

//C#
RDFSPARQLEndpoint dbPedidaWiktionaryEndpoint = new RDFSPARQLEndpoint(new Uri(@"https://dbpedia.org/sparql"));

RDFNamespace terms = new RDFNamespace("terms", "http://wiktionary.dbpedia.org/terms/");
RDFNamespace dc = new RDFNamespace("dc", "http://purl.org/dc/elements/1.1/");
RDFNamespace rdfs = new RDFNamespace("rdfs", "http://www.w3.org/2000/01/rdf-schema#");

RDFResource termsHasPos = new RDFResource(terms + "hasPoS");
RDFResource termsNoun = new RDFResource(terms + "Noun");
RDFResource termsEnglish = new RDFResource(terms + "English");

// Create variables
RDFVariable searchTerm = new RDFVariable("term"); //passed in
RDFVariable termLabel = new RDFVariable("termLabel");

RDFPatternGroup PG1 = new RDFPatternGroup();

RDFPattern termIsANoun = new RDFPattern(searchTerm, termsHasPos, termsNoun);

RDFModifier limitReturnCount = new RDFLimitModifier(5);

PG1.AddPattern(termIsANoun)
   .AddFilter(new RDFComparisonFilter( RDFQueryEnums.RDFComparisonFlavors.EqualTo, termLabel, new RDFPlainLiteral(term)));

RDFSPARQLEndpointQueryOptions endpointQueryOptions = new RDFSPARQLEndpointQueryOptions();

endpointQueryOptions.TimeoutMilliseconds = 30000;

RDFGraph graph = new RDFGraph();
// Compose query
RDFSelectQuery query = new RDFSelectQuery()
    .AddPrefix(terms)
    .AddPrefix(dc)
    .AddPrefix(rdfs)
    .AddPatternGroup(PG1)
    .AddModifier(limitReturnCount);

//have tried these "flavors" of query invocations, jic, alway empty result :/
//RDFSelectQueryResult selectResult = await query.ApplyToSPARQLEndpointAsync(dbPedidaWiktionaryEndpoint, endpointQueryOptions);
//RDFSelectQueryResult selectResult = query.ApplyToGraph(graph);
RDFSelectQueryResult selectResult = await query.ApplyToGraphAsync(graph);

string queryText = query.ToString();

</code>```

Body:
I am trying to return dbpedia entries for Wiktionary terms by searching for the term using the RDFSharp library. (Once I have the term, I'll get additional properties, but for now I just need to know if I'm approaching this the right way.)

My current implementation (below) only returns empty result sets.

How can I modify my RDFQuery and the dependent object instances to return get the dbpedia entry for a specific Wiktionary term by matching part of speech and the term string?

I used a related example SPARQL query from SO  (How to get all nouns in a certain language from Wiktionary using SPARQL) and the RDFSharp query docs as a starting point.

...

//spaql generated by rdfsharp
PREFIX terms: <http://wiktionary.dbpedia.org/terms/>
PREFIX dc: <http://purl.org/dc/elements/1.1/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>

SELECT *
WHERE {
  {
    ?TERM terms:hasPoS terms: Noun .
    FILTER ( ?TERMLABEL = "dog" )
  }
}
LIMIT 5
//end sparql fragment

//C#
RDFSPARQLEndpoint dbPedidaWiktionaryEndpoint = new RDFSPARQLEndpoint(new Uri(@"https://dbpedia.org/sparql"));

RDFNamespace terms = new RDFNamespace("terms", "http://wiktionary.dbpedia.org/terms/");
RDFNamespace dc = new RDFNamespace("dc", "http://purl.org/dc/elements/1.1/");
RDFNamespace rdfs = new RDFNamespace("rdfs", "http://www.w3.org/2000/01/rdf-schema#");

RDFResource termsHasPos = new RDFResource(terms + "hasPoS");
RDFResource termsNoun = new RDFResource(terms + "Noun");
RDFResource termsEnglish = new RDFResource(terms + "English");

// Create variables
RDFVariable searchTerm = new RDFVariable("term"); //passed in
RDFVariable termLabel = new RDFVariable("termLabel");

RDFPatternGroup PG1 = new RDFPatternGroup();

RDFPattern termIsANoun = new RDFPattern(searchTerm, termsHasPos, termsNoun);

RDFModifier limitReturnCount = new RDFLimitModifier(5);

PG1.AddPattern(termIsANoun)
   .AddFilter(new RDFComparisonFilter( RDFQueryEnums.RDFComparisonFlavors.EqualTo, termLabel, new RDFPlainLiteral(term)));

RDFSPARQLEndpointQueryOptions endpointQueryOptions = new RDFSPARQLEndpointQueryOptions();

endpointQueryOptions.TimeoutMilliseconds = 30000;

RDFGraph graph = new RDFGraph();
// Compose query
RDFSelectQuery query = new RDFSelectQuery()
    .AddPrefix(terms)
    .AddPrefix(dc)
    .AddPrefix(rdfs)
    .AddPatternGroup(PG1)
    .AddModifier(limitReturnCount);

//have tried these "flavors" of query invocations, jic, alway empty result :/
//RDFSelectQueryResult selectResult = await query.ApplyToSPARQLEndpointAsync(dbPedidaWiktionaryEndpoint, endpointQueryOptions);
//RDFSelectQueryResult selectResult = query.ApplyToGraph(graph);
RDFSelectQueryResult selectResult = await query.ApplyToGraphAsync(graph);

string queryText = query.ToString();


问:
How do I use the robot class to draw islands inside a two dimensional array?
I am trying to create a program that will take control of my mouse for me, and draw an island created by an array in one go, however I have no clue how to begin this, or if it is possible. I included an example of a type of island in a two dimensional array. The actual array would contain numbers from 0-63, and therefore have 64 types of islands. The image is simplified.

example of an island
Another type of island

I am not sure on how to even begin and came here to ask for a plan on how to draw these types of islands in one go. I already have the two dimensional array, I just want to know how to make my mouse control it.


问:
Nuke Build Framework Setting
Nuke build and running unit tests
My solution has projects of various Framework targets.

After the successful builds, I want to run Unit Tests with VSTest, passing the matching assemblies to it via VSTestSettings.

I found the assemblies with Nuke.IO.Common's PathConstruction AbsolutePath GlobFiles

However, only one framework version will end up being tested

So what I imagined I should do, was to split up the call of VSTest to just the list of assemblies for each framework:

To do so, I found the distinct list of all target frameworks:

```<code>List<string> disctinctFrameworks = assemblies.Select(a => ((TargetFrameworkAttribute)Assembly.LoadFrom(a).GetCustomAttributes(typeof(TargetFrameworkAttribute)).First()).FrameworkDisplayName).Distinct().ToList();
</code>```

That results in a list like:

```<code>- disctinctFrameworks   Count = 3   System.Collections.Generic.List<string>
    [0] ".NET Framework 4.8"    string
    [1] ".NET Framework 4.7.2"  string
    [2] ".NET Framework 4.6.1"  string
</code>```

[EDIT: note that I did change FrameworkDisplayName to FrameworkName, and also changed to Load instead of LoadFrom, and it seems to work, but is looping through assemblies in this manner the only way to achieve this??]

With that, I wanted to setup a new VSTestSettings with the matching assemblies for each listed framework, and call VSTest with the result:

```<code>var vsTestSettings = new VSTestSettings()
    .SetTestAssemblies(assemblies)
    .SetLogger(BuildConstants.VsTestLoggerParameters)
    .SetTestAdapterPath(PackagesDirectory)
    .SetProcessExecutionTimeout(BuildConstants.TestExecutionTimeout)
    .SetInIsolation(true)
    .SetFramework(framework)
    .SetParallel(true);
</code>```

where 'framework' is one of the values above...

but when you look at SetFramework, it only seems to take a VsTestFramework parameter, and that only looks like it supports the options:

```<code>Framework35
Framework40
Framework45
</code>```

My frameworks listed above don't match this format, or value, as they're higher versions, but it doesn't 'complain' when I call the .SetFramework(framework). I don't think this is using this correctly.

What is the correct way to create the VSTestSettings for the frameworks listed above, so I can appropriately call VSTest?

Title: Nuke Build Framework Setting

Body:
Nuke build and running unit tests
My solution has projects of various Framework targets.

After the successful builds, I want to run Unit Tests with VSTest, passing the matching assemblies to it via VSTestSettings.

I found the assemblies with Nuke.IO.Common's PathConstruction AbsolutePath GlobFiles

However, only one framework version will end up being tested

So what I imagined I should do, was to split up the call of VSTest to just the list of assemblies for each framework:

To do so, I found the distinct list of all target frameworks:

List<string> disctinctFrameworks = assemblies.Select(a => ((TargetFrameworkAttribute)Assembly.LoadFrom(a).GetCustomAttributes(typeof(TargetFrameworkAttribute)).First()).FrameworkDisplayName).Distinct().ToList();

That results in a list like:

- disctinctFrameworks   Count = 3   System.Collections.Generic.List<string>
    [0] ".NET Framework 4.8"    string
    [1] ".NET Framework 4.7.2"  string
    [2] ".NET Framework 4.6.1"  string

[EDIT: note that I did change FrameworkDisplayName to FrameworkName, and also changed to Load instead of LoadFrom, and it seems to work, but is looping through assemblies in this manner the only way to achieve this??]

With that, I wanted to setup a new VSTestSettings with the matching assemblies for each listed framework, and call VSTest with the result:

var vsTestSettings = new VSTestSettings()
    .SetTestAssemblies(assemblies)
    .SetLogger(BuildConstants.VsTestLoggerParameters)
    .SetTestAdapterPath(PackagesDirectory)
    .SetProcessExecutionTimeout(BuildConstants.TestExecutionTimeout)
    .SetInIsolation(true)
    .SetFramework(framework)
    .SetParallel(true);

where 'framework' is one of the values above...

but when you look at SetFramework, it only seems to take a VsTestFramework parameter, and that only looks like it supports the options:

Framework35
Framework40
Framework45

My frameworks listed above don't match this format, or value, as they're higher versions, but it doesn't 'complain' when I call the .SetFramework(framework). I don't think this is using this correctly.

What is the correct way to create the VSTestSettings for the frameworks listed above, so I can appropriately call VSTest?


问:
Sliverlist can't render page via go_router
When I trying to display the page through Material.router, flutter throws an error stating that CustomScrollView received RenderSemanticsAnnotations, and expected RenderSliver despite the fact that the TestPage() page contains a list with one element

```<code>The following assertion was thrown building _FocusMarker:
A RenderViewport expected a child of type RenderSliver but received a child of type RenderSemanticsAnnotations.

RenderObjects expect specific types of children because they coordinate with their children during layout and paint. For example, a RenderSliver cannot be the child of a RenderBox because a RenderSliver does not understand the RenderBox layout protocol.
    The RenderViewport that expected a RenderSliver child was created by: Viewport ← IgnorePointer-[GlobalKey#37a38] ← Semantics ← Listener ← _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#51ead] ← Listener ← _ScrollableScope ← _ScrollSemantics-[GlobalKey#08b2b] ← NotificationListener<ScrollMetricsNotification> ← Scrollable ← CustomScrollView ← ⋯
    The RenderSemanticsAnnotations that did not match the expected child type was created by: Semantics ← _FocusMarker ← Focus ← HeroControllerScope ← ScrollConfiguration ← MaterialApp ← Viewport ← IgnorePointer-[GlobalKey#37a38] ← Semantics ← Listener ← _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#51ead]
</code>```

```<code>class App extends StatelessWidget {
  App({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: CustomScrollView(
          slivers: [
            AppBarLayout(),
            MaterialApp.router(routerConfig: _router,)
          ],
        ),
        bottomNavigationBar: FooterNavbar());
}

final _router = GoRouter(
  initialLocation: "/test",
  navigatorKey: _rootNavigatorKey,
  routes: [
    GoRoute(
        path: "/test",
        builder: (BuildContext context, GoRouterState state) {
          return const TestPage();
        }),
  ],
);
</code>```
```<code>class TestPage extends StatefulWidget {
  const TestPage({Key? key}) : super(key: key);

  @override
  State<TestPage> createState() => _TestPageState();
}

class _TestPageState extends State<TestPage> {
  @override
  Widget build(BuildContext context) {
    return SliverList(
    }, childCount: 0));
  }
}
</code>```

On the other hand, if you access the desired page directly, it will display it correctly.

```<code>Widget build(BuildContext context) {
    return Scaffold(
        body: CustomScrollView(
          slivers: [
            AppBarLayout(),
            TestPage()
          ],
        ),
        bottomNavigationBar: FooterNavbar());
  }
</code>```

Are there any solutions to this problem?

Body:
When I trying to display the page through Material.router, flutter throws an error stating that CustomScrollView received RenderSemanticsAnnotations, and expected RenderSliver despite the fact that the TestPage() page contains a list with one element

The following assertion was thrown building _FocusMarker:
A RenderViewport expected a child of type RenderSliver but received a child of type RenderSemanticsAnnotations.

RenderObjects expect specific types of children because they coordinate with their children during layout and paint. For example, a RenderSliver cannot be the child of a RenderBox because a RenderSliver does not understand the RenderBox layout protocol.
    The RenderViewport that expected a RenderSliver child was created by: Viewport ← IgnorePointer-[GlobalKey#37a38] ← Semantics ← Listener ← _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#51ead] ← Listener ← _ScrollableScope ← _ScrollSemantics-[GlobalKey#08b2b] ← NotificationListener<ScrollMetricsNotification> ← Scrollable ← CustomScrollView ← ⋯
    The RenderSemanticsAnnotations that did not match the expected child type was created by: Semantics ← _FocusMarker ← Focus ← HeroControllerScope ← ScrollConfiguration ← MaterialApp ← Viewport ← IgnorePointer-[GlobalKey#37a38] ← Semantics ← Listener ← _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#51ead]

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: CustomScrollView(
          slivers: [
            AppBarLayout(),
            MaterialApp.router(routerConfig: _router,)
          ],
        ),
        bottomNavigationBar: FooterNavbar());
}

final _router = GoRouter(
  initialLocation: "/test",
  navigatorKey: _rootNavigatorKey,
  routes: [
    GoRoute(
        path: "/test",
        builder: (BuildContext context, GoRouterState state) {
          return const TestPage();
        }),
  ],
);

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

  @override
  State<TestPage> createState() => _TestPageState();
}

class _TestPageState extends State<TestPage> {
  @override
  Widget build(BuildContext context) {
    return SliverList(
    }, childCount: 0));
  }
}

On the other hand, if you access the desired page directly, it will display it correctly.

Widget build(BuildContext context) {
    return Scaffold(
        body: CustomScrollView(
          slivers: [
            AppBarLayout(),
            TestPage()
          ],
        ),
        bottomNavigationBar: FooterNavbar());
  }

Are there any solutions to this problem?


问:
Multiple Different Clicks as input
I am trying to code so that the code can take in 2 points where i clicked on the canvas(GUI) and can draw a line between these two points but i am not sure where to start and how it works.

I know how to make the program draw a line and i also know that i have to collect the clicked points in an Arraylist but i dont know how the code can take the clicked points as input. I think "MouseListener" should be used here but i dont know how to go forward with it. How can I code the program so that it takes in the clicked points and adds them in the Arraylist?

Title: Multiple Different Clicks as input


问:
Await for the user choice in AlerDialog
How can I wait for the  user choice, I tried many approaches like this one: https://github.com/chakra-ui/chakra-ui/issues/1554 but doesn't work.
My code:

```<code> import {
  AlertDialog,
  AlertDialogBody,
  AlertDialogContent,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogOverlay,
  Button,
} from "@chakra-ui/react"
import { useRecoilState } from "recoil"
import { unTitleTag as unTitleTagAtom } from "../../atoms/controls"

export function AlertDelCreateCancel({ isOpen, onClose }) {
  const [unTitletag, setunTitleTag] = useRecoilState(unTitleTagAtom)
  //setunTitleTag(1)

  function deleteTag() {
    setunTitleTag(2)
    onClose()
  }

  return (
    <>
  <AlertDialog
    isOpen={isOpen}
    onClose={onClose}
    closeOnOverlayClick={false}
  >
    <AlertDialogOverlay>
      <AlertDialogContent backgroundColor="dark.background">
        <AlertDialogHeader fontSize="lg" fontWeight="bold">
          Your Region
        </AlertDialogHeader>

        <AlertDialogBody>
          Are you sure you want to exit....?
        </AlertDialogBody>

        <AlertDialogFooter>
          <Button onClick={cancelAnswer}>Cancel</Button>
          <Button colorScheme="red" onClick={deleteTag} ml={3}>
            Delete
          </Button>
          <Button colorScheme="red" onClick={createEmptyTag} ml={3}>
            Create Empty
          </Button>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialogOverlay>
  </AlertDialog>
</>
</code>```

)
}

And I'm calling this AlertDialog from other component:

```<code>const {
  isOpen: isAlertOpen,
  onOpen: openAlert,
  onClose: closeAlert,
} = useDisclosure()...
openAlert()
if (unTitleTag === 1) {
        return
} else if (unTitleTag === 2) {
        //delete
        setTags((prev) => prev.filter((s) => s.id !== tagSelected.id))
}....
<AlertDelCreateCancel onClose={closeAlert} isOpen={isAlertOpen} />
</code>```

....

Please help, I need to wait for one of the choices: Cancel, Delete, Create, but the program continues immediately after the AlertDialog (modal) is called.

Title: Await for the user choice in AlerDialog

Body:
How can I wait for the  user choice, I tried many approaches like this one: https://github.com/chakra-ui/chakra-ui/issues/1554 but doesn't work.
My code:

 import {
  AlertDialog,
  AlertDialogBody,
  AlertDialogContent,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogOverlay,
  Button,
} from "@chakra-ui/react"
import { useRecoilState } from "recoil"
import { unTitleTag as unTitleTagAtom } from "../../atoms/controls"

export function AlertDelCreateCancel({ isOpen, onClose }) {
  const [unTitletag, setunTitleTag] = useRecoilState(unTitleTagAtom)
  //setunTitleTag(1)

  function deleteTag() {
    setunTitleTag(2)
    onClose()
  }

  return (
    <>
  <AlertDialog
    isOpen={isOpen}
    onClose={onClose}
    closeOnOverlayClick={false}
  >
    <AlertDialogOverlay>
      <AlertDialogContent backgroundColor="dark.background">
        <AlertDialogHeader fontSize="lg" fontWeight="bold">
          Your Region
        </AlertDialogHeader>

        <AlertDialogBody>
          Are you sure you want to exit....?
        </AlertDialogBody>

        <AlertDialogFooter>
          <Button onClick={cancelAnswer}>Cancel</Button>
          <Button colorScheme="red" onClick={deleteTag} ml={3}>
            Delete
          </Button>
          <Button colorScheme="red" onClick={createEmptyTag} ml={3}>
            Create Empty
          </Button>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialogOverlay>
  </AlertDialog>
</>

)
}

And I'm calling this AlertDialog from other component:

const {
  isOpen: isAlertOpen,
  onOpen: openAlert,
  onClose: closeAlert,
} = useDisclosure()...
openAlert()
if (unTitleTag === 1) {
        return
} else if (unTitleTag === 2) {
        //delete
        setTags((prev) => prev.filter((s) => s.id !== tagSelected.id))
}....
<AlertDelCreateCancel onClose={closeAlert} isOpen={isAlertOpen} />

....

Please help, I need to wait for one of the choices: Cancel, Delete, Create, but the program continues immediately after the AlertDialog (modal) is called.


问:
How to communicate between multiple discord Bots?
I am trying to let two discord Bots communicate together.
Since I am using py-cord and aiohttp is already in my stack, I thought maby I could use aiohttp to to that.
I could not find a way to do that using the aiohttp websockets. I could not create a permanent tcp connection that I could use from both direction in case of an event.
One direction works fine.

Do you have an advice how I could let the Bots communicate?

How would you let the bots communicate?

(I am using Python)

At the moment my plan is to make a webserver listener on one bot and when the other needs something, it makes a request to the webserver.

EDIT:
Why Websockets? They are most efficient!


问:
Unresolved inclusion in Eclispe linux kernel. CDT instructions error?
I managed to compile the Ubuntu 5,15 linux kernel with Eclipse 2022,09, Ubuntu kernel link

I followed The Eclipse Kernel instructions

The kernel is correctly compiled  BUT In some files I’m getting “Unresolved inclusion:< …. .h>

This seems to show that the problem is due to Eclipse, NOT the compiler. The indexer is not finding some include library (like #include <inttypes.h> in mkpiggy.c)

I have a DEADLOCK:

I wondering HOW to solve the problem:

-for the Eclipse kernel instructions above, we must NOT INCLUDE
Preprocessor Include Paths and Paths and Symbols to consider the
standard include directory

-for the Indexer, considering that some include file are NOT present in the linux project tree, we must DO INCLUDE  Preprocessor Include Paths and Paths and Symbols to consider the standard include directory

The PROBLEM seems to BE in the same Eclipse INSTRUCTIONS for the Linux kernel, that is preventing the system to look for standard system library:

“ The kernel is a free-standing environment by ISO C99 definition. That is, it does not want to be polluted, and obviously cannot work with, the "host" header files and libraries.

...

Rationale for this step: -nostdinc already asked gcc to not search the standard system directories for header files. But the Linux Kernel depends on GCC-provided "freestanding environment" headers like stdarg.h, stdbool.h and so on, which are typically hosted by GCC under /usr/lib/gcc///include.”

The solutions for the indexer, that are forcing to act on Preprocessor Include Paths and Paths and Symbols, are the following:
"Unresolved inclusion" error with Eclipse CDT for C standard library headers

https://help.eclipse.org/latest/index.jsp?topic=%2Forg.eclipse.cdt.doc.user%2Ftasks%2Fcdt_t_sd.htm

https://help.eclipse.org/latest/index.jsp?topic=%2Forg.eclipse.cdt.doc.user%2Freference%2Fcdt_u_prop_general_sd_entries.htm

Are there any other solutions compatible with the Eclipse linux kernel instructions ?


问:
Importing gmsh gives OSError
I'm trying to import the gmsh python package but getting the following error. I installed gmsh using mamba install python-gmsh (which I got from here) inside Ubuntu but I'm importing the module within Pycharm on Windows using WSL.

```<code>File "/home/mai/mambaforge/envs/myenv/lib/python3.9/site-packages/gmsh.py", line 86, in <module>
    lib = CDLL(libpath)
  File "/home/mai/mambaforge/envs/myenv/lib/python3.9/ctypes/__init__.py", line 374, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: libGL.so.1: cannot open shared object file: No such file or directory
</code>```

I've installed gmsh previously using mamba and it worked but this time it's giving issues.

Edit:  I found out it was because I was missing OpenGL. It comes preinstalled on Windows/Linux but not with WSL it seems.

Title: Importing gmsh gives OSError

Body:
I'm trying to import the gmsh python package but getting the following error. I installed gmsh using mamba install python-gmsh (which I got from here) inside Ubuntu but I'm importing the module within Pycharm on Windows using WSL.

File "/home/mai/mambaforge/envs/myenv/lib/python3.9/site-packages/gmsh.py", line 86, in <module>
    lib = CDLL(libpath)
  File "/home/mai/mambaforge/envs/myenv/lib/python3.9/ctypes/__init__.py", line 374, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: libGL.so.1: cannot open shared object file: No such file or directory

I've installed gmsh previously using mamba and it worked but this time it's giving issues.

Edit:  I found out it was because I was missing OpenGL. It comes preinstalled on Windows/Linux but not with WSL it seems.


问:
Generic struct with no fields of type T, only methods
Im trying to create a struct which can be used to read and write to file with generic parameters.

I have several methods on this struct which take a generic type T, but the struct itself does not have any fields of type T.

Here is the code:

pub struct AccessObject<T: Identifiable + Serialize + DeserializeOwned> {
    pub indexes: String,
    pub file_names: Vec<String>,
}

impl<T: Identifiable + Serialize + DeserializeOwned> AccessObject<T> {
    pub fn new(indexes: &String, file_names: Vec<String>) -> AccessObject<T> {
        return AccessObject {
            indexes: indexes.clone(),
            file_names,
        };
    }

    pub fn get(&self, id: u64) -> Option<T> {
        let index_dao = IndexDao::new(&self.indexes);

        return match index_dao.get(id) {
            Some(index) => {
                let mut file = file_op::connect(&self.file_names[index.file_number as usize]);

                file.seek(SeekFrom::Start(index.file_position));

                let read = file_op::read::<T>(&mut file).unwrap();
                Some(read)
            }
            None => None,
        };
    }
}
```
<p>I would like to keep the references to <code>indexes</code> and <code>file_names</code>, hence the struct. I would like to be able to create other structs with the generic one, something like this:</p>
<pre class="lang-rust prettyprint-override"><code>pub struct GraphAccessObject {
    pub access_object: AccessObject<Graph>,
}
</code>```

Initially I had implemented the AccessObject struct as a trait, but I realised I was repeating a lot of code writing the same thing for each struct I implemented the trait for.

The problem is I get an error on my generic struct saying that there are no fields with type T and so to remove the generic parameter. Is there a way I can do this other than just implementing the methods on their own outside of the struct?

Can I implement a trait for several types at once?

Body:
Im trying to create a struct which can be used to read and write to file with generic parameters.

I have several methods on this struct which take a generic type T, but the struct itself does not have any fields of type T.

Here is the code:

pub struct AccessObject<T: Identifiable + Serialize + DeserializeOwned> {
    pub indexes: String,
    pub file_names: Vec<String>,
}

impl<T: Identifiable + Serialize + DeserializeOwned> AccessObject<T> {
    pub fn new(indexes: &String, file_names: Vec<String>) -> AccessObject<T> {
        return AccessObject {
            indexes: indexes.clone(),
            file_names,
        };
    }

    pub fn get(&self, id: u64) -> Option<T> {
        let index_dao = IndexDao::new(&self.indexes);

        return match index_dao.get(id) {
            Some(index) => {
                let mut file = file_op::connect(&self.file_names[index.file_number as usize]);

                file.seek(SeekFrom::Start(index.file_position));

                let read = file_op::read::<T>(&mut file).unwrap();
                Some(read)
            }
            None => None,
        };
    }
}

I would like to keep the references to indexes and file_names, hence the struct. I would like to be able to create other structs with the generic one, something like this:

pub struct GraphAccessObject {
    pub access_object: AccessObject<Graph>,
}

Initially I had implemented the AccessObject struct as a trait, but I realised I was repeating a lot of code writing the same thing for each struct I implemented the trait for.

The problem is I get an error on my generic struct saying that there are no fields with type T and so to remove the generic parameter. Is there a way I can do this other than just implementing the methods on their own outside of the struct?

Can I implement a trait for several types at once?


问:
Uploading a file via android app to PHP web server
An independent developer is developing a native Android app for me. I am responsible for making the API endpoint in PHP for the app to upload an image file to the server.

I do not have any Android development experience (so I can't answer any questions you may have in this regard). All uploads I have done before in PHP were on-site, using a browse button, and then I have access to the $_FILES object, easy-peasy, but I am not sure what the inputs from the app will be (developer is not available right now). How does this typically work when an app sends uploaded file data through to an API endpoint? Is it an encoded string of sorts? I am assuming that the app will read the file from the local device, and pass a string through to me, that I need to handle via something like file_put_contents on the server. Is that correct?

Edit: I simulated this in Postman to some degree. I set up the endpoint to simply output $_FILES in PHP, and then browsed for a file in Postman to send, and Postman uses new CURLFILE() to pass the file on to the API endpoint. It then appears that I have access to the $_FILES object. So - let me rephrase the question slightly now: Is it safe to assume I will get the file in that format and handle as a normal upload, or what should I prepare for?


问:
Big html blur doesn't work on firefox and has a slow performance on Safari
I have these Shapes on my Website as a background, so they need to be extremely blurred:

```

On firefox, the blur just can't be bigger than 100px, and on safari, the performance is awful and laggy.

Is there another way to add that gradient effect to my website or what else can I do?

Body:
I have these Shapes on my Website as a background, so they need to be extremely blurred:

On firefox, the blur just can't be bigger than 100px, and on safari, the performance is awful and laggy.

Is there another way to add that gradient effect to my website or what else can I do?


问:
What does ''r:|[._-]=* r:|=*' accomplish in ZSH Completion matching?
Does r:|[._-]=* r:|=* accomplish anything in ZSH Completion matching? Aren't we already matching forward on the right hand side?

I've tried a few examples with it on and off and it seems like it accomplishes nothing

Completion already completes forward in the right hand side direction, anything that originally matches seems to still be matching with or without that pattern matching list from some trials? I can't think of an example where the matching occurs with the extra rule and no matching occurs without the extra rule.


问:
Failed to load plugin 'react' declared in 'BaseConfig » somepath\index.js': Cannot find module '../internals/a-callable'
Out of nowhere, the following errors appeared while I was trying to run yarn build on my windows machine

Failed to load plugin 'react' declared in 'BaseConfig » C:\builds\caseIsNotTheIssue\clients\react-client-app\node_modules\eslint-config-react-app\index.js': Cannot find module '../internals/a-callable'

I have tried the following:

Delete node_modules folder

Delete yarn.lock`

Update various plugins but it didn't change a thing

Update Node versions

Removing eslintConfig from package.json

Checking path upper/lower case

Nothing of the above-changed anything :|

Any idea why this error appeared and how can I try and fix it?


问:
Debugging craps game simulation in C
Before scoffing at my erroneous code let me briefly inform you what I am trying to accomplish, and where I am going wrong.

Craps is a game played with 2 dice. If you roll 7 or 11 on the first roll you win. If you roll 2, 3 or 12 on the first roll you lose. Any other roll is called the "point" and the game continues. Now the player wins if on any subsequent roll the player rolls "point" again. However if the player rolls a 7 before rolling the "point" then the player loses. Any other roll (aside from "point" or 7) is ignored and we continue rolling until we hit "point" or 7.

In my simulation the roll_dice function should generate two random numbers between 1 and 6 and add them. The play_game function should play one craps game and returns true if the player wins and false if the player loses. It is also responsible for displaying messages showing the results of the player's dice rolls. We keep track of the numbers of wins and losses in main.

The problem in my code happens when the roll_dice function returns a number that is not: 7, 11 or 2, 3, 12. I.e. When it rolls a "point". When it rolls a "point" then the subsequent roll is also always the "point" and the game finishes with a win. I'm looking at the last for loop in play_game and I suspect the error is there but I don't know why it's wrong. For some reason the value of the score2 variable is always the "point" (if score1 is a "point") and I don't know why this is the case. Surely by invoking roll_dice a second time score2 should sometimes not be equal to score1?

```<code>#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>

int roll_dice(void);
bool play_game(void);

int main(void)
{
  int wins = 0, losses = 0;

  for(;;) {
    if(play_game())
    {
      printf("You win!\n");
      wins++;
    }
    else
    {
      printf("You lose!\n");
      losses++;
    }
    char x;
    printf("\nPlay again? ");
    scanf("%c", &x);
    getchar();      //absorbs the "ENTER" button once y,Y,n or N has been typed

    if(x == 'y' || x == 'Y')
    continue;
    if(x == 'n' || x == 'N')
    {
       printf("Wins: %d Losses: %d\n", wins, losses);
       break;
    }
   }

  return 0;
}

int roll_dice(void)
{
  int die1, die2;
  srand((unsigned) time(NULL));

  die1 = 1 + rand() % 6;
  die2 = 1 + rand() % 6;

  return die1 + die2;
}

bool play_game(void)
{
  int score1 = roll_dice();

  if(score1 == 7 || score1 == 11)
  {
    printf("You rolled: %d\n", score1);
    return true;
  }
  if(score1 == 2 || score1 == 3 || score1 == 12)
   {
     printf("You rolled: %d\n", score1);
     return false;
   }

  else
  {
    printf("You rolled %d\nYour point is %d\n", score1, score1);
  }

  for(;;){
    int score2 = roll_dice();
    if(score2 == 7) {
      printf("You rolled: %d\n", score2);
      return false; }
    if(score2 == score1) {
      printf("You rolled: %d\n", score2);
      return true; }
    else printf("You rolled: %d\n", score2);
    }
}
</code>```

Title: Debugging craps game simulation in C

Body:
Before scoffing at my erroneous code let me briefly inform you what I am trying to accomplish, and where I am going wrong.

Craps is a game played with 2 dice. If you roll 7 or 11 on the first roll you win. If you roll 2, 3 or 12 on the first roll you lose. Any other roll is called the "point" and the game continues. Now the player wins if on any subsequent roll the player rolls "point" again. However if the player rolls a 7 before rolling the "point" then the player loses. Any other roll (aside from "point" or 7) is ignored and we continue rolling until we hit "point" or 7.

In my simulation the roll_dice function should generate two random numbers between 1 and 6 and add them. The play_game function should play one craps game and returns true if the player wins and false if the player loses. It is also responsible for displaying messages showing the results of the player's dice rolls. We keep track of the numbers of wins and losses in main.

The problem in my code happens when the roll_dice function returns a number that is not: 7, 11 or 2, 3, 12. I.e. When it rolls a "point". When it rolls a "point" then the subsequent roll is also always the "point" and the game finishes with a win. I'm looking at the last for loop in play_game and I suspect the error is there but I don't know why it's wrong. For some reason the value of the score2 variable is always the "point" (if score1 is a "point") and I don't know why this is the case. Surely by invoking roll_dice a second time score2 should sometimes not be equal to score1?

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>

int roll_dice(void);
bool play_game(void);

int main(void)
{
  int wins = 0, losses = 0;

  for(;;) {
    if(play_game())
    {
      printf("You win!\n");
      wins++;
    }
    else
    {
      printf("You lose!\n");
      losses++;
    }
    char x;
    printf("\nPlay again? ");
    scanf("%c", &x);
    getchar();      //absorbs the "ENTER" button once y,Y,n or N has been typed

    if(x == 'y' || x == 'Y')
    continue;
    if(x == 'n' || x == 'N')
    {
       printf("Wins: %d Losses: %d\n", wins, losses);
       break;
    }
   }

  return 0;
}

int roll_dice(void)
{
  int die1, die2;
  srand((unsigned) time(NULL));

  die1 = 1 + rand() % 6;
  die2 = 1 + rand() % 6;

  return die1 + die2;
}

bool play_game(void)
{
  int score1 = roll_dice();

  if(score1 == 7 || score1 == 11)
  {
    printf("You rolled: %d\n", score1);
    return true;
  }
  if(score1 == 2 || score1 == 3 || score1 == 12)
   {
     printf("You rolled: %d\n", score1);
     return false;
   }

  else
  {
    printf("You rolled %d\nYour point is %d\n", score1, score1);
  }

  for(;;){
    int score2 = roll_dice();
    if(score2 == 7) {
      printf("You rolled: %d\n", score2);
      return false; }
    if(score2 == score1) {
      printf("You rolled: %d\n", score2);
      return true; }
    else printf("You rolled: %d\n", score2);
    }
}


问:
Exporting a list of objects to a text file without including __str__ method formatting
I'm trying to get my program to export the contents of a list to a text file. I've managed to get the writing to the file part working, however it exports it to the text file with the formatting from my str method. Is there a way to export the data to the file without including the str method's formatting?

The end result I'm aiming for is to have the students list start out as an empty list and then have the program load the data from the text file to populate the list when required.

The list I want to export:

```<code>students = [Student('First 1', 'Last 1', 20, '5615641564', 'zip code 1', "additional info 1"), Student(
        'First 2', 'Last 2', 37, '5641561616', 'zip 2', "additional info 2"), Student('First 3', 'Last 3', 15, '5616516165', 'zip code 3', "symptoms set 3")]
</code>```

The str method causing the issue (part of the Student class):

```<code>def __str__(self):
     return f'{self.full_name():^20}|{self.__tutor:^20}|{self.__age:^5}|{self.__mobile:^15}|{self.__zipcode:^10}|{self.__additional:^30} '
</code>```

My current method writing the list to the file:

```<code>    def export_students(students):
        with open('students.txt', 'w+') as f:
            for items in students:
                f.write('%s\n' %items)
# close the file
        f.close()
</code>```

I tried using the write method and making it run as part of my main() function thinking it would export it without the formatting from the str method, it didn't work and the program still outputted it with the formatting

Body:
I'm trying to get my program to export the contents of a list to a text file. I've managed to get the writing to the file part working, however it exports it to the text file with the formatting from my str method. Is there a way to export the data to the file without including the str method's formatting?

The end result I'm aiming for is to have the students list start out as an empty list and then have the program load the data from the text file to populate the list when required.

The list I want to export:

students = [Student('First 1', 'Last 1', 20, '5615641564', 'zip code 1', "additional info 1"), Student(
        'First 2', 'Last 2', 37, '5641561616', 'zip 2', "additional info 2"), Student('First 3', 'Last 3', 15, '5616516165', 'zip code 3', "symptoms set 3")]

The str method causing the issue (part of the Student class):

def __str__(self):
     return f'{self.full_name():^20}|{self.__tutor:^20}|{self.__age:^5}|{self.__mobile:^15}|{self.__zipcode:^10}|{self.__additional:^30} '

My current method writing the list to the file:

    def export_students(students):
        with open('students.txt', 'w+') as f:
            for items in students:
                f.write('%s\n' %items)
# close the file
        f.close()

I tried using the write method and making it run as part of my main() function thinking it would export it without the formatting from the str method, it didn't work and the program still outputted it with the formatting


问:
How do I know which item is not synced
I'm using AWS Amplify DataStore to store data to the cloud. When the device is offline, DataStore will keep the data in local storage until it's online again.

This is working fine but I'd like to display an offline/to be synced icon next to the those items that are not pushed to the cloud yet.

DataStore.query only seems to give me the content based on the model defined, is there any metadata I can use to determine whether or not an item is saved to the cloud?

Thanks!

Title: How do I know which item is not synced


问:
How to cross-build a flutter app from Linux x64 host to Linux arm64
I am trying to compile from linux-x64 to linux-arm64. When I type flutter build linux --target-platform linux-arm64 I get this error: Cross-build from Linux x64 host to Linux arm64 target is not currently supported.

I need to know if I have to install something specific tool on my PC to do the compilation.

The uname -a of my pc is: Linux jaime-Inspiron-3537 5.4.0-124-generic #140~18.04.1-Ubuntu SMP Fri Aug 5 11:43:34 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

this is my flutter doctor -v

```<code>[✓] Flutter (Channel stable, 3.3.10, on Ubuntu 18.04.5 LTS 5.4.0-124-generic, locale es_CU)
    • Flutter version 3.3.10 on channel stable at /home/jaime/snap/flutter/common/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 135454af32 (hace 3 semanas), 2022-12-15 07:36:55 -0800
    • Engine revision 3316dd8728
    • Dart version 2.18.6
    • DevTools version 2.15.0

[✗] Android toolchain - develop for Android devices
    ✗ Unable to locate Android SDK.
      Install Android Studio from: https://developer.android.com/studio/index.html
      On first launch it will assist you in installing the Android SDK components.
      (or visit https://flutter.dev/docs/get-started/install/linux#android-setup for detailed instructions).
      If the Android SDK has been installed to a custom location, please use
      `flutter config --android-sdk` to update to that location.

[✓] Chrome - develop for the web
    • Chrome at google-chrome

[✓] Linux toolchain - develop for Linux desktop
    • clang version 10.0.0-4ubuntu1
    • cmake version 3.16.3
    • ninja version 1.10.0
    • pkg-config version 0.29.1

[!] Android Studio (not installed)
    • Android Studio not found; download from https://developer.android.com/studio/index.html
      (or visit https://flutter.dev/docs/get-started/install/linux#android-setup for detailed instructions).

[✓] VS Code (version 1.67.1)
    • VS Code at /usr/share/code
    • Flutter extension version 3.56.0

[✓] Connected device (2 available)
    • Linux (desktop) • linux  • linux-x64      • Ubuntu 18.04.5 LTS 5.4.0-124-generic
    • Chrome (web)    • chrome • web-javascript • Google Chrome 93.0.4577.63

[✓] HTTP Host Availability
    • All required HTTP hosts are available

! Doctor found issues in 2 categories.

</code>```

Body:
I am trying to compile from linux-x64 to linux-arm64. When I type flutter build linux --target-platform linux-arm64 I get this error: Cross-build from Linux x64 host to Linux arm64 target is not currently supported.

I need to know if I have to install something specific tool on my PC to do the compilation.

The uname -a of my pc is: Linux jaime-Inspiron-3537 5.4.0-124-generic #140~18.04.1-Ubuntu SMP Fri Aug 5 11:43:34 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

this is my flutter doctor -v

[✓] Flutter (Channel stable, 3.3.10, on Ubuntu 18.04.5 LTS 5.4.0-124-generic, locale es_CU)
    • Flutter version 3.3.10 on channel stable at /home/jaime/snap/flutter/common/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 135454af32 (hace 3 semanas), 2022-12-15 07:36:55 -0800
    • Engine revision 3316dd8728
    • Dart version 2.18.6
    • DevTools version 2.15.0

[✗] Android toolchain - develop for Android devices
    ✗ Unable to locate Android SDK.
      Install Android Studio from: https://developer.android.com/studio/index.html
      On first launch it will assist you in installing the Android SDK components.
      (or visit https://flutter.dev/docs/get-started/install/linux#android-setup for detailed instructions).
      If the Android SDK has been installed to a custom location, please use
      `flutter config --android-sdk` to update to that location.

[✓] Chrome - develop for the web
    • Chrome at google-chrome

[✓] Linux toolchain - develop for Linux desktop
    • clang version 10.0.0-4ubuntu1
    • cmake version 3.16.3
    • ninja version 1.10.0
    • pkg-config version 0.29.1

[!] Android Studio (not installed)
    • Android Studio not found; download from https://developer.android.com/studio/index.html
      (or visit https://flutter.dev/docs/get-started/install/linux#android-setup for detailed instructions).

[✓] VS Code (version 1.67.1)
    • VS Code at /usr/share/code
    • Flutter extension version 3.56.0

[✓] Connected device (2 available)
    • Linux (desktop) • linux  • linux-x64      • Ubuntu 18.04.5 LTS 5.4.0-124-generic
    • Chrome (web)    • chrome • web-javascript • Google Chrome 93.0.4577.63

[✓] HTTP Host Availability
    • All required HTTP hosts are available

! Doctor found issues in 2 categories.


问:
speech recognition doesn't work in chrome on iOS
I am using standard JS speech recognition in my NextJS 13 app, and it works well in Chrome web browser and on Android. But it doesn't work when I try to run it in Chrome on iOS, but in Safari it works well. What can be the issue? I checked Chrome settings and access to mic is allowed there.

This is the speech recognition method that I use:

```<code>// new speech recognition object
var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition;
var recognition = new SpeechRecognition();

// This runs when the speech recognition service starts
recognition.onstart = function() {
    console.log("We are listening. Try speaking into the microphone.");
};

recognition.onspeechend = function() {
    // when user is done speaking
    recognition.stop();
}

// This runs when the speech recognition service returns result
recognition.onresult = function(event) {
    var transcript = event.results[0][0].transcript;
};

// start recognition
recognition.start();
</code>```

Body:
I am using standard JS speech recognition in my NextJS 13 app, and it works well in Chrome web browser and on Android. But it doesn't work when I try to run it in Chrome on iOS, but in Safari it works well. What can be the issue? I checked Chrome settings and access to mic is allowed there.

This is the speech recognition method that I use:

// new speech recognition object
var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition;
var recognition = new SpeechRecognition();

// This runs when the speech recognition service starts
recognition.onstart = function() {
    console.log("We are listening. Try speaking into the microphone.");
};

recognition.onspeechend = function() {
    // when user is done speaking
    recognition.stop();
}

// This runs when the speech recognition service returns result
recognition.onresult = function(event) {
    var transcript = event.results[0][0].transcript;
};

// start recognition
recognition.start();


问:
Difference between types of HTN planners (total, partial, unordered)
In the context of HTN (hierarchical task network) planners, what is the difference between Total order, Partial order, and Unordered planning?</p>


问:
Do I need to reinstall nodule_modules for backend if I'm also reinstalling nodule_modules for frontend?
Basically, do they need to match up? Having some Vue issues (I might actually post a question about that later) but I just want to know if I'm supposed to be editing things in backend as well as frontend. Thanks</p>


问:
How to tick-level backtest the spot grid trading strategy?
Is there a Python library with which I could tick-level backtest the famous Spot Grid Trading crypto strategy? I already did the tick data download part from data.binance.vision, although in my attempt I have used backtesting.py that seems to not be suitable for tick-level backtests, as discussed here. The grid strategy is pretty straightforward, so I assume it should be fairly easy to backtest on tick-level. I assume there are others who have already achieved this, I just can't find it, so that's why I'm asking the question.

The strategy is described here and I also found a few open source references on GitHub:

https://github.com/xzmeng/crypto-grid-backtest/blob/master/grid/backtest.py

https://github.com/webclinic017/aibitgo/blob/master/strategy/GridStrategyPercent.py

https://github.com/ulbdir/trading_bot/blob/main/GridStrategy.py

What I have so far

from backtesting import Backtest
from grid.grid import GridStrategy
from tick_data.data import Kind, load_data

if __name__ == "__main__":
    # 1s interval pickle
    df = load_data(symbol="ETHUSDT", start="2022-12-16", end="2022-12-16", kind=Kind.SPOT, tz="UTC")

    df = df.resample("1s").first().dropna()
    print(f'{df}')

    # Backtest
    bt = Backtest(df, GridStrategy, cash=10_000, commission=.001, exclusive_orders=True)
    stats = bt.run()
    bt.plot()
```
<pre class="lang-py prettyprint-override"><code>import numpy as np
import pandas as pd

from enum import Enum
from backtesting import Strategy

class GridType(Enum):
    ARITHMETIC = 1
    GEOMETRIC = 2

class GridStrategy(Strategy):
    lower_limit = 2000
    upper_limit = 10000
    grid_count = 4
    grid_type = GridType.ARITHMETIC
    grids = []

    current_position = None

    def init(self):
        self.grids = self.get_grids(self.lower_limit, self.upper_limit, self.grid_count, self.grid_type)

        print(f'{self.grids}')

    def next(self):
        pass

    @staticmethod
    def get_grids(lower_limit, upper_limit, grid_count, grid_type=GridType.ARITHMETIC):
        if grid_type == GridType.ARITHMETIC:
            grids = np.linspace(lower_limit, upper_limit, grid_count + 1)
        elif grid_type == GridType.GEOMETRIC:
            grids = np.geomspace(lower_limit, upper_limit, grid_count + 1)
        else:
            print("not right range type")
        return grids
</code>```

import io
import logging
from concurrent.futures import ThreadPoolExecutor
from datetime import date
from enum import Enum
from pathlib import Path
from typing import Optional, Union
from zipfile import ZipFile
from datetime import datetime

import pandas as pd
import httpx
from pandas import DataFrame

DATA_DIR = Path.cwd().joinpath("data")

def create_logger():
    logger_ = logging.getLogger(__name__)
    logger_.setLevel(logging.INFO)
    formatter = logging.Formatter(
        "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    )
    handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    logger_.addHandler(handler)
    return logger_

logger = create_logger()

class Kind(Enum):
    SPOT = "spot"
    FUTURES_UM = "futures/um"
    FUTURES_CM = "futures/cm"

class DataLoader:
    def __init__(
            self,
            kind: Kind,
            symbol: str,
            start: Union[date, str],
            end: Union[date, str],
            tz: str = None,
    ) -> None:
        self.kind = kind
        self.symbol = symbol
        self.start = start
        self.end = end
        self.tz = tz

    def load_data(self) -> pd.DataFrame:
        with ThreadPoolExecutor(max_workers=20) as executor:
            dfs = list(
                executor.map(self.load_daily_data, pd.date_range(self.start, self.end))
            )
        df = pd.concat(dfs)
        if self.tz:
            df.index = df.index.tz_localize("utc").tz_convert(self.tz)
        return df

    def load_daily_data(self, dt: date) -> Optional[pd.DataFrame]:
        try:
            return self.load_local_daily_data(dt)
        except FileNotFoundError:
            return self.download_daily_data(dt)

    def load_local_daily_data(self, dt: date) -> pd.DataFrame:
        pickle_path = self.get_daily_pickle_path(dt)
        return pd.read_pickle(pickle_path)

    def download_daily_data(self, dt: date) -> Optional[pd.DataFrame]:
        logger.info(f'Downloading {self.symbol} {datetime.strftime(dt, "%Y-%m-%d")}')
        url = f'https://data.binance.vision/data/{self.kind.value}/daily/trades/{self.symbol}/' \
              f'{self.symbol}-trades-{datetime.strftime(dt, "%Y-%m-%d")}.zip'

        resp = httpx.get(url)
        resp.raise_for_status()

        with ZipFile(io.BytesIO(resp.content)) as zf:
            with zf.open(zf.namelist()[0]) as f:
                df = pd.read_csv(f, usecols=[1, 4], names=["price", "datetime"])

        df["datetime"] = pd.to_datetime(df.datetime, unit="ms")
        df.set_index("datetime", inplace=True)
        # df = df.resample("1s").first().dropna()

        # df.price.resample("1s").agg({
        #     "Open": "first",
        #     "High": "max",
        #     "Low": "min",
        #     "Close": "last"
        # })

        pkl_path = self.get_daily_pickle_path(dt)
        Path(pkl_path).parent.mkdir(parents=True, exist_ok=True)
        df.to_pickle(pkl_path)

        return df

    def get_daily_pickle_path(self, dt: date) -> Path:
        return DATA_DIR.joinpath(self.kind.value, f"{self.symbol}-{dt.year}-{dt.month}-{dt.day}.pkl")

def load_data(
        symbol: str,
        start: Union[date, str],
        end: Union[date, str] = date.today(),
        kind: Union[Kind, str] = Kind.SPOT,
        tz: str = "UTC",
) -> DataFrame:
    if isinstance(kind, str):
        kind = {"spot": Kind.SPOT, "cm": Kind.FUTURES_CM, "um": Kind.FUTURES_UM}[kind]
    return DataLoader(kind, symbol, start, end, tz).load_data()
```

Body:
Is there a Python library with which I could tick-level backtest the famous Spot Grid Trading crypto strategy? I already did the tick data download part from data.binance.vision, although in my attempt I have used backtesting.py that seems to not be suitable for tick-level backtests, as discussed here. The grid strategy is pretty straightforward, so I assume it should be fairly easy to backtest on tick-level. I assume there are others who have already achieved this, I just can't find it, so that's why I'm asking the question.

The strategy is described here and I also found a few open source references on GitHub:

https://github.com/xzmeng/crypto-grid-backtest/blob/master/grid/backtest.py

https://github.com/webclinic017/aibitgo/blob/master/strategy/GridStrategyPercent.py

https://github.com/ulbdir/trading_bot/blob/main/GridStrategy.py

What I have so far

from backtesting import Backtest
from grid.grid import GridStrategy
from tick_data.data import Kind, load_data

if __name__ == "__main__":
    # 1s interval pickle
    df = load_data(symbol="ETHUSDT", start="2022-12-16", end="2022-12-16", kind=Kind.SPOT, tz="UTC")

    df = df.resample("1s").first().dropna()
    print(f'{df}')

    # Backtest
    bt = Backtest(df, GridStrategy, cash=10_000, commission=.001, exclusive_orders=True)
    stats = bt.run()
    bt.plot()

import numpy as np
import pandas as pd

from enum import Enum
from backtesting import Strategy

class GridType(Enum):
    ARITHMETIC = 1
    GEOMETRIC = 2

class GridStrategy(Strategy):
    lower_limit = 2000
    upper_limit = 10000
    grid_count = 4
    grid_type = GridType.ARITHMETIC
    grids = []

    current_position = None

    def init(self):
        self.grids = self.get_grids(self.lower_limit, self.upper_limit, self.grid_count, self.grid_type)

        print(f'{self.grids}')

    def next(self):
        pass

    @staticmethod
    def get_grids(lower_limit, upper_limit, grid_count, grid_type=GridType.ARITHMETIC):
        if grid_type == GridType.ARITHMETIC:
            grids = np.linspace(lower_limit, upper_limit, grid_count + 1)
        elif grid_type == GridType.GEOMETRIC:
            grids = np.geomspace(lower_limit, upper_limit, grid_count + 1)
        else:
            print("not right range type")
        return grids

import io
import logging
from concurrent.futures import ThreadPoolExecutor
from datetime import date
from enum import Enum
from pathlib import Path
from typing import Optional, Union
from zipfile import ZipFile
from datetime import datetime

import pandas as pd
import httpx
from pandas import DataFrame

DATA_DIR = Path.cwd().joinpath("data")

def create_logger():
    logger_ = logging.getLogger(__name__)
    logger_.setLevel(logging.INFO)
    formatter = logging.Formatter(
        "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    )
    handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    logger_.addHandler(handler)
    return logger_

logger = create_logger()

class Kind(Enum):
    SPOT = "spot"
    FUTURES_UM = "futures/um"
    FUTURES_CM = "futures/cm"

class DataLoader:
    def __init__(
            self,
            kind: Kind,
            symbol: str,
            start: Union[date, str],
            end: Union[date, str],
            tz: str = None,
    ) -> None:
        self.kind = kind
        self.symbol = symbol
        self.start = start
        self.end = end
        self.tz = tz

    def load_data(self) -> pd.DataFrame:
        with ThreadPoolExecutor(max_workers=20) as executor:
            dfs = list(
                executor.map(self.load_daily_data, pd.date_range(self.start, self.end))
            )
        df = pd.concat(dfs)
        if self.tz:
            df.index = df.index.tz_localize("utc").tz_convert(self.tz)
        return df

    def load_daily_data(self, dt: date) -> Optional[pd.DataFrame]:
        try:
            return self.load_local_daily_data(dt)
        except FileNotFoundError:
            return self.download_daily_data(dt)

    def load_local_daily_data(self, dt: date) -> pd.DataFrame:
        pickle_path = self.get_daily_pickle_path(dt)
        return pd.read_pickle(pickle_path)

    def download_daily_data(self, dt: date) -> Optional[pd.DataFrame]:
        logger.info(f'Downloading {self.symbol} {datetime.strftime(dt, "%Y-%m-%d")}')
        url = f'https://data.binance.vision/data/{self.kind.value}/daily/trades/{self.symbol}/' \
              f'{self.symbol}-trades-{datetime.strftime(dt, "%Y-%m-%d")}.zip'

        resp = httpx.get(url)
        resp.raise_for_status()

        with ZipFile(io.BytesIO(resp.content)) as zf:
            with zf.open(zf.namelist()[0]) as f:
                df = pd.read_csv(f, usecols=[1, 4], names=["price", "datetime"])

        df["datetime"] = pd.to_datetime(df.datetime, unit="ms")
        df.set_index("datetime", inplace=True)
        # df = df.resample("1s").first().dropna()

        # df.price.resample("1s").agg({
        #     "Open": "first",
        #     "High": "max",
        #     "Low": "min",
        #     "Close": "last"
        # })

        pkl_path = self.get_daily_pickle_path(dt)
        Path(pkl_path).parent.mkdir(parents=True, exist_ok=True)
        df.to_pickle(pkl_path)

        return df

    def get_daily_pickle_path(self, dt: date) -> Path:
        return DATA_DIR.joinpath(self.kind.value, f"{self.symbol}-{dt.year}-{dt.month}-{dt.day}.pkl")

def load_data(
        symbol: str,
        start: Union[date, str],
        end: Union[date, str] = date.today(),
        kind: Union[Kind, str] = Kind.SPOT,
        tz: str = "UTC",
) -> DataFrame:
    if isinstance(kind, str):
        kind = {"spot": Kind.SPOT, "cm": Kind.FUTURES_CM, "um": Kind.FUTURES_UM}[kind]
    return DataLoader(kind, symbol, start, end, tz).load_data()