i create time using tolocalString() and then i use this code to change the color every sec but it work only last color not for all

i create time using tolocalString() and then i use this code to change the color every sec but it work only last color not for all

var time=document.getElementById("time");


setInterval(function(){
    var da=new Date();
var ti=da.toLocaleTimeString();
// console.log("yes");
time.innerHTML=ti;
},1000);

setInterval(function(){
var arr=["red","blue","green"];
 var i=Math.floor(Math.random() * 2) + 1;
//  console.log(i);
    time.style.color=time.classList.add(arr[i]);
    console.log(i);

},1000);

How do I write a Map to a text file in JavaScript?

I am trying to write the contents of a Map to a text file, but am getting an error. Here is my code:

const dictionary = new Map()
dictionary['foo'] = 10
dictionary['test'] = 5
dictionary['sample'] = 7
require('fs').writeFile('textFile.txt', dictionary, (error) => {
    if(error) throw err
})

The error I get says that I cannot write a Map as the ‘data’ argument must be of type string or an instance of Buffer, TypedArray, or DataView. Is there a way that I can write the contents of my Map to the ‘textFile.txt’ file?

How to access Firebase Realtime Database through a REST API

right now I am using firebase in a react project with some cloud functions. The react app writes and listens to updates from the firebase database in real time through the javascript sdk. However, I’d like to move all my backend logic to a REST API. Howver, I am stuck wondering how I’d subscribe to realtime updates on the database without accessing the database directly on the client. Is there an existing way to do this currently?

ReCaptcha missing styling on every Apple Devices

Hi every I hope your doing well, I’m having an issue with my re-captcha and some how the missing styling it happens on every Apple Devices while THE desktop and android devices are working fine. I’d like to know your all thought on this issue. Thank you.

enter image description here

I use the basic usage of react-google-recaptcha:

import ReCAPTCHA from "react-google-recaptcha";

function onChange(value) {
  console.log("Captcha value:", value);
}

ReactDOM.render(
  <ReCAPTCHA
    sitekey="Your client site key"
    onChange={onChange}
  />,
  document.body
);

Unit testing for JavaScript in the context of a web application

I’ve done some research about this topic, and I think I know what to do. However, as per my understanding this requires confusing or complex configuration.

Objective:

Ability to perform unit testing for JavaScript code that is used within the context of a web application.

The JavaScript functions are deployed in script file and linked to the HTML page using traditional methods.

We need to used a simple Unit Testing Framework similar to Jest and avoid the need to get into Brower Control such as using Selenium WebDriver and the like.

The problem is Jest works with NodeJS and not sure how to make this work with front-end web application.

High-Level Approach:

Based on my research, it seems I have to keep the script used for the web application in a separate configuration of the test project. See example below:

//Main JavaScript used by HTML: sciprt.js
function addTwoNumbers(a, b) {
  return a+b;
}
...
...
other functions
...
...
<!DOCTYPE html>
<html>
<body>

<h1>The script src attribute</h1>

<script src="script.js">
</script>

</body>
...
...
</html>

Now let’s say we need to used Jest to write test scripts, then we have to setup a NodeJS project which means we have to copy the script file script.js to the test project, and convert it to use JavaScript Modules.

I am trying to avoid this confusing setup, and looking for a method to write test scripts to use the same deployed parts of the web application without the need to mess around with files.

Another problem I will face is how to deal with functions that references HTML components? Those will not be available to NodeJS, correct? I believe this can be done by refactoring the code to become modular so that the functions to be tested will not reference web elements.

I appreciate your help to setup a test project and use the deployed script and avoid the need to do complex or confusing setup.

How can I keep track of a variable in android app?

when user enter to the app he chose team 1 (Brazil)or team 2(Argentine) after that he chose yellow or red card then he chose a player after that in the first page it will show the player number and color of card.

enter image description here

My Question is How can keep track of the number of card and instead of showing player number I show how many either yellow or red card does team have .

CardActivity

public class CardActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_card);
}

private void setCardData(int card) {
    SharedPreferences settings getApplicationContext().getSharedPreferences("MainThisApp", 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putInt("card", card);
    editor.apply();

    Intent intent = new Intent(this, Myapp.game.NumberActivity.class);
    startActivity(intent);
}

public void setRedCard(View view) {

    ((Variable) this.getApplication()).setSomeVariable("card_yellow");

    setCardData(0);
}

public void setYellowCard(View view) {

    ((Variable) this.getApplication()).setSomeVariable("card_red");

    setCardData(1);
}}

