Javascript Date out by one day (the day before)

So I select two dates and build an array based on this.

For example:

var getDaysArray = function (s, e) { for (var a = [], d = new Date(s); d <= e; d.setDate(d.getDate() + 1)) { a.push(new Date(d)); } return a; };
var daylist = getDaysArray(new Date(datefrom), new Date(dateto));

This returns (daylist) the following:

0: Thu Mar 31 2022 00:00:00 GMT+0800 (Australian Western Standard Time) {}
1: Fri Apr 01 2022 00:00:00 GMT+0800 (Australian Western Standard Time) {}
2: Sat Apr 02 2022 00:00:00 GMT+0800 (Australian Western Standard Time) {}
3: Sun Apr 03 2022 00:00:00 GMT+0800 (Australian Western Standard Time) {}
4: Mon Apr 04 2022 00:00:00 GMT+0800 (Australian Western Standard Time) {}
5: Tue Apr 05 2022 00:00:00 GMT+0800 (Australian Western Standard Time) {}

This is correct. However when I then build these dates:

const thesedays = daylist.map((v) => v.toISOString().slice(0, 10));

This returns (thesedays) the following:

0: "2022-03-30"
1: "2022-03-31"
2: "2022-04-01"
3: "2022-04-02"
4: "2022-04-03"
5: "2022-04-04"

So it is actually using the day before (March 30 instead of 31 and April 4 instead of 5)

It is the const of thesedays that I need to adjust … just not sure how?

Built Neutralino app cannot open localhost?

I have a very peculiar issue, I have a Neutralino app built with Preact that runs perfectly fine when run with neu run, however, once I build the project (with enableServer on or off), the built application will not load anything.

With enableServer on, it will complain that it cannot connect to localhost:
“This localhost page cannot be found”

and with it off it gives me a completely white screen/DOM.

The GitHub repository is here: https://github.com/SpikeHD/XeniaLauncher

I suspect it may be the way I am building the project, but I find it weird that neu run works completely fine.

Below is my configuration:

{
  "applicationId": "js.xenia_launcher.app",
  "version": "1.0.0",
  "defaultMode": "window",
  "port": 0,
  "documentRoot": "/build/",
  "url": "/",
  "enableServer": true,
  "enableNativeAPI": true,
  "tokenSecurity": "one-time",
  "logging": {
    "enabled": true,
    "writeToLogFile": true
  },
  "nativeAllowList": [
    "app.*",
    "os.*",
    "filesystem.*",
    "storage.*",
    "window.*",
    "debug.log"
  ],
  "modes": {
    "window": {
      "title": "XeniaLauncher",
      "width": 1000,
      "height": 800,
      "minWidth": 400,
      "minHeight": 200,
      "fullScreen": false,
      "alwaysOnTop": false,
      "icon": "/resources/icons/appIcon.png",
      "enableInspector": true,
      "borderless": false,
      "maximize": false,
      "hidden": false,
      "resizable": true,
      "exitProcessOnClose": true
    },
    "browser": {},
    "cloud": {
      "url": "/resources/#cloud",
      "nativeAllowList": [
        "app.*"
      ]
    },
    "chrome": {
      "width": 1000,
      "height": 800,
      "args": "--user-agent="Neutralinojs chrome mode""
    }
  },
  "cli": {
    "binaryName": "XeniaLauncher",
    "resourcesPath": "/resources/",
    "extensionsPath": "/extensions/",
    "clientLibrary": "/resources/js/neutralino.js",
    "binaryVersion": "4.4.0",
    "clientVersion": "3.3.0"
  }
}

JavaScript filter object resemble key name and push to arr

This is my question:

const arr = [];
const Picture = {
  PictureDescription1: "this is description 1",
  PictureDescription2: "this is description 2",
  PictureDescription3: "this is description 3",
  PictureUrl1:"https://www.taiwan.net.tw/att/event/8b20ab7e-90e0-49a8-9137-d140fa5d369a.jpg",
  PictureUrl2:"https://www.taiwan.net.tw/att/event/7da4b849-11a7-46c8-96fb-412f187ad8bf.jpg",
  PictureUrl3:"https://www.taiwan.net.tw/att/event/f04581ce-6b16-46cd-9af3-5661276b9b68.jpg", 
}

and I want to make url and descirption to a group and push to a arr. This was my way, but I think it too lengthy:

if(Picture.PictureUrl1) {
 arr.push({
  url: Picture.PictureUrl1,
  description: Picture.PictUrlDescription1
 })
}

if(Picture.PictureUrl2) {
 arr.push({
  url: Picture.PictureUrl2,
  description: Picture.PictUrlDescription2
 })
}

if(Picture.PictureUrl3) {
 arr.push({
  url: Picture.PictureUrl3,
  description: Picture.PictUrlDescription3
 })
}

Is there any ohter way to do this?

