Pushing items to array in an interpolated order

I have an array of objects and I am trying to interpolate data in a new array.

This is the array, that might have two or more objects:

const param = [{
    sortType: "ascending",
    sortField: "id",
  },
  {
    sortType: "descending",
    sortField: "title",
  },
];


let sortFields = [];
let sortTypes = [];
let sortString = [];

//iterates the sort params
for (let p of param) {
  sortFields.push(p.sortField);
  sortTypes.push(p.sortType);
}

for (let st of sortTypes) {
  sortString.push(st === "ascending" ? "+" : "-");
  for (let sf of sortFields) {
    sortString.push(sf);
  }
}
console.log({
  sortString
})

What I intend to do is to have an array with the following output:
["+id","-title"]

At the moment I am stuck with two interpolated for loops that do something very different.
I have tried labeling the loops and using the continue keyword in the inner loops, but is still gives me a very different output.

Any suggestion on how can I achieve this?
Maybe lopping the two array separately and then creating a new loop that interpolates and joins the strings in the array?

Any help is appreciated!

Large delay between Canvas `pointerdown` and `pointermove` events with stylus

I’m trying to create a very basic sketch pad using an HTML Canvas and pointer events. I’ve implemented a very basic codepen that demonstrates the issue at hand. The key functionality draws a red dot upon pointerdown events and a blue dot on pointermove events:

c.addEventListener('pointerdown', event => {
  event.preventDefault();
  updatePosition(event);
  ctx.fillStyle = 'red';
  ctx.fillRect(position.x - 2, position.y - 2, 4, 4);
  drawing = true;
});

c.addEventListener('pointermove', event => {
  if (!drawing) return;
  event.preventDefault();
  updatePosition(event);
  ctx.fillStyle = 'blue';
  ctx.fillRect(position.x - 2, position.y - 2, 4, 4);
});

Both when using a stylus (a Surface Pen) or just touch, I observe a large gap between the initial pointerdown event and the eventual (good) “stream” of pointermove events, as demonstrated here:

enter image description here

I’ve observed to varying degrees with multiple input methods on different hardware. Is there a way I can eliminate or mitigate this?

how do I fix the total amount of pixel used from a grid in css?

I’m sorry if this is a repeated question and I’d like some help cause I’m a noob.
I created a grid. But every time I enter a different number, it uses a different total amount of pixel. I want the height and the width of the body that contains grid to stay exactly the same size no matter what the number of grid is.

https://moonsol124.github.io/ETCH-A-SKETCH-TOP-PROJECT-/

here is what I made.

java:

function createGrid(maxGrid = 16) {
    for (let i = 0; i < maxGrid; i++) {
        const divRow = document.createElement('div');
        divRow.classList.add('div-row');
        for (let j = 0; j < maxGrid; j++) {
            const div = document.createElement('div');
            div.classList.add('div-style');
            divRow.appendChild(div);
        }
        body.appendChild(divRow);
    }
addColorOnGrid();

}

css:

.div-row {
    display: flex;
    flex-direction: column;
}

.div-style {
    width: 25px;
    height: 25px;
    flex: 1 1 auto;
    background-color: RGB(0, 0, 0);
    border: solid 3px RGB(255, 255, 255);
}

html:

   <body>
        <div class="btn-group">
            <button class="btn" id="grid-button">Enter number of grid</button>
            <button class="btn" id="reset-button">Reset</button>
        </div>
        <div class="grid-body">

        </div>
    </body>

please tell me if my approach is wrong. thanks for your help.

Need help in getting the Continuation Token while making a “List paths” Rest API call in Azure Data Lake Storage Gen2

When I make API call for listing the paths in ADLS Gen2 using maxResults and Continuation as uri parameters.

Initially I’m getting the correct continuation token returned as response headers but when i try to make subsequent calls for listing the remaining files, sometimes ADLS returns with a continuation token that ends with “==”(lets call it type one) and sometimes if returns with the normal token(type two).Now,when I try to make API call using the first type, ADLS gives me an error and it works fine in the case of the other token.