MainActivity

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SharedPreferences prefs = getApplicationContext().getSharedPreferences("MainThisApp", 0);
    int check = prefs.getInt("check", 0);

    String s = ((Variable) this.getApplication()).getSomeVariable();
    try{
        Integer number = Integer.valueOf(s);
        System.out.println(number);
    }
    catch (NumberFormatException ex){
        ex.printStackTrace();
    }

    if (check == 50) {
        TextView view = null;
        int country = prefs.getInt("country", -1);
        int card = prefs.getInt("card", -1);

        if (country == 0 & card == 0) {

            view = findViewById(R.id.textView4);
        }
        if (country == 0 & card == 1) {

            view = findViewById(R.id.textView3);
        }
        if (country == 1 & card == 0) {

            view = findViewById(R.id.textView2);

        }
        if (country == 1 & card == 1) {

            view = findViewById(R.id.textView);
        }
        view.setText(String.valueOf(prefs.getInt("number",1)));
    }

}

public void chooseBrasil(View view) {
    setCountryData(0);
}

private void setCountryData(int country) {
    SharedPreferences settings = getApplicationContext().getSharedPreferences("MainThisApp", 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putInt("country", country);
    editor.apply();
    Intent intent = new Intent(this, CardActivity.class);
    startActivity(intent);
}
public void chooseArgentine(View view) {
    setCountryData(1);
}

NumberActivity

public class NumberActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_number);
    }

