Remove id and style properties from span tag Javascript

Suppose I have a element with a span tag as follows:
<span id="myId" style="background-color: #FFFFFF">Hey there!</span>

How could I remove the id and style properties from this span tag in Javascript so that my solution is something like <span>Hey there!</span>? I think I have to use regex to do so but I’m not entirely sure where to start.

Draw players for knockout phase after group phase is finished

I’m trying to create an algorithm which will randomly pair chess players for knockout phase. One player from players.first should be paired with one player from players.second, but condition is that first player must have different first.group than second.group

players = {
    first: [
        { name: 'Carlsen', group: A },
        { name: 'Caruana', group: B },
        { name: 'Duda', group: C },
        { name: 'Vidit', group: D },
    ],
    second: [
        { name: 'Nakamura', group: A },
        { name: 'Giri', group: B },
        { name: 'Pragga', group: C },
        { name: 'Nepo', group: D }
    ]
}

Goal is to get array like below

pairs = [
            [ { name: 'Carlsen', group: A }, { name: 'Pragga', group: C } ],
            [ { name: 'Duda', group: C }, { name: 'Nepo', group: D } ],
            [ { name: 'Vidit', group: D },  { name: 'Giri', group: B } ],
            [ { name: 'Caruana', group: B }, { name: 'Nakamura', group: A } ]
        ]

Asynchronous API calls returning null values

I am working on an online booking site for a few resorts. Each of the resorts have different rooms (saved as an array of objects for each resort). I am trying to come up with an efficient way to query all of the rooms for availability via a 3rd party API call. I have set up a nested for loop for this. Basically the code aggregates an array of resorts and calls an API endpoint to check for availability for each room at each resort. I am currently able to get this to work by making synchronous API calls; however the time it takes for all the requests to complete is too slow to work for the end user. That got me thinking about making multiple calls at once and waiting for the data to be sent back before rendering the data to the screen. This is the part that I am struggling with. I have created multiple different methods that would supposedly work asynchronously but none of them actually return data back to the front end. Here is my code so far:

backend code that calls the API

export async function getAvailAsync(startDate, endDate, groupID, resortID, roomInfo, weekendCheckIn, duration) {
    const username = await wixSecretsBackend.getSecret("userName")
    const password = await wixSecretsBackend.getSecret("password")
    const baseUrl = await wixSecretsBackend.getSecret("liveBaseUrl")
    const authInfo = await encode.encode(`${username}:${password}`, "base64")
    const url = `${baseUrl}/Availability/GetByRoomType?groupID=${groupID}&resortID=${resortID}&roomType=${roomInfo}&startDate=${startDate}&endDate=${endDate}&checkForArrivalCalendarSetup=${weekendCheckIn}`

    let validAvail = []
    let temp = []

    return new Promise((resolve, reject) => {
        axios({
            method: "get",
            url,
            headers:{ Authorization: `Basic ${authInfo}`}
        }).then((res) => {
            let avail = res.data.Value.DaysAvailable
            const dateInfo = Object.keys(avail)
            for(let i = 0; i < dateInfo.length; i++) {
                let current = dateInfo[i]
                if(avail[current] !== "0") {
                    let dateInfo = current.split(" ")[0]
                    temp.push(dateInfo)
                } else {
                    if(temp.length >= duration) {
                        let startDate = new Date(temp[0])
                        let endDate = new Date(temp[temp.length - (duration + 1)])
                        let availInfo = {startDate, endDate}
                        validAvail.push(availInfo)
                    }
                    temp = []
                }
            }
            resolve({
                res: {validAvail}
            })
        }).catch((err) => {
            if(err.response) {
               reject(err.response.data)
            } else {
               reject(err)
            }
        })
    })
}

And here is the inner loop that I am using to handle the requests:

await rooms.map(room => {
            callbacks.push(getAvailAsync(startDate, endDate, attributeId, resortId, room.name, false, duration).then(response => {
                if(response.length > 0) {
                    let roomName = room.name.split(" ")
                    roomName.pop()
                    roomName.join(" ")
                    let earliest = response[0].startDate
                    return {roomName, earliest, costPerNight: "199", availability: response}
                }
            }))
        })

        await Promise.allSettled(callbacks).then(res => console.log(res))