I searched this before and what I found in one of the answers was that we have to ignore the response in which the token returned ends with “==” and we have to make calls again and again ignoring the continuation token(not using this token in the uri and using the same previous request uri) returned until we get the second(working) type of token.

This is a complex task when it comes to larger amount of files,is there a better solution for this?
Is there a better solution for getting the right type of continuation token for making subsequent calls?

The Sample request for making the call is

GET https://storageAccountName.dfs.core.windows.net/sampleDirectory?recursive={recursive}&resource=filesystem&maxresults={maxresults}&continuation={continuation}

The two types of sample continuation tokens returned are

  1. LCJhbGciOiJSUzI1NiIsIng1dCI6ImpTMVhvMU9XRGpfNTJ2Ynd==(Not working one)
  2. LCJhbGciOiJSUzI1NiIsIng1dCI6ImpTMVhvMU9XRGpfNTJ2Ynd (working one)

The Official Documentation for ADLS Gen2 for listing paths is
https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/list

The link to the stackoverflow answer which I was referring to can’t get ADLS Gen2 REST continuation token to work

Record video from webcam in Angular

Is there a way to record a video from the webcam in Angular, using ngx-webcam ?
If not, do you know any technology that is compatible with Angular/TypeScript, that could allow me to show a webcam preview on my web app and then start recording the video output once a record button is pressed ?
Thank you!

break line in locale text used in components vue

I am using locales for texts in my vue app and these texts need to have break lines in the in certain places. I have tried n and <br> tags but they don’t work. How can I go about breaking locale i18n text lines and use them in my components?

For example, the following text should go to a new line after “home is” and “heart is or”

locales/en.json:

"description": {
   "home": "home is n where the heart is or <br> another random cliche sentence here"
}

components/hello.vue:

<div> {{$t("description.home")}}</div>

file upload backup api to backup file on aws s3 in nodejs

I want a make an API that will take a file or folder path from the user and upload it to AWS s3 I made progress but

when the user gives a file path it’s searching the file path in the server, not in the user’s pc

I know I made a mistake but I don’t know how to connect API from the users pc and get access to system files

here is code for the post route

router.post("/create/:id", auth, async (req, res) => {
  try {
    let form = new multiparty.Form();
    form.parse(req, async (err, fields, files) => {
      console.log(fields);
      console.log(files);
      //check if user has access to project
      const user_id = req.userId;
      const project_id = req.params.id;
      const user_access = await check_user_access_project(user_id, project_id);
      const user = await User.findById(user_id);
      const project = await Project.findById(project_id);
      if (user_access === 1) {
        //create version
        const version = new Version({
          project_id: project_id,
          user_id: user_id,
          versionName: fields.versionName[0],
          version_description: fields.versionDescription[0],
          version_file: [],
        });
        const version_data = await version.save();
        console.log(version_data);

        let version_id = version_data._id;

        //sync folders to s3
        const version_folder_path = fields.files_path[0];
        let key = `${user.firstName}_${user_id}/${project.projectName}/${fields.versionName[0]}`;
        const version_folder_list = await sync_folders(
          version_folder_path,
          key
        );

        console.log("version folder list", version_folder_list);

        //update version with version folders
        await Version.findByIdAndUpdate(
          version_id,
          {
            $set: {
              version_file: version_folder_list,
            },
          },
          { new: true }
        );
        //wait for version update
        await version.save();

        //send response
        res.json({
          success: true,
          version: version_data,
        });
      } else {
        res.status(401).json({
          success: false,
          message: "User does not have access to project",
        });
      }
    });
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});

here is the folder sync code

const sync_folders = async (folder_path, key) => {
  function getFiles(dir, files_) {
    files_ = files_ || [];
    var files = fs.readdirSync(dir);
    for (var i in files) {
      var name = dir + "/" + files[i];
      if (fs.statSync(name).isDirectory()) {
        getFiles(name, files_);
      } else {
        files_.push(name);
      }
    }
    return files_;
  }

  const files = getFiles(folder_path);
  console.log(files);
  const fileData = [];
  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    console.log(file);

    const fileName = file.split("/").pop();
    const fileType = file.split(".").pop();
    const fileSize = fs.statSync(file).size;
    const filePath = file;

    const fileBuffer = fs.readFileSync(filePath);

    //folder is last part of folder path (e.g. /folder1/folder2/folder3)
    const folder = folder_path.split("/").pop();

    console.log("folder: " + folder);
    //split filepath
    const filePath_ = filePath.split(folder).pop();

    let filekey = key + "/" + folder + filePath_;

    console.log("filekey: " + filekey);

    const params = {
      Bucket: bucket,
      Key: filekey,
      Body: fileBuffer,
      ContentType: fileType,
      ContentLength: fileSize,
    };
    const data = await s3.upload(params).promise();
    console.log(data);
    fileData.push(data);
  }

  console.log("file data", fileData);
  console.log("files uploaded");
  return fileData;
};

