Contador de hashtags

Estoy investigando para hacer un contador de hashtags de Facebook, Instagram ,Twitter , TikTok la idea es que de un hashtag en especifico que se este utilizando en estas redes sociales , vaya contando automáticamente cuantos hay , he estado mirando para conectarme desde la api , pero solo he visto en la api de Twitter un buscador de publicaciones que incluso cuesta dinero por su uso, pero en las demás no he logrado encontrar nada de eso , no se si sea posible o alguno se le ocurre como podrá realizarse , soy nuevo en esto.

He intentado conectarme desde las api pero no encuentro opciones lo único que encontré fue en la api de Twitter pero no me dejaba usarlo ya que me pedía un nivel mas alto en la cuenta que se esta haciendo el desarrollo lo cual cuesta mucho dinero

problem parsing an xml stream with multiple text items each containing a title and description

This is what I have created. It appears the script never gets to the Data:

!DOCTYPE html>
<html>
<head>
    <title>XML Feed </title>
    <script>
        // Fetch and parse the XML feed
        function fetchXMLFeed() {
            fetch('https://solidsports.com.au/scores/Venue_GPS/live/Scores.xml')
                .then(response => response.text())
                .then(data => {
                    const parser = new DOMParser();
                    const xmlDoc = parser.parseFromString(data, 'text/xml');
                    const items = xmlDoc.getElementsByTagName('item');
                    
                    // Iterate through each item and display the description for the needed titles 
                    let descriptionContainer = document.getElementById('description-container');
                    for (let i = 0; i < items.length; i++) {
                      let title = items[i].getElementsByTagName('title')[0].textContent;
                      let descript = items[i].getElementsByTagName('description')[0].textContent;
                        
                      if (`your text`title === 'AwayPoints') {
                  descriptionContainer.textContent = descript;
                          break;
                        }
                    }
                })
                .catch(error => {
                    console.error('Error fetching XML feed:', error);
                });
        }
    </script>
</head>
<body onload="fetchXMLFeed()">
    <h2>Description for Item with Title "AwayPoints":</h2>
    <div id="description-container"></div>
</body>
</html>

the html code does not provide any output
I have tried adding elements within the Data =>{} construct and displaying them in the html. It appears the script never gets to the data.
I am sure there is something simple I am not doing, but being new to this I can’t figure it out.
Any help or comments would be greatfully received.
Thanks

No ‘Access-Control-Allow-Origin’ header is present on the requested resource for amazon S3

I am using reactjs and axios

I have this error when fetching the png from S3 to the local environment.

Access to fetch at 'https://xxx-xxx-xxx.s3.ap-northeast-1.amazonaws.com/0.png' from origin 'http://localhost:8021' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I try to send header

 let headers = new Headers();
 headers.append('Access-Control-Allow-Origin','*');
 headers.append('Access-Control-Allow-Credentials', 'true');
 fetch(fileUrl,{headers: headers}).then(function(response){
 })

and S3 has this CORS setting.

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET",
            "POST",
            "PUT"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": [
            "ETag"
        ],
        "MaxAgeSeconds": 3000
    }
]

Somehow my header is not sent correctly or am I wrong anywhere else?


Another trial

I install npm install http-proxy-middleware

and make src/setupProxy.js

const { createProxyMiddleware } = require("http-proxy-middleware");
console.log("setup is called");
module.exports = function (app) {
  app.use(
    "/",
    createProxyMiddleware({
      target: "https://quc-local-admin-bk.s3.ap-northeast-1.amazonaws.com",
      changeOrigin: true,
    })
  );
};

then server start with webpack --mode development --watch

However nothing changes. and console.log("setup is called"); is not called

How can I solve this?

React: How to calculate a value and pass to parent so that siblings can use it?

Imagine I have some logic that looks like this:

items = [1, 1, 2, 3, 1];
count = 0;
items.map((x) => {count += x; return count;})  // expected: [1, 2, 4, 7, 8]

Now I want to implement this in React, where a Parent component is responsible for rendering the whole array, and a Child component is responsible for rendering one item.

