Javascript code generation : Self $ref attributes type not adding to import section which leads to “ReferenceError: XXXXX is not defined”

Swagger.yaml:

openapi: 3.0.1
info:
  title: Test API
  version: "1.0"
servers:
  - url: http://localhost:9005/v1
  - url: https://localhost:9005/v1
security:
  - OAuth2: []
components:
  schemas:
    Portfolio:
      allOf:
        - $ref: '#/components/schemas/DlResource'
        - type: object
          properties:
            name:
              type: string
            description:
              type: string
            isArchived:
              type: boolean
            baselinePortfolioPlanUser:
              $ref: '#/components/schemas/PortfolioPlanUser'
            fields:
              $ref: '#/components/schemas/Fields'
            projects:
              $ref: '#/components/schemas/Projects'
            portfolioPlans:
              $ref: '#/components/schemas/PortfolioPlans'
            portfolioPlanUsers:
              $ref: '#/components/schemas/PortfolioPlanUsers'
            attributes:
              $ref: '#/components/schemas/Attributes'
            isCombined:
              type: boolean
            userRegistrationToken:
              type: string
              description: user registration token string
            subPortfolios:
              $ref: '#/components/schemas/Portfolio'
            combinedPortfolios:
              $ref: '#/components/schemas/Portfolio'
            resourcePools:
              $ref: '#/components/schemas/ResourcePools'
            totalBudget:
              type: number
              format: double
              default: 0.0
            newNotificationsCount:
              type: integer
            customNames:
              $ref: '#/components/schemas/CustomNames'

Generated code:

(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ApiClient', 'model/Attributes', 'model/CustomNames', 'model/DlResource', 'model/Fields', 'model/PortfolioPlanUser', 'model/PortfolioPlanUsers', 'model/PortfolioPlans', 'model/Projects', 'model/ResourcePools'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'), require('./Attributes'), require('./CustomNames'), require('./DlResource'), require('./Fields'), require('./PortfolioPlanUser'), require('./PortfolioPlanUsers'), require('./PortfolioPlans'), require('./Projects'), require('./ResourcePools'));
} else {
// Browser globals (root is window)
if (!root.TestApi) {
root.TestApi = {};
}
root.TestApi.Portfolio = factory(root.TestApi.ApiClient, root.TestApi.Attributes, root.TestApi.CustomNames, root.TestApi.DlResource, root.TestApi.Fields, root.TestApi.PortfolioPlanUser, root.TestApi.PortfolioPlanUsers, root.TestApi.PortfolioPlans, root.TestApi.Projects, root.TestApi.ResourcePools);
}
}(this, function(ApiClient, Attributes, CustomNames, DlResource, Fields, PortfolioPlanUser, PortfolioPlanUsers, PortfolioPlans, Projects, ResourcePools) {
'use strict';

subPortfolio and combinedPortfolio has Portfolio type in Portfolio definition in YAML file. I have tried to generate the code with latest swagger-codegen-cli-3.0.46.jar, Portfolio type should be in import section but not added. Why Portfolio type not adding to module.exports, define and root.xxxx.api section.

Tested Java code and code generated as expected. Is self $ref not supported for Javascript ?

Expected code:

(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ApiClient', 'model/Attributes', 'model/Portfolio', 'model/CustomNames', 'model/DlResource', 'model/Fields', 'model/PortfolioPlanUser', 'model/PortfolioPlanUsers', 'model/PortfolioPlans', 'model/Projects', 'model/ResourcePools'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'), require('./Portfolio'), require('./Attributes'), require('./CustomNames'), require('./DlResource'), require('./Fields'), require('./PortfolioPlanUser'), require('./PortfolioPlanUsers'), require('./PortfolioPlans'), require('./Projects'), require('./ResourcePools'));
} else {
// Browser globals (root is window)
if (!root.TestApi) {
root.TestApi = {};
}
root.TestApi.Portfolio = factory(root.TestApi.ApiClient, root.TestApi.Portfolio, root.TestApi.Attributes, root.TestApi.CustomNames, root.TestApi.DlResource, root.TestApi.Fields, root.TestApi.PortfolioPlanUser, root.TestApi.PortfolioPlanUsers, root.TestApi.PortfolioPlans, root.TestApi.Projects, root.TestApi.ResourcePools);
}
}(this, function(ApiClient, Attributes, CustomNames, DlResource, Fields, Portfolio, PortfolioPlanUser, PortfolioPlanUsers, PortfolioPlans, Projects, ResourcePools) {
'use strict';

How to edit modal hide in vuejs

I have a vuejs component that displays a modal dialog box with a small form inside. I want to hide the Modal from where I send the api. I want it to update the data in the table. I’ve tried many ways. But I don’t know what to do.

enter image description here

        Swal.fire({
          title: response.data.alert,
          text: response.data.text,
          icon: response.data.type,
          showConfirmButton: false,
          timer: 2000,
        }).then(async () => {
          if (response.data.type == 'success') {
            try {
              const reloadtable = await this.retable();
              this.DataShow = reloadtable.data;
              $('#edit').modal('hide')
              this.$emit('save')
            } catch (error) {
              console.error(error);
            }
          } else {
            window.location.reload();
          }
        });

Cannot add property 0, the object is not extensible in react.js

When I try to select a checkbox, it shows the error ‘Cannot add property 0, the object is not extensible,’ and I’m unable to add items properly. Can someone please help me with this?

  const [formData, setFormData] = useState<RoleFormData>({
    name: "",
    permissions: [],
  });

  useEffect(() => {
    if (addRole) {
      setFormData({
        name: addRole.name,
        permissions: addRole.permissions,
      });
    }
  }, []);

handling the checkbox

  const handleCheckboxChange = (
    permissionId: number,
    section: string,
    checkedValues: CheckboxValueType[]
  ) => {
    const updatedFormData = { ...formData };

    const permission = updatedFormData.permissions.find(
      per => per.permissionId === permissionId && per.section === section
    );

    if (permission) {
      permission.name =
        checkedValues.length > 0 ? String(checkedValues[0]) : "";
    } else {
      updatedFormData.permissions.push({
        permissionId,
        section,
        name: checkedValues.length > 0 ? String(checkedValues[0]) : "",
      });
    }

    setFormData(updatedFormData);
  };

rendering the checkbox dynamically and trying to update on form data

        {Object.keys(permissionList).map(sectionKey => (
          <Collapsible
            title={permissionList[sectionKey][0]?.section}
            isFirst={false}
            key={sectionKey}
          >
            {permissionList[sectionKey]?.map((item, index) => (
              <Checkbox.Group
                options={[
                  {
                    label: item.name.toLowerCase(),
                    value: item.name.toLowerCase(),
                  },
                ]}
                key={index}
                value={formData.permissions
                  .filter(
                    per =>
                      per.section.toLowerCase() === item.section.toLowerCase()
                  )
                  .flatMap(per => per.name.toLowerCase())}
                onChange={checkedValues =>
                  handleCheckboxChange(
                    item.permissionId,
                    item.section.toLowerCase(),
                    checkedValues
                  )
                }
              />
            ))}
          </Collapsible>

This is initial State in redux

const initialState: IRoles = {
  rolesList: [],
  permissionList: [],
  permissionsBySection: {} as PermissionsBySection,
  addRole: {
    roleId: 0,
    name: "",
    permissions: [],
  },
  error: null,
  loading: false,
};

This is Reducer

  reducers: {
    resetRolesItem: () => initialState,
    // updateAddCoupon: (state, action: PayloadAction<UpdateAddCoupon>) => ({
    //   ...state,
    //   addCoupon: {
    //     ...state.addCoupon,
    //     ...action.payload,
    //   },
    // }),
    updateAddRoles: (state, action: PayloadAction<UpdateAddRole>) => ({
      ...state,
      addRole: {
        ...state.addRole,
        ...action.payload,
      },
    }),
  },

ERROR
Cannot add property 0, object is not extensible
TypeError: Cannot add property 0, object is not extensible
at Array.push ()
at handleCheckboxChange (http://localhost:5173/src_pages_authorized_role_rolesDetail_index_tsx.d2f40c44ee046000e94a.hot-update.js:97:35)
at onChange (http://localhost:5173/src_pages_authorized_role_rolesDetail_index_tsx.d2f40c44ee046000e94a.hot-update.js:188:24)
at Object.toggleOption (http://localhost:5173/static/js/bundle.js:22699:57)
at InternalCheckbox.checkboxProps.onChange (http://localhost:5173/static/js/bundle.js:22561:23)
at handleChange (http://localhost:5173/static/js/bundle.js:59282:57)
at HTMLUnknownElement.callCallback (http://localhost:5173/static/js/bundle.js:88407:18)
at Object.invokeGuardedCallbackDev (http://localhost:5173/static/js/bundle.js:88451:20)
at invokeGuardedCallback (http://localhost:5173/static/js/bundle.js:88508:35)
at invokeGuardedCallbackAndCatchFirstError (http://localhost:5173/static/js/bundle.js:88522:29)

Using method name as a string for array accessor [closed]

I am trying to use the string ‘pop’ as an array accessor in JS. But it is referencing the function pop()

If I try to push a value into it I will get an error.

let myKey = 'pop';
myArray[myKey].push('myValue'); 
// throws an error `TypeError: myArray.pop.push is not a function`

I have tried calling myKey.toString() but it results in the same error. Is there a way to use ‘pop’ as a string accessor, without referencing the function pop().

how to calculate how much time has passed when I registered such an item in the database

const getHoursOrMinutesAgo = (createdAtNanos) => {
    console.log(createdAtNanos)
    const now = moment();
    const createdAtMilliseconds = createdAtNanos / 1000000; 
    const createdAt = moment(createdAtMilliseconds);
        
    const duration = moment.duration(now.diff(createdAt));
        
    const hoursAgo = duration.hours();
    const minutesAgo = duration.minutes();
    const secondsAgo = duration.seconds();
    
    if (hoursAgo > 0) {
       return `${hoursAgo} hora(s) atrás`;
    } else if (minutesAgo > 0) {
       return `${minutesAgo} minuto(s) atrás`;
    } else {
       return `${secondsAgo} segundo(s) atrás`;
    }
};

I don’t know how to explain, please help me with that, i want just calculate how much time passed with a nanoseconds parameter

Api routes google maps

good evening, I have an issue when using the routes API to calculate tolls for a route. I initially used the places API for autocomplete, but I’m unsure how to implement the routes API to achieve the toll calculation.

I found a way to do it, storing in a variable called ‘toolcost’ the total toll fees, but I couldn’t make it work; it’s the part of the comment where it says ‘here’

var request = {
        origin: document.getElementById("from").value,
        destination: document.getElementById("to").value,
        travelMode: google.maps.TravelMode.DRIVING, //WALKING, BYCYCLING, TRANSIT
        unitSystem: google.maps.UnitSystem.IMPERIAL
    }

    //pass the request to the route method
    directionsService.route(request, function (result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            //HEREEEEEE
            let tollCost = 0;
            for (const step of request.steps) {
                if (step.toll) {
                    tollCost += step.toll.amount;
                }
            }

I have this malware on my website. Any tips to remove it? https://sweetwinsprizes.info/?u=mr1kd0x&o=f5pp7z3&t=p2&cid=ZG1zbmQ7ZTZiNzVlMmY5Zg==

Site Issue Detected
http://quancheyeent.com/ (More Details)

Known malware: warning.html_anomaly?11

window.location.replace(“https://sweetwinsprizes.info/?u=mr1kd0x&o=f5pp7z3&t=p2&cid=ZG1zbmQ7ZTZiNzVlMmY5Zg==”);

Redirects to https://quancheyeent.com/

Can not figure out how to remove it.

Do not know where to look as Securi says the line is located in the quancheyeent.com

In the Javascript Debug Console, when I set var someVariable = Object.keys(objectWithKeys)[0], the keys and object get set to a string

Please see the attached screenshots showing this reproducible behavior.

When I try to set most variables in the Javascript Debug Console, I am able to do so successfully, demonstrated when I set x in the screenshot. However, when I try to do this while referencing Object.keys(), strange behavior occurs and the variable name is evaluated as a String, and the Object’s keys are set to this String which happens to be the variable name.

Is there an explanation for this?

Showing issue when setting to index under keys array

Showing issue with Object.keys()

why does it give me option 2 when option 1 is selected? [closed]

I am coding a website that randomly selects one of three options and then puts a border around the input box that is selected. I have an alert so that I can see which one is actually selected and when it randomly selects one, it changes to two. I want it to select each of the three options evenly.

function onButtonClick() {
  let num = Math.random();

  if (num < 0.34) {
    alert('Option 1');
    document.getElementById(`one`).style.border = "dashed";
    document.getElementById(`two`).style.border = "none";
    document.getElementById(`three`).style.border = "none";
  }

  if (num <= 0.67) {
    alert('Option 2');
    document.getElementById(`one`).style.border = "none";
    document.getElementById(`two`).style.border = "dashed";
    document.getElementById(`three`).style.border = "none";
  }

  else {
    alert('Option 3');
    document.getElementById(`one`).style.border = "none";
    document.getElementById(`two`).style.border = "none";
    document.getElementById(`three`).style.border = "dashed";
  }
}

button.addEventListener('click', onButtonClick);

Why does metamask default to BNB when a custom purchase tokens has been defined?

I’m currently creating a presale dapp for fun on the BSC testnet, and all is going well. Aside from the fact that when I initiate the “buyButton”, metamask seems to default to purchasing with BNB. I’ve attempted to set a custom token as the purchase currency to buy the presale token with, and this is defined in the presale contract itself. I’m not available to send my scripts at the moment but I was wondering if there’s any general guidance or similar experience that you could share, and what could be potentially causing this?

thanks!

tried different variations of my contract and my JS code, but I can only seem to get the BNB default or no purchase currency at all (metamask still opens, but no currency shows)

Why the filter method is not working when filtering an array of objects requested from an API (Javascript)

I have been practicing some coding after some break. I’m trying to filter an array of objects from an api and creating a function the which will return me every word from the title of the fetch I’m making the request.

However, when I want to do the filter it shows that filter method is not recognized, and I don’t know if its affected if you are filtering an array that you called from an api.

This is the code.

function titles(word){
    let sentence
    let array = []
    let api = 'https://jsonplaceholder.typicode.com/posts'
    let data = fetch(api)
    let response = data.then(res => res.json()).then(data => data.map((e) => { e.title}))
    array = array.concat(response)
    sentence = Promise.all(array.flat()).then(results => results.flat())
  const people = sentence.filter(e => e.title.includes(word))
    return people
}

However, returns an error message (see image)

But when I do the same on an array of objects the filter works well.

I appreciate any help, feedback and code improvement. Thanks in advance!

error message

How to store user settings for game in MySql?

So I’m working on a website where users can create their own bullet hell games. Users make patterns by placing enemies (or emitters) on the screen and using form fields to control the properties of those enemies. There are also fields for creating the bullet objects that these enemies shoot.

I want to allow users to save their patterns so that they can edit them later, or allow other users to play the bullet hell they made. But I’m having trouble thinking of a good database schema for this.

I currently have 3 separate tables for patterns, emitters, and bullets. A pattern can have many emitters, so there’s a one to many relationship there. Emitters can fire many bullets, so there’s another one to many relationship there. So when looking up a pattern, you have to look up all of its emitters, and then look up all of the bullets for each emitter. This seems slightly ridiculous and I’m not sure if it’s a good way to set up my database.

I was going to try converting all of a pattern’s emitter objects into a string. And then convert all of the emitter bullets into strings as well and have a unique separator for them. Example below.

const bullets = [
  {
  emitterId: 1,
  minSpeed: -99999,
  maxSpeed: 99999,
  speed: 90,
  accel: 0,
},
  {
  emitterId = 2,
  minSpeed: 100,
  maxSpeed: 200,
  speed: 150,
  accel: 0.09,
},
]

const dbBllts = bullets.map(bllt => Object.entries(bllt)).join("|")

And then I insert this string in the bullets field for tablets and do the same for the emitters. However, I was told that this was a really, really bad idea. My questions are:

  1. Why is this a bad idea.
  2. What would be a better way to store user settings for the game that doesn’t involve this weird one to many to many relationship.

What event is triggered when input values are populated from browser cache (when user clicks the back button)

Background

I am working on an e-commerce website, where users can create a product (list a new product)

When user wants to create a new product, they open a new form, fill the product details and click on submit.

After submitting the form, they can click the back button… all the values that they had previously filled, gets automatically filled from browser cache…

Now if the user submit this form, the e-commerce website creates a new product (instead of editing the existing one) because the form values populated from browser cache don’t have an id (id is generated on the server side, after submitting the form)

I want to prevent this by clearing the form, if the user comes to the form by clicking the back button.

Here is what I have tried:

function clearFormIfAlreadySubmitted() {
    let isNewProduct = $('#productId').val() == 0;
    if (isNewProduct) {
        let submitStatus = $('#submitStatusId').val();
        if (submitStatus === "submitted") {
            // if product does not have an id and the form has already been submitted 
            // reset the form
            $("form").trigger('reset');
        }
    }
}

// set the submitStatusId (hidden input)
function setFormSubmitStatus() {
    if ($("form").valid()) {
        $('#submitStatusId').val("submitted");
    }
}

$(document).ready(function () {
    $("form").on('submit', setFormSubmitStatus);
    clearFormIfAlreadySubmitted();
});

so I have added a hidden input submitStatusId and set its value when submitting the form.

If product does not have any id and submitStatusId == 'submitted' I want to reset the form.

The problem

The problem is the value of my input submitStatusId is not available at the time document.ready event is triggered… it seems like the input value gets set from the browser cache after document ready… I am not sure which event handler I should use to check the value of my input after it’s set?

If I change my code to the following then it works as expected:

$(document).ready(function () {
    $("form").on('submit', setFormSubmitStatus);
    setTimeout(() => {
        clearFormIfAlreadySubmitted();
    }, 100);
});

But I am wondering if there is an event that I can listed to instead of randomly waiting for 100 ms?

Is it possible to bind a HTML Canvas to an ffmpeg JavaScript port to get a video file as output without a server?

First of all, I’ve found this repository which has a ffmpeg JavaScript implementation:
https://github.com/ffmpegwasm/ffmpeg.wasm

I’m curious if I can somehow bind my canvas output and pass some frametimes to get a video output. (for example, visualize a physics object)

So far, I’ve set up a basic physics simulator in JS. I have a bunch of squares being rendered based on their x and y coordinates.

class PhysicsObject {
  // ...
  render(canvas, ctx) {
    ctx.fillStyle = this.color;
    ctx.fillRect(this.x - this.w / 2, this.y - this.h / 2, this.w, this.h);
  }
  // ...
}

let timer = performance.now();
// ...

function draw() {
  // ...
  let now = performance.now();
  dt = (now - timer) / 1000;
  timer = now;
  // ...

  for (let object of physicsObjects) {
    // ...
    object.update(dt);
    object.render(canvas, ctx);
    // ...
  }
  requestAnimationFrame(draw);
}

I now need a way to link my canvas output to the ffmpeg and some other parameters but I have no idea where to even start.

If there is a way to bind the canvas output to the ffmpeg port, I’d like to delve deeper into the documentation of this ffmpegwasm thing.