Angular 16 – global import in all tests

I’m using Angular 16 with Karma/Jasmine. I want to have a module be imported by default in all my tests but am unable to find where this can be configured. I saw this post which makes use of a test.ts file, but my project does not include this.

How can I include this test.ts file in order to globally import a module in all my tests?

django Direct assignment to the forward side of a many-to-many set is prohibited. Use user.set() instead

hi i have aproject in django when i try to runserver the message above is shwon this is models.py fo

    class Display(models.Model) :
     url=models.URLField(unique=True)
     text = models.CharField(max_length=150) 
    
    class  Display_Data(models.Model) :
         displays = models.ManyToManyField(Display)  
         user= models.ManyToManyField(User)
         choosenum=models.IntegerField()
         puplish_date =models.DateTimeField(default=datetime.now) 
and this the view.py

tdef submit_operation(request):
 if request.method == 'POST':
    url = request.POST.get('url')
    text = request.POST.get('title')
    choosenum = request.POST.get('CHOOSE')

    if Display.objects.filter(url=url).exists():
        display = Display.objects.get(url=url)
        display_data = Display_Data.objects.create(choosenum=choosenum, user=request.user,                  date_published=datetime.now())
        display_data.displays.add(display)
    else:
        display = Display.objects.create(url=url, text=text)
        display_data = Display_Data.objects.create(choosenum=choosenum, user=request.user,    date_published=datetime.now())
        display_data.displays.add(display)        # ... (إعادة توجيه المستخدم)

    #return redirect('searchpage') 
    return redirect(request.META.get('HTTP_REFERER'))ype herea

`and when i try to refer to vidion saved before the message above abeer



i make a site show video from youtube in a frame and asked a user to value the vidio i saved vidio url and when i want from user to again evluate the vidio the mistake apeer

Hover over the axis instead of the point (echarts)

I tried to configure the line graph to hover the mouse on the X axis, instead of hovering the mouse over the point on this same graph to apply the value to another (gauge).

This code below works for the point on the graph:

   <head>
      <script src='https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js'></script>
      <link href='https://fonts.cdnfonts.com/css/ds-digital' rel='stylesheet'>
    </head>
    
    <div id='chart' style='width: 400px; height: 200px;'></div>
    <div id='gauge' style='width: 300px; height: 300px; margin-top: -60px;'></div>
    
    <script>
      document.addEventListener('DOMContentLoaded', function() {
        let myChart = echarts.init(document.getElementById('chart'));
        let gaugeChart = echarts.init(document.getElementById('gauge'));
    
        let dataset = {
          'source': {
            'quant': [1000, 2000, 3000, 4000, 5000, 6000],
            'Discount': [2, 82.1, 88.7, 70.1, 53.4, 85.1],
            'Discount (adj)': [8, 51.4, 55.1, 53.3, 73.8, 68.7],
            'Increase': [-4, -62.2, -69.5, -36.4, -45.2, -32.5]
          }
        }
    
        let option = {
    
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: dataset.source.quant.map(value => value.toFixed(0))
          },
          yAxis: {
            type: 'value'
          },
          series: [{
              type: 'line',
              name: 'Discount',
              data: dataset.source.Discount
            },
            {
              type: 'line',
              name: 'Increase',
              data: dataset.source.Increase
            }
          ]
        };
    
        myChart.setOption(option);
    
        let gaugeOption = {
          series: [{
            type: 'gauge',
            min: -100,
            max: 100,
            detail: {
              formatter: '{value}%'
            },
            axisLabel: {
              textStyle: {
                fontSize: 15,
                fontFamily: 'Lato',
                color: '#f2f2f2',
                textBorderWidth: 1,
                textBorderColor: '#020202'
              }
            },
            data: [{
                value: 0,
                name: 'Discount'
              },
              {
                value: 0,
                name: 'Increase'
              },
              {
                value: 50,
                name: 'TEST'
              }
            ]
          }]
        };
    
        gaugeChart.setOption(gaugeOption);
    
        myChart.on('mousemove', function(params) {
          if (params.seriesType === 'line') {
            let index = params.dataIndex;
            let value1 = dataset.source['Discount'][index];
            let value2 = dataset.source['Increase'][index];
            gaugeOption.series[0].data[0].value = value1;
            gaugeOption.series[0].data[1].value = value2;
            gaugeChart.setOption(gaugeOption);
          }
        });
      });
    
    </script>

I tried it too:

       myChart.getZr().on('mousemove', function(params) {
          let xAxis = myChart.getModel().getComponent('xAxis', 0);
          let pointInGrid = [params.offsetX, params.offsetY];
          let index = xAxis.pointToDataIndex(pointInGrid);
          if (index >= 0 && index < dataset.source.quant.length) {
            let value1 = dataset.source['Discount'][index];
            let value2 = dataset.source['Increase'][index];
            gaugeOption.series[0].data[0].value = value1;
            gaugeOption.series[0].data[1].value = value2;
            gaugeChart.setOption(gaugeOption);
          }
        }); 

and:

triggerLineEvent: true

But not working.

In other words, I don’t want the mousemove effect to apply to the point on the line, but to the whole line as a function of the X axis.

Failed to execute ‘fetch’ on ‘Window’: Failed to parse URL from https://:9901/api/auth/sign_in

I am having a weird issue with a MERN app I am making. When I access to my React front-end and try to log into my app, the following error message appears:

Failed to execute 'fetch' on 'Window': Failed to parse URL from https://<my_ip_address>:9901/api/auth/sign_in

And that is very weird considering that I’m making sure that my server is running on HTTPS and it’s on port 9901:

const https = require('https');
const express = require('express');
const fs = require('fs');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const ApiRouter = require('./src/routers/ApiRouter');
const path = require('path');
const cors = require('cors');
const os = require('os');
const { DB_LINK, BASE_URL, NODE_ENV } = require('./src/config/config');

const app = express();

const whitelist = ['http://localhost:3000'];

function getLocalIpAddress() {
  const interfaces = os.networkInterfaces();
  for (const key in interfaces) {
    const iface = interfaces[key];
    for (let i = 0; i < iface.length; i++) {
      const alias = iface[i];
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
        return alias.address;
      }
    }
  }
  return null;
}

const localIpAddress = getLocalIpAddress();

if (localIpAddress) {
  whitelist.push(`http://${localIpAddress}:3000`);
}

