How do vector based drawing apps generally work?

I tried to make my own kind of vector based drawing app with javascript and canvas, but calculating and rendering even a few lines seems to be unbelievably laggy, especially when panning or zooming (I’m currently just re-rendering every line when panning or zooming).

I’m wondering now if it is just the browser not being suited for that or if apps like Inkscape or even Goodnotes, instead of re-rendering the lines every time, just use a different kind of approach. Google has a kind of okay-ish app called “Google canvas” which runs on browser, but even compared to apps on desktop (like Inkscape) it seems terribly slow when drawing a lot of lines. 

Even when not working on browser, re-rendering every line after actions like panning, zooming, undoing etc. seems to me like a terrible idea, considering that apps like Inkscape run smoothly without a single lag even after hundreds of lines drawn, so if there is a different approach, which I am pretty sure there is, how does it work?

React Router V6 UseContextApi: object null is not iterable

I am having a small problem with my code.

So, this is the first time I am trying to implement context on a project but I am getting an error:

Uncaught TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator))

I guess is because the object is not being accessed by the child component.

Here is the parent component (My Routes)

import {UserContext} from "../Context/UserContext"

function WebRoutes() {
  const [user,setUser]=useState(null);

  return (
    <UserContext.Provider value={(user,setUser)}>
    <Router>
        <Routes>
            <Route path="/" element={<Login/>}/>
            <Route path="/home" element={<Home/>}/>
            <Route path="/departaments" element={<Departaments/>}/>
            <Route path="/product/:id" element={<Product/>}/>
            <Route path="*" element={<NotFound/>}/>
        </Routes>
    </Router>
    </UserContext.Provider>
  )
}

This one will be the child component:

import React, {useState, useContext} from 'react'
import {UserContext} from '../../Context/UserContext';

const [user,setUser]=useContext(UserContext)

That’s the way I am trying to get the context.

I am not sure where I am wrong.

This is the UserContext file:

import {createContext} from "react"

export const UserContext = createContext(null);

I would appreciate any kind of help. I am trying to achieve this by using a course.

Thanks a lot in advance.

You May need an appropriate loader to handle this file type error when using React UseState

Rightbar.jsx code snippet:

import "./rightbar.css"
import {Users} from "../../dummyData"
import Online from "../online/Online";
import { useEffect, useState, useContext } from 'react';
import axios from 'axios';
import { AuthContext } from "../../context/AuthContext";
import { Link } from "react-router-dom";
import { Add, Remove } from "@material-ui/icons";

export default function Rightbar({ user }) {
  const PF = process.env.REACT_APP_PUBLIC_FOLDER;
  const [subscriptions, setSubscriptions] = useState([]);
  const { user: currentUser, dispatch } = useContext(AuthContext);
  const [followed, setFollowed] = useState(
    currentUser.followings.includes(user?.id)
  ); 

Error:
error

I’ve seen similar issues on here and have tried various solutions with installing file-loader and creating a webpack.config.js file. Although none of the solutions have seemed to work. I’m using npm instead of yarn. Any help would be appreciated!

Can I send with websocket value of a variable being updated with a Kafka topic

Problem: I have an object attribute .status that is updated with a Kafka topic, then I send it through websocket. My problem is that each time I ask from the Client side (javascript), then the Server (websockets + asyncio in Python) will start a Kafka consumer from the beginning.

Question: Is it possible to have the Kafka for loop (for msg in consumer:) updating my custom_obj object and send its .status value only when asked for it?

What I’ve tried

This is what I have so far on the server side:

import asyncio
import websockets
from kafka import KafkaConsumer
import Custom_obj

async def test(websocket):
    consumer = KafkaConsumer(
    'kafka-topic', 
    bootstrap_servers=['kafka.server.com:1234'],
    auto_offset_reset='earliest', #Must start from the beginning to build the object correctly
    enable_auto_commit=True,
    )
    custom_obj = Custom_obj()
    for msg in consumer:
        msg_dec = msg.value.decode()
        custom_obj.update(msg_dec)
        await websocket.send(custom_obj.status) 

async def main():
    async with websockets.serve(test, "localhost", 1234):
        await asyncio.Future()  # run forever

if __name__ == "__main__":
    asyncio.run(main())

Client side (javascript in Vue component) code:

created() {
  const ws = new WebSocket('ws://localhost:1234');
  ws.onopen = function(e) {
    ws.send('Got here!')
    this.connectionStatus = 'Connected.'
  }
  ws.onerror = function(e) {
    ws.close()
  }
  ws.onclose = function(e) {
    this.connectionStatus = 'Disconnected.'
  }
  ws.onmessage = (e) => {
    console.log(1)
  }

Project object from Nested Array MongoDB

[
  {
    "_id": "grandParentId",
    "types": [
      {
        "_id": "parentId",
        "files": [
          {
            "url": "1.example.com",
            "_id": "1childId"
          },
          {
            "url": "2.example.com",
            "_id": "2childId"
          }
        ]
      }
    ]
  }
]

cond: { _id: 2childId }

expected output: {
“url”: “2.example.com”,
“_id”: “2childId”
}

question 2: is this a good approach or should I just use loops to get the desired output?

Make ECharts.js full screen

I have been trying to reproduce this Highcharts.js functionality in Echarts.js to make a plot full screen: https://www.highcharts.com/demo/line-basic.

Note that by clicking on the top right button you can select a full screen mode, which can then be disabled by pressing Esc.

I have tried creating a custom button in Echarts.js like this one in Highcharts https://jsfiddle.net/BlackLabel/1ga2fqL0/ without much success:

btn.addEventListener('click', function() {
  Highcharts.FullScreen = function(container) {
    this.init(container.parentNode); // main div of the chart
  };

  Highcharts.FullScreen.prototype = {
    init: function(container) {
      if (container.requestFullscreen) {
        container.requestFullscreen();
      } else if (container.mozRequestFullScreen) {
        container.mozRequestFullScreen();
      } else if (container.webkitRequestFullscreen) {
        container.webkitRequestFullscreen();
      } else if (container.msRequestFullscreen) {
        container.msRequestFullscreen();
      }
    }
  };
  chart.fullscreen = new Highcharts.FullScreen(chart.container);
})

Any ideas?

TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client – DiscordJS

I am actually making a Discord Bot and I’m trying to make a command and events handler for it.

First of all, here is the code of my main file :

const Discord = require('discord.js');
const fs = require("fs"); 
const client = new Discord.Client({
  intents: 
  [
    Discord.Intents.FLAGS.GUILDS, 
    Discord.Intents.FLAGS.GUILD_MESSAGES, 
    Discord.Intents.FLAGS.GUILD_MEMBERS, 
    Discord.Intents.FLAGS.DIRECT_MESSAGES 
  ]
});

const {TOKEN} = require('./config.json');

client.commands = new Discord.Collection();

const functions = fs.readdirSync(`./src/functions`).filter(file => file.endsWith(".js"));
const eventFiles = fs.readdirSync(`./src/events`).filter(file => file.endsWith(".js"));
const commandFolders = fs.readdirSync(`./src/commands`);

(async () => {
  for (file of functions){
    require(`./src/functions/${file}`)(client);
  }
  client.handleEvents(eventFiles, "./src/events");
  client.handleCommands(commandFolders, "./src/commands");
  client.on("ready", () => {
    client.user.setActivity("Lyna !", {type: "WATCHING"});
  })
  client.login(TOKEN);
  
})();

When I run my bot, I got an error about the intents. Here is the full error :

throw new TypeError('CLIENT_MISSING_INTENTS');
            ^

TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.
    at Client._validateOptions (C:UsershpdesktopDiscordLynaLynanode_modules←[4mdiscord.js←[24msrcclientClient.js:544:13)
    at new Client (C:UsershpdesktopDiscordLynaLynanode_modules←[4mdiscord.js←[24msrcclientClient.js:73:10)
    at Object.<anonymous> (C:UsershpdesktopDiscordLynaLynasrceventsready.js:2:16)
←[90m    at Module._compile (node:internal/modules/cjs/loader:1101:14)←[39m
←[90m    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)←[39m
←[90m    at Module.load (node:internal/modules/cjs/loader:981:32)←[39m
←[90m    at Function.Module._load (node:internal/modules/cjs/loader:822:12)←[39m
←[90m    at Module.require (node:internal/modules/cjs/loader:1005:19)←[39m
←[90m    at require (node:internal/modules/cjs/helpers:102:18)←[39m
    at Client.client.handleEvents (C:UsershpdesktopDiscordLynaLynasrcfunctionshandleEvents.js:15:27) {
  [←[32mSymbol(code)←[39m]: ←[32m'CLIENT_MISSING_INTENTS'←[39m
}

So apparently, the issue come from my handleEvents file. So here it is :

module.exports = (client) => {
    client.handleEvents = async (eventFiles, path) => {
        for (const file of eventFiles){
            const event = require(`../events/${file}`);
            if (event.once) {
                client.once(event.name, (...args) => event.execute(...args, client));
            } else {
                client.on(event.name, (...args) => event.execute(...args, client));
            }
        }
    };
};

My intents are in my main file and even when I add it in my handleEvents file so I’m actually not able to find how to fix this issue.

Multi-Step Form Required Fields To Go to Next Step

I’m trying to merge two codes for several days now without success. Is there someone who can help me with that please ? I’m a total beginner with web developpment, i’m sorry if it’s a mess. It’s all copy-paste essentially. The first part of the javascript is working with no issues, the second part of it has to be “added” to the first one.

/* Multistep code */

const prevBtns = document.querySelectorAll(".btn-prev");
const nextBtns = document.querySelectorAll(".btn-next");
const progress = document.getElementById("progress");
const formSteps = document.querySelectorAll(".form-step");
const progressSteps = document.querySelectorAll(".progress-step");

let formStepsNum=0;

nextBtns.forEach((btn) => {
    btn.addEventListener("click", () => {
      formStepsNum++;
      updateFormSteps();
      updateProgressbar();
    });
  });
  
  prevBtns.forEach((btn) => {
    btn.addEventListener("click", () => {
      formStepsNum--;
      updateFormSteps();
      updateProgressbar();
    });
  });
  
  function updateFormSteps() {
    formSteps.forEach((formStep) => {
      formStep.classList.contains("form-step-active") &&
        formStep.classList.remove("form-step-active");
    });
  
    formSteps[formStepsNum].classList.add("form-step-active");
  }
  
  function updateProgressbar() {
    progressSteps.forEach((progressStep, idx) => {
      if (idx < formStepsNum + 1) {
        progressStep.classList.add("progress-step-active");
      } else {
        progressStep.classList.remove("progress-step-active");
      }
    });
  
    const progressActive = document.querySelectorAll(".progress-step-active");
  
    progress.style.width =
      ((progressActive.length - 1) / (progressSteps.length - 1)) * 100 + "%";
  }

/*Validation code*/

$(document).ready(function(){
$(".btn-next").click(function(){
    var form = $("#register-user");
    form.validate({
      errorElement: 'span',
      errorClass: 'help-block',
      highlight: function(element, errorClass, validClass) {
        $(element).closest('.input-group').addClass("has-error");
      },
      unhighlight: function(element, errorClass, validClass) {
        $(element).closest('.input-group').removeClass("has-error");
      },
      rules: {
        first_name: {
          required: true,
          minlength: 3,
        },
        last_name: {
          required: true,
          minlength: 3,
        },
        user_login: {
          required: true,
        },
        user_pass: {
          required: true,
        },
        user_pass2: {
          required: true,
          equalTo: '#user_pass',
        },
        user_email: {
          required: true,
        },
        
      },      
      messages: {
        first_name: {
          required: "First name required",
        },
        last_name: {
            required: "Last name required",
        },
        user_login: {
            required: "Username required",
        },
        user_pass: {
          required: "Password required",
        },
        user_pass2: {
          required: "Password required",
          equalTo: "Password don't match",
        },
        user_email: {
          required: "Email required",
        },
      }
    });


if (form.valid() === true){
}})});
            <form name="myForm" action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post" class="form" id="register-user">
                <!-- progress bar -->
                <div class="progressbar">
                <div class="progress" id="progress"></div>
                    <div class="progress-step progress-step-active" data-title="Intro"></div>
                    <div class="progress-step" data-title="contract"></div>
                    <div class="progress-step" data-title="ID"></div>
                    <div class="progress-step" data-title="Password"></div>
                </div>
                <!-- steps -->
                <div class="form-step form-step-active">
                        <div class="input-group">
                            <input type="text" name="first_name" id="first_name" placeholder='Prenom' required>
                        </div>
                        <div class="input-group">
                            <input type="text" name="last_name" id="last_name" placeholder='Nom' required>
                        </div>
                        <div class="input-group">
                            <input type="text" value= "<?php echo isset($_POST['user_login']) ? $_POST['user_login'] : ''?>" name="user_login" id="user_login" placeholder="Nom d'utilisateur" required>
                        </div>

                
                    <div class="">
                        <a href="#Step2" class="btn btn-next width-50 ml-auto">Suivant</a>
                    </div>
                </div>  
                <div class="form-step">
                    <div class="container">
                        <div class="input-group">
                            <input type="radio" name="occupation" id="reg_nurse" value="Registered Nurse" required>
                            <label for="reg_nurse">Registered Nurse</label>
                        </div>

                        <div class="input-group">
                            <input type="radio" name="occupation" id="prac_nurse" value="Practical Nurse" required>
                            <label for="prac_nurse">Practical Nurse</label>
                        </div>

                        <div class="input-group">
                            <input type="radio" name="occupation" id="nurse_prac" value="Nurse Practioner" required>
                            <label for="nurse_prac">Nurse Practioner</label>
                        </div>

                        <div class="input-group">
                            <input type="radio" name="occupation" id="midwife" value="Midwife" required>
                            <label for="midwife">Midwife</label>
                        </div>

                        <div class="input-group">
                            <input type="radio" name="occupation" id="reg_nurse_anes" value="Registered Nurse Anesthetist" required>
                            <label for="reg_nurse_anes">Registered Nurse Anesthetist</label>
                        </div>

                        <div class="input-group">
                            <input type="radio" name="occupation" id="nurse_spec" value="Nurse Specialist" required> 
                            <label for="nurse_spec">Nurse Specialist</label>
                        </div>

                    </div>
                        <div class="btns-group">
                            <a href="#Step1" class="btn btn-prev">Précédent</a>
                            <a href="#Step3" class="btn btn-next">Suivant</a>
                        </div>
                </div>
                        
                <div class="form-step">
                    <div class="container2">

                        <div class="input-group">
                            <input type="radio" name="contract" id="trav_cont" value="Travel Contact" required>
                            <label for="trav_cont">Travel Contact</label>
                        </div>

                        <div class="input-group">
                            <input type="radio" name="contract" id="FT_staf_pot" value="Full-time Staff Position" required>
                            <label for="FT_staf_pot">Full-time Staff Position</label>
                        </div>

                        <div class="input-group">
                            <input type="radio" name="contract" id="PT_staf_pot" value="Part-time Staff Position" required>
                            <label for="PT_staf_pot">Part-time Staff Position</label>
                        </div>

                        <div class="input-group">
                            <input type="radio" name="contract" id="not_work" value="Not Working" required>
                            <label for="not_work">Not Working</label>
                        </div>
                    </div>

                        <div class="btns-group">
                            <a href="#Step2" class="btn btn-prev">Précédent</a>
                            <a href="#Step4" class="btn btn-next">Suivant</a>
                        </div>
                </div>
                        
                <div class="form-step">
                        <div class="input-group">
                            <input type="email" value= "<?php echo isset($_POST['user_email']) ? $_POST['user_email'] : ''?>" name="user_email" id="user_email" placeholder='Votre email' required>
                        </div>

                        <div class="input-group">
                            <input type="password" name="user_pass" id="user_pass" placeholder='Votre mot de passe' required>
                        </div>

                        <div class="input-group">   
                            <input type="password" name="user_pass2" id="user_pass2" placeholder='Confirmez votre mot de passe' required>
                        </div>

                        <div class="btns-group">
                            <a href="#Step3" class="btn btn-prev">Précédent</a>
                            <input classe="btnsub" value="Inscription" type="submit"/>
                        </div>
                    </div>
            </form>

window.print() without printers causes the main process to crash in Electron App

I’m using Electron with react-js. whenever I call window.print() it shows the popup but if I tries to close it, it causes a crash and the whole window closed automatically.

btn.onClick = (e) => { 
    e.preventDefault
    window.print()
}

/* dependencies */
'version' : '17.0.1' ,
"react": "^17.0.2" ,
"electron-squirrel-startup": "^1.0.0"

So, my question is how to fix it in the Electron app, and can I use silent print in react-js if yes how I can use it?

HTML form, JS response

My is code

index.html:

<form action="https://localhost:1000/rest/api/submit-job/testhtml" method="GET">
        <div id="name-group" class="form-group">
          <label for="texta">texta</label>
          <input
            type="text"
            class="form-control"
            id="texta"
            name="texta"
          />
        </div>          
        <button type="submit" class="btn btn-success">
        
          Generate PDF
        </button>

form.js:

$(document).ready(function () {
  $("form").submit(function (event) {
    var formData = {
      texta: $("#texta").val(),
    };

    $.ajax({
      type: "GET",
      url: "https://localhost:10000/rest/api/submit-job/testhtml",
      data: formData,
      dataType: "text",
      encode: true,
    }).done(function (data) {
      console.log(data);
      document.write("<embed width='1300px' height='1250px' src=" + data + ">");      
    });
    event.preventDefault();
  });
  
});

My api returns PDF in base64 and it works just fine, but is there a better way to do it?
for example, those forms in index.html disappear and I don’t want them to disappear.
Thank you.

How to wrap the response of a json-server into a custom response

I am using the npm module json-server in order to set up a REST-API. I have set up a db.json with the following content:

{
  "home": [
        {
          "value": 1234,
          "number": 2
        },
        {
          "id": 1,
          ...
        },
        {
          "id": 2,
          ...
        }
      ]
}

I can easily return the entire array when requesting BASE_URL/home. I can also return an individual object when requesting BASE_URL/home/{id}. However, when doing so, what I would actually like to retrieve is NOT:

        {
          "id": 1,
          ...
        }

for id=1, but instead:

  [
    {
      "value": 1234,
      "number": 2
    },
    {
      "id": 1,
      ...
    }
  ]

What does this mean? – Well, I want to retrieve an array ALWAYS. I also want the first object, which contains properties “value” and “number” to ALWAYS be inside the returned array. And in addition to this I want the requested object to be inside this array.

I believe that I have to start an express server instead of the json-server in order for this to work. Unfortunately, I am not familiar with express. I have assembled an educated guess as an example, here it is:

const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()

server.use(middlewares)

server.get('/api/v1/', (req, res) => {
    res.jsonp(req.query)
  })


server.use(jsonServer.bodyParser)
server.use((req, res, next) => {
  if (req.method === 'GET') {
      const alwaysReturn = {
        "value": 1234,
        "number": 2
      };
      let resArray = [];
      resArray.push(alwaysReturn);
      resArray.push(res.body)
      res.body = resArray;
  }
  next()
}) 
 
server.use(router)

This is probably very far off from a solution. Can somebody help me out?

How to find spesific Object type from string value contained in this object’s properties

I want to generate Filter pipe in Angular that works for filtering the Car, Brand and Color array object by it’s pipe parameter corresponding their “carName” , “brandName” etc. property.

For example this pipe is going to filter the Colors by their name corresponding the value of filter pipe parameter.

But I want to do that this pipe filters on all Object types with it’s(Object’s) Name property that i created wherewithal.

To do that, All Objects need to have same “Name” property name. But My Objects has different name properties like;

carName:string (Car)

name:string (Brand)

name:string (Color)

I’ve created a pipe that works successfully on object that only has “name” properties but I can’t make it successful that this pipes works on Car object as well ;

@Pipe({
 name: 'filter',
})



export class FilterPipe implements PipeTransform {

  transform(entityList: any[], filter: string): any[] {

    filteredList: typeof entityList;

if (filter) {
  filter = filter.toLocaleLowerCase();
  return entityList.filter((c) =>
    c.name.toLocaleLowerCase().includes(filter)
  );
}

return entityList;
 

 }
}

How can I create a generic Pipe to filter objects with its(Object’s) name property by just the properties of object includes “name” expression ?

How to record zoom meeting and preview it on react website

I am trying to use the zoom Api to import it into my website so I can host live sessions which can also be recorded and stored for later viewing. Is there a way to do that. I am integrating zoom using the Zoom SDK which will allow me to create meetings directly from my website but I want to know if I can record and save the meeting directly on my website and save it so I can later watch it whenever I need to ?

Remove field depending on display type in Embed entity ckeditor Drupal

I have a specific display for document type entity. We made caption required for other media type but I want it to not be required when I select display as “document link” how can I do ?

For now I have something like this:

function MY_MODULE_form_entity_embed_dialog_alter(&$form, DrupalCoreFormFormStateInterface $form_state, $form_id){
  if (isset($form['attributes']['data-entity-embed-display'] && .....)){
    $form['attributes']['data-caption']['#required'] = FALSE;
  } else {
    $form['attributes']['data-caption']['#required'] = TRUE;
      }

The … is for adding the fact that document link option must be selected bu I don’t know how to do it.

Anyone have an idea, please ?