Distinct Digit Year -Codewars Challenge-

I was solving a codewars challenge and got stuck in an endless loop. The task is to find from a given input like year 1987 the next greater integer that has only distinct digits. In that case it would be 2013 as 1988, 1998,2000 etc. do not have 4 distinct digits. I wanted to solve this task with an Object and see where the length of the Object.keys(obj) is equal to 4.

Here is my try

function distinctDigitYear(year) {
  
  let obj = {}
  let count = 1
  let yearCounter = year + count
  
  while (Object.keys(obj).length !==4) {
    obj = {}
    yearCounter.toString().split('').forEach(el=> {
      if(!Object.keys(obj).includes(el)){
        obj[el] = 1
      } else {
        obj[el] +=1
      }
    }
    )
   
      count++
  }
  return yearCounter + 1
}

distinctDigitYear(2000)

Thanks for reading!

How can I make two objects of the same class bounce when colliding?

I made a bouncing ball code, and so far as the bouncing itself the code works perfectly. I then created a second ball, and it also does what it’s supposed to do. However, when I try to use an if condition to make the two balls bounce off one another as well as the edges, it doesn’t work. Either they don’t move or they just don’t collide, and go through each other. This code was made in processing. Can anyone help me make ball1 and ball2 collide?

Moving ball1;
Moving ball2;
void setup(){
  size(600,600);
  ball1 = new Moving();
  ball2 = new Moving();
}

void draw(){
  background(255);
  ball1.move();
  ball1.display();
  ball1.bounce();
  ball2.move();
  ball2.display();
  ball2.bounce();
  ball1.clash();
  ball2.clash();
}

class Moving {
  float speed = 7;
  float x = random(0, width);
  float y= random(0, height);
  float xdirection = 1;
  float ydirection = 1;
  float ball_size = 50;
  float radius = ball_size/2;
  Moving() {
  }
  void move() {
    x = x + (xdirection * speed);
    y = y + (ydirection* speed);
  }
  void display() {
    noStroke();
    fill(50, 0, 50);
    circle(x, y, ball_size);
  }
  void bounce() {
    if ((x >= width - radius) || (x <= radius)) {
      xdirection = xdirection * -1;
    }
    if ((y >= height - radius)|| (y<=radius)) {
      ydirection = ydirection * -1;
    }
  }
  void clash() {
    if ((ball1.y+radius == ball2.y+radius) && (ball1.x+radius == ball2.x+radius)) {
      ball1.ydirection = ball1.ydirection * -1;
      ball2.ydirection = ball2.ydirection * -1;
      ball1.xdirection = ball1.xdirection * -1;
      ball2.xdirection = ball2.xdirection * -1;
      x = x + (xdirection * speed);
      y = y + (ydirection* speed);
      if (ball1.x+radius == ball2.x+radius) {
        xdirection = xdirection * -1;
      }
    }
  }
}

REGEXP for matching or finding only Streetname and housenumber without additionals

This is a regexp specific something that I need to do in the backend to strip the address. I need the streetname + number to be cleaned to a Streetname + housenumber without any additional letters or any other characters with other numbers. For example:

  • Teststreet 123 (correct)
  • Teststreet 123F needs to be stripped to Teststreet 123
  • Teststreet 12 and 3 needs to be stripped to Teststreet 12
  • Teststreet 123,5 needs to be stripped to Teststreet 123
  • Street name long 122 (correct)
  • Street name long 122 – A needs to be stripped to Street name long 122

And so on… does anyone have an idea how I can do this? And anyone an idea what the correct REGEXP for this can be?

Shopify CLI – Shopify node serve is not working for 1 year old project

I am trying to refactor my old shopify project but, when I run command, “shopify node serve” It gives me the following error.

“This command can only be run within node projects.”

But, It is a node project. It is a next.js shopify application.

Below is my package.json file.