// I know this is not secure, this is only for develipment purposes
app.use(
  cors({
    origin: function (origin, callback) {
      callback(null, true);
    }
  })
);

// Load SSL certificate
const credentials = {
  pfx: fs.readFileSync('sslcert/cert/localhost.p12'),
  passphrase: 'changeit'
};

// Use HTTPS
const httpsServer = https.createServer(credentials, app);

app.use(bodyParser.json());

app.use(express.urlencoded({ extended: true }));

express.static.mime.types['css'] = 'text/css';

app.use(express.static('public'));

app.use('/uploads', express.static(path.join(__dirname, './uploads')));

mongoose.connect(DB_LINK, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  retryWrites: true,
  connectTimeoutMS: 10000
})
  .then(() => {
    app.use('/api', ApiRouter);

    const port = 9901;
    httpsServer.listen(port, () => {
      console.log('Connected to MongoDB');
      // BASE_URL = 'https://<my_ip_address>:9901';
      console.log(`Server started at ${BASE_URL}/`);
      console.log(`Environment: ${NODE_ENV}`);
    });
  })
  .catch((err) => {
    console.error(err);
    process.exit(1);
  });
  

Then, in my client, I have the following configuration file that defines the URL where my backend is running so my endpoint calls (or ‘fetch’ requests) know where it is. This file is called basePath.js:

const serverBaseUrl = process.env.REACT_APP_SERVER_BASE_URL || '<my_ip_address>';

export const basePath = `https://${serverBaseUrl}:9901/api`;

So, as you can imagine, I observed the following condition:

  • The port number for my server is the correct one since it’s the one defined in my server’s configuration.
  • Right now my CORS configuration allows requests for any origin. This is strictly for development purposes only.
  • Both my client and server are running correctly and on the same network (since I am running them on my local machine).
  • My API route is implemented in my server:
router.post('/sign_in', async (req, res, next) => {
  const { email, password } = req.body;

  try {
    const authData = await signIn(email, password);
    res.json(authData);
  } catch (error) {
    errorCallback(error, res);
  }
});

and in my client:

import { getJSONHeaders } from '../../functions/sharedHeaders';
import { basePath } from '../../config/basePath';
...

async function signIn({ email, password }) {
  const response = await fetch(`${basePath}/auth/sign_in`, {
    method: 'POST',
    body: JSON.stringify({ email, password }),
    headers: getJSONHeaders()
  });

  const { user, token, refreshToken, message, success } = await response.json();

  ...
}

So, what could be my issue here?

Detecting touch events that started in another element?

In my browser game I have a grid and am working on mobile support. I need to be able to “swipe” from one cell of the grid to another cell.

I am finding I can trigger either onTouchStart or onTouchMove within any given cell of the grid, but when I then drag my finger to another adjacent cell it does not trigger either event on the other cell. I have to lift my finger and touch that cell anew in order to trigger the events on it.

How can I detect the user “swiping into”/”dragging into” an element? On desktop this is simply onmouseenter but that doesn’t apply on mobile.

Axios requests stuck at pending

I have an app written in javascript with react.js framework, it uses react-query to fetch data with axios, but suddenly my requests hangs “pending” state

  • My back-end is written in laravel 11.x

  • for Chrome:

    • All of the requests hangs “pending” state, sometimes they fail with “ERR_ADDRESS_IN_USE” or “ERR_TIMED_OUT”
  • for Mozilla (Nightly):

    • Most of them was succeeding, some of them hangs pending at the beginning, then i am started to getting CORS same-policy error
    • Some of them fails as CORS failed or NS_ERROR_DOM_BAD_URI

node.js runs on : 127.0.0.1:3000
laravel runs on : 127.0.0.1:8000

Chrome developer console.

Firefox developer console.

Laravel config/cors.php file.

it was just fine like 2-3 days ago, tried to revert last commits but it didn’t seem to work.

My custom axios object.

  • Tried to improve server performance by working on with relationships.
  • Tried to change axios config
  • Setup “Laravel Telescope” in order to review requests & SQL queries.
    • Requests & Queries seems to work just fine.

How to prevent scrolling when touching a certain html element on a touch device?

I have a simple browser game which is finished on desktop, but which I am trying to make work on mobile.

The current problem is that when the user uses a touchscreen to make a vertical dragging motion within the game’s container, it either scrolls the screen or tries to refresh the page depending on direction and level of scroll.

I have tried setting onScroll, onTouchMove, onTouchStart, onDragStart, and onDrag events, all with both e.stopPropagation() and e.preventDefault() as well as returning false but the problem persists.

I know it is possible because if you open 2048‘s browser implementation on your phone and try dragging within the game container, it does not scroll, yet you can scroll if you drag anywhere on the page outside the game container. I couldn’t find how it’s done in the page’s source, though.

How can this be accomplished?

How to apply different CSS style to the same component based on fetched result? [closed]

So I have a problem with implementing certain mechanic in my simple image selector one vs one game.

The idea is that one player, for example, should click on the presented image (out of 36 images within parent component that holds them) and it should trigger a request to the server that will validate whether the correct image is selected. As a response the server should send correct or incorrect and if the result is correct, the component that holds the image should set its CSS to green. However, this is for one player only, the other player should instead of green see orange(to indicate that the first player has clicked on this image) and it should prevent second player from clicking on orange colored image. How can the CSS part be implemented based on some simple example?

I am unable to start, frozen by difficulty of the problem.

Seeking Guidance on GSAP Animation for Diagonal and Horizontal Movement in React

I’m currently developing a feature using React and GSAP in a personal project where elements (spaceships and clouds) animate across the screen in a continuous loop. The spaceships are supposed to move diagonally across the screen at specific angles, while the clouds move horizontally. The main challenge arises with the repositioning of these elements: after exiting the screen, they should reappear from the opposite side to maintain a seamless loop.

My implementation involves an “if” condition to differentiate the movement based on the angle—horizontal movement for clouds (angle = 0) and diagonal for spaceships (angle != 0). While the initial animation sequence works as expected, making the elements reappear from the opposite side has proven to be problematic. Instead of continuing their journey across the screen from where they exited, they reset to their original starting positions.

This issue is particularly perplexing as it interrupts the desired continuous flow of the animation. I have set up a minimal demo to illustrate my current approach and the issue at hand. This setup is supposed to showcase a looped animation effect for each element based on their designated movement patterns.