I have also tried to process the API calls with the following:

const callbacks =  await rooms.map(room => () => getAvailAsync(startDate, endDate, attributeId, resortId, room.name, false, duration).then(response => {console.log(response)}))

I then called a custom function with the following:

const items = await chunk(callbacks)

Here is the chunk function to handle the requests:

export async function chunk(callbacks){
    const result = []
    const promises = []
    let def = 1
    const length = callbacks.length
    console.log("callbacks", callbacks)
    console.log(typeof(callbacks[0]))
    console.log(Object.values(callbacks))
    
    for(let i = 0; i < length; i++) {
        const callback = callbacks[i]

        if(i && i % 10 === 0) {
            result.push(...await Promise.allSettled(promises))
            promises.length = 0
        }
        promises.push(callback())
    }
    result.push(...await Promise.all(promises))
    return result
}

None of these methods seem to be working. When I call the API using the Promise.allSettled method I just get the following object returned: {resolved: true, value: undefined}

When I call the API using the chunking function I get an error message logged to the console saying “callback is not a function” and the value of callBacks that is passed into the function is an array with multiple null values (equal to the number of rooms a resort has)

At this point I am stumped. If anybody can help it would be greatly appreciated. Thank you!

Detect the active Google Analytics version using JavaScript

I have JavaScript code that is currently used in analytics.js to call various custom events, but I’d like to prepare it to support the new Google Analytics 4.

I’ve recently upgraded the site to gtag.js in my local environment, and was planning to make sure all of its custom events/ecommerce tracking/etc is working properly, then set up an Analytics 4 installation and migrate to it.

I’d like to set up a script that would detect which version of Analytics is running and would call the JavaScript syntax for that version, but I’m having trouble figuring out if this is reliable.

Here is my first attempt:

if ( typeof gtag !== 'undefined' ) {
    var params = {
        'event_category': category,
        'event_label': label
    };
    if ( typeof value !== 'undefined' ) {
        params.value = value;
    }
    gtag( type, action, params );
} else if ( typeof ga !== 'undefined' ) {
    if ( typeof value === 'undefined' ) {
        ga( 'send', type, category, action, label );
    } else {
        ga( 'send', type, category, action, label, value );
    }
}

I notice that this does run my events as I would expect in the gtag.js install (I’m running it with this GA Debug plugin in Chrome). The ga portion is what is running on our production site, so I know that it works as well.

However, in the Analytics.js version gtag is (sometimes) already loaded because of old Google AdWords installations. Detecting whether gtag is defined would return that it’s true, in these cases.

But on the flip side, I’ve noticed that even when gtag.js is the only version of Analytics that is running, detecting whether ga is defined also returns true. Presumably because at least in the legacy version of gtag.js, it contains a wrapper around analytics.js.

Is there any reliable way of detecting in JavaScript whether analytics.js or gtag.js is being used specifically for Analytics, or would I need to handle this on the server side before it gets this far?

How can I turn this into a function that takes 2 arguments – a sentence and then the word I want to count in the string?

I am a newbie here. I had a technical assessment the other day and had a coding question where I had to write a function that took two arguments, a sentence and a word. The function had to count how many times the word was repeated in the sentence. I have managed to get the answer doing it the first way you see below but cannot for the life of me seem to figure it out as a function that takes 2 arguments which is what the task asked for. Can anyone tell me where I am going wrong please?

let count = 0;
let str = "hello hello hello Bob is my name so it is hello"
let query = "hello";
let array = str.split(" ")
for (let i = 0; i < array.length; i++) {
  if (array[i] === query) {
    count++;
  }
}
console.log(count);
let str = "hello my name is my my bob";
let word = "my";

function countWord(str, word) {
  let count = 0;
  let strArray = str.split(" ");
  let array = strArray;
  for (let i = 0; i < array.length; i++) {
    if (array[i] === word) {
      count++
    }
  }
}
console.log(countWord(str, word));

Why is player movement happening faster in the code than on the screen?

I am trying to implement a wall collision detection in my Pacman game. Game map is a grid which consist of tiles.
The way I try to do wall collision is by tracking player position in the grid and check if player will be in a position where is a wall.

