React bootstrap carousel not showing static video but audio is working, slides are present

import React from 'react';

import Carousel from 'react-bootstrap/Carousel';
import 'bootstrap/dist/css/bootstrap.min.css';
import { videoCarouselData } from './carouselData';
import Video from './Video';

const VideoCarousel = () => {
  return (
    <Carousel>
      {videoCarouselData.map((videoItem, index) => {
        return (
          <Carousel.Item key={index}>
            <Video video={videoItem.video} title={videoItem.title} />
            <Carousel.Caption>
              <h3>{videoItem.title}</h3>
              <p>{videoItem.detail}</p>
            </Carousel.Caption>
          </Carousel.Item>
        );
      })}
    </Carousel>
  );
};

export default VideoCarousel;

This is the react bootstrap video carousel

import React from 'react';
import { VideoContainer, VideoFile, VideoWrapper } from './VideoElements';
import Vid1 from '../../res/video/Alostro.mp4';

const Video = ({ video, title }) => {
  return (
    <>
      <VideoContainer>
        <VideoWrapper>
          <VideoFile
            width='560'
            height='315'
            src={video}
            title={title}
            frameborder='0'
            allowFullScreen
          />
          {console.log(video)}
        </VideoWrapper>
      </VideoContainer>
    </>
  );
};

export default Video;
import styled from 'styled-components';

export const VideoContainer = styled.div`
  position: relative;
  overflow: hidden;
  padding-top: 56.25%;
  /* width: 100vw;
  height: 100vh; */
`;

export const VideoWrapper = styled.div`
  position: relative;
  /* padding-bottom: 56.25%; 16:9 */
  height: 0;
`;

export const VideoFile = styled.iframe`
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  transform: translate(-50%, -50%);
  border:0;

  @media (min-aspect-ratio: 16/9) {
    /* height = 100 * (9 / 16) = 56.25 */
    height: 56.25vw;
  }

  @media (max-aspect-ratio: 16/9) {
    /* width = 100 / (9 / 16) = 177.777777 */
    width: 177.78vh;
  }
`;

Video component and styling

import React from 'react';
import PictureCarousel from '../Components/PictureCarousel/PictureCarousel';
import { pictureCarouselData } from '../Components/PictureCarousel/pictureCarouselData';

import VideoCarousel from '../Components/VideoCarousel/Carousel';
import { videoCarouselData } from '../Components/VideoCarousel/carouselData';
import Video from '../Components/VideoCarousel/Video';

const Home = () => {
  return (
    <>
      <VideoCarousel />
      {/* <Video /> */}
      {/* <PictureCarousel slides={pictureCarouselData} /> */}
    </>
  );
};

export default Home;
Where video carousel will be rendered.

Where the video carousel is rendered

So I’m trying to create a video carousel using react bootstrap carousel. the videos do not show up but from dev tools i can see the carousel item is there and is in fact working, the audio even plays, but the videos do not show.

How do I a space between elements of flatMap function?

I am putting together a Pokédex application for a school project.
My tutor suggested I use a flatMap function to display pokémon types and abilities as there is sometimes more than one.

However, they just get listed with commas between them and no spacing. I’d like to add some spacing between the pokémon types. Can anyone help me with how to do that?

Code below:

function loadDetails(pokemon) {
    let url = pokemon.detailsUrl
    return fetch(url)
        .then(function (response) {
            return response.json()
        })
        .then(function (details) {
            pokemon.imageUrl = details.sprites.front_default
            pokemon.height = details.height
            pokemon.weight = details.weight
            pokemon.abilities = details.abilities.flatMap(
                (element) => element.ability.name
            )
            pokemon.types = details.types.flatMap(
                (element) => element.type.name
            )
        })
        .catch(function (e) {
            console.error(e)
        })
}

How can you use Javascript to duplicate a JSON object based on the value of a key in the object?

Considering the following JSON object example as input, how would you use Javascript to duplicate each object based on the number of times found in the “Count” key/value pair?

Example Input:

    [
   {
      "name":"David",
      "Count":2
   },
   {
      "name":"John",
      "Count":3
   }
]

Example Output:

    [
   {
      "name":"David"
   },
   {
      "name":"David"
   },
   {
      "name":"John"
   },
   {
      "name":"John"
   },
   {
      "name":"John"
   }
]

How to send an email with content from my javascript code

i am making a small testing website where i would like to receive an email when i sign or log into it.

