问:
Can't access the apis from inside the monogdb connect function in vercel
I am working on an express server, and using mongodb as database. The server is working on local. I have deployed the server to vercel with git repository. Heres the deployed server, https://annoor-server.vercel.app/ when i hit the url it serves the response form the "/" api, but when i hit https://annoor-server.vercel.app/get-product (which api is inside the mongodb connect function) it says Cannot GET /get-product.

Here the repository https://github.com/shahadat2772/annoor-server

vercel.json

```<code>{
  "version": 2,
  "builds": [
    {
      "src": "./index.js",
      "use": "@vercel/node"
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "/"
    }
  ]
}

</code>```

index.js

```<code>const express = require("express");
const app = express();
const {
  MongoClient,
  ServerApiVersion,
  TopologyDescriptionChangedEvent,
  ObjectId,
} = require("mongodb");
const PORT = 5000 || process.env.PORT;
const cors = require("cors");
require("dotenv").config();
const jwt = require("jsonwebtoken");
const verify = require("jsonwebtoken/verify");
const multer = require("multer");

// All Middleware
app.use(express.json());
app.use(cors());

const path = require("path");
app.use("/assets", express.static(path.join(__dirname, "assets")));

const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.trnyuya.mongodb.net/?retryWrites=true&w=majority`;
const client = new MongoClient(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  serverApi: ServerApiVersion.v1,
});

// Img upload middleware
const imageFilter = (req, file, cb) => {
  // filter image file
  //check file type is image
  if (file.mimetype.includes("image/png")) {
    // if image file
    cb(null, true);
  } else if (file.mimetype.includes("image/jpeg")) {
    // if image file
    cb(null, true);
  } else if (file.mimetype.includes("image/jpg")) {
    // if image file
    cb(null, true);
  } else {
    cb("Please upload only jpg, png or jpeg image.", false);
  }
};

var storage = multer.diskStorage({
  // multer storage
  destination: (req, file, cb) => {
    cb(null, "./assets" + "/"); // upload file to backend/
  },
  filename: (req, file, cb) => {
    // rename file
    const ext = file.mimetype.split("/")[1];
    const filename = Date.now() + "." + ext;
    req.filename = filename;
    cb(null, filename);
  },
});
var uploadFile = multer({ storage: storage, fileFilter: imageFilter });

// TO VERIFY TOKEN
function verifyJWT(req, res, next) {
  const authHeader = req.headers?.authorization;
  if (!authHeader) {
    return res.status(401).send({ message: "unauthorized", success: false });
  }
  const accessToken = authHeader.split(" ")[1];
  verify(accessToken, process.env.JWT_SECRET_TOKEN, (err, decoded) => {
    if (err) {
      return res
        .status(403)
        .send({ message: "forbidden access", success: false });
    }
    if (decoded.uid !== req.headers.uid) {
      return res
        .status(403)
        .send({ message: "forbidden access", success: false });
    }
    req.decoded = decoded;
    next();
  });
}

app.get("/", async (req, res) => {
  res.send("Hello there!");
});

async function run() {
  try {
    // Connecting with mongodb
    await client.connect();

    // Collections
    const userCollection = client
      .db("annoor-business")
      .collection("users-collection");

    const productCollection = client
      .db("annoor-business")
      .collection("product-collection");

    app.get("/get-product", async (req, res) => {
      try {
        // const category = req.headers?.category;
        // const filter = { category: category };
        const result = await productCollection.find({}).toArray();
        res.status(200).send({
          data: result,
          success: true,
          message: "Got products data.",
        });
      } catch (error) {
        res.status(500).send({
          message: "Internal server error.",
          success: false,
        });
      }
    });

    // app.get("/", async (req, res) => {
    //   res.send("Hello there!");
    // });

    // Verify admin
    async function verifyAdmin(req, res, next) {
      const uid = req?.decoded?.uid;
      const filter = { uid };
      const user = await userCollection.findOne(filter);
      const role = user?.role;
      if (role === "admin") {
        next();
      } else {
        return res
          .status(403)
          .send({ message: "forbidden access", success: false });
      }
    }

    // Get token/user creation
    app.put("/token", async (req, res) => {
      try {
        const userInfo = req.body;
        const doc = {
          $set: userInfo,
        };
        const uid = userInfo.uid;
        const option = {
          upsert: true,
        };
        const result = await userCollection.updateOne({ uid }, doc, option);
        const accessToken = jwt.sign({ uid }, process.env.JWT_SECRET_TOKEN, {
          expiresIn: "1d",
        });
        res
          .status(200)
          .send({ data: accessToken, success: true, message: "Got token" });
      } catch (error) {
        res
          .status(500)
          .send({ message: "Internal server error.", success: false });
      }
    });

    // Get user info
    app.get("/user", verifyJWT, async (req, res) => {
      try {
        const uid = req.headers.uid;
        const filter = { uid };
        const user = await userCollection.findOne(filter);
        res
          .status(200)
          .send({ data: user, success: true, message: "Got user info" });
      } catch (error) {
        res
          .status(500)
          .send({ success: false, message: "Internal server error." });
      }
    });

    // Update user profile
    app.post("/update-user-info", verifyJWT, async (req, res) => {
      try {
        const uid = req.headers.uid;
        const updatedInfo = req.body;
        const filter = { uid };
        const option = {
          upsert: true,
        };
        const doc = {
          $set: updatedInfo,
        };
        const result = await userCollection.updateOne(filter, doc, option);
        res.status(200).send({ message: "Profile updated.", success: true });
      } catch (error) {
        res
          .status(500)
          .send({ message: "Internal server error.", success: false });
      }
    });

    // Get products by category
    app.get("/product", async (req, res) => {
      try {
        const category = req.headers?.category;
        const filter = { category: category };
        const result = await productCollection.find(filter).toArray();
        res.status(200).send({
          data: result,
          success: true,
          message: "Got products data.",
        });
      } catch (error) {
        res.status(500).send({
          message: "Internal server error.",
          success: false,
        });
      }
    });

    // Admin Routes

    // Add Product
    app.post(
      "/product",
      verifyJWT,
      verifyAdmin,
      uploadFile.single("image"),
      async (req, res) => {
        try {
          let path = "http://localhost:5000/assets/" + req.filename;
          const product = req.body;

          const productInfo = {
            name: product.name,
            category: product.category,
            subtext: product.subtext,
            stock: product.stock,
            description: product.description,
            price: product.price,
            image: path,
          };
          const result = await productCollection.insertOne(productInfo);
          res.status(200).send({ message: "Product added.", success: true });
        } catch (error) {
          res
            .status(500)
            .send({ path, message: "Internal server error.", success: false });
        }
      }
    );

    // Edit Product
    app.post(
      "/edit-product",
      verifyJWT,
      verifyAdmin,
      uploadFile.single("image"),
      async (req, res) => {
        try {
          const filter = { _id: ObjectId(req.headers._id) };
          const product = req.body;
          let productInfo = {
            name: product.name,
            category: product.category,
            subtext: product.subtext,
            stock: product.stock,
            description: product.description,
            price: product.price,
          };

          if (req?.filename) {
            let path = "http://localhost:5000/assets/" + req.filename;
            productInfo = { ...productInfo, image: path };
          }

          const doc = {
            $set: productInfo,
          };

          const result = await productCollection.updateOne(filter, doc);
          res
            .status(200)
            .send({ message: "Updated the product.", success: true });
        } catch (error) {
          res
            .status(500)
            .send({ message: "Internal server error.", success: false });
        }
      }
    );

    // Get all products / search products
    app.get("/all-products", verifyJWT, verifyAdmin, async (req, res) => {
      try {
        const page = parseInt(req?.query?.page) - 1;
        const search = req?.query?.search;
        let products;
        let productCount;

        if (search !== "") {
          const query = { $text: { $search: search } };
          productCount = await productCollection.countDocuments(query);
          products = await productCollection
            .find(query)
            .skip(page * 15)
            .limit(15)
            .toArray();
        } else {
          productCount = await productCollection.estimatedDocumentCount();
          products = await productCollection
            .find({})
            .sort({ $natural: -1 })
            .skip(page * 15)
            .limit(15)
            .toArray();
        }

        res.status(200).send({
          success: true,
          message: "Got all products",
          data: products,
          productCount: productCount,
        });
      } catch (error) {
        res.status(500).send({
          success: false,
          message: "Internal server error.",
        });
      }
    });

    // Delete a product
    app.delete("/delete-product", verifyJWT, verifyAdmin, async (req, res) => {
      try {
        const filter = { _id: ObjectId(req.headers._id) };
        const result = await productCollection.deleteOne(filter);
        res.status(200).send({ success: true, message: "Product deleted." });
      } catch (error) {
        res
          .status(500)
          .send({ success: false, message: "Internal server error." });
      }
    });

    // Get product by id
    app.get("/single-product", verifyJWT, verifyAdmin, async (req, res) => {
      try {
        const filter = { _id: ObjectId(req.headers._id) };
        const result = await productCollection.findOne(filter);
        res
          .status(200)
          .send({ success: true, message: "Got single product", data: result });
      } catch (error) {
        res
          .status(500)
          .send({ success: false, message: "Internal server error." });
      }
    });
  } finally {
    // await client.close();
  }
}

run().catch(console.dir);

app.listen(PORT, () => {
  console.log("Responding to port", PORT);
});

// Export the Express API
module.exports = app;

