Byte array transfer through echo framework to JS blob

I’m trying to pass the result of a google text to speech api SynthesizeSpeech.audio_content to frontend throught echo framework (golang).

resp, err := client.SynthesizeSpeech(c.ctx, &req)
if err != nil {
    return nil, err
}
c.Blob(http.StatusOK, "audio/mp3", resp.AudioContent)

The audio itself is generated normally (I tried saving it as mp3 on the server and listening to it). But when I’m trying to get the data on the client side this way:

var options = {
  url: "/tts",
  method: "POST",
  contentType: 'application/json',
  responseType: 'audio/mp3',
  data: JSON.stringify(data),
 
  success: function (response) {
     console.log(response.length)
    
     var blob = new Blob([response], { type: 'audio/mp3' });
     console.log(blob.size)
     var blobUrl = URL.createObjectURL(blob);
     var audio = new Audio(blobUrl);

     audio.addEventListener('loadeddata', function() {
        
        audio.play();
     });

     audio.addEventListener('error', function(event) {
        console.error('Audio error:', event.target.error.message);
     });

     audio.load(); 
                          
  },
  error: function (xhr, status, error) {
    console.log(status, error)
    
  }
 }

 $.ajax(options);

I get an error: prime.js:221 Audio error: DEMUXER_ERROR_COULD_NOT_OPEN: FFmpegDemuxer: open context failed

It’s also strange that on the server side the size of the byte array before sending is for example 5664, but when I measure the size of response.length I see 5375 besides blob.size is 10591.

I also looked at the analysis in wireshark and noticed that the response was coming to the client quite well. Here it is:

enter image description here

How can we see the size of the received data at the wireshark level even before the browser is 5664 as it should be.

In the browser debugger I see the following data:

enter image description here

It seems that the array is somehow damaged or modified by the browser. What do you guys think?

JavaScript/HTML/CSS Website to Upload and Download Zip File

I want to ask a question. Basically I’m trying to make a website that can upload multiple file and then turn it into a Zip or Rar. Im not really smart at coding and use ChatGPT + BlackBox AI to help me and here is the result.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Encpr.com</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>

<header class="header">
    <h1>A Website For Your Encryption Convenience &#128512;</h1>
</header>

<main class="main">
    <section id="services">
        <h2>Our Services</h2>
        <div class="service-grid">
            <div class="service">PDF Merge</div>
            <div class="service">PDF Split</div>
            <div class="service">PDF to Word</div>
            <!-- Add more services as needed -->
        </div>
    </section>
    <input type="file" id="fileInput">
    <button onclick="uploadAndConvert()">Upload & Convert to Zip</button>
    <div id="downloadLink" style="display: none;">
        <a id="zipDownloadLink" href="#" download="converted_files.zip">Download Zip</a>
    </div>
    
    <section id="contact">
        <h2>Contact Us</h2>
        <div class="social-links">
            <a href="https://www.instagram.com" target="_blank">
                <img src="Logo/Logo_IG.png" alt="Instagram">
            </a>
            <a href="https://www.facebook.com" target="_blank">
                <img src="Logo/Logo_FB.png" alt="Facebook">
            </a>
            <a href="https://www.linkedin.com" target="_blank">
                <img src="Logo/Logo_Linkedin.png" alt="LinkedIn">
            </a>
        </div>
    </section>
    
</main>

<footer class="footer">
    <p>Your files are safe.... Why would we even want to look at your files? You think we got time for that? &#128548;</p>
</footer>

<script src="script.js"></script>

</body>
</html>

script.js

function uploadAndConvert() {
    var fileInput = document.getElementById('fileInput');
    var files = fileInput.files;

    if (files.length === 0) {
        alert('Please select a file.');
        return;
    }

    var formData = new FormData();
    formData.append('file', files[0]);

    fetch('http://localhost:3000/upload', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Failed to convert file to zip.');
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            document.getElementById('downloadLink').style.display = 'block';
            document.getElementById('zipDownloadLink').href = data.zipUrl;
        } else {
            alert('Failed to convert file to zip.');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred while uploading and converting the file.');
    });
}

