How to keep the date exactly as specified in the input string (without any implicit UTC conversion) [duplicate]

I am facing an issue while writing a function with [dayjs][1] library.

The problem I am trying to solve, is to extract the date part (only) from a given date-time string and ensure that the value of date is not changed.

For example: "Thu Jan 30 2225 23:45:46 GMT-0800 (Pacific Standard Time)" should result in "2225-01-30" in YYYY-MM-DD format, but with the solution I attempted (code snippet below), I am getting output as "2225-01-31".

In summary, I do not need any time-conversion to be applied, while extracting the date part. I have also tried to include dayjs/plugin/timezone but the date change happens before itself, when dayjs(date) is invoked.

Code snippet:

const date = "Thu Jan 30 2225 23:45:46 GMT-0800 (Pacific Standard Time)";
const formattedDate = dayjs(date).format("YYYY-MM-DD");
console.log(formattedDate);
<script src="https://unpkg.com/[email protected]/dayjs.min.js"></script>

Any insights on this will be helpful. I am open to writing a native JavaScript function as well or consider other libraries.

I have also gone through similar question asked before, and have tried the suggestions and still not getting the desired outcome.

Triggering a script from an existing script in Big Commerce

Before I implement a script in Script Manager, I’m just wondering if there’s a way to trigger a script after an existing one (under the hood) has been fired.

So I would like to trigger my custom script after a product option has been selected on the product page. I’m currently working on the script but it occurred to me that this would be the best practice.

Thanks all

Stroke canvas elements as if they’re one element

I have a canvas with multiple circles and want to stroke them as if they are 1.

as you can see, it is all drawn on their own

  context.beginPath();
  context.fillStyle = "#F9F8F3";
  context.arc(0, height/6*4, width/6, 0, Math.PI*2);
  context.arc(width/6*1.9, height/6*4.45, width/6*1.25, 0, Math.PI*2);
  context.arc(width/6*3.75, height, width/6, 0, Math.PI*2);
  context.arc(width/6*5.5, height/6*4, width/5, 0, Math.PI*2);
  context.stroke();

image with all circles being stroked

its supposed to look kind of like this
example for desired output

How can I get the input from an input tag and use it back in the code? [duplicate]

I am trying to make a dice where you can choose the minimum and maximum values. Currently, I have tried different ideas, but they don’t work. It messes up the other code, and I don’t know why.

<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="styles.css" />
  <script src="styles.js"></script>
  <title>Dice Roller</title>
</head>

<body>
  <h1>Dice Roller</h1>
  <p>Can't decide on what to eat? Or what to do? Our dice roller is perfect for this.</p>
  <div>
    <label>Minimum:</label><input type="number" min="1" class="input min" id="min"><p> </p><label>Maximum:</label><input type="number" min="2" class="input max" id="max">
  </div><br>
  <div>
  <section>
    <button class="roll-button" type="button" onclick="rollDice(document.getElementById(`min`).value, document.getElementById(`max`).value)">Roll</button>
    <h1 id="output"></h1>
  </section>
  <section>
  <script type="text/javascript">
       function rollDice(a = 1, b = 6) {
          dice = Math.floor(Math.random() * (b - a + 1)) + a
          console.log(dice);
          document.getElementById("output").innerHTML = dice;
        }
          </script>
  </section>
  </div>
</body>

</html>

How can I get the input from the min and max values and use it in the JavaScript function in a way that it works? (starter coder, sorry if it is an easy question)

How can I get the actual bounding borders of a SVG after rotation?

I need to get the position of the actual bounding borders of a SVG image after its parent being applied CSS rotation. The grey color in the image below indicates its parent element(In my case it is transparent – I added the grey color in the image below just for indicating the parent element’s border)

getBoundingClientRect() seems to only show the bounding borders of the original rectangle – the red borders shown below. But what I want is the bounding borders without SVG’s transparent background after rotation – like the green borders.

Screenshot image

I have tried getBoundingClientRect() or getBBox() but they don’t work with rotation being applied.

$('#box').html(svgElement)
$('#box').css({ transform: 'rotate(60deg)' })
svgElement.getBoundingClientRect()