</code>```

Body:
I am working on an express server, and using mongodb as database. The server is working on local. I have deployed the server to vercel with git repository. Heres the deployed server, https://annoor-server.vercel.app/ when i hit the url it serves the response form the "/" api, but when i hit https://annoor-server.vercel.app/get-product (which api is inside the mongodb connect function) it says Cannot GET /get-product.

Here the repository https://github.com/shahadat2772/annoor-server

vercel.json

{
  "version": 2,
  "builds": [
    {
      "src": "./index.js",
      "use": "@vercel/node"
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "/"
    }
  ]
}

index.js

const express = require("express");
const app = express();
const {
  MongoClient,
  ServerApiVersion,
  TopologyDescriptionChangedEvent,
  ObjectId,
} = require("mongodb");
const PORT = 5000 || process.env.PORT;
const cors = require("cors");
require("dotenv").config();
const jwt = require("jsonwebtoken");
const verify = require("jsonwebtoken/verify");
const multer = require("multer");

// All Middleware
app.use(express.json());
app.use(cors());

const path = require("path");
app.use("/assets", express.static(path.join(__dirname, "assets")));

const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.trnyuya.mongodb.net/?retryWrites=true&w=majority`;
const client = new MongoClient(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  serverApi: ServerApiVersion.v1,
});

// Img upload middleware
const imageFilter = (req, file, cb) => {
  // filter image file
  //check file type is image
  if (file.mimetype.includes("image/png")) {
    // if image file
    cb(null, true);
  } else if (file.mimetype.includes("image/jpeg")) {
    // if image file
    cb(null, true);
  } else if (file.mimetype.includes("image/jpg")) {
    // if image file
    cb(null, true);
  } else {
    cb("Please upload only jpg, png or jpeg image.", false);
  }
};

var storage = multer.diskStorage({
  // multer storage
  destination: (req, file, cb) => {
    cb(null, "./assets" + "/"); // upload file to backend/
  },
  filename: (req, file, cb) => {
    // rename file
    const ext = file.mimetype.split("/")[1];
    const filename = Date.now() + "." + ext;
    req.filename = filename;
    cb(null, filename);
  },
});
var uploadFile = multer({ storage: storage, fileFilter: imageFilter });

// TO VERIFY TOKEN
function verifyJWT(req, res, next) {
  const authHeader = req.headers?.authorization;
  if (!authHeader) {
    return res.status(401).send({ message: "unauthorized", success: false });
  }
  const accessToken = authHeader.split(" ")[1];
  verify(accessToken, process.env.JWT_SECRET_TOKEN, (err, decoded) => {
    if (err) {
      return res
        .status(403)
        .send({ message: "forbidden access", success: false });
    }
    if (decoded.uid !== req.headers.uid) {
      return res
        .status(403)
        .send({ message: "forbidden access", success: false });
    }
    req.decoded = decoded;
    next();
  });
}

app.get("/", async (req, res) => {
  res.send("Hello there!");
});

async function run() {
  try {
    // Connecting with mongodb
    await client.connect();

    // Collections
    const userCollection = client
      .db("annoor-business")
      .collection("users-collection");

    const productCollection = client
      .db("annoor-business")
      .collection("product-collection");

    app.get("/get-product", async (req, res) => {
      try {
        // const category = req.headers?.category;
        // const filter = { category: category };
        const result = await productCollection.find({}).toArray();
        res.status(200).send({
          data: result,
          success: true,
          message: "Got products data.",
        });
      } catch (error) {
        res.status(500).send({
          message: "Internal server error.",
          success: false,
        });
      }
    });

    // app.get("/", async (req, res) => {
    //   res.send("Hello there!");
    // });

    // Verify admin
    async function verifyAdmin(req, res, next) {
      const uid = req?.decoded?.uid;
      const filter = { uid };
      const user = await userCollection.findOne(filter);
      const role = user?.role;
      if (role === "admin") {
        next();
      } else {
        return res
          .status(403)
          .send({ message: "forbidden access", success: false });
      }
    }

    // Get token/user creation
    app.put("/token", async (req, res) => {
      try {
        const userInfo = req.body;
        const doc = {
          $set: userInfo,
        };
        const uid = userInfo.uid;
        const option = {
          upsert: true,
        };
        const result = await userCollection.updateOne({ uid }, doc, option);
        const accessToken = jwt.sign({ uid }, process.env.JWT_SECRET_TOKEN, {
          expiresIn: "1d",
        });
        res
          .status(200)
          .send({ data: accessToken, success: true, message: "Got token" });
      } catch (error) {
        res
          .status(500)
          .send({ message: "Internal server error.", success: false });
      }
    });

    // Get user info
    app.get("/user", verifyJWT, async (req, res) => {
      try {
        const uid = req.headers.uid;
        const filter = { uid };
        const user = await userCollection.findOne(filter);
        res
          .status(200)
          .send({ data: user, success: true, message: "Got user info" });
      } catch (error) {
        res
          .status(500)
          .send({ success: false, message: "Internal server error." });
      }
    });

    // Update user profile
    app.post("/update-user-info", verifyJWT, async (req, res) => {
      try {
        const uid = req.headers.uid;
        const updatedInfo = req.body;
        const filter = { uid };
        const option = {
          upsert: true,
        };
        const doc = {
          $set: updatedInfo,
        };
        const result = await userCollection.updateOne(filter, doc, option);
        res.status(200).send({ message: "Profile updated.", success: true });
      } catch (error) {
        res
          .status(500)
          .send({ message: "Internal server error.", success: false });
      }
    });

    // Get products by category
    app.get("/product", async (req, res) => {
      try {
        const category = req.headers?.category;
        const filter = { category: category };
        const result = await productCollection.find(filter).toArray();
        res.status(200).send({
          data: result,
          success: true,
          message: "Got products data.",
        });
      } catch (error) {
        res.status(500).send({
          message: "Internal server error.",
          success: false,
        });
      }
    });

    // Admin Routes

    // Add Product
    app.post(
      "/product",
      verifyJWT,
      verifyAdmin,
      uploadFile.single("image"),
      async (req, res) => {
        try {
          let path = "http://localhost:5000/assets/" + req.filename;
          const product = req.body;

          const productInfo = {
            name: product.name,
            category: product.category,
            subtext: product.subtext,
            stock: product.stock,
            description: product.description,
            price: product.price,
            image: path,
          };
          const result = await productCollection.insertOne(productInfo);
          res.status(200).send({ message: "Product added.", success: true });
        } catch (error) {
          res
            .status(500)
            .send({ path, message: "Internal server error.", success: false });
        }
      }
    );

    // Edit Product
    app.post(
      "/edit-product",
      verifyJWT,
      verifyAdmin,
      uploadFile.single("image"),
      async (req, res) => {
        try {
          const filter = { _id: ObjectId(req.headers._id) };
          const product = req.body;
          let productInfo = {
            name: product.name,
            category: product.category,
            subtext: product.subtext,
            stock: product.stock,
            description: product.description,
            price: product.price,
          };

          if (req?.filename) {
            let path = "http://localhost:5000/assets/" + req.filename;
            productInfo = { ...productInfo, image: path };
          }

          const doc = {
            $set: productInfo,
          };

          const result = await productCollection.updateOne(filter, doc);
          res
            .status(200)
            .send({ message: "Updated the product.", success: true });
        } catch (error) {
          res
            .status(500)
            .send({ message: "Internal server error.", success: false });
        }
      }
    );

    // Get all products / search products
    app.get("/all-products", verifyJWT, verifyAdmin, async (req, res) => {
      try {
        const page = parseInt(req?.query?.page) - 1;
        const search = req?.query?.search;
        let products;
        let productCount;

        if (search !== "") {
          const query = { $text: { $search: search } };
          productCount = await productCollection.countDocuments(query);
          products = await productCollection
            .find(query)
            .skip(page * 15)
            .limit(15)
            .toArray();
        } else {
          productCount = await productCollection.estimatedDocumentCount();
          products = await productCollection
            .find({})
            .sort({ $natural: -1 })
            .skip(page * 15)
            .limit(15)
            .toArray();
        }

        res.status(200).send({
          success: true,
          message: "Got all products",
          data: products,
          productCount: productCount,
        });
      } catch (error) {
        res.status(500).send({
          success: false,
          message: "Internal server error.",
        });
      }
    });

    // Delete a product
    app.delete("/delete-product", verifyJWT, verifyAdmin, async (req, res) => {
      try {
        const filter = { _id: ObjectId(req.headers._id) };
        const result = await productCollection.deleteOne(filter);
        res.status(200).send({ success: true, message: "Product deleted." });
      } catch (error) {
        res
          .status(500)
          .send({ success: false, message: "Internal server error." });
      }
    });

    // Get product by id
    app.get("/single-product", verifyJWT, verifyAdmin, async (req, res) => {
      try {
        const filter = { _id: ObjectId(req.headers._id) };
        const result = await productCollection.findOne(filter);
        res
          .status(200)
          .send({ success: true, message: "Got single product", data: result });
      } catch (error) {
        res
          .status(500)
          .send({ success: false, message: "Internal server error." });
      }
    });
  } finally {
    // await client.close();
  }
}

run().catch(console.dir);

app.listen(PORT, () => {
  console.log("Responding to port", PORT);
});

// Export the Express API
module.exports = app;


来源: stackexchange

问:
Context in environment is not connected warning even if context is connected
When I move from a detail view of an object to its edit view , where I will edit the coredata object values, I keep getting  Context in environment is not connected warning

I have added the DataController in environment and also created a data class, can any one please suggest where is my issue

I keep getting this error in my @main struct