Admittedly, I’m new to React and unfamiliar with the inner workings, but my natural instinct is to somehow create a variable that can be passed back and forth between Parent and Child, where the Child is responsible for doing the count += x bit. Yet I just can’t find a way to get it to work.

So far I have:

  • Looked up various StackOverflow questions on “how to pass a value back to parent” but all of them seem to be about events (such as onClick). I’m not updating a value based on events, I just want to update the value in a loop.
  • Tried to mess with states but honestly I have no idea what’s going on and sometimes after changing one line of code my browser hangs and I have to kill it with task manager.
  • Considered giving up just moving the calculation to Parent and make Child only responsible for rendering, however this feels ugly because 1) the logic of “handling one item” is not encapsulated in one place and 2) it means that I will need to iterate through the loop twice.

The closest I have to working is this:

function Child({ item, addCount }) {
  const newCount = addCount(item);
  return <div>{newCount}</div>;
}

function Parent({ items }) {
  let count = 0;
  const addCount = (x) => {
    count += x;
    return count;
  };
  return items.map((item) => <Child item={item} addCount={addCount} />);
}

function App() {
  const items = [1, 1, 2, 3, 1];
  return (
    <Parent items={items} />
  );
}

However the result I get is [2, 4, 8, 14, 16], which means each Child is called twice. Again I am new to React and I don’t know what’s going on behind the scenes. I don’t even know if using a let variable this way would cause problems or not.

Any ideas or suggestions? What’s the “correct” way to implement something like this?

How to cache a page that was generated primarily in javascript?

I have some pages in my website that are quite heavy in javascript and calculations, querying APIs, rendering, etc. Is there any way to cache the page on the server for example 2 weeks? I want to avoid the enormous hit of recalculating these pages each time it is visited. Also, I have a dynmic map on the page which I asssume should not be cached.

I have googled this topic but it seems that most answers are about caching the script rather than the generated page.

Also, this is all done in wordpress 6.2

Allowing selective script loading in iframes using the ‘sandbox’ attribute

I was reading about Iframe and it looks like there is an attribute called sandbox that can prevent all the scripts from loading, however, I want to allow all the scripts except one, so is that possible?

In other words, My question is how can I allow all scripts to load in an iframe except for one using the ‘sandbox’ attribute? If not possible, what are alternative solutions to prevent the loading of specific scripts when using an iframe? Are there any alternatives to using iframes altogether?

How to clear a users image cache when the page loads

I am running a website where images get updated automatically and very frequently. The image src’s stay the same but the contents of the src change. For example, I could have an image src of animal.png, but I may switch the image from a tiger to an elephant.

The problem is the cache is holding onto those previous images even when they update in the background. Is there a way to force the browser to clear the image cache when the page loads. My website is coded in .html .css and .js

Discord.Js intents

My bot isnt responding to any of my commands can you look to see where I went wrong? I think it might be the intents but I am not sure. I followed the discord guide and some posts on here to just have all intents declared. Do I need to list them individually or does my current way work?

require('dotenv').config();
const Discord = require('discord.js');
const sqlite3 = require('sqlite3').verbose();
const { Client, GatewayIntentBits } = require("discord.js");
const client = new Client({
    intents: Object.keys(GatewayIntentBits).map((a)=>{
        return GatewayIntentBits[a]
    }),
});

const prefix = "!";

let db = new sqlite3.Database('./keywords.db', (err) => {
    if (err) {
        return console.error(err.message);
    }
    console.log('Connected to the SQlite database.');

    db.run(`CREATE TABLE IF NOT EXISTS keywords (
    keyword TEXT,
    channelOrCategory TEXT,
    role TEXT,
    author TEXT,
    thumbnail TEXT,
    color TEXT,
    message TEXT
  );`, (err) => {
        if (err) {
            console.log('Error creating table', err);
        }
    });
});

// Set a cooldown for mentions in each channel
let cooldowns = new Map();

client.on('ready', () => {
    console.log(`Bot is ready as: ${client.user.tag}!`);
});