$(function() {

  let svgString = '<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 425.58 635.88"><defs><style>.cls-1{fill:#000000;fill-rule:evenodd;}</style></defs><title>1</title><path id="path" class="cls-1" d="M918.94,831.44c-103,110.83-133.9,110.83-236.86,0-68.44-73.68-80.26-150.84-84.92-241.2-4.22-81.95-26.86-194.68,18.05-248.36,70.51-84.25,300.09-84.25,370.59,0,44.92,53.68,22.28,166.41,18.06,248.36C999.2,680.6,987.39,757.77,918.94,831.44Z" transform="translate(-587.72 -278.69)"/></svg>'

  let svgElement = new DOMParser().parseFromString(svgString, 'text/xml').documentElement

  $('#box').html(svgElement)

  $('#box').css({
    transform: 'rotate(60deg)'
  })

  let rect = svgElement.getBoundingClientRect()

  $('#bounding-border').css({
    left: rect.left + 'px',
    top: rect.top + 'px',
    width: rect.width + 'px',
    height: rect.height + 'px',
  })
})
#box {
  position: absolute;
  left: 100px;
  top: 100px;
  width: 100px;
  height: 150px;
}

svg {
  path:hover {
    fill: red;
  }
}

#bounding-border {
  position: absolute;
  border: 2px solid red;
  z-index: -1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="box"></div>
<div id="bounding-border"></div>

codepen

How to upload to existing folder to minio through strapi

I have a bucket called mybucket in minio and MINO_FOLDER=static. I connected this to my strapi CMS. When using CMS interface I am able to upload images to folder and get image url like domain/static/web/logo.png. However when trying to upload to this web folder using custom strapi Rest API my images are uploaded to static (static/logo.png not static/web/logo.png). I tried all possible ways of passing folder and path but none worked. Is it possible to achieve desired result ?
Here is my service function:

I tried passing path and folder. And passing mybucker/static/web

async add(ctx) {
    const { files } = ctx.request;
    // const { folder } = ctx.request.body;

    if (!files || !files.files) {
      return ctx.badRequest("No files uploaded");
    }

    const uploadedFile = await strapi.plugins["upload"].services.upload.upload({
      data: {},
      files: files.files,
      path: "static/web",
    });

    return uploadedFile;
  },

Attribute’s ordering is reversed everytime parallel plot is rerendered

I am using Hiplot chart in my react component similar to example here

I use order param of Parallel Plot to show attributes in certain ordering. When first time component is rendered ordering(Order of attr in Parallel plot from left to right) is correct. But when more data is added to the experiment data or just component is rendered, the ordering of attributes in Parallel Plot is reversed. And ordering keeps on reversing every time new data is added to experiment state for example on button click.

Check this code


      const [items, setItems] = React.useState<hip.HiPlotExperiment | null>();
    
      const createExperiment = (data: any) => { 
        const experiment: hip.HiPlotExperiment = hip.Experiment.from_iterable(data);
        experiment.colorby = "P1";
        experiment.enabled_displays = [hip.DefaultPlugins.PARALLEL_PLOT]
        experiment.display_data = {
          "PARALLEL_PLOT": {
              hide: ["uid"], // this attr is hidden successfully
              order: ["P1", "output_result"] // Attrs list i need to order
          }
       };
       setItems(experiment);
       console.log(items?.display_data?.PARALLEL_PLOT?.order); // though in the console always correct order is looged
    }

Html snippet


       {items && (
           <div className="m-3 pb-12">
             <hip.HiPlot
              experiment={items}
              plugins={plugins}
              dark={false}
              onChange={{ 'brush_extents': handleSelectionChange }}
              />
           </div>
          )}

I use version 0.1.34-rc.200

Can I refresh site engagement for another domain?

I want to make a PWA that daily checks whether new posts are available, and give notification if there is. The problem is the blog is .blogspot.com which means I can’t host javascript or manifest files on the domain. I need to host the app on another domain, and ask the user to install the app from there. According to this article, periodic sync won’t be fired if user engagement is zero on the website, which will be the case since the reader isn’t spending any time on the website hosting the PWA, and is spending time reading on my blog instead. So is there any way to refresh the site engagement on the website hosting the PWA while the user is reading on my blog?

Why use for of over forEach when iterating over defined arrays? [duplicate]

