convert one array data to another data with new changes

I want to convert one data array to another array with new change means, if id match then push data into current one otherwise create new object with second id

letfinaldata=[]

let data =[{id:1,name:"meet"},{id:2,name:"raj"},{id:1,name:"hari"},{id:3,name:"hari"},{id:2,name:"ram"}]

//I want this below array how can I archive this.?

finaldata= [ { id: 1, names: [ 'meet', 'hari' ] },
  { id: 2, names: [ 'raj', 'ram' ] },
  { id: 3, names: [ 'hari' ] }]

/usr/bin/bash: C:UsersRamanAppDataLocalTemppostinstall-1656089066815.sh: command not found

$ npx create-react-app ramana
npm WARN config global --global, --local are deprecated. Use --location=global instead.

Creating a new React app in C:UsersRamanDesktopNew folder (2)ramana.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template…

npm ERR! code 127
npm ERR! path C:UsersRamanDesktopNew folder (2)ramananode_modulescore-js
npm ERR! command failed
npm ERR! command C:Program FilesGitbinbash.exe -c ‘C:UsersRamanAppDataLocalTemppostinstall-1656089066815.sh’
npm ERR! /usr/bin/bash: C:UsersRamanAppDataLocalTemppostinstall-1656089066815.sh: command not found

npm ERR! A complete log of this run can be found in:
npm ERR! C:UsersRamanAppDataLocalnpm-cache_logs2022-06-24T16_40_55_472Z-debug-0.log

Aborting installation.
npm install –no-audit –save –save-exact –loglevel error react react-dom react-scripts cra-template has failed.

Deleting generated file… package.json
Deleting ramana/ from C:UsersRamanDesktopNew folder (2)
Done.

Javascript prevent column headers from scrolling with page

I am making a small app in Shiny, however I believe that this issue can fixed with just some Javascript knowledge.

I am using the excelR package with Shiny to display some tables. This package is simply using the jexcel/jspreadsheet plugin and translates it into useable R functions – as such, the underlying javascript of the app is the same as a website using vanilla javascript.

enter image description here

How can I prevent the column headers to follow the scroll like in the gif above?
I cannot seem to find the documentation for that specific behaviour, so I was wondering if there was a way to overwrite the Javascript for it perhaps?

Cloned Custom HTML Element does not become custom element until it’s attached to the main DOM?

Consider the following scenario where I have a list of custom elements which is dynamically created. The CustomElement has a custom property displayName that should do something when set:

class CustomElement extends HTMLElement {
  set displayName(v) {
    this.querySelector(".name").textContent = v;
  }
}
customElements.define("custom-element", CustomElement)

const template = document.querySelector("template");
const list = document.querySelector(".list");
document.querySelector("button").addEventListener("click", () => {
  const customElTemplate = template.content.firstElementChild;
  console.log("Template constructor: ", customElTemplate.constructor.name);
  const el = template.content.firstElementChild.cloneNode(true);
  console.log("Cloned el constructor:", el.constructor.name);
  
  el.displayName = "Should has content";
  
  const frag = new DocumentFragment();
  frag.appendChild(el);
  console.log("Cloned el in DocumentFragment constructor:", el.constructor.name);
  
  list.appendChild(frag);
  console.log("Cloned el in Document constructor:", el.constructor.name);
});
custom-element {
  display: block;
  margin-bottom: .5rem;
  border: 1px solid black;
}
<template>
  <custom-element><span class="name"></span></custom-element>
</template>

<button>Add Item</button>

<div class="list"></div>

When clicking the button, the console output are:

Template constructor:  HTMLElement
Cloned el constructor: HTMLElement
Cloned el in DocumentFragment constructor: HTMLElement
Cloned el in Document constructor: CustomElement

As you can see, the cloned element doesn’t become CustomElement until it’s attached to the root document and displayName is simply a plain property that does nothing.