client.on('message', async message => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).trim().split(/ +/);
    const command = args.shift().toLowerCase();

    if (command === 'keyword') {
        const subCommand = args.shift();
        if (subCommand === 'add') {
            // Check if the user has 'ADMINISTRATOR' permission
            if (!message.member.hasPermission('ADMINISTRATOR')) {
                return message.reply('You do not have permission to use this command.');
            }

            const keyword = args.shift();
            const channelOrCategory = args.shift();
            const role = message.mentions.roles.first();

            if (!keyword || !channelOrCategory || !role) {
                message.reply('Please provide a keyword, a channel or category, and mention a role.');
                return;
            }

            db.run(`INSERT INTO keywords(keyword, channelOrCategory, role) VALUES(?, ?, ?)`, [keyword, channelOrCategory, role.name], function(err) {
                if (err) {
                    return console.log(err.message);
                }
                message.reply(`Keyword "${keyword}" is now set for the channel/category "${channelOrCategory}" with role "${role.name}".`);
            });
        } else if (subCommand === 'delete') {
            const keyword = args.shift();

            if (!keyword) {
                message.reply('Please provide a keyword to delete.');
                return;
            }

            db.run(`DELETE FROM keywords WHERE keyword = ?`, keyword, function(err) {
                if (err) {
                    return console.log(err.message);
                }
                if (this.changes > 0) {
                    message.reply(`Keyword "${keyword}" has been deleted.`);
                } else {
                    message.reply(`Keyword "${keyword}" not found.`);
                }
            });
        } else if (subCommand === 'list') {
            db.all(`SELECT * FROM keywords`, [], (err, rows) => {
                if (err) {
                    throw err;
                }
                let reply = 'Here are the keywords currently being monitored:n';
                rows.forEach((row) => {
                    reply += `Keyword: ${row.keyword}, Channel/Category: ${row.channelOrCategory}, Role: ${row.role}n`;
                });
                message.reply(reply);
            });
        }
    } else if (command === 'embed') {
        // Check if the user has 'ADMINISTRATOR' permission
        if (!message.member.hasPermission('ADMINISTRATOR')) {
            return message.reply('You do not have permission to use this command.');
        }

        const keyword = args.shift();
        const author = args.shift();
        const thumbnail = args.shift();
        const color = args.shift();
        const messageContent = args.join(" ");

        if (!keyword || !author || !thumbnail || !color || !messageContent) {
            message.reply('Please provide a keyword, author, thumbnail url, color, and message.');
            return;
        }

        db.run(`UPDATE keywords SET author = ?, thumbnail = ?, color = ?, message = ? WHERE keyword = ?`, [author, thumbnail, color, messageContent, keyword], function(err) {
            if (err) {
                return console.log(err.message);
            }
            if (this.changes > 0) {
                message.reply(`Embed updated for keyword "${keyword}".`);
            } else {
                message.reply(`Keyword "${keyword}" not found.`);
            }
        });
    } else if (command === 'help') {
        message.channel.send(`
      Here are the commands you can use:

      +keyword add <keyword> <channel/category> @role - Adds a keyword to the database which triggers a role ping when found in a specific channel or category in an embed's title, description, or footer.
      +keyword delete <keyword> - Deletes a keyword from the database.
      +keyword list - Lists all keywords currently being monitored and their associated channels or categories.
      +embed <keyword> <author> <thumbnail> <color> <message> - Sets a custom embed message for a keyword. The <color> should be a hex color code.
      +help - Shows this help message.
    `);
    }
});

client.on('message', message => {
    if (!message.embeds.length) return;

    message.embeds.forEach(embed => {
        db.all(`SELECT * FROM keywords`, [], (err, rows) => {
            if (err) {
                throw err;
            }

            rows.forEach((row) => {
                if ((embed.title && embed.title.includes(row.keyword)) ||
                    (embed.description && embed.description.includes(row.keyword)) ||
                    (embed.footer && embed.footer.text.includes(row.keyword)) &&
                    (message.channel.name === row.channelOrCategory || message.channel.parent.name === row.channelOrCategory)) {
                    // If a mention has already been made in the last 15 seconds, don't mention again
                    if (cooldowns.get(message.channel.id)) return;
                    // Set a cooldown for the channel
                    cooldowns.set(message.channel.id, Date.now());

                    if (row.author && row.thumbnail && row.color && row.message) {
                        // Send a custom embed if one exists
                        const embedMessage = new Discord.MessageEmbed()
                            .setColor(row.color)
                            .setAuthor(row.author)
                            .setThumbnail(row.thumbnail)
                            .setDescription(row.message);
                        message.channel.send(embedMessage);
                    } else {
                        // Send a role mention if no custom embed exists
                        const role = message.guild.roles.cache.find(role => role.name === row.role);
                        if (role) {
                            message.channel.send(`${role} keyword found!`);
                        }
                    }

                    // Remove the cooldown after 15 seconds
                    setTimeout(() => {
                        cooldowns.delete(message.channel.id);
                    }, 15000);
                }
            });
        });
    });
});

