Not sending the right page

I am creating a website and to do so, the Admin Account has access to create posts. While doing this, I have come across the error of when running the postLaunchCourse function sends me to 403 (No access) page and wont post it.

The code:

exports.getLaunchCourse = (req, res) => {
  res.render("admin/launch-course", {
    isAdmin: req.user && req.user.role === "admin" ? true : false,
    isAutherized: req.user ? true : false,
    username: req.user ? req.user.username : null,
  });
};

// Type : POST
// Access : Private (Only For Admin)
// @Desc : Upload Course To Server
exports.postLaunchCourse = (req, res, next) => {
  const title = req.body.title;
  const description = req.body.description;
  const price = req.body.price;
  const thumbnail = req.file ? req.file.path : null;
  const facultyAccess = req.body.facultyAccess.split(",");
  const tags = req.body.tags.split(",");

  cloudinary.v2.uploader.upload(thumbnail, (error, result) => {
    deleteFileHandler.deleteFileHandler(thumbnail);
    const course = new Course({
      creator: req.user,
      title: title,
      description: description,
      price: price,
      thumbnail: result.url,
      tags: tags,
      facultyAccess: facultyAccess,
    });

    course
      .save()
      .then((course) => {
        console.log("Course Created Successfully");
        res.redirect("/course/" + course._id);
      })
      .catch((err) => {
        const error = new Error("Wasn't able to Create-Course");

        next(error);
      });
  });
};

I’ve tried changing the code and looking at other fixes but it wont work. I am expecting the post function to run properly and for it to post onto Remote Courses section.

Can I add a vanilla JS canvas as a react background?

I created a background canvas in Vanilla JS with just a bunch of dots that connect and 3 functions. Is there a way for me to just transfer this vanilla js file over and insert it into my React page?

I tried moving the code over into react but I am having trouble turing all this data into states and passing it between multiple functions.

Is there a way to reset lodash’s once() so the next time it is called as though the first time?

For context, I’m writing an automated test for a function that takes a while to calculate its result. Therefore, I want to make sure the result is cached. Lodash’s once function does what I need, but if I want to unit test my function, once doesn’t reset between tests so it introduces test pollution.

Is there a way I can “reset” once between tests so at the beginning of every test it acts like it’s being called the first time? This is once‘s source code:

  function once(func) {
    return before(2, func);
  }

  function before(n, func) {
    var result;
    if (typeof func != 'function') {
      throw new TypeError(FUNC_ERROR_TEXT);
    }
    n = toInteger(n);
    return function() {
      if (--n > 0) {
        result = func.apply(this, arguments);
      }
      if (n <= 1) {
        func = undefined;
      }
      return result;
    };
  }

FWIW, it’s easy for me to solve this problem by avoiding once and writing my own one-off cache. Alternatively, I could monkey patch/stub once or before. But I’m asking this for academic purposes: if there is another way to reset once, I think it’ll teach me a new technique I didn’t know existed–a technique that’ll be useful for other things down the line.

TypeError: r is not a function in Production Build

I am currently trying to use this VueCarousel package for my web app, but I am getting this error in my production app:

TypeError: r is not a function
    at t (vue.common.prod.js:11:68600)
    at s.__patch__ (vue.common.prod.js:11:70431)
    at t._update (vue.common.prod.js:11:43128)
    at s.o (vue.common.prod.js:11:77577)
    at In.get (vue.common.prod.js:11:26615)
    at In.run (vue.common.prod.js:11:27259)
    at Ge (vue.common.prod.js:11:17853)
    at Array.<anonymous> (vue.common.prod.js:11:21774)
    at fn (vue.common.prod.js:11:21202)

I am certain that there is an issue with how I have imported the package, but so far I have not been able to find the cause.

This is how I am importing the carousel in my main app.js file:

import Vue from "vue";
import { Carousel, Slide } from "vue-carousel";
import CustomCarousel from "./components/employees/CustomCarousel.vue";

