Jest mock for nested function call not working

I have a function a() that calls a function b().
I have a test that checks the results of a(); but I want to mock the result of b() so it returns false instead of true.

// myModule.js

export const a = () => {
  const c = b();
  console.log('c: ', c); 

  return c;
};

export const b = () => true;
// myModule.test.js
import { a } from './myModule';

beforeEach(() => {
  jest.mock('./myModule', () => ({
    ...jest.requireActual('./myModule'),
    b: jest.fn(() => false)
  }));
});

describe('a()', () => {
  test('should return false when b() returns false', () => {
    const result = a();
    expect(result).toBe(false);
  });
});

When I run it with jest myModule.test.js --silent=false, the test fails: the log for b() within a() is returning true instead of false, and the result value in the test is true as well.
AFAIK this should work; any hint will be appreciated.

How to get a jquery.cycle news ticker to pause on focus

I have a basic jquery.cycle news ticker that is used by us on some sites and currently pauses when you hover over the currently chown item with your mouse pointer. All good, but I also need it to pause when someone has tabbed to the news item using a keyboard (ie it is in focus). I don’t know javascript at all so have been struggling with this!
I’ve stripped this down as best I can to demonstrate what we have currently and put it at https://www.prolocal.co.uk/ticker/ .

In the jquery.cycle.all.js file there is a section that goes…

if ( /mouseenter|mouseover/i.test(opts.pagerEvent) ) {
        $a.hover(pagerFn, function(){/* no-op */} );
    }
    else {
        $a.bind(opts.pagerEvent, pagerFn);
    }

I tried adding changing the first line of this to include variations of focus, eg onfocus, focusin, just focus, thinking it might then trigger the contained code, but sadly this didn’t work for me. I wasn’t sure which variation of focus to use, which doesn’t help! I’m sure this does just need a minor change in the jquery.cycle.all.js code but it’s beyond me.

Can anyone help point me in the right direction on this one? Thanks in advance for any help

Don’t know how to get access to input value [duplicate]

I would like to get access to the text written in an input text.

To see if I have access to the text written in this input box, I put an Event Listener on a button with a function that console.logs the input value. However I’m getting no luck.

const input = document.getElementById("text-input").value;
const checkBtn = document.querySelector("#check-btn");
const result = document.querySelector("#result");
checkBtn.addEventListener("click", () => {
  console.log(input)
})

Here’s the HTML

<input id="text-input" type="text" class="input" required/>
        <button type="submit" id="check-btn" name="text">Check</button>

Import xlsx file using jspreadsheet gives Invalid HTML: could not find error

I’m trying to use jspreadsheet from bossanova.uk to import a .xlsx file as described here. However I get an Invalid HTML: could not find <table> error. This error should mean the file is interpreted as HTML, but it’s actually an xlsx file. I created an HTML input allowing the user to choose the file and a container for the spreadsheet:

<input type="file" id="inputXlsFile" />
<div id="spreadsheet"></div>

Then in Javascript:

inputElement = document.getElementById("inputXlsFile");
inputElement.addEventListener("change", handleFiles, false);

var handleFiles = function() {
    const files = this.files;

    jexcel.fromSpreadsheet(files[0], function(result) {
        if (!result.length) {
            console.error('Jspreadsheet: Something went wrong.');
        } else {
            if (result.length == 1) {
                jexcel(document.getElementById('spreadsheet'), result[0]);
            } else {
                jexcel.createTabs(document.getElementById('spreadsheet'), result);
            }
        }
    });
}

Here is a screenshot of the xlsx file opened in Excel:

Screenshot of the xls file opened in Excel

Offline display of a website in kiosk mode (Windows 10) [closed]

I’m currently trying to set up a media terminal for an exhibiton. It’s supposed to show a website with further informations, videos, sound files in the Windows 10 Kiosk Mode (so that Users can’t easily leave the website). The website must be offline because access to the Internet is not always guaranteed.

I’ve downloaded the website with its subsites using WinHTTrack and most of it works, but some media like videos, sound files or slide shows won’t load. I have adjusted the file paths in the source code accordingly, but I guess, that there might be a problem with Javascript. The website itself is using the JW Player.

Does anyone here has experiences with the use of offline webites and can help me? Or do you have other recommendations on how to show the offline website in a safe environment?

Dynamically set/manipulate max-height to avoid scrollbar at outer container

The snippet below gives me two vertical scrollbars, one at dialogBox and the other at withLongContent.

How can I set/manipulate max-height of withLongContent so that there will be no scrollbar at dialogBox? That is, the height of withLongContent and that of “up stuff” togther do not exceed 95vh, dialogBox‘s height.

If JS is required, I need vanilla JS solution. I cannot adopt jQuery.

<div id="dialogBox" style="max-height:95vh; overflow:auto;">
  <!-- Some dynamic inline and block elements up here. Let's call them "up stuff". -->

  <div style="display:table;">
    <div style="display:table-row;">
      <div style="display:table-cell;">
        <div id="withLongContent" style="max-height:95vh; overflow:auto;">
          <!-- A dynamic long list of stuff here... -->
        </div>
      </div>
      <div style="display:table-cell;">
        <!-- Some other contents here... -->
      </div>
    </div>
  </div>
</div>

A list of lists grouped by overlapping dates

I would like a javascript function that builds a list of lists grouped by overlapping dates and roomId:
Given this list

const inputList = [
   { roomId: 1, start: 1, end: 10 },
   { roomId: 1, start: 1, end: 4 },
   { roomId: 1, start: 5, end: 7 },
   { roomId: 2, start: 5, end: 7 } 
];

I expect a function to return a list of 3 groups, one with first and second elements, another with first of third, as the second and third don’t overlap and a third group composed of only fourth elment as the roomId is different.

I tried every AI, none gave me the correct answer.

The expected output should be

[
  [
   { roomId: 1, start: 1, end: 10 },
   { roomId: 1, start: 1, end: 4 }
  ],
  [
   { roomId: 1, start: 1, end: 10 },
   { roomId: 1, start: 5, end: 7 }
  ],
  [
   { roomId: 2, start: 5, end: 7},
  ]
]

JS PDF Parsing: How do I extract the contents of PDF and automatically display it on the text fields?

I am working on our thesis which has a functionality similar to autofill when you select your resume when applying for a job through websites. The problem is, when I select a different PDF file from the one I used for testing, the information isn’t showing up on the text fields although I can see in the console that it was extracted. Is there any other way I can capture and display the information? I already tried different regex patterns.

Here is my full JS code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.min.js"></script>
<script>
const pdfjsLib = window['pdfjs-dist/build/pdf'];

// Set the location of the worker script
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.worker.min.js';

document.getElementById('fileInput').addEventListener('change', function (event) {
    var file = event.target.files[0];
    var fileReader = new FileReader();

    fileReader.onload = function () {
        var typedarray = new Uint8Array(this.result);

        pdfjsLib.getDocument(typedarray).promise.then(function (pdf) {
            var textPromises = [];

            // Loop through pages 1 to 5 and create promises for text extraction
            for (let pageNumber = 1; pageNumber <= 5; pageNumber++) {
                textPromises.push(
                    pdf.getPage(pageNumber).then(page => {
                        return page.getTextContent().then(textContent => {
                            return textContent.items.map(item => item.str).join('n');
                        });
                    })
                );
            }

            // Wait for all promises to resolve
            Promise.all(textPromises).then(pagesText => {
                // Concatenate text from all pages
                var text = pagesText.join('n');

                console.log("Extracted text:", text);

                var titleRegex = /ARCHITECTUREn([sS]+?)nA/;
                var authorRegex = /(By:|By|by:|by)s*([sS]+?)s*(January|February|March|April|May|June|July|August|September|October|November|December) d{4}/;
                var yearRegex = /(January|February|March|April|May|June|July|August|September|October|November|December) (d{4})/;
                var abstractRegex = /ABSTRACTn([sS]+?)nPage/;
                var adviserRegex = /(w+)s+Adviser/; // Capture word before "Adviser"

                var titleMatch = text.match(titleRegex);
                var authorMatch = text.match(authorRegex);
                var yearMatch = text.match(yearRegex);
                var abstractMatch = text.match(abstractRegex);
                var adviserMatch = text.match(adviserRegex);

                console.log("Title match:", titleMatch);
                console.log("Author match:", authorMatch);
                console.log("Year match:", yearMatch);
                console.log("Abstract match:", abstractMatch);
                console.log("Adviser match:", adviserMatch);

                if (titleMatch) {
                    document.getElementById('title').value = titleMatch[1].trim();
                }
                if (authorMatch) {
                    document.getElementById('author').value = authorMatch[2].trim();
                }
                if (yearMatch) {
                    document.getElementById('year').value = yearMatch[2];
                }
                if (abstractMatch) {
                    document.getElementById('abstract').value = abstractMatch[1].trim();
                }
                if (adviserMatch) {
                    document.getElementById('adviser').value = adviserMatch[1].trim();
                }
            });
        });

    };

    fileReader.readAsArrayBuffer(file);
});
</script>

Bootstrap: close modal and open another one (with same id) by javascript

I have one modal window opened (contains a paginated list), and from that modal I have buttons next/prev that should show new content.

I can’t have HTML code for modals next and prev inside first modal as Bootstrap suggests, as this should work for many pages.

My solution would be to close current modal and open a new one by javascript, this is working quite ok except this: everytime I close a modal, the modal is closed, but a grey semitransparent background (curtain like) stays and adds to the one added to the new opened one.

Because of framework used and template stuff, these modals have same id. I tried using different modal id’s for each page but the result is similar.

The question is, why is this semitransparent div staying when closing modal? or is there a different approach for this? (I think keeping html code of next/prev inside this modal is not an option).

This is my code, in comments you see other options I tried but all with similar result:

openModalWindow: function(route, modalId)
{
    $.ajax({
        type: "GET",
        url: route, 
        success: function(data){
                                $('#' + modalId).remove();
                                $('body').append(data);
                                $('#' + modalId).modal('show');
                               }
      });
},
closeModalWindow: function(modalId)
{
    // $('#' + modalId).remove();
    // $('#' + modalId).on('hidden.bs.modal', function () {$('#' + modalId).modal('show')});
    
    let myModal = new bootstrap.Modal(document.getElementById(modalId),
                                      {keyboard: false});

    //myModal.dispose();
    myModal.hide();

},
openOtherModal: function(closeModalId, newRoute)
{
    closeModalWindow(closeModalId);
    openModalWindow(newRoute, closeModalId);
},

And prev/next buttons insied modals are:

    <a href="javascript:void(0)" onclick="AdminUI.openOtherModal('clientfile-listby'
                                                                 'list.php/page-1')">
        &lt; Prev.
    </a>
    <a href="javascript:void(0)" onclick="AdminUI.openOtherModal('clientfile-listby'
                                                                 'list.php/page+1')">
        Next. &gt;
    </a>

Google app script -Get the value of first google form response

I have below code that give me the last response submitted from a form.
But this code gives me the values of all the questions in a form but I need the value only for the first question [0] i tried to use the below code but it is not working can someone help

const item = form.getItems()[0];

function getArrayOfLastSubmissionsAnswers() {
var allQuestions,i,itemType,L,thisAnswer,thisQuestion,thisSubmissionsAnswers,number_of_submissions;
   //Define all variables without assigning a value - value at this point
   //is undefined

number_of_submissions = FormApp.openById('your_Form_ID').getResponses().length;
allQuestions = FormApp.openById('your_Form_ID').getResponses()[number_of_submissions - 1].getItemResponses();

L = allQuestions.length;//How many questions are there in the Form
thisSubmissionsAnswers = [];//Create an empty array for answers

for (i=0;i<L;i++) {//Loop through all the questions in this Form submission
thisQuestion = allQuestions[i];//Get this question

itemType = thisQuestion.getItem().getType();

if (itemType === FormApp.ItemType.PAGE_BREAK) {
continue;//keep looping
    };

thisAnswer = thisQuestion.getResponse();//Get the answer
Logger.log(i + " - " + thisAnswer); 

thisSubmissionsAnswers.push(thisAnswer);//add answer to the array
  };

Logger.log("thisSubmissionsAnswers: " + thisSubmissionsAnswers); 

return thisSubmissionsAnswers; 
};