The problem in my implementation is that the code is updating faster than the player is moving on the screen.
For example it detects a wall coming in the code way earlier than on the screen and then it jumps to position where it would collide with a wall.

let pxPerSecond = 100;
let lastTime = Date.now();

function animate() {
    const now = Date.now();
    const delta = now - lastTime;
    lastTime = now

    movePacman(delta)

    requestAnimationFrame(animate)
}



function movePacman(elapsed) {

    // player.startCol and player.startRow are player starting position in the grid
    let col = Math.floor(player.x / 32) + player.startCol
    let row = Math.floor(player.y / 32) + player.startRow

    // g.size is length of the row
    let position = (row * g.size) + col;

    // t stands for type. Type 1 means wall
    if (myBoard[position].t == 1) {
        return
    }

    let moveBy = pxPerSecond * (elapsed / 1000)
    
    switch (player.currentMovingDirection) {
        case MovingDirection.right:
            player.x += moveBy;
            break
        case MovingDirection.left:
            player.x -= moveBy;
            break
        default:
            break;
    }
    // g.pacman is the player pacman we are moving on the screen
    g.pacman.style.transform = `translate(${player.x}px, ${player.y}px)`

}

React-Native: Get X and Y coordinates of draggable Object using Reanimated 2 API

I am developing an app, which provides the design of different shapes like Square , I have used the following Reanimated 2 API . I want to get its coordinates (pageX and PageY) every time I move the object.

my research

So i read this article about measure and i decided to try with that.

Then i created ref to my animated view like that const aref = useAnimatedRef();.

After that i read again in Reanimated docs that i should use useDerivedValue combined with measure. But unfortunately I didn’t get what I needed in the end. My app crashed with following error –

Tried to synchronously call usederivedvalue from a different thread

enter image description here

My code so far i tried to use runOnJs – no luck again! And my question is –

import React from "react";
import { StyleSheet, View } from "react-native";
import {
  GestureHandlerRootView,
  PanGestureHandler,
} from "react-native-gesture-handler";
import Animated, {
  measure,
  runOnJS,
  useAnimatedGestureHandler,
  useAnimatedRef,
  useAnimatedStyle,
  useDerivedValue,
  useSharedValue,
  withSpring,
} from "react-native-reanimated";

const SIZE = 100.0;
const CIRCLE_RADIUS = SIZE * 2;

export default function App() {
  const translateX = useSharedValue(0);
  const translateY = useSharedValue(0);
  const aref = useAnimatedRef();

  const panGestureEvent = useAnimatedGestureHandler({
    onStart: (event, context) => {
      context.translateX = translateX.value;
      context.translateY = translateY.value;
    },
    onActive: (event, context) => {
      translateX.value = event.translationX + context.translateX;
      translateY.value = event.translationY + context.translateY;
      const wrap = () => {
        try {
          const pageX = measure(aref).pageX;
          console.log({ pageX });
        } catch {}
      };
      useDerivedValue(() => {
        runOnJS(wrap)(true);
      });
    },
    onEnd: () => {
      const distance = Math.sqrt(translateX.value ** 2 + translateY.value ** 2);

      if (distance < CIRCLE_RADIUS + SIZE / 2) {
        translateX.value = withSpring(0);
        translateY.value = withSpring(0);
      }
    },
  });

  const rStyle = useAnimatedStyle(() => {
    return {
      transform: [
        {
          translateX: translateX.value,
        },
        {
          translateY: translateY.value,
        },
      ],
    };
  });

  return (
    <GestureHandlerRootView style={{ flex: 1 }}>
      <View style={styles.container}>
        <View style={styles.circle}>
          <PanGestureHandler onGestureEvent={panGestureEvent}>
            <Animated.View style={[styles.square, rStyle]} ref={aref} />
          </PanGestureHandler>
        </View>
      </View>
    </GestureHandlerRootView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
  square: {
    width: SIZE,
    height: SIZE,
    backgroundColor: "rgba(0, 0, 256, 0.5)",
    borderRadius: 20,
  },
  circle: {
    width: CIRCLE_RADIUS * 2,
    height: CIRCLE_RADIUS * 2,
    alignItems: "center",
    justifyContent: "center",
    borderRadius: CIRCLE_RADIUS,
    borderWidth: 5,
    borderColor: "rgba(0, 0, 256, 0.5)",
  },
});

