Waffle Chart Issue

 var gallery;
var waffles = [];
var data;
var days = ["Activities Weekday", "Activities Weekends", "Other", "Favourite Activity", "How often dinner", "How often friends", "Activity to do more"];
var values = ['Watch TV', 'Play Computer Games', 'Engage in Hobbies', 'Go out for Dinner', 'Go to the Pub', 'Watch a show', 'Go for a walk', 'Meet Friends', 'Weekend Away', 'Watch a band', 'Other'];

function preload() {
  // Load the data here so it's ready before setup runs.
  data = loadTable('./data/myData.csv', 'csv', 'header', function() {
    console.log("Data loaded successfully");
  }, function() {
    console.log("Error loading data");
  });
}

function setup() {
  // Create a canvas to fill the content div from index.html.
  var c = createCanvas(1024, 576);
  c.parent('app');

  // Create a new gallery object.
  gallery = new Gallery();

  // Add other visualization objects to the gallery.
  gallery.addVisual(new TechDiversityRace());
  gallery.addVisual(new TechDiversityGender());
  gallery.addVisual(new PayGapByJob2017());
  gallery.addVisual(new PayGapTimeSeries());
  gallery.addVisual(new ClimateChange());
  gallery.addVisual(new Offences());
  gallery.addVisual(new PetrolPrices());
//  gallery.selectVisual(new Waffle());
    
    
   // Create one Waffle instance that manages all seven waffle charts.
  if (data && data.getRowCount() > 0) {
   gallery.addVisual(new Waffle(20, 20, 200, 200, 10, 10, data, days, values));
//    gallery.addVisual(ne Waffle()); // Add the single Waffle visualization to the gallery
    gallery.selectVisual(waffles); // Select the Waffle visual by default
  } else {
    console.log("Data is not loaded or empty.");
  }
}


function draw() {
  background(255);

  if (gallery.selectedVisual != null) {
    gallery.selectedVisual.draw();
      
      for(var i = 0; i < days.length; i++){
          waffles[i].draw();
        
      }
      for(var i = 0; i < waffles.length; i++){
          waffles[i].checkMouse(mouseX, mouseY)
      }
  }
} 

thtas script

function Waffle(x, y, width, height, boxes_across, boxes_down, table, days, values) {
  this.name = "Evening Activities";
  this.id = "Waffle";

  this.x = x;
  this.y = y;
  this.width = width;
  this.height = height;
  this.boxes_across = boxes_across;
  this.boxes_down = boxes_down;
  this.table = table;
  this.days = days;
  this.values = values;
  this.currentDayIndex = 0; // Track the currently displayed day
  this.boxes = [];
  this.categories = [];
  this.loaded = false;

  this.preload = function() {
    // Load data if needed
    this.loaded = true;
    this.setup();
  };

  this.setup = function() {
    if (!this.loaded) {
      console.log('Data not yet loaded');
      return;
    }
    this.addCategories(this.days[this.currentDayIndex]);
    this.addBoxes();
  };

  this.addCategories = function(day) {
    console.log('Adding categories for day:', day);
    var colours = ["aqua", "yellow", "purple", "red", "blue", "green", "orange", "pink", "black", "grey"];
    this.categories = []; // Reset categories for the new day
    for(var i = 0; i < this.values.length; i++) {
      this.categories.push({
        "name": this.values[i],
        "count": 0,
        "colour": colours[i % colours.length]
      });
    }

    var column = this.table.getColumn(day);
    for(var i = 0; i < column.length; i++) {
      var catLocation = this.categoryLocation(column[i]);
      if(catLocation != -1) {
        this.categories[catLocation].count++;
      }
    }

    for(var i = 0; i < this.categories.length; i++) {
      this.categories[i].boxes = Math.round((this.categories[i].count / column.length) * (this.boxes_down * this.boxes_across));
    }
    console.log('Categories added for day:', this.categories);
  };

  this.categoryLocation = function(categoryName) {
    for(var i = 0; i < this.categories.length; i++) {
      if(categoryName === this.categories[i].name) {
        return i;
      }
    }
    return -1;
  };

  this.addBoxes = function() {
    console.log('Adding boxes for day');
    var currentCategory = 0;
    var currentCategoryBox = 0;
    const boxWidth = this.width / this.boxes_across;
    const boxHeight = this.height / this.boxes_down;

    this.boxes = []; // Reset boxes for the new day
    for(var i = 0; i < this.boxes_down; i++) {
      this.boxes.push([]);
      for(var j = 0; j < this.boxes_across; j++) {
        if (currentCategoryBox === this.categories[currentCategory].boxes) {
          currentCategoryBox = 0;
          currentCategory++;
        }
        this.boxes[i].push(new Box(this.x + (j * boxWidth), this.y + (i * boxHeight), boxWidth, boxHeight, this.categories[currentCategory]));
        currentCategoryBox++;
      }
    }
    console.log('Boxes added for day:', this.boxes);
  };

  this.draw = function() {
    for(var i = 0; i < this.boxes.length; i++) {
      for(var j = 0; j < this.boxes[i].length; j++) {
        if(this.boxes[i][j].category != undefined) {
          this.boxes[i][j].draw();
        }
      }
    }
  };

  this.checkMouse = function (mouseX, mouseY) {
    for(var i = 0; i < this.boxes.length; i++) {
      for(var j = 0; j < this.boxes[i].length; j++) {
        if(this.boxes[i][j].category != undefined) {
          const mouseOver = this.boxes[i][j].mouseOver(mouseX, mouseY);
          if(mouseOver != false) {
            push();
            fill(255);
            textSize(20);
            const tWidth = textWidth(mouseOver);
            textAlign(LEFT, TOP);
            rect(mouseX, mouseY, tWidth + 20, 40);
            fill(255);
            text(mouseOver, mouseX + 10, mouseY + 10);
            pop();
            break;
          }
        }
      }
    }
  };

//  this.updateDay = function(index) {
//    if (index >= 0 && index < this.days.length) {
//      this.currentDayIndex = index;
//      this.setup(); // Update the Waffle table for the new day
//    }
//  };
}