I’m looking through the MDN guidelines and it shows that to iterate over what seems like a defined array of data (ie. const names = ['adam', 'billy', 'cody']) they state that we should use for of over forEach.

ie

// Good
for (const name of names) {
  console.log(name);
}

// Less good
names.forEach(name => console.log(name));

// Definitely don't do this
for (let i = 0; i < names.length; i++) {
  console.log(names[i]);
}

I completely understand the last point about the for(; ;) usage, but why not use forEach? It’s been my usual go-to method for this type of thing for as long as I can remember.

The example given on the documentation does show it being used in a longer way such as

names.forEach(name => {
  console.log('name')
});

rather than doing a quick return as I did previously name => console.log(name) which would be more concise.

I’m just wondering what the benefit of using for of here is, other than maybe being “explicit” about what the names belong to?

How to send custom data in google analytics default GA4 events

I am using Google analytics in my angular project. Initially I simply added the google analytics reference in my index.html and was collecting the default event data like page_view. Recently I started sending some custom data like the type of user that logged in and the event name I am using is user_type. When I check the network tab, now I can see two types of google analytics calls. One is the calls where the event type is user_type and I can see the custom data in the payload. The second type of calls are the default GA4 events call.
My question is how can I send my custom data also in the default calls. Is that possible? Or this is the expected behaviour?

Cors Error FastAPI And NextJs when sending a POST request

I am trying to send a post request from my nextjs app local server to my FastAPI local server, but i still get the cors error, the thing is when i sent the same request to my prod url of my azure web app api (same api but hosted on azure) from my nextjs app i dont get any cors errors

Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/charger/get_status_by_ou/0000-0016' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
C:Userskenkiklantportaal2testing2azuretestingazurepagesrealtime.tsx:181 Error fetching data: AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
nextJsHandleConsoleError @ client.js:85
fetchData @realtime.tsx:181
await in fetchData
Realtime.useEffect @ 

    
   POST http://127.0.0.1:8000/api/charger/get_status_by_ou/0000-0016 net::ERR_FAILED

This is how i send the request in my frontend

