My object flies off the canvas when i move it instead of staying within the bounds of the canvas

I’m currently trying to code a simple game for class. Right now I want my rectangle to stay within the bounds of my canvas when i move it by using a bounce function, but it doesn’t seem to be working and I cant figure out why. I have tried implementing my bounce function and calling it at the top. When I move my rectangle it goes past the bounds of the canvas without staying inside and “bouncing” off the border.

var canvas;
var ctx;
var w = 1000;
var h = 700;
 

var o1 = {
    x: 100,
    y: h/2,
    w: 100,
    h: 100,
    c: 0,
    a: 100,
    angle: 0, //changes angle that shape sits at
    distance: 10
}
 

document.onkeydown = function(e){keypress(e, o1)}
 
 
 
 
setUpCanvas();
// circle (o1);
animationLoop();
 
 
function animationLoop(){
    //clear
    clear();
    //draw
    rect(o1);
    //update
   bounce(o1)

    requestAnimationFrame(animationLoop)
 
}
 


function bounce(o){
    if(o.x+o.w/2 > w || o.x-o.w/2 < 0){ //makes shape bounce from edge instead of middle. collision detection
        o.changeX *= -1; //same as o.changeX = o.changeX = -1;
    }
 
    if(o.y+o.h/2 > h || o.y-o.h/2 <0){
        o.changeY *= -1;
    }
   
 
}
 
 
function updateData(o){
o.x += o.changeX;
o.y += o.changeY;
}



function keypress(e,o){

 
    if (e.key == "ArrowUp"){
        o.angle = 270;
        o.distance= 80;
        forward(o);
       
    }
 
    if (e.key == "ArrowDown"){
        o.angle = 90;
        o.distance= 20;
        forward(o);
        
    }
}
 
 
 
function forward(o){ //makes shape able to move
    var cx;
    var cy;
    cx = o.distance*Math.cos(o.angle);
    cy = o.distance*Math.sin(o.angle)
    o.y += cy;
 
 }
 

    function rect(o){
        var bufferx = o.x;
        var buffery = o.y
        o.x = o.x - o.w/2;
        o.y = o.y- o.h/2;
        ctx.beginPath(); //this is very important when we are changing certain ctx properties
        ctx.moveTo(o.x,o.y);
        ctx.lineTo(o.x+o.w,o.y);
        ctx.lineTo(o.x+o.w,o.y+o.h);
        ctx.lineTo(o.x, o.y+o.h);
        ctx.lineTo(o.x,o.y);
        ctx.fillStyle = "hsla("+String (o.c)+",100%,50%,"+o.a+")";
        ctx.fill();
    
        o.x = bufferx; //o.x = o.x + o.w/2;
        o.y = buffery;//o.y = o.y+ o.h/2;
    }
    
 
 
 
 
 
 
function clear(){
    ctx.clearRect(0, 0, w, h);
}
 
function randn(range){
    var r = Math.random()*range-(range/2);
    return r
}
function rand(range){
    var r = Math.random()*range
    return r
}
 
function setUpCanvas(){
    canvas = document.querySelector("#myCanvas");
    canvas.width = w;
    canvas.height = h;
    // canvas.style.width = "1000px";
    // canvas.style.height = "700px";
    canvas.style.border = "10px solid black";
    ctx = canvas.getContext("2d");
}
 
console.log("Final Assignment")
 
 
 
 
 
 


How do I make my .js.erb files work in rails 7

I’m following a Rails Tutorial | Building a Link Shortener with Rails 6 and ruby 2.xx to build the same app. However, I’m using rails 7.0.4 and ruby 3.0.0.
My create.js.erb file does not work. And from a quick lookup on google, I discovered .js.erb has been removed from rails 7 and replaced with turbo_stream and hot stimulus.js.

How do I hook my code in create.js.erb which is embedded ruby in javascript into the new rails 7 say links_controller.js under javascript >> controller directory. since the latter is purely javascript.

create.js.erb:

var lookupCode = "<%#= @link.lookup_code %>";

var element = document.getElementById('short-link');
element.innerHTML = lookupCode;

I created this file under javascript >> controller directory: links_controller.js

import { Controller } from '@hotwired/stimulus';

export default class extends Controller {
  connect() {
    this.element.textContent = "I believe I should hook the content of create.js.erb here";
  }
}

