weaspyrint does not render uploaded image from database

So here is my html code for the pdf

<div class="cont">
     <img class="logo1" src="{% static 'upload/' %}{{ wmsu_logo.img_name }}" />

     <div>
       <p>Republic of the Philippines</p>
       <p>Western Mindanao State University</p>
       <p>{{ syllabus.college }}</p>
       <p class="title">DEPARTMENT OF {{ syllabus.department }}</p>
     </div>

     <img class="logo2" src="{% static 'upload/' %}{{ course_logo.img_name }}" />

     <img class="logo3" src="{% static 'upload/' %}{{ iso_logo.img_name }}" />
</div>

and this is the view where it processes things.

def pdf(request, id):
    # ---------- SYLLABUS ----------
    syllabus = get_object_or_404(Syllabus, user_id=request.user, id=id)

    # ---------- SYLLABUS TEMPLATE ----------
    syllabus_template = get_object_or_404(Syllabus_Template, user_id=request.user, id=syllabus.syllabus_template_id.id)
    wmsu_logo = Logo.objects.get(syllabus_template_id=syllabus_template, name='wmsu_logo')
    course_logo = Logo.objects.get(syllabus_template_id=syllabus_template, name='course_logo')
    iso_logo = Logo.objects.get(syllabus_template_id=syllabus_template, name='iso_logo')
    
    total_term_percentage = midterm.term_percentage + finalterm.term_percentage   

    template = loader.get_template('PDF_template/template.html') # Load HTML template
    html_string = template.render({

        'wmsu_logo': wmsu_logo,
        'course_logo': course_logo,
        'iso_logo': iso_logo,
}) # Render the template

    # Generate the PDF using WeasyPrint
    pdf = HTML(string=html_string, base_url=request.build_absolute_uri()).write_pdf()

    # Create an HttpResponse with the PDF content
    response = HttpResponse(pdf, content_type='application/pdf')
    # Display in the browser
    response['Content-Disposition'] = 'inline; filename=Syllabus' + str(datetime.datetime.now()) + '.pdf'

    return response

I need the uploaded image in the pdf conversion in weasyprint. I already deployed this in pythonanywhere. When I use the local file the image renders but when I deploy it, it does not render the image. I tried every possible way. Please recommend a fix to this I really need it. Please help.

How to use Javascript to increment displayed/hidden variables OnClick [closed]

I have a checkout page, and on the page there is a form with radio buttons representing upgrade options. The first (and initially selected) radio button represents the base price option, while the other three represent various price upgrades. The current price is determined from a php session variable and displayed on the page.

Using Javascript, I assume, what is the best method for creating an onclick event for each radio button option that increments/decrements both a displayed variable and one hidden in a form input field by the specified amount?

Tried an onclick method I found to send variable to a form field, but couldn’t get it working.

Iterating through an array is returning the index not the value [duplicate]

I have this block of code for filtering through two arrays then assigning the matched value to a 3rd array. All acts correctly however….. in the for(y in groupsToShow) I seem to get y= “0”,”1″,”2″… etc instead of what I want which is it to step through the values [“outlet”, “recess can”, “heaters”, “meter can”, “panel”, “air conditioner”, “switches”, “plate covers”].

Looks like the y is the index being returned. What am I missing and what is causing the index to be returned? For reference the results is an array of object.

