How to achieve multi-line output with formatting in JavaScript

I am experimenting with the following codepen.io trinket and trying to achieve multiline output with formatting for the JavaScript text that is returned in response to user-input.

For instance, if the user types “/engage” the following text is returned:

“Follow the white rabbit. I want this to be the second line”

The code is below. I would like the above text to:

a) be output on two separate lines with my being able to control the breaks between lines (like br in HTML)
b) allow some basic formatting – specifically to add bold formatting to the word “rabbit”.
c) allow for changing the font size of “follow” to a larger font/or different style etc.

I have tried various things but they all come up with errors.

RELEVANT CODE

submitForm.addEventListener("submit", function(e) {
    e.preventDefault();
    if (input.value === "/clear") {
        clearCommand();
    } else if (input.value === "/list" || input.value === "help") {
        listAllCommands();
    } else if (input.value === "/connect") {
        goProgress();
    } else if (input.value === "/engage") {
        matrixEffect();
        clearCommand();
        textArea.value = "Follow the white rabbit. I want this to be the second line"
    } else {
        textArea.value +=
            "nERROR: Unknown command! Type 'help' for list of commands.";
        input.value = "";
    }
    textArea.scrollTop = textArea.scrollHeight;
});

CODEPEN ENTIRE SNIPPET

https://codepen.io/damyco/pen/oyewjR

Why does only the first filter for “show more” work?

On the webshop for my internship I’m trying to resolve a filter problem.
On each page, only the first filter works when you press “show more”. On all other filters nothing happens once you press “show more”.

This is the code responsible:

function _toConsumableArray(e) {
    if (Array.isArray(e)) {
        for (var o = 0, s = Array(e.length); o < e.length; o++) s[o] = e[o];
        return s;
    }
    return Array.from(e);
}
function showLessMore(e) {
    var o = e.target;
    if (qty.hasClass("js-hook__amshopby-more")) {
        e.preventDefault();
        var s = o.parentNode.parentNode,
            a = s.querySelectorAll(".js-hook__amshopby-item");
        if (a.length) {
            for (var r = [].concat(_toConsumableArray(a)), t = 0; t < r.length; t++) {
                var l = r[t];
                "none" == l.style.display && (l.classList.add("filter--visible"), (l.style.display = "block"));
            }
            (o.style.display = "none !important"), (s.querySelector(".js-hook__amshopby-less").style.display = "block !important");
        }
    }
    if (qty.hasClass(o, "js-hook__amshopby-less")) {
        e.preventDefault();
        var n = o.parentNode.parentNode,
            y = n.parentNode.parentNode.querySelectorAll(".js-hook__amshopby-item.filter--visible");
        if (y.length) {
            for (var i = [].concat(_toConsumableArray(y)), p = 0; p < i.length; p++) {
                var c = i[p];
                c.classList.remove("filter--visible"), (c.style.display = "none");
            }
            (o.style.display = "none !important"), (n.querySelector(".js-hook__amshopby-more").style.display = "block !important");
        }
    }
}

Any help would be greatly appreciated!

Registering pre keys with server in signal protocol

I was recently going through documentation of signal protocol. https://github.com/signalapp/libsignal-protocol-javascript. In the documentation after they generate the pre key bundles and other things they say “// Register preKeys and signedPreKey with the server”. But there is no mention of how to do that. Apart from this can anyone please help me with how to know a users recipient id to decrypt his message. Also are the keys permanent or they disappear on closure of browser.

Can not populate nested array in mongoose

I try to populate products data in order. I use mongoose with nestjs and graphql. The problem is that I don’t want to create new collection. So all I want to do is to create an order which has attribute orderedProductArray. This consists of product and amount. Product has a reference to Product object.

Schemas

@Schema()
export class OrderedProduct {
  @Prop(() => ID)
  _id: string

  @Prop(() => Int)
  amount: string

  @Prop({ type: Types.ObjectId, ref: Cloth.name })
  product: Cloth
}

export const OrderedProductSchema = SchemaFactory.createForClass(OrderedProduct)

@Schema()
export class Order {
  @Prop()
  _id: string

  @Prop({ type: Date, default: Date.now })
  confirmedDate: Date

  @Prop({ type: Types.ObjectId, ref: OrderStatus.name })
  orderStatus: OrderStatus

  @Prop()
  userName: string

  @Prop()
  email: string

  @Prop()
  phoneNumber: string

  @Prop({ type: [OrderedProductSchema] })
  orderedProductArray: [OrderedProduct]
}

export const OrderSchema = SchemaFactory.createForClass(Order)