then another

function Box(x, y, width, height, category) {
    
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    this.category = category;

    this.mouseOver = function(mouseX, mouseY) {
        if (mouseX > this.x && mouseX < this.x + this.width &&
            mouseY > this.y && mouseY < this.y + this.height) {
            return this.category.name;
        }
        return false;
    };

    this.draw = function() {
        fill(this.category.colour);
        rect(this.x, this.y, this.width, this.height);
    };
}

i am making a vis app and all other areas are find, but cannot get 7 waffle charts for each day column of code very frustrating. either i get 7 buttons or i get 1 button 1 chart.

enter image description here the image will show what i mean.

ived tried just adding waffle to the gallery then it stops others from working, looping through again i get boxes on each other visualisation. it is probably something so small but i just cannot figure it out

Error when trying to convert base64 encoded audio data and play via web audio api

I have some data that comes in on a websocket from https://play.ai/business

{"type":"audioStream","data":"//uyxPaD6eFa4g7vLcyOK12B3WU4RuTGAgReYNDBVKBheIRrquBo4yEhPRdQ0Fq0kSoILOIQxkeOLWhBBekaDUZb5kKqLFVzQM86nlgEzR4cHDPYh6GQF1HQBopfEoBCoLdFN3bLiKxBjyq7NoGToLBK/FGw4RyGAMKVuWi2VYjK4g579LWjjtQ/Id2bedirbmeWp/WdW3UwraUATA+GCOHO7k2vmQjNXLVMlkVgw3QsTM3E8MdG9Y1kmMcgTM1c3kXHII0hZOWIBCRlvBIBBz8YcMmNhAFFjQSwxshNBEDHzQysyMuKzWCYyw1OXcGMgPwRojB5wWGocCnThTHQQsCZQpqigQkx7zaTBKZDS7ogEHBVMh1k0AAUiENM6DIUFDLHlprNlFpiTDUAFDDoBUQKCBBYiYNw8ouSsXoki/4dyQFCx6UhhgE3AERMIpDVGhFgWBNQBBMWZCAkI1V1lCIZQ8iBEQCYhaAtOAgiwKu0OUWsNGDpRctlBimg0dQYmLWfAT/RIswXZZgVjw4jwGGkoSEZghp7FnU72LonI2wERAMAKgqyU80vkqEeE+3lbRkzlMtf2Rzkml+VPTzstjt25fp7G+4ays0yGHmCCZ1ShJrdKNmYIDYY8YkRCEyYggepg3ArGQRZqE2ZUnmSFRzu0Bwcy5HNaKDFzcy4pNFNjARwzs0CooaSVGGH5nh2F0w0dYMEEzMBMxoRGDM3QpNFOkOBgIyAnkwAVdU1FxgYi7NJ8wDQh0z6gEyaAoXYInlAESh0gxxTahAxw0KZJyYbQQAWYzpnBiIcVJMxcraQDEU4ChMtQdFAhqkkSBJJJFjJ"}

I want to convert this data to binary and output it in the users browser as audio. The play ai docs just show this documentation for that: https://docs.play.ai/api-reference/websocket#sample-code-for-receiving-audio

The code I have looks right – I convert the base64 data to binary and then try to play it via web audio api:

     myWs = new WebSocket('wss://api.play.ai/v1/talk/MY_AGENT_ID');
    myWs.onopen = () => {
      console.log('connected!');
      myWs.send(JSON.stringify({ type: 'setup', apiKey: 'MY_API_KEY' }));

  myWs.onmessage = async (message) => {
    const event = JSON.parse(message.data);
    console.log(message.data);
    try {
    if (event.type === 'audioStream') {
      const base64String = event.data;
       // deserialize event.data from a base64 string to binary
      const arrayBuffer = Uint8Array.from(atob(base64String), c => c.charCodeAt(0)).buffer
      // enqueue/play the binary data at your player

      const audioContext = new (window.AudioContext || window.webkitAudioContext)();

      audioContext.decodeAudioData(arrayBuffer)
      .then((audioBuffer) => {
        // Step 3: Play the audio data
        const source = audioContext.createBufferSource();
        source.buffer = audioBuffer;
        source.connect(audioContext.destination);
        source.start(0);
      })
      .catch(e => {console.error(e)});
    }
  } catch(e) {
    console.log('error', e);
  }
};
    }

However, I get an error in the console when running this code:

Failed to execute ‘decodeAudioData’ on ‘BaseAudioContext’: Unable to decode audio data

I’ve searched and tried many solutions. It seems that one other person is also seeing the same issue in this repo: https://github.com/Bradymck/Play.ai-Test

Somehow the data is not in the right format but I’m not sure how to fix it.

How to use Draw2D

I am new at web development and I would like to use Draw2D to make a drawing tool. My problem is I didn’t know how to run the given examples and implement it to my project. I can’t also find a tutorial for this.

I would like to use it because it is free unlike the more popular React Flow.

Below is the example that I tried to run on Github Sandbox but it didn’t work.

https://github.com/freegroup/draw2d/tree/master/examples/galerie_shape_basic

I am not also familiar on how I can implement it to my project. I am more familiar on scripts on adding libraries.

Below are the only instructions which I didn’t understand because it is different from other libraries.

Local Development:

nvm use v14.15.0

npm install
DIR=/examples yarn dev

Build:

./build.sh

Publish new version:

npm version patch
npm publish

The link to the answer similar to my question is now unavailable.

https://github.com/freegroup/draw2d/tree/master/examples/galerie_shape_basic

Also, is there an alternative library that is also free and does the same as Draw2D? Especially the connection of multiple objects.

Guidance needed on simple Ajax(?) update

layout

(Beginner alert)

I’m working on a website with a headless CMS and completely custom front end.

What I want to achieve is:

Load post list into frame as shown above via API.(I’m comfortable with this, although using php… Which may make things messy for what I want to achieve?)

Then, when a post title is clicked, another API call retrieves the body text for that post ID and displays it in the main body frame as shown in the picture, without page refreshes etc, maybe adding some CSS effect to transition in.

I’m not going to lie, I’ve never done any Java script (which is what I assume I’ll have to use?) and don’t know where to start…

Any assistance to get me going will be appreciated, I’m not necessarily asking for a full solution, just somewhere to start researching-I’ve seen about fetch and things, but it’s the using the click to get the id then making the reload happen in the other frame which is where I’m struggling

Thanks!

Haven’t tried anything yet as I’m unsure of even the method I should be using, is fetch even the right thing or is it something else?

How do I show csv data on html [closed]

I want to show csv data on html but not as a table. I want to show then for example I am creating a blog page and I have the title image content, etc. on csv and I want to show them on html which has a place holder for the style. Is it even possible? Or should I use other tools for this.

I want to create a blog page where I can update my csv and the whole website will be updated according to the filter such as published date, likes or views.

TypeError: Cannot read properties of null (reading ‘useEffect’) when using a locally linked Excalidraw package in React

I’m attempting to use the Excalidraw library as a locally linked package in my React application. After setting up the package with yarn link, I imported Excalidraw into my component:

import { Excalidraw } from "@excalidraw/excalidraw";

However, when I run my app, I get the following error:

Uncaught TypeError: Cannot read properties of null (reading 'useEffect') at useEffect (react.development.js:1634:1) at ExcalidrawBase (index.tsx:84:1) ...

I’ve ensured that both my app and the Excalidraw package are using React 18.3.1. The error seems related to mismatched React versions or an issue with how the package is built. I’ve also tried updating the build script to externalize React and ReactDOM, but the error persists.

What could be causing this useEffect error, and how can I resolve it?

How can I format an ion-input like accounting.js in Ionic?

I am using Ionic with Angular and have an ion-input for entering a discount amount. I want to format the input similar to how accounting.js (enter link description here)formats numbers, with specific decimal places and a percentage symbol. Here’s my current code:

<ion-input
        #amountInput
        class="input-field"
        style="--padding-end: 20px; text-align: end;"
        placeholder="Amount"
        [(ngModel)]="discountAmount"
        (ngModelChange)="onDiscountAmountChange($event)"
        type="text">
        <p slot="end"></p>
      </ion-input>

I get a “>” appear in my HTML that shouldn’t be there [closed]

I have produced an HTML file that uses some (i.e. loads) of javascript to make the code more flexible.
Sadly, a lot of the javascript is specific to one task, but …
I have written some javascript to populate a div with a table (and do some other “stuff”).
I have used similar javascript to produce a number of tables without issue, but this one is puzzling me.
The table that is frustrating me has an “>” where none should be, and I cannot figure out why.
I am sure it will be an “obvious” error, but I am not familiar with HTML/ … to be confident.
I use a class to have the table displayed without a border (used in a number of other tables).
I generate the code to populate the “div” where some of the code is as follows:-

I am running my webpage off an internal server (Apache2), and I have seen the issue with my tablet and two different Ubuntu laptops, on the following browsers – Brave, Chromium, Edge, Safari and Firefox.

The output of the HTML page is:-

Screenshot of issue