async loadGroups() {
    var groupsToShow = ["outlet", "recess can", "heaters", "meter can", "panel", "air 
     conditioner", "switches", "plate covers"] 
    var groupList = []
    var results: any[] = (await this.groupsApiService.GetAll({
      path: {version: this.apiVersion},
      query: {}
    }).toPromise())?.data

    for (var i = 0; i < results.length; i++) {
       for (let y in groupsToShow){ // getting the y = "0" | "1" ...etc.
         if (results[i].name.includes(y)) {
         this.groupList!.push(results[i]);
         }
       }
    }
   console.log(this.groupList) //undefined
 }

I have also tried this variation with Object.values()

async loadGroups() {
    var groupsToShow = ["outlet", "recess can", "heaters", "meter can", "panel", "air 
     conditioner", "switches", "plate covers"] 
    var groupList = []
    var results: any[] = (await this.groupsApiService.GetAll({
      path: {version: this.apiVersion},
      query: {}
    }).toPromise())?.data

    for (var i = 0; i < results.length; i++) {
       for (let y in Object.values(groupsToShow)){ // getting the y = "0" | "1" ...etc.
         if (results[i].name.includes(y)) {
         this.groupList!.push(results[i]);
         }
       }
    }
   console.log(this.groupList) //undefined
 }

v4 Chart.js positive negative line color

I have an Ajax filter that pulls positive and negative values from posts. These values I am showing using chart.js. All works but i want to make the lines between two points different color.

For example values [1000,-500,1000,-500]
From 1000 to 0 the line color to be blue and from 0 to -500 yellow. Then from -500 to 0 yellow and from 0 to 1000 blue etc.
I tried to experiment with the plugin option but without much of success using the examples here – Chart JS plugin to change line color depending on value

Here is my code so far:

(function($) {
    $(document).ready(function ($) {
        // Variable to store the chart instance
        var myLineChart;
            
        // Variables to store the previous values of dropdowns
        var prevSport = $('#sport').val();
        var prevSportType = $('#sport_type').val();
        
        $('#filter').on('click', function () {
            // Get the current values of dropdowns
            var currentSport = $('#sport').val();
            var currentSportType = $('#sport_type').val();

            if (!currentSport || !currentSportType) {
                $.ajax({
                    type: 'post',
                    url: ajax_object.ajax_url,
                    data: {
                        action: 'filter_posts',
                        sport: currentSport,
                        sport_type: currentSportType,
                    },
                    success: function (response) {
                        if (response.error) {
                            $('.notice').html(response.message);
                            return;
                        } else {
                            $('.notice').remove();
                        }
                        // Destroy existing chart if it exists
                        if (myLineChart) {
                            myLineChart.destroy();
                        }

                        // Create a new chart
                        updateChart(response);
                    },
                });
                return;
            }

            // Check if dropdown values have changed
            if (currentSport !== prevSport || currentSportType !== prevSportType) {
                // Update previous dropdown values
                prevSport = currentSport;
                prevSportType = currentSportType;

                // Perform AJAX request only if dropdown values have changed
                $.ajax({
                    type: 'post',
                    url: ajax_object.ajax_url,
                    data: {
                        action: 'filter_posts',
                        sport: currentSport,
                        sport_type: currentSportType,
                    },
                    success: function (response) {
                        if (response.error) {
                            $('.notice').html(response.message);
                            return;
                        } else {
                            $('.notice').remove();
                        }
                        // Destroy existing chart if it exists
                        if (myLineChart) {
                            myLineChart.destroy();
                        }

                        // Create a new chart
                        updateChart(response);
                    },
                });
            }
        });

        function updateChart(data) {
            var ctx = document.getElementById('myLineChart').getContext('2d');
            
            myLineChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: data.labels,
                    datasets: [{
                        data: data.datasets[0].data,
                        borderColor: function(context) {
                            const chart = context.chart;
                            const {ctx, chartArea} = chart;

                            if (!chartArea) {
                                // This case happens on the initial chart load
                                return;
                            }

                            // Create the gradient
                            const gradient = ctx.createLinearGradient(0, chartArea.bottom, 0, chartArea.top);
                            gradient.addColorStop(0, 'blue'); // Change this color to your preference
                            gradient.addColorStop(1, 'yellow'); // Change this color to your preference

                            return gradient;
                        },
                    }],
                },
                options: {
                    scales: {
                        y: {
                            min: -3000,
                            max: 3000,
                        },
                    },
                    plugins: {
                        legend: {
                            display: false, // Set display property to false to hide the legend
                        },
                    },
                },
            });
        }
    });
})(jQuery);

VS Code Not Highlighting Errors/Missing Imports

VS Code stopped highlighting errors/missing imports. Using Prettier, ESLint extensions, but no luck.
I tried to reinstall again, didn’t work still. Any suggestions?

More:
Version: 1.84.2 (user setup)
Commit: 1a5daa3a0231a0fbba4f14db7ec463cf99d7768e
OS: Windows_NT x64 10.0.19045

Thanks!

Is it possible to integrate a web browser inside webpage?

I want to integrate web browser inside my code where I run different websites, web surfing. I tried Google Programmable search engine but it we can only surf on that when we will try to open it then it will show either on same tab or different tab.

Instead showing on tab I want it will show results within the component or part where search engine working.

If it’s not possible then how Browserstack is working ? Is I am doing something wrong ?

Optimizing Colisons to stop infinite colisions

I’m doing a simple project of simulating how gravity affects diferent objects in canvas but i’m having a problem with my code.

The problem is that my objects are causing infinite colisions when there are to many objects on the bottom of the canvas.