const fetchData = async () => {
    try {
      if (!ouData) {
        console.error("OU data is empty!");
        return;
      }
      console.log(`url: ${process.env.NEXT_PUBLIC_LOCAL_URL} `);
      const statusResponse = await axios.post(
        `${process.env.NEXT_PUBLIC_LOCAL_URL}/api/charger/get_status_by_ou/${ouData}`,
        {},
        {
          headers: {
            Authorization: `Bearer ${apiToken}`,
            Accept: 'application/json',
          }
        }
      );
      console.log("Status Data:", statusResponse.data);

And my fast api main.py

from fastapi import FastAPI, Query, HTTPException
from database import get_db_connection
import traceback
import logging
from fastapi.middleware.cors import CORSMiddleware

# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

origins = [
    "http://localhost:3000"
]

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,  # Allows requests from these origins
    allow_credentials=True,
    allow_methods=["*"],    # Allow all HTTP methods (GET, POST, etc.)
    allow_headers=["*"],    # Allow all headers
)

Scrolling animation with framer motion

I’m learning to use framer motion in React.

I want to create a scroll type animation where I enter the webpage, scroll down and when I get to some section looks like the webpage sticks in that section and if I keep scrolling it displays some cards with an image. When I finish scrolling that section the flow continues with the sections below.

It is something similar with the landing page of Jet rains. https://www.jetbrains.com/

I’ve tried to read the documentation but I think it’s not fully explained how some hooks work and all the options available and honestly I don’t know how could I start.

Why does one recursive promise chain cause a memory leak, while the other does not?

I have two recursive promise chains that seem to be doing the same thing, but one of them is causing a memory leak while the other is not. I’ve simplified the code to the following examples:

Leaking code:

function leakingLoop() {
  return delay(1)
  .then(() => {
    console.log(`Tick ${Date.now()}`)
    return leakingLoop()
  })
}

Non-leaking code:

function nonLeakingLoop() {
  delay(1)
    .then(() => {
      console.log(`Tick ${Date.now()}`)
      nonLeakingLoop()
    })
}

The only difference between the two is that the leakingLoop function returns the result of the delay promise, while the nonLeakingLoop function does not.

Can someone explain why the leakingLoop function is causing a memory leak, while the nonLeakingLoop function is not? Is there something about the way promises are handled that I’m missing?

Note: I’ve assumed that the delay function is a promise-based function that resolves after a certain amount of time. If that’s not the case, please let me know and I’ll update the question accordingly.

Charts are overlapping legend after refreshing the data

I’m building pie charts in Apex Charts with HTML/CSS/JS. The first time I fetch data from the API and populate the charts, everything works well. However if I click the “refresh data” button and update the charts, the pie chart appears pushed over to the side and overlapping the legend. See screenshots below to illustrate:

1st time fetching data:
Initial Load

// Example data
[{
    "count": 11,
    "percent": 0.9166666666666666,
    "profanity": "none"
  },
  {
    "count": 0,
    "percent": 0,
    "profanity": "mild"
  },
  {
    "count": 0,
    "percent": 0,
    "profanity": "medium"
  },
  {
    "count": 0,
    "percent": 0,
    "profanity": "strong"
  },
  {
    "count": 1,
    "percent": 0.08333333333333333,
    "profanity": "extreme"
  }
]


// Function to create empty chart. This only gets called on initial query, if the data is just filtered or refreshed, code will go right to updating the alreayd existing chart.
const createEmptyProfanityChart = () => {
  var options = {
    series: [],
    chart: {
      width: 380,
      height: 265,
      type: "pie",
      id: "profanity-chart",
    },
    labels: [],
    redrawOnParentResize: false,
    redrawOnWindowResize: false,
  };

  var chart = new ApexCharts(
    document.querySelector("#profanity-chart"),
    options
  );
  chart.render();
};


// Function to update chart with new data
const updateProfanityChart = (data) => {
  let extremeCount;
  let strongCount;
  let mediumCount;
  let mildCount;
  let noneCount;

  // loop through profanity data and push counts into array
  data.profanity_list.forEach((item) => {
    switch (item.profanity) {
      case "none":
        noneCount = item.count;
        break;
      case "mild":
        mildCount = item.count;
        break;
      case "medium":
        mediumCount = item.count;
        break;
      case "strong":
        strongCount = item.count;
        break;
      case "extreme":
        extremeCount = item.count;
        break;
    }
  });

  let countsArr = [
    extremeCount,
    strongCount,
    mediumCount,
    mildCount,
    noneCount,
  ];

  let labelsArr = ["Extreme", "Strong", "Medium", "Mild", "None"];

  ApexCharts.exec("profanity-chart", "updateSeries", countsArr, true);

  ApexCharts.exec(
    "profanity-chart",
    "updateOptions", {
      labels: labelsArr,
    },
    false,
    true
  );
};


// Create empty chart if first time populating data
if (initialFetch === false) {
  createEmptyChart()
}

// Function to update the chart with  data
populateChart(data)
.stats-card-container {
  width: 400px;
  border-collapse: separate;
  border-spacing: 0;
  border: 1px solid #ddd;
  position: relative;
  border-radius: 0.8rem;
  overflow: clip;
}

.stats-cards-row {
  display: flex;
  justify-content: space-evenly;
  margin-bottom: 3rem;
  margin-top: 1rem;
  column-gap: 1rem;
}

.stats-card-header {
  height: 40px;
  background-color: var(--main-orange-th-color);
  padding: 8px;
  display: flex;
  align-items: center;
  font-weight: 600;
}

.stats-chart-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
}

#no-data__stats {
  text-align: center;
  margin-top: 2rem;
<!-- Row 1 -->
<div id="stats-cards-row-1" class="stats-cards-row">
  <!-- Bent -->
  <div id="bent-card-container" class="stats-card-container">
    <div id="bent-card-header" class="stats-card-header">
      Philosophical Bent
    </div>
    <div id="bent-chart-container" class="stats-chart-container">
      <div id="bent-chart"></div>
    </div>
  </div>
  <!-- /Bent -->
  <!-- Profanity -->
  <div id="profanity-card-container" class="stats-card-container">
    <div id="profanity-card-header" class="stats-card-header">
      Profanity
    </div>
    <div id="profanity-chart-container" class="stats-chart-container">
      <div id="profanity-chart"></div>
    </div>
  </div>
  <!-- /Profanity -->
</div>
<!-- /Row 1-->

All following chart updates with new data
Refresh Data