I have the code that give me the last response submitted from a form. But this code gives me the values of all the questions in a form but I need the value only for the first question [0] i tried to use the below code but it is not working can someone help

const item = form.getItems()[0];

Save mongoDb schema objects into a database

We require the schemas not only for defining the structure of our data but also for leveraging features like pre and post hooks, virtuals, and validation. However, instead of defining these schemas directly in our code, we aim to store them in a MongoDB database. Currently, we’re storing the schemas as objects and attempting to retrieve them later to create models and insert data. Unfortunately, this approach isn’t functioning as anticipated.

const mongoose = require('mongoose');
const dotenv = require('dotenv');

dotenv.config({ path: './config.env' });
const app = require('./app');
const { aggregate } = require('./models/taskModel');


mongoose
  .connect(process.env.DATABASE, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: true,
  })
  .then(() => console.log("DB CONNECTED"))
  .catch((err) => console.log("DB CONNECTION ERR", err));

// Define your Mongoose schema
const taskSchema = new mongoose.Schema({
  title: String,
  description: String,
  dueDate: Date,
});

// Extract field information without unnecessary stringification
let serializedSchema = {};
Object.keys(taskSchema.paths).forEach(path => {
  serializedSchema[path] = taskSchema.paths[path].instance;
});

// Store the serialized schema in MongoDB
const storeSchema = async (serializedSchema) => {
  try {
    // Define a schema for storing the serialized schema
    const SchemaSchema = new mongoose.Schema({
      schema: Object, // Use Object type for the schema structure
    });

    // Create a model for the schema collection
    const SchemaModel = mongoose.model('Schema', SchemaSchema);

    // Create a document with the serialized schema and save it to the database
    await SchemaModel.create({ schema: serializedSchema });

    console.log('Schema stored successfully!');
  } catch (error) {
    console.error('Error storing schema:', error);
  } finally {
    // Disconnect from MongoDB
    await mongoose.disconnect();
  }
};

// Store the schema in MongoDB
storeSchema(serializedSchema);


const retrieveSchema = async (_id) => {
  try {
    // Retrieve the stored schema with the specified _id from the 'schemas' collection
    const schemaData = await mongoose.model('Schema').findById(_id);

    if (!schemaData) {
      console.error("Error: Schema not found with the provided _id.");
      return;
    }

    // Extract the actual schema object from the 'schema' field
    const retrievedSchema = schemaData.schema;

    // Remove the unnecessary _id field if present (recommended for clarity)
    delete retrievedSchema._id;

    return retrievedSchema;
  } catch (error) {
    console.error("Error retrieving schema:", error);
  } finally {
    // Disconnect from MongoDB (recommended for proper database handling)
    await mongoose.disconnect();
  }
};

// Example usage: Retrieve the schema with _id 65cdaec1b8f0a534282aee97
const _idToRetrieve = "65cdaec1b8f0a534282aee97";


retrieveSchema(_idToRetrieve)
  .then(async (retrievedSchema) => {
    if (retrievedSchema) {
      // Ensure schema is in object format, if necessary
      if (typeof retrievedSchema === 'string') {
        retrievedSchema = JSON.parse(retrievedSchema);
      }

      // Define a generic schema
      const genericSchema = new mongoose.Schema(retrievedSchema);

      // Create a generic model from the schema
      const GenericModel = mongoose.model('GenericModel', genericSchema);

      // Prepare data to insert
      const data = {
        title: "Example Task",
        description: "This is a test task.",
        dueDate: new Date(),
      };

      // Create and save a new document
      const newDocument = new GenericModel(data);
      await newDocument.save();
      console.log("Data inserted successfully!");
    } else {
      console.error("Error: Schema not found.");
    }
  })
  .catch((error) => {
    console.error("Error:", error);
  });

const port = process.env.PORT || 8000;
app.listen(port, () => {
  console.log(`App running on port ${port}...`);
});
 ``