DataController class

```<code>@MainActor
class DataController: ObservableObject {
    static let shared = DataController()
    let container: NSPersistentContainer
    @Published var carSheet: [CarDetails] = []
    @Published var logInfo = false
    init(inMemory: Bool = false) {
        container = NSPersistentContainer(name: "CarData")
        if inMemory {
            container.persistentStoreDescriptions.first?.url = URL(fileURLWithPath: "/dev/null")
        }

        container.loadPersistentStores { descriptions, error in
            if let error = error {
                fatalError("failed to load data store \(error)")
            }

        }
    }

    func save() {
        if container.viewContext.hasChanges {
              try? container.viewContext.save()
        }
    }

    func delete(obj: NSManagedObject) {
        container.viewContext.delete(obj)
    }

    func getData() {
        let request = NSFetchRequest<CarDetails>(entityName: "CarDetails")

        do {
             carSheet = try container.viewContext.fetch(request)

        } catch {
            print("Error getting data. \(error.localizedDescription)")
        }
    }

    func simpleSuccess() {
        let generator = UINotificationFeedbackGenerator()
        generator.notificationOccurred(.success)
    }
}
</code>```

my @main

```<code>@main
struct appDemo: App {
    let userInfo = UserDefaults.standard.bool(forKey: "loginData")
    @StateObject var dataController =  DataController()

    var body: some Scene {

                WindowGroup {
                    if userInfo {
                        NavigationStack {
                            ContentView(dataContent: dataController)
                            .environment(\.managedObjectContext, dataController.container.viewContext)                        }

                    } else {

                        LogInView( dataLog: dataController)

                    }
                }

    }
}
</code>```

my Edit View which gives error when I fetch the data

```<code>struct EditViewData: View {
    @FetchRequest(entity: CarDetails.entity(), sortDescriptors: []) var myCars: FetchedResults<CarDetails>

    var body: some View {
        VStack {

        }

    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When I move from a detail view of an object to its edit view , where I will edit the coredata object values, I keep getting  Context in environment is not connected warning

I have added the DataController in environment and also created a data class, can any one please suggest where is my issue

I keep getting this error in my @main struct

DataController class

@MainActor
class DataController: ObservableObject {
    static let shared = DataController()
    let container: NSPersistentContainer
    @Published var carSheet: [CarDetails] = []
    @Published var logInfo = false
    init(inMemory: Bool = false) {
        container = NSPersistentContainer(name: "CarData")
        if inMemory {
            container.persistentStoreDescriptions.first?.url = URL(fileURLWithPath: "/dev/null")
        }

        container.loadPersistentStores { descriptions, error in
            if let error = error {
                fatalError("failed to load data store \(error)")
            }

        }
    }

    func save() {
        if container.viewContext.hasChanges {
              try? container.viewContext.save()
        }
    }

    func delete(obj: NSManagedObject) {
        container.viewContext.delete(obj)
    }

    func getData() {
        let request = NSFetchRequest<CarDetails>(entityName: "CarDetails")

        do {
             carSheet = try container.viewContext.fetch(request)

        } catch {
            print("Error getting data. \(error.localizedDescription)")
        }
    }

    func simpleSuccess() {
        let generator = UINotificationFeedbackGenerator()
        generator.notificationOccurred(.success)
    }
}

my @main

@main
struct appDemo: App {
    let userInfo = UserDefaults.standard.bool(forKey: "loginData")
    @StateObject var dataController =  DataController()

    var body: some Scene {

                WindowGroup {
                    if userInfo {
                        NavigationStack {
                            ContentView(dataContent: dataController)
                            .environment(\.managedObjectContext, dataController.container.viewContext)                        }

                    } else {

                        LogInView( dataLog: dataController)

                    }
                }

    }
}

my Edit View which gives error when I fetch the data

struct EditViewData: View {
    @FetchRequest(entity: CarDetails.entity(), sortDescriptors: []) var myCars: FetchedResults<CarDetails>

    var body: some View {
        VStack {

        }

    }
}


问:
replace a field for all user in firestore every 24 hour?
i work on a android game and i set lucky wheel and user can only spin it 5 time per day, after 24 hour it should be reset to 5 again ( for prevent cheating i want to do it with Firebase rule

so i want to make a rule in Firebase to change a "spin left" field for all user , every 24 hour (00:00 GMT should change field for all user)

would you please help me with that?

what i tried? i don't know how to make my own rules and i am in hurry unfortunately


问:
None attribute error while webscrapping using Beautiful Soup
enter image description here

Error while trying to do web scrapping

AttributeError                            Traceback (most recent call last)
<ipython-input-6-d288f07b930a> in <module>
     29
     30     for link in data_array_tcs:
---> 31         title_all = link.find("strong").text
     32         # news_all = link.find(class_="FL").text
     33         date_all = link.find(class_="PT3 a_10dgry").text

AttributeError: 'NoneType' object has no attribute 'text'
```

Trying to retrieve news using web scrapping from money-control site but receiving an none type attribute error

Body:
enter image description here

Error while trying to do web scrapping

AttributeError                            Traceback (most recent call last)
<ipython-input-6-d288f07b930a> in <module>
     29
     30     for link in data_array_tcs:
---> 31         title_all = link.find("strong").text
     32         # news_all = link.find(class_="FL").text
     33         date_all = link.find(class_="PT3 a_10dgry").text

AttributeError: 'NoneType' object has no attribute 'text'

Trying to retrieve news using web scrapping from money-control site but receiving an none type attribute error


问:
Unhandled Exception: FileSystemException: Cannot create file, path
I am trying to download a file(image|pdf|video) from firebase cloud storage.
I am using Dio package.
But i am getting this error.
Have a look.
I add all permissions as well.

`

```<code>Future<String> createFolderInDocDir(String folderName)async{

  final Directory _appDocDir = await getApplicationDocumentsDirectory();

  final Directory _appFolderDir = Directory('${_appDocDir.path}/$folderName/download.jpeg');

  if(await _appFolderDir.exists()){
    return _appFolderDir.path;
  }
  else{
    final Directory _newAppFolderDir =await _appFolderDir.create(recursive: true);
    return _newAppFolderDir.path;
  }
}

Future download(String url) async {
  Dio dio = Dio();
  String _destinationPath =await createFolderInDocDir("myResume");
  print("destination path => $_destinationPath");
  print("Url => $url");

  var response = await dio.download(url, _destinationPath);
  print("response status => $response");
  print("response data => ${response.data.toString()}");
}
</code>```

 E/flutter ( 9729): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: FileSystemException: Cannot create file, path = '/data/user/0/com.example.portfolio360/app_flutter/myResume/download.jpeg' (OS Error: Is a directory, errno = 21)
E/flutter ( 9729): #0      _File.throwIfError (dart:io/file_impl.dart:635:7)
E/flutter ( 9729): #1      _File.createSync (dart:io/file_impl.dart:273:5)
E/flutter ( 9729): #2      DioForNative.download (package:dio/src/entry/dio_for_native.dart:124:10)
E/flutter ( 9729):
E/flutter ( 9729): #3      FirebaseStorageController.download (package:portfolio360/Controllers/FirebaseStorageController.dart:117:20)
E/flutter ( 9729):
E/flutter ( 9729): `

Body:
I am trying to download a file(image|pdf|video) from firebase cloud storage.
I am using Dio package.
But i am getting this error.
Have a look.
I add all permissions as well.

`

Future<String> createFolderInDocDir(String folderName)async{

  final Directory _appDocDir = await getApplicationDocumentsDirectory();

  final Directory _appFolderDir = Directory('${_appDocDir.path}/$folderName/download.jpeg');

  if(await _appFolderDir.exists()){
    return _appFolderDir.path;
  }
  else{
    final Directory _newAppFolderDir =await _appFolderDir.create(recursive: true);
    return _newAppFolderDir.path;
  }
}

Future download(String url) async {
  Dio dio = Dio();
  String _destinationPath =await createFolderInDocDir("myResume");
  print("destination path => $_destinationPath");
  print("Url => $url");

  var response = await dio.download(url, _destinationPath);
  print("response status => $response");
  print("response data => ${response.data.toString()}");
}

 E/flutter ( 9729): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: FileSystemException: Cannot create file, path = '/data/user/0/com.example.portfolio360/app_flutter/myResume/download.jpeg' (OS Error: Is a directory, errno = 21)
E/flutter ( 9729): #0      _File.throwIfError (dart:io/file_impl.dart:635:7)
E/flutter ( 9729): #1      _File.createSync (dart:io/file_impl.dart:273:5)
E/flutter ( 9729): #2      DioForNative.download (package:dio/src/entry/dio_for_native.dart:124:10)
E/flutter ( 9729):
E/flutter ( 9729): #3      FirebaseStorageController.download (package:portfolio360/Controllers/FirebaseStorageController.dart:117:20)
E/flutter ( 9729):
E/flutter ( 9729): `


问:
How to get specification/architecture of SSD Mobilenet or any models
spec = model_spec.get('ssd-mobilenet-v2') What is the name that I should type here?</p>
```<code>KeyError                                  Traceback (most recent call last)
<ipython-input-23-b156688d28f7> in <module>
----> 1 spec = model_spec.get('ssd-mobilenet-v2')

/usr/local/lib/python3.8/dist-packages/tensorflow_examples/lite/model_maker/core/task/model_spec/__init__.py in get(spec_or_str, *args, **kwargs)
    103   """Gets model spec by name or instance, and init with args and kwarges."""
    104   if isinstance(spec_or_str, str):
--> 105     model_spec = MODEL_SPECS[spec_or_str]
    106   else:
    107     model_spec = spec_or_str

KeyError: 'ssd-mobilenet-v2'
</code>```