My error – every time when i move my square my app crash with error above.

How can i get coordinates (pageX and PageY) every time I move the object.

What is causing the problem?

Of course this is the use of

const wrap = () => {
            try {
              const pageX = measure(aref).pageX;
              console.log({ pageX });
            } catch {}
          };
          useDerivedValue(() => {
            runOnJS(wrap)(true);
          });

in onActive event but i don’t know how to fix that ?

Sorry for my bad English.

how to take screenshot of canvas element

As title says i want to take screenshot of canvas, here what i have done and what problem: I’m using html2canvas to take a snapshot of canvas (stream), simply i have a button ‘take a snapshot’ and div which contains < h1>this text is viewable< / h1> and under that is live stream(stream works fine), but as you can see from picture below when i click that button it only takes snapshot of that h1 text and video shows blank and in console there is yellow triangle which says ‘React_devtools_backend.js:3973 #1 155ms Unable to clone WebGL context as it has preserveDrawingBuffer=false ‘, i have not set that… , any idea why video is blank ? and how can i change that to ‘true’ ?

English is not my mother language so could be mistakes

image:

enter image description here

video.js:

import { Height } from '@material-ui/icons';
import React, { useRef, useEffect, useState } from 'react';
import { loadPlayer } from 'rtsp-relay/browser';

const StreamVideo = () => {
  const canvasRef = useRef(null);

  useEffect(() => {
    if (!canvasRef.current) throw new Error('Ref is null');

    loadPlayer({
      url: 'ws://localhost:.../api/stream',
      canvas: canvasRef.current,
    });
  
  }, []);


  return (
    <div style={{ border: '5px solid red' }}>
      <canvas ref={canvasRef} style={{ width: '100%', height: '100%' }} />
    </div>
  );
};

export default StreamVideo;

here using that :

  const ref = useRef();
  const [pic, setPic] = useState(null);

  const createPicHandle = () => {
  html2canvas(ref.current).then((canvas) => {
  setPic(canvas.toDataURL());
  });
  };

  <button onClick={createPicHandle}>take a snapshot</button>

          <div ref={ref}>
            <h1>this text is viewable</h1>

            <StreamVideo />
          </div>

          {pic ? (
            <img src={pic} style={{ width: '100%', height: 'auto' }} alt="" />
          ) : null}

if needed here is nodejs:

const express = require('express');
const app = express();

const { proxy, scriptUrl } = require('rtsp-relay')(app);

const handler = proxy({
  url: `rtsp://....:.../Streaming/Channels/101`,
 
  verbose: false,
  transport: 'tcp',
});

app.ws('/api/stream', handler);

app.get('/', (req, res) =>
  res.send(
    `hg`,
  
  ),
);

app.listen(5000);

Store item from array of objects in new array

I have an array of objects that looks like this:

[
{
    "id": 1,
    "name": "Name 1",
    "created": "2022-04-07T18:40:11Z",
    "updated": "2022-04-07T18:40:19Z",
    "deleted": null,
    "accounts": [
        "89084",
        "34342"
    ]
},
{
    "id": 2,
    "name": "Name 2",
    "created": "2022-01-07T18:40:11Z",
    "updated": "2022-01-07T18:40:19Z",
    "deleted": null,
    "accounts": [
        "99084",
        "38342"
    ]
}

]
How do I store all accounts fields into a single array. Notice accounts is an array inside an object inside an array of objects.

On the popup form – Why Form submission is loading the page

On this page https://spa.micra-anglia.gr/ if you go to “Purifying Detox face & body ritual” section and click on this title you can see that a sidebar is showing. On this sidebar, I am calling ajax to get some content.

On this content, I have a WordPress form that is showing using shortcode.

Now, If I press the Submit button (Blue one) it’s reloading the page. Why?

but if you check the same form on this page: https://spa.micra-anglia.gr/test-form/ you can see the page is not loading.

Can you tell me what is happening here?

My JS code for the pulling content:

jQuery(document).ready(function($){
    $(document).on('click','.custom-ajax-link,.open_sidebar_post, .post-title a,.post .post-item .post-thumbnail a',function(e){
        loadPostEvent(e);
        return false;
    });

    function loadPostEvent(event){
        var el = $(event.currentTarget);
        var url = el.attr('href');
        if(typeof url == "undefined" || url  === ''){
            url = el.attr('data-href');
            if(typeof url == "undefined" || url  === '') {
                var classList = el.attr('class').split(/s+/);
                $.each(classList, function (idx, item) {
                    if(item.indexOf('MAINURL') >=0){
                        url = item.replace('MAINURL',main_url).trim();
                    }
                })
            }

        }
        $('.sidebar-post').empty();
        $('.sidebar-post').append('<span class="close-sidebar-post"></span><span class="loading-circle"><i class="fas fa-circle-notch fa-spin"></i></span>');
        if(!$('body').hasClass('open-right-sidebar')){
            var scrollbarWidth = getScrollbarWidth();
            if(scrollbarWidth > 0){
                $('body').css('padding-right',scrollbarWidth+'px');
            }
            $('body').addClass('open-right-sidebar');
        }
        $.ajax({
            url: '<?php echo admin_url('admin-ajax.php')?>',
            data: {action: 'load_sidebar_post', url: url},
            type: 'POST',
            success: function(res){
                if(res !== ''){
                    if(!$('#vc_accordion_script-js').length){
                        $('<script>')
                            .attr('id', 'vc_accordion_script-js')
                            .attr('src', '<?php echo get_site_url()?>/wp-content/plugins/js_composer/assets/lib/vc_accordion/vc-accordion.min.js?ver=6.7.0')
                            .appendTo('head');
                    }
                    $('.sidebar-post').empty();
                    $('.sidebar-post').append('<div class="sidebar-content portfolio-template-default single single-portfolio"><span class="close-sidebar-post"></span>'+res+'</div>');
                    window.vc_js();
                    console.log(Kalium);
                    galleryContentPost();
                    Kalium.Media.VideoJS.initVideoElements();
                }
            }
        })
    }
});

Find first repeated number javascript

I’ve a task to create the function and check which number repeats first in array (numbers). I need to create variable firstIndex in this function. I need to check which number repeats first and assign its index to firstIndex. Then write this variable to the console – outside of the for loop.
Finally return firstIndex from the function.
I wrote code below but something is wrong here, can you advise?

const numbers = [2, 4, 5, 2, 3, 5, 1, 2, 4];
function indexOfRepeatedValue(array) {
    const firstIndex = numbers[0];
    for (let i = 0; i < array.length; i++) {
        for(let j = i + 1; j < array.length; j++){
           if(firstIndex === array [j]) {
               return i;
           }
        }
    }
}
const firstIndex = indexOfRepeatedValue(numbers);
console.log(firstIndex);

Smartchain – Alternatives to covalentAPI endpoint balances_v2

I’m working in a wallet and we need to show the user tokens/assets in the binance-smartchain.
We are using covalentAPI and the endpoint balances_v2.
But this endpoint isn’t reliable, is common to have a 562 status response

562: Failed to connect to upstream third-party service - The API server can’t reach the external server where the data is hosted at the moment. This is intentionally done in order to avoid returning erroneous data.

Does anyone knows any alternative to covalent?

How to retrieve and change data from json file

I am having difficulties accessing my json file from my javascript file. I would like to change the data in the status section of my json file once a submit button is clicked on the webpage. I am aware that I would use ajax to achieve this goal, but I do not know how to access the json file.

This is the db.json file

{
{
  "assets": [
    {
      
      "id": "0946",
      "manufacturer": "SONY",
    },
    {
      "id": "0949",
      "manufacturer": "AUDIOTECNIA"
      
    }
],
  "transfers": [
    {
      "id": 1,
      "status": "in-progress"
    }
               ]
}

This is my Javascript file

 $('form').on('submit', function(e){
        e.preventDefault();

        parsedData = JSON.parse(db.json);
        console.log(parsedData[0].id)


    //Changing Status 

    $.ajax({ 
        type: "PATCH",
        url: `http://localhost:3000/transfers/`
        
        
    });

I’ve tried using parseData because I read that is how to retrieve the object, from the json file, but I do not believe I am writing it correctly. What documentation or steps would one recommend for solving this issue?