client.login(process.env.DISCORD_BOT_TOKEN);

Was expecing it to respond to commands, it appears online but nothing happens.

Disable Button For X Seconds After Page Load With Error Message If Clicked Too Early

I’m trying to delay the functionality of a Submit button for a few seconds after a page loads. That part I have working.

Where I’m stuck is I’d like an “error” message to appear if the button is clicked while it’s disabled. And then have the message disappear once the button is no longer disabled.

I’m having trouble getting this to work. My thought was to use a “click” event listener, which doesn’t work while the button id disable — which defeats the purpose.

Here’s the html

<input type="submit" class="submitbtnstyle" id="submitbnid" value="Next"></input>
<div id="button-error"></div>

Here’s the working disable/enable function…

window.onload = (submitDelay);

function submitDelay(){
    document.getElementById("submitbnid").disabled = true;
    
    setTimeout(function() {
        document.getElementById("submitbnid").disabled = false;
    }, 3000);
    
}

And here’s the error message that I haven’t quite figured how to make work with the disable button and/or combine with the above script.

document.getElementById("submitbnid").addEventListener("click", ButtonError);

function ButtonError(){
        document.getElementById('button-error').innerHTML = 'Oops, Too Fast. Try Again in 2 seconds.';

        setTimeout(function() {
        document.getElementById('button-error').innerHTML = '';
    }, 3000);
    
}

For reference, the purpose of this delay is because I have a hidden form field that dynamically updates the value after searching/finding an id in a first-party cookie that is set in the browser. There is a slight delay placed for this process as the cookie has to be first set prior to searching for and adding this id.

So perhaps a better strategy is not to arbitrarily disable the submit button for x seconds, but rather somehow check to see if the id is updated in the hidden field. But I’m not entirely sure how to go about that approach. So I’m resorting to a 3 second delay, which should not cause an issue for the majority of users.

window.onload = (submitDelay);

function submitDelay() {
  document.getElementById("submitbnid").disabled = true;

  setTimeout(function() {
    document.getElementById("submitbnid").disabled = false;
  }, 3000);

}

document.getElementById("submitbnid").addEventListener("click", ButtonError);

function ButtonError() {
  document.getElementById('button-error').innerHTML = 'Oops, Too Fast. Try Again in 2 seconds.';

  setTimeout(function() {
    document.getElementById('button-error').innerHTML = '';
  }, 3000);
}
<input type="submit" class="submitbtnstyle" id="submitbnid" value="Next"></input>
<div id="button-error"></div>

Generating sound in browser at interval

I would like to schedule a sound to be produced at a certain interval in a web app. A sample code is below. Please note that I also tried using Web Audio APIs with exactly the same problem I will be describing here. First, the code:

export default class BeepPlayer {
  constructor(interval) {
    this.audio = new Audio()
    this.audio.src = 'src/assets/sounds/metronomeClick.wav'
    this.interval = (60 / interval) * 1000
    this.intervalID = null

    console.log('interval: ' + this.interval)
  }

  play() {
    this.intervalID = setTimeout(this._playSound.bind(this), this.interval)
  }

  _playSound() {
    console.log('beep')
    this.audio.play()

    clearTimeout(this.intervalID)
    this.intervalID = setTimeout(this._playSound.bind(this), this.interval)
  }

  stop() {
    clearTimeout(this.intervalID)
    this.audio = null
  }
}