I can’t reproduce the issue on a codepen since I’m using a private API. See below for example data, as well as my code for populating the chart.

Want to execute all test cases n times?

I am a beginner in Cypress. I use Cypress with javascript to perform automation testing.

Question: How can I iterate all it blocks n times?

Description: In a JSON file, one key has an array including names of different profiles. I have one spec file, in which I have multiple it() blocks. Now I want to run my spec file for all profiles available in a key.

For that, I tried below solution:

TestData.JSON

{
"test": {
    "customerAccountName": "RD test R97 01 new",
    "userRole": "Customer Admin",
    "profiles": ["Generic SIP Service", "Genesys PureCloud"],
    "profile": "",
    "serviceCarrier": "",
    "isCarriage": "",
    "type": "",
    "blockSize": ""
}
"stage": {
    "customerAccountName": "RD test R97 01 new",
    "userRole": "Customer Admin",
    "profiles": ["Generic SIP Service", "Genesys PureCloud"],
    "profile": "",
    "serviceCarrier": "",
    "isCarriage": "",
    "type": "",
    "blockSize": ""
}

TestSpec.js

describe("Create, edit, pause, resume and delete Generic SIP Service", function () {

let siteTestData, credentials, SIPServiceTestData, profiles;
before(function () {

cy.fixture('credentials').then(function (testdata) {
  credentials = testdata[window.environment]

  //Login to a portal if require
  if (isLoginRequire(credentials.sausername, credentials.sapassword)) {
    cy.loginAs(credentials.url, credentials.sausername, credentials.sapassword)
  }
})

//Get test data from 'genericSIPServiceTestData' file
cy.fixture('SIPServiceTestData').then((testData) => {
  SIPServiceTestData = testData[window.environment]
  profiles = SIPServiceTestData.profiles
})

//Get test data from 'siteTestData' file
cy.fixture('siteTestData').then(function (testdata) {
  siteTestData = testdata[window.environment]
  //If siteName is empty, add site name
  if (siteTestData.siteName == '') {
    siteTestData.siteName = 'Automation site ' + getUTCTime()
  }
  //If siteEmail is empty, add site email
  if (siteTestData.siteEmail == '') {
    siteTestData.siteEmail = 'automationtestsite' + getUTCTime() + '@gmail.com'
  }
  //If updateSiteName is empty, add site name to update
  if (siteTestData.updateSiteName == '') {
    siteTestData.updateSiteName = 'Update ' + siteTestData.siteName
  }
})
})

it(“Load test profiles”, function () {

Array.from(profiles).forEach($profile => {


  describe('test json loop', function () {

    beforeEach(() => {
      SIPServiceTestData.profile = $profile
    })

    after(() => {
      console.log('inside after')
      // Only log out if require
      if (isLoginRequire(credentials.sausername, credentials.sapassword)) {
        cy.logout();
      }
    });

    it("Navigate to Customer account", function () {
      //Navigate to customer account
      clickCustomer(SIPServiceTestData.customerAccountName)
      //Verify services header on services page
      verifyServicesHeader()
    })

    it("Verify either account is existing or new", function () {
      isAccountNew(siteTestData)
    })

    it("Click on 'Add new service' button, select SIP service and Navigate to 'Select numbers' page", function () {
      //Click on services tab
      clickServicesTab();
      //Add service button should be enable on services page
      getAddServiceButton().should('be.visible').and('be.enabled').and('have.text', 'Add New Service').click();
      //Select profile and carrier, and navigate to select numbers page
      selectProfileAndCarrier(SIPServiceTestData);
      //Verify sub header
      getAccountName().should('be.visible').and('have.text', SIPServiceTestData.customerAccountName)
      //Verify header section and search field on select numbers page
      verifyHeaderOnSelectNumberPage(SIPServiceTestData)
      //Verify tooltip text on hover of inventory number on select number page
      verifyTooltipOnSelectNumberPage()
      //Select number
      selectNumberForServices()
      //Set details of selected number into json
      setSelectedNumberDetails(SIPServiceTestData)
    })
  })
})
});
})

When I run above code it works fine. But Cypress chrome window doesn’t show all it blocks in it’s UI.
enter image description here

Is there any solution for this issue? If not…
Is there any other solution to iterate it block multiple times and it works normally?