`const W = canvas.width,
        H = canvas.height;

      class BasketBall {
        constructor(x, y) {
          this.R = 10;
          this.COLOR = "orange";
          this.outlineColor = "black";
          this.outlineWidth = 1;
          this.lastCollisionTime = 0;
          this.x = x;
          this.y = y;
          this.A = 0.2;
          this.dX = 0; // Velocidade no eixo X
          this.dY = 0;
        }

        draw() {
          ctx.fillStyle = this.COLOR;
          ctx.strokeStyle = this.outlineColor; // Set the outline color
          ctx.lineWidth = this.outlineWidth; // Set the outline width
          ctx.beginPath();
          ctx.arc(this.x, this.y, this.R, 0, 2 * Math.PI);
          ctx.fill();
          ctx.stroke(); // Stroke the circle to create an outline
        }

        update() {
          this.x += this.dX;
          this.y += this.dY;

          if (this.x - this.R < 0) {
            this.x = this.R;
            this.dX = -this.dX;
          }
          if (this.x + this.R > W) {
            this.x = W - this.R;
            this.dX = -this.dX;
          }

          if (this.y > H - this.R) {
            this.y = H - this.R;
            this.dY = -this.dY * 0.6; // Inverta a velocidade vertical e reduza a força do salto
          } else {
            this.dY += this.A;
            this.y += this.dY;
          }
        }

        getButtonColor() {
          return this.COLOR;
        }
      }

      class Cannon {
        constructor(x, y) {
          this.R = 20;
          this.COLOR = "black";
          this.outlineColor = "black";
          this.outlineWidth = 1;
          this.lastCollisionTime = 0;
          this.x = x;
          this.y = y;
          this.A = 0.5;
          this.dX = 0;
          this.dY = 0;
        }

        draw() {
          ctx.fillStyle = this.COLOR;
          ctx.strokeStyle = this.outlineColor; // Set the outline color
          ctx.lineWidth = this.outlineWidth; // Set the outline width
          ctx.beginPath();
          ctx.arc(this.x, this.y, this.R, 0, 2 * Math.PI);
          ctx.fill();
          ctx.stroke(); // Stroke the circle to create an outline
        }

        update() {
          this.x += this.dX; // Atualize a posição no eixo X
          this.y += this.dY;

          // Adicione lógica para lidar com colisões nas bordas do canvas
          if (this.x - this.R < 0) {
            this.x = this.R;
            this.dX = -this.dX * 0.1; // Inverta e reduza a velocidade no eixo X
          }
          if (this.x + this.R > W) {
            this.x = W - this.R;
            this.dX = -this.dX * 0.1; // Inverta e reduza a velocidade no eixo X
          }

          if (this.y > H - this.R) {
            this.y = H - this.R;
            this.dY = -this.dY * 0.1; // Inverta e reduza a velocidade no eixo Y
          } else {
            this.dY += this.A;
            this.y += this.dY;
          }
        }

        getButtonColor() {
          return this.COLOR;
        }
      }

      class PingPong {
        constructor(x, y) {
          this.R = 5;
          this.COLOR = "white";
          this.outlineColor = "black";
          this.outlineWidth = 1;
          this.lastCollisionTime = 0;
          this.x = x;
          this.y = y;
          this.A = 0.3;
          this.dX = 0; // Velocidade no eixo X
          this.dY = 0;
        }

        draw() {
          ctx.fillStyle = this.COLOR;
          ctx.strokeStyle = this.outlineColor; // Set the outline color
          ctx.lineWidth = this.outlineWidth; // Set the outline width
          ctx.beginPath();
          ctx.arc(this.x, this.y, this.R, 0, 2 * Math.PI);
          ctx.fill();
          ctx.stroke(); // Stroke the circle to create an outline
        }

        update() {
          this.x += this.dX;
          this.y += this.dY;

          if (this.x - this.R < 0) {
            this.x = this.R;
            this.dX = -this.dX;
          }
          if (this.x + this.R > W) {
            this.x = W - this.R;
            this.dX = -this.dX;
          }

          if (this.y > H - this.R) {
            this.y = H - this.R;
            this.dY = -this.dY * 0.8; // Inverta a velocidade vertical e reduza a força do salto
          } else {
            this.dY += this.A;
            this.y += this.dY;
          }
        }

        getButtonColor() {
          return this.COLOR;
        }
      }

      const objects = [];

      canvas.addEventListener("click", (event) => {
        const rect = canvas.getBoundingClientRect();
        const mouseX = event.clientX - rect.left;
        const mouseY = event.clientY - rect.top;

        let newObject;

        switch (currentObjectClass) {
          case "BasketBall":
            newObject = new BasketBall(mouseX, mouseY);
            break;
          case "Cannon":
            newObject = new Cannon(mouseX, mouseY);
            break;
          case "PingPong":
            newObject = new PingPong(mouseX, mouseY);
            break;
        }

        if (newObject) {
          objects.push(newObject);
        }
      });

      // Função de detecção de colisões
      function checkCollision(obj1, obj2) {
  const dx = obj1.x - obj2.x;
  const dy = obj1.y - obj2.y;
  const distanceSquared = dx * dx + dy * dy;
  const sumOfRadiiSquared = (obj1.R + obj2.R) ** 2;

  return distanceSquared < sumOfRadiiSquared;
}


      // Lógica de colisões
      function handleCollisions() {
        for (let i = 0; i < objects.length; i++) {
          for (let j = i + 1; j < objects.length; j++) {
            const obj1 = objects[i];
            const obj2 = objects[j];

            if (checkCollision(obj1, obj2)) {
              const dx = obj2.x - obj1.x;
              const dy = obj2.y - obj1.y;
              const distance = Math.sqrt(dx * dx + dy * dy);

              if (distance < obj1.R + obj2.R) {
                const angle = Math.atan2(dy, dx);
                const overlap = (obj1.R + obj2.R - distance) * 0.5;

                const targetX1 = obj1.x - Math.cos(angle) * overlap;
                const targetY1 = obj1.y - Math.sin(angle) * overlap;
                const targetX2 = obj2.x + Math.cos(angle) * overlap;
                const targetY2 = obj2.y + Math.sin(angle) * overlap;

                obj1.x = targetX1;
                obj1.y = targetY1;
                obj2.x = targetX2;
                obj2.y = targetY2;
              }
            }
          }
        }
      }`