{
  "name": "Announcement_Bar",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "dev": "forever start --minUptime 1000 server.js",
    "build": "next build",
    "start": "NODE_ENV=production forever start --minUptime 1000 server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^1.2.34",
    "@fortawesome/free-brands-svg-icons": "^5.15.2",
    "@fortawesome/free-regular-svg-icons": "^5.15.2",
    "@fortawesome/free-solid-svg-icons": "^5.15.2",
    "@fortawesome/react-fontawesome": "^0.1.14",
    "@koa/cors": "^3.1.0",
    "@material-ui/core": "^4.11.3",
    "@material-ui/icons": "^4.11.2",
    "@maxmind/geoip2-node": "^1.6.0",
    "@shopify/app-bridge": "^1.28.0",
    "@shopify/app-bridge-react": "^1.28.0",
    "@shopify/app-bridge-utils": "^1.28.0",
    "@shopify/koa-shopify-auth": "^3.2.0",
    "@shopify/koa-shopify-graphql-proxy": "^3.3.1",
    "@shopify/koa-shopify-webhooks": "^2.6.0",
    "@shopify/polaris": "^4.27.0",
    "@zeit/next-css": "^1.0.1",
    "@zeit/next-sass": "^1.0.1",
    "ag-grid-community": "^22.1.1",
    "ag-grid-react": "^22.1.1",
    "agile_crm": "^1.2.5",
    "animate.css": "^3.7.2",
    "animate.css-react": "1.0.0",
    "apollo-boost": "^0.4.9",
    "bitly": "^7.1.2",
    "currency-formatter": "^1.5.6",
    "dotenv": "^8.2.0",
    "draft-js": "^0.11.7",
    "draftjs-to-html": "^0.9.1",
    "emoji-picker-react": "^3.4.2",
    "es6-promise": "^4.2.8",
    "fbjs": "^3.0.0",
    "graphql": "^14.7.0",
    "he": "^1.2.0",
    "html-to-draftjs": "^1.5.0",
    "install": "^0.13.0",
    "isomorphic-fetch": "^2.2.1",
    "javascript-obfuscator": "^0.24.6",
    "js-cookie": "^2.2.1",
    "jsonwebtoken": "^8.5.1",
    "koa": "^2.13.1",
    "koa-body": "^4.2.0",
    "koa-bodyparser": "^4.3.0",
    "koa-cache-control": "^2.0.0",
    "koa-conditional-get": "^2.0.0",
    "koa-etag": "^3.0.0",
    "koa-mongo": "^1.9.3",
    "koa-router": "^7.4.0",
    "koa-session": "^5.13.1",
    "koa-shopify-auth-cookieless": "^1.0.31",
    "koa-shopify-graphql-proxy-cookieless": "^1.0.11",
    "koa-static": "^5.0.0",
    "koa-static-cache": "^5.1.4",
    "koa2-formidable": "^1.0.2",
    "lodash": "^4.17.20",
    "mailchimp-api-v3": "^1.14.0",
    "mmmagic": "^0.5.3",
    "moment": "^2.29.1",
    "mongodb": "^3.6.4",
    "ms": "^2.1.3",
    "next": "^9.5.5",
    "node-cron": "^2.0.3",
    "node-sass": "^4.14.1",
    "nodemailer": "^6.4.17",
    "notistack": "^0.9.17",
    "npm": "^7.5.2",
    "parse-link-header": "^1.0.1",
    "react": "^16.14.0",
    "react-apollo": "^3.1.5",
    "react-color": "^2.19.3",
    "react-copy-to-clipboard": "^5.0.3",
    "react-datepicker": "^2.16.0",
    "react-dom": "^16.14.0",
    "react-draft-wysiwyg": "^1.14.5",
    "react-hotjar": "^2.2.1",
    "react-loading-overlay": "^1.0.1",
    "react-measure": "^2.5.2",
    "react-player": "^1.15.3",
    "react-select": "^3.2.0",
    "react-select-country-list": "^2.2.3",
    "react-slick": "^0.27.14",
    "react-world-flags": "^1.4.0",
    "shopify-jwt-auth-verify": "^1.0.10",
    "store-js": "^2.0.4"
  },
  "devDependencies": {}
}