And the service:

  async getOrderById(getByIdArgs: GetOrderByIdArgs): Promise<Order> {
try {
  const searchedOrderId = await this.orderModel
    .findById(getByIdArgs)
    .populate({
      path: 'orderedProductArray',
      populate: {
        path: 'product._id',
        model: 'Cloth'
      }
    })
    .exec()

  if (searchedOrderId) {
    return searchedOrderId
  }
  throw new NotFoundException('The given id does not exist')
} catch (error) {
  throw new NotFoundException(error)
}

I will be appreciated for your help. I tried almost everything that I’ve found in StackOverflow. Thanks in advance!!!

How to change bar width of a specific series while in different axis target – Angular google charts

I am developing a layered column chart using ComboChart on Angular google charts. Although I’ve separated two series of bar charts in two different axis, being able to find a bar in front of the other, like needed, I can’t change the width of one of the series only. I want a result like the amCharts Layered Column Chart:

Layered Column Chart example

Right now, the chart looks like:

Current chart – Angular google charts

Also, if there is a way to share the same y axis while keeping one bar in front of the other, instead of staking then, it would be great.

The code I’ve been using for options of the angular google chart:

    this.options =
    {  
      colors: ['#1E90FF', '#f39800'], 
      hAxis: {
        title: 'haxisTitle',
        type: 'category'
      },
      vAxis:{
        title: 'Value',
        minValue: 0,
        format: this.numberFormat
      },
      seriesType: 'bars',
      bar: {1: {groupWidth: "30"}},
      series: 
        {
          0: {
            targetAxisIndex: 0
          },
          1: {
            targetAxisIndex: 1,
          }
        },        
      vAxes: {
        0: {
          title: 'Altered Value',
          label:'Altered Value',
          viewWindow: {  // <-- set view window
            min: 0,
            max: this.maxValue + 0.1*this.maxValue, // Sets the maximun value of altered or real value to the window size (both axis)
          },
          format: this.numberFormat,
          type: 'bars'     
        },
        1: {
          title: 'Real Value',
          label:'Real Value',
          viewWindow: {  // <-- set view window
            min: 0,
            max: this.maxValue + 0.1*this.maxValue,
          },
          format: this.numberFormat,
          type: 'bars'
        }    
      },
      aggregationTarget: 'auto',
      stackSeries: true,
      isStacked : true,
      explorer: {
        actions: ['dragToZoom', 'rightClickToReset'],
        keepInBounds: true,
        maxZoomIn: 4.0
      }
    };
  }

The chart shows the data correctly, the only problem is the layout.

Some reference that might help:

Google Developers – Visualization: Combo Chart
amCharts Layered Column chart
Overlapped bars – Stack overflow quote – Here the result was a stacked bar chart (something I don’t want)

Stop clock when page is not on screen [duplicate]

in the title I used a clock as an example but my question is for all functions.
How do I stop some function when it is not on-screen. For the clock I used the useEffect Hook with setInterval(), since I am using ReactJs. So how do I stop the interval when the page is not visible on the screen so it does not slow down the users computer. I read that it is not possible to stop setInterval so I know that I need to clearInterval and and setInterval again.

Firebase onSnapshot listener: How to handle if doc does not exist yet?

I am building an app where users can tag subjects they are interested in.

I am looking for best practices on how to handle the following issue:

I have a page that mounts an onSnapshot listener during page creation (example page path: site.com/tags/apple). This page allows the user to actually add the tag to their feed. First, I need to “watch” whether they add the tag to their feed or check to see if it already exists so that way I can toggle the state of a button icon to let them know that they already have added this tag to their feed.

I thought I’d use the onSnapshot listener to handle this logic like so (simplified for this question):

mounted() {

    loadwatchedTag() {
      const docRef = doc(db, `users/${this.userProfile.uid}/tags`, 'apple') //<-- example tag

      this.unsubscribe = onSnapshot(docRef, {
        next: (doc) => console.log('tag', doc.data()),
        error: (error) =>
          console.log('watchedTag listener error', error)
      })
    }

}

The problem is that on page load, I get the following error in console (because the tag does not yet exist):

tag, undefined

So, how to handle this issue on page load if the tag does not yet exist? Should I be doing something like this within the onSnapshot code?

if (docSnap.exists()) {
  console.log("tag exists!", docSnap.data());
} else {
  // doc.data() will be undefined in this case
  console.log("tag does not exist");
}

Java script XMLHttpRequest

My code is not working when I uploaded it to the hosting site but it is 100% working in localhost. What’s wrong with my code?

var questionno="1";
load_questions(questionno);

function load_questions(questionno)
{
    document.getElementById("current_que").innerHTML=questionno;
    var xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            
            if(xmlhttp.responseText=="over")
            {
                window.location="result.php";
            }
            else
            {
                document.getElementById("load_questions").innerHTML=xmlhttp.responseText;
                load_total_que(); 
            }
        }
    };
    xmlhttp.open("GET","load_questions.php?questionno="+ questionno,true);
    xmlhttp.send(null);
}