private void setNumberData(int number) {
    SharedPreferences settings = getApplicationContext().getSharedPreferences("MainThisApp", 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putInt("number", number);
    editor.putInt("check", 50);
    editor.apply();
    Intent intent = new Intent(this, MainActivity.class);
    startActivity(intent);
}

public void setNumber1(View view) {
    setNumberData(1);
}

public void setNumber2(View view) {
    setNumberData(2);
}

public void setNumber3(View view) {
    setNumberData(3);
}

public void setNumber4(View view) {
    setNumberData(4);
}

public void setNumber5(View view) {
    setNumberData(5);
}

public void setNumber6(View view) {
    setNumberData(6);
}

public void setNumber7(View view) {
    setNumberData(7);
}

public void setNumber8(View view) {
    setNumberData(8);
}

Dark Mode Function

I created a dark mode function that allows me to use local storage to “save” the last selected preference the user chose by clicking on an icon even if they go to different pages within the site, refresh, close, etc. What I can’t figure out is how I can add an if statement so that the icon will also chance its “src” into a different png file when the “darkmode” is enabled and then switch back to another icon when it is disabled. If anyone could help me with this I would very much appreciate it.

let darkMode = localStorage.getItem('darkMode'); 

const darkModeToggle = document.querySelector('#dark-mode-toggle');

const enableDarkMode = () => {
  document.body.classList.add('darkmode');
  localStorage.setItem('darkMode', 'enabled');
}

const disableDarkMode = () => {
  document.body.classList.remove('darkmode');
  localStorage.setItem('darkMode', null);
}

if (darkMode === 'enabled') {
  enableDarkMode();
}


darkModeToggle.addEventListener('click', () => {
  darkMode = localStorage.getItem('darkMode');
  
  if (darkMode !== 'enabled') {
    enableDarkMode();

  } else {  
    disableDarkMode(); 
  }
});

const scrollBtn = document.getElementById("scroll_up")

    scrollBtn.addEventListener("click", () => {
        document.documentElement.scrollTop= 0;
    });

How to send data from popup.js to content.js in a Chrome Extension

I am making a chrome extension that will auto fill a input on a page (the outlook subject line in this case), and I need to somehow pass the message that I get from the input on popup.js (the extension), into the content.js so that I can update the DOM on that page.

GitHub repo here

popup.html

<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div class="container">
        <input type="text" id="message" name="message" placeholder="Enter a message..." class="message-input">
        <input type="submit" value="Set new message" id="message-btn" class="message-btn">
    </div>
</body>
<script src="popup.js"></script>

</html>

popup.js

let messageInput = document.getElementsByClassName('message-input')[0];
let updateMessageBtn = document.getElementById('message-btn');

updateMessageBtn.addEventListener('click', async(messageInput) => {
        // Query tab
    let queryOptions = { active: true, currentWindow: true };
    let tabs = await chrome.tabs.query(queryOptions);

    // Open up connection
    const port = chrome.tabs.connect(tabs[0].id, {
        name: "uiOps",
    });

        port.postMessage({
            message: messageInput.value
        });

            port.onMessage.addListener(function(msg) {
        if (msg.exists) {
            alert('Exists');
        } else {
            alert("Doesn't exist");
        }
    })
});

content.js

chrome.runtime.onConnect.addListener(function (port) {
  port.onMessage.addListener(function (msg) {
    if (port.name === "uiOps") {
      const idToQuery = msg.message;
      if (idToQuery) {
        port.postMessage({
          exists: true,
        });
      } else {
        port.postMessage({
          exists: false,
        });
      }
    }
  });
});

manifest.json

{
    "name": "Email Autofiller",
    "description": "Automatically fill email subject lines!",
    "version": "1.0",
    "manifest_version": 3,
    "permissions": ["storage", "activeTab", "scripting"],
    "action": {
        "default_popup": "popup.html",
        "default_icon": {
        "16": "/images/get_started16.png",
      "32": "/images/get_started32.png",
      "48": "/images/get_started48.png",
      "128": "/images/get_started128.png"
    }
    },
      "icons": {
    "16": "/images/get_started16.png",
    "32": "/images/get_started32.png",
    "48": "/images/get_started48.png",
    "128": "/images/get_started128.png"
  }
}

I’ve tried a ton of different things, including trying to use localstorage, which didn’t work. I think I’m on the right track, but the Google Chrome Extension docs are confusing me a little. Any help is appreciated – thanks!

Can I fetch data from a json that is in dropbox

The goal is to store json files on an external server. I’m going to fetch data and show in my react native app. The files won’t be adjusted often. It’s a static data.

The first thing that came to mind is to keep those json files on some file hosting. But I was trying to explore the option of doing the same thing with dropbox.

The get_metadata request https://api.dropboxapi.com/2/files/get_metadata only provides metadata (obviously).

get_preview also won’t give me what I need.

Is there a way to store json files in dropbox and read them with react native?

In general should routes be placed before or after middleware?

Oddly, when I moved my middleware in front of my routes, my routes stopped working. I got no error, on the client or the server.

My fetch() calls seemingly disappeared.

However when I put the routes before my middleware, the routes begin to work again.

I’m refactoring code and have no idea why this is happening.

// load middleware
const middleware = require(__dirname +'/middleware');
app.use(middleware.session.session);
...

// load routes
const routes = require(__dirname + '/routes');
app.use('/articles', routes.articles);
...

Get file extention using only file name in javascript

I am creating a discord bot (irrelevent) that sends images into the chat. The user can type out the name of the image without needing to type the file extention. The problem is that the bot doesn’t know what the file extention is so it will crash if the picture is a .jpg and the program was expecting a .png. Is there a way to make the program not require a file extention to open the file?

let image = imageName;
message.channel.send({ files: [`media/stickers/${imageName}.png`] });

Heroku not finding endpoint with Express

So I created this local host app I am trying to deploy to Heroku with express and for some reason it works on localhost but not on the Heroku API, getting 502, if someone could help that would be awesome!

app.listen(process.env.PORT || 3000, () => console.log('listening at 3000'));
app.use(express.static('public'));
app.use(express.json({ limit: '5mb' }));
const database = new Datastore('database.db');
database.loadDatabase();
app.get('/api', (request, response) => {
database.find({}, (err, data) => {
if (err) {
  response.end();
  return;
}
response.json(data);
});
});

Wondering why this occurring to be honest, deployed many apps with the same setup and never had it happen like this. The package.json has all the proper NPM packages aswell

is there a way to filter this request with mongoose?

I need to make a query of all products but only with the category status in true,
The model of my products is something like this:

const ProductSchema = Schema({
name : {type: String},
category: {type: Schema.Types.ObjectId, ref: 'Category'}
})

Normally I would just make a query and then a filter for the products with category.status === true, but the thing is that I’m using pagination and due to the filter my page of 15 products ends up with fewer products than 15 obviously because of the filter, so I really don’t know if I can make the filter with a population in the query, maybe something like this:

const query = await Product.find().populate('category', 'name status')
.select(['-cost']).where('category.status')
.equals(true).skip(0).limit(15)

but sadly it doesnt work, is there a way to do it or should i give up?