server.js

const express = require('express');
const multer = require('multer');
const archiver = require('archiver');
const fs = require('fs');
const cors = require('cors');

const app = express();
const port = 3000;

app.use(cors());

// Serve static files from the 'public' directory
app.use(express.static('public'));

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/')
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname)
    }
});

const upload = multer({ storage: storage });

app.post('/upload', upload.single('file'), (req, res) => {
    const fileName = req.file.originalname;

    const output = fs.createWriteStream(`uploads/${fileName}.zip`);
    const archive = archiver('zip', {
        zlib: { level: 9 }
    });

    output.on('close', () => {
        console.log('Zip file created successfully.');
        res.json({ success: true, zipUrl: `http://localhost:3000/uploads/${fileName}.zip` });
    });

    archive.on('error', (err) => {
        console.error('Failed to create zip file:', err);
        res.status(500).json({ success: false });
    });

    archive.pipe(output);
    archive.append(fs.createReadStream(`uploads/${fileName}`), { name: fileName });
    archive.finalize();
});

app.listen(port, () => {
    console.log(`Server listening at http://localhost:${port}`);
});

With these code, I expect it to upload multiple file and then turn it into Zip or Rar like what I said above but what I get only error like this
(https://i.stack.imgur.com/mBCGU.png)(https://i.stack.imgur.com/mBCGU.png)(https://i.stack.imgur.com/RNxla.png)(https://i.stack.imgur.com/RNxla.png)(https://i.stack.imgur.com/BPs9X.png)(https://i.stack.imgur.com/BPs9X.png

I also already tried running it with administrator privilege, XAMPP, node server.js, even ChatGPT said theres nothing wrong with the code so im seriously confused here….

Please help, appreciate it

Is there a way to specify Typescript events based on obsidian element creation?

After typing some markdown and pressing enter, obsidian converts the text into a formatted form. I am trying to build a plugin to change the color of callout elements based on the name. I’ve got it working, but only when the extension is first installed. What I want is for it to recalculate every time a callout is edited or created, or when the user switches between reading view and editing mode.

This is what my javascript on my plugin looks like

export default class MyPlugin extends Plugin {
    settings: MyPluginSettings;
    async onload() {
        await this.loadSettings();
        await this.ConvertColor();
    }

    onunload() {
    }

    async loadSettings() {
        this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
    }


    async ConvertColor() {
             // ...code for converting color
        });
    }
}

and this is an example of the markdown:

> [!192,255,46] Test
> Testing

which results in:
enter image description here

Instead of onload, I would like to find some way to run ConvertColor() whenever the markdown text is converted by obsidian. but I don’t know what event that would be (if it exists).

Any ideas?

Error by passing tests with a canvas in NodeJS

I need some help. I have a blocker with a specific algorithm.

I am working on a solution where I have to pass my test which is the following code:

it('should render a basic shape', done => {
      client.run(['steps 5', 'right', 'steps 5', 'render'], (err, lines) => {
      console.log({lines})
      expect(err).toNotExist();
      expectLines(lines, '94ff358ab3e2613010529d818681c766239e97f6');
      done();
    });
  });

I am not sure why I am not passing the tests.
I tested both options:

  • Draw a graphic with 5 positions up and 5 to the right or
  • Draw a graphic 5 positions up and 4 to the right (because I can overwrite the position 15,11 when I change the direction to the right).

As you can see, I don’t have the result, I have a specific sha value so I cannot recover the original result.

Both alternatives are invalid for the test.

What could be the reason?

enter image description here

enter image description here

My cursor starts in the middle of the canvas (15,15) and I have to make my tests work. Displaying the graph following the instructions.

I was testing previously the other cases and they work well

it('should connect')
it("should handle invalid commands")
it('should render an empty canvas')