Body:
spec = model_spec.get('ssd-mobilenet-v2') What is the name that I should type here?

KeyError                                  Traceback (most recent call last)
<ipython-input-23-b156688d28f7> in <module>
----> 1 spec = model_spec.get('ssd-mobilenet-v2')

/usr/local/lib/python3.8/dist-packages/tensorflow_examples/lite/model_maker/core/task/model_spec/__init__.py in get(spec_or_str, *args, **kwargs)
    103   """Gets model spec by name or instance, and init with args and kwarges."""
    104   if isinstance(spec_or_str, str):
--> 105     model_spec = MODEL_SPECS[spec_or_str]
    106   else:
    107     model_spec = spec_or_str

KeyError: 'ssd-mobilenet-v2'


问:
What is the possible reason of why react native MapView is lagging?
My app have structure like this,

MapPage.js that contain expo-barcode-scanner wrapped with Modal and MapView.
DetailsPage.js that contain search result/products' details.

User can use the barcode scanner or TextInput(also in MapPage, not wrapped in Modal) to search product ID and the app will navigate to DetailsPage for result. If result is not found, app will automatically navigate.goBack() to MapPage. If result existed, will goto the result and stay in DetailsPage.

User can also navigate to DetailsPage by pressing marker callout on MapView.

Here is situation:

user press on marker callout(navigate to DetailsPage), then press back(navigate.goBack()) to MapPage : No lagging

user search by TextInput, then back to MapPage: No lagging whether search result exist or not

user search by Barcode, result not exist, automatically back to MapPage: not lagging

user search by Barcode, result existed, stay in DetailsPage, user manually press back: LAGGING

Below codes for your references

```<code>//MapPage
            <MapView
                style={{ width: '100%', height: '100%' }}
                provider={PROVIDER_GOOGLE}
                showsMyLocationButton={true}
                showsUserLocation={true}
                region={{
                    latitude: region.latitude,
                    longitude: region.longitude,
                    latitudeDelta: region.latitudeDelta,
                    longitudeDelta: region.longitudeDelta,
                }}>
                <MapMarker
                    markerLocation={markers}
                    countryCode={country.countryCode}
                />
            </MapView>
...
                    <TextInput
                        placeholder={
                            i18n.t('SearchId')
                        }
                        placeholderTextColor="white"
                        onSubmitEditing={() =>
                            handleBarCodeScanned({ data: textSearchData })
                        }
                        onChangeText={(text) => {
                            settextSearchData(text.toUpperCase());
                        }}
                    />
                    <Pressable onPress={() => setqrcodeModalVisi(true)}>
                        <Ionicons
                            name="qr-code-outline"
                            size={33}
                            color="white"
                        />
                    </Pressable>
...
            <Modal
                visible={qrcodeModalVisi}
                animationType="slide"
                onRequestClose={() => setqrcodeModalVisi(false)}
                transparent={true}>
                <View>
                    <Pressable onPress={() => setqrcodeModalVisi(false)}>
                        <Feather
                            name="x"
                            size={24}
                            color="white"
                        />
                    </Pressable>
                    {!hasPermission && (
                        <View>
                            <Text
                                style={{
                                    color: colors.text,
                                }}>
                                Camera access denied.
                            </Text>
                            <Pressable onPress={() => getBarCodeScannerPermissions()}>
                                <Text style={{ color: colors.secondary }}>
                                    Goto setting page
                                </Text>
                            </Pressable>
                        </View>
                    )}
                    {hasPermission && (
                        <View
                            style={{
                                flex: 1,
                                justifyContent: 'center',
                                alignItems: 'center',
                            }}>
                            <BarCodeScanner
                                onBarCodeScanned={
                                    scanned ? undefined : handleBarCodeScanned
                                }
                                style={{
                                    width: '100%',
                                    height: '80%',
                                }}
                            />
                        </View>
                    )}
                </View>
            </Modal>

</code>```
```<code>//MapMarker
        <View>
            {markerLocation.map((array) => (
                <Marker
                    key={array.title}
                    coordinate={{
                        latitude: array.latitude,
                        longitude: array.longitude,
                    }}
                    image={require('../../../assets/icons/map_marker.png')}
                    title={''}
                    description={''}
                    onCalloutPress={() => handleMapMarkerPress(array.regionCode)}>
                    <Callout>
                        <View
                            style={{
                                backgroundColor: 'white',
                                width: 180,
                                paddingVertical: 5,
                                alignItems: 'center',
                                justifyContent: 'center',
                            }}>
                            <Text
                                style={{
                                    width: '80%',
                                    textAlign: 'center',
                                    color: colors.secondary,
                                    fontWeight: 'bold',
                                }}>
                                {array.title}
                            </Text>
                            <View
                                style={{
                                    backgroundColor: colors.secondary,
                                    width: '80%',
                                    height: 25,
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    marginTop: 2,
                                    flexDirection: 'row',
                                    marginVertical: 5,
                                }}>
                                <Text style={{ color: 'white', fontWeight: 'bold' }}>
                                    {i18n.t('MapMarkerBtn')}
                                </Text>
                            </View>
                        </View>
                    </Callout>
                </Marker>
            ))}
        </View>
</code>```

Thanks!

Body:
My app have structure like this,

MapPage.js that contain expo-barcode-scanner wrapped with Modal and MapView.
DetailsPage.js that contain search result/products' details.

User can use the barcode scanner or TextInput(also in MapPage, not wrapped in Modal) to search product ID and the app will navigate to DetailsPage for result. If result is not found, app will automatically navigate.goBack() to MapPage. If result existed, will goto the result and stay in DetailsPage.

User can also navigate to DetailsPage by pressing marker callout on MapView.

Here is situation:

user press on marker callout(navigate to DetailsPage), then press back(navigate.goBack()) to MapPage : No lagging

user search by TextInput, then back to MapPage: No lagging whether search result exist or not

user search by Barcode, result not exist, automatically back to MapPage: not lagging

user search by Barcode, result existed, stay in DetailsPage, user manually press back: LAGGING

Below codes for your references

//MapPage
            <MapView
                style={{ width: '100%', height: '100%' }}
                provider={PROVIDER_GOOGLE}
                showsMyLocationButton={true}
                showsUserLocation={true}
                region={{
                    latitude: region.latitude,
                    longitude: region.longitude,
                    latitudeDelta: region.latitudeDelta,
                    longitudeDelta: region.longitudeDelta,
                }}>
                <MapMarker
                    markerLocation={markers}
                    countryCode={country.countryCode}
                />
            </MapView>
...
                    <TextInput
                        placeholder={
                            i18n.t('SearchId')
                        }
                        placeholderTextColor="white"
                        onSubmitEditing={() =>
                            handleBarCodeScanned({ data: textSearchData })
                        }
                        onChangeText={(text) => {
                            settextSearchData(text.toUpperCase());
                        }}
                    />
                    <Pressable onPress={() => setqrcodeModalVisi(true)}>
                        <Ionicons
                            name="qr-code-outline"
                            size={33}
                            color="white"
                        />
                    </Pressable>
...
            <Modal
                visible={qrcodeModalVisi}
                animationType="slide"
                onRequestClose={() => setqrcodeModalVisi(false)}
                transparent={true}>
                <View>
                    <Pressable onPress={() => setqrcodeModalVisi(false)}>
                        <Feather
                            name="x"
                            size={24}
                            color="white"
                        />
                    </Pressable>
                    {!hasPermission && (
                        <View>
                            <Text
                                style={{
                                    color: colors.text,
                                }}>
                                Camera access denied.
                            </Text>
                            <Pressable onPress={() => getBarCodeScannerPermissions()}>
                                <Text style={{ color: colors.secondary }}>
                                    Goto setting page
                                </Text>
                            </Pressable>
                        </View>
                    )}
                    {hasPermission && (
                        <View
                            style={{
                                flex: 1,
                                justifyContent: 'center',
                                alignItems: 'center',
                            }}>
                            <BarCodeScanner
                                onBarCodeScanned={
                                    scanned ? undefined : handleBarCodeScanned
                                }
                                style={{
                                    width: '100%',
                                    height: '80%',
                                }}
                            />
                        </View>
                    )}
                </View>
            </Modal>

//MapMarker
        <View>
            {markerLocation.map((array) => (
                <Marker
                    key={array.title}
                    coordinate={{
                        latitude: array.latitude,
                        longitude: array.longitude,
                    }}
                    image={require('../../../assets/icons/map_marker.png')}
                    title={''}
                    description={''}
                    onCalloutPress={() => handleMapMarkerPress(array.regionCode)}>
                    <Callout>
                        <View
                            style={{
                                backgroundColor: 'white',
                                width: 180,
                                paddingVertical: 5,
                                alignItems: 'center',
                                justifyContent: 'center',
                            }}>
                            <Text
                                style={{
                                    width: '80%',
                                    textAlign: 'center',
                                    color: colors.secondary,
                                    fontWeight: 'bold',
                                }}>
                                {array.title}
                            </Text>
                            <View
                                style={{
                                    backgroundColor: colors.secondary,
                                    width: '80%',
                                    height: 25,
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    marginTop: 2,
                                    flexDirection: 'row',
                                    marginVertical: 5,
                                }}>
                                <Text style={{ color: 'white', fontWeight: 'bold' }}>
                                    {i18n.t('MapMarkerBtn')}
                                </Text>
                            </View>
                        </View>
                    </Callout>
                </Marker>
            ))}
        </View>