Pls, any help will be greatly appreciated.
I did a lot of research and googling before asking this question. And the only one that could have answered my question was closed:

Ruby on Rails 7 – Is there any way to implement js.erb files?

How to slow down animation loop

I am using this babylonjs playground as an example to animate a boat in a scene I am creating for a class project. But the animation is going far too fast for what want to use it for. Could you please show me how to slow this animation down? As well as explain how the animation part works. Thank you!

Babylonjs playground: https://playground.babylonjs.com/#1YD970#14

sorry im very new to babylonjs

I don’t really understand some of the classes and variables used so I don’t know what exactly to change to have a slower animation loop.

Dynamic buttons background-color changes at same time when clicked

Created an small project in vuejs to understand how binding works with classes and style and so on.
The behavior I wanted is that when clicked on different dynamic buttons they should have different backgrounds and it works partially.The issue is when I clicked on one button the other buttons also changes its background-color at the same time and I don’t want this behavior.
I have active props and I think its causing this issue. Any help will be much appreciated from you.

my code:
DynamicButton.vue

<template>
  <div>
    <div class="btn1">
      <button
        v-on="$listeners"
        :class="[dark ? 'dark' : 'light', 'baseButton']"
        class="btn"
        :style="{ backgroundColor: color }"
      >
        {{ buttonText }}
      </button>
    </div>
  </div>
</template>

<script>
export default {
  name: "DynamicButton",

  props: {
    buttonText: {
      type: String,
      default: "label",
    },
    dark: {
      type: Boolean,
      default: false,
    },

    light: {
      type: Boolean,
      default: true,
    },
    active: {
      type: Boolean,
      default: false,
    },
    color: {
      type: String,
      default: "gray",
    },
  },
};
</script>

<style scoped>
.baseButton {
  border-radius: 5px;
  border: none;
  padding: 10px;
  width: 200px;
  height: 30px;
}

.light {
  background: white;
  color: black;
  border: 1px solid lightgray;
}

.dark {
  background: black;
  color: white;
}

.btn {
  margin: 10px;
}
</style>

app.vue:

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
   
    <DynamicButton
      buttonText="Dark Mode"
      :dark="true"
      @click="handleDarkMode"
      :color="active ? 'red' : 'blue'"
    />
   
    <DynamicButton
      buttonText="Light Mode"
      @click="handleLightMode"
      :color="active ? this.color : '#16a085'"
    />
  </div>
</template>

<script>

import DynamicButton from "./components/DynamicButton.vue";