it('should render a basic line', done => {
    client.run(['steps 5', 'render'], (err, lines) => {
      expect(err).toNotExist();
      expectLines(lines, 'e93477bbe56d53603973fd584b6227121a73b894');
      done();
    });
  });

  Front backend test
    ✓ should connect
    ✓ should handle invalid commands
    ✓ should render an empty canvas
    ✓ should render a basic line

1) should render a basic shape


  4 passing (23ms)
  1 failing

This is the Cursor class

class Cursor {
  constructor(x = 15, y = 15, direction = 0) {
    this.x = x;
    this.y = y;
    this.direction = direction;
    this.directions = [
      "up", // 0
      "upper_right", // 1
      "right", // 2
      "lower_right", // 3
      "down", // 4
      "lower_left", // 5
      "left", // 6
      "upper_left", // 7
    ];
  }

  move(value, canvas) {
    let deltaX = 0;
    let deltaY = 0;

    switch (this.directions[this.direction]) {
      case "up":
        deltaY = -1;
        break;
      case "down":
        deltaY = 1;
        break;
      case "left":
        deltaX = -1;
        break;
      case "right":
        deltaX = 1;
        break;
      default:
        console.log("Unknown direction");
    }

    for (let i = 0; i < value; i++) {
      // get new position
      const newX = this.x + i * deltaX;
      const newY = this.y + i * deltaY;
      console.log("new position to draw:", newX, newY);
      canvas.draw(newX, newY);
    }

    const finalX = this.x + (value - 1) * deltaX;
    const finalY = this.y + (value - 1) * deltaY;

    this.x = finalX;
    this.y = finalY;
  }

  getPosition() {
    return `(${this.x},${this.y})`;
  }

  changeDirection(direction) {
    switch (direction) {
      case "right":
        this.direction = (this.direction + 2) % this.directions.length;
        this.x = this.x + 1; //if I remove this line, I would print a length of 5x4 
        break;
      case "left":
        this.direction =
          (this.direction - 2 + this.directions.length) %
          this.directions.length;
        this.x = this.x - 1;
        break;
      default:
        console.log("Unknown direction");
    }
  }
}

module.exports = Cursor;

And this is the handleCommand logic

const handleCommand = (command, socket, cursor, canvas) => {
  const commandParts = command.split(" ");
  const commandName = commandParts[0];
  const value = parseInt(commandParts[1], 10);

  switch (commandName) {
    case "coord":
      socket.write(cursor.getPosition() + "rn");
      break;
    case "quit":
      socket.end();
      break;
    case "steps":
      cursor.move(value, canvas);
      break;
    case "render":
      const renderedCanvas = canvas.render();
      socket.write(renderedCanvas + "rn");
      break;
    case "right":
      cursor.changeDirection("right");
      break;
    default:
      console.log("Unknown command");
      break;
  }
};

module.exports = handleCommand;


Why do we say that React’s synthetic events solve cross-browser compatibility?

When I write:

btn.addEventListener("click", someFunction);

It runs without any issues in all browsers. So, I’m confused about why React’s synthetic events are needed to address cross-browser compatibility when this event handler already works in all browsers. Moreover, if it’s about supporting older browsers, isn’t Babel.js responsible for resolving this? After all, Babel.js is involved in React projects. Can you help clarify this for me??

How do I create a video transition when clicking an a tag in html, css, and javascript

I am trying to create a transition between html pages using a video that is hidden and has a height of 0%. I don’t know where to begin and hope to get some guidance in this issue. Here is my code so far

CSS Code 1

CSS Code 2

HTML code here

JavaScript Code Here

The point of this is when the a links in the nav are clicked the video’s visibility will be shown and width set to 100% and a 1.5s delay timer will start. Then while the video is playing the whole page will start to blur, then after the 1.5s the user will change to the desired page. After the user changes pages the effect up to this point will reverse going back to 0px blur and the videos opacity will go back to 0 with the visibility set back to hidden.

I’ve tried setting a:active to the html and It worked but only for the nav bar. Then I looked up little pieces of what I need but was confused on how to put them together so I excluded that code from the provided pictures from about.

