How to change transform.y of a Rectangle object with pinned to the bottom in Spark AR Studio?

I want to change the position of a Rectangle object (rectangle0) with pinning to the bottom and right. But I couldn’t change the y-position of it when it is pinned to the bottom. It works fine with it pinned to the top.

Also I couldn’t change the x-position when it is pinned to the right.
It works fine with it pinned to the left.

Any ideas would be appreciate.

rectangle with pinning to the bottom

var timer = Time.setInterval(update, 10);
function update() {
    if(scale < 1.0)
    {
        scale += 0.01;
    }
    rect.transform.scaleX = scale;
    rect.transform.scaleY = scale;
    rect.transform.x = rect_posx - rect_width * 0.5 * (1.0 - scale);
    rect.transform.y = rect_posy + rect_height * 0.5 * (1.0 - scale);
}

Open New window in JavaScript like CTRL + N (Not like new tab / CTRL + T)

I have one requirement where I have to open one URL in the new window & new tab.

I have implemented the below code to complete my requirement, but it will open URL in the new tab in the current browser window.

var url = 'https://www.google.com/';
const win = window.open(url, '_blank');
win.focus();

I also provided properties as the third parameter like the below code but after that i am not able to update the URL. Here I attach a screenshot for more understanding.

Current Output

Required Output

Filter option cannot be loaded into the payload in vuejs datatable

I’m trying to implement a filter for my employees vue component.

I’m displaying data in a datatable.

I have multiple filters and one of the filter is called, employee types.

<!--Employee Type  filter-->
                        <div class="w-6/12 pl-4 h-auto">
                            <cs-multiple-select
                                v-model="selectedEmployeeTypes"
                                :options="employeeType"
                                key-id="id"
                                label="name"
                                name="employee-type"
                                placeholder="Employee Type"
                            >
                            </cs-multiple-select>
                        </div>

following is my code inside the <script></script>

<script>
// Helper
import Helper from '@/Support/Helper.js';
import AddEmployeeModal
    from "@/components/dashboard/corporate/employee/project-employees/add-employee-modal";
import Datatable from "@/components/reusable/datatable/Datatable";
import CsConfirmationModal from "@/components/dashboard/reusable-modals/cs-confirmation-modal";
import HasToastrMessage from '@/Mixins/HasToastrMessage.js';
import Pagination from "@/Mixins/Pagination";
import AssignDepartment
    from "@/components/dashboard/corporate/project/employers-projects-detail-departments/assign-department";
import OpenOverlay from "@/components/overlay/open-overlay";
import InviteEmployees from "@/components/dashboard/corporate/employee/project-employees/invite-employees";
import CsButton from "@/components/reusable/cs-button";
import CsMultipleSelect from "@/components/reusable/dropdowns/cs-multiple-select";
import DatatableActionbarItem from "@/components/reusable/datatable/DatatableActionbarItem";