In text (the formatting may not work, but …:-

Edit programme

R> X Programme Name:

The following is the console.log output of the string created over the relevant part.

I would note that in the example below, to try to highlight where the issue is, I added the “R” and “X” around the <td ... > to show where the “>” crops up.

The HTML code I am highlighting in the console.log output is between the two “#”‘s to show if I have added any odd elements.


divstr = #<br>
 <h2>Edit programme</h2>
 <br>
 <table class="tableNoBorder">
 <tr class="tableNoBorder">
 R<td class="tableNoBorder">X #

The HTML from the debug window is as follows (in the “relevant” area!):-


<br>
<h2>Edit programme</h2>
<br>
       
                R&gt;<table class="tableNoBorder">
            <tbody><tr class="tableNoBorder"><td class="tableNoBorder">X

Here,the erroneous “>” appears in a place that doesn’t make sense to me (seen as the “>” before the <table ....

Any clues as to what I am doing wrong would be most appreciated, as I have looked through lots of the code around area, and to ensure the cell, row and table elements are “closed” with the appropriate HTML tags.

Many thanks for any help.

I have replaced the assumed “guilty” tags (<table ..., <tr... & <td ....) with “working ones, without any changes!

A Drag-and-Drop style like in Video Games

I need help with my project.

I’m trying to make a Drag-and-Drop to assign devices to specific positions or cells.

I researched about this but most are Kanban style or drag-and-drop files, which I tried when learning Vue.

when I tried my problem, I couldn’t pull it off or maybe I still lack knowledge of this.

I wanna try this before doing other approaches like Dropdown or modal/popup assignment.

Thank you in advance for the help and insights.

I have an image for visualization. https://imgur.com/a/tAyygBl

How Scope works in Nest js

As per docs if a service is a request scope then the controller depends on it and will be request scope automatically.

Imagine the following dependency graph: CatsController <- CatsService <- CatsRepository. If CatsService is request-scoped (and the others are default singletons), the CatsController will become request-scoped as it is dependent on the injected service. The CatsRepository, which is not dependent, would remain singleton-scoped.

import { Injectable, Scope, Inject } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';

export class CatsService {
  constructor(@Inject(REQUEST) private request: Request) {}
}

so in the example, that I share CatsService injected REQUEST which is the request scope then CatsService service should be requested scrope automatically?

TypeError: Cann’t read properties of undefined (reading ‘then’)

// when I try to run then function on it, it will return this error

TypeError: Cannot read properties of undefined (reading ‘then’)
at Object.<anonymous> (/app/src/index.js:52:2)
at Module._compile (node:internal/modules/cjs/loader:1546:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1691:10)
at Module.load (node:internal/modules/cjs/loader:1317:32)
at Module._load (node:internal/modules/cjs/loader:1127:12)
^

const  {Client} = require('pg');
    const PG_USER= 'root';
    const PG_PASSWORD = 'example';
    const PG_HOST= 'postgres';
    const PG_PORT='5432';
    const PG_URI= `postgresql://${PG_USER}:${PG_PASSWORD}@${PG_HOST}:${PG_PORT}`;

    const client =  new Client({
    connectionString: PG_URI,
    });
    client.connect(PG_URI)
    .then( () =>console.log('connect to postgresdb...'))
    .catch((err)=>console.log('failed connect to postgresdb:' ,err))                                                                                                            

Connect MongoDB database Hosted in RockMongo (Serve00.net) with Prisma

I am trying to connect a MongoDB database that is hosted on RockMongo (Serve00.net) with Prisma, a JavaScript ORM. I followed the usual procedure to connect MongoDB databases with Prisma, but I encountered issues and couldn’t establish the connection. I need guidance on how to properly connect Prisma to my RockMongo-hosted MongoDB database.

I attempted to connect Prisma to the MongoDB database by following the standard Prisma setup steps: using the npx prisma init command to initialize Prisma, updating the prisma.schema file with the MongoDB connection string, and then running the npx prisma generate command. I expected Prisma to successfully connect to the MongoDB database and allow me to run database queries. However, Prisma was unable to connect, and I received connection error messages. I’m looking for alternative methods or troubleshooting steps to resolve this issue.

Change array of object value based on another array – Javascript

const array1 = [
  {
    id: "40",
    alias: "Number",
    name: "Number",
  },
  {
    id: "41",
    alias: "Salary",
    name: "Salary",
  },
];


const array2 = [
  {
    id: "Sum__Salary__U3VtKFVTJTIwRW1wbG95ZWUuU2FsYXJ5KQ__",
    name: "Salary",
  },
  { id: "40", name: "Number" },
];

I want to modify my array2, my ‘Salary’ id should become “41” in my second array instead of “Sum__Salary__U3VtKFVTJTIwRW1wbG95ZWUuU2FsYXJ5KQ__”

Sharing the snipped which i have tried:

const result = array1
  .filter((array1Value) =>
    [...array2].find(
      (array2Value) => array2Value.name === array1Value.alias
    )
  )
  .map((column) => ({
    id: column.id,
    name: column.name,
  }));
console.log("result: ", result);

The above snippet is working fine, but here I am returning new set of array using map, is there any way where I can replace the values instead of creating new set of array? Looking for good approach to implement this.

Accumulator Array becomes Undefined in Reduce loop

The Accumulator Array(Indices) is initialized correctly to an ’empty array’ during creation in a Reduce loop but on pushing values to it , it becomes ‘Undefined’.

Why does this happen ?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test.html</title>
</head>
<body>
    <script>


var data = {'Number' : [1,2,3,4,5]};
const startNumber = 2;
const endNumber = 5;



Numbers_filtered_indices = data['Number'].reduce((indices,e,i,arr)=> {
console.log(`loop ${i}`);
console.log('Accumulator Array');
console.log(indices);
console.log(`e = ${e}`);
console.log(`i = ${i}`);
console.log(`arr = ${arr}`);

if(startNumber <= e && e <= endNumber){indices.push(i);return indices}}

,[]) 

  



console.log('Numbers_filtered_indices')
console.log(Numbers_filtered_indices)
</script>
</body>
</html>