if some buddy can help me pls I need your help

Download image from URL in HTML/JavaScript

I want to download image from website and that image is located to a different website. I specified image’s url but it’s not downloading. It’s just opens the picture itself in it’s original page but only image is displayed. I did some research and it turned that my code should work perfectly. I can’t identify the problem. Here’s my code:

document.querySelector("#memeDownload").addEventListener("click", function () {
    var a = $("<a>").attr("href", "https://iynmemes.netlify.app/images_memes/meme0.jpg").attr("download", "Meme(IYN").appendTo("body");
    a[0].click();
    a.remove();
});

How to know if an input is clicked and unclicked in Javascript

I’m trying to figure out how to know when an input is clicked and when it is unclicked. Let me explain:

When ever you want to type something on an input field, you click on the input box and when you don’t want to type, you click somewhere else and the input field is disabled.

<input type='text'>

Here as you can see, when you click on it, the field is enabled, and when you click somewhere else other than the field, it disables.

I just want to know when the field is disabled/unclicked.

Trouble with hiding/showing a div containing a plotly.js plot

I have a div that contains a header. In this header I will write characteristics of the object I am clicking on in the page. The initial on-click trigger works fine and processes the post request to a local flask server and displays the plot in the div using plotly.js. The problem comes in when the div is collapsed by clicking on the header and then trying to click on an object in the page. The desired outcome for this second on-click event is for the data inside the ‘plot data’ div to update, and causing the header to expand if it is minimized. However, the observed behavior is that if you click on an object, triggering an on-click event while the div is hidden, it results in the following error in the dev console.

Cannot read properties of null (reading 'innerText')
referencing this line:
console.log(document.getElementById("header symbol").innerText)

The relevant code here is below:

Jquery for expanding and closing the div

$(".header").click(function () {
const $header = $(this);
//getting the next element
var $content = $header.next();
//open up the content needed - toggle the slide- if visible, slide up, if not slidedown.
$content.slideToggle(200, function () {
  //execute this after slideToggle is done
  //change text of header based on visibility of content div
  console.log(document.getElementById("header symbol").innerText);
  $header.text(function () {
    //change text based on condition
    return $content.is(":visible")
      ? `▼ ${clickedBranchName} -- ${clickedBranchFromBus} ⟶ ${clickedBranchToBus}`
      : `▲ ${clickedBranchName} -- ${clickedBranchFromBus} ⟶ ${clickedBranchToBus}`;
    });
  });
});

Plotting the data into the ‘plot data’ div:

function plotFlow(info) {
  console.log(info.object.properties.name);
  const dates = topoData.data.datetime;
  const flows = topoData.data.flow;
  var trace1 = { x: dates, y: flows, mode: "lines", type: "scatter" };
  var data = [trace1];
  var layout = {
    plot_bgcolor: "rgba(128,128,128,1)",
    paper_bgcolor: "rgba(128,128,128,1)",
    height: 350,
    xaxis: {
      tickmode: "auto",
      nticks: 36,
    },
  };
  var plot_div = document.getElementById("plot_data");
  // plot_div.replaceChildren();
  console.log(document.getElementById("header symbol").innerText);
  document.getElementById(
    "header symbol"
    ).innerText = `▼ ${clickedBranchName} -- ${clickedBranchFromBus} ⟶ ${clickedBranchToBus}`;
  console.log(document.getElementById("header symbol").innerText);
  Plotly.newPlot(plot_div, data, layout);
  
}