Why is my setter function provided by the context api not working in the handle function

I have this implementation for a search filter using tags.

https://codesandbox.io/s/search-filter-tags-zgfcs?file=/src/Tags.tsx:622-626

I for the life of me cannot figure out why my setTags() method is not working in the handleChange function, but is working fine in the handleAllChange function.

Tags.tsx

import * as React from "react";
import { TagContext } from "./TagContext";

let AllTags = [
  "Html",
  "CSS",
  "JavaScript",
  "ReactJS",
  "GitHub",
  "TypeScript",
  "Celebal"
];

const Tags = () => {
  const { tags, setTags } = React.useContext(TagContext);
  const [allChecked, setAllChecked] = React.useState(false);
  // const [tags, setTags] = React.useState([] as string[]);

  const handleAllChange = () => {
    if (!allChecked) {
      setTags(AllTags);
    } else {
      setTags([]);
    }
    setAllChecked(!allChecked);
  };

  const handleChange = (name: string) => {
    let temp = tags;
    if (temp.includes(name)) {
      temp.splice(temp.indexOf(name), 1);
    } else {
      temp.push(name);
    }
    console.log("temp - ", temp);
    setTags(temp);
  };

  React.useEffect(() => {
    console.log("Tags - ", tags);
  }, [tags]);

  return (
    <>
      <h1>Filter Tags</h1>
      <div className="tags-container">
        <div className="w-fit p-2 m-2">
          <button
            className="p-1 border-2 border-black rounded font-semibold"
            onClick={handleAllChange}
          >
            Apply All
          </button>
        </div>
        {AllTags.map((tag, i) => {
          return (
            <div className="w-fit p-2 m-2" key={i}>
              <input
                className="mt-2"
                type="checkbox"
                value={tag}
                name={tag}
                onChange={(e) => handleChange(tag)}
                checked={tags.includes(tag)}
              />
              <label htmlFor={tag}>#{tag}</label>
            </div>
          );
        })}
      </div>
    </>
  );
};

export default Tags;

The tags, and setTags are coming from context API.

TagContext.tsx

import * as React from "react";

interface ITagContext {
  tags: any;
  setTags: any;
  handleChange: (name: string) => void;
}

export const TagContext = React.createContext({} as ITagContext);

interface ITagProvider {
  children: React.ReactNode;
}

export const TagProvider = ({ children }: ITagProvider) => {
  const [tags, setTags] = React.useState([] as string[]);

  const handleChange = (name: string) => {
    debugger;
    let tag = name;
    let temp = tags;
    if (temp.includes(tag)) {
      temp.splice(temp.indexOf(tag), 1);
    } else {
      temp.push(tag.toString());
    }
    setTags(temp);
  };

  React.useEffect(() => {
    debugger;
    console.log("Tags in Context - ", tags);
  }, [tags]);
  return (
    <TagContext.Provider value={{ tags, setTags, handleChange }}>
      {children}
    </TagContext.Provider>
  );
};

combine new line json into one array

I have a JSON from web server that looks like this:

{"timestamp":1642069251.6908009,"station_id":"ORBB","channel":5,"freq":131.725,"level":-28.1,"error":0,"mode":"2","label":"Q0","block_id":"8","ack":false,"tail":"A6-ANR","flight":"G90369","msgno":"S10A"}
{"timestamp":1642069257.00876,"station_id":"ORBB","channel":5,"freq":131.725,"level":-41.3,"error":0,"mode":"2","label":"Q0","block_id":"7","ack":false,"tail":"PH-HXO","flight":"HV6905","msgno":"S28A"}
{"timestamp":1642069259.057013,"station_id":"ORBB","channel":5,"freq":131.725,"level":-24.9,"error":0,"mode":"D","label":"Q0","block_id":"9","ack":false,"tail":"A6-ANR","flight":"G90369","msgno":"S11A"}

l have followed this answer but l have nothing to show in console.

l cant edit the data JSON above to deliver a valid JSON because it’s coming from a data server using ajax .

         $.ajax('acarsdec.json', {
        type: 'GET',
        dataType: "json",
        timeout: 10000,
        cache: false,
        
}).done(function (data, textStatus, jqXHR) {
    console.log(data)
var lines = data.split(/n/);
var wrapped = "[" + lines.join(",") + "]";
var obj = JSON.parse(wrapped);
console.log(obj)
    })

How to use setInterval with react useEffect hook correctly?

I tried to create a simple timer app with ReactJS and found the below code on the internet.

Does the function that we passed to the useEffect will execute with the dependency change or does it recreates with every dependency change and then execute?

Also I console log the return function of the useEffect and it runs with every render. Does it run only when the component unmount? or with every render?

import { useEffect,  useState } from "react";