How to change the data in extJS combo dropdown?

How to change the data in extJS combo dropdown ?

I have Combo box and I am trying to load the data. I want to sanatiize my data for some Reg expression.

Here is my Stroe code.

Ext.define("MyApp.store.combo.country", {
    extend: "Ext.data.Store",
    alias:"widget.country",
    //autoLoad:true,
     fields: [{
            name: 'name',type:'string'
        },{
            name: 'key',type:'int'
        }],
    proxy: {
        type: 'ajax',
        method: 'GET',
        url: '/myCountry/getName',
        reader: {
            type: 'json'                
        }
    },
    listeners: {
        beforeload ( store, operation, eOpts ) {
            console.log("combo before load");
        },

        load: function (_this, records, successful, operation, eOpts) {
            var length = records.length;
            var htmlRegex = new RegExp("<("[^"]*"|'[^']*'|[^'">])*>");
            for(var i=0; i<length; i++){
                if(htmlRegex.test(records[i].data.name)){
                    records[i].data.name = records[i].data.name.replace( /(<([^>]+)>)/ig, '');
                }
            }
        }
     }
});

Now when I click on COmbobox I can not see the data in the dropdown is sanatize (Executing without passing RegExp). For the second time this is working fine.

So my question is how can I alter my data in this situation.

What I ahve tried taht you can see in load method.(Even In before load method also nothing is happening.)

Any work around

Remove and replace build files of a particular entry in wepack

I have a webpack file that have multiple entry points, and it build each output of the entry files into a single build file.

for eg :

  commonSettings = {
    entry: {
      dashboard: "/manage/dashboard.js",
      settings: "/manage/settings.js",
     },
  }

So the issue is that each time i take build a particular entry, i will get more and more built files inside it.

dashboard-f1aw545234ej235213513.min.js
dashboard-f3ari2j3jn5b534k6j3rm.min.js
dashboard-f5kljh3q4jbkl2jrjkenn1.min.js

How can i replace the existing build file for the particular entry when am doing a new build ?

Calling API between React Navigation events

I am trying to set up an authentication flow using React Navigation where the app loads the appropriate stack according to the redux state. If auth.isAuthenticated I would like to call fetchBusiness() but during this call the loading screen should render.

The problem I am having is that the fetchBusiness() function keeps re-rendering.

const NavigationStack = () => {
  const auth = useSelector((state) => state.auth);
  const business = useSelector((state) => state.business);
  const dispatch = useDispatch();
  //  In general, it's best and safest to load fonts from
  // your local assets. -Expo
  let [fontsLoaded] = useFonts({
    Metropolis: require("./assets/fonts/metropolis.regular.otf"),
  });

  useTokenVerify();

  if (!fontsLoaded || auth.isLoading || business.isLoading) {
    return <LoadingScreen />;
  }

  if (auth.isAuthenticated && !business.isLoading) {
    dispatch(fetchBusiness());
  }

  return (
    <NavigationContainer>
      {!auth.isAuthenticated ? (
        <AuthFlow />
      ) : business.business.status === "succeeded" && business.business.count === 0 ? (
        <RootNavigationStack initialRouteName={"BusinessProfile"} />
      ) : business.business.count === 1 ? (
        <RootNavigationStack initialRouteName={"BottomTabFlow"} />
      ) : (
        <AuthFlow />
      )}
    </NavigationContainer>
  );
};

How can I fix this? I have tried useLayoutEffect which, as I understand, calls the function after the the component fully mounts, to no avail.

How to use add.js in shopify for multiple ids and quantity

;
If I use multiple id and quantity it add only first id product
can you please guide me how can I use add.js for multiple products
If i use this code it works perfectly but I want dynamic quantity and Ids

const data = {items: [{quantity: 1,id: 42617994903793},{quantity: 2,id: 42617996542193}]};

Here is my code

Set minimum length restriction to Password Validation – Regular Expression

I have a regular expression for validating passwords.

/[wd]*(([0-9]+.*[A-Za-z]+.*)|[A-Za-z]+.*([0-9]+.*))/

This regex matches any words which contain letters and numbers in them.

I want to add a minimum length restriction as well, I got to know we can use {4,} to add a minimum length of 4.

But I am not able to figure out how to add this minimum length to the whole expression.

For example:
The above regex matches p12 as valid.

I dont want it to match words with letters and numbers with a length of less than 4.

I tried this, but this did not work

/[wd]*(([0-9]+.*[A-Za-z]+.*)|[A-Za-z]+.*([0-9]+.*)){4,}/

Any help with respect to adding minimum length restriction to the whole expression would be appriciated.

Thank you.

Combining and grouping arrays using JavaScript

I have two sets of data that need to be combined and grouped a certain way.

First set of data:

let overallCert =
[
  {
      "id": "1",
      "entity_id": "3",
      "status": "Certified",
  },
  {
      "id": "379",
      "entity_id": "417",
      "status": "Certified",
  }
];

Second set of data:

let userCerts =
[
  {
      "id": "640",
      "entity_id": "417",
      "method": "Field Study",
      "strand": "",
      "date_completed": "2016-07-15T08:00:00.000Z"
  },
  {
      "id": "814",
      "entity_id": "417",
      "method": "Field Study",
      "date_completed": "2019-07-15T08:00:00.000Z"
  },
  {
      "id": "844",
      "entity_id": "3",
      "method": "Online",
      "date_completed": "2022-03-28T08:00:00.000Z"
  },
  {
      "id": "845",
      "entity_id": "3",
      "method": "Field Study",
      "date_completed": "2022-03-28T08:00:00.000Z"
  }
];

I want to merge and group these arrays of objects by entity_id to create this output below…

Desired output:

let desiredOutput = 
[
  [
    [
      {
        "id": "640",
        "entity_id": "417",
        "method": "Field Study",
        "date_completed": "2016-07-15T08:00:00.000Z"
      },
      {
        "id": "814",
        "entity_id": "417",
        "method": "Field Study",
        "date_completed": "2019-07-15T08:00:00.000Z"
      },
    ],
    [
      {
        "id": "379",
        "entity_id": "417",
        "status": "Certified",
      }
    ]
  ],
  [
    [
      {
        "id": "844",
        "entity_id": "3",
        "method": "Online",
        "date_completed": "2022-03-28T08:00:00.000Z"
      },
      {
        "id": "845",
        "entity_id": "3",
        "method": "Field Study",
        "date_completed": "2022-03-28T08:00:00.000Z"
      }
    ],
    [
      {
        "id": "379",
        "entity_id": "417",
        "status": "Certified",
      }
    ]
  ]
];

So far, I have managed this:

let certsDataCombined = overallCert.map(item => ({ ...item,
  0 : userCerts.filter(c => c.entity_id == item.entity_id)
}));

let userCertsGroupBy = groupBy(certsDataCombined, "entity_id");

function groupBy(arr, prop) {
  const map = new Map(Array.from(arr, obj => [obj[prop], []]));
  arr.forEach(obj => map.get(obj[prop]).push(obj));
  return Array.from(map.values());
}

This code almost does the trick, but I need to encapsulate the overallCert data in its own array, plus the nesting is a little off. Here is the current output:

enter image description here

MeshBasicMaterial Three.js brightness

I am currently using a MeshBasicMaterial in threejs to be lights. There is a fake point light inside of each one.
I have a variable called color. It is rgb(random value, random value, random value). I want the MeshBasicMaterial to be brighter, currently. Is there any way to do this? I am open to switching to another material if I need to.

Finding a specific object in state, removing it and replacing it in React

My current code finds an object in a state array, removes it and then adds a newValue in its place. I know using .splice() mutates the state directly which is not a recommended practice in React. What is the proper way to do what I am trying to do below?

      const found = clientServiceReferral.selectedTimeSlots.find(element => element.timeSlot === timeWithDate);

      if (found) {
        clientServiceReferral.selectedTimeSlots.splice(found, 1)
      }


      const newValue = {
        timeSlot: timeWithDate,
        value: value.value
      }

      setClientServiceReferral({
        ...clientServiceReferral,
        selectedTimeSlots: [...clientServiceReferral.selectedTimeSlots, newValue]
      })

Conditionally add an object to API response

I run a JS API request that is supposed to return a 200 response code with no content. However, I need it to return an object.

Would you know how to add a condition that checks if a response is empty, and if that is the case would add an object to the response? Something simple such as if response is empty return {“success”: true}, if response is not empty return {“success”:false}

Here’s my JS request:

const options = {
  url: `https://${bundle.authData.server}.boostlingo.com/api/web/appointment/cancel`,
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${bundle.authData.token}`
  },
  params: {

  },
  body: {
    'appointmentId': bundle.inputData.appointmentId,
    'reason': bundle.inputData.reason,
    'otherReason': bundle.inputData.otherReason,
    'suppressCancellationNotifications': bundle.inputData.suppressCancellationNotifications
  }
}

return z.request(options)
  .then((response) => {
    response.throwForStatus();
    const results = response.json;

    // You can do any parsing you need for results here before returning them

      return results;


  });

I tried a few conditional block statements but no luck.

Let me know your thoughts.

Express validator custom function

I’m trying to write a custom validator for an express API. I can’t figure out how I can reject incorrect values from the custom validator. Here’s what I have:


function validateInput(value) {
    if (!(
        (check(value).isIn(utils.getNames()) ||
        check(value).isIn(utils.getIds()) ||
        check(value).isIn(utils.getHexIds()))
    )) {
        return Promise.reject("Invalid input");
    }
}

router.get('/endpoint',
    query("input").custom(async (value) => {
        await validateInput(value).catch()
    }),
    async (req, res) => {
        try {
            validationResult(req).throw();
        } catch (err) {
            res.status(400).json({"error": "A valid value for input must be passed"});
            return;
        }
   }

I have a feeling I”m not correctly handling the promise correctly, but I can’t figure out the right solution either. Here are the docs for the custom validator: https://express-validator.github.io/docs/custom-validators-sanitizers.html

Make the content fit the width of MUI gird

Trying to make the with of material ui form 100% but not working. I inspected the elements and tried as many classes I think are causing the problem the fields to skew to left.

JSS:

    const useStyles = makeStyles((theme) => ({
        root: {
            background: "#fff",
            padding: theme.spacing(1),
            flexGrow: 1,
            alignItems: "center",
            align: "center",

            "& .MuiFormControl-root": {
                margin: theme.spacing(2),
                width: "90%",
            },
            "& .MuiFormControlLabel-root": {
                marginLeft: theme.spacing(2),
            },
            "& .Mui-checked": {
                color: "primary",
            },
            "& .MuiSvgIcon-root": {
                fill: "#0ad33c",
            },
            "& .MuiFormHelperText-root": {
                color: "red",
            },
            "& .MuiCheckbox-root": {
                paddingLeft: theme.spacing(2),
            },
            "& .MuiGrid-root.row": {
                minWidth: '99% !import',
            },
        },
        row:{
            minWidth: '95%'
        }
    }));

and and formik form:

        <Formik
        initialValues={initialValues}
        onSubmit={onSubmit}
        enableReinitialize
        >
        {({ values, isSubmitting, setFieldValue,  }) => (
            <Form>
                <Fragment>
                    <Grid className={classes.root}>
                        <Grid 
                            container 
                            spacing={3}
                            style={{alignItems: 'center', paddingRight: '1em', flexDirection: 'row'}}
                        >
                                <FieldArray name="PreTaxDeductions">
                                {({ remove, push }) => (
                                <Grid>
                                    {values.PreTaxDeductions.map((_, index) => (
                                        <Fragment>
                                            <Grid className="row" key={index}>
                                                <InputField label="Name of the reduction" name={`PreTaxDeductions.${index}.name`} />
                                                <InputField label="Rate" name={`PreTaxDeductions.${index}.rate`} type="number" />
                                                <SelectField 
                                                    label="Apply To" 
                                                    name={`PreTaxDeductions.${index}.applyTo`} 
                                                    options={ApplyTo} 
                                                    onChange={(e)=>{
                                                        setFieldValue(`PreTaxDeductions.${index}.applyTo`, e.target.value)
                                                    }}
                                                />
                                                { values.PreTaxDeductions.length > 1 &&
                                                    <IconButton 
                                                        aria-label="delete" 
                                                        style={{paddingTop: '2em'}} 
                                                        disabled={isSubmitting}
                                                        onClick={()=>remove(index)} 
                                                    >
                                                        <DeleteIcon fontSize="medium"  />
                                                    </IconButton>
                                                }
                                            </Grid>
                                        </Fragment>
                                        ))}
                                        <Box 
                                            style={{display: "flex", flexDirection: "row", 
                                            justifyContent: size < 960 ? "center" :"flex-end"
                                        }} 
                                            mb={2} mt={6} 
                                        >
                                            <Button 
                                                type="button"
                                                variant="contained" 
                                                color="primary"
                                                style={{marginRight: "1em"}}
                                                onClick={() => push({ name: '', rate: '', applyTo: "" })}
                                                disabled={isSubmitting}
                                            >
                                                Add A Pre-tax Deduction 
                                            </Button>
                                            <Button
                                                type="submit"
                                                variant="contained"
                                                color="secondary"
                                                disabled={isSubmitting}
                                            >
                                                {isSubmitting ? <ButtonCircularProgress />: "Save"}
                                            </Button>
                                        </Box>
                                    </Grid>
                                )}
                                </FieldArray>
                        </Grid>
                    </Grid>
                </Fragment>
            </Form>
        )}
        </Formik>

and here is the output:

enter image description here

I tried many solutions to fit the fields to 100% of the width but I’m stuck really.

This only happens when the fields are in a map function, can anyone help me?

How do I make two dispatches in redux run in order?

Suppose I have two dispatches I want to fire in order called

dispatch(action1())
dispatch(action2())

Action1 is an action creator created using

createAsyncThunk 

method from redux/toolkit.

Therefore, it uses async… await in the process.

Action2 is a synchronous process.

I want to make

`dispatch(action2())` run only after `action1()` has been dispatched.

How can I achieve this?

I have tried doing

dispatch(action1(), dispatch(action2())

but I have found that dispatching inside of a reducer is an anti-pattern since reducers are pure.