Thanks!


问:
Struggling with DOM traversing. How can I select the "#img" element?
I am trying to attach an event listener to multiple buttons, using a for loop. The event function will "flip" my card by hiding the front side.

```<code><div class="team__box">
          <div class="front" id="front">
            <img
              src="/assets/avatar-drake.jpg"
              alt="headshot"
              class="front__img"
            />
            <h3 class="front__name">Drake Heaton</h3>
            <p class="front__info">Business Development Lead</p>
          </div>
          <div class="back hide" id="back">
            <h3 class="back__name">Drake Heaton</h3>
            <p class="back__quote">
              “Hiring similar people from similar backgrounds is a surefire way
              to stunt innovation.”
            </p>
            <div class="back__social">
              <a href="#" class="back__social-link"
                ><img
                  src="/assets/icon-twitter.svg"
                  alt="twitter"
                  class="back__social-img"
              /></a>
              <a href="#" class="back__social-link"
                ><img
                  src="/assets/icon-linkedin.svg"
                  alt="linkedin"
                  class="back__social-img"
              /></a>
            </div>
          </div>
          <button class="team__btn front__btn" id="btn">
            <img
              src="/assets/icon-cross.svg"
              alt="close button"
              class="btn__img"
              id="img"
            />
          </button>
        </div>
        <div class="team__box">
          <div class="front" id="front">
            <img
              src="/assets/avatar-griffin.jpg"
              alt="headshot"
              class="front__img"
            />
            <h3 class="front__name">Griffin Wise</h3>
            <p class="front__info">Lead Marketing</p>
          </div>
          <div class="back hide" id="back">
            <h3 class="back__name">Griffin Wise</h3>
            <p class="back__quote">
              “Unique perspectives shape unique products, which is what you need
              to survive these days.”
            </p>
            <div class="back__social">
              <a href="#" class="back__social-link"
                ><img
                  src="/assets/icon-twitter.svg"
                  alt="twitter"
                  class="back__social-img"
              /></a>
              <a href="#" class="back__social-link"
                ><img
                  src="/assets/icon-linkedin.svg"
                  alt="linkedin"
                  class="back__social-img"
              /></a>
            </div>
          </div>
<button class="team__btn front__btn" id="btn">
            <img
              src="/assets/icon-cross.svg"
              alt="close button"
              class="btn__img"
              id="img"
            />
          </button>
        </div>
</code>```

Javascript below. It is almost all working, except when I click directly on the "#img" element. I would assume

```<code>const btn = document.getElementsByClassName("team__btn");

for (i = 0; i < btn.length; i++) {
  btn[i].addEventListener("click", function (e) {
    console.log(e.target);
    let front = e.target.closest("div").firstElementChild;
    let back = e.target.closest("div").children[1];

    if (e.target !== "img") {
      img = e.target.firstElementChild;
    } else {
      img = e.target;
    }

    front.classList.toggle("hide");
    back.classList.toggle("hide");

    if (front.classList.contains("hide")) {
      img.src = "./assets/icon-close.svg";
    } else {
      img.src = "./assets/icon-cross.svg";
    }
  });
}
</code>```

Assuming I am clicking directly on the '#img" element, I tried to assign that targetted element to img variable through an if/else statement. Using that, I would expect to be able to reassign the src property of the img variable, depending on whether the front or backside of the card is hidden.

However, when I click directly on the img element I receive the following error:
"Uncaught TypeError: Cannot set properties of null (setting 'src')
at HTMLButtonElement."

What gives?

Body:
I am trying to attach an event listener to multiple buttons, using a for loop. The event function will "flip" my card by hiding the front side.

Drake Heaton

Business Development Lead

Drake Heaton

              “Hiring similar people from similar backgrounds is a surefire way
              to stunt innovation.”

          <button class="team__btn front__btn" id="btn">

          </button>

Griffin Wise

Lead Marketing

Griffin Wise

              “Unique perspectives shape unique products, which is what you need
              to survive these days.”

<button class="team__btn front__btn" id="btn">

          </button>

Javascript below. It is almost all working, except when I click directly on the "#img" element. I would assume

const btn = document.getElementsByClassName("team__btn");

for (i = 0; i < btn.length; i++) {
  btn[i].addEventListener("click", function (e) {
    console.log(e.target);
    let front = e.target.closest("div").firstElementChild;
    let back = e.target.closest("div").children[1];

    if (e.target !== "img") {
      img = e.target.firstElementChild;
    } else {
      img = e.target;
    }

    front.classList.toggle("hide");
    back.classList.toggle("hide");

    if (front.classList.contains("hide")) {
      img.src = "./assets/icon-close.svg";
    } else {
      img.src = "./assets/icon-cross.svg";
    }
  });
}

Assuming I am clicking directly on the '#img" element, I tried to assign that targetted element to img variable through an if/else statement. Using that, I would expect to be able to reassign the src property of the img variable, depending on whether the front or backside of the card is hidden.

However, when I click directly on the img element I receive the following error:
"Uncaught TypeError: Cannot set properties of null (setting 'src')
at HTMLButtonElement."

What gives?


问:
React-Quill, videos are not displayed at all. Only other tags/images, I can't understand why
I have a couple objects created using the React-Quill editor and some contain images while others contain videos. The ones containing images are rendered back in my app without issue but the ones with videos end up rendering while ignoring all video tags.

For example this is one set of data:

```<code><p>Some text</p><video class="quill-upload-video" src="https://res.cloudinary.com/hidden-bucket/video/upload/v1670504722/InspirationMedia/hvnctjls3jpglucerfso.mov" controls="true" controlslist="nodownload" width="100%"></video><p>Some more text</p>
</code>```

Quill renders both paragraph tags and absolutely ignores the video tag as though it isn't there. This is not an issue for images.

Is there an explanation for this? How can I troubleshoot the problem?

Body:
I have a couple objects created using the React-Quill editor and some contain images while others contain videos. The ones containing images are rendered back in my app without issue but the ones with videos end up rendering while ignoring all video tags.

For example this is one set of data:

Some text
<video class="quill-upload-video" src="https://res.cloudinary.com/hidden-bucket/video/upload/v1670504722/InspirationMedia/hvnctjls3jpglucerfso.mov" controls="true" controlslist="nodownload" width="100%"></video>
Some more text

Quill renders both paragraph tags and absolutely ignores the video tag as though it isn't there. This is not an issue for images.

Is there an explanation for this? How can I troubleshoot the problem?


问:
LaTeX interpreter in Octave fails a 'run-time test'
I am trying to create a plot in Octave using the LaTeX interpreter for the axis labels, but whenever I try to do so, using the following code:

```<code>figure()
xlabel('The $x$ axis','interpreter','latex')
</code>```

Octave returns the following message:

warning: latex_renderer: a run-time test failed and the 'latex' interpreter has been disabled.

According to the online Octave documentation, it requires some external tools, all of which are present on my system.

The "latex" interpreter only works if an external LaTeX tool chain is present. Three binaries are needed: latex, dvipng, and dvisvgm. If those binaries are installed but not on the path, one can still provide their respective path using the following environment variables: OCTAVE_LATEX_BINARY, OCTAVE_DVIPNG_BINARY, and OCTAVE_DVISVG_BINARY.

I even tried manually setting the aforementioned environment variables, using Octave's setenv() function, but no dice. I'm using Octave version 7.3.0, running on OpenSUSE. If there is a way I can get some more verbose output from Octave to help debug the issue I'm all ears.

Body:
I am trying to create a plot in Octave using the LaTeX interpreter for the axis labels, but whenever I try to do so, using the following code:

figure()
xlabel('The $x$ axis','interpreter','latex')

Octave returns the following message:

warning: latex_renderer: a run-time test failed and the 'latex' interpreter has been disabled.

According to the online Octave documentation, it requires some external tools, all of which are present on my system.

The "latex" interpreter only works if an external LaTeX tool chain is present. Three binaries are needed: latex, dvipng, and dvisvgm. If those binaries are installed but not on the path, one can still provide their respective path using the following environment variables: OCTAVE_LATEX_BINARY, OCTAVE_DVIPNG_BINARY, and OCTAVE_DVISVG_BINARY.

I even tried manually setting the aforementioned environment variables, using Octave's setenv() function, but no dice. I'm using Octave version 7.3.0, running on OpenSUSE. If there is a way I can get some more verbose output from Octave to help debug the issue I'm all ears.


问:
How to POST a REST api using ClientRequest with pem files
I am having a resteasy application and trying to push mqtt data over https to AWS IoT core service.

I have a Curl command (with --tlsv1.2 enabled) with which I am able to publish the data to AWS. It is a POST request with cacert, cert and private keys file path (passed as .pem files). Now I need to achieve the same using rest easy application.

I am not sure how to pass the pem certificate files in a ClientRequest.

Any sort of help would be appreciated.

Thanks in advance.

With curl command able to publish the data trying to achieve the same with a rest easy application.


问:
Flutter local notifications
anybody knows how can I make the notifications to be showed in flutter daily but with different notifications every day? I'm struggling for few days how to figure it out how can I make that work.

Here is my code:

```<code>Future<void> showNotification(int id, String title, String body) async {
    await flutterLocalNotificationsPlugin.periodicallyShow(
      id,
      title,
      body,
      RepeatInterval.everyMinute,
      const NotificationDetails(
        // Android details
        android: AndroidNotificationDetails('main_channel', 'Main Channel',
            channelDescription: "ashwin",
            importance: Importance.max,
            priority: Priority.max),
        // iOS details
        iOS: DarwinNotificationDetails(
          sound: 'default.wav',
          presentAlert: true,
          presentBadge: true,
          presentSound: true,
        ),
      ),
      androidAllowWhileIdle:
          true, // To show notification even when the app is closed
    );
  }
}
</code>```
```<code>String? randomName;
    final random = new Random();
    randomName = names[random.nextInt(names.length)];
</code>```
```<code>onPressed: () {
                      setState(() {
                        showToast();
                        NotificationService().showNotification(
                          1,
                          '$randomNames ${widget.userPost}',
                          randomName!,
                        );
                      });
                    },
</code>```

Here i call the notifications, but the problem is not updating, it update only if i press the button again, but i don t want to press the button every time. I want to press the button just only one time and after the String to be updated to every single notification.

Title: Flutter local notifications

Body:
anybody knows how can I make the notifications to be showed in flutter daily but with different notifications every day? I'm struggling for few days how to figure it out how can I make that work.

Here is my code:

Future<void> showNotification(int id, String title, String body) async {
    await flutterLocalNotificationsPlugin.periodicallyShow(
      id,
      title,
      body,
      RepeatInterval.everyMinute,
      const NotificationDetails(
        // Android details
        android: AndroidNotificationDetails('main_channel', 'Main Channel',
            channelDescription: "ashwin",
            importance: Importance.max,
            priority: Priority.max),
        // iOS details
        iOS: DarwinNotificationDetails(
          sound: 'default.wav',
          presentAlert: true,
          presentBadge: true,
          presentSound: true,
        ),
      ),
      androidAllowWhileIdle:
          true, // To show notification even when the app is closed
    );
  }
}

String? randomName;
    final random = new Random();
    randomName = names[random.nextInt(names.length)];

onPressed: () {
                      setState(() {
                        showToast();
                        NotificationService().showNotification(
                          1,
                          '$randomNames ${widget.userPost}',
                          randomName!,
                        );
                      });
                    },

Here i call the notifications, but the problem is not updating, it update only if i press the button again, but i don t want to press the button every time. I want to press the button just only one time and after the String to be updated to every single notification.


问:
Better to pass Laravel Collection or array to Blade template?
What are the pros and cons of passing a Laravel Collection versus a regular array into a Blade template?


问:
Exoplayer: elements cannot be seen even set as VISIBLE when the controller hide
When exoplayer controller is visible , I pinch to zoom or swipe to controll the brightnes ,I can see the brightness logo and the progress of brightness. So doen the volume and zoom logo.

```<code>@Override
public void onSingleTouch() {
    super.onSingleTouch();
    if (double_tap_playpause.getVisibility() == View.VISIBLE) {
        double_tap_playpause.setVisibility(View.GONE);
    }

    if(controller.getVisibility()==View.VISIBLE){
        controller.setVisibility(View.GONE);
    }else{
        controller.setVisibility(View.VISIBLE);

    }

}
</code>```

BUT when I tap the screen and hide the controller,I cannot see any logo(Brightness volume pinch-zoom)

EVEN I set them as 'VISIBLE'.

```<code>@Override
public boolean onScale(ScaleGestureDetector detector) {
    scale_factor *= detector.getScaleFactor();
    scale_factor = Math.max(0.1f, Math.min(scale_factor, 6.0f));

    zoomLayout.setScaleX(scale_factor);
    zoomLayout.setScaleY(scale_factor);
    int percentage = (int) (scale_factor * 100);
    zoomPercentage.setText(" " + percentage + "%");
    zoomContainer.setVisibility(View.VISIBLE);   //HERE,show zoom zoomPercentage

    return true;
}
</code>```

Been struggled for a couple of days,any help will be appreciated.

Body:
When exoplayer controller is visible , I pinch to zoom or swipe to controll the brightnes ,I can see the brightness logo and the progress of brightness. So doen the volume and zoom logo.

@Override
public void onSingleTouch() {
    super.onSingleTouch();
    if (double_tap_playpause.getVisibility() == View.VISIBLE) {
        double_tap_playpause.setVisibility(View.GONE);
    }

    if(controller.getVisibility()==View.VISIBLE){
        controller.setVisibility(View.GONE);
    }else{
        controller.setVisibility(View.VISIBLE);

    }

}

BUT when I tap the screen and hide the controller,I cannot see any logo(Brightness volume pinch-zoom)

EVEN I set them as 'VISIBLE'.

@Override
public boolean onScale(ScaleGestureDetector detector) {
    scale_factor *= detector.getScaleFactor();
    scale_factor = Math.max(0.1f, Math.min(scale_factor, 6.0f));

    zoomLayout.setScaleX(scale_factor);
    zoomLayout.setScaleY(scale_factor);
    int percentage = (int) (scale_factor * 100);
    zoomPercentage.setText(" " + percentage + "%");
    zoomContainer.setVisibility(View.VISIBLE);   //HERE,show zoom zoomPercentage

    return true;
}

Been struggled for a couple of days,any help will be appreciated.


问:
My blazor hybridn app UI doesn't refresh?
I converted my regular Blazor App to MAUI and the design and stuff works, the API fetches the data but the UI doesn't refresh.

I tried statehaschanged but that doesn't work either.
Tried it on both android and Windows build and same result.

Any ideas will be a great help.


问:
How to Publish Quarto HTML book in Microsoft Sharepoint
I rendered a Quarto HTML book with several pages and trying to host the Quarto HTML book in Microsoft sharepoint / Teams. But clueless on how to publish it in Microsoft sharepoint. Because the requirements for Sharepoint is .aspx and Quarto files are in html. Manually changing the HTML to aspx is not a viable solution. Is there anyway to upload & publish Quarto HTML pages to Sharepoint?</p>


问:
Building an android apk from HTML/CSS/JavaScript App using Cordova on ubuntu 22.04
I have successfully built apk out of HTML/CSS/JavaScript App using Cordova. And I can successfully install the run the app on my tablet (android version 9) . However, some pages in my app fails to load. Some pages which required keyboard input doesn't work etc. When I copy over same content and host it over apache, they work fine. I wonder what I am missing.

Here is what I do:

I use https://github.com/slaszu/docker-compose-cordova-android.git to run cordova environment.

Inside of cordova container, I add "cordova platform add android" to add platform. ( Gets version8.1.0)

I copy contents of html folder over into the www folder

I have config.xml inside of my www folder which looks like this

```<code><?xml version='1.0' encoding='utf-8'?>
<widget id="io.cordova.abc" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>ABC 1-3</name>
    <description>
       epaath app
    </description>
    <author email="abc@example.org" href="http://cordova.io">
        nepal team
    </author>
    <content src="index.html" />
    <plugin name="cordova-plugin-whitelist" spec="1" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <platform name="android">
        <icon src="www/img/logo.png" />
        <allow-intent href="market:*" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
    </platform>
</widget>

</code>```

I have index.html file with following lines added in suitable place

```<code><script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
    <script src="cordova.js"></script>
    <script type="text/javascript" src="js/bootstrap.min.js"></script>
    <script type="text/javascript" src="js/handlebars-3.0.3.js"></script>
    <script type="text/javascript" src="js/ole.index.js" defer></script>
    <script type="text/javascript" src="js/ole.search.js" defer></script>

    <script>

</code>```

I use following commands to generate apk
#cordova build clean
#cordova build android

Tried building apk using cordova.

It was successful.
Got some minor issues while loading the pages.

Body:
I have successfully built apk out of HTML/CSS/JavaScript App using Cordova. And I can successfully install the run the app on my tablet (android version 9) . However, some pages in my app fails to load. Some pages which required keyboard input doesn't work etc. When I copy over same content and host it over apache, they work fine. I wonder what I am missing.

Here is what I do:

I use https://github.com/slaszu/docker-compose-cordova-android.git to run cordova environment.

Inside of cordova container, I add "cordova platform add android" to add platform. ( Gets version8.1.0)

I copy contents of html folder over into the www folder

I have config.xml inside of my www folder which looks like this

<?xml version='1.0' encoding='utf-8'?>
<widget id="io.cordova.abc" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>ABC 1-3</name>
    <description>
       epaath app
    </description>
    <author email="abc@example.org" href="http://cordova.io">
        nepal team
    </author>
    <content src="index.html" />
    <plugin name="cordova-plugin-whitelist" spec="1" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <platform name="android">
        <icon src="www/img/logo.png" />
        <allow-intent href="market:*" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
    </platform>
</widget>

I have index.html file with following lines added in suitable place


问:
What is the direct download link for Google Sheets HTML export?
I'm creating a google apps script that would export a Google Sheet as an HTML file and place it in my Google Drive, however I need a direct download link in my script, and I couldn't find a working URL for exporting a spreadsheet as HTML. In addition to the data the HTML should also include any images embedded in the spreadsheet.

The direct download link for my Google sheet appears to work when exporting PDF as follows:
https://docs.google.com/spreadsheets/d/1TavkbXHhw3hrDaRKhhNsevyRCM_UG8VD0x-d5eZnHZE/export?format=pdf

however, when swapping out 'format=pdf' to 'format=html' I get an error.
https://docs.google.com/spreadsheets/d/1TavkbXHhw3hrDaRKhhNsevyRCM_UG8VD0x-d5eZnHZE/export?format=html

and the problem appears to be just for html, since the links for .csv, .xlsx, and .ods also work fine.

This solution comes close, but it downloads a .zip that has the html file inside it https://stackoverflow.com/a/44184071/19982878

It should be noted that Google Docs has a direct download link for HTML, which is showcased in this video (at 5:31) https://youtu.be/Rwau69hCC4Y?list=LL&t=331
Swapping out the ID for mine and 'document' to 'spreadsheet' didn't work in this case either.


问:
only size-1 arrays can be converted to Python scalars
I used ORB feature extractor which gave the features vectors of every image but not same number of features. In order to make them same I wanted to append or pad with 0 to the largest-sized feature vector to all the feature vectors. While doing that I got this error.

I have compared the resultant array to the array I used previously which worked. The only difference was every feature vector was uint8. Even I converted to uint 8 and tried converting to int as well it again showed the same error.

Below is the code:

```<code>WIDTH = 256
HEIGHT = 256
data = []
labels = []
descriptors_train = []
orb = cv2.ORB_create()
# loop over the input images
for imagePath in imagePaths:
    # load the image, resize the image to be HEIGHT * WIDTH pixels (ignoring
    # aspect ratio) and store the image in the data list
    image = cv2.imread(imagePath[0], 0)
    image = cv2.resize(image, (WIDTH, HEIGHT))  # .flatten()
    kp = orb.detect(image,None)
    kp, des = orb.compute(image, kp)
    data.append(image)
    des = np.ravel(des)
    descriptors_train.append(des)

    # extract the class label from the image path and update the
    # labels list
    label = imagePath[1]
    labels.append(label)

# Lenght of the max feature vector
max_vector_len_train = a[max_val_index_train]
max_vector_len_test = b[max_val_index_test]

# Adding Padding with respect to largest feature vector
trainX_with_padding = []
testX_with_padding = []
for i in trainX:
    trainX_with_padding.append(i)
for i in testX:
    testX_with_padding.append(i)

trainX_with_padding = np.array(trainX_with_padding)
testX_with_padding = np.array(testX_with_padding)

# Appending 0 after converting to list then Np array
for i in range(len(trainX_with_padding)):
    if (len(trainX_with_padding[i]) != max_vector_len):
        b = list(trainX_with_padding[i])
        for j in range(max_vector_len - len(trainX_with_padding[i])):
            b.append(0)
        b = np.array(b)
        b.astype(np.uint8)
        trainX_with_padding[i] = b
    else:
        pass

from sklearn import svm
clf = svm.NuSVC()
clf.fit(trainX_with_padding, trainY)
</code>```

Body:
I used ORB feature extractor which gave the features vectors of every image but not same number of features. In order to make them same I wanted to append or pad with 0 to the largest-sized feature vector to all the feature vectors. While doing that I got this error.

I have compared the resultant array to the array I used previously which worked. The only difference was every feature vector was uint8. Even I converted to uint 8 and tried converting to int as well it again showed the same error.

Below is the code:

WIDTH = 256
HEIGHT = 256
data = []
labels = []
descriptors_train = []
orb = cv2.ORB_create()
# loop over the input images
for imagePath in imagePaths:
    # load the image, resize the image to be HEIGHT * WIDTH pixels (ignoring
    # aspect ratio) and store the image in the data list
    image = cv2.imread(imagePath[0], 0)
    image = cv2.resize(image, (WIDTH, HEIGHT))  # .flatten()
    kp = orb.detect(image,None)
    kp, des = orb.compute(image, kp)
    data.append(image)
    des = np.ravel(des)
    descriptors_train.append(des)

    # extract the class label from the image path and update the
    # labels list
    label = imagePath[1]
    labels.append(label)

# Lenght of the max feature vector
max_vector_len_train = a[max_val_index_train]
max_vector_len_test = b[max_val_index_test]

# Adding Padding with respect to largest feature vector
trainX_with_padding = []
testX_with_padding = []
for i in trainX:
    trainX_with_padding.append(i)
for i in testX:
    testX_with_padding.append(i)

trainX_with_padding = np.array(trainX_with_padding)
testX_with_padding = np.array(testX_with_padding)

# Appending 0 after converting to list then Np array
for i in range(len(trainX_with_padding)):
    if (len(trainX_with_padding[i]) != max_vector_len):
        b = list(trainX_with_padding[i])
        for j in range(max_vector_len - len(trainX_with_padding[i])):
            b.append(0)
        b = np.array(b)
        b.astype(np.uint8)
        trainX_with_padding[i] = b
    else:
        pass

from sklearn import svm
clf = svm.NuSVC()
clf.fit(trainX_with_padding, trainY)


问:
Pre launch report of Google Play Console shows too long cold start time
Pre launch report of Google Play Console shows too long cold start time, but does not give any details about it. Report shows only test devices without issues but not test devices with issues. It does not give which devices has higher cold start time or any log related it.

I can see all devices used in tests via Stability section. I think last two Google Pixel 2(virtual) have higher cold start time. Am I wrong?

I tried to robo test on Firebase Test Lab. I did not run tests on Google Pixel 2(virtual) because system skipped this device, but I finished test without any issue on Pixel 2(Arm).

I could run the application on Pixel 2 (x86_64 and SDK 32 emulator) through windows Pc. I didn't take abnormal cold start time.

Maybe I take a kind of false positive result on pre launch report.

Is there anyone who experience it? Do you have any idea or suggestion about that problem?


问:
Page link jumps to top of the page before exiting with Animate Presence (framer-motion) in React
I have a page where clicking on a link should land me on a different page after the exit animations of framer motion. The issue I'm facing is that the link is visible after scrolling down the page and upon clicking, the scroll goes to the top and then the exit animation takes place before the redirection.

Expected behavior:

The exit animations to take place at the same scroll point where I clicked on the link.

