My javascript function returns data.forEach is not a function [duplicate]

I’m trying to run this forEach to fill as null the positions of the array where the attributes have the value = 0

var dados ={aguardando: 314356, enviando: 6440, enviado: 23455, erro: 7716, lido: 98, …}
function createLotesChart4(dados){
            

            var dataChart = {};
            dataChart['masstotal'] =dados.aguardando + dados.enviando + dados.enviado + dados.lido + dados.respondido + dados.erro + dados.pausado + dados.blacklist;
            dataChart['disparado'] = dados.enviado;
            dataChart['lidos'] = dados.lido;
            dataChart['respondidos'] = dados.respondido;
            dataChart['soft_bounce'] = dados.erro;
            dataChart['hard_bounce'] = dados.blacklist;
            dataChart['processando'] = dados.aguardando + dados.enviando;
            var dataChartJSON = JSON.stringify(dataChart);
            dataChartJSONObject = JSON.parse(dataChartJSON);
            
            //var = 0 ? null : var

            dataChartJSONObject.forEach(function(element, index) {
                if (element === 0) {
                    dataChartJSONObject[index] = null;
                }
            });

           ...

error presented on console:

Uncaught TypeError: dataChartJSONObject.forEach is not a function
    at createLotesChart4 (gerencial:2805)
    at Object.success (gerencial:2195)
    at fire (jquery.js:3182)
    at Object.fireWith [as resolveWith] (jquery.js:3312)
    at done (jquery.js:8757)
    at XMLHttpRequest.<anonymous> (jquery.js:9123)

How do i filter sitemap url with date modified to show urls for current date in app script?

var ss = SpreadsheetApp.getActiveSpreadsheet();

var sheet = ss.getSheetByName(‘Sheet1’);

function getLinks(){

var xml = UrlFetchApp.fetch(‘https://www.*********.com/job_listing-sitemap.xml’).getContentText();

var xmlObj = XmlService.parse(xml);

var root = xmlObj.getRootElement();

var ns = XmlService.getNamespace(‘http://www.sitemaps.org/schemas/sitemap/0.9’);

var links = root.getChildren();

var linksArr = [];

for(var i = 0; i < links.length; i++){

linksArr.push([links[i].getChildren()[0].getText()]);

}

sheet.getRange(2, 1, linksArr.length, 1).setValues(linksArr);
}

makeStyles() throwing error using Typescript

Good Evening,
I am trying to convert my JS react application to React Typescript, but I am running into a very long error. I am not sure how to get past this. Below is the code in the file its referencing and how I am implementing it, as well as the error.

I am new to Typescript and I have tried other solutions from other Stackoverflow posts, but none to see to have worked. I was originally using creatStyles(), but that does not seem to work either.

If I changed the implementation of useStyles to

//const useStyles = makeStyles<DefaultTheme>((theme: Theme) => {createStyles(appStyle)});

Then the error I get tells me that theme:Theme => void

Any guidance is appreciated

TypeScript error in /Users/augustshah/Documents/Coding-Tools-new/Projects/Payment-Dashboard/src/layouts/Admin.tsx(43,30):
Argument of type '(theme: Theme) => { wrapper: { position: string; top: string; height: string; }; mainPanel: { maxHeight: string; width: string; overflowScrolling: string; transition: string; overflow: string; position: string; float: string; }; content: { ...; }; container: { ...; }; map: { ...; }; }' is not assignable to parameter of type 'Styles<Theme, {}, "content" | "map" | "wrapper" | "mainPanel" | "container">'.
  Type '(theme: Theme) => { wrapper: { position: string; top: string; height: string; }; mainPanel: { maxHeight: string; width: string; overflowScrolling: string; transition: string; overflow: string; position: string; float: string; }; content: { ...; }; container: { ...; }; map: { ...; }; }' is not assignable to type 'StyleRulesCallback<Theme, {}, "content" | "map" | "wrapper" | "mainPanel" | "container">'.
    Call signature return types '{ wrapper: { position: string; top: string; height: string; }; mainPanel: { maxHeight: string; width: string; overflowScrolling: string; transition: string; overflow: string; position: string; float: string; }; content: { ...; }; container: { ...; }; map: { ...; }; }' and 'StyleRules<{}, "content" | "map" | "wrapper" | "mainPanel" | "container">' are incompatible.
      The types of 'wrapper' are incompatible between these types.
        Type '{ position: string; top: string; height: string; }' is not assignable to type 'CSSProperties | CreateCSSProperties<{}> | PropsFunc<{}, CreateCSSProperties<{}>>'.
          Type '{ position: string; top: string; height: string; }' is not assignable to type 'CreateCSSProperties<{}>'.
            Types of property 'position' are incompatible.
              Type 'string' is not assignable to type 'PositionProperty | PropsFunc<{}, PositionProperty>'.  TS2345

    41 |   </Switch>
    42 | );
  > 43 | const useStyles = makeStyles((theme: Theme) => (appStyle(theme)));
       |                              ^
    44 | 
    45 | 
    46 |  //const useStyles = makeStyles<DefaultTheme>((theme: Theme) => {createStyles(appStyle)});

Admin.tsx

const useStyles = makeStyles((theme: Theme) => (appStyle(theme)));



export default function Admin({ ...rest }) {
  // styles
  //const classes = useStyles();
  const theme = useTheme<Theme>();
  const classes = useStyles(theme);

 
  return (
    <div className={classes.wrapper}>
      {handleSideBarLogin() ?
     null :  <Sidebar
     routes={routes}
     logoText={"02DesignStudio"}
     logo={logo}
     image={image}
     handleDrawerToggle={handleDrawerToggle}
     open={mobileOpen}
     color={color}
     {...rest}
    />
      }
    </div>
  );
}

AdminStyle.tsx

import {
  drawerWidth,
  transition,
  container
} from "../../material-dashboard-react";

const appStyle = theme => ({
  wrapper: {
    position: "relative",
    top: "0",
    height: "100vh"
  },
  mainPanel: {
    [theme.breakpoints.up("md")]: {
      width: `calc(100% - ${drawerWidth}px)`
    },
    overflow: "auto",
    position: "relative",
    float: "right",
    ...transition,
    maxHeight: "100%",
    width: "100%",
    overflowScrolling: "touch"
  },
  content: {
    marginTop: "70px",
    padding: "30px 15px",
    minHeight: "calc(100vh - 123px)"
  },
  container,
  map: {
    marginTop: "70px"
  }
});

export default appStyle;

How to i echo $date in the js for every row in the database not just the first one?

I’m trying to display unavaliable dates by disabling them over the admin control panel which creates a table of dates that are non working days. Right now i thought of a way to display /”yyyy-mm-dd”,/ perfectly, tried it in regular php, works, i put it in js, no i get just the first value, the first date in this case 23rd of december (2021-12-23), how do i display every value of the $date. Here’s my code that you might find relevant

               <?php
                   $sql = "SELECT * FROM tbl_closed ORDER BY date ASC";
                   $res = mysqli_query($conn, $sql);
                   if($res==TRUE)
                   {
                       $count = mysqli_num_rows($res); 
                       if($count>0)
                       {
                           while($rows=mysqli_fetch_assoc($res))
                           {
                               $date=$rows['date'];
                               ?>
                                       
<script type="text/javascript">
    $(function () {
          var disabledDate = [<?php echo ""$date","; ?>];
        $('#datetimepicker1').datetimepicker({
            disabledDates: disabledDate
        });
    });
</script>
<?php echo ""$date",";?> //tried running this test to see what i get, i get what i want when outside of the js [], "2021-12-23", "2021-12-24", "2021-12-31", "2022-01-01",
<?php
                           }
                          }
                          else{}
                        }
?>

♣️Help.micro⍪soft.com #1877♣️947♣️7788♣️ Talk to 👁‍🗨a Person | ♣️👁‍🗨♣️

♣️Help.micro⍪⍪soft.com #1877♣️947♣️7788♣️ Talk to a Person | ♣️♣️

Help.microsoft.com +1-877-947-7788 rebuilds the data utility but doesn’t fix the help.microsoft.com talk to a person. This is often a complicated issue and has required fixing as soon as possible. When this Help.microsoft.com occurs users generally get the message, ‘Recover data file’ or ‘Your help.microsoft.com isn’t working. For this help.microsoft.com talk to a person, the help.microsoft.com file must fix and recovered. To stop this Help.
https://helpmicrosoftcomtalktoapersoni.pageride.com/

How to expand to maxWidth with alignSelf set

The following code correctly expands the max-width of a div:

<div style="display: flex; flex-direction: column;">
    <div style="max-width: 500px;">
        <div style="background-color: red; height: 20px;"></div>
    </div>
</div>

Result:
enter image description here

However, when I set any alignment, align-items on the parent-most div, align-self on the max-width div, etc, the maxWidth will no longer be used, and the actual width will be set to 0.
For example:

<div style="display: flex; flex-direction: column;">
    <div style="max-width: 500px; align-self: center">
        <div style="background-color: red; height: 20px;"></div>
    </div>
</div>

Produces a blank screen:

enter image description here

How do I both align the div (to the center for example), and keep its width intact? The goal is not to resort to using width, because that won’t adjust to the parent width (which may be anything). Any solution that would keep the width, but won’t insist on taking it even if there is no space, like with width, would work.

How do I handle undefined properties from the html in my Angular application before I receive data from my controller?

When my Angular component HTML renders. I will get lots of errors that look like this

ERROR TypeError: Cannot read properties of undefined (reading ‘someProperty’)

In my HTML page, I have lots of bindings that look like this

<h1>{{event.title.toUpperCase()}}</h1>

In most components I call a service to fetch data from my controller in the ‘ngOnInit()’ and I know that one solution to prevent this error before the data comes back from my controller is to make the property nullable like this

event?.title

but this doesn’t seem like a practical solution, especially if I have dozens on the page.

What I have tried –

  1. Making them nullable with a ‘?’ but that doesn’t seem correct, especially if I always doing it
  2. Setting the object type being returning from the controller to a ‘any’ (ex. event: any), but in some cases it still shows an error

QUESTION – What’s the best solution to handle this so I don’t keep getting these errors until my page data loads?

Should I have some conditional like *ngIf=”event” and hide the page until the data is received and show some loading indicator while waiting? Or is some way to jsut prevent these error from showing in the console?

JSON and JS repeat check index number (PURE JAVASCRIPT)

I am making a login site via JSON, and I want to check if a username matches with a password (by using array indexes to match username, password and email) but I can’t figure out how to see if the username matches with any index number and if there is an index in an array that corresponds with it in the passwords section. I can use indexOf with recursion (function that calls itself) but I have to increment the index checked by 1 which I do not know how to do. (searched for any stuff but I can’t find anything)
like this:

{
"usernames": [
"Supa", "Marwan", "Jason", "Jacob",
]
"passwords": [
"placeholder", "placeholder1", "placeholder2", "placeholder3",
]
}
function checkDetails(username, password) {
let message = document.getElementById("placeholder");
let password = document.getElementById("placeholder1");
let username = document.getElementById("placeholder2");

//part I am struggling with
let usernames = json.parse("usernames");
let passwords = json.parse("passwords");
message.innerHTML = (username === usernames[/*i want this to increment to check*/]) ? 
message.innerHTML = (password === indexOf(/*I want this to be the index of the one 
index that IS true to the conditional above*/)) ? m
essage.innerHTML = "Success with logging in" :
 message.innerHTML = "Invalid username or password";

How do i synchronize dynamic-body element networked a-frame and a-frame-physics

I am currently creating a online vr world with multiplayer, so i used networked a-frame to create the multiplayer world and i am using aframe-physics-system to create physics. But when i add a synchronized object with dynamic-body this doesnt get synchronized by the server so only the creator of the object can move it around.

<a-assets>
    <template id="sphere">
        <a-entity class="sphere">
            <a-sphere color="blue"></a-sphere>
        </a-entity>
    </template>
</a-assets>

<a-entity dynamic-body position="0 3 -10" id="sphere" Networked="template:#sphere;attachTemplateToLocal:True"></a-entity>

<!--Collide event-->
<script>
AFRAME.registerComponent('foo', {
    init: function() {
      this.el.addEventListener('collide', function(e) {
        console.log('Player has collided with ', e.detail.body.el);
        e.detail.target.el; // Original entity (playerEl).
        e.detail.body.el; // Other entity, which playerEl touched.
        e.detail.contact; // Stats about the collision (CANNON.ContactEquation).
        e.detail.contact.ni; // Normal (direction) of the collision (CANNON.Vec3).
      });
    }
})
</script>

TS keyof typeof does not allow object.keys() to be assigned?

I do not understand what the problem is with this code.

Here is my code:

export type SportsTypes = keyof typeof SportsIcons

export const sports: SportsTypes[] = Object.keys(SportsIcons);

I am typing my variable to the keys of an object.
But, when I then try to assign an array of said keys to this variable, I get the ts error:
Type 'string[]' is not assignable to type '("Football" | "GameController" | "Tennis" | "Basketball" | "PingPong" | "Volleyball" | "HockeyPuck" | "Chess" | "AmericanFootball" | "Baseball" | "SandVolleyball")[]

JS onclick function passing external file

I have a menu which is plain HTML In there I have some images. When you click on those an action should be preformed (for example opening or closing the menu). This plain HTML menu is included by PHP.

To preform an action, I thought adding the JS onclick=”” tag to my HTML would be a good idea. Now I have created some .js files that are in a subdirectory called js.

Now is my question how to pass the .js files located in the subdir to the onclick=”” tag.

(TLDR)

/index.php <- there is the navigation bar inside

/js/file.js <- want to access this file via onclick=”” in index.php

How can I do that

Sorting array based on property existence

I have an array, i need to sort the array based on one property if that exists.

  const arr =  [
        {
            "item_name": "Cake",
            "quantity": 1,
        },
        {
            "item_name": "Choclate",
            "out_of_stock_detail": {
                "out_of_stock_quantity": 1
            },
            "quantity": 3,
    
        }
    ]

let output = arr.sort((a,b) => {
   if(a.out_of_stock_detail){
    return 1 
  }else{
    return -1
  }
})

console.log(output)

What am I missing in this one, Any help is appreciated

Unable to display the images of backend on the browser

I build an eCommerce App with an admin dashboard, and I have faced an issue when adding or updating an image for every product, and can’t handle this error. the images are being stored in the database as a URL link and being stored in the uploads folder, but not being displayed in the table, and that’s what appears in the console on the browser.
this error shows in the console “Failed to load resource: the server responded with a status of 404 (Not Found)“. and can’t handle with this issue

Beurer-BEU-FC40-1638202407224.png:1 GET http://localhost:3000/public/uploads/Beurer-BEU-FC40-1638202407224.png 404 (Not Found)

this is the server code for the location of images (uploads) in app.js

   app.use('../public/uploads', express.static(__dirname + '../public/uploads'))

And this is the multer code for image files.

// file types
const FILE_TYPE_MAP = {
    'image/png': 'png',
    'image/jpg': 'jpg',
    'image/jpeg': 'jpeg'
};

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        const isValid = FILE_TYPE_MAP[file.mimetype];
        let uploadError = new Error('invalid image type');

        if (isValid) {
            uploadError = null;
        }
        cb(uploadError, 'public/uploads');
    },
    filename: function (req, file, cb) {
        const fileName = file.originalname.split(' ').join('-');
        const extension = FILE_TYPE_MAP[file.mimetype];
        cb(null, `${fileName}-${Date.now()}.${extension}`);
    }
});

const uploadOptions = multer({ storage: storage });

And this is the API code for posting a product with an image.

router.post(`/`, uploadOptions.single('image'), async (req, res) => {
    // validate the category of product
    const category = await Category.findById(req.body.category);
    if (!category) return res.status(400).send('Invalid Category');

    // validate the image file of the product
    const file = req.file;
    if (!file) return res.status(400).send('No image in the request');

    const fileName = file.filename;
    const basePath = `${req.protocol}://${req.get('host')}/public/uploads/`;
    
    let product = new Product({
        name: req.body.name,
        description: req.body.description,
        richDescription: req.body.richDescription,
        image: `${basePath}${fileName}`,
        brand: req.body.brand,
        price: req.body.price,
        category: req.body.category,
        countInStock: req.body.countInStock,
        rating: req.body.rating,
        numReviews: req.body.numReviews,
        isFeatured: req.body.isFeatured
    });

    product = await product.save()
    
    if(!product) return res.status(404).send({success:false, data: message, message: "the product not found"})

    res.status(200).send({ success: true, data: product })
})

Could anyone help me?