And finally,. index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    <meta charset="utf-8" />
    <title> WHO!?!?</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style>
      body {
        margin: 0;
        font-family: sans-serif;
        width: 100vw;
        height: 100vh;
        overflow: hidden;
      }
      .container {
      position: absolute;
      margin: 0;
      bottom: 0px;
      width: 100%;
      border:1px solid #d3d3d3;
      z-index: 999;
      }
      .container div {
          width:100%;
      }
      .container .header {
          background-color:#d3d3d3;
          padding: 2px;
          cursor: pointer;
          font-weight: bold;
      }
      .container .content {
          display: none;
          padding : 5px;
      }
    </style>

  </head>
  <body>
    <div id="app"></div>
    <div id="plot_div" class="container">
      <div class="header">
        <span id="header symbol">▲</span>
      </div>
      <div id="plot_data"></div>
    </div>
    </div>
  </body>
  <script type="text/javascript" src="app.js"></script>
  <script type="text/javascript">
    App.renderToDOM(document.getElementById("app"));
  </script>
</html>

How to stay at the same page and the same location (after scrolling) after submitting post request with Express?

I am counting the views on a post on my website and for that I have created a ‘more’ button (but styled as a link) after some text so that the user clicks on that and the view count increases. The button submits a post request and I increment the view count in the database. The problem is that I have 2 separate pages (which might increase in the future) that display the posts and they both have this ‘more’ button which submits the post request to the same route. I want the user to click the button and stay on that same page on that same location but in express we are required to res.redirect or render 1 page which isn’t possible in this case. I tried to redirect to (‘/’), but this goes only to one of the 2 pages that I talked about and not the current page. Moreover, when redirecting, the extra paras shown on clicking that button also vanishes, basically going to the original orientation. I am happy to change the entire logic of this function as long as you cannot find any solution with this one…

    router.post("/clicked-more", ensureAuth, async (req, res) => {
  try {
    
    let secId=req.body.clicked_more
  
    const sec = await XXX.find({_id:secId}).lean();
    sec[0].views++
  
  await XXX.findOneAndUpdate({ _id: secId},{views: sec[0].views});
  res.redirect('/')
    
  } catch (err) {
    console.log(err);
    //   res.send(err)
    res.render("../views/error/500");
  }
});

This is one of my 2 pages..(2nd one has the same function as this one)

     <form action="/clicked-more" method="post">
    <div class="wrapper">


            <p class="startPara">{{stripTags (truncate body 200)}}<span class="dots" >...</span></p>
            <span class="content">
            <p>{{stripTags (truncate body 400)}}</p>
            </span>
                    <button type="submit"  name="clicked_more" value={{_id}} class="link-button buttonReadMore" onclick="readMoreFunction(this)"  >more</button>
            </div>

    </form>

This is my ‘read more’ function

function readMoreFunction(el) {
var parent = el.closest(".wrapper")
var dots = parent.querySelector(".dots");
var contentText = parent.querySelector(".content");
var btnText = parent.querySelector(".buttonReadMore");
var startPara=parent.querySelector(".startPara");



 btnText.style.display = "none";
  startPara.style.display= "none";
  dots.style.display = "none";
  contentText.style.display = "inline";

}

Getting the index value of a specific div in a group

I’m creating a group of <div>‘s that have separate content:

<div class="container">
  <div class="container__item"></div>
  <div class="container__item"></div>
  <div class="container__item myClass"></div>
</div>

I need to be able to get the specific index value of a <div> when it has a certain class applied to (e.g., myClass)

const item = document.querySelector(".container__item");
const items = document.querySelectorAll(".container__item");
const myClass = document.querySelector(".myClass");

I’m looping through the collection of items but not able to get the index value, e.g., 0, 1, 2. FYI, I’ll be converting those values to 1, 2, 3.

for (var i = 0; i < item.length; i++) {
  var hasClass = item[i]classList.contains(showItem);
  if (hasClass) {
    console.log(i);
  }
}