export default {
    components: {
        DatatableActionbarItem,
        CsMultipleSelect,
        CsButton,
        InviteEmployees,
        OpenOverlay,
        AssignDepartment,
        CsConfirmationModal,
        Datatable,
        AddEmployeeModal
    },

    props: ['companyUuid', 'projectId'],

    mixins: [HasToastrMessage, Pagination],

    data() {
        return {
            projectEmployees: [],
            originalEmployees: [],
            page: 1,
            perPage: 15,
            selectedDepartments: [],
            selectedEmployeeTypes:[],
            selectedCountries: [],
            selectedJobTitles: [],
            status: [],
            matrixStatus: [],
            searchText: null,
            jobTitles: [],
            departments: [],
            countries: [],
            isLoading: false,
            selectedUserId: null,
            showMatrixModal: false,
            selectedJobTitleId: null,
            selectedDepartmentId: null,
            selectedUserToShowMatrix: null,
        }
    },

    watch: {
        status() {
            this.$refs.datatable.refreshPagination()
        },

        matrixStatus() {
            this.$refs.datatable.refreshPagination()
        },

        selectedJobTitles() {
            this.$refs.datatable.refreshPagination()
        },

        selectedDepartments() {
            this.$refs.datatable.refreshPagination()
        },

        selectedCountries() {
            this.$refs.datatable.refreshPagination()
        },
        
        selectedEmployeeTypes(){
            this.$refs.datatable.refreshPagination()
        },
    },

    async mounted() {
        await this.loadProjectEmployees()
        this.originalEmployees = this.projectEmployees

        eventsHub.$on('filtering:done', () => {
            eventsHub.$emit('pagination:reset');
        });

        this.loadProjectSpecificJobTitles()
        this.loadDepartments();
        this.loadCountries();

        await this.loadProject();

        eventsHub.$on('overlay:isMounted:statusSummaryComponent', () => {
            eventsHub.$emit('overlay:open:statusSummaryComponent');
        });

        eventsHub.$on('overlay:close:statusSummaryComponent', () => {
            this.showMatrixModal = false
        });

    },

    computed: {
        HeaderArray() {
            return [
                {text: 'Employee', value: 'employee_detail'},
                {text: 'Job title', value: 'job_title'},
                {text: 'Department', value: 'department_name'},
                {text: 'Start date', value: 'start_date', filters: ['formatDate']},
                {text: 'End date', value: 'end_date', filters: ['formatDate']},
                {text: 'Nationality', value: 'country_flag', classList: 'text-center'},
                {text: 'Qualification status', value: 'status'},
                {text: 'Matrix status', value: 'matrix_status'},
            ];
        },

        noData() {
            return !(Helper.isset(this.originalEmployees) && this.originalEmployees.length > 0)
        },

        certificateStatusList() {
            return [
                {status: 'expire_soon', name: 'Expire Soon'},
                {status: 'expired', name: 'Expired'},
                {status: 'missing', name: 'Missing'},
            ]
        },

        matrixStatusList() {
            return [
                {status: 'complaint', name: 'compliant'},
                {status: 'non_complaint', name: 'non-compliant'},
            ]
        },

        employeeType() {
            return [
                {name: 'Employee', id: '0'},
                {name: 'Subcontractor', id: '1'},
            ]
        },

        isSelectedCountIsOne() {
            return this.$refs.datatable.selected.length === 1
        },

        userSuggestionApiURL() {
            return `json/companies/${this.companyUuid}/projects/${this.projectId}/suggested-users`;
        },

        project() {
            return this.$store.getters.getProject.project;
        },

        inviteModalTitle() {
            const title = this.project ? this.project.title : '';
            return `Invite employee(s) to ${title}`;
        },
        employeeCount() {
            return Helper.isset(this.projectEmployees.total) ? this.projectEmployees.total : 0;
        }
    },

    methods: {
        async loadProjectEmployees() {
            this.isLoading = true
            let payload = {};

            payload.companyUuid = this.companyUuid;
            payload.projectId = this.projectId;
            payload.certificate_status = this.status;
            payload.matrix_status = this.matrixStatus;
            payload.search_text = this.searchText;
            payload.page = this.page;
            payload.per_page = this.perPage;
            payload.job_titles = this.selectedJobTitles;
            payload.departments = this.selectedDepartments;
            payload.employee_type= this.selectedEmployeeTypes;
            payload.countries = this.selectedCountries;

            await this.$store.dispatch('loadProjectEmployees', payload)
                .then((data) => {
                    this.projectEmployees = data
                    this.isLoading = false
                }).catch(() => this.isLoading = false)
        },

        HandleChange(currentPage, perPage, searchTerm) {
            this.page = currentPage
            this.perPage = perPage
            this.searchText = searchTerm
            this.loadProjectEmployees()
        },

        handleRowClick(event, item) {
            let element = event.target;

            // Handle all exceptions here

            if (element.classList.contains('selectable--checkbox')) {
                return false;
            } // do nothing, the selectable handles the functionality

            if (element.classList.contains('status--summary--component')) {
                return false;
            } // do nothing, the selectable handles the functionality

            // The default action should be handled below.
            window.location.href = `/${Helper.getLocale()}/dashboard/companies/${this.companyUuid}/users/${item.unique_id}/certificates`;
        },

        isAllActive(item) {
            return !(
                item.expire_soon || item.expired
            )
        },

        loadProjectSpecificJobTitles() {
            let payload = {}
            payload.companyUuid = this.companyUuid
            payload.project_id = this.projectId

            this.$store.dispatch('loadProjectSpecificJobTitles', payload)
                .then((data) => {
                    this.jobTitles = data.projectSpecificJobTitles
                });
        },

        loadDepartments() {
            let payload = {}
            payload.companyUuid = this.companyUuid
            payload.projectId = this.projectId

            this.$store.dispatch('loadProjectDepartments', payload)
                .then((data) => {
                    this.departments = data
                }).catch(() => {
            });
        },

        loadCountries() {
            let payload = {}
            payload.companyUuid = this.companyUuid
            payload.projectId = this.projectId

            this.$store.dispatch('loadProjectUserCountries', payload)
                .then((data) => {
                    this.countries = data
                }).catch(() => {
            });
        },

        removeProjectEmployees() {
            axios
                .post(`/${Helper.getLocale()}/dashboard/json/companies/${this.companyUuid}/projects/${this.projectId}/users`, {
                    _method: 'delete', users: this.$refs.datatable.selected
                })
                .then(({data}) => {
                    if (data.success) {
                        this.showToastrSuccessMessage(data.success)
                    }
                    this.loadProjectEmployees()
                }).catch(() => {
                this.showToastrErrorMessage("User remove failed.")
            })
        },

        handleEmployeeAssignToDepartment(data) {
            this.loadProjectEmployees()
            this.showToastrSuccessMessage(data.success)
        },
        addEmployeeToProject(userIds) {
            return axios
                .post(`/${Helper.getLocale()}/dashboard/companies/${this.companyUuid}/projects/${this.projectId}/users`, {
                    user_ids: userIds,
                }).then(({data}) => {
                        if (Helper.isset(data.success)) {
                            this.showToastrSuccessMessage(data.success.message);
                            this.loadProjectEmployees()
                            this.$refs.addEmployeeModal.suggestedUsers = []
                            this.$refs.addEmployeeModal.selectedEmployees = []
                            this.$refs.addEmployeeModal.loadSuggestedUsers()
                        }
                    }
                ).catch(() => {
                    this.showToastrErrorMessage("Project employee is failed to add")
                })
        },
        loadProject() {
            let payload = {};

            payload.companyUuid = this.companyUuid;
            payload.projectId = this.projectId;

            this.$store.dispatch('loadProject', payload);
        },
        /**
         *
         * @param inviteEmails
         * @param loader
         * @param cb
         */
        handleInvitedEmployees(inviteEmails, loader, cb) {
            //Processing
            loader.toggle();

            const data = {
                company_uuid: this.companyUuid,
                project_id: this.projectId,
                employees_emails: inviteEmails,
            }
            this.$store.dispatch('inviteEmployeesToProject', data).then((data) => {
                cb(data);
            }).catch((error) => {
                this.errorMessages = collect([]);
                this.$nextTick(() => {
                    let responseErrors = collect(error.response.data.errors);
                    this.errorMessages = responseErrors.flatten();
                });
            }).finally(() => loader.toggle());
        },

        showAddEmployeeModal() {
            eventsHub.$emit('overlay:open:addEmployeeModal');
        },

        employeeDetailRoute(employee) {
            return `/${Helper.getLocale()}/dashboard/companies/${this.companyUuid}/employees/${employee.id}/certificates`;
        },

        showAssignEmployeeToDepartmentModal(item) {
            this.selectedUserId = [item.id]
            eventsHub.$emit('overlay:open:assignEmployeeToDepartment');
        },

        showMatrixStatusModal(item) {
            this.showMatrixModal = true
            this.selectedUserToShowMatrix = item.id
            this.selectedJobTitleId = item.job_title_id
            this.selectedDepartmentId = item.department_id
            eventsHub.$emit('overlay:open:statusSummaryComponent');
        }
    }
}
</script>

