Flutter Cloud Funtion: Update fieds in subcollection

I have a Cloud Function in my Flutter app with the following code:

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const database = admin.firestore();
const min = "* * * * *";

exports.scheduled = functions.pubsub.schedule(min).onRun(async (context) => {
  const batch = database.batch();
  const {docs} = await database.collection("ADSGHANA").get();
  docs.map((doc) => {
    const {
      TimeToDelete,           //this is a Timestamp in a main collection
      TimestampArrival,      //this is a Timestamp in a main collection
      TimestampDeparture,    //this is a Timestamp in a main collection
      PostStatus,            //This is a string in a main collection
    } = doc.data();
    const now = admin.firestore.Timestamp.now();
    const starting = now > TimestampDeparture;    //If this time is reached an update in its corresponding subCollection should be performed.
    const ending = now > TimestampArrival;
    let val = PostStatus;
    if (starting) val = "Started";
    if (ending) val = "Completed";

    batch.set(
        database.doc(`ADSGHANA/${doc.id}`), {
          Timestamp: TimeToDelete? TimestampArrival : now,
          PostStatus: val,
          //the subCollection update should be here
        }, {
          merge: true,
        },
    );
  });

  await batch.commit();
});

I want that if const starting = now > TimestampDeparture; is reached it should update a particular update field in its subcollection as in the flutter code below. Except that I don’t know how to write this in JS.

FirebaseFirestore.instance.collection("collectionName")
                          .doc(theDocumentID)
                          .collection("subCollectionName")
                          .where("AdStatus", whereNotIn: ["Passenger cancelled",
                           "Rejected"])
                          .get()
                          .then((value) =>
                              value.docs.forEach((element) {
                                  FirebaseFirestore.instance
                                  .collection(collectionName)
                                  .doc(uid)
                                  .collection(subCollectionName)
                                  .doc(element.id)
                                  .update({"AdStatus": "Started"});
                                    }));

Any help please?

Prettier Vscode extention ignoring config file

I created prettier.config.cjs:

module.exports = {
  singleQuote: true,
  plugins: ["prettier-plugin-tailwindcss"],
};

but when I am using single quote the prettier change it into double quote so it is ignoring my configs. What’s wierd is that the plugin does work…

How do I fix it?

edit:my default formatter is prettier

Getting errors when importing BrowserRouter as Router, Route, Routes

I am creating a React app and trying to add routes using react-router-dom but when importing

import { BrowserRouter as Router, Route, Routes } from "react-router-dom";

I am getting a ton of errors which are as follows

enter image description here

there are many more (if needed ask for in the comment I’ll post them)

Index.js

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";

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

App.js

I am trying to route “/login” to Login and “/register” to Register but when importing the routes from react-router-dom I am getting errors, even when I am not using them in my code

import "./App.css";
import Login from "./components/Login/Login";
import Register from "./components/Register/Register";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";

function App() {
  return (
    <div className="App">
      <Register />
      <Login />
    </div>
  );
}

export default App;

enter image description here

I am using “react-router-dom”: “^6.21.1”

I tried fresh installing the react-router-dom but still didn’t work.

I have never faced this before and I don’t know whats wrong this time.

Odoo client error – TypeError: Cannot read properties of undefined (reading ‘form’)

TypeError: Cannot read properties of undefined (reading ‘form’)

I get this error when I try to open the Settings as an Admin. Since I can’t access my Settings page, I am unable to activate the debugger also.

TypeError: Cannot read properties of undefined (reading 'form')
    at http://65.2.111.189/web/content/3316-e929ab4/web.assets_backend.js:448:309
    at _.each._.forEach (http://65.2.111.189/web/content/1908-99650a5/web.assets_common.js:108:558)
    at Class._generateActionViews (http://65.2.111.189/web/content/3316-e929ab4/web.assets_backend.js:448:229)
    at http://65.2.111.189/web/content/3316-e929ab4/web.assets_backend.js:443:497

I had installed a module to take auto-backups of DB to Google Drive, and since I can’t access my settings page, even the Google Drive error is popping up whenever I open any page like CRM or Invoice.

Odoo Server Error
Traceback (most recent call last):
  File "/odoo/odoo-server/odoo/http.py", line 624, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/odoo/odoo-server/odoo/http.py", line 310, in _handle_exception
    raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])
  File "/odoo/odoo-server/odoo/tools/pycompat.py", line 14, in reraise
    raise value
  File "/odoo/odoo-server/odoo/http.py", line 669, in dispatch
    result = self._call_function(**self.params)
  File "/odoo/odoo-server/odoo/http.py", line 350, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/odoo/odoo-server/odoo/service/model.py", line 94, in wrapper
    return f(dbname, *args, **kwargs)
  File "/odoo/odoo-server/odoo/http.py", line 339, in checked_call
    result = self.endpoint(*a, **kw)
  File "/odoo/odoo-server/odoo/http.py", line 915, in __call__
    return self.method(*args, **kw)
  File "/odoo/odoo-server/odoo/http.py", line 515, in response_wrap
    response = f(*args, **kw)
  File "/odoo/odoo-server/addons/web/controllers/main.py", line 1342, in call_kw
    return self._call_kw(model, method, args, kwargs)
  File "/odoo/odoo-server/addons/web/controllers/main.py", line 1334, in _call_kw
    return call_kw(request.env[model], method, args, kwargs)
  File "/odoo/odoo-server/odoo/api.py", line 466, in __getitem__
    return self.registry[model_name]._browse(self, (), ())
  File "/odoo/odoo-server/odoo/modules/registry.py", line 177, in __getitem__
    return self.models[model_name]
KeyError: 'google.drive.config'

Kindly suggest what can be done to resolve this. And to add to my bad luck, I have forgotten the root password to the backend. The service is hosted in AWS EC2.

Function returning a function n times until printing string [closed]

Write a function named: countDownTimer(n). This function will represent a count
down of days till the New Year. The countDownTimer function will
take in a number argument (n) the first time it is called and if that
number is greater than 0 the countDownTimer will return a function.

The function returned by countDownTimer can then be invoked n times before it
returns a string of “Happy New Year!”.

 function countDownTimer(n) {
var count = 0;
var temp;

while (count !== n) {
    if (n !== 0) {
        return function() {
            temp = function() {};
            count++;
            return temp;
        }
    } else {
        return 'Happy New Year!'
    } 
}

return 'Happy New Year!'

};

how to allow download file .zip in web site

I have a website that downloads a ZIP file using ReactJS code. The ZIP file contains several files, including an application installer and other files. However, when I attempt to download it, Google Chrome displays a message saying suspicions download blocked . How can I fix this? Thanks very much.This is my code download

This is Error is google chorem

Babel issue from writing to its cache file

I am attempting to set up a local p5.js project. When I run the following command:

docker-compose -f docker-compose-development.yml run --rm app npm run fetch-examples

I encounter the following error:

Getting p5 user
Babel could not write cache to file: /usr/src/app/node_modules/.cache/@babel/register/.babel.7.22.5.development.json
due to a permission issue. Cache is disabled.
Deleting old projects...

Operating System: Ubuntu

I have deleted all the projects completely and repeated this process more than 4 to 5 times. Additionally, I have cleared all Docker images and thoroughly cleaned everything.

VSCode Warning/Error: ‘foo’ is assigned a value but never used in JavaScript project [duplicate]

I have a small snippet on a JavaScript using Visual Studio Code, and I’ve encountered a warning/error that I find puzzling. In my project, I have three files: index.php, utils.js, and index.js.

Here’s the structure of my files:

index.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS Test</title>
</head>
<body>
    JS Test
    <script type="text/javascript" src="./utils.js"></script>
    <script type="text/javascript" src="./index.js"></script>
</body>
</html>

utils.js

console.log("utils.js");

const foo = () => {
    console.log('foo');
}

index.js

console.log("index.js");

foo();

In Visual Studio Code, I’m receiving a warning or error indicating that ‘foo’ is assigned a value but never used. However, I am indeed using foo in the index.js file. Despite this, the warning persists.

I’m seeking clarification on why this warning is appearing and if there’s a way to resolve it. I believe I am correctly using the foo function, but the IDE seems to think otherwise. Any insights or guidance on resolving this issue would be greatly appreciated.

This is a small snippet of what I’m trying to do in my actual project. Also I apologize for if any mistake I made in this post.

I tried making this snippet for same case but it didn’t work.

EDIT: I’m trying to use jslint/eslint on my project. I don’t know if it is possible with vanilla js or not.

I have 2 fields 1 is CKEDITOR and other one is signature text field when I am trying to update in signature text field ckeditor field is not updating

I am getting issue in Ckeditor I have ckeditor textarea and signature text field when I am trying to update in signature it has to update in ckeditor signature area.

Here is my code

// Function to update subject and body based on start date
   function updateSubjectAndBody(startDate) {
     const form = $('#formCpiStop');
     const fromField = form.find('#from');
     const toField = form.find('#to');
     const subjectParagraph = form.find('#subjectParagraph');
    // Format the selected date as "Full day Month and date, year"
    const formattedDate = startDate ? new Date(startDate).toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' }) : '';
   // Get the values from the fields
    const from = fromField.val() || '';
    const to = toField.val() || '';
    const signature = $('#cpistopsignature').val() || '';
    const subjectText = `Request for deployment for ${formattedDate}  - Please Acknowledge`;
   // Set the updated content to the subject paragraph
   subjectParagraph.html(subjectText);
   // Body content for CKEditor (excluding From and To)
   const bodyContent = `
   <p>Dear Team,</p>
   <p>This is a request for successfully publish thethe tonight's ${formattedDate} for . 
    We will inform you once the release is complete.</p>
    <p>${signature}</p> <!-- Append signature to body content -->
    `;
   console.log(bodyContent);
  // Update CKEditor content directly
 if (CKEDITOR.instances.bodyTextarea) {
    CKEDITOR.instances.bodyTextarea.setData(bodyContent);
 }
 }

Here is the HTML field

    <div class="form-group">
      <label for="subjectCpiStop"><i class="fas fa-heading"></i> Subject</label>
      <p id="subjectParagraph"></p>
    </div>
    <div class="form-group">
      <label for="cpistopsignature"><i class="fas fa-signature"></i> Signature</label>
      <input type="text" id="cpistopsignature" class="form-control">
    </div>

Please let me know what I am doing wrong why the ckeditor not updating the signature field

Note I am not getting any error but ckeditor field is not updating

Unexpected global objects in node 18 [duplicate]

I’m busy trying to understand the behaviour of the this keyword by reading up about it on mdn web docs.

I made the following code snippet to explore the this keyword behaviour, especially around arrow functions:

const arrow = () => this;

let y = {
  name: 'object',
  f1() { return this },           // y object
  f2: () => { return this },      // global
  f3() { return arrow() },        // global
  f4() { return (() => this)() }, // y object
  f5() {                          // global
    function foobar () {
      return this;
    }
    return foobar();
  },
  f6() {                          // undefined
    function foobar () {
      'use strict';
      return this;
    }
    return foobar();
  },
};

this.name = 'global';

console.log(globalThis) // global
console.log(this);      // global
console.log(y.f1());    // object
console.log(y.f2());    // global
console.log(y.f3());    // global
console.log(y.f4());    // object
console.log(y.f5());    // global
console.log(y.f6());    // undefined

When executing the above code from within Chrome v120 everything behaves as expected, where the global object is the Window.

When executing the code with node v18.17.1 the y.f5() method yields the following:

<ref *1> Object [global] {
  global: [Circular *1],
  queueMicrotask: [Function: queueMicrotask],
  clearImmediate: [Function: clearImmediate],
  setImmediate: [Function: setImmediate] {
    [Symbol(nodejs.util.promisify.custom)]: [Getter]
  },
  structuredClone: [Function: structuredClone],
  clearInterval: [Function: clearInterval],
  clearTimeout: [Function: clearTimeout],
  setInterval: [Function: setInterval],
  setTimeout: [Function: setTimeout] {
    [Symbol(nodejs.util.promisify.custom)]: [Getter]
  },
  atob: [Function: atob],
  btoa: [Function: btoa],
  performance: Performance {
    nodeTiming: PerformanceNodeTiming {
      name: 'node',
      entryType: 'node',
      startTime: 0,
      duration: 23.78549998998642,
      nodeStart: 1.4962089955806732,
      v8Start: 4.412084013223648,
      bootstrapComplete: 16.266708999872208,
      environment: 9.128708988428116,
      loopStart: -1,
      loopExit: -1,
      idleTime: 0
    },
    timeOrigin: 1703311964946.281
  },
  fetch: [AsyncFunction: fetch]
}

Why is this?

Im working on my mimicking duolingo project and I couldn’t figure out why my checkButton isn’t working [closed]

This code ensures that the JavaScript logic runs after the HTML document has fully loaded. It introduces a result message element, displayed at the bottom of the page, and adds an event listener to the “CHECK” button. When the button is clicked, it checks if the order of dragged words matches the predefined order, and then updates the result message accordingly, indicating whether the word order is correct or not. However, the checkButton isn’t working, I’m not sure which part of my code is written incorrectly.

<!DOCTYPE html>
<html lang="en">

<head>
    <!-- Meta tags for character set, viewport, and compatibility -->
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Duolingo exercise</title>
    
    <!-- Link to import the 'Fredoka' font from Google Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Fredoka:wght@300;400;500;600;700&display=swap"
        rel="stylesheet">
    
    <!-- CSS styles for the document -->
    <style>
        /* Your CSS styles go here */
        :root {
            --grey-color: rgb(228, 228, 228);
            --darker-grey-color: rgb(189, 189, 189);
            --text-color: rgb(60, 60, 60);
            --border-radius: 15px;
        }
        
        /* Styles for the body and overall layout */
        body {
            /* ... */
        }

        /* Styles for different sections and elements */
        .wrapper {
            /* ... */
        }

        /* ... Other styles ... */

        /* Styles for the footer and buttons */
        footer {
            /* ... */
        }

        .skip_button,
        .check_button {
            /* ... */
        }

        /* ... More styles ... */
    </style>
</head>

<body>
    <!-- Main content of the page -->
    <div class="wrapper">
        <!-- Heading for the exercise -->
        <h1>Write this in Japanese</h1>
        
        <!-- Top container containing image and original text -->
        <div class="top__container">
            <div class="image_text__container">
                <!-- Duo image -->
                <img src="assets/duo.svg" alt="duo">
                <!-- Original text in Chinese -->
                <p id="original__text"></p>
            </div>
            
            <!-- Container for the destination (dragged) words -->
            <div id="destination__container"></div>
        </div>
        
        <!-- Container for the source (original) words -->
        <div id="origin__container"></div>
    </div>
    
    <!-- Footer with SKIP and CHECK buttons -->
    <footer>
        <div class="skip_button">SKIP</div>
        <div class="check_button">CHECK</div>
    </footer>

    <!-- JavaScript code -->
    <script>
        // Array of exercises with Chinese, Japanese, and word list
        const exercises = [
            // Exercise 1
            {
                chinese: "我是一隻貓",
                japanese: "私は猫です",
                list: ["は", "で", "私", "す", "猫"],
            },
            // Exercise 2
            {
                chinese: "這是學校啊",
                japanese: "これは学校ですね",
                list: ["学", "こ", "は", "で", "ね", "校", "れ", "す"],
            },
            // Exercise 3
            {
                chinese: "是,是這樣",
                japanese: "はい、そうですね",
                list: ["は", "そ", "、", "で", "ね", "い", "う", "す"],
            },
        ];

        // Get references to HTML elements
        const destinationContainer = document.getElementById("destination__container");
        const originContainer = document.getElementById("origin__container");
        const originalText = document.getElementById("original__text");
        const words = document.getElementsByClassName("word");

        // Get default position of the destination container
        let destinationPosDefault = destinationContainer.getBoundingClientRect();

        // Arrays to store word objects for destination and origin containers
        let destinationArray = [];
        const originArray = [];

        // Randomly select an exercise
        let exercise = exercises[Math.floor(Math.random() * exercises.length)];
        let chineseSentence = exercise.chinese.split(" ");
        let listOfWords = exercise.list;

        // Create span elements for the Chinese sentence
        for (let i = 0; i < chineseSentence.length; i++) {
            const spanNode = document.createElement("span");
            spanNode.textContent = chineseSentence[i];
            originalText.appendChild(spanNode);
        }

        // Create word elements for the word list
        for (let i = 0; i < listOfWords.length; i++) {
            const wordNode = document.createElement("div");
            wordNode.textContent = listOfWords[i];
            wordNode.classList.add("word");
            originContainer.appendChild(wordNode);
        }

        // Function to calculate the x position for the destination container cursor
        function calibrateDestinationCursorPos(destinationArray) {
            if (destinationArray.length === 0) {
                return destinationPosDefault.x;
            } else {
                let sum = destinationPosDefault.x;
                destinationArray.forEach((element) => {
                    sum += element.width + 20; // Add 20 pixels for the space between words
                });
                return sum;
            }
        }

        // Function to create an object for the origin array
        function createOriginArray(word) {
            let wordPosition = word.getBoundingClientRect();
            let newWordObject = Object.assign(wordPosition);
            newWordObject.word = word.textContent;
            newWordObject.location = "origin";
            originArray.push(newWordObject);
        }

        // Iterate through each word in the origin container
        for (let i = 0; i < words.length; i++) {
            createOriginArray(words[i]);

            // Add click event listener for each word to enable dragging
            words[i].addEventListener("click", () => {
                // Calculate animation travel distance
                destinationStartPos = calibrateDestinationCursorPos(destinationArray);
                let yTravel =
                    originArray[i].y -
                    (destinationPosDefault.y +
                        (destinationPosDefault.height - originArray[i].height) / 2);
                let xTravel = (originArray[i].x > destinationStartPos) ?
                    -(originArray[i].x - destinationStartPos) :
                    destinationStartPos - originArray[i].x;

                // Check word position and update arrays accordingly
                if (originArray[i].location === "origin") {
                    originArray[i].location = "destination";
                    destinationArray.push(originArray[i]);
                } else if (originArray[i].location === "destination") {
                    yTravel = 0;
                    xTravel = 0;
                    originArray[i].location = "origin";
                    let test = destinationArray.filter(
                        (wordObject) => wordObject.word !== originArray[i].word
                    );
                    destinationArray = test;
                }

                // Apply translation to simulate dragging
                words[i].style.transform = `translate(${xTravel}px,-${yTravel}px)`;
            });
        }

        // Get references to check and reset buttons, and result message
        const checkButton = document.getElementById("check__button");
        const resultMessage = document.getElementById("result__message");
        const resetButton = document.getElementById("reset__button");

        // Add event listener to check button for result check
        checkButton.addEventListener("click", () => {
            let isCorrect = true;

            // Check if the order of dragged words matches the exercise list
            for (let i = 0; i < destinationArray.length; i++) {
                console.log("Checking:", destinationArray[i].word, exercise.list[i]);
                if (destinationArray[i].word !== exercise.list[i]) {
                    isCorrect = false;
                    break;
                }
            }

            // Display result message
            console.log("Result:", isCorrect ? "Correct!" : "Incorrect!");
            resultMessage.textContent = isCorrect ? "Correct!" : "Incorrect!";
            resultMessage.style.color = isCorrect ? "green" : "red";
        });

        // Add event listener to reset button for exercise reset
        resetButton.addEventListener("click", () => {
            // Reset arrays and word positions
            destinationArray = [];
            originArray.forEach((wordObject) => {
                wordObject.location = "origin";
                words.forEach((word) => (word.style.transform = "translate(0, 0)"));
            });

            // Select a new random exercise
            exercise = exercises[Math.floor(Math.random() * exercises.length)];
            chineseSentence = exercise.chinese.split(" ");
            listOfWords = exercise.list;

            // Clear result message
            resultMessage.textContent = "";
        });
    </script>
</body>

</html>

Langchain query using Pinecone and ParentDocumentRetriever returns no results

I am really not understanding how to retrieve the parent documents using Langchain’s ParentDocumentRetriever when using Pinecone. The following code is working for creating the embeddings and inserting them into Pinecone:

const pinecone = new Pinecone();

const pineconeIndex = pinecone.Index(process.env.PINECONE_INDEX);
const docstore = new InMemoryStore();

const vectorstore = await PineconeStore.fromExistingIndex(
  new OpenAIEmbeddings(),
  { pineconeIndex }
);

const retriever = new ParentDocumentRetriever({
  vectorstore,
  docstore,
  childSplitter: new HTMLSplitter(),
  parentK: 5,
});

// We must add the parent documents via the retriever's addDocuments method
await retriever.addDocuments(docs);

const retrievedDocs = await retriever.getRelevantDocuments("What is emptiness?");

console.log(retrievedDocs);

The retrievedDocs contains a few parent documents, as expected.

Now that my index is created, I would like to subsequently perform the same operation, but without the await retriever.addDocuments(docs):

const pinecone = new Pinecone();

const pineconeIndex = pinecone.Index(process.env.PINECONE_INDEX);
const docstore = new InMemoryStore();

const vectorstore = await PineconeStore.fromExistingIndex(
  new OpenAIEmbeddings(),
  { pineconeIndex }
);

const retriever = new ParentDocumentRetriever({
  vectorstore,
  docstore,
  childSplitter: new HTMLSplitter(),
  parentK: 5,
});

const retrievedDocs = await retriever.getRelevantDocuments("What is emptiness?");

console.log(retrievedDocs);

This yields no results. The documentation is really rather unclear on this: am I expected to implement my own document store containing all of the parent documents with their accompanying IDs or something like that? Can I save the InMemoryStore to the filesystem, or use the LocalFileStore? Does this document store pertain just to the parent documents?

I am not sure how to use LocalFileStore since dropping it in as a replacement causes my IDE to become unhappy, because it extends BaseStore<string, Uint8Array>, whereas InMemoryStore extends BaseStore<string, T>.

In summary, how would I use Pinecone as a vector store in combination with ParentDocumentRetriever? What document store do I use?

It seems to me that this would be a pretty common use case; where might I find an example?