export default {
  name: "App",
  components: {
    HelloWorld,
    DynamicButton,
  },

  props: {
    // darkColorChange: {
    //   type: String,
    //   default: "",
    // },
    // lightColorChange: {
    //   type: String,
    //   default: "",
    // },
  },

  data() {
    return {
      active: true,
      color: "#3aa1b6",
    };
  },

  methods: {
    handleDarkMode() {
      console.log("Dark-mode clicked");
      // eslint-disable-next-line
      // this.darkColorChange.style.backgroundColor = "pink";
      this.active = !this.active;
    },

    handleLightMode() {
      console.log("Light-mode clicked");
      this.active = !this.active;
    },
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

my buttons Components:
enter image description here

Why does connecting to mongodb stop my app from rendering?

In my react app, when connecting to mongodb via mongoose, no error is thrown but the page does not render.

I think the problem is that connecting to my mongo server takes forever so the page will never render. I tried putting the mongoose connect in multiple files. Here is my code.

App.js


import UploadWidget from "./components/UploadWidget";


function App() {
  return (
    <div>
      <UploadWidget />
    </div>



  );
}

export default App;

UploadWidget.js

import { useEffect, useRef } from "react";
import saveImage from "../server/mongoose"


const UploadWidget = () => {
    const cloudinaryRef = useRef()
    const widgetRef = useRef()

    useEffect(() => {
        cloudinaryRef.current = window.cloudinary
        widgetRef.current = cloudinaryRef.current.createUploadWidget({
            cloudName: "dthoiaec2",
            uploadPreset: "webf9xvo"
        }, (err, res) => {
            console.log(res || err)
        })
    }, [])

    return (
        <button onClick={() => {
            saveImage(widgetRef.current.open())

        }}>
            Upload
        </button >
    )

}
export default UploadWidget

mongoose.js


import mongoose from "mongoose";
mongoose.connect('mongodb://localhost:27017/bereal')
export default function (url) {
    console.log(url)
}



All that is rendered is a white screen. If I remove mongoose.connect it renders completely fine.

TypeError: Spread syntax requires …iterable[Symbol.iterator] to be a function

i have this error when i trying use the update component with my app, and i don’t know, why is that error

Error:

TypeError: Spread syntax requires ...iterable[Symbol.iterator] to be a function
    at HttpHeaders.applyUpdate (http.mjs:244:22)
    at http.mjs:211:56
    at Array.forEach (<anonymous>)
    at HttpHeaders.init (http.mjs:211:33)
    at HttpHeaders.forEach (http.mjs:274:14)
    at Observable._subscribe (http.mjs:1811:25)
    at Observable._trySubscribe (Observable.js:37:25)
    at Observable.js:31:30
    at errorContext (errorContext.js:19:9)
    at Observable.subscribe (Observable.js:22:21)

And this is the code of my app, i use Laravel 9 in the Back-end, but the problem appears to me as if it were from the front, just in case i leave the code from back at the end

**UpdateComponent.ts: **

onSubmit(form:any){
    this._userService.update(this.token, this.user).subscribe(
      response => { 
        console.log(response)
      },
      error => {
        this.status = 'error'
        console.log(error)
      }
    )
  }

ModelUser.ts:

export class User{
    constructor(
        public id: number,
        public name: string,
        public surname: string,
        public role: string,
        public email: string,
        public password: string,
        public description: string,
        public image: string
    ){}
}

UserService.ts

update(token:any, user:any):Observable<any>{
        let json = JSON.stringify(user)
        let params = 'json=' + json
        let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded').set('Authorization', token)

        return this._http.put(this.url + 'user/update', params, { headers: headers })
    }

UserController/update.php

 public function update(Request $request){
        
        //Recoger los datos por POST
        $json = $request->input('json', null);
        $params_array = json_decode($json, true);

        if($checkToken && !empty($params_array)){
            //Sacar usuario identificado
            $user = $jwtAuth->checkToken($token, true);

            //Validar los datos
            $validate = Validator::make($params_array, [
                'name' => 'required|alpha',
                'surname' => 'required|alpha',
                'email' => 'required|email|unique:users,'.$user->sub
            ]);

            //Quitar los campos que no se actualizan
            unset($params_array['id']);
            unset($params_array['role']);
            unset($params_array['password']);
            unset($params_array['created_at']);
            unset($params_array['remember_token']);

            //Actualizar el usuario en la DB
            $user_update = User::where('id', $user->sub)->update($params_array);

            //Devolver array con resultado
            $data = array(
                'code' => 200,
                'status' => 'success',
                'user' => $user,
                'changes' => $params_array
            );
        }else{
            $data = array(
                'code' => 400,
                'status' => 'error',
                'message' => 'Usuario no identificado'
            );
        }

        return response()->json($data, $data['code']);
    }

i don´t know how acces to the pet object (EXCERCISE WITH OBJECTS IN JS)

im doing a project-excercise of debugging using objects, im already done all the other´s excercises but im very stuck in this, i dont know how to solve.

    /*

Fix the `feedPet` function. `feedPet` should take in a pet name and return a
function that, when invoked with a food, will return the pet's name and a list
of foods that you have fed that pet.

*/

function feedPet(name) {
  const foods = [];
  return (food) => {
    return "Fed " + name + " " + foods.push(food) + ".";
  }
}

const feedHydra = feedPet('Hydra');

console.log(feedHydra('bones')); // Fed Hyrda bones.
console.log(feedHydra('Hercules')); // Fed Hyrda bones, Hercules.

const feedHippogriff = feedPet('Hippogriff');

console.log(feedHippogriff('worms')); // Fed Hyrda worms.
console.log(feedHippogriff('crickets')); // Fed Hyrda worms, crickets.
console.log(feedHippogriff('chicken')); // Fed Hyrda worms, crickets, chicken.

how can I get the output of prototype correctly [duplicate]

I am learning JS prototype, and I got the following code, all is clear except the output of console.log(myObj.name). How come it gives the name of the object itself, which is myObj? Doesn’t it need to find the prototype from its upper-level object?

const myObj = function () {}

myObj.prototype.name = 'prototype.name'

myObj1 = new myObj()

console.log(myObj.name) // => myObj
console.log(myObj1.name) // => 'prototype.name'
console.log(myObj.prototype.name) // => prototype.name

I was expecting the same output as myObj1 and their prototype.

Redirect popup button onclick to a custom page

We have a popup form, which is triggered by Omnisend application on Shopify – we want to redirect customers to a custom thank you page, made by us (the page is made on Shopify also). But there is just simply no options for that in Omnisend.

Can i target or grab the class / id of the button with jquery and make a custom redirection based on that? As i cannot edit the source code, so i can’t create onclick function.

Would something like this work?

$('#IDhere').click(function(){

Thank you so much if you try to help me! 🙂

SFMC AMPscript Understanding Controlling Expression Evaluation unclear

The below expression is not making sense to me. I’m having a hard time understand why it will result in “free shipping”. Can someone elaborate on the explanation?

%%[

var @statusTier, @amount, @freeShipping
set @statusTier = "Bronze"
set @amount = 300

if @statusTier == "Bronze" or @statusTier == "Silver" and @amount > 500 then
  set @freeShipping = true
endif

]%%

<p>You %%=Iif(@freeShipping == true, "qualify","do not qualify")=%% for free shipping.</p>

Output:
The join operators in the above if statement will be evaluated as a single expression and will produce the following result:

<p>You qualify for free shipping.</p>

From my understanding the set amount of 300 is not > 500 therefore this should not have been a true statement and should output “You do not qualify for free shipping.”. I’m a missing something here? Please help, I’m a newbie to AMPscript with little knowledge to JavaScript.

Original THE AMPSCRIPT GUIDE post: https://ampscript.guide/controlling-expression-evaluation/

Thank you for you input in advance!

Errors with GEOJSON handling in javascript function

An image says more than a thousand words 🙂

enter image description here

I mean i get these three errors caused by line 37. The layer is not null or undefined, the same is true for the map, but anyway, something goes wrong with removal from the map…

Code snippet:

$(grid).click(function () {
    if (myLayerGrid !== undefined && myLayerGrid !== null && myMap !== undefined && myMap !== null) {
        if (this.checked) {
            if (!myMap.hasLayer(myLayerGrid)) {
                myLayerGrid.addTo(myMap);
            }
        } else {
            if (myMap.hasLayer(myLayerGrid)) {
                //myMap.removeLayer(myLayerGrid);
                myLayerGrid.remove(myMap);
            }
        }
    }
});

Error messages:

Uncaught TypeError: Cannot read properties of undefined (reading 'appendChild')

LatLngBounds.js:103 Uncaught TypeError: Cannot read properties of undefined (reading 'min')

Uncaught TypeError: Cannot read properties of null (reading '_targets')

SyntaxError: Unexpected token ‘else’ [closed]

I have a little problem, i need to set value 0 for inputs witch have style “display: none” but i get one error: SyntaxError: Unexpected token ‘else’ , and for display:block put the value from first input but this step i maked

<script>
jQuery(document).ready(function ($) {

var $apartament = $('input#value-apartament'),

$permetru = $('.put-value input');

$apartament.on('input', function () {

$permetru.val($apartament.val());

for (var n = 0; n < $permetru.length; ++n) {
    if ($permetru[n].style.display = "none") {
         $permetru.val(0);
         
};
};
 else if ($permetru[n].style.display = "block"); {
         $permetru.val($apartament.val());
};
};
};
};
});
});
</script>
[enter image description here][1]


  [1]: https://i.stack.imgur.com/XvMKy.png

scss file saved but not updating homepage

I am running into some problem about updating my front page. The scss file is saved only it won’t update my background color. It is in a file called full-width-split.scss. I also have a file called style-index.css in the build folder of the WordPress website. I don’t know why it isn’t updating my background color even though the scss file is saved. How do I solve this issue?

Inspect shows this:

  @include atMedium {
    display: flex;
  }

  &__one {
    flex: 1;
    padding: 1.6rem 16px;
    @include atMedium {
      padding: 40px;
    }

    .full-width-split__inner {
      @include atMedium {
        float: right;
      }
    }
  }

  &__two {
    flex: 1;
    background-color: $beige;
    padding: 1.6rem 16px;
    @include atMedium {
      padding: 40px;
    }
  }

  &__inner {
    @media (min-width: 1350px) {
      width: 610px;
    }
  }
}

