How to group objects from angular http call to backend

I am calling the backend with this http call:

this.StudentEnrollment.getRecordsById(list.value.split(/[rn]+/)).subscribe(values => {
  this.studentObject = values;
});

studenObject looks like this

{
    records: [{name: james, school: USC, .....}, {name: Micheal, school: UCLA, ......},{name: 
         John, school: UCLA, ......}],
    size: 3
}

Is it possible to group the schools then add it to studentObject? maybe create a list of schools with all their objects?

i am getting this error Uncaught TypeError TypeError: allSections.addEventListener is not a function [duplicate]

// Here i m getting these following errorsstrong text
//I have laready checked post with jquery and javascript mix match but couldnt understand them

const sections = document.querySelectorAll('.section');
const sectBtns = document.querySelectorAll('.controlls');
const sectBtn = document.querySelectorAll('.control');
const allSections = document.querySelectorAll('.main-content');


function PageTransitions() {
    //Button click active class
    for (let i = 0; i < sectBtn.length; i++) {
        sectBtn[i].addEventListener('click', function() {
            let currentBtn = document.querySelectorAll('.active-btn');
            currentBtn[0].className = currentBtn[0].className.replace('active-btn', '');
            this.className += 'active-btn';

        })
    }
    //section active
    allSections.addEventListener('drag', (e) => { console.log($(this).e.target) });


}
PageTransitions();

not receiving jwt after logging in?

I’ve been trying to work on a movie app using the MERN stack. After having a few issues regarding the backend of one the features, I went back through my code and realised it doesnt seem that the jwt is being recieved after login. I have no issues with the signup and login other that it seemingly not obtaining the jwt

Heres the authJwt file

    const jwt = require("jsonwebtoken");
    const config = require("../config/auth.config.js");
    const db = require("../models");
    const User = db.user;
    const Role = db.role;
    
    verifyToken = (req, res, next) => {
      let token = req.headers["x-access-token"];
    
      if (!token) {
        return res.status(403).send({ message: "No token provided!" });
      }
    
      jwt.verify(token, config.secret, (err, decoded) => {
        if (err) {
          return res.status(401).send({ message: "Unauthorized!" });
        }
        req.userId = decoded.id;
        next();
      });
    };
    
    isAdmin = (req, res, next) => {
      User.findById(req.userId).exec((err, user) => {
        if (err) {
          res.status(500).send({ message: err });
          return;
        }
    
        Role.find(
          {
            _id: { $in: user.roles }
          },
          (err, roles) => {
            if (err) {
              res.status(500).send({ message: err });
              return;
            }
    
            for (let i = 0; i < roles.length; i++) {
              if (roles[i].name === "admin") {
                next();
                return;
              }
            }
    
            res.status(403).send({ message: "Require Admin Role!" });
            return;
          }
        );
      });
    };
    
    isModerator = (req, res, next) => {
      User.findById(req.userId).exec((err, user) => {
        if (err) {
          res.status(500).send({ message: err });
          return;
        }
    
        Role.find(
          {
            _id: { $in: user.roles }
          },
          (err, roles) => {
            if (err) {
              res.status(500).send({ message: err });
              return;
            }
    
            for (let i = 0; i < roles.length; i++) {
              if (roles[i].name === "moderator") {
                next();
                return;
              }
            }
    
            res.status(403).send({ message: "Require Moderator Role!" });
            return;
          }
        );
      });
    };
    
    const authJwt = {
      verifyToken,
      isAdmin,
      isModerator
    };
  module.exports = authJwt;

Heres the user routes file. When I go to http://localhost:8081//api/test/user after logging in, it displays the message “No token provided!”

const { authJwt } = require("../middlewares");
const controller = require("../controllers/user.controller");

module.exports = function(app) {
  app.use(function(req, res, next) {
    res.header(
      "Access-Control-Allow-Headers",
      "x-access-token, Origin, Content-Type, Accept"
    );
    next();
  });

  app.get("/api/test/all", controller.allAccess);

  app.get("/api/test/user", [authJwt.verifyToken], controller.userBoard);

  app.get(
    "/api/test/mod",
    [authJwt.verifyToken, authJwt.isModerator],
    controller.moderatorBoard
  );

  app.get(
    "/api/test/admin",
    [authJwt.verifyToken, authJwt.isAdmin],
    controller.adminBoard
  );
};

Code being skipped over in node async fs.readFile [duplicate]

enter image description here

I’m trying to store an array of objects , with each object containing an array and an index (called ‘column’). the column is string that looks like

'0:lubbock:LW8-12$'

In the main file I am calling:

const tbdObj = await myFunctions.getFromStorageBy(mycolumn);

I want to search through the json in the file ‘storage.json’ for the object that matches the index (there should be only 1).

async function getFromStorageBy(index) {
  let match;
  fs.readFile("storage.json", function (err, data) {
    // Display the file content
    // console.log(index);
    const jsonArray = JSON.parse(data);
    const matches = jsonArray.filter(obj => obj.column == index);
    console.log('matches');
    console.log(matches);
    match = matches.pop();
    console.log(match);
  });
    return match;
}