My issue is exactly same as the one mentioned in this github issue (https://github.com/framer/motion/issues/626) but I'm using React 17.0.2, React router V6 and Framer-motion 4.1.17, hence linking the issue here.

Codesandbox link from the github issue:

https://codesandbox.io/s/sharp-ardinghelli-jw5f9

Steps to reproduce

Scroll down a bit so you are not at the top

click the link to page 2 under the paragraph and you will see it scrolls to the top then fades out.

I'm completely stuck to figureout a solution for this, so couldn't try other solutions


问:
swiperjs arrows doesnt showup in chrome browser
Im using swiper js for a project and wanted the navigation arrows so i added navigation module. it does works in all firefox browser(mobile/desktop) but not in any chrome browser what is causing the problem?

css im using to change color of the arrow

```<code>.Swiper1 {
  width: 100%;
  height: 300px;
}
.SwiperSlide1 {
  text-align: center;
  font-size: 18px;
  background: #fff;
  display: -webkit-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  flex-direction: column;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  -webkit-justify-content: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  -webkit-align-items: center;
  align-items: center;
  transition: 0.3s ease;
}

.swiper-slide img {
  display: block;
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.swiper-button-prev::after{
  font-size: 1.5rem;
  color: white;
  visibility: visible;
}

.swiper-button-next::after{
  font-size: 1.5rem;
  color: white;
}
</code>```

html (JSX)

```<code> <Swiper
      navigation={true}
      loop={true}
      modules={[Navigation,Autoplay]}
      autoplay={{
        delay: 4000,
        disableOnInteraction: false,
      }}
      className="Swiper1">
  <SwiperSlide></SwiperSlide >
</code>```

swiper slide basically have pictures.(the code is too long)

Body:
Im using swiper js for a project and wanted the navigation arrows so i added navigation module. it does works in all firefox browser(mobile/desktop) but not in any chrome browser what is causing the problem?

css im using to change color of the arrow

.Swiper1 {
  width: 100%;
  height: 300px;
}
.SwiperSlide1 {
  text-align: center;
  font-size: 18px;
  background: #fff;
  display: -webkit-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  flex-direction: column;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  -webkit-justify-content: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  -webkit-align-items: center;
  align-items: center;
  transition: 0.3s ease;
}

.swiper-slide img {
  display: block;
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.swiper-button-prev::after{
  font-size: 1.5rem;
  color: white;
  visibility: visible;
}

.swiper-button-next::after{
  font-size: 1.5rem;
  color: white;
}

html (JSX)

 <Swiper
      navigation={true}
      loop={true}
      modules={[Navigation,Autoplay]}
      autoplay={{
        delay: 4000,
        disableOnInteraction: false,
      }}
      className="Swiper1">
  <SwiperSlide></SwiperSlide >

swiper slide basically have pictures.(the code is too long)


问:
How to repeat alarm using alarm manager (weekly or daily)
I am making a watering alarm for my application, I want it to alarm based on what I have set (weekly or daily) continuously. The problem is, it only alarm once and is not repeating

This is the switch statement for spinner where the user could choose if the alarm will be weekly or daily

```<code>switch (spinnerWF2){
                                        case "weekly":
                                            Calendar cal = Calendar.getInstance();
                                            int currDay = cal.get(Calendar.DAY_OF_WEEK);
                                            scheduleAlarm(pName, currDay, time, 7 * 24 * 60 * 60 * 1000);
                                            break;
                                        case "daily":
                                            Calendar cal1 = Calendar.getInstance();
                                            int currDay2 = cal1.get(Calendar.DAY_OF_WEEK);
                                            scheduleAlarm(pName,currDay2,time, 24*60*60*1000);
                                            break;
                                    }
</code>```

Method for scheduling alarm

```<code>private void scheduleAlarm(String text, int dayOfWeek ,long time, int intervalTime) {
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek);

        // Check we aren't setting it in the past which would trigger it to fire instantly
        if(calendar.getTimeInMillis() < System.currentTimeMillis()) {
            calendar.add(Calendar.DAY_OF_YEAR, 7);
        }
        Intent intent = new Intent(getApplicationContext(), AlarmBroadCastForTrack.class);
        // Set this to whatever you were planning to do at the given time
        intent.putExtra("message", text);
        Toast.makeText(this, ""+text, Toast.LENGTH_SHORT).show();

        PendingIntent pendingIntent;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_IMMUTABLE);
        } else {
            pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
        }

        String dateandtime = datePlanted.getText().toString() + " " + timeTonotify;
        DateFormat formatter = new SimpleDateFormat("yyyy-M-d hh:mm");
        try {
            Date date1 = formatter.parse(dateandtime);
            am.setRepeating(AlarmManager.RTC_WAKEUP, date1.getTime(),intervalTime, pendingIntent);
            Toast.makeText(this, "Alarm Setup Successful", Toast.LENGTH_SHORT).show();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
</code>```

broadcast receiver for alarm

```<code>public class AlarmBroadCastForTrack extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        String text = bundle.getString("message");
//        String de = bundle.getString("desc");
//        String date = bundle.getString("date") + " " + bundle.getString("time");

        //On receive on Notification
        Intent intent1 = new Intent(context, NotificationMessageForTrack.class);
        intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent1.putExtra("message", text);
//        intent1.putExtra("desc", text);

        //Notification Builder
        PendingIntent pendingIntent ;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            pendingIntent = PendingIntent.getActivity(context, 1, intent1, PendingIntent.FLAG_IMMUTABLE);
        } else {
            pendingIntent = PendingIntent.getActivity(context, 1, intent1, PendingIntent.FLAG_ONE_SHOT);
        }
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, "notify_001");

        RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.notification_layout_for_track);
        contentView.setImageViewResource(androidx.appcompat.R.id.image, R.mipmap.ic_launcher);
        PendingIntent pendingSwitchIntent ;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            pendingSwitchIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE);
        } else {
            pendingSwitchIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        }
//        contentView.setOnClickPendingIntent(R.id.viewButton, pendingSwitchIntent);
        contentView.setTextViewText(R.id.message, text);
//        contentView.setTextViewText(R.id.description, de);
//        contentView.setTextViewText(R.id.date, date);
        mBuilder.setSmallIcon(R.drawable.ic_baseline_alarm_on_24);
        mBuilder.setAutoCancel(true);
        mBuilder.setOngoing(true);
        mBuilder.setPriority(Notification.PRIORITY_HIGH);
        mBuilder.setOnlyAlertOnce(true);
        mBuilder.build().flags = Notification.FLAG_NO_CLEAR | Notification.PRIORITY_HIGH;
        mBuilder.setContent(contentView);
        mBuilder.setContentIntent(pendingIntent);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "channel_id";
            NotificationChannel channel = new NotificationChannel(channelId, "channel name", NotificationManager.IMPORTANCE_HIGH);
            channel.enableVibration(true);
            notificationManager.createNotificationChannel(channel);
            mBuilder.setChannelId(channelId);
        }

        Notification notification = mBuilder.build();
        notificationManager.notify(1, notification);

    }
}
</code>```

Body:
I am making a watering alarm for my application, I want it to alarm based on what I have set (weekly or daily) continuously. The problem is, it only alarm once and is not repeating

This is the switch statement for spinner where the user could choose if the alarm will be weekly or daily

switch (spinnerWF2){
                                        case "weekly":
                                            Calendar cal = Calendar.getInstance();
                                            int currDay = cal.get(Calendar.DAY_OF_WEEK);
                                            scheduleAlarm(pName, currDay, time, 7 * 24 * 60 * 60 * 1000);
                                            break;
                                        case "daily":
                                            Calendar cal1 = Calendar.getInstance();
                                            int currDay2 = cal1.get(Calendar.DAY_OF_WEEK);
                                            scheduleAlarm(pName,currDay2,time, 24*60*60*1000);
                                            break;
                                    }

Method for scheduling alarm

private void scheduleAlarm(String text, int dayOfWeek ,long time, int intervalTime) {
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek);

        // Check we aren't setting it in the past which would trigger it to fire instantly
        if(calendar.getTimeInMillis() < System.currentTimeMillis()) {
            calendar.add(Calendar.DAY_OF_YEAR, 7);
        }
        Intent intent = new Intent(getApplicationContext(), AlarmBroadCastForTrack.class);
        // Set this to whatever you were planning to do at the given time
        intent.putExtra("message", text);
        Toast.makeText(this, ""+text, Toast.LENGTH_SHORT).show();

        PendingIntent pendingIntent;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_IMMUTABLE);
        } else {
            pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
        }

        String dateandtime = datePlanted.getText().toString() + " " + timeTonotify;
        DateFormat formatter = new SimpleDateFormat("yyyy-M-d hh:mm");
        try {
            Date date1 = formatter.parse(dateandtime);
            am.setRepeating(AlarmManager.RTC_WAKEUP, date1.getTime(),intervalTime, pendingIntent);
            Toast.makeText(this, "Alarm Setup Successful", Toast.LENGTH_SHORT).show();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

broadcast receiver for alarm

public class AlarmBroadCastForTrack extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        String text = bundle.getString("message");
//        String de = bundle.getString("desc");
//        String date = bundle.getString("date") + " " + bundle.getString("time");

        //On receive on Notification
        Intent intent1 = new Intent(context, NotificationMessageForTrack.class);
        intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent1.putExtra("message", text);
//        intent1.putExtra("desc", text);

        //Notification Builder
        PendingIntent pendingIntent ;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            pendingIntent = PendingIntent.getActivity(context, 1, intent1, PendingIntent.FLAG_IMMUTABLE);
        } else {
            pendingIntent = PendingIntent.getActivity(context, 1, intent1, PendingIntent.FLAG_ONE_SHOT);
        }
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, "notify_001");

        RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.notification_layout_for_track);
        contentView.setImageViewResource(androidx.appcompat.R.id.image, R.mipmap.ic_launcher);
        PendingIntent pendingSwitchIntent ;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            pendingSwitchIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE);
        } else {
            pendingSwitchIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        }
//        contentView.setOnClickPendingIntent(R.id.viewButton, pendingSwitchIntent);
        contentView.setTextViewText(R.id.message, text);
//        contentView.setTextViewText(R.id.description, de);
//        contentView.setTextViewText(R.id.date, date);
        mBuilder.setSmallIcon(R.drawable.ic_baseline_alarm_on_24);
        mBuilder.setAutoCancel(true);
        mBuilder.setOngoing(true);
        mBuilder.setPriority(Notification.PRIORITY_HIGH);
        mBuilder.setOnlyAlertOnce(true);
        mBuilder.build().flags = Notification.FLAG_NO_CLEAR | Notification.PRIORITY_HIGH;
        mBuilder.setContent(contentView);
        mBuilder.setContentIntent(pendingIntent);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "channel_id";
            NotificationChannel channel = new NotificationChannel(channelId, "channel name", NotificationManager.IMPORTANCE_HIGH);
            channel.enableVibration(true);
            notificationManager.createNotificationChannel(channel);
            mBuilder.setChannelId(channelId);
        }

        Notification notification = mBuilder.build();
        notificationManager.notify(1, notification);

    }
}


问:
How do i make the speeddial buttons do something in KivyMd?
Im learning kivymd and i tried using the speed dial button but i cant get it to do something
this is my .py file

```<code>from kivy.lang import Builder
from kivymd.app import MDApp

class Test(MDApp):

    data = {
        'Python': 'language-python',
        'C++': 'language-cpp'
    }

    def callback(self, instance):
        self.root.ids.my_label.text = f'You pressed {instance.icon}'

    def build(self):
        self.theme_cls.theme_style = 'Dark'
        self.theme_cls.primary_palette = 'Teal'
        self.theme_cls.accent_palette = 'Pink'
        return Builder.load_file('design3.kv')

Test().run()

</code>```

and this is the .kv file

```<code>MDBoxLayout:
    orientation: 'vertical'

    MDScreen:
        MDLabel:
            id: my_label
            text: 'Some stuff'
            halign: 'center'

        MDFloatingActionButtonSpeedDial:
            data: app.data
            root_button_anim: True
            label_text_color: '#FFF000'

            #action
            callback: app.callback

</code>```

i tried using the callback function because thats what the tutorial used, but it does not seem to work for me

Body:
Im learning kivymd and i tried using the speed dial button but i cant get it to do something
this is my .py file

from kivy.lang import Builder
from kivymd.app import MDApp

class Test(MDApp):

    data = {
        'Python': 'language-python',
        'C++': 'language-cpp'
    }

    def callback(self, instance):
        self.root.ids.my_label.text = f'You pressed {instance.icon}'

    def build(self):
        self.theme_cls.theme_style = 'Dark'
        self.theme_cls.primary_palette = 'Teal'
        self.theme_cls.accent_palette = 'Pink'
        return Builder.load_file('design3.kv')

Test().run()

and this is the .kv file

MDBoxLayout:
    orientation: 'vertical'

    MDScreen:
        MDLabel:
            id: my_label
            text: 'Some stuff'
            halign: 'center'

        MDFloatingActionButtonSpeedDial:
            data: app.data
            root_button_anim: True
            label_text_color: '#FFF000'

            #action
            callback: app.callback

i tried using the callback function because thats what the tutorial used, but it does not seem to work for me