if I construct the object with an interval of 60, play() will sound every 1 second.

if I construct the object with an interval of 30, play() will sound every 2 seconds but skips the first beep.

if I construct the object with an interval of 20, play() will sound every 3 seconds but skips the first beep.

if I construct the object with an interval of 15, play() will not produce any sound.

I have no idea why there is a threshold at around the 3-second mark and why even the Web Audio API code which does not even load an audio file behaves the same way.

Any thoughts on how I can overcome this bizarre issue would be appreciated.

thanks.

How to deal with this string that needs to be sent into a JSON + API?

I receive strings coming from an external source. Most of them work nice. In the past I had some issues with some special characters in the strings that gave error when tried to parse them into a JSON to send an API, but was solved using this regex: [^a-zA-Z0-9s]+

Recently I came with some errors that even using the regex were escaping and giving an error. Tried to use this another regex (it looks like it’s a tab): [^a-zA-Z0-9st]+

Still having issues. This useful page: https://www.soscisurvey.de/tools/view-chars.php detects the character as:
9
0x09

This is where the JSON has the weird character:

"Description": { "esp": "   Minimizer BraStyle 2357 Blush  36F", "spa": "   Minimizer BraStyle 2357 Blush  36F", "eng": "   Minimizer BraStyle 2357 Blush  36F" }

Any ideas?
Edit: seems stackoverflow editor is “fixing” the weird character, so if you copy-paste it from the editor it won’t work. This is a jsfiddle with that weird characters: https://jsfiddle.net/b1fmk53d/

I can’t insert values into arrays without “item[index]”, according to an exercise I’m doing

I’m having a lot of difficulty with this Javascript exercise, I’ve tried for hours and hours, would you know how to help me?:

  • Below the “randomNumbers” array, use a for loop to generate 2 new ones
    arrays: an array with only odd numbers from “randomNumbers” and another array with only even numbers;

    • After that, using the two arrays you created, display the sentence below in the console, replacing “XX, XX and XX” by the correct numbers. Phrase numbers must not be inserted with the “item[index]” notation and the “e” before the last odd number and the last even number must appear in the sentence;
  • Hint: to know if a number is even, the remainder of its division by 2 must
    be 0.

    “Odd numbers: XX, XX and XX. Even numbers: XX, XX and XX.”

const randomNumbers = [73, 4, 67, 10, 31, 58]

I’m having a lot of difficulty with this Javascript exercise, I’ve tried for hours and hours, would you know how to help me?:

  • Below the “randomNumbers” array, use a for loop to generate 2 new ones
    arrays: an array with only odd numbers from “randomNumbers” and another array with only even numbers;

    • After that, using the two arrays you created, display the sentence below in the console, replacing “XX, XX and XX” by the correct numbers. Phrase numbers must not be inserted with the “item[index]” notation and the “e” before the last odd number and the last even number must appear in the sentence;
  • Hint: to know if a number is even, the remainder of its division by 2 must
    be 0.

    “Odd numbers: XX, XX and XX. Even numbers: XX, XX and XX.”

const randomNumbers = [73, 4, 67, 10, 31, 58]

Command not found when ran with execSync in github Codespace

I am using a github codespace to test a discord.js bot. In it i use the command fortune | cowsay which uses the fortune and cowsay commands, the fortune command is installed with sudo apt install fortune-mod and cowsay with sudo apt install cowsay. Their install directory is under “/usr/games” and not “/bin” therefore when I run the command fortune | cowsay I get

bash: fortune: command not found
bash: cowsay: command not found

This is because in Github codespaces /usr/games is not in the $PATH

When I added “/usr/games” to the path in both “/etc/profile” and “~/.profile” using
export PATH="/usr/games:$PATH"put at the bottom of both the files and then used the command “source /etc/profile” and in later testing “source ~/.profile” The commands work… but it is when I try to run the file using VScode’s built in runner (hitting f5 and clicking on node.js) where it automatically makes a new shell and uses node to run the file it commands not found.

I am wondering how GitHub codespaces makes their new shells without the new path I added. And how I might be able to add the /usr/games directory to the path for the new shell that opens when vscode runs the file