var app = new Vue({
    el: "#app",
    components: {
        Carousel,
        Slide,
        CustomCarousel,
    },
});

I am also using the carousel package in a custom carousel Vue component, and it is being imported into the component like so:

<script>
import { Carousel, Slide } from "vue-carousel";

export default {
    name: "CustomCarousel",
    components: {
        Carousel,
        Slide,
    },
};
</script>

In my code, I was also getting this warning:
Could not find a declaration file for module 'vue-carousel'.

I was assuming that this was causing my carousel to not show up, so I created a *.d.ts file that declared this module.

I have also removed the importing of the carousel from the specific Vue components to see if that would solve my issue, but that did not seem to work either.

Cannot read properties of undefined (method as parameter)

I did this implementation before but it doesn’t work for me in this application.

The implementation was changed but it still doesn’t work. It gives the following error:

TypeError: cannot read properties of undefined (reading handleEdit)

const columnHelper = createColumnHelper();

const IMarcas = ({
    handleEdit = () => null,
    handleDetails = () => null,
    handleDisable = () => null
}) => {
    return [
        columnHelper.accessor('idMarca', {
            header: () => 'Id',
            cell: info => info.getValue()
        }),
        columnHelper.accessor('acccions', {
            header: () => 'Acciones',
            cell: ({ row }) => (
                <div style={{ display: "flex", flexDirection: "row" }}>
                    <Tooltip onClick={()=>handleEdit({row})} title="Editar"><IconButton><EditIcon /></IconButton></Tooltip>
                    <Tooltip onClick={()=>handleDetails({row})} title="Detalle"><IconButton><DisplaySettingsIcon /></IconButton></Tooltip>
                    <Tooltip onClick={()=>handleDisable({row})} title="Deshabilitar"><IconButton><DoNotDisturbOffIcon /></IconButton></Tooltip>
                </div>
            )
        })
    ]
}

react version and dom is 17.0.2
“@tanstack/react-table”: “^8.9.1”,
enter image description here

Transition issue in a JavaScript animation

I have an animation problem that I can’t seem to solve. Here is the purpose of the animation:

  1. The card is initially placed in the bottom-right corner of its wrapper, with opacity set to 0.
  2. Then, the card moves to the bottom-left corner of its wrapper, and the opacity transitions to 1 over a duration of one second.
  3. Next, the card moves upwards within the wrapper by a number of pixels equal to its size, with a one-second transition.
  4. Step 3 is repeated, one movement at a time, until the card exceeds the height of the wrapper. During its last movement, the card returns to an opacity of 0.

So far this is the code:

const wrapper = document.querySelector('.wrapper');
const card = document.querySelector('.card');
card.style.bottom = '0';
card.style.right = '0';
card.style.opacity = '0';
requestAnimationFrame(() => {

  card.style.transition = '1s';
  card.style.bottom = '0';
  card.style.right = 'auto';
  card.style.left = '0';
  card.style.opacity = '1';
  const cardHeight = card.offsetHeight;
  const wrapperHeight = wrapper.offsetHeight;

  function moveCard() {
    if (parseInt(card.style.bottom) < wrapperHeight) {
      card.style.transition = '1s';
      card.style.bottom = parseInt(card.style.bottom) + cardHeight + 'px';
      card.style.opacity = '1';
      setTimeout(moveCard, 1000);
    } else if (parseInt(card.style.bottom) >= wrapperHeight && card.style.opacity !== '0') {
      // Dernier mouvement : Repasser à une opacité de 0
      card.style.transition = '1s';
      card.style.opacity = '0';
      setTimeout(moveCard, 1000);
    }
  }
  setTimeout(moveCard, 1000);
});
.wrapper{
  display:flex;
  height : 200px;
  width : 300px;
  background: grey;
  position: relative;
}
.card{
  position: absolute;
  width:50px;
  height: 50px;
  background: red;
}
<div class= "wrapper">
  <div class="card">
  
</div>
</div>