el.displayName = "Should has content"; won’t work even after attaching to a DocumentFragment. It only works after attaching to the document (i.e. after list.appendChild(frag); in the above example)

Why is this happening? Is there anyway I can set up the element before attaching it to the main document?

Changing height of border-right according to scrollPosition

Sorry if this is a dumb question, I am super new to programming in html and Javascript.

I know, that I can change some transformation with the scrollpositon, but right now I’m a bit lost. I want to increase the height of a box, when the user scrolls down.

It starts with

“height: 60px;”

and then I’d like it to grow like “height =”60 + scrollY * a very small number + px”.

Is there any way to achieve this?

Kind regards and greetings!

Handling canvas (through Filerobot) in modal

Goal

I am building a Django app where a user can upload and edit (crop and annotate) an image in a Bootstrap 4 Modal. To this end, I used Filerobot Image Editor. Everything seemed to be working ok: I can upload an image and edit it in the modal. I can even save it in my database through ajax. My goal is to be able to open/close the modal as many times as needed while keeping the image editor working. Note: every time the modal is opened, a new image is loaded, so there is no need to keep the modification history across the openings/closings of the modal.

Problem

Currently, when I close the modal, I get the following error in the console:

filerobot-image-editor.min.js:8
DOMException: Failed to execute
‘drawImage’ on ‘CanvasRenderingContext2D’: The image argument is a
canvas element with a width or height of 0.
at og.drawImage (http://127.0.0.1:8000/static/js/filerobot-image-editor.min.js:8:202927)
at _m.drawScene (http://127.0.0.1:8000/static/js/filerobot-image-editor.min.js:8:254091)
at http://127.0.0.1:8000/static/js/filerobot-image-editor.min.js:8:236299
at Array.forEach ()
at Jg._drawChildren (http://127.0.0.1:8000/static/js/filerobot-image-editor.min.js:8:236274)
at Jg.drawScene (http://127.0.0.1:8000/static/js/filerobot-image-editor.min.js:8:235350)
at Jg.drawScene (http://127.0.0.1:8000/static/js/filerobot-image-editor.min.js:8:264669)
at Jg.draw (http://127.0.0.1:8000/static/js/filerobot-image-editor.min.js:8:229035)
at http://127.0.0.1:8000/static/js/filerobot-image-editor.min.js:8:242010
at Array.forEach ()

Whenever I get this error, Filerobot is just gone when I reopen the modal.

Note: the error only appears when the image has been edited.

What I’m asking for

I’m completely new to image editing and canvas. I’m not sure whether the error I get is specific to Filerobot or is generic to canvas. I’d appreciate any tip that could me help me debug this issue.

My code

(See below for working fiddle, I couldn’t get it to work through SO)

const {TABS, TOOLS} = window.FilerobotImageEditor;
const config = {
  // source: 'https://scaleflex.airstore.io/demo/stephen-walker-unsplash.jpg',
  source: 'https://upload.wikimedia.org/wikipedia/commons/9/9a/Gull_portrait_ca_usa.jpg',
  tabsIds: [TABS.ADJUST, TABS.ANNOTATE], // or ['Adjust', 'Annotate', 'Watermark']
  defaultTabId: TABS.ADJUST, // or 'Annotate'
  defaultToolId: TOOLS.CROP, // or 'Text'
  closefAterSave: false,
  disableZooming: false
};

// Génération de l'éditeur
const filerobotImageEditor = new FilerobotImageEditor(
  $('#filerobot-editor')[0],  
  config,
);

filerobotImageEditor.render({
  onClose: (closingReason) => {
    filerobotImageEditor.terminate();
  },
});

$('.my-class').on('click', function(){
  let selSaveButton = $('.FIE_topbar-save-wrapper');
  let clone = selSaveButton.clone(false);
  clone.addClass('my-sc-lxwit0-0');
  selSaveButton.replaceWith(clone);
});

$(document).on('click', '.my-sc-lxwit0-0', function(){
  let canvas = $('canvas')[0];
  let dataURL = canvas.toDataURL();
  let boolModalClose = $(this).hasClass('close-modal') ? true : false;

  console.log('ajax: do backend stuff with dataURL');
  
  if (boolModalClose) {
    $('#my-id').modal('hide');
  }

});
<script src="https://scaleflex.cloudimg.io/v7/plugins/filerobot-image-editor/latest/filerobot-image-editor.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="my-img" src="">
<button type="button" class="btn btn-block btn-sm btn-outline-primary my-class" data-toggle="modal" data-target="#my-id">
  Edit photo
</button>

<div class="modal fade" id="my-id" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog" role="document">
      <div class="modal-content" data-ddl-termine="False">

        <div class="modal-body">
          <div id="filerobot-editor"></div>
        </div>  <!-- modal-body -->

        <div class="modal-footer">
          <button type="button" class="btn btn-sm btn-secondary" data-dismiss="modal">Close</button>
          <button class="btn btn-sm btn-primary my-sc-lxwit0-0 close-modal" type="button">Save and close</button>
        </div>  <!-- modal-footer -->

      </div> <!-- modal-content -->
    </div> <!-- modal-dialog -->
  </div> <!-- modal -->

I reproduced a minimal working example in the following fiddle: https://jsfiddle.net/zd1kowa8/3/

However I’m not able to get the same error, I’m getting sometimes some “Tainted canvas” errors and also some “ResizedObserver loop limit exceeded” errors but not the one I’m usually getting.

I’m convinced I’m missing something with the use of canvas + modal so I figured I’d still try to ask a question and see if anyone could help me debug.

Thanks!

Offline Database for Item management? [closed]

I want to create a game with html, css, js… and want to convert it to an apk later.
The game has a lot of different items and characters that you can get multiple times and that are unique f.e.:

  • lets call a character bob.
  • my bob is level 10 and I just got another bob which is level 1
  • all bobs have their own stats like xp, equipped gear etc.

I thought the easiest way of dealing with the item and character management is by using a database but I have no idea how to do that “offline” when the game is finished

Cannot read property ‘close’ of null

I have a cron job program that checks for certain information and if a condition is met then it simultaneously casts audio message to all google home devices on a wifi network use google text to speech. It works, but crashes after delivering the message and I’m not sure how to get it to continue checking for information updates via cron without crashing. How can I get the program to not crash and just continue cron?

Error: Cannot read property 'close' of null

enter image description here

cron.js

const { checkForNewMessages } = require("./checkForNewMessages");
const { broadcastMessage } = require("./broadcastMessage");

var cron = require("node-cron");

cron.schedule("* * * * *", async () => {
  try {
    const message = await checkForNewMessages();
    if (message) {
      broadcastMessage(message);
    } else {
      const today = new Date();
      // get the date and time
      const now = today.toLocaleString();
      console.log("No new updates -", now);
    }
  } catch (e) {
    console.log("FAILED TO CHECK FOR NEW MESSAGES", e.message);
  }
});

broadcastMessage.js

var Client = require("castv2-client").Client;
var DefaultMediaReceiver = require("castv2-client").DefaultMediaReceiver;
const googleTTS = require("google-tts-api");

function broadcastMessage(message) {
  var App = {
    playin: false,
    DeviceIp: "",
    Player: null,
    GoogleHome: function (host, url) {
      var client = new Client();
      client.connect(host, function () {
        client.launch(DefaultMediaReceiver, function (err, player) {
          client.setVolume({ level: 5 }, function (err, volume) {
            if (err) {
              // Handle error as appropriate
              console.log("Error on setVolume:", err);
            } else {
              console.log("Sending new alert");
            }
          });

          var media = {
            contentId: url,
            contentType: "audio/mp3",
            streamType: "BUFFERED",
          };
          App.Player = player;
          App.Player.load(media, { autoplay: true }, function (err, status) {
            App.Player.on("status", function (status) {
              if (status.playerState === "IDLE" && App.playin === false) {
                client.close();
              }
            });
          });
        });
      });
      client.on("error", function (err) {
        console.log("Error: %s", err.message);
        client.close();
      });
    },
    run: function (ip, text) {
      App.DeviceIp = ip;
      const url = googleTTS.getAudioUrl(text, {
        lang: "en-US",
        slow: false,
        host: "https://translate.google.com",
      });
      App.GoogleHome(App.DeviceIp, url, function (res) {
        console.log(res);
      });
    },
    broadcast: function (text) {
      const IPs = ["10.0.0.9", "10.0.0.10", "10.0.0.11", "10.0.0.12"];
      for (var s of IPs) {
        App.run(s, text);
      }
    },
  };

  App.broadcast("Incoming alert");
  setTimeout(() => {
    App.broadcast(message);
  }, 4000);
}

module.exports = {
  broadcastMessage,
};

React – Calling a function from content management system html

I have an odd case that I need to solve. I have a react app that dynamically injects html content via (dangerouslySetInnerHTML={{__html: data}}). Think of it as a pseudo content management system with some legacy html content with some embedded javascript method calls, so I can’t change the follling html block.

Example embedded html block (injected using dangerouslySetInnerHTML):

<p><a href="javascript:showvideo('http://urldir/vid.mp4',vwidth,vheight,0)">Launch vid.</a></p>

in my react component:

function showvideo(url,width,height,id){
  console.log('called showvideo')
}

I keep getting ‘Uncaught ReferenceError: showvideo is not defined’

How do I call a function with <a href='javascript:myfunction'> in react?

The Slides is showing on mobile app but not showing on web app React Native(Using Expo)

Mobile app:
[here][1]

Web app:
[here][2]

The Code:

import React, { useEffect, useState } from "react";
import {
  Animated,
  Dimensions,
  Image,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Text,
  View,
} from "react-native";

const { width } = Dimensions.get("window");
const BASE_UNIT = 8;

const slides = [
  {
    title: "Secured, forever.",
    description:
      "Secured Curabitur lobortis id lorem id bibendum. Ut id consectetur magna. Quisque volutpat augue enim, pulvinar lobortis.",
    img:
      "https://raw.githubusercontent.com/react-ui-kit/dribbble2react/master/vpn-app/assets/images/welcome.png",
  },
  {
    title: "Encrypted, forever.",
    description:
      "Encrypted Curabitur lobortis id lorem id bibendum. Ut id consectetur magna. Quisque volutpat augue enim, pulvinar lobortis.",
    img:
      "https://raw.githubusercontent.com/react-ui-kit/dribbble2react/master/vpn-app/assets/images/encrypted.png",
  },
  {
    title: "Privacy, forever.",
    description:
      "Privacy Curabitur lobortis id lorem id bibendum. Ut id consectetur magna. Quisque volutpat augue enim, pulvinar lobortis.",
    img:
      "https://raw.githubusercontent.com/react-ui-kit/dribbble2react/master/vpn-app/assets/images/privacy.png",
  },
];

const Dots = ({ scrollX }) => {
  const dotPosition = Animated.divide(scrollX, width);

  return (
    <View style={styles.dotWrapper}>
      {slides.map((item, index) => {
        const opacity = dotPosition.interpolate({
          inputRange: [index - 1, index, index + 1],
          outputRange: [0.3, 1, 0.3],
          extrapolate: "clamp",
        });

        return <Animated.View key={`dot-${index}`} style={[styles.dot, { opacity }]} />;
      })}
    </View>
  );
};

const SlideTexts = ({ slideIndex }) => {
  const slide = slides[slideIndex];

  return (
    <>
      <Animated.Text style={styles.title}>{slide && slide.title}</Animated.Text>
      <Animated.Text style={styles.description}>{slide && slide.description}</Animated.Text>
    </>
  );
};

const SlideImages = ({ scrollX }) => {
  return (
    <View style={{ flex: 2 }}>
      <ScrollView
        horizontal
        pagingEnabled
        scrollEnabled
        decelerationRate={0}
        scrollEventThrottle={BASE_UNIT * 2}
        snapToAlignment="center"
        showsHorizontalScrollIndicator={false}
        onScroll={Animated.event([{ nativeEvent: { contentOffset: { x: scrollX } } }], {
          useNativeDriver: false,
        })}>
        {slides.map((item, index) => (
          <View key={`img-${index}`} style={styles.slideWrapper}>
            <Image source={{ uri: item.img }} resizeMode="contain" style={styles.slideImage} />
          </View>
        ))}
      </ScrollView>
    </View>
  );
};

const Vpn = () => {
  const scrollX = new Animated.Value(0);
  const [slideIndex, setSlideIndex] = useState(0);

  useEffect(() => {
    scrollX.addListener(({ value }) => {
      setSlideIndex(Math.floor(value / width));
    });
  });

  return (
    <View style={styles.container}>
      <SlideImages scrollX={scrollX} />
      <View style={styles.bottomWrapper}>
        <SlideTexts slideIndex={slideIndex} />
        <Dots scrollX={scrollX} />
        <Animated.View style={styles.buttonWrapper}>
          <TouchableOpacity activeOpacity={0.75} style={styles.buttonContainer} onPress={() => {}}>
            <Text style={styles.buttonTitle}>GET STARTED</Text>
          </TouchableOpacity>
        </Animated.View>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
  slideWrapper: {
    width,
    alignItems: "center",
  },
  slideImage: {
    width: width / 1.5,
    height: "100%",
  },
  title: {
    textAlign: "center",
    fontSize: BASE_UNIT * 3,
    fontWeight: "bold",
  },
  description: {
    textAlign: "justify",
    fontSize: BASE_UNIT * 2,
    marginHorizontal: BASE_UNIT * 3,
    marginVertical: BASE_UNIT * 2,
  },
  bottomWrapper: {
    flex: 1,
    justifyContent: "flex-end",
  },
  buttonTitle: {
    color: "#FFFFFF",
    marginHorizontal: BASE_UNIT * 6,
    marginVertical: BASE_UNIT,
    fontWeight: "bold",
  },
  buttonContainer: {
    backgroundColor: "#00A9FC",
    borderRadius: BASE_UNIT * 2,
  },
  buttonWrapper: {
    alignItems: "center",
    margin: BASE_UNIT * 3,
  },
  dotWrapper: {
    flex: 0,
    flexDirection: "row",
    justifyContent: "center",
    marginVertical: BASE_UNIT,
  },
  dot: {
    flex: 0,
    width: BASE_UNIT,
    height: BASE_UNIT,
    margin: BASE_UNIT / 2,
    borderRadius: BASE_UNIT,
    backgroundColor: "gray",
  },
});

export default Vpn;

If someone can help me I’ll be thankful
Everything is good on the mobile app but the web app is not showing the slides and I there is no error on the console
Everything is good on the mobile app but the web app is not showing the slides and I there is no error on the console
[1]: https://i.stack.imgur.com/gAvKN.png
[2]: https://i.stack.imgur.com/00axb.png

How to just pick those matching regex which doesn’t contains any value behind

Like I have a text

Lorem https://open.spotify.com/episode/0xmdIsJ28Pwix7MOKcK3Zv?si=50957b8039154544 loremhttps://open.spotify.com/episode/0xmdIsJ28Pwix7MOKcK3Zv?si=50957b8039154544lorem

I want my regex to just pick the first occurrence because it’s have empty space behind which show sit’s independent

Does any body knows how to check that?

Here’s my current regex

/(https://open.spotify.com/episode/|spotify:user:spotify:playlist:)([a-zA-Z0-9]+)(.*)/g

The (Chart Js) library only renders a chart in a Post when the user is logged into WordPress

First of all I am a beginner user in wordpress; The last few weeks I have tried to build a “graph” that will be shown to the user in a Post at the end of a survey. I carried out the survey using the GravityForms plugin, the “Post” where the result of the survey will be displayed next to the graph is automatically created by a GravityForms Add-On after the user presses the “Submit” button. I was able to make the chart using ChartJs after inserting a reference to a CDN in the topic header as follows:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js" integrity="sha512-vBmx0N/uQOXznm/Nbkp7h0P1RfLSj0HQrFSzV8m7rOGyj30fYAOKHYvCNez+yM8IrfnW0TCodDEjRqf6fodf/Q==" crossorigin="anonymous" referrerpolicy="no-referrer" type="application/javascript"></script>

I made the chart using hooks from functions.php to be able to handle the data that the user inserts in the form and thus insert in the content of the Post an element of type where the chart with the results of the survey will be:

Chart maded with ChartJs

The problem is that this only works when I am logged into WordPress, when I share the link so that someone else can fill out the survey or when I do it from incognito mode instead of showing me the chart, the Post shows me raw text:

Raw text

Why is it that I can only see the chart when I am logged into WordPress?

how to improve my code javascript to be shorter [closed]

my code is already doing what I want, so it’s functional, now my concern is, if there is a way to make it easier to read or even better and shorter my code, it’s supposed to check if 3 ‘X’ or ‘O’ are continuous in 3 cells in a row, column or diagonal, code for the string ‘O’ is the same as ‘X’ only changes classList.contains(‘targetO’); else is the same. it’s a tictactoe game.

  //horizontal X wins
if (td[0].classList.contains ('targetX') && td[1].classList.contains ('targetX') && td[2].classList.contains ('targetX')){ alert('X player Won')}
if (td[3].classList.contains ('targetX') && td[4].classList.contains ('targetX') && td[5].classList.contains ('targetX')){ alert('X player Won')};
if (td[6].classList.contains ('targetX') && td[7].classList.contains ('targetX') && td[8].classList.contains ('targetX')){ alert('X player Won')};

//vertical X wins
if (td[0].classList.contains ('targetX') && td[3].classList.contains ('targetX') && td[6].classList.contains ('targetX')){ alert('X player Won')}
if (td[1].classList.contains ('targetX') && td[4].classList.contains ('targetX') && td[7].classList.contains ('targetX')){ alert('X player Won')};
if (td[2].classList.contains ('targetX') && td[5].classList.contains ('targetX') && td[8].classList.contains ('targetX')){ alert('X player Won')};

//diagonal X wins

if (td[0].classList.contains ('targetX') && td[4].classList.contains ('targetX') && td[8].classList.contains ('targetX')){ alert('X player Won')}
if (td[2].classList.contains ('targetX') && td[4].classList.contains ('targetX') && td[6].classList.contains ('targetX')){ alert('X player Won')};

How to render different data in Cesium without reloading the map?

The graphData field here will update to render different boxes on the Cesium map. Which works perfectly until I want to edit the timeline time range. If I remove clockViewModel here everything is find. But with that field, every time I change graphData the map reloads. Is there a way I can change graphData, while keeping a custom timeline, without reloading the map?

  <Viewer
    id="wdt-map-viz-cesium"
    clockViewModel={myClock}
    >
     <Camera/>
        <CameraFlyTo
            destination={startCoordinates}
            orientation={startOrientation}
            duration={0}
        />
    {
      graphData && graphArray
        ? (
          graphData.map((rule, index) => (
            <Entity
              key={rule.apc}
              position={Cartesian3.fromDegrees(
                rule.location.longitude,
                rule.location.latitude,
                graphArray[index].offset,
              )}
              name={rule.apc}
              description={`<div>Days to deploy: ${rule.daysToDeploy}</br>`}
              box={graphArray[index]}
            />
          ))
        ) : ''
    }
  </Viewer>