The program appears to skip over the readfile block and match is undefined when I try to return it. What am I doing wrong?

svelte: how can I declare two cyclically reactive variables?

I have two variables a and b which add up to 100. How do I set up a reactive declaration such that when a changes b changes to be 100 - a and vice versa? When I try something like

let total = 100;
$: a = total - b;
$: b = total - a;

I get a ‘Cyclical dependency detected’ error. Is there any way to get this done?

Unable to redirect user to login page after authentication check in Express.js

I have been attempting to redirect users to a login page after submitting a request to the home page if they are not logged in, but they keep getting redirected to the home page regardless. I have a method that is used to verify if they are logged in and returns a boolean with their status, then I have written another helper function using this method to redirect the user:

const verifySession = (req, res, next) => {
  if (req.session) {
    models.Sessions.get({hash: req.session.hash})
      .then(sessionInfo => {
        return models.Sessions.isLoggedIn(sessionInfo);
      })
      .then (status => {
        if (!status) {
    console.log(‘status’, status);
          res.redirect('/login');
        } else {
          next();
        }
      });
  }
};

The console.log for status is returning false as expected, but still no redirect is occurring. I have tried using this helper function in several different ways in my express request handler:

app.get('/',
  (req, res) => {
    verifySession(req, res);
    res.render('index');
  });

Or:

app.get('/', verifySession,
  (req, res) => {
    res.render('index');
  });

Or also:

app.use('/', verifySession);

app.get('/',
  (req, res) => {
    res.render('index');
  });

All of these have failed to redirect the user, and they are still being sent to the home page even when the status is returning false and the res.redirect call should be occurring.

Using Shopify Product AJAX API on Checkout.Liquid

Goal:
To create a product upsell section within checkout.liquid in a Shopify Plus store by checking the cart’s products metafields for the appropriate upsell product.

Issue:
The main issue I am running into is retrieving any response from the Product AJAX API. I retrieve the handles which are stored in the metafields using this liquid code:

  var recommendation_handle = [];
  {% for line_item in checkout.line_items %}
  {% if {{line_item.product.metafields.details.recommendation}} != "" %}
  recommendation_handle.push("{{line_item.product.metafields.details.recommendation}}");
 
  {% endif %}
  {% endfor %}

I then try to get the product data from the Shopify Product API, but I just receive a 404 error.

    var storeURL = "https://www.examplestore.com";
    jQuery.getJSON(storeURL + "/products/"+ recommendation_handle[0], function( product ){
      productTitle = product.title;
      console.log(productTitle);
    });

It looks to be that the url redirects to a unique checkout url. Is there a different way I can call the Product AJAX API within checkout.liquid?

One dropdown overwriting another’s value

I’m making a page with javascript react and formik and I have two dropdowns in one form, I got them to work but now that I’m using both of them, when I choose a value with one the other’s value resets. Don’t know how to word this better so I’ll add a gif of what happens:

Dropdown overwriting example

These are my drop down menus (both identical just taking values from a different object).

                  <Field
                    as="select"
                    className="custom-select d-block w-100"
                    name="fk_room"
                    required
                  >
                    <option></option>
                    {this.state.doctors.map((doctors) => (
                      <option value={doctors.surname} selected>
                        {" "}
                        {doctors.surname}
                      </option>
                    ))}
                  </Field>

I have a sneaking suspicion it’s likely to do with me setting the state twice

  componentDidMount() {
    userService.getAllRooms().then((result) => {
      this.setState({
        rooms: result.map(({ name }) => name),
      });
    });
    userService.getAllEmployees().then((result) => {
        this.setState({
          doctors: result.map(o => ({name: o.name, surname: o.surname, specialization: o.specialization})),
        });
      });
  }

even though with console.log it looks like I get the values correctly, I assume something funky is going on since every dropdown click calls the componentDidMount again (I think).
Has anyone dealt with a similar issue? Does it have to do with me setting the state twice or I need to somehow save the value from the dropdowns? (It worked fine with just 1 dropdown menu where I called the state once).
Sorry if this is complete novice territory I am very inexperienced in javascript and react.
P.S. the dropdowns are completely independent, all the guides I found online were about dependent dropdown menus but this is not the final result I want, they both should never change from the initial call to fill the objects.

XCODE: error opening input file ‘/Users/name/Desktop/test/appname/node_modules/react-native-compressor/ios/Video/Compressor-Bridging-Header.h’

I have a problem when I run my project in XCode.
I just installed the package react-native-compressor by following the installation instructions
And when I run my project in XCode, I have this problem:

<unknown>:0: error: error opening input file '/Users/name/Desktop/test/appname/node_modules/react-native-compressor/ios/Video/Compressor-Bridging-Header.h' (No such file or directory)

This file exists, and contain exactly what contains in this url: https://github.com/Shobbak/react-native-compressor/blob/master/ios/Video/VideoCompressor.h

