async function foo() {
return await db.collection("users").find({user_id:id}).toArray();
}
async function bar() {
await foo()
}
Do I need both awaits here or can I remove one of them? If so which await should I remove?
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
async function foo() {
return await db.collection("users").find({user_id:id}).toArray();
}
async function bar() {
await foo()
}
Do I need both awaits here or can I remove one of them? If so which await should I remove?
I need to call a method from within a JavaScript file using execjs in python. This file has many window and document calls. So, execjs is not able to compile it. Is there any way to bypass this limitation of execjs? I only need one method from within the file but it has so many other methods it calls which call other methods. Anyway, here is what I have tried so far:
window and document variables. Though, adding/fixing something would break another. So, I finally gave up.promises and the script uses those. I cannot use selenium because of my special use case. I want a solution small in size and also portable.Your feedback is appreciated.
`I’m working on a React project where I need to fetch anime information based on an alphanumeric ID from the URL. The ID can contain letters, numbers, and special characters (e.g., high-school-dxd-1834).
I’m using react-router-dom to extract the ID from the URL and axios to make the API request. While the setup works perfectly with numeric IDs (e.g., 1234), it fails with alphanumeric IDs (e.g., high-school-dxd-1834).
Here’s what happens:
With Numeric IDs:
URL: http://localhost:3000/anime/1234
The ID 1234 is extracted correctly and the API request succeeds, returning the expected anime information.
API request: https://mellieapi2.vercel.app/anime/info?id=1234
Status: 200 OK
With Alphanumeric IDs:
URL: http://localhost:3000/anime/high-school-dxd-1834
The ID high-school-dxd-1834 is extracted correctly, but the API request fails with a 404 Not Found error.
API request: https://mellieapi2.vercel.app/anime/info?id=high-school-dxd-1834
Status: 404 Not Found
I’ve verified that the ID is correctly extracted and URL-encoded before making the API request. The API documentation indicates that it should handle both numeric and alphanumeric IDs, but it seems to fail for the latter.
I’ve attempted the following solutions without success:
Encoding the ID: Using encodeURIComponent to ensure the ID is properly encoded.
Direct API Testing: Manually testing the API with alphanumeric IDs to verify if the issue lies with the API.
Error Handling: Adding error handling to log and understand any errors returned by the API.`
AnimeInfo.js:
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Typography, Card, CardMedia, CardContent, CircularProgress } from '@mui/material';
import { useParams } from 'react-router-dom';
const AnimeInfo = () => {
const { id } = useParams(); // Extract 'id' from the URL
const [anime, setAnime] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
console.log(`Extracted ID from URL: ${id}`); // Log the ID
if (id) {
const encodedId = encodeURIComponent(id); // Encode the ID
const fetchAnimeInfo = async () => {
try {
const response = await axios.get(`https://mellieapi2.vercel.app/anime/info?id=${encodedId}`);
setAnime(response.data);
setLoading(false);
} catch (error) {
setError(error);
setLoading(false);
}
};
fetchAnimeInfo();
} else {
setLoading(false);
setError('Invalid ID');
}
}, [id]);
if (loading) return <CircularProgress />;
if (error) return <Typography variant="body1" color="error">Error fetching anime info: {error.toString()}</Typography>;
if (!anime) return null;
return (
<Card>
<CardMedia
component="img"
height="auto"
image={anime.poster}
alt={`${anime.name} poster`}
/>
<CardContent>
<Typography variant="h4">{anime.name}</Typography>
<Typography variant="body1" paragraph>
{anime.description}
</Typography>
<Typography variant="body2">Rating: {anime.stats.rating}</Typography>
<Typography variant="body2">Sub Episodes: {anime.stats.episodes.sub}</Typography>
<Typography variant="body2">Dub Episodes: {anime.stats.episodes.dub}</Typography>
<Typography variant="body2">Duration: {anime.stats.duration}</Typography>
</CardContent>
</Card>
);
};
export default AnimeInfo;
App.js:
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import AnimeInfo from './components/AnimeInfo';
function App() {
return (
<Router>
<Switch>
<Route path="/anime/:id" component={AnimeInfo} />
<Route path="*">
<div>404 Not Found</div>
</Route>
</Switch>
</Router>
);
}
export default App;
`ID Extraction and Encoding:
Expected the id to be correctly extracted from the URL using useParams.
Expected the encodeURIComponent function to encode the ID properly, ensuring it is safe for use in the URL.
Making the API Request:
Expected the API request to succeed and return the anime information for both numeric and alphanumeric IDs.
For example, navigating to http://localhost:3000/anime/high-school-dxd-1834 should make a successful API call and display the corresponding anime information.
Direct API Testing:
Expected the API to handle both numeric and alphanumeric IDs correctly when tested directly.
Anticipated a successful response (status 200) with the expected data for IDs like high-school-dxd-1834.
Reviewing API Documentation:
Expected to find confirmation that the API supports alphanumeric IDs and any specific constraints or formats required.
Actual Outcome:
With Numeric IDs:
The ID is extracted, encoded, and the API request succeeds, returning the expected anime information.
With Alphanumeric IDs:
The ID is extracted and encoded correctly, but the API request fails with a 404 Not Found error.
Direct API testing confirms that the API endpoint returns a 404 error for alphanumeric IDs, despite the documentation indicating support for them.`
I’m working on a web application where I need to make API requests. It needs to be robust and assume it can fail because of network or sever errors. I want to have a re-try function that continues making a certain number of calls before it stops.
I need to improve this function so it can handle 2 cases. 1) Cancellation. Suppose the user closes the browser or navigates to a different part of the page. The current function doesn’t have way to cancel ongoing retries. 2) Handle certain error codes. Suppose you get a HTTP 4xx error code. There is no point in retrying because it could be unauthorized (401) or forbidden (403). But, it should retry for 5xx error codes. My current function doesn’t provide a way to tell the difference between different error codes.
Here is the minimal reproducible example I have for you:
function retry(fn, retries = 3, delay = 1000) {
return new Promise((resolve, reject) => {
let attempt = (n) => {
fn().then(resolve)
.catch((error) => {
if (n === 0) {
reject(error)
} else {
setTimeout(() => {
}, delay); // 1 second delay default
}
});
};
attempt(retries);
})
}
// Test
let fetchWithRetry = () => retry(() => fetch("https://jsonplaceholder.typicode.com/todos/95"));
fetchWithRetry()
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Failed to fetch data:', error));
I found another Stack Overflow answer regarding the retry logic but it does not fully address the need for cancellation and specific HTTP error codes. Promise Retry Design Patterns
I use this effect to show a navigation, now when i click the link and the page reloads the mouse is mostly still over the element that triggered the event on mousenenter. Now when the page is loaded again the mousenter is fired again and the subnavigation shows. How can i just fire the event when the mouse really enters it from the outside and not on page load?
jQuery(document).ready(function ($) {
$( "#main-header .shop-nav-item" )
.on( "mouseenter", function() {
$("#shop-navigation").addClass("opened")
});
});
I made a a particle letter effect for a website using canvas. The way it works is it first generates a small text on a canvas and then reads the image data from that text to turn each pixel into a particle. Below is the relevant javascript
ctx.fillStyle = 'white'
ctx.font = `${45 * resultion}px Courier`;
ctx.fillText('SYOMA',0,30)
const textCoords = ctx.getImageData(0, -15 , 150,45+30)
//Im fairly certian the problem is not with the particle generating fucntion so I did not include it.
The website works fine on Firefox desktop and Chrome Mobile(first image) however runs into issues when loaded on Firefox for android(second image).
Ignore the messed up M on the second picture that is an intended effect when a mouse is hovered above the text.
I suspect the issue is something about Firefox mobile not generating the courier font in canvas for some reason and instead using the default font which is larger leading it to not fit in the image data scan and cutting off the text.
Again I want to mention that this issue happens only on Firefox for mobile and the issue isn’t there for Firefox desktop or any other browser I’ve tested.
I’ve set up a Slack bot with Node.js and @slack/bolt. It uses socket mode.
To install the bot to a workspace, I go to https://localhost/slack/install, which has a link to Slack to install the bot. Slack then redirects to https://localhost/slack/oauth_redirect. That URL gives the following error in the server console:
[ERROR] OAuth:InstallProvider:0 Error: The state parameter is not for this browser session.
at new InvalidStateError (D:[email protected]:65:47)
at InstallProvider.<anonymous> (D:CodingProjectsGearboxnode_modules@slackoauthdistinstall-provider.js:498:39)
at step (D:CodingProjectsGearboxnode_modules@slackoauthdistinstall-provider.js:44:23)
at Object.next (D:CodingProjectsGearboxnode_modules@slackoauthdistinstall-provider.js:25:53)
at D:CodingProjectsGearboxnode_modules@slackoauthdistinstall-provider.js:19:71
at new Promise (<anonymous>)
at __awaiter (D:CodingProjectsGearboxnode_modules@slackoauthdistinstall-provider.js:15:12)
at InstallProvider.handleCallback (D:CodingProjectsGearboxnode_modules@slackoauthdistinstall-provider.js:462:16)
at Server.<anonymous> (D:CodingProjectsGearboxnode_modules@slackboltdistreceiversSocketModeReceiver.js:85:50)
at Server.emit (node:events:518:28)
at parserOnIncoming (node:_http_server:1143:12)
at HTTPParser.parserOnHeadersComplete (node:_http_common:119:17) {
code: 'slack_oauth_invalid_state'
I have verified that my environment variables are correct and have updated both @slack/bolt and @slack/oauth. I am piping the HTTP request from port 443 (where the rest of my website runs) to another SLACK_PORT.
My bot code is as follows:
import { SlashCommand, AckFn, RespondArguments, RespondFn, App, Installation } from "@slack/bolt";
import SlackCommands from "./SlackCommands";
import { Collections, getDatabase } from "./MongoDB";
const slackApp = new App({
// token: process.env.SLACK_BOT_TOKEN,
signingSecret: process.env.SLACK_SIGNING_SECRET,
socketMode: true,
port: +process.env.SLACK_PORT,
redirectUri: "https://localhost/slack/oauth_redirect",
installerOptions: {
redirectUriPath: "/slack/oauth_redirect",
},
appToken: process.env.SLACK_APP_TOKEN,
clientId: process.env.NEXT_PUBLIC_SLACK_CLIENT_ID,
clientSecret: process.env.SLACK_CLIENT_SECRET,
stateSecret: process.env.SLACK_STATE_SECRET,
scopes: ["chat:write", "commands"],
installationStore: {
storeInstallation: async (installation) => {
// ... code to store the installation
},
fetchInstallation: async (InstallQuery) => {
// ... code to fetch the installation
},
},
});
export async function startSlackApp() {
await slackApp.start(process.env.SLACK_PORT);
console.log("Slack bot is listening at: http://localhost:" + process.env.SLACK_PORT);
return slackApp;
}
How do I set up the installation so the state parameter is valid?
comment crée une IA sur un pc qui tourne sur Windows 10
j ai essaye de créé mais je n ai pu arrivée car je un enfant de 12 et je aussi monétisé l IA pour une IA en pleine apprentissages . Pour ne pas être entrainé de bug et sécurisée pour ne par être hacker
I am trying to get a downsampled audio so that I can use it for an hotword detection API. In the solution I am currently using, the audio is correctly converted and the API is able to recognize the content of the audio file. However, I am constantly forced to write temporary output files. I have tried several times to use “pipe:1” in ffmpeg to output the converted audio as a stream to stdout, but it has always given me errors.
function downsampleAudio(pcmBuffer) {
return new Promise((resolve, reject) => {
const inputStream = new PassThrough();
inputStream.end(pcmBuffer);
let filePath = path.join(__dirname, "output.wav")
const ffmpeg = spawn("ffmpeg", [
"-f", "s16le",
"-ar", "48000",
"-ac", "1",
"-i", "pipe:0",
"-ar", "16000",
"-ac", "1",
"-c:a", "pcm_s16le",
filePath
]);
ffmpeg.stdin.on('error', (error) => {
reject(new Error('Errore nello stream stdin di ffmpeg: ' + error.message));
});
ffmpeg.on('close', (code) => {
if (code !== 0) {
reject(new Error(`Il processo ffmpeg è terminato con codice ${code}`));
} else {
console.log('Conversione completata con successo');
const waveBuffer = fs.readFileSync(filePath);
fs.unlinkSync(filePath);
resolve(waveBuffer)
}
});
inputStream.pipe(ffmpeg.stdin);
});
}
Can anyone help me figure out how to correctly use ffmpeg to output the audio as a stream to stdout without errors? Thanks in advance!
I see people using extensions like .d.ts, .schema.ts, .route.ts, routes.ts and basically anything and everything, so I was wondering if there is no limit to the extensions you can give to your files in typescript/javascript (I’ve seen people do this with javascript too). So someone kindly explain what are these extensions and how to use them.
Thank you.
Im trying to make a intermediate table between 2 models, called User and Reminder.
The fact is everytime i try to migrate or create the table UserReminders I dont get 2 foreing keys, userId and reminderId, instead I only get ONE foreing key, which is reminderId.
This is what appears on my table on heidiSQL
I created a model on my backend called UserReminder and the migration of it for my database on HeidiSQL.
MODEL:
import { Model } from 'sequelize'
const loadModel = (sequelize, DataTypes) => {
class UserReminder extends Model {
static associate (models) {
// Un UserReminder pertenece a un usuario
UserReminder.belongsTo(models.User, { foreignKey: 'userId', onDelete: 'CASCADE' })
// Un UserReminder pertenece a un recordatorio
UserReminder.belongsTo(models.Reminder, { foreignKey: 'reminderId', onDelete: 'CASCADE' })
}
}
UserReminder.init({
userId: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: 'Users',
key: 'id'
},
onDelete: 'CASCADE',
onUpdate: 'CASCADE'
},
reminderId: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: 'Reminders',
key: 'id'
},
onDelete: 'CASCADE',
onUpdate: 'CASCADE'
},
createdAt: {
allowNull: false,
type: DataTypes.DATE,
defaultValue: DataTypes.NOW
},
updatedAt: {
allowNull: false,
type: DataTypes.DATE,
defaultValue: DataTypes.NOW
}
}, {
sequelize,
modelName: 'UserReminder',
tableName: 'UserReminders',
timestamps: true,
indexes: [
{
unique: true,
fields: ['userId', 'reminderId']
}
]
})
return UserReminder
}
export default loadModel
MIGRATION:
'use strict'
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up (queryInterface, Sequelize) {
await queryInterface.createTable('UserReminders', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
userId: {
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: 'Users',
key: 'id'
},
onDelete: 'CASCADE'
},
reminderId: {
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: 'Reminders',
key: 'id'
},
onDelete: 'CASCADE'
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
defaultValue: Sequelize.fn('now')
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
defaultValue: Sequelize.fn('now')
}
})
await queryInterface.addConstraint('UserReminders', {
fields: ['userId', 'reminderId'],
type: 'unique',
name: 'unique_user_reminder'
})
},
async down (queryInterface, Sequelize) {
await queryInterface.dropTable('UserReminders')
}
}
I was expecting to have 1 primary key called id, 2 foreing keys userId and reminderId, and one unique key compound (userId, reminderId). But i got the things I said but with only ONE foreing key (reminderId) instead of 2.
I’ve looked through the documentation. Can someone point me in the right direction? I’m simply trying to learn to create a assistant with a firebase cloud function and use an assistant. Just those two functions. couldn’t find it anywhere
I’m able to use the normal chatgpt api but not the one with the assistants. I believe I need an assistant id and then later on a thread id to mantain the conversation. Any help is appreciated. Thanks.
I’m encountering an error while using Next.js with a custom Express server. The error message is:
TypeError: Response body object should not be disturbed or locked
This occurs during API requests when I send a body with a POST request. The requests without a body (GET, even POST without sending a body, etc.) work fine.
I’m using a custom server with Express and have added middleware to allow Next.js to handle routing. The pages are served correctly, but the issue arises with the API route handler.
Here is the relevant part of my server setup:
import express from 'express';
import dotenv from 'dotenv';
import next from 'next';
import path from 'path';
dotenv.config({
path: path.resolve(__dirname, '../.env'),
});
const PORT = Number(process.env.PORT) || 3000;
const app = express();
const nextApp = next({
dev: process.env.NODE_ENV !== 'production',
port: PORT,
hostname: 'http://localhost',
});
const nextHandler = nextApp.getRequestHandler();
async function start() {
await nextApp.prepare();
app.use(express.json()); // Ensure the body parser is included
app.use((req, res) => nextHandler(req, res));
app.listen(PORT, () => {
console.log(`Server started, and running at http://localhost:${PORT}`);
});
}
start();
What could be causing this TypeError when sending a body with POST requests? How can I resolve this issue to ensure that my API routes work correctly with body data?
My version of next is 14.2.5 and my version of express is 4.18.2
Thank you for your assistance!
Is it possible for me to get the descriptor for the actual constructor method of a JS class? I am writing my own little wrapper around Express to try and procedurally generate routes and stuff (and I am sure there are plenty of other libraries to do this, but it’s a learning experience).
If I iterate through the function descriptors for a class prototype, I can convert the ‘value’ property to a string that represents a single method. If I call getString() on the descriptor for ‘constructor’ I get the entire class. I ONLY want the body of the constructor. I could add more parsing logic, but there has to be a way to do this.
Here is a simple controller:
const
BaseController = require('../src/baseController');
/**
* Handle requests for the home page
*/
class HomeController extends BaseController {
/**
* @param settings Controller settings
* @param vault Injected vault client
*/
constructor(settings, vault) {
super(settings);
this.vault = vault;
}
/**
* Serve the landing page
* @returns
*/
async get() {
await this.renderAsync({ pageTitle: 'Pechanga Demo' });
}
}
module.exports = HomeController;
Here is what currently comes back for ‘get’:
Object.getOwnPropertyDescriptor(controllerType.prototype, 'get').value.toString()
async get() {
await this.renderAsync('index', { pageTitle: 'Pechanga Demo' });
}
However, getting the descriptor for ‘constructor’ returns the entire class body:
Object.getOwnPropertyDescriptor(controllerType.prototype, 'constructor').value.toString()
I really want is just:
constructor(settings, vault) {
super(settings);
this.vault = vault;
}
Is this possible without parsing the entire class body?
On my wordpress site there are a couple of videos that could play in fullscreen mode, but only in iPhones I have an issue with video: it is getting paused when then leaving the fullscreen mode to normal mode and shows both the iOS video player controls and the presto player controls which looks very confusing.
Besides, in iOS 17.2 there is a dark screen in fullscreen mode instead of full length video.
Here is an example of code:
var lazyVideos = [].slice.call(document.querySelectorAll("video.lazy"));
if ("IntersectionObserver" in window) {
var lazyVideoObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
var video = entry.target;
var source = video.querySelector("source");
// Load and play the video from data-src
if (source && source.dataset.src) {
source.src = source.dataset.src;
video.load();
video.play();
}
video.classList.remove("lazy");
lazyVideoObserver.unobserve(video);
}
});
});
lazyVideos.forEach(function(lazyVideo) {
lazyVideoObserver.observe(lazyVideo);
});
}
function isIOS() {
return /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
}
// Add event listener to play button
document.querySelectorAll(".playbutton").forEach(function(button) {
button.addEventListener("click", function() {
var container = this.closest(".video-container");
var fa = container.querySelector(".fa");
var video = container.querySelector("video");
var source = video.querySelector("source");
if (video && source) {
// Pause the current video
video.pause();
// Load the full video
if (source.dataset.fullsrc) {
source.src = source.dataset.fullsrc;
}
video.load();
video.controls = true;
video.loop = false;
// Play the full video in fullscreen mode
video.addEventListener('loadeddata', function() {
if (video.requestFullscreen) {
video.requestFullscreen();
} else if (video.mozRequestFullScreen) { // Firefox
video.mozRequestFullScreen();
} else if (video.webkitRequestFullscreen) { // Chrome, Safari and Opera
video.webkitRequestFullscreen();
} else if (video.msRequestFullscreen) { // IE/Edge
video.msRequestFullscreen();
} else if (isIOS() && video.webkitEnterFullscreen) { // iOS Safari
video.webkitEnterFullscreen();
}
video.play();
}, {
once: true
});
// Exit fullscreen and remove controls when the video ends
video.addEventListener('ended', function() {
if (document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.msFullscreenElement) {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.mozCancelFullScreen) { // Firefox
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) { // Chrome, Safari and Opera
document.webkitExitFullscreen();
} else if (document.msExitFullscreen) { // IE/Edge
document.msExitFullscreen();
}
}
video.controls = false;
}, {
once: true
});
// Handle manual exit from fullscreen mode
var handleFullscreenChange = function() {
if (!(document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.msFullscreenElement)) {
video.controls = false;
if (fa.classList.contains("fa-play") && video.play) {
fa.classList.remove("fa-play");
fa.classList.add("fa-pause");
}
if (isIOS()) {
video.controls = false;
video.play();
}
document.removeEventListener('fullscreenchange', handleFullscreenChange);
document.removeEventListener('mozfullscreenchange', handleFullscreenChange);
document.removeEventListener('webkitfullscreenchange', handleFullscreenChange);
document.removeEventListener('msfullscreenchange', handleFullscreenChange);
}
};
}
});
});
<div class="video-wrapper section_video" id="animationvideo">
<div class="video-container">
<video class="img-fluid lazy animation-video" width="600" height="400" autoplay loop muted playsinline poster="https://www.w3schools.com/w3css/img_forest.jpg">
<source data-src="https://www.w3schools.com/html/mov_bbb.mp4" data-fullsrc="https://www.w3schools.com/html/movie.mp4" type="video/mp4">
</video>
<button class="playbutton" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-custom-class="expand-tooltip play-tooltip" data-bs-trigger="hover" title="Pause animation" aria-label="Play or pause this animation by clicking this link">Play full video<i class="fa fa-play" aria-hidden="true"></i></button>
</div>
</div>
I tried to switch functionality from the wordpress core player to the native player for fullscreen the method of which is described on the forum, but it didn’t help me.
add_action(
'wp_footer',
function () { ?>
<script>
jQuery(function() {
if (!wp || !wp.hooks) return;
wp.hooks.addFilter('presto.playerSettings', 'ios-native-fullscreen', function(settings) {
settings.fullscreen = { enabled: true, fallback: true, iosNative: true, container: null };
return settings;
});
});
</script>
<?php
}
);