My node version is: 14.6.0
Shopify version: 2.6.5

I am not sure what is the problem, Only shopify node commands related to starting the server, are not working. All other shopify commands are working.

Confetti Animation issue

I’m creating a website to wish my friend her birthday. i added the confetti animation to it. the animation does work but the animation does not appear over the text it just appears underneath the text elements. help!

IF/ELSE statement in Javascript problems

I am new here and new to Javascript, I have looked through many of the questions and answers here relating to using IF/ELSE but I still can’t seem to get what I have working.
What I have is a page with a user input, so based upon the number entered I want to do one calculation if TRUE and another if FALSE. I would be grateful of any help or guidance. Script below:

<script language="javascript" type="text/javascript">
function calculate()

if ($("#lvl").val() < 50)
{

let lvl_fld={}

lvl_fld.level = Math.floor($("#lvl").val() * 1.5 + 4.5)
$("#flds").val(lvl_fld.level);

let total = Math.floor(lvl_fld.level); 

$("#total_value").text(total);
}
else
{
let lvl_fld={}

lvl_fld.level = Math.floor($("#lvl").val() * 2 + 8)
$("#flds").val(lvl_fld.level);

let total = Math.floor(lvl_fld.level); 

$("#total_value").text(total);

}

$(function()
{
$(".qty").on("change keyup",calculate)
})

</script>  

Why does Safari ignore transition events like transitionend?

I’ve added a simple ontransitionend listener. The code works in Firefox and Chrome, but doesn’t in Safari (desktop + iOS). I’ve tried syntax variations and used AlpineJS (Codepen) to do the same. But the problem appears to be with Safari not reacting at all to transition events. What could be happening here?

const el = document.getElementById('hasTransition');
el.ontransitionend = () => {
  document.getElementById('message').classList.remove('hidden');
};
#hasTransition{
  transition: all linear 200ms;
}
.hidden{
  opacity: 0;
}
<button onclick="el.classList.remove('hidden')">
  Click to trigger a transition
</button>
<p id="message" class="hidden">We've detected a transition.</p>
<p id="hasTransition" class="hidden">✨ I'm visible ✨</p>

Joi date validation not working on greater than

I have this joi validation schema

  requiredInceptionDate: Joi.date().format("DD/MM/YYYY").raw(),
  requiredExpiryDate: Joi.date()
    .format("DD/MM/YYY")
    .raw()
    .min(Joi.ref("requiredInceptionDate")),

however I get this error

Error: ValidationError: "requiredExpiryDate" must be greater than or equal to "ref:requiredInceptionDate"

the file I’m processing has

  "requiredInceptionDate":"01/09/2021",
  "requiredExpiryDate":"30/10/2022",

All i can think of is perhaps it doesn’t like the fact it’s a string? But that’s why I used raw()

Vue3 & Webpack generate index.common.js instead of index.js

I have a Vue 3 library. In package.json I have:

"main": "dist/index.js",
"unpkg": "dist/index.umd.min.js",

In vue.config.js I have:

configureWebpack: config => {
   config.output.filename = 'index.js';
},

To build library I do:

vue-cli-service build --target lib --name index src/index.ts && tsc --emitDeclarationOnly --outDir dist -p tsconfig.json

src/index.ts is a file that exports all classes, interfaces etc.

However, when I build my library I have the following in dist:

demo.html  
index.common.js  
index.common.js.map  
index.umd.js  
index.umd.js.map  
index.umd.min.js  
index.umd.min.js.map  
src
tsconfig.tsbuildinfo

As you see there is no index.js but there is index.common.js. Could anyone say how to fix it?

Lock WooCommerce product single page

I need to lock WooCommerce product single page while someone has put this item into cart. It has to have 15-min time countdown when product would be unlocked and cart will be emptied for others to buy that product( if it is still in stock).

Any ideas how to solve it?

Store content of JS variable inside DB? (Laravel)

I have some JS variables inside a Blade file which is a checkout page. In this checkout page, there is a cart summary with some informations about the product that is being purchased that are retrieved from a form in the previous page with Laravel sessions. In the checkout page I proceed to declare some JS variables to perform some basic calculations like cart total.

I also have a form with the order information, shipping and such, and I need to store the cart total inside this form. So I would need to save the total (the variable costoTotale) that has been calculated and save it as a value=”” inside an input. Is there a way I can do it?

This is my script tag with the variables:

  `   var costoIniziale = {{session('prezzo')}} * {{session('quantity')}};
                var costoSpedizione = costoIniziale + {{session('spedizione')}};
                var IVA = ((costoSpedizione * 1.22) - costoSpedizione).toFixed(2);
                var costoTotale =  (costoSpedizione * 1.22).toFixed(2);

     `

What I have tried so far is to do this:

 `  function total() {
               (costoSpedizione * 1.22).toFixed(2);
            }
            

            function getMyTotal() {
                document.getElementById('totaleLordo').setAttribute('value', total());
            }

With “totaleLordo” being the ID of my hidden input, but it doesnt’ work.

UseEffect Running infinitely

I have to make an api call that gets me a list.
So i am dispatching an action inside useEffect that makes an api call and then dispatches an action that is consumed by the reducer, which in turn returns updated state..
But the problem is when the component gets mounted useEffect is called infinitely..
I have tried-
1- Adding the dependencies inside the UseEffect
2- Passing empty array of dependencies..

This is my useEffect

useEffect(() => {
    console.log(enteredSearch)
    const identifier = setTimeout(() => {
      console.log('sending request')
          dispatch(getDSAList({
            page: 1,
            pageSize: 10,
            searchString: enteredSearch
          }))
        }, 500);
        return () => {
          console.log('cleanup')
          clearTimeout(identifier)
        }
    }, [enteredSearch]) 

This is the Action

export const getDSAList = (searchData) => {
    return async (dispatch) => {
        
        const fetchData = async () => {
            console.log('Fetching Data')
            const response = await webApiCall.post('https://a30fa91e-ae8b-42fb-8439-c2cc2d3cedfe.mock.pstmn.io/dsa/api/user/list',searchData)
            if(response.data.status !== 200) {
                throw new Error('Could not fetch DSA List')
            }
            return response.data.dsaResponse
        }

        try {
            const dsaData = await fetchData()
            dispatch(dsaActions.fetchDSAList(dsaData))
        }
        catch(error) {
            console.log(error)
        }
    }
}

This is the Reducer

import { createSlice } from "@reduxjs/toolkit";

const dsaSlice = createSlice({
    name: 'dsa',
    initialState: {},
    reducers: {
        fetchDSAList(state, action) {
            state.dsaList = action.payload.dsaList 
        },
        commentAndStatusUpdate(state, action) {
            state.commentAndStatusUpdate = action.payload
        }
    }
})
export const dsaActions = dsaSlice.actions
export default dsaSlice;

This is the store

import {configureStore} from '@reduxjs/toolkit'
import { loginSlice } from 'containers/signin/reducer'
import { logoutSlice } from 'containers/signout/reducer'
import dsaSlice from 'containers/DSA/reducer'
// Export store with reducers
export const store = configureStore({
    preloadedState:{},
    reducer: {
        signin: loginSlice.reducer,
        signout: logoutSlice.reducer,
        dsa: dsaSlice.reducer
    }
})

export const loginActions = loginSlice.actions
export const logoutActions = logoutSlice.actions

Scatter plot in Chart.js with annotations

I’ve created a scatter plot in Chart.js v3.7.1 and I’m trying to add some label annotations (chartjs-plugin-annotation is v1.4.0) to it which don’t seem to be working. I’ve added annotations in the past with earlier versions, but this version doesn’t seem to want to add them. Not sure what am I missing. Here is my code:

<div class="row">
    <div class="col-md-8 col-md-offset-1">
         <canvas id="ph" height="400" width="300" style="display:block"></canvas>
    </div>
</div>

@section Scripts {
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/1.4.0/chartjs-plugin-annotation.min.js"></script>
<script type="text/javascript">

self.phGraph();
self.updatepH(phChart);
var phChart;

 self.phGraph = function () {
        var ph = document.getElementById("ph").getContext('2d');
        if (phChart != undefined) phChart.destroy();
        phChart = new Chart(ph, {
            type: 'scatter',
            data: {
               label: [],
               datasets: [
                   {
                       backgroundColor: reportColor.Blue,
                       borderColor: reportColor.Blue,
                       label: 'pH',
                       yAxisID: 'y',
                       data: [],
                       borderWidth: 1,
                       pointRadius: 5,
                       fill: false
                   },
               ]
            },
            options: {
               responsive: true,
               plugins: {
                  legend: {
                    position: 'top',
                  },
                  title: {
                    display: true,
                    text: self.selectedWell().description() + ' pH profile'
                  },
                  annotation:{
                      annotations: []
                  }
               },
               scales: {
                   x: 
                   {
                       id: 'x-axis-1',
                       title: {
                          display: true,
                          text: 'pH',
                          //color: '#911',
                          font: {
                            size: 18
                          }
                       },
                       ticks: {
                           beginAtZero: false
                       }
                   },
                   y: 
                   {
                       id: 'y-axis-1',
                        title: {
                          display: true,
                          text: 'Along hole depth from RT (ft)',
                          //color: '#911',
                          font: {
                            size: 18
                          }
                        },
                        reverse: true,
                   }
               },
               elements: {
                    point: {
                       radius: 5
                    }
               },
               legend: {
                   display: true,
                   labels: {
                       filter: (legendItem, chartData) => (!chartData.datasets[legendItem.datasetIndex].data.every(item => item === null))
                   }
               }
            }
        });
    };
    self.updatepH = function (phChart) {
        var chartPH = phChart;
        chartPH.data.labels = [];
        for (var j = 0; j < chartPH.data.datasets.length; j++) {
            chartPH.data.datasets[j].data = [];
        }

        for (let seg of segs) {
            chartPH.data.datasets[0].data.push({x: parseFloat(seg["pH"].toFixed(3)), y: parseFloat(fromSI(seg["AHD"], unit["leng"]).toFixed(1))})
        }
        console.log(chartPH.data.datasets[0].data)
        chartPH.update();
        self.phChartAnnotation(phChart);
        chartPH.update();
    };

    self.phChartAnnotation = function (phChart) {
        var chart = phChart;
        chart.options.annotation = {};
        chart.options.annotation.annotations = [];

        var count = 0;
        if(self.plotLabelList().length > 0){
            for (var i = 0; i < segs.length; i++) {
                if(count < self.plotLabelList().length){
                    if (self.plotLabelList()[count].ahd() <= parseFloat(fromSI(segs[i+1]["AHD"], unit["leng"]).toFixed(1)) && self.plotLabelList()[count].ahd() >= parseFloat(fromSI(segs[i]["AHD"], unit["leng"]).toFixed(1))) {
                        //Add labels
                        chart.options.annotation.annotations.push({                    
                            type: 'label',
                            xScaleID: "x-axis-1",
                            yScaleID: "y-axis-1",
                            yValue: parseFloat(fromSI(segs[i]["AHD"], unit["leng"]).toFixed(1)),
                            backgroundColor: 'rgba(245,245,245)',
                    
                            content: [self.plotLabelList()[count].label()],
                           textAlign: 'start',
                            font: {
                              size: 18
                            },
                        });
                        count++;
                    }
                }
            }
        }
        chart.update();
    };   

Any help would be greatly appreciated! Thanks!

Printing newline characters in ejs

I’d like to print a string with newline characters with ejs.

I have this ejs file:

1.

If the string “names” is “line 1line 2” I get this:

line 1line 2

But I’d like this:

line 1
line 2

What is the best way of getting ejs to correctly interpret newline characters?