Why doesn’t the transition on the first translate work?

Clearing input fields of a child component when the select option is changed

My problem basically is that I have a form and within that form.

I have a dropdown <select /> and the form dynamically changes when the type is switched

          <select
            name="Type_Switcher"
            id="type_switch"
            onChange={handleOptionChange}
            
            
          >
            <option value={options[0]}>{options[0]}</option>
            <option value={options[1]}>{options[1]}</option>
            <option value={options[2]}>{options[2]}</option>
          </select>
        </label>
        <div id="product_specification">
            {selectedOption === options[0] && <DVDForm optionChanged={optionChanged} register={register} />}
            {selectedOption === options[1] && <FurnitureForm optionChanged={optionChanged} register={register} />}
            {selectedOption === options[2] && <BookForm  optionChanged={optionChanged}  register={register}/>}

        </div>

Here’s the function that triggers when the option changes

 function clearInput() {
    // Replace 'your-element-id' with the ID of your target HTML element
    var targetElement = $("#product_form_field");
    // Select all input-type child elements of the target element and clear their values
    console.log(targetElement)
    targetElement.find('input').val("");
  }
//   console.log(value)
  const handleOptionChange = (event) => {
    clearInput() // first clear off the input fields 
    setselectedOption(event.target.value);
    setOptionChanged(true);
    onChange(event);
  };

And here’s an example of a child component for one of the options :

const DVDForm = ({ onChange, value, register, optionChanged }) => {
    const inputRef = useRef(null);

    useEffect(() => {
      if (optionChanged && inputRef.current) {
        inputRef.current.value = '';
      }
    }, [optionChanged]);
  return (
    <label htmlFor='size' className='product_form_field' id='product_form_field'>
      <p>Size (MB)</p>
      <input
        ref={inputRef}
        type="text"
        name="size"
        id="size"
        placeholder="Enter size of the product"
        // onChange={onChange}
        // value={value.type?.size}
        {...register("type.size", { required: true})}
        

      />
      <span className='product_description'>Please provide size in MB</span>
    </label>

Please Note: I’m using react-hook-form so I’m not able to set the field with the traditional way of linking value and onChange props to the input field to manipulate it

I have tried solutions including ( JQuery find('input').val(''), and form.reset() ) as long with many other solutions that didn’t work

Build electron js application

I have problems with build electron application.
After building ipcRenderer doesn’t send information to ipcMain process.

I have structure a project:

  • main-process/
    • main.js – entry in application
    • main-method.js
    • thread/. – worker’s threads
  • render-process/
    • routers/
    • service/
    • views/
  • package.json

package.json

{
  "name": "XXXXX",
  "version": "1.0.0",
  "description": "XXXXX",
  "main": "main-process/main.js",
  "scripts": {
    "start": "electron .",
    "pack": "electron-builder --dir",
    "dist": "electron-builder"
  },
  "author": "",
  "license": "ISC",
  "browser": {
    "fs": false
  },
  "dependencies": {
    "@electron/remote": "^2.0.9",
    "form-data": "^4.0.0",
    "md5-file": "^5.0.0",
    "threads": "^1.7.0"
  },
  "devDependencies": {
    "electron": "^24.3.1",
    "electron-builder": "^23.6.0"
  },
  "build": {
    "appId": "XXXXX",
    "mac": {
      "category": "XXXXX"
    },
    "directories": {
      "output": "dist",
      "buildResources": "main-process/threads"
    }
  }
}

How to pass variable to http client in my script in react.js project

I have a web-app with a webchat as a script which is connected to an AI-Service via URL. The URL is hardcode in my client, now I want to implement a variable on my webchat with which an user can pass his own URL to the client to connect to any service. My problem is, that I dont know how I can pass a variable value to my script. When I inspect the web-app I can see that the component of the web-app gets the new URL but when I print the variable of the script it says “undefined”. How do I have to proceed here?

Client needs the URL but prints “undefined” this is a component of my script

export class APIClient {
  constructor(serviceURL) {

    const serviceURL = widget.get("serviceURL");

 
    this.apiUrl = serviceURL;
    this.apiKey = process.env.REACT_APP_OPENAI_API_KEY;
    console.log("Service URL:", this.serviceURL)
    
    
  }

  async sendMessage(message) {
    console.log('API-Key:' + this.apiKey);

    try {
      const apiBody = {
        "model": "gpt-3.5-turbo",
        "messages": [{"role": "user", "content": "Can you act like you are the Chatbot of the University" +
        "of Heilbronn aka HHN and answer the following prompt and format the message with the respect to only use 100 tokens with the API call: " + message}],
        "max_tokens": 100,
        "temperature": 0,
      }

      console.log(JSON.stringify(apiBody))

      const response = await fetch(this.apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + this.apiKey,
        },
        body: JSON.stringify(apiBody),
      });

      if (!response.ok) {
        throw new Error(`Error: ${response.status} - ${response.statusText}`);
      }

      const data = await response.json();
      return data.choices[0].message.content;
    } catch (error) {
      console.error(error);
      return 'Sorry, something went wrong.';
    }
  }
}

My web-app component which loads the script

import * as React from "react";
import * as Scrivito from "scrivito";
import "./WebChatWidget.scss";




const WebChatWidget = ({ widget }) => {
  const serviceURL = widget.get("serviceURL");
  console.log("Service URL Widget:" , serviceURL)



//Use React Hooks to load external script into scrivito widget
  React.useEffect(() => { 
   
    const cssLink = document.createElement('link'); 
    cssLink.href = "/static/css/main.23941078.css";
    cssLink.rel = 'stylesheet';
    document.head.appendChild(cssLink);

    const script = document.createElement('script');
    script.src = "/static/js/main.14ec3828.js"; 
    script.async = true;
    document.body.appendChild(script);

    const chunkScript = document.createElement('script');
    chunkScript.src = "/static/js/787.4ed02641.chunk.js"; 
    chunkScript.async = true;
    document.body.appendChild(chunkScript);

    meinSkript(serviceURL);
  }, [serviceURL]);

  const meinSkript = (link) => {
    // Verwende den serviceURL in deinem Skript
    console.log(link);
    // ...
  };

  

  return <div id="Chatbot" className="WebChatWidget" style={{ zIndex: 1000 }}></div>;

};



Scrivito.provideComponent("WebChatWidget", WebChatWidget);

thank you in advance

I expect the script to load my URL passed from the web-app

Why is my dispatch.then method running before my fetch and state changes (promise)?

I’m using Vue router and vuex for state management (laravel in the backend).
Any time I try to log the user in through a function calling a vuex action, it will fire it’s own .then’s instead of resolving the promise provided by store.dispatch.

In any case, this makes my router push happen before the user is validated, which fails the redirect because the target page is protected.
Why do the functions fire in the order that they do, and how do I make sure that the redirect happens after everything else?

I want to redirect the user to a protected page once they succesfully login using the following code:

Login.vue:

function login(ev) {
  ev.preventDefault();
  store.dispatch('login', user)
    .then(() => {
      console.log(3)
      router.push({ name: 'Dashboard' });
    })
// error catching...

actions.js:

export function login({commit}, user) {
  laravelClient.post('/login', user)
    .then((response) => {
      console.log(1);
      commit('setUser', response.data);
      return response;
    })
}

mutations.js:

export function setUser (state, userData) {
    console.log(2);
    state.user.token = userData.token;
    state.user.data = userData.user;
    sessionStorage.setItem('TOKEN', userData.token);
}

As far as I know the console should be logging the numbers in the right order, but I can’t seem to wrap my head around why it fires in the order: (3, 1, 2)

Error sending email using XMLHttpRequest in JavaScript

I’m trying to send an email using XMLHttpRequest in JavaScript, but I’m facing an issue. Here’s what I’ve tried so far:

I have the following code snippet:

,
.

<!DOCTYPE html>
<html>
<head>
    <title>Email Sending Example</title>
</head>
<body>
    <h1>Email Sending Example</h1>

    <script>
        function sendEmail() {
            var email = {
                to: '[email protected]', // Replace with the recipient's email address
                from: '[email protected]', // Replace with your desired sender's email address
                subject: 'Example Email',
                message: 'Hello, This is an example email!'
            };

            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'https://api.intercom.io/email/send', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.setRequestHeader('Authorization', 'Bearer dG9rOjhhZa='); // Replace with your Intercom token

            xhr.onreadystatechange = function() {
                if (xhr.readyState === XMLHttpRequest.DONE) {
                    if (xhr.status === 200) {
                        alert('Email sent successfully!');
                    } else {
                        alert('Error sending email. Please try again.');
                    }
                }
            };

            xhr.send(JSON.stringify(email));
        }
    </script>

    <button onclick="sendEmail()">Send Email</button>
</body>
</html>

The issue I’m facing is that when I click the “Send Email” button, I’m receiving an error message saying “Error sending message. Please try again.” I have already checked the Intercom token, and it appears to be correct.

Am I missing something in the code or making a mistake with the XMLHttpRequest setup? I would appreciate any guidance or suggestions to resolve this issue.

Thank you in advance for your help!

my best and it should be able to send email

Difficulty in dealing with response from promise in React frontend

I’m having a hard time getting actual values from Django objects I created using API calls on the React frontend (and I believe my issue is with frontend). I’m trying to set an array to values from an API response to then be displayed on the frontend. I’m fairly new to this stuff so I apologize if I leave out something relevant

It seems, based on console logs I’ve done, that an array I create to eventually use to display these things gets populated with something but not what I’m expecting. In my component I have this provisions array that I am referencing and use to display values on the frontend:

this.state = {
      provisions: [],
    };

Next in the componentDidMount() method I call the method that will make the API call:

componentDidMount() {
    this.provisionsRequest();
  }

and then the provisions request method:

provisionsRequest(){
    Api.getProvisions().then((resp) => {
      this.setState({
        provisions: resp,
      });
    });
}

For the time being, I’m just checking the length of the provisions array, which happens to be 6. The issue though is that in the console log once I deploy the testing site, its an array of 6 ‘category’ objects with null values:

Array(6)
0: {category: null}
1: {category: null}
2: {category: null}
3: {category: null}
4: {category: null}
5: {category: null}
length: 6
[[Prototype]]: Array(0)

Initially I thought to check in views and see what the queryset was being given since it does happen to be 6 elements in length, but after using a logger to check that it seemed fine:

<QuerySet [('Category 1',), ('Category 2',), ('Category 3',), ('Category 4',), ('Category 5',), ('Category 6',)]>

My goal here is to have this array be six strings for each of the six categories from the queryset in views. What I am wondering is why does the array get set to the right size, get filled with category objects, but then have those objects have null fields?

For further info here is my api.js which handles the endpoints from urls.py:

const toJSON = (resp) => resp.json();
ENDPOINTS: {
    getProvisions: () => `${Api.BASE_PATH}/provision`,
  },
getProvisions: () => {
    return fetch(Api.ENDPOINTS.getProvisions()).then(toJSON);
  },

How to customize react native expo transition between screens?

I’ve been reading the documentation https://reactnavigation.org/docs/stack-navigator/ but none of the changes I apply makes a difference in the transition I want to develop (I’m using a iPhone 12 Pro)

Do you know how can I customize the transition between screens, similar to how WhatsApp or Instagram does it with a minimum effect and not and horizontal or vertical effect.

Thanks

I tried with YouTube videos, React Native documentation and other consults on Stack Overflow but besides the docs, questions/answer are not updated to 2023.

How to make jira and xray properties dynamic of cypress-xray plugin

I am working as a QA and got a chance to integrate Xray with Jira and cypress for automation testing.

I have integrated cypress with xray by following this documentaion ->
https://qytera-gmbh.github.io/projects/cypress-xray-plugin/
I have integrated the Xray with my Jira Board successfully. I am assuming that Cypress and Xray integration working because when I am executing cypress script at that time a new Test issue ticket and Test Execution ticket created successfully on jira board.

I have setup the configuration in cypress.config.js file.
Here is the code :

const { defineConfig } = require("cypress");

const { addXrayResultUpload, configureXrayPlugin } = require("cypress-xray-plugin/plugin");

module.exports = defineConfig({
  waitForAnimations: false,
  animationDistanceThreshold: 50,
  videoCompression: false,
  trashAssetsBeforeRuns: false,
  e2e: {
    baseUrl: "http://localhost:3000/",
    env: {
      jiraApiToken: 'shgvgsyashdgvyhsgdaygshduyjscgbsdydhjcbjyhdchn',
      jiraApiBaseUrl: 'https://xyz.atlassian.net/rest/api/2',
      jiraUserName: '[email protected]'
    },
    setupNodeEvents(on, config) {
      configureXrayPlugin({
        jira: {
          projectKey: "PZA",
          url: "https://xyz.atlassian.net",
          jiraTestIssueType: 'Test',
          createTestIssues: false,
          createTestExecutionIssues: false,
          testExecutionIssueDescription: "This test run was approved by Prachi.",
          testExecutionIssueSummary: "Finaly..............Test Success ",
          jiraTestExecutionIssueType: 'Test Execution',
          testExecutionIssueKey: "PZA-81",
         testIssueKey: "PZA-80",
          assignee: '[email protected]'
        },
        xray: {
          createTestExecutionIssues: false,
          createTestIssues: false,
          uploadResults: true
        }
      });
      addXrayResultUpload(on) ;
      return config;
    }
  },
  component: {
    devServer: {
      framework: "create-react-app",
      bundler: "webpack"
    }
  }
});

I am using below properties for make it disable but execution property is not working

createTestExecutionIssues: false,
createTestIssues: false,

Here is my newTest.cy.js file

import React from "react";

<reference types="cypress" />

import "cypress-xray-plugin/register";

import {
  JOINTHEADERMENU, imgJson
} from "./constant";

describe(" New Test", () => {
  
  //Here we have specified the Test issue id in inside it block 
  it("PZA-80", async () => {
    cy.viewport(1440, 900);
    cy.visit(`${Cypress.config().baseUrl}login`);
    cy.get('img[src="/images/logo.svg"]').should("be.visible");

    cy.wrap(JOINTHEADERMENU).each((str) => {
      cy.log(str);
      cy.contains(str).should("be.visible");
    });

    cy.contains("PERSONAL").should("be.visible").click().wait(5000);
    cy.url().should("eq", `${Cypress.config().baseUrl}personal`);

    cy.get('img[src="/images/personalLanding.svg"]').should("be.visible");


    cy.get('img[src="/images/personalLanding.svg"]').should("be.visible");

    cy.contains("FOR MYSELF").should("be.visible");

    cy.contains("Don’t miss out on the wellbeing benefits because you work for yourself").should(
      "be.visible"
    );
    cy.contains(
      "pirkx brings together benefits to help you affordably improve your financial wellbeing, health and much more."
    ).should("be.visible");
    cy.contains("ONLINE DEMO").should("be.visible");

    cy.contains("WHY PIRKX?").should("be.visible").click().wait(5000);
    const newImgJson = imgJson.map((obj) => {
      cy.contains(obj.text).should("be.visible");
      cy.get(`img[src="${obj.image}"][alt="First"]`).should("be.visible");
    });
   
  });

  
}); 

I want to do this jira and xray configuration dynamic for each test script so that I can change test execution and test issue key Id’s.

Or

If it is not possible so I want to make it disable so that when I am running any script then new jira tickets for Test Execution and Test Issue will not create and existing ticket will update based on assigned ticket id to the particular test script.