How do I make a navigation drawer open another website link or page?

There are tons of tutorial videos about how to create navigation drawers, but I want to know how to actually make it function. I figured out how to make the navigation menu, but when I click each option, it doesn’t do anything or move to another page. Please help me re-direct the user to a website from my app or another page. I am using android studio, please help!

I want the menu to have:

About Us -> re-directs to another page for information

Contact Us -> re-directs to another page for information

Website -> re-directs to another website

Facebook -> re-directs to another website

Copyright -> re-directs to another page for information

I am using the Navigation Drawer Menu. I tried creating fragments and layouts, but it doesn’t work. Whenever I click the app closes and says “stop working”. I am using Javascript + XML.

select2 x-eitable problem with not showing opt group

I have the below code which has two problems;

  1. it does not show the option Group which i am trying to setup as i am getting Array of Objects from database

  2. once i edit and select select team, it does not let me trigger the select 2nd time.

Here is the code i tried

$('#boats c').editable({
        type: "select",
        dataType: "json",
        placement: "top",
        showbuttons: false,

        display: function(value, sourceData, response, pk) {
            var key = $(this).attr("data-pk");
            var $that = $(this);
            setTimeout(function() {
                $that.editable('option', 'source', 'results.cfm?process=getTeams&key=' + key + '&i=' + Math.random());
            }, 0);
            $(this).html(response); // display the correct value instead of 'empty'

            // Initialize Select2
            $that.editable().on('shown', function(e, editable) {
                editable.input.$input.select2({
                    placeholder: "Select Team",
                    allowClear: true,
                    width: '100%'
                });

                // Set the default value to the first option from the JSON array
                editable.input.$input.on('select2:selecting', function(e) {
                    var firstOption = $(this).find('option:first').val();
                    $(this).val(firstOption).trigger('change');
                });
            });
        },
        success: function(response, newValue) {
            if (response == 'errorEvent') {
                swal({
                    text: 'This team is no longer registered in any events.',
                    type: "warning",
                    showCancelButton: false,
                    confirmButtonColor: "#EF5350",
                    confirmButtonText: "OK",
                    closeOnConfirm: true
                });
            } else if (response.substr(0, 4) == 'This') {
                return response;
            } else {
                // Assuming response is an array of objects with 'div' and 'team' properties
                var teamsByDiv = {};
                response.forEach(function(item) {
                    if (item.div && item.div.trim() !== '') {
                        if (!teamsByDiv[item.div]) {
                            teamsByDiv[item.div] = [];
                        }
                        teamsByDiv[item.div].push(item.team);
                    }
                });

                // Prepend the "Select Team" option
                var select2Input = $('#boats c').editable().data('editable').input.$input;
                select2Input.empty(); // Clear existing options
                select2Input.append($('<option>').val('-1').text('Select Team'));

                // Create optgroup elements
                Object.keys(teamsByDiv).forEach(function(div) {
                    var optgroup = $('<optgroup>').attr('label', div);
                    teamsByDiv[div].forEach(function(team) {
                        optgroup.append($('<option>').val(team).text(team));
                    });
                    select2Input.append(optgroup);
                });

                // Update Select2 with new options
                select2Input.select2('destroy').select2({
                    placeholder: "Select Team",
                    allowClear: true,
                    width: '100%'
                });
            }
        }
    });

here is the JSON repsonse

[
  {
    "divid": "",
    "text": " Select Team...",
    "temp": "",
    "div": "-1",
    "value": "0"
  },
  {
    "divid": 1298,
    "text": "Ducks",
    "temp": "DUCKS",
    "div": "Division #3",
    "value": 6270
  },
  {
    "divid": 1164,
    "text": "Lightning",
    "temp": "LIGHTNING",
    "div": "Division #1",
    "value": 6059
  },
  {
    "divid": 1164,
    "text": "Rangers",
    "temp": "RANGERS",
    "div": "Division #1",
    "value": 6261
  }
]