But it needs to show this:

.full-width-split {
  @include atMedium {
    display: flex;
  }

  &__one {
    flex: 1;
    background-color: #ffffff;
    padding: 1.6rem 16px;
    @include atMedium {
      padding: 40px;
    }

    .full-width-split__inner {
      @include atMedium {
        float: right;
      }
    }
  }

  &__two {
    flex: 1;
    background-color: #faf0ca;
    padding: 1.6rem 16px;
    @include atMedium {
      padding: 40px;
    }
  }

  &__inner {
    @media (min-width: 1350px) {
      width: 610px;
    }
  }
}



  [1]: https://i.stack.imgur.com/IAO6k.png
  [2]: https://i.stack.imgur.com/leSek.png

React / Node – PayPal can’t capture a new subscription

I wan’t to capture a new paypal subscription from frontend in my backend and give response with the needed data for mongodb.

If I add a body with capture_type: ‘OUTSTANDING_BALANCE’ (I found that in the manual) I’m getting this error.
So I’m not sure either it’s just a wrong body or i totally mess up something else in the backend but so far I can’t capture the subscription even so I get a subscription Id from
createSubscription Controller

PayPalScriptProvider

<PayPalScriptProvider options={initialOptions}>
    <PayPalSubscriptionButton/>
</PayPalScriptProvider>

PayPal Button

      {isPending ? <LoadingMedium /> : null}
      <PayPalButtons
        createSubscription={(data, actions) => {
          return axios
            .post(
              '/api/subscription',
            )
            .then((response) => {
              return response.data.id;
            });
        }}
        onApprove={(data, actions) => {
          axios
            .post(`/api/subscription/${data.subscriptionID}/capture`)
            .then(() => {
              axios
                .patch(
                  `/api/activesubscription`,
                  {
                    id: activeSub[0]?._id,
                    subscriptionID: data.subscriptionID,
                  }
                )
                });
            });
        }}
      />

Route for createSubscription

router.route('/subscription').post(async (req, res) => {
  const searchPlan = await SubscriptionAmount.find();
  console.log(searchPlan[0]?.subscriptionAmount);
  const subscription = await paypalFee.createSubscription(
    searchPlan[0]?.subscriptionAmount
  );
  res.json(subscription);
});

Router for onApprove

router.post('/subscription/:subscriptionID/capture', async (req, res) => {
  const { subscriptionID } = req.params;
  console.log('subscriptionID', subscriptionID);
  const captureData = await paypalFee.captureSubscription(subscriptionID);
  console.log('captureData', captureData);
  res.json(captureData);
});

createSubscription Controller

async function createSubscription(planId) {
  const accessToken = await generateAccessToken();
  const url = `${base}/v1/billing/subscriptions`;
  const response = await fetch(url, {
    method: 'post',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${accessToken}`,
    },
    body: JSON.stringify({
      intent: 'subscription',
      plan_id: planId,
    }),
  });
  const data = await response.json();
  console.log('data', data);
  return data;
}

captureSubscription Controller

async function captureSubscription(subscriptionId) {
  const accessToken = await generateAccessToken();
  const url = `${base}/v1/billing/subscriptions/${subscriptionId}/capture`;
  const response = await fetch(url, {
    method: 'post',
    body: JSON.stringify({
     // capture_type: 'OUTSTANDING_BALANCE',
    }),
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${accessToken}`,
    },
  });
  const data = await response.json();
  console.log('data', data);
  return data;
}

I’m getting this logs for my data in captureSubscription if I do not pass a body in my captureSubscription Controller:

captureData {
  name: 'INVALID_REQUEST',
  message: 'Request is not well-formed, syntactically incorrect, or violates schema.',
  details: [
    {
      location: 'body',
      issue: 'MISSING_REQUEST_BODY',
      description: 'Request body is missing.'
    }
  ]
}

With body I’m getting this error

captureData {
  name: 'UNPROCESSABLE_ENTITY',
  message: 'The requested action could not be performed, semantically incorrect, or failed business validation.',

  details: [
    {
      issue: 'ZERO_OUTSTANDING_BALANCE',
      description: 'Current outstanding balance should be greater than zero.'
    }
  ],
}