I tried to change the handleCollisions() and the objects.

i wanted the objects to eventualy stop and stack on top of eachother verticaly.

How to enforce a specific timezone ignoring system time

I am trying to convert an ISO date to EST, so that the user always sees EST, regardless of the system.

Like so

luxon.DateTime("2023-04-16T03:00:00Z").setZone("EST").toFormat('ttt')

Yet it always comes out like so:

10:00:00 PM GMT-5

I want:

10:00:00 PM EST

What am I doing wrong? I know EST is IANA compliant.

how to search and loop array of object for particular key using recursion

I have a array of objects

  • Some objects id some are not
  • those having id can present with either “split” or “relation” key not both
  • inside split there can be another split or relation
  • now I need to read all relation present by digging deeply

I need output like below:

let _rel = [
    {"relation": "a"},
    {"relation": "b"}
]
// my try which is not working 
const getRelations = (arr, _rel=[]) => {
    for(let {uuid, relations, split} of arr){
        if(uuid) {
            if(relations) [..._rel, relations]
            else if(split) {
                getRelations(split)
            }
        }
    }
    return _rel    
}
getRelations(arr)

Input:

let arr = [
            {"start_offset": 0},
            {
                "uuid": "100",
                "relations": [
                    {
                        "relation": "a",
                    }
                ]            
            },
            {"start_offset": 355},
            {
                "uuid": "200",
                "split": [
                    {
                        "uuid": "300",
                        "split": [
                            {
                                "uuid": "400",
                                "relations": [
                                    {
                                        "relation": "b",
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        "uuid": "500",
                    }
                ],
            },
            {"start_offset": 689}
]

// my try which is not working 
const getRelations = (arr, _rel=[]) => {
    for(let {uuid, relations, split} of arr){
        if(uuid) {
            if(relations) [..._rel, relations]
            else if(split) {
                getRelations(split)
            }
        }
    }
    return _rel    
}
getRelations(arr)

I need to get the alt attribute of the clicked image element. The alt value of multiple images on click. How to do in tag manager JavaScript?

This is the exact code that i’m using currently.

function ()

{

if (document.querySelector(“#wrapper > section.panel.spacer–banner.bg–banner.flex-column.first > div > div > div.col-lg-5 > div > ul > li:nth-child(1) > a > img”).onclick = true) {

return “playstore”;

}

else if (document.querySelector(“#wrapper > section.panel.spacer–banner.bg–banner.flex-column.first > div > div > div.col-lg-5 > div > ul > li.d-none.d-xl-block > button”).onclick = true) {

return “appstore”;

}

else {

return “”;

}

}

I need to get the image alt attribute of any clicked element in a web page (via tag manager). In tag manager, I’m tracking events. For the events, I need to pass the parameter as image alt value. Can someone help with the exact js code?

Base64 decode failed. I met a very strange problem. I tried to decode this string, but the decoding failed

Original string:

SELECT product_name FROM order_info GROUP BY product_name HAVING COUNT(*) > 6;

Base64 string:

U0VMRUNUIHByb2R1Y3RfbmFtZQ0gRlJPTSBvcmRlcl9pbmZvDSBHUk9VUCBCWSBwcm9kdWN0X25hbWUNIEhBVklORyBDT1VOVCgqKSA+IDY7**

Java decode failed:

String test_str = "U0VMRUNUIHByb2R1Y3RfbmFtZQ0gRlJPTSBvcmRlcl9pbmZvDSBHUk9VUCBCWSBwcm9kdWN0X25hbWUNIEhBVklORyBDT1VOVCgqKSA+IDY7";
byte[] decodedBytes = Base64.getDecoder().decode(test_str);
String strrrr = new String(decodedBytes);
System.out.println("strrrr length  :   " + strrrr.length()); // 81
System.out.println(" strrrr : " + strrrr);  //  HAVING COUNT(*) > 6;
// tell me thy ???

python decode failed:

import base64
test_str = "U0VMRUNUIHByb2R1Y3RfbmFtZQ0gRlJPTSBvcmRlcl9pbmZvDSBHUk9VUCBCWSBwcm9kdWN0X25hbWUNIEhBVklORyBDT1VOVCgqKSA+IDY7"
decoded_str = base64.b64decode(test_str).decode('utf-8')
print(len(decoded_str))  # 81
print(decoded_str)  #  HAVING COUNT(*) > 6;
#  Why ???

JavaScript decode success:

const base64String = "U0VMRUNUIHByb2R1Y3RfbmFtZQ0gRlJPTSBvcmRlcl9pbmZvDSBHUk9VUCBCWSBwcm9kdWN0X25hbWUNIEhBVklORyBDT1VOVCgqKSA+IDY7"; // base64 string
const decodedString = atob(base64String); 
console.log(decodedString); // SELECT product_name FROM order_info GROUP BY product_name HAVING COUNT(*) > 6;

How can I fix the problem?

How to execute the command npx serve in docker container?

I have dockerized a expo react native web app.

And I created the production folder: web-build witht the command: npx expo export:web

And if I go to the directory web-build And I execute the command: npx serve

Then I can browse to http://localhost:3000/ and the app works

But how to run this from docker container?

my dockerfile looks like:

# pull base image

FROM node:lts-alpine


ARG NODE_ENV=production
ENV NODE_ENV $NODE_ENV


ARG PORT=19006
ENV PORT $PORT
EXPOSE $PORT 19001 19002


ENV NPM_CONFIG_PREFIX=/home/node/.npm-global
ENV PATH /home/node/.npm-global/bin:$PATH
RUN npm i --unsafe-perm --allow-root -g npm@latest expo-cli@latest

RUN mkdir /opt/dwl_frontend
WORKDIR /opt/dwl_frontend
ENV PATH /opt/dwl_frontend/.bin:$PATH
COPY package.json yarn.lock ./
RUN yarn
RUN yarn install


WORKDIR /opt/dwl_frontend

COPY ./ ./ 

RUN npx serve

ENTRYPOINT ["yarn", "run", "web"]

and my package.json file looke:

{
    "name": "dierenwelzijnapp",
    "version": "1.0.0",
    "main": "node_modules/expo/AppEntry.js",
    "scripts": {
        "start": "expo start, react-app-rewired start ",
        "android": "expo start --android",
        "ios": "expo start --ios",
        "web": "expo start --web",
        "eject": "expo eject",
        "lint": "eslint . --ext .js",
        "postinstall": "patch-package"
    },

But if I do a docker compose -f docker-compose-prod.yml build it hangs on this command:

RUN npx serve I mean it doesnt go futher.

Question: how to make use of the folder web-build within docker?

What means “Uncaught SyntaxError: ambiguous indirect export: default” and why does this happens?

I’m working on a simple presentation website made with Vite and React. In my code I use JavaScript and I encounter this error in my App.jsx file and I don’t understand what’s wrong. Can someone bring some light here? Thanks.

error: Uncaught SyntaxError: ambiguous indirect export: default

my code:

import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Navbar from "./components/Navbar/Navbar";
import Footer from "./components/Footer/Footer";
import Home from "./pages/Home";
import About from "./pages/About";
import Contact from "./pages/Contact";

const App = () => {
  return (
    <Router>
      <Navbar />
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/contact" element={<Contact />} />
      </Routes>
      <Footer />
    </Router>
  );
};

export default App;

I tried to replace the const App with functin App but nothing changed the situation.