The minimal demo

In my implementation, I used GSAP’s fromTo function to animate the elements based on their designated paths. For horizontal movement (clouds with an angle of 0), the elements are supposed to move from the left off-screen to the right off-screen and then reappear on the left, creating a loop. For diagonal movement (spaceships), the expectation was similar, with the elements moving in a diagonal path across the screen and then reappearing from the opposite side they exited.

What I Tried:
I implemented a conditional logic within my GSAP animation to distinguish between horizontal and diagonal movements. For the horizontal case, the animation starts with the element off-screen on the left and moves it across to exit on the right. I then used the onRepeat callback to reset the element’s position to its starting point off-screen on the left.

For diagonal movements, I calculated the deltaX and deltaY to ensure the element moves in the correct diagonal direction and distance based on the specified angle. Again, I relied on onRepeat to reset the element’s position, aiming for a seamless re-entry from the opposite side.

Expected Outcome:
I expected each element to continuously loop across the screen in its respective path — horizontally for clouds and diagonally for spaceships. The key was for them to reappear seamlessly from the opposite side they exited, maintaining a constant flow in the animation.

Actual Result:
While the initial movement across the screen works as expected, the repositioning does not. Instead of reappearing from the opposite side, each element resets to its original starting position. This breaks the continuity of the loop, causing a noticeable jump in the animation rather than a smooth transition.

This issue is crucial for the visual effect I’m aiming for, and despite various adjustments to my approach, including tweaking the onRepeat logic and experimenting with different GSAP properties, the problem persists. I’m looking for insights or alternative methods to achieve the seamless looping effect for both types of movements.

Trying send a message to a especifc number

async function enviarMensagem(message, number) {
    try {
        
        await sendMessageToWhatsApp(number, message);

        console.log(`Mensagem enviada para ${number} com sucesso`);
    } catch (error) {
        console.error(`Erro ao enviar mensagem para ${number}:`, error);
    }
}

async function sendMessageToWhatsApp(number, message) {

    (async () => {
        try {
            const message = "Isso foi um teste.";
            const number = "**************";
            console.log(`Mensagem enviada para ${number}`)
    
            await enviarMensagem(message, number);
        } catch (error) {
            console.error('Erro durante o envio da mensagem:', error);
        }
    })();
   
    console.log(`Enviando mensagem para ${number}: ${message}`);
     await client.sendMessage(`${number}@c.us`, message);
}

client.initialize();

I’m trying to send a message to a specific number using whatsapp.js
It isn’t showing any log error or something like that and the message isn’t sending.

Any tips?

Message Delete Logging to channel (javascript)

Im trying to make my discord bot log deleted messages like dyno im using discord.js v14 and for some reason the code below is not logging at all but im not receiving any errors and im very confused. To why there is no errors but it is not logging.

const { EmbedBuilder } = require("discord.js");
const { getSettings } = require("@schemas/Guild");

module.exports = async (client, message) => {
  if (message.partial) return;
  if (message.author.bot || !message.guild) return;

  const settings = await getSettings(message.guild);
  if (!settings.modlog_channel) return;

  const logChannel = message.guild.channels.cache.get(settings.modlog_channel);
  if (!logChannel) return;

  if (message.content) {
    // Log deleted message
    const embed = new EmbedBuilder()
      .setColor("#FF5733")
      .setTitle("Message Deleted")
      .addFields(
        { name: "Content", value: message.content },
        { name: "Author", value: `${message.author.tag} (${message.author.id})`, inline: true },
        { name: "Channel", value: message.channel.toString(), inline: true }
      )
      .setFooter({ text: `Deleted at: ${new Date().toLocaleString()}` });

    logChannel.send({ embeds:  });
  }
};

im expecting it to send a embed to the logs channel as shows in code above with who deleted it what they deleted and so on.

Markers are not showing up on Leaflet map when I embed it in squarespace website

I made a leaflet map for work and uploaded it to our website. The markers are all defaulting to the “error” replacement marker that leaflet puts in when you direct it to an image file that doesn’t exist, and my popups aren’t working either. How do I get my markers back?

Here is an example line of code from the map:

//RTC Transit
var rtcIcon = L.icon({
iconUrl: 'RTC_Transit_LOGO.png',
iconSize: [35, 35],
});
var singleMarker = L.marker([36.1716, -115.1391], {icon:rtcIcon});
var popup = singleMarker.bindPopup('<a 
href="https://www.rtcsnv.com/">RTC Southern Nevada').openPopup() 
popup.addTo(map)

object undefined issue in Javascript

const fetchBelongTo = () => {
    fetch(
      `http://localhost/FoodDeliverySystem/api/Restaurant/fetchBelongsto?bid=${state.b_id}`
    )
      .then((response) => response.json())
      .then((data) => {
        setBelongsTo(data);
        if (data.length > 0) {
          fetchFoodItem(data[0]?.BelongsTo?.category);
          // Update belongstoData with the first item from the fetched data
          setBelongsToData({
            f_id: data[0]?.BelongsTo.f_id || "",
            res_id: localStorage.getItem("res_id"),
            b_id: state.b_id,
            f_ingredients: data[0]?.BelongsTo.f_ingredients || "",
            description: data[0]?.BelongsTo.description || "",
            taste: data[0]?.BelongsTo.taste || "",
          });

          console.log(data[0].BelongsTo.f_image);
        }
      })
      .catch((error) => {
        console.error("Error fetching Belongto:", error);
      });
  };

in the above code when i print console.log(data[0]

{
    "BelongsTo": {
        "f_id": 162,
        "res_id": 1012,
        "b_id": 25,
        "f_ingredients": "Ice , Cream , flavour, vanilla,artifical sweetners",
        "description": "Jameel Sweets ICeCream  taste  it bite it",
        "taste": "sweets",
        "f_image": "99ea8109-d117-4231-8cf6-20c300359f8d.jpeg"
    },
    "FoodItem": {
        "f_id": 162,
        "f_name": "Madni IceCream",
        "f_category": "IceCream"
    }
}

I get this objects
and when i console.log

console.log(data[0].BelongsTo);

i get this

{
    "f_id": 162,
    "res_id": 1012,
    "b_id": 25,
    "f_ingredients": "Ice , Cream , flavour, vanilla,artifical sweetners",
    "description": "Jameel Sweets ICeCream  taste  it bite it",
    "taste": "sweets",
    "f_image": "99ea8109-d117-4231-8cf6-20c300359f8d.jpeg"
}

now i want to print or save data of f_image
i am typing

 console.log(data[0].BelongsTo.f_image);

i get undefined

I tried to console.log (data[0].belongsto.f_image);
but i get undefined
so in future if i get f_image i will save in global variable

Affiliate tracking via imagepixel cookies

Anyone ever comes under a situation.. how affiliate marketing platform track their conversion via cookies..can anyone suggest me the code in nodejs to track and get the third party cookies data through image pixel postback..

Anyone have the answer than please share the code.

Receiving HTML response from API instead of JSON

I am trying to consume an API inside of a useEffect hook and it’s leading to CORS issue.
To resolve this I am trying to set up proxy middleaware. After this I am not getting the CORS issue but instead of the JSON response from the API, I am receiving a HTML body. I am not really sure what and how to resolve this as I am learning React and not really sure where to look into this.

proxy middleware

created a addProxyMiddleware.js file inside ‘../server/addProxyMiddleware’ and added this code –

const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function addProxyMiddleware(app){
    app.use('/dapi', createProxyMiddleware({
        target: 'https://www.apiUrl.com',
        changeOrigin: true
    }));
}

inside of bodyComp.js component (where I am consuming the API), added this code –

import { useEffect, useState } from "react";
const BodyComp = () => {

    const [restaurantList, setrestaurantList] = useState(resDataList);
    useEffect(()=>{
        fetchData();
    },[]);

    const fetchData = async () => {
        console.log('fetchData');
        const data = await fetch(
            "/dapi/restaurants/list/v5?lat=28.6105073&lng=77.1145653&is-seo-homepage-enabled=true&page_type=DESKTOP_WEB_LISTING"
        );

        const jsonData = await data.json();
        console.log(jsonData);
    };
    return(  
        <div className="bodyCls">
        </div>
    );
}
export default BodyComp;

After this I am receiving below response in the console –

Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON