How to generate random number from -1 to 1 without 0

i want to generate random number from -1 to 1 without getting any zero 0 like function should generate -1 or 1 no zero 0 i don’t need 0, i managed to do this but unfortunately im getting undefined on behalf of the zero can anyone explain me why this happed and how to solve this.

code —

function random(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    var save = Math.floor(Math.random() * (max - min + 1) + min)
    if (save == 1 || save !== 0 && save !== undefined) {
        return save
    }
}

random(-1, 1)

Google Docs DOM rendering mode

I’m developing a Chrome extension (it isn’t publised yet) wich will interact with Google Docs, it should find some words in text and highlight it without changing document styles. As now Google switched from DOM rendering to canvas I’ve faced some problems with searching text position in document. Google API has some endpoints to get the structure of the document, but in doesn’t contain information about text position, moreover this operation will be very long with huge documents if i call this API after every change in document to recalculate position. I’ve found this question (Switching Google Docs from Canvas to DOM mode – programmatically?). I’ve filled in the form to get access to DOM rendering and I’ve got this access, after a week I’ve noticed “mode=html” param in URL and DOM tags in browser developer tools. BUT, i suppose I’ve got access to DOM rendering only on my Google account and not on my extension, also I’ve found that after Goolge whitelisted my extension they should send me some documentation according on comments in this question (Annotated canvas rendering in Google Docs).
So, my question is, how get access to DOM rendering to my extension, not the user, and how should I interact with DOM in code without “mode=html” param?

Why my autocomplete input is not working?

Hello newbie here writing my first question, I have an input field and when I type it will filter a json file and it will show the matching places starting with the same letter  ( I’m trying to build a autocomplete search bar for a weather app). the problem that I’m having is that when I click on one of the element it doesn’t set the input text to what I  have been clicking..any help would be great! thanks!

Codesandbox here : https://codesandbox.io/s/exciting-fire-vhvl5w

import data from "./city2.list.json";

const SearchBar = () => {
  const [input, setInput] = useState("");
  const [matchesArray, setMatchesArray] = useState([]);
  const [city, setCity] = useState("");

  const getCitySuggestions = (input) => {
    let matches = [];
    if (input !== "") {
      for (let i = 0; i < data.length && matches.length < 10; i++) {
        if (data[i].name.toLowerCase().startsWith(input.toLowerCase())) {
          matches.push({
            id: data[i].id,
            long: data[i].coord.lon,
            lat: data[i].coord.lat,
            name: data[i].name,
            country: data[i].country,
          });
          setMatchesArray(matches);
        }
      }
    }
    return matches;
  };
  useEffect(() => {
    getCitySuggestions(input);
  }, [input]);

  const handleClick = (e) => {
    e.preventDefault();
    let a = setCity(e.target.value);
    console.log("city is..", a);
  };

  return (
    <div>
      <form onSubmit={(e) => handleClick(e)}>
        <input
          type="text"
          name="search"
          id="search"
          placeholder="search..."
          onChange={(e) => setInput(e.target.value)}
        />
        <button type="submit">search..</button>
        {matchesArray.map((item, index) => (
          <div onClick={(e) => handleClick(e)} value={item.name} key={index}>
            {item.name}
          </div>
        ))}
      </form>
    </div>
  );
};

export default SearchBar;```

Change Header Content-Type from application/json to multipart/form-data

I have a project with next js. in this project I am using fetch for handling requests.

I wrote a wrapper for my requests as below

 fetch(url, {
        method: method.toUpperCase(),
        headers: 'Content-Type': 'application/json',
      ...headers,
    };,
        cache: cache,
        body: body
          ? JSON.stringify(body):null
      });

it works good for all requests with header Content-Type:’application/JSON

But I have an issue now I have a form and in this form, I have a file input so in this case my headers must be multipart/form-data.

I am using formData API but since I used application/JSON as the default header My data will be posted with the header of application/JSON. so I changed explicitly my headers for this specific request to multipart/form-data and it created another issue because in this way the browser doesn’t set boundary for this header.
this is my request

    const onSubmitHandler = (values) => {
       
            const formData = new FormData();
            formData.delete('captcha');
            formData.append('jobTitle', careerData.title);
            for (let value in values) {
                formData.append(value, values[value]);
            }
            setCaptchaIsRequired(false);
            const globalService = new GlobalService();

            globalService
                .postCareer(
                    formData,
                    { "Content-Type":"multipart/form-data" }
                )
                .then((res) => {
                    //some codes
                }).catch(e => console.log(e, 'ERRROR'));
        }
    };

I want to know how can do this and if this hasn’t any solutions is it Ok to set boundary my self or not

Thank’s all of you in advanced

How to Create a Dynamic URL Instead of Id Which is in Mongoose Schema

How can I make the dynamic URL which is present in the Database as the link (tag) how can I use that link for fetching only one post from that database like an e-commerce website (it makes the new page for each post)

http://localhost:3000/{here is the link}

here is my code =>

Schema of Mongoose (link)

const mongoose = require('mongoose');

const Posts = mongoose.model('Posts', {
    link: {
        type: String,
        required: true,
        unique:true
    },
    
    title: {
        type: String,
        required: true
    }
    
    });

module.exports = { Posts }
"addPosts": {
    "link": "newoneawesomed",
    "title": "How can we achieve sucessfully",}

Below I making for id that renders a separate post from MongoDB

like

http://localhost:3000/625d056d4e412fb823d9cc4e

But how can achieve instead of id?

is

http://localhost:3000/newoneawesomed

which is present in the database…

Pls…
help me to Solve these problems

How to fix unsafe value used in a resource URL context in Angular unit test using jest

I got below error while writing the unit test in Angular using Jest. I have gone through all the similar suggestions here in stackoverflow, but none were helpful.

Error: unsafe value used in a resource URL context (see https://g.co/ng/security#xss) Jest

Below is the code from test file for your review.

import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';

import { MaterialModule } from '../../Material/material.module';

import { DashboardViewComponent } from './dashboard-view.component';

describe('DashboardViewComponent', () => {
  let component: DashboardViewComponent;
  let fixture: ComponentFixture<DashboardViewComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [
        RouterTestingModule, 
        HttpClientTestingModule,
        MaterialModule,
      ],
      declarations: [ DashboardViewComponent ],
      providers: [{
        provide: DomSanitizer,
        useValue: {
          bypassSecurityTrustResourceUrl: (): SafeResourceUrl => ''
        }
      }],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(DashboardViewComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  test('should create', () => {
    // expect(component).toMatchSnapshot();
    expect(component).toBeTruthy();
  });
});

Thanks in advance.

How to obtain URL from a rel=canonical tag using Javascript

I’m using Disqus comments system and I’m trying to use the feature of adding comment count links.

The code that I can use is below:

<span class="disqus-comment-count" data-disqus-url="http://example.com/article1.html">Comments</span>

And this is where I have some issue. The thing is I have several hundreds of pages so editing the data-disqus-url value for each and every html pages will take a very long time and not feasible. Is there maybe some Javascript code that will dynamically input the data-disqus-url value with my canonical url?

I can’t use php code since I’m using html files but I have SSI enabled since I need to use includes for easy template management. Also, all my html pages already have a unique meta tag for rel=”canonical”. I just need perhaps some Javascript codes that will fill-up the data-disqus-url value with the value indicated in my canonical url tag. Is that possible?

I am making a project to add users in MongoDB but I am getting ERR_HTTP_HEADERS_SENT

    import User from '../model/user.js';

// Get all users
export const getUsers = async (request, response) => {
    // Step -1 // Test API
    // response.send('Code for Interview');
    try{
        // finding something inside a model is time taking, so we need to add await
        const users = await User.find();
       return response.status(200).json(users);
    }catch( error ){
        return response.status(404).json({ message: error.message })
    }
}

// Save data of the user in database
export const addUser = async (request, response) => {
    // retreive the info of user from frontend
    const user = request.body;
    response.send("hello");
    
    

    const newUser = new User(user);
    try{
        await newUser.save();
        response.status(201).json(newUser);
    } catch (error){
        return response.status(404).json({ message: error.message});     
    }
}

// Get a user by id
export const getUserById = async (request, response) => {
    try{
        const user = await User.findById(request.params.id);
         response.status(200).json(user);
    }catch( error ){
         response.status(409).json({ message: error.message })
    }
}

// Save data of edited user in the database
export const editUser = async (request, response) => {
    let user = await User.findById(request.params.id);
    user = request.body;

    const editUser = new User(user);
    try{
        await User.updateOne({_id: request.params.id}, editUser);
        response.status(201).json(editUser);
    } catch (error){
        return response.status(411).json({ message: error.message});     
    }
}

// deleting data of user from the database
export const deleteUser = async (request, response) => {
    try{
        await User.deleteOne({_id: request.params.id});
       response.status(201).json("User deleted Successfully");
    } catch (error){
        response.status(406).json({ message: error.message});     
    }
}

This is the error I am receiving
node:internal/errors:464
ErrorCaptureStackTrace(err);
^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:371:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at ServerResponse.header (C:UserseggfrDesktopdemocrud-servicenode_modulesexpresslibresponse.js:771:10)
at ServerResponse.send (C:UserseggfrDesktopdemocrud-servicenode_modulesexpresslibresponse.js:170:12)
at ServerResponse.json (C:UserseggfrDesktopdemocrud-servicenode_modulesexpresslibresponse.js:267:15)
at addUser (file:///C:/Users/eggfr/Desktop/demo/crud-service/controller/user-controller.js:29:37)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code:

Form a Long Line from Short Lines algorithm

arr= [ [2,3], [7,8], [2,5], [8,9], [3,6], [6,8], [7,9] ];

So, we can see that [ [2,3],[3,6],[6,8] ] will form a line from Point 2 to 3, 3 to 6, 6 to 8.

function long_connect()

long_connect([2,4]) will output a false because there is no connection from Point 2 to Point 4.

long_connect([2,6]) or long_connect([3,8]) will output a true because there is a connection from Point 2 to 3 and 3 to 6, so its valid.

long_connect([7,9]) will output a true because there is a connection from Point 7 to 8 and 8 to 9, so its valid.

long_connect([7,10]) will output a false because there is no connection from Point 7 to 10.

May I know the methods to solve this or show a demo 🙂 ? Thank you and have a nice day.

create function to add some elements to an object using spread

I have an object that called state like below code . I want to add many states and cities to it

const state = {

    missouri: ["springfield", "rolla"],
    nevada: ["carlin", "vegas"],
}

How can I Create a function to add new state to object using Spread? how can I Create a function to Add list of new city to one of state using Spread?

Highchart, Can we export multi-page PDF file or do we have to use another PDF?

Can we export multi-page PDF file or do we have to use another PDF? Any advice as I can’t figure out how to do a multi-page PDF?
LINK DEMO
I would like to have a separate page between the graph and the data table so that all data can be displayed fully in both the graph and the data table. like this enter image description here
Or if not, then set the page to display both graph and data table when pressing export.

How to change google base map in OpenLayers

Currently I have Bing map as base map with openlayers but I want google map instead of Bing map. I have google map API key.
What I want is, I will have a dropdown menu and when I select a map from the dropdown then corresponding base map will load.
In dropdown option will like: Roadmap, Terrain, Satellite, Hybrid etc.

My current Bing map code:

import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import GeoJSON from 'ol/format/GeoJSON';
import TileWMS from 'ol/source/TileWMS';

import BingMaps from 'ol/source/BingMaps';

let myview = new View({
  center: [10064015.097881343, 2725467.6940862294],
  zoom: 13
})
 
let mylayer = new TileLayer({
  source: new OSM()
})
 
let layer = []
 
 
// Being map
let styles = [
  'RoadOnDemand',
  'Aerial',
  'AerialWithLabelsOnDemand',
  'CanvasDark',
  'OrdnanceSurvey',
];
 
 
// Being map
let i, ii;
for (i = 0, ii = styles.length; i < ii; ++i) {
  layer.push(
    new TileLayer({
      visible: false,
      preload: Infinity,
      source: new BingMaps({
        key: '**************************************',
        imagerySet: styles[i],
      }),
    })
  );
}
 
 
let map = new Map({
  target: 'map',
  layers: layer,
  view: myview
});


// Being map
let select = document.getElementById('layer-select');
function onChange() {
  let style = select.value;
  for (let i = 0, ii = layer.length; i < ii; ++i) {
    layer[i].setVisible(styles[i] === style);
  }
}
select.addEventListener('change', onChange);
onChange();


<select id="layer-select">
                                <option value="Aerial">Aerial</option>
                                <option value="AerialWithLabelsOnDemand">Aerial with labels</option>
                                <option value="RoadOnDemand" selected>Road</option>
                                <option value="CanvasDark">Road dark</option>
                                <option value="OrdnanceSurvey">Ordnance Survey</option>
                            </select>

Cannot fetch data from Firestore collection

enter image description here

I want to get data from Firebase’s et_events collection and have the events displayed on the frontend.

I wrote the following code in the events.js file and tried to get the event information from Firebase, but I couldn’t get it.

export const actions = {
  fetchAllEvents: async ({ dispatch, commit }, eventIds) => {
    // TODO: fetch events from firestore
    console.log("start")
    const eventsSnap = await getDocs(query(eventsRef, where(documentId(), 'et_events', eventIds)))
    const events = await Promise.all(
      eventsSnap.docs.map(async snap => {
        const organization = await dispatch('fetchOrganization', snap.data().organizationId)
        return {
          id: snap.id,
          organization,
          isEvent: true,
          ...snap.data(),
        }
      }),
    )
    events.sort((a, b) => {
      if(a.startDT > b.startDT) return 1;
      if(a.startDT < b.startDT) return -1;
      return 0;
    });
    events.splice(1, 0, {
      isEvent: false,
      imgUrl: 'https://storage.googleapis.com/eventomy/statics/thumbnails/tutorial.png',
      title: 'Eventomyを始めよう',
    })


    // remove code above and put your code instead
    commit(SET_EVENTS, events)
  },
}

Also, I don’t quite understand the meaning of “dispatch”, “commit”, and “eventsSnap” in this code. Can anyone tell me?

The full code is published below.

const SET_EVENTS = 'SET_EVENTS'

export const state = () => ({
  events: [],
})

export const mutations = {
  SET_EVENTS: (state, events) => {
    state.events = events
  },
}

export const getters = {
  allEvents(state) {
    return state.events
  },
}


// import { doc, getDoc } from "firebase/firestore";
export const actions = {
  fetchAllEvents: async ({ dispatch, commit }, eventIds) => {
    // TODO: fetch events from firestore
    console.log("start")
    const eventsSnap = await getDocs(query(eventsRef, where(documentId(), 'et_events', eventIds)))
    const events = await Promise.all(
      eventsSnap.docs.map(async snap => {
        const organization = await dispatch('fetchOrganization', snap.data().organizationId)
        return {
          id: snap.id,
          organization,
          isEvent: true,
          ...snap.data(),
        }
      }),
    )
    events.sort((a, b) => {
      if(a.startDT > b.startDT) return 1;
      if(a.startDT < b.startDT) return -1;
      return 0;
    });
    events.splice(1, 0, {
      isEvent: false,
      imgUrl: 'https://storage.googleapis.com/eventomy/statics/thumbnails/tutorial.png',
      title: 'Eventomyを始めよう',
    })


    // remove code above and put your code instead
    commit(SET_EVENTS, events)
  },
}