const App = () => {
  const [isActive, setIsActive] = React.useState(false);
  const [isPaused, setIsPaused] = React.useState(true);
  const [time, setTime] = React.useState(0);

  React.useEffect(() => {
    let interval = null;

    if (isActive && isPaused === false) {
      interval = setInterval(() => {
        setTime((time) => time + 10);
      }, 10);
    } else {
      clearInterval(interval);
    }
    return () => {
      console.log("cleanup");
      clearInterval(interval);
    };
  }, [isActive, isPaused]);

  const handleStart = () => {
    setIsActive(true);
    setIsPaused(false);
  };

  const handlePauseResume = () => {
    setIsPaused(!isPaused);
  };

  const handleReset = () => {
    setIsActive(false);
    setTime(0);
  };

  return (
    <div className="stop-watch">
      {time}
      <button onClick={handleStart}>start</button>
      <button onClick={handlePauseResume}>pause</button>
      <button onClick={handleReset}>clear</button>
    </div>
  );
};

export default App;

Given a number in base 2, convert it into base 6 in javascript

Given a number in base 2, convert it into base 6

For e.g.

1100 in base 2 represented as [false, false, true, true] in test #1,
12 in base 10, and
20 in base 6 represented as [0, 2] in test #1.
[execution time limit] 4 seconds (js)

[input] array.boolean base2

Max length = 100

if ith position of the array is true that means the ith position of the number is 1.

[output] array.integer

ith position of the array represents the ith position of the number is in base 6

I can’t solve this question.

Can we simulate mouse movement with TypeScript

I am actually working on a project where I need to “draw” rectangles on a PDF. This happens the same way you would select multiple files on your desktop. You hold down your click, “draw” a rectangle and once your rectangle has the size you want it to, you just release the click.

To do this, I use React-PDF-highlighter (find an example here: https://agentcooper.github.io/react-pdf-highlighter/ —> Note that to draw said rectangle in this example, you need to be holding down option key on mac or Altkey on windows at the same time.)

For some reasons I would really like to let the user drag a square from some kind of left menu on the PDF. For the “drag and drop”, I use React-dnd.

so from now on, just imagine a screen divided in 2. On the left side, you have the possibility to drag and drop a rectangle and on the right side, you have a PDF file that can contain multiple pages of course.

Problem is, when I drag and drop my square on my pdf highlighter component, I have no way to know what page I dropped my rectangle on. I do have the screen coordinates of the drop though.

Is there a way to SIMULATE a mouse mouvement? Not actually do it, I know that’s impossible. But can I make the browser believe that the mouse clicked on a certain point (the coordinates of the released drop) and from there on make it believe the click has been released a bit further in diagonal to create a simple square that would be nicely added to the list?

If someone helps me out here, he or she would get my eternal gratitude!

Have a wonderful day, and all the best for 2022!!

How to add item to each level of a nested array

I have infinite levels array in each object and I want to add “id” based on levels. Suppose if level 1 then id should be 1 and level two then id will be 2 etc.

{
"name": "Anything2",
"code": "SS_1",
"levels": [
    {
        "levelName": "New level",
        "levels": [
            {
                "levelName": "New Level2",
                "levels": [
                    {
                        "levelName": "New Level2",
                        {
                            "levelName": "New Level2",
                            "levels": [
                                {
                                    "levelName": "New level"
                                }
                            ]
                        }
                    },
                    {
                        "levelName": "New Level2",
                    },
                    {
                        "levelName": "New Level2",
                    }
                ]
            },
            {
                "levelName": "New Level2"
            },
            {
                "levelName": "New Level2",
                "levels": [
                    {
                        "levelName": "New level"
                    }
                ]
            }
        ]
    }
]

}

I want to convert the above array into below new array. I have tried using for loop but its not working I am not getting expected data. I want to add “id” based on levels. Suppose if level 1 then id should be 1 and level two then id will be 2 etc.

{
"name": "Anything2",
"code": "SS_1",
"levels": [
    {
        "id": 1,
        "levelName": "New level",
        "levels": [
            {
                "id": 2,
                "levelName": "New Level2",
                "levels": [
                    {
                        "id": 3,
                        "levelName": "New Level2",
                        {
                            "levelName": "New Level2",
                            "levels": [
                                {
                                    "id": 4,
                                    "levelName": "New level"
                                }
                            ]
                        }
                    },
                    {
                        "id": 3,
                        "levelName": "New Level2",
                    },
                    {
                        "id": 3,
                        "levelName": "New Level2",
                    }
                ]
            },
            {
                "id": 2,
                "levelName": "New Level2"
            },
            {
                "id": 2,
                "levelName": "New Level2",
                "levels": [
                    {
                        "id": 3,
                        "levelName": "New level"
                    }
                ]
            }
        ]
    }
]

}