Regex matching dates in a string in Javascript

Following up from this thread, im trying to make this work

JavaScript regular expression to match X digits only

string = '2016-2022'
re = /d{4}/g
result = [...string.matchAll(re)]

This returns an array of two arrays. Is there a way to consolidate this into 1 array?

However it doesn’t look like this is returning the desired results

I’m new to regular expression. What am I doing wrong?

Fix @ Jinja variable parsing at Javascript code in a static JS file …?

I am running into this “old problem”: Jinja variable parsing only works on the html template (passed in to render_template), so if your Javascript code is in a static JS file the Flask/Jinja variables can’t be accessed”.
Jinja Flask issue: Uncaught SyntaxError: Unexpected token { in JSON at position 1 at JSON.parse
Does anyone know if there is already a solution for this. It’s ugly to embed the JS code in the HTML file

Define multiple get Ranges and Sheet Names with javascript

I am using below script to pull date from all spreadsheets in a folder. It is strong and working.

now i would like to expand this script to define multiple different sheet names instead of one. that is because we have the same file in 3 different langueses, now when it is running and there is a file from an other langues it cannot find the sheet(name) so the script gives the error that GetRange is null. The data is the same, So Ill go through the files looking for

The sheets: “Gegevenskaart” || “DataCard” || “Datenkarte”

The Same for Range. in this specified Sheet I have 6 different ranges. they are all the same size and all have the same kind of data but there are rows that I dont want to use. (20 rows data, 25 empty rows in between)

The ranges to get data from are : [A15:BC34 ,A63:BC82 ,A11:BC130, A159:BC178 ,A207:BC226 ,A255:BC274, A300:3BC319]
(also these data rows have a string in colomn A while the other rows dont have a string)

    function CombineDataToMasterFile() {                                                                    

  var folder = DriveApp.getFolderById("1234567890234567891234567");
  var filesIterator = folder.getFiles();
  var file;
  var fileType;
  var ssID;
  var combinedData = [];
  var data;

  while(filesIterator.hasNext()){
    file = filesIterator.next();
    fileType = file.getMimeType();
    if(fileType === "application/vnd.google-apps.spreadsheet"){
      ssID = file.getId();
      data = getDataFromSpreadsheet(ssID);
      data = data.map(function(r){return r.concat([file.getName()]); });
      combinedData = combinedData.concat(data);
    }
  }

  var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Datatest");
  ws.getRange("A2:BC").clearContent();
  ws.getRange(2, 1, combinedData.length, combinedData[0].length).setValues(combinedData);
} 

function getDataFromSpreadsheet(ssID){

  var ss =  SpreadsheetApp.openById(ssID);
  var ws = ss.getSheetByName("Blad1");
  var data = ws.getRange("A15:BC34").getValues();
  return data;

why is bool always FALSE, cannot reassign bool value in ajax call [duplicate]

learning javascript and making an ajax call as follows:

var emailExists= function (email) {

    var bool = false; 
    $.ajax({
        url: '@Url.Action("checkEmail")',
        type: 'POST',
        data: JSON.stringify({ 'email': email }),
        contentType: "application/json; charset=utf-8",
        async: true,
        success: function (response) {
            if (response.success) {
                console.log('success');
            } else {
                console.log('fail');
                $('#email-exists').show();
                bool = true;
            }
        },
        error: function (xhr, x, y) {
            $("body").removeClass("loader-section");
            $("div.loader-icon").hide();

            console.error('failed', xhr, x, y);
        }
    });
    console.log(bool);
    return bool;
}

as you can see in this line,

            console.log('fail');
            $('#email-exists').show();
            bool = true;

i am setting bool to be true, however, it never reassign the value of the bool variable, and always prints and returns false, despite the outcome of the response of the ajax call

How to replace global variable with relative import using Rollup?

Is it possible to use a global variable with rollup to result to a relative import of a file in the bundled dest?
Something like

const file = window.MY_GLOBAL;

to

const file = require(`path-to-file`);

I’ve seen the define plugin

define({
   replacements: {
      "window.manifestData": () => `require ("${externalManifestFile}")`,
    },
}),

but get Error SyntaxError: Unexpected token (1:12)

How to open file chooser using button (not input)?

I use Vue2 and my goal is to open choose file window, however I don’t want to use simple <input type='file'>. I just wanted to use a button for doing it. I prepared reusable Button module, which allows to choose file. I added logic to Button module and need to trigger this button in parent module Parent (as to open choose file window). I got stuck in @someFuncEmit – don’t know what function assign to it, actually I don’t want to assign a function since everything happens inside a Button module. And I just need to trigger the functions inside Button.

Button.vue

<template>
  <div>
    <v-btn @click="handleFileImport">
      {{ btnText }}
    </v-btn>
    <input 
      ref="uploader" 
      class="d-none" //here I hide the input
      type="file" 
      @change="openFile"> 
  </div>  
</template>

<script>
export default {
    name: 'Button',
    props: {
        btnText: {
            type: String
        },
    },
    methods: {
        handleFileImport() {
            this.$refs.uploader.click()
            this.$emit('someFuncEmit')
        },

        openFile(e) {
            var file = e.target.files[0];
            if (!file) {
                return;
            }
            var reader = new FileReader();
            reader.onload = e => e.target.result;
            reader.readAsText(file);
        }
    },
}
</script>

Parent.vue

<template>
  <v-container>
      <Button btnText="Add a file" @someFuncEmit /> // here I should assign some function but don't need it in fact I guess
  </v-container>
</template>

<script>
import Button from '../components/Button.vue'

export default {
  name: 'Project',
  components: {
    Button
  }
}
</script>

Is there something blocking a map method inside of a for loop?

I have JSON data stored in a file titled recipes.json (it’s local) and I’m using state hooks and storing that data in a state variable titled “recipes”. For reference,

here’s local .json data structure:

[
    {"id": "0001",
    "title": "Chicken Pot Pie",
    "url": "https://www.pillsbury.com/recipes/classic-chicken-pot-pie/1401d418-ac0b-4b50-ad09-c6f1243fb992",
    "time": {
        "prepTime": 25,
        "cookTime": 40
    },
    "ingredients": [
        "CHICKEN "
    ]
},

Here’s the state variable declaration and assignment:

const [recipes, setRecipes] = useState([]);

  useEffect(() => {
    const fetchRecipes = async () => {
      const response = await fetch('recipes.json');
      const recipesData = await response.json();
      setRecipes(recipesData);
    };
    fetchRecipes();
  }, []);

I have an array that I know is containing a dynamic ingredient list and am printing it to the user at any given time to display what’s contained within. It’s a variable titled allIngredients.

I’m trying to run a for loop through the diffrent json objects by id, per id map() the ingedients into an array arrayToCheck, and then compare that finished-per-recipe arrayToCheck to the user-created allIngredients, but I’m getting an error in my function: “The parser expected to find a ‘}’ to match the ‘{‘ token here.” I know it’s no where else in my code because I haven’t altered anything else and it was functional before adding this block:

  const useRecipes = () => {
    let arrayToCheck = [];
    for (recipes.id; recipes.length; recipes.id++) {
      recipes.map((map.recipe) => {
        arraytoCheck = arrayToCheck.push(recipe.ingredients.toUpperCase())
        if (arrayToCheck.sort() === allIngredients.sort()) {
          return recipe.title;
        }
      })
      arrayToCheck = [];
    }
  }

I know this may seem complicated (I’m newer to Stack Overflow, so ask any clarifying questions. Thanks in advance for the assistance.

cognitoUser.signOut() is not signing user out in React JS

  const logout = () => {
    const user = Pool.getCurrentUser();
    if (user) {
      user.signOut();
    }
  };

here’s my Logout code.

I tried this same code and hosted my react app in the S3 static host. it’s working properly on s3 generated URL. signout is working without any error

now I connected a domain to my s3 hosted site.
domain doesn’t have SSL.

domain format : http://{subdomain}.{domain}.co

I am able to log in and perform all Cognito operation. I am also getting a valid token . but during signout, it’s not working. why ?

is it because I am running without SSL?
how to fix it . here’s my code snippet for cookie storage setup as well

const authenticate = async (Username, Password) => {
    return await new Promise((resolve, reject) => {
      const user = new CognitoUser({
        Username,
        Pool,
        Storage: new CookieStorage({ domain: awsCookieStorageDomain , secure:false}),
      });

How to fix it.

Javascript Regex match() is returning diffrent output every time [duplicate]

I am creating a regex to match any space or tab in staring of string and end up with this error,
Here javascript returning 2 different outputs
1st time its matching 2nd time not matching and so on..

So I searched and found this kind of behaviour basically happen with //g (global)
Cause there will be multiple output due to global search

but here i am using //y

let SPACEORTAB = /^[ t]+/y
//here is the sample test

' test'.match(SPACEORTAB)
//[' ', index: 0, input: ' test', groups: undefined]

' test'.match(SPACEORTAB)
//null

' test'.match(SPACEORTAB)
//[' ', index: 0, input: ' test', groups: undefined]

' test'.match(SPACEORTAB)
//null

' test'.match(SPACEORTAB)
//[' ', index: 0, input: ' test', groups: undefined]

' test'.match(SPACEORTAB)
//null

You can see the out here at imgur, stcakoverflow was not allowing me to post img

Sorting and ordering an array with different criteria

I am trying to implement sorting and order to an array.

The challenge which I am facing is that I have 5 criteria on which to base my sorting, which are:

  1. due_date === 1000
  2. status && is_approved(boolean)
  3. is_overdue(boolean checking with
    date-fns using the due_date)
  4. due_date (either null, or number)
  5. is_approved

What I would like to achieve is to create a sorting function which orders the above criteria as the following (from highest to lowest):

  1. due_date === 1000

  2. is_overdue (I am using isAfter of the date-fns which returns a boolean)

  3. status === 'DONE' && !is_approved

  4. due_date starting from lowest to highest (ignore the null values)

  5. is_approved === true

  6. any other remaining object

I was thinking of perhaps running .map method, and appending a ranking value for each of the object by checking the criteria, but there must be a way of doing this in single iteration with .sort method. I already checked other StackOverflow threads, but most of their data is relatively simple such as age, name etc.

How to make a smooth texture transition in three.js

I was able to do this in Blender, my goal is to have a smooth transition between two texture. I did this because I’d like to avoid having a huge 8k texture on the ground.

However, it is not possible to export this in a GLTF file, so I tried to do this in Three.js unsuccesfully. I have no clue what approach to take.

enter image description here

How to make OpenWeather API work in Chrome?

I’m writing code for a personal dashboard and I need to have the weather report for the current location.

I put relating part of my code below, it works in every other browser(FireFox, Safari, Edge, etc) but not in Chrome, access to location is enabled inside Chrome and I tried to log out the response data from API to console but there is nothing, it doesn’t even get the data.

How can I fix that?

*I’m learning on Scrimba and they somehow customize the API so we don’t need ‘API key’. That’s why the api is slightly different from the original one

Corresponding JavaScript Code

    navigator.geolocation.getCurrentPosition(position => {
    fetch(`https://apis.scrimba.com/openweathermap/data/2.5/weather?lat=${position.coords.latitude}&lon=${position.coords.longitude}&units=metric`)
        .then(res => {
            if (!res.ok) {
                throw Error("Weather data not available!");
            }
            return res.json();
        })
        .then(data => {
            console.log(data);
            const iconUrl = `http://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png`;
            document.getElementById("weather").innerHTML = `        
                <img src=${iconUrl} />
                <p class="weather-temp">${Math.round(data.main.temp)}&#176</p>
                <p class="weather-city">${data.name}</p>
            `
        })
        .catch(err => console.log(err));
    }); 

Screenshot In Chrome

enter image description here

Screenshot In Edge

enter image description here

How to create a md file using javascript data onto github

I’m getting form submission data through Netlify forms.

I want to be able to create a md file with that same data on github when the form is submitted.

So far on my submission-created.js function (triggered by client submission) I’m fetching client’s submission data like so:

exports.handler = async function(event, context, callback) {

  const data = JSON.parse(event.body).payload.data;

  let date = new Date().toUTCString().replace(/[s|,|:]/g, "-");
  date = date.substring(5, date.length);

  let courtData = 
`---
name: Automatic-file-${date}
location:
lat: ${data?.latitude}
lng: ${data?.longitude}
email: ${data?.email}
byhoopers: ${data?.byhoopers ? data?.byhoopers : false}
openUse: ${data?.openUse}
openTime: ${data?.openTime ? data?.openTime : "unknown"}
social: ${data?.social}
image: ${data?.file?.url}
formcourt: true
---
${data?.info ? data?.info : ""}
![](${data?.file2?.url ? data?.file2?.url : ""})
![](${data?.file3?.url ? data?.file3?.url : ""})
![](${data?.file4?.url ? data?.file4?.url : ""})
![](${data?.file5?.url ? data?.file5?.url : ""})
`;

  return { 
    statusCode: 200,
    body: JSON.stringify(data),
  };
};

It’s working fine but now I need to save this data to a md file and push it to github.

I’m doing something like this but struggling with next step:

let githubContent = Buffer.from(courtData).toString('base64');

let courtInfo = JSON.stringify({
    message: `new court file ${date}`,
    content: githubContent,
});

let githubPush = {
        method: "put",
        url: `https://api.github.com/repos/*****${date}.md`,

    headers: {
        Authorization: "*********",
        "Content-Type": "application/json",
    },
    data: courtInfo,
};

Failed to execute ‘share’ on ‘Navigator’: A earlier share had not yet completed

I just saw some users on my site experience this error

InvalidStateError: Failed to execute ‘share’ on ‘Navigator’: A earlier share had not yet completed.

This happens on this portion of the code:

if(navigator.share) {
  navigator.share({
    url: 'https://www.example.com',
  });
}

The MDN website do not even mentions about possibility of this error.

I saw the the error is coming from Chrome browser from Windows, Android and Chrome Os. I saw that chrome on mac do not have share feature as of now. Worth to mention that the issue happens quite rarely. I tried to reproduce it, by clicking the share multiple times fast, throttling cpu and network, canceling the share and I was never able to make it throw this error.

Do anyone know how to trigger this error or saw any documentation about it?