Why can’t I understand programming and become a better developer

I have tried learning programming(self-taught). I just feel like giving up because I don’t understand many things. There way too much things to learn. I have tried learning some concept but everytime one is learning a certain concept another one pops up and up. I started learning coding in 2020 didn’t take it that serious. I told myself I’ll start afresh and take my time learning to code this year but I just feel discourage. Can’t even build anything reasonable or write any fancy code. I’m just tired and I want to know how you guys do it. I want to be an open source developer and I don’t even know where to start though I’m learning JavaScript but I have no predefined route. I have watched couple of YouTube videos but most times it feels overwhelming. I have also read couple of books but I can’t even boast of one thing. I love programming and any time I try leaving it something draws me back to it. Please guys expert in here, have you guys ever felt this way. How can I overcome this challenge and become a better developer to contribute to the world. Please I seriously need your advice I’m very down today because of this problem

Tried some many things expecting result but no result

Datetimepicker client side validation for start and end date

I have 2 datetimepickers that I’m using and I’m setting the default date on each of them when the page loads. One is the start time (#datetimepicker1), the other is the end time (#datetimepicker2). I have validation in place for when the user changes the values. It will validate that the end date is not less than the start date and the start date is not greater than the end date.

This works, however, it does not seem to register the default values, so the validation only works if you click into it and select a new datetime and then go to the other datetimepicker and select a value. Basically, it’s treating the default value as null within the validation. Any idea how to make the validation factor in the default values provided?

@using (Html.BeginForm("Graph", "Home", FormMethod.Post))
        {
            <div class="form-group">
                <div class="container">
                    <div class='col-lg-4 text-center' style="text-align:center">
                        <label class="control-label col-md-2" style="width:40%" for="datetimepicker1">From Date:</label>
                        @Html.TextBoxFor(m => m.datetimepicker1, new { @class = "input-group date" })

                    </div>
                    <div class='col-lg-4' style="text-align:center">
                        <label class="control-label col-md-2" style="width:40%" for="datetimepicker2">To Date:</label>
                        @Html.TextBoxFor(m => m.datetimepicker2, new { @class = "input-group date" })
                    </div>
                    <div class='col-lg-4' style="text-align:center">
                        <button type="submit" class="btn btn-primary">
                            <span class="glyphicon glyphicon-search" aria-hidden="true"></span>&nbsp;Search
                        </button>
                    </div>
                </div>
            </div>
        }

<link rel="stylesheet" href="~/Content/bootstrap-datetimepicker.min.css">
<script src="~/Scripts/bootstrap-datetimepicker.min.js"></script>

<script type="text/javascript">
    $(function () {
        $('#datetimepicker1').datetimepicker({
            defaultDate: "@DateTime.Now.ToString("MM/dd/yyyy") 12:00:00 AM"
        });
        $('#datetimepicker2').datetimepicker({
            defaultDate: "@DateTime.Now.ToString("MM/dd/yyyy") 11:59:59 PM"
        });
        $("#datetimepicker1").on("dp.change", function (e) {
            $('#datetimepicker2').data("DateTimePicker").minDate(e.date);
        });
        $("#datetimepicker2").on("dp.change", function (e) {
            $('#datetimepicker1').data("DateTimePicker").maxDate(e.date);
        });
    });
</script>

Why responsive mode shows incorrect size?

I have an 32″ 4k monitor.
That means it has a 3840x2160px resolution.
So in theory, an 1920x937px website should take about 1/4 of my screen.
But in reality, it takes about 2/3 of my screen, which si way bigger than it should be.

So why it taking so much space and why it doesn’t show the true size of the site?

What’s the problem and how can I solve it?
Image

Angular – I want to split a service into several services but share the same data

I have a service that is 1000 lines long, I would like to split it into several services but I need to share some data between these different services.

@Injectable()
export class ServiceParent {
  toto = new Toto(),
}

@Injectable()
export class ServiceChild extend ServiceParent {

  init() {
    this.toto.doSomething();
  }
}

@Component()
export class myComponent {

  ngOnInit() {
    console.log('this.ServiceChild.init()') // return undefined
  }
}

How to solve this problem ?

Thanks ^^

Express middleware not catching errors

With using express and typescript I’m trying to create an middleware to catch errors like eq. Sentry, code is below:

 const catchError = (
  error: Error,
  req: Request,
  _res: Response,
  next: any
) => {
   console.log("ERROR: ", error);
   //some logic

  next(error);
}

index.ts

  app.use(bodyParser.json({ limit }));
  app.use(morgan("[:date[iso]] :method :url :status :response-time ms"));

  app.use(express.json());
  app.use(cors({ credentials: true, origin: true }));

  app.use(bodyParser.urlencoded({ extended: false }));
//controllers

app.use(catchError as express.ErrorRequestHandler)

why my middleware is working only when i put:

} catch (error) { 
   next(error);
}

in function where is an error and not working without it? This middleware should also catching errors and exceptions without using next(error)

thanks for any help!