the above code should should show two optiongroups because it has two different divisions, if it will have on, it will show one and if all div is empty except the first one, whih is -1, it means there is no optiongroup

Need a recomendation to front end technology [closed]

What framework for front end development do you recommend to do my software architecture project, taking into account that my time to learn front end technology is very short, thank you very much. By the way, for the backend I decided to use python with fast api to create my logic

researching, most frameworks use javascript. which I have little knowledge of. What recommendation would you give me taking into account the peak of learning?

Why does console.log(typeof foo) return undefined?

This one was short enough to keep in the title but I’ll also add my understanding.

My understanding is any variable (regardless of using ‘var’, ‘let’, or ‘const’), if you referenced without any declaration results in a ‘Reference Error’

This is the behavior of functions as well (arrow and regular).

So why does the following:

console.log(typeof foo)

return ‘undefined’. If I never declared it? Why isn’t it a ‘Reference Error’?

Reducing white space on either side of a single-bar stacked horizontal bar chart – Chart js

enter image description here

I am using chart js to generate this chart within a React component.

My code is as follows:

setChartData({
                labels: ['SDA300'],
                datasets: [
                    {
                        label: `Pass (%)`,
                        data: [passValue],
                        backgroundColor: 'rgba(150,190,45,1)',
                        barThickness: 40,
                    },
                    {
                        label: `Fail (%)`,
                        data: [failValue],
                        backgroundColor: 'rgba(238,109,109, 1)',
                        barThickness: 40,
                    },
                ],
            });

const options: ChartOptions<'bar'> = {
        indexAxis: 'y',
        
        scales: {
            x: {
                stacked: true,
            },
            y: {
                stacked: true,
            },
        },
        plugins: {
            legend: {
                display: true,
            },
        },
    };
{chartData.labels && <Bar data={chartData} options={options} />}

I tried removing the barThickness and playing with barPercentage and categoryPercentage, but it doesn.t seem to be getting me where I want, which is reducing the white space on top and under the bar.

Test expected with sha1

I need some help. I have a blocker with a specific algorithm.

I am working in a solution where I have to pass my test which is the following code:

it('should render a basic shape', done => {
      client.run(['steps 5', 'right', 'steps 5', 'render'], (err, lines) => {
      client.run(['steps 5', 'right', 'render'], (err, lines) => {
      console.log({lines})
      expect(err).toNotExist();
      expectLines(lines, 'specificSHA1value123456789ABC');
      done();
    });
  });

I am not sure why I am not passing the tests.
I tested both options:

  • Draw a graphic with 5 positions up and 5 to the right or
  • Draw a graphic 5 positions up and 4 to the right (because I can overwrite the position 15,11 when I change the direction to the right).

As you can see, I don’t have the result, I have a specific sha value so I cannot recover the original result.

Both alternatives are invalid for the test.

What could be the reason?

enter image description here

enter image description here

My cursor starts in the middle of the canvas (15,15) and I have to make my tests work. Displaying the graph following the instructions.

I was testing previously the other cases and they work well

it('should connect')
it("should handle invalid commands")
it('should render an empty canvas')

it('should render a basic line', done => {
    client.run(['steps 5', 'render'], (err, lines) => {
      console.log({lines})
      expect(err).toNotExist();
      expectLines(lines, 'especificSHA1Value');
      done();
    });
  });

  Front backend test
    ✓ should connect
    ✓ should handle invalid commands
    ✓ should render an empty canvas
    ✓ should render a basic line

1) should render a basic shape


  4 passing (23ms)
  1 failing

problem when rederizing component fetching data from strapi

Hello, how are you? I’m trying to render my component by fetching the data from the api and I’m using next.js 14 with strapi v4 and it always returns the same error. I’ve tried several things but it doesn’t solve it in the console. You can see that the data passes but there is a problem in the component apparently since it doesn’t show me the card with the data I’m trying to create a blog in advance thank you very much any kind of help is appreciated.

error console

"use client";
import { useState, useEffect } from "react";
import { fetchPosts, getImages } from "../services/postsService";
import { Card } from "flowbite-react";
import Link from "next/link";

const Home = () => {
    const [posts, setPosts] = useState([]);

    useEffect(() => {
        const fetchData = async () => {
            try {
                const data = await fetchPosts();
                const postsWithImages = data.map((post) => ({
                    ...post,
                    attributes: {
                        ...post.attributes,
                        imageUrl:
                            post.attributes.image.data[0].attributes.formats.medium.url,
                    },
                }));
                setPosts(postsWithImages);
            } catch (error) {
                console.error("Error fetching posts:", error);
                setPosts([]);
            }
        };

        fetchData();
    }, []);

    return (
        <main className="flex min-h-screen flex-col items-center justify-between p-24">
            {posts.length > 0 ? (
                posts.map((post, id) => {
                    const { title, content } = post.attributes;
                    const imageUrl = getImages(post.attributes.image);
                    return (
                        <Card key={id} className="max-w-sm">
                            <img src={imageUrl} alt="cover" className="w-full h-auto" />
                            <Link href={`/post/${id}`}>
                                <h5 className="text-2xl font-bold tracking-tight text-gray-900 dark:text-white">
                                    {title}
                                </h5>
                                <p className="font-normal text-gray-700 dark:text-gray-400">
                                    {content}
                                </p>
                            </Link>
                        </Card>
                    );
                })
            ) : (
                <p>Loading...</p>
            )}
        </main>
    );
};

export default Home;

the service for strapi requests

import { API_URL, STRAPI_URL } from "../config";

export async function fetchPosts() {
    try {
        const res = await fetch(`${API_URL}/posts?populate=*`);
        if (!res.ok) {
            throw new Error("Oops! Something went wrong");
        }
        const { data } = await res.json();
        console.log(data);

        const formattedData = data.map((post) => ({
            ...post,
            attributes: {
                ...post.attributes,
                image: post.attributes.image || { data: [] },
            },
        }));

        return formattedData;
    } catch (error) {
        console.error("Error fetching posts:", error);
        return [];
    }
}

export async function getImages(imageData) {
    if (imageData && imageData.data && imageData.data.length > 0) {
        const imageUrl = imageData.data[0].attributes.url;
        console.log(imageData.data[0].attributes.url);

        return `${STRAPI_URL}${imageUrl}`;
    }

    return null;
}

I have tried different modifications to the code and I hope I can solve it

$.get(code_url) executes code returned, without using eval( ) neither appending it to DOM. jQuery security fail?

I was debugging my NodeJS app when I came to this huge fact : Using jQuery, a simple

$.get(code_url)

Where code_url is an URL toward javascript code on the server, does executes the code.

What is expected is :

$.get("script.js", function(data) {
    // data contains the content of 'script.js' as a string
    // We can choose either to :
    // - Append it to the DOM
    // - Evaluate it using eval()
    // - Store it for later use
});

But still, even with nothing done in the callback, code is indeed executed.

I tried to recreate a server almost empty, with just a few lines of code to make sure that it does not come from my project. Even with a total of a dozen of lines, I can reproduce.

NodeJS server :

const express = require('express');
const App = express();
App.use(express.static('www'));
App.listen(5000);

index.js (executed by the index.html)

$(document).ready(function() {
    $.get("utils.js")
});

utils.js (served as static in www/ by the server)

console.log("Hello World");
let a=1000;
console.log(Math.PI*a);

And BOOM, code executed :
Google Chrome console showing code execution

NB: Issue seems to happen only on local server, but still I think it’s quite a serious issue. I just cannot manage to download any piece of code without having it executed on the fly… Come on. Did I find a HUGE jQuery bug ?

Tested on

  • jQuery 3.6.3 and 3.7.1
  • Google Chrome (Version 123.0.6312.122 (Official Build) (64-bit))
  • Linux Ubuntu 22.04