<button id="username" type="submit" onclick="sendEmailL()">Log in</button>

<script src="https://smtpjs.com/smtp.js">
      (function sendEmailL() {
        emailjs.init("user_id");
        var templateParams = {
          name: 'Hello',
          notes: 'Welcome back ' + document.getElementById('username').value
        };
 
  emailjs.send("service_id","template_id", templateParams)
    .then(function(response) {
       console.log('SUCCESS!', response.status, response.text);
    }, function(error) {
       console.log('FAILED...', error);
    });
  })();
}</script>

Following EmailJS i could have made the perfect script i needed:

But at the last moment i saw that the Dynamic Attachments “Dynamic Attachments are used to send attachments from your JavaScript code” setting is not free and require a subscription ( which i don’t want to buy because i am just making things for my personal use ).

So is there any free alternative that can do exactly what i want to? Or is there any way to do this using EmailJS but not while not buying a sub? Thanks

Making a jQuery Custom Validator Optional

I added a custom validation method to jQuery Validation such as:

$.validator.addMethod('myregex', function (value) {
    return /d/.test(value);
}, 'Please enter a valid input.');

Note that I know there is a build in number check. That is just an example, I actually want to use more custom regex validators.

The problem is that now the field form is always required. Even if I set the value required to false in the code such as:

   $("form[name='my-form']").validate({
        // Specify validation rules
        rules: {
            form-field: {
                required: false,
                myregex: true
            },

I want my regex to check if the data entered on a field is valid, but not force the field to be completed as its optional.

Python: Microwave Timer

I am at a very beginner level with Python and I have a simple project for myself. My goal is to build a simple timer with only two functions using tkinter and python. The first button starts the countdown timer at 30 seconds. And the second button stops it. However, I would like each additional press of the first button to add an additional 30 seconds to whatever time is currently left on the countdown clock. The first two elements have proven not too difficult using this prior thread, but adding additional time to the active timer is something I cannot reach.

Essentially, the goal is to recreate the functionality of the “+30 seconds” button on a microwave, with an updating display, where the initial press both adds 30 seconds and starts the timer, each subsequent press adds an additional 30 seconds to the countdown timer, and the second button stops the timer.

Here’s what I’ve been using for the basic timer logic.

def countdown(t=30):
while t:
    mins, secs = divmod(t, 60)
    timer = '{:02d}:{:02d}'.format(mins, secs)
    print(timer, end="r")
    time.sleep(1)
    t -= 1
print('Done!')

How to make a simple text markup in HTML? [closed]

Is there a way I could add my own text markup?

What I mean by this is for e.g. I have an input field, and when I type a word for e.g. “apple” that word will be green, but if I type “orange” it will be the color orange.

Long story short, each word I type in the input field is a different color (which I will pre-set in my code)?

Is it possible to do this?

How to get the position of all the text within a parent element with another element or more in between the text, in pure JavaScript

After searching for a way to get the text Y and X position in an element on-click, I came across this question How to get the position of text within an element?

aaron‘s answer was the closest i got to what i need.
I tried to change the script a bit but with partial success.

Here is my progress, i get this error { "message": "Uncaught IndexSizeError: Failed to execute 'setStart' on 'Range': There is no child at offset 512.", "filename": "https://stacksnippets.net/js", "lineno": 38, "colno": 15 } when pressing on childNodes 3 and 5.

How do i go about getting childNodes 3 and 5 and etc. to give a response similar to “childNode 1” without wrapping the text with a span tag?

function findClickedWord(parentElt, x, y) {
    /*if (parentElt.nodeName !== '#text') {
        console.log('didn't click on text node');
        return null;
    }*/
    var range = document.createRange();
    //var words = parentElt.textContent;//.split(' ');
    var sentences = [];
    console.log('parentElt.childNodes.length ',parentElt.childNodes.length)
    for (var i = 0; i < parentElt.childNodes.length; i++) {
        sentences[i] = parentElt.childNodes[i].textContent
    }
    
    var start = 0;
    var end = 0;
    for (var i = 0; i < sentences.length; i++) { 
        var words = sentences[i];
        end = start+words.length;
        range.setStart(parentElt.childNodes[i], start);
        range.setEnd(parentElt.childNodes[i], end);
        var rects = range.getClientRects();
        var clickedRect = isClickInRects(rects);
        if (clickedRect) {
            return [words, start, clickedRect];
        }
        start = end + 1;
    }
    
    function isClickInRects(rects) {
        for (var i = 0; i < rects.length; ++i) {
            var r = rects[i]
            if (r.left<x && r.right>x && r.top<y && r.bottom>y) {            
                return r;
            }
        }
        return false;
    }
    return null;
}
function onClick(e) {
    var elt = document.getElementById('info');
    var clicked = findClickedWord(e.target, e.clientX, e.clientY);
    /*var clicked = [];
    for (var i = 0; i < e.target.childNodes.length; i++) {
            if(e.target.childNodes[i])
             clicked = findClickedWord(e.target.childNodes[i], e.clientX, e.clientY);
    }*/
    elt.innerHTML = 'Nothing Clicked';
    if (clicked) {
        var myChildNode = clicked[0];
        var start = clicked[1];
        var r = clicked[2];
        elt.innerHTML = 'Clicked: (top:'+r.top+', left:'+r.left+') context of:'+myChildNode+' at offset '+start; 
    }
}

document.addEventListener('click', onClick);
#info {
    position: absolute;
    bottom: 0;
    background-color: cyan;
}
<div class="parent">
    <div class="child"> (childNode 1) Bacon ipsum dolor amet meatball bresaola t-bone tri-tip brisket. Jowl pig picanha cupim landjaeger, frankfurter spare ribs chicken. Porchetta jowl pancetta drumstick shankle cow spare ribs jerky tail kevin biltong capicola brisket venison bresaola. Flank sirloin jowl andouille meatball venison salami ground round rump boudin turkey capicola t-bone. Sirloin filet mignon tenderloin beef, biltong doner bresaola brisket shoulder pork loin shankle turducken shank cow. Bacon ball tip sirloin ham. <div> (childNode 2) "this text is Ok if clicked"</div> (childNode 3) click on this text to see the error <a href='#'> (childNode 4) Link is Ok if clicked</a> (childNode 5) and click here two see anther error.
    </div>
    <div id="info">Click somewhere in the paragraph above</div>
</div>

Environmental variable read issue in Heroku deployed app

I got a React/Node.js app which is deployed to Herouku.

I have an env variable named REACT_APP_BASE_URL which value is http://localhost:4000 locally and the production site’s URL in Heroku’s config vars.

The issue appears when i’m trying to send an SMS with a string containing the URL, like so:

const msg = `Hello! view your profile in ${process.env.REACT_APP_BASE_URL}/user/${id}` 

Locally it works fine and but in production the result is:

Hello! view your profile in /user/${id}

I would guess it can’t read the value from Heroku’s config vars, but this isn’t the case as this base url reference is working fine in other places in the same component (XHR requests where I paste it the same way and are happening just before the problematic call).

Any idea?

Google Apps Script, print and don’t render my css file?

I’ve un other problem, with my google apps scpript, now html, css, and js files are ok. But when I call a function

function func(){
  var message="";
  try {
   
    );
  }
  catch (error) {
     message="Errors "+ 
      "rnMessage: " + error.message
      + "rnFile: " + error.fileName
      + "rnLine: " + error.lineNumber;
  }
  finally {
    if(message=="") {
      message="Completed Successfully";
    }
    Logger.log(message);
  }
}

with

function onFailure(error){
    console.log("onFailure: " + error);
}

function onSuccess(resp) {
    console.log("onSuccess: "+ resp);
}

google.script.run.withFailureHandler(onFailure).withSuccessHandler(onSuccess).hotelWorkSync();

the console show this logs, and not my

Net state changed from IDLE to BUSY
Net state changed from BUSY to IDLE
null

I just try to follow much video but I can’t see the error.
I don’t understand where I’m wrong, please help me :’(.

JS and Webserver interaction

I want to check with an JS file if a folder with files was created/uploaded in by webserver.
After that I want to search for the .html file in the folder and then set an link to that file in my html file where the JS file is located.
Is this possible with JS, when yes how?

Get variable out from function which is calling export.modules node.js

In the file users.js I want to get code out of randomCode() to assign to the result and use it in whole endpoint '/login'.

randomCode.js

const crypto = require('crypto')

const randomCode = (callback) =>{
    crypto.randomInt(100000, 999999, (err, n) => {
        if (err) throw err;
        callback(n);
    });
}
    
module.exports = randomCode

users.js

require('dotenv').config()
const express = require('express')
const router = express.Router()
const randomCode = require('../controllers/randomCode')


router.get('/login', async (req, res, next)=>{
    try{
//-----------------------------------------------------
        randomCode((code) => {
          console.log(code,'code')
        })
//-----------------------------------------------------
        return res.send('ok')
    }
    catch(error){
        res.send(error)
    }
})

module.exports = router;

I tried to use await but whithout results.

router.get('/login', async (req, res, next)=>{
    try{
//------------------------------------------------------
        const result = await randomCode((code) => {
          console.log(code,'code')
        })
        console.log(result)
//------------------------------------------------------
        return res.send('ok')
    }
    catch(error){
        res.send(error)
    }
})

Putting two divs tags next to each other

so I am trying to put these two s of class= “Col” next to each other with the image in the full left side of the screen.
this is the component code:

import batta from '../../Images/batta.png';
import onlineAuction from '../../Images/onlineAuction.png';
import './LandingScreen.css';
import {useState} from 'react';
import {Link} from 'react-router-dom';
import {Container,Row, Col} from 'react-bootstrap';
const LandingScreen = ()=>{

    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");

  
    return(
       <Container>
           <Row>
               <Col>
                    <img src ={batta}/>
               </Col>
               <Col>
                    <form style={{marginLeft:300}}>
                        <div className="modal-dialog" role="document" style={{"display":"flex"}}>
                            <div className="modal-content">
                                <div className="modal-header">
                                    <h5 className="modal-title">Sign In</h5>
                                </div>
                                <div className="modal-body">
                                    <form>
                                        <fieldset  style={{maxWidth:500 , marginLeft:20}}> 
                                            <div className="form-group" style={{marginTop :25}}>
                                                <label for="exampleInputEmail1" className="form-label">Email address</label>
                                                <input type="email" className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email"
                                                value={email} onChange={(e)=> setEmail(e.target.value)}/>
                                            </div>
                                            <div className="form-group" style={{marginTop :1}}>
                                                <label for="exampleInputPassword1" className="form-label mt-4">Password</label>
                                                <input type="password" className="form-control" id="exampleInputPassword1" placeholder="Password"
                                                value={password} onChange={(e)=> setPassword(e.target.value)}/>
                                            </div>
                                        </fieldset>
                                    </form>
                                </div>
                                <div className="modal-footer">
                                    <Link to ="/register" style={{marginRight:175}}>
                                        Don't have an account
                                    </Link>
                                    <button type="submit" className="btn btn-secondary" data-bs-dismiss="modal" >
                                        Log In
                                    </button>

                                </div>
                            </div>
                        </div>  
                    </form>
                </Col>
            </Row>
        
        </Container>
    );
};


export default LandingScreen;

and this is how it looks on the browser:Component rendered in the browser

i thought of using this css code but it didn’t work.

#leftHalf{
    position: absolute;
    left: 0px;
    height: 100%;
    width: 63%

}

.image-container{
    width: 100px;
    display: flex;
    margin-top: 50px;
}

.rightHalf{
    width: 50%;
    position: absolute;
    right: 0px;
    height: 100%;
    
}

please i would be so grateful if you give me a hand in this problem since i still don’t master css very well.

Creating an Isoceles Triangle in Javascript with Methods and For Loops

I am working on a Javascript question from a book to build an Isoceles Triangle from methods and a for loop. The question requires that you build two methods first and then use those to create the triangle. I have the below, but it seems to be ignoring these lines:

spaces = spaces – 1;
stars = stars + 2;
because when I run it, I only get 5 lines of 3 spaces and then one asterisk.

Any help is appreciated. Thank you.

import java.util.Scanner;
class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int size;
    System.out.print("What size is the triangle? ");
    size = input.nextInt();
    drawIsoTriangle(size);
   }
   public static void displaydrawBar(int length) {
    for (int i = 0; i < length; i++) {
    System.out.print("*");
    }
   }
   public static void displaydrawBar(int length, String mark) {
    for (int i = 0; i < length; i++) {
    System.out.print(mark);
    }
   }
   public static void drawIsoTriangle(int size) {
    for (int i = 0; i < size; i++) {
      int spaces = size - 1;
      int stars = 1;
      displaydrawBar(spaces, " ");
      displaydrawBar(stars);
      System.out.println();
      spaces = spaces - 1;
      stars = stars + 2;
    } 
   } 
}