Now the issue is when I try to filter by employee type, it’s selected value (0 or 1) cannot be loaded into the payload.

This is my sample payload out put if I filtered by employee type,

page: 1
per_page: 15
search_text:

This is my payload if I filtered by filter like qualification status,

page: 1
per_page: 15
status[]: expired
search_text:  

This is my payload output if I filter by both qualification status and employee type,

page: 1
per_page: 15
status[]: expired
search_text: 

Expected result has to be,

page: 1
per_page: 15
status[]: expired
employee_type[]:1
search_text:

employee_type is not getting passed to the payload…

Where should I fix to send employee_type value to payload?

How to optimise if condition to check for particular array of json object in javaScript

I want code optimisation for if condition because I’ve to add more key value pair in if condition with &&. So I’ve array of object as follow just as example.

let arr = [{
    a:12,
    b:14,
    c:undefined,
    d:undefined,
    e:56,
    f:"file 1",
    g:"file 2",
    h:undefined
}]
for(let key of arr){
if(key.a!==undefined && key.b!==undefined && key.c!==undefined && key.d!==undefined && key.e!==undefined && key.f!==undefined && key.g!==undefined){
console.log("code works")
}else{
console.log("fails")}
}

So I’ve to add multiple key value to check for condition for undefined value. I’m trying to optimise please help or any suggestion. thanks you.

express req.body is returing an empty json object

I have read all the other posts and I have verified none of the solutions on any of them solve my problem. In insomnia I am setting the content type header to “application/json” and I am applying the express.json() middle ware before any of my routes. The MOST frustrating thing is the body isnt empty in my /register route however it always is inside my /login route. I have even tried putting the middle ware directly into the route with “router.get(‘/’, express.json(), async (req, res) => {” but it was to no avail. Also when I make the route a post I get a “cannot GET /register” with code 404 but not when its a “get” route. On my register route there is both a get and post route so I cant fathom why its any different with the login route ESPECIALLY since I made the register route by copy and pasting the login routes js file. Here is the code for the app

const express = require("express"),
  bodyParser = require('body-parser'),
  rta = require('./RTAuth.js'),
  mysql = require('mysql'),
  app = express(),
  port = 8080;

//app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
//app.use(bodyparser.urlencoded({ extended : true }));
//app.use(express.json({ limit: "200mb" }));

app.use(function(req,res, next) {
  res.locals.loginDB = mysql.createConnection({
    host: "localhost",
    user: "removed before posting",
    database: "removed before posting",
    password: "removed before posting"
  });
  res.locals.rta = rta;
  next();
});


//ImportRoutes
const loginRouter = require("./routes/login");
const registerRouter = require("./routes/register");

//Setup ImportRoutes
app.use("/AuthTest/login", loginRouter);
app.use("/AuthTest/register", registerRouter);


app.listen(port, () => {console.log("its alive!")});

I included commented out code I have tried. Now here is the problematic route up until the part it fails so ignore missing brackets after the return, the rest is irrelevant as its flow is cut off by the return statement.

const express = require("express");

//Setup express server routers
const router = express.Router();

//On get request
router.get('/', async (req, res) => {
  var test = req.body;
  res.status(200).send({
    success: false,
    message: "Test.",
    body: test,
    headers: req.headers
  });
  return;

How to shift a row to column inside a `div` if the container is using `display : flex`

I have least knowledge about css. The question might be silly for you.I am facing a problem to shifting div using display : flex
Let me explain :

This is my template :

*{
  margin: 0;
  padding: 0;
  text-decoration: none;
}
.container{
  width: 100%;
  display: flex;
}
.sidebar{
  background: grey;
  width: 280px;
  height: 100vh;
  color: white;
}
.header{
  background: orange;
  height: 80px;
  width: 100%;
  
}
.content{
  float: right;
}
<div class="container">
    <div class="sidebar">sidenav</div>
    <div class="header">header</div>
    <div class="content">content</div>
  </div>

The result I am getting is .content is placed at the last of the same row. I want it below the .header
What I want :
enter image description here

Array of different properties with the same id in an object – React JS

I am traversing an object that has an array of objects inside a property and I must access the id of an object to check which colors of my objects have the same id and make an array of the different colors of the same id to display it in the frontend as a concatenated. I hope you can help me.

Here I leave the image of the object on which I am getting the ids and colors

enter image description here

The dm_id are the ones I need to be able to make the color_bom_header array with the same dm_id

Here is the code that makes this happen but it doesn’t work right 🙁

this.state.stylesArray = this.props.location.state.stylesCombo.components.map((index, current) => {
        const col = this.state.stylesCombo.components && (this.state.stylesCombo.components[current].style_colors = index.color_bom_name)
        if(this.state.stylesCombo.components && this.state.stylesCombo.components[current].dm_id === index.dm_id){
          if(this.state.stylesCombo.components[current].dm_name === index.dm_name){
            this.state.colorStArray.push(col)
            this.state.cstarr = [...new Set(this.state.colorStArray)]
          }
        }else{
          this.state.stylesCombo.components && (this.state.stylesCombo.components[current].style_colors = current.color_bom_name)
        }
        this.state.stylesCombo.components && (this.state.stylesCombo.components[current].style_colors = this.state.cstarr)   
      })

i have also tried with this but im stuck

 this.state.stylesArray = this.props.location.state.stylesCombo.components.map((current, index) => {
        for (current.dm_id in this.props.location.state.stylesCombo && this.props.location.state.stylesCombo.components) {
          if(current.dm_id === index.dm_id){
            
          }else{
            
          }
        }
        this.state.stylesCombo.components && (this.state.stylesCombo.components[index].style_colors = this.state.colorStArray) 
      })

How can I debug to see my database in Mongoose

Please see my question in image. I opened Mongoose, type “nodemon app.js” but cannot run my app.js successfully (it said “SyntaxError: Invalid or unexpected token”). I am not sure whether it’s because I didn’t finish the code, but I’m supposed to see “Success” in my hyper but not the SyntaxError.
Thank you so much!
A newbie here~

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

mongoose.connect("mongodb://localhost:27017/todolistDB", {useNewUrlParser: true});

const itemsSchema = new mongoose.Schema({
  name: String
});
const Item = mongoose.model("Item", itemsSchema);

const item1 = new Item ({
  name: "Drink milk"
});

const item2 = new Item ({
  name: "Eat egg"
});

const defaultItems = [item1, item2];
Item.insertMany(defaultItems, function(err) {
  if (err){
    console.log(err);
  } else {
    console.log("Success");
  }
});

app.get("/", function(req, res) {


  res.render("list", {listTitle: "Today", newListItems: defaultItems});

});

app.post("/", function(req, res){

  const item = req.body.newItem;

  if (req.body.list === "Work") {
    workItems.push(item);
    res.redirect("/work");
  } else {
    items.push(item);
    res.redirect("/");
  }
});


app.listen(3000, function() {
  console.log("Server started on port 3000");
});

My Question

BX Slider timing and trigger issues

I’m currently using bx slider for 4 images on a carousel and it has a timer but for some reason its independent of when a user clicks on another of the image slides tabs with respect to the timer restarting at 0.

Examples:
Each slide has a slide time of 5 seconds but if you clicked on th tabs to slide after 2-3 seconds it will only stay on that new slide for the remaining 2 seconds to switch again.

Build a REST API using Node JS

I followed this video and here is the Github Basically, this video used a mock database (in-memory objects), which is not very practical.

I wanted to change the logic of getUsers() in a way that when I hit the endpoint (localhost:5000/users), it will return the user information from the Mysql database.

p.s. I am not sure if this is the correct way of using API, but this is the code I revised:

This is index.js file, no change:

import express from 'express';
import bodyParser from 'body-parser';
import usersRoutes from './routes/users.js';

const app = express(); 
const PORT = 5000;
app.use(bodyParser.json());

app.use('/users', usersRoutes);

app.get('/', (req, res) => {
    res.send('Hello from HomePage!');
});

This is users.js in routes folder, no change:

import express from 'express';
import { getUsers } from '../controllers/users.js';

const router = express.Router();
router.get('/', getUsers);
export default router;

This is users.js in controllers folder, where I want to make connections to MySQL:

import mysql from 'mysql';

const connection = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "root",
    connectionLimit: 10
})

const users = connection.query('SELECT * FROM SOME_TABLE', function (error, results, fields) {
    if (error)
        throw error;

    return results;
});

export const getUsers = (req, res) => {
    res.send(users);
}

So it can connect to MySQL, but the return values were not what I expected, and if I console.log(users), it gives me the following messages (kind of long, so I truncated it):

<ref *1> Query {
  _events: [Object: null prototype] {
    error: [Function (anonymous)],   
    packet: [Function (anonymous)],
    timeout: [Function (anonymous)],
    end: [Function (anonymous)]
  },
  _eventsCount: 4,
  _maxListeners: undefined,
  _callback: [Function (anonymous)],
  _callSite: Error
      at Protocol._enqueue (C:UsersstanlVS Code JavaScript Projectsnode_express_rest_api_1node_modulesmysqllibprotocolProtocol.js:144:48)    
      at Connection.query (C:UsersstanlVS Code JavaScript Projectsnode_express_rest_api_1node_modulesmysqllibConnection.js:198:25)
      at file:///C:/Users/stanl/VS%20Code%20JavaScript%20Projects/node_express_rest_api_1/database.js:23:26
      at ModuleJob.run (node:internal/modules/esm/module_job:185:25)
      at async Promise.all (index 0)

And it gives me this (truncated) error when hitting the endpoint:

TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Query'
    |     property '_timer' -> object with constructor 'Timer'
    --- property '_object' closes the circle
    at JSON.stringify (<anonymous>)

I have two questions:

(1) Is this a preferred way to build/use API?

(2) The SQL in connection.query(‘SELECT * FROM SOME_TABLE’) is fixed, is there a way I can change it dynamically when hitting the endpoint? Basically I want to supply complex SQLs from the frontend, and pass this SQL to the API I tried to build now, then get results back.

Thank you.

var hoisting Question in javascript and it’s output

I’m just wondering why is it that the output for the 3rd console.log is 2?
I know that var statements are hoisted (without their value initialization) to the top of the global or function scope it belongs to, even when it’s inside a with or catch block. I’m still currently studying javascript at the moment and no one can explain to me properly, since I was expecting that the value of the last 2 console.log is undefined. Why is it that the 2nd console.log is undefined and the last console.log output is 2? Why the last one is able to access the value of y inside the catch block?

(function () {
    try {
        throw new Error();
    } catch (x) {
        var x = 1, y = 2;
        console.log(x);
    }
    console.log(x);
    console.log(y);
})();