#development
1 messages · Page 100 of 1
const chartJSNodeCanvas = new ChartJSNodeCanvas({ width, height, backgroundColour, chartCallback: (ChartJS) => {
ChartJS.global.defaultFontFamily = 'Inter';
}});```
so global is undefined?
ChartJS.global is undefined
how you doing battleless, you need any help with your projects?
ill try to be here and help ya out if ican
point of origin?
it depends on what you are measuring
but that looks like from the graph that is the start of the measure
it could also just be the first entry into your data set, in which you would delete the corresponding data
if you give me some more information about what you are measuring i could be of more help
Id just call it a line
That could be true as well! if its the entire part that he highlighted, then it could be
cus it looks weird there
chartjs?
Can you take a closer screenshot of what you are trying to remove
if youre talking about the vertical black line, i am not sure
ye
yeah
thats what i highlighted
yeah. Well if you want to learn to be a better communicator (not sure if thats a real word) its important to both learn the definitions of words, but also their "working" definition
what
how do i remove the highlighted?
💀
well i was asking how to remove the message i just wrote which from your view is highlighted
that is the semantics part of understandign someone
what are you on about
"what"
i do not know the name of the black line that you highlighted in your data
but someone may be able to help you better remove it
ok
I apologize if i made that more confusing
No need to apologize, not ur fault
Many came, many tried, none succeeded
You're pretty polite
When we have questions, we should be sure to encourage giving as much information as possible as we are trying to be open
is that the number of fucks you give over time?
so in july you will give 0 fucks
:^)
no
it's a random dataset i found on the chartjs website
btw guys how can i remove ExperimentalWarning's
check the docs of wherever that is included from
buffer.File is an experimental feature and might change at any time
is it ok to use it
well it's from node, no?
then check the docs for that on node
or check whatever error message is included. Those normally tell you where/what you need to do to fix the issue
battleless+? oh thank god, we were due an upgrade
yes
😮💨
does anyone know something like https://www.npmjs.com/package/chartjs-plugin-datalabels that works with common.js
uh oh
better change your name in this server
if you want this
you can do it
:lutune:
Tf are this weird people today
not that this channel would be a place of sanity but still
lol
nvm figured it out
looks pretty nice
how are you making it look like that lol
i can only get mine like this https://cdn.discordapp.com/attachments/709592014127235121/1082482322164691116/graph.png
please do 
sure
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
👌
Hello,
in my interactionCreate, interactionSuccess events, I only receive an object with id and nonce fields. How can i access the interaction`when it has been answered by a bot (and the response of a bot to that interaction?)
you cant listen to other bots' interactions
nor can bots use yours
ok thx! and if i get a message with an embed in messageCreate event, how can i read that embed? the content='' and embeds=[]
iterate over the embed
messages can have up to 10 embeds
thx!
Hey after listening some people, I try to up my project to version 14 but I get this error when I running my bot
require('dotenv/config');
const { ShardingManager } = require('discord.js');
const Bot = require('./src/Structures/bot.js');
const client = new Bot();
client.start();
const manager = new ShardingManager('./src/Structures/bot.js', {
token: process.env.BotToken,
totalShards: 'auto',
});
manager.spawn();
manager.on('shardCreate', (shard) => {
console.log(`Launched shard ${shard.id}`);
shard.on('ready', () => console.log(`Shard ${shard.id} ready!`));
shard.on('disconnect', () => console.log(`Shard ${shard.id} disconnected!`));
shard.on('reconnecting', () => console.log(`Shard ${shard.id} reconnecting...`));
shard.on('error', (error) => console.error(`Shard ${shard.id} encountered an error: ${error.message}`));
shard.on('warn', (warning) => console.warn(`Shard ${shard.id} encountered a warning: ${warning.message}`));
});
My client.js file
require('dotenv/config');
const { Client, Collection, Partials } = require('discord.js');
const { GatewayIntentBits } = require('discord.js');
const { Channel, GuildMember, GuildScheduledEvent, Message, Reaction, ThreadMember, User } = Partials;
const { readdirSync } = require('fs');
const { BotToken, Prefix } = process.env;
const Util = require('./Utils');
const chalk = require('chalk');
class BOT extends Client {
constructor() {
super({
... //intent + partail, Discord limit don't allow me puthere
});
this.token = BotToken;
this.config = require('./config.json');
this.setMaxListeners(0);
this.events = new Collection();
this.legacyCommands = new Collection();
this.aliases = new Collection();
this.commands = new Collection();
this.components = {
buttons: new Collection(),
modals: new Collection(),
selectMenus: new Collection(),
};
this.cooldowns = {
legacyCommands: new Collection(),
buttons: new Collection(),
commands: new Collection(),
modals: new Collection(),
selectMenus: new Collection(),
};
(this.commandArray = []), (this.developerArray = []);
this.legacyArray = [];
this.colors = {
green: 0x22b14c,
};
this.rds = readdirSync;
global.chalk = chalk;
this.utils = new Util(this);
}
async start(token) {
const functionFolders = this.rds(`./src/functions`);
for (const folder of functionFolders) {
const functionFiles = this.rds(`./src/functions/${folder}`).filter((file) => file.endsWith('.js'));
for (const file of functionFiles) require(`../functions/${folder}/${file}`)(this);
}
this.handleEvents();
this.login(token).then(async () => {
await this.utils.logger();
this.handleCommands();
this.handleComponents();
if (Prefix) this.handleLegacyCommands();
});
}
}
module.exports = BOT;
My bot.js file
D:\CoronaChanV3\Discordjs-v14-Template\node_modules\discord.js\src\sharding\Shard.js:162
reject(new Error(ErrorCodes.ShardingReadyDied, this.id));
^
Error [ShardingReadyDied]: Shard 0's process exited before its Client became ready.
This is my first time with discord.js-v14, anyone know why my shard always die?
My project is start normal if I'm not putting sharding
You've got it mixed up, that's not how sharding works, you're passing your bot.js file to your sharding manager which just exports a client and it doesn't even login, that's why it exits the process
Read through https://discordjs.guide/sharding/#getting-started
require('dotenv/config');
const Bot = require('./src/Structures/bot.js');
const client = new Bot();
client.start();
but this should work right, I think my job is move shard code to shard.js file but it don't work too ://
You're supposed to instantiate the bot and login in the file you're passing to your sharding manager
For example:
// bot.js
import { Client, GatewayIntentBits } from 'discord.js';
const client = new Client({
intents: [GatewayIntentBits.Guilds]
});
await client.login(process.env.botToken);
// index.js
import { ShardingManager } from 'discord.js';
const manager = new ShardingManager('./bot.js', {
token: process.env.botToken
});
manager.on('shardCreate', (shard) => console.log(`Launched shard ${shard.id}`));
await manager.spawn();
I will try this way again, I remember I tired it but fail
I should rewrite some lines like this?
im not sure, but intents seems to be determining what data can go through a gateway
and by checking that data
@earnest phoenix I think I will move const Bot .... Start(); into a new files, then create a connect from main files and start shard.js file, I think it should work
alr, bad lang looking less bad now Id guess
well then you do call set()
And what happens to the variable setting technique 
its unaffected, you cant overwrite predefined functions
disappointed
I wish it would be that easy
Eventually parsing is a bit more "complex"
yeah, it isnt that hard
what theme r u using? 👀
looks pretty nice
LMAO
great 
Slash command adoption for Feb 2023 was ~73% 👀
That means pretty much 3 out of 4 commands run were slash commands
What happened in December 
I think that's when slash commands stopped loading in everyone's clients? There was that Discord bug
Ah may have bene that time yeah
Anyway, I implemented slash commands in Feb 2022 and 1 year later this is where we're at without me even promoting the use of them anywhere in my bot / Top.gg page.
So this is natural adoption

It actually also equates for 75% of unique users
where did you get this data
That's for their own bot
oh i thought it's from Top.gg or smth
So I was wondering. You can hypothetically get infinite queries on midjourney using different Accounts!, Now you can also make infinite (or many) bot account in discord developer portal, so if you were to somehow make it happen that "your bot" types "/imagine" then presses the pop up that shows that it's going to register that /imagine as a command and not a message, then type out what you provided then press enter/send then you can"
Exploit your bots for midjourney free queries and each time one runs out, you can just put your first bot's preset to your new bot and go on. Will that be possible?
Better
how would they get that from top.gg
Might want to read Midjourney ToS
I know it ain't allowed, but is it possible though?
F
omg lesgooo
i hacked rust using discord
what
bots cannot run slash commands
i hacked tim using rust
Daily Aurel rent
Who the fuck invented leap years
I hope you continuously suffer in your grave
Like
Haha yes lets have funny month days numbers years numbers haha
it's caesar
Fuck that dude
Time savings is also a mess
Nobody cares about leap years, yet devs have to deal with it
Jesus
IM NOT GONNA GET STARTED ON TIMES YEAH
Hellno
what about leap seconds :^)

what about sidereal time, terrestrial time, ephemeris time, universal time, mean and apparent times
also universal time (UT1) !== coordinated universal time (UTC)
if I’m tracking multiple stats of games is it best to have a table for each
cus there’s going to be a lot of data
looking at that data on /slash commands, is that good or bad in your opinion! I def see that it is changing!
Yeah! you could organize the table in many ways, if you were pulling public game stats or dev available stats, make sure youre not breaking any ToU as i have no idea what the rules for that are. But i would say thats probably what most of these reward/punishment systems for in game bots is based on
What sort of data are you looking at pulling? ive done it for a few games in the past, but just as smaller projects! if you want an example of a 3rd party using game stats, check out some applications like overwolf or fire for blizzard
☠️
depends how the data is organized
there’s going to be like 300k rows a day
wym
I was going to organize it by adding a type column
you have to think of different ways to organize tabular data, i dont know what exactly your data looks like, but for example:
table a+b
id, type, value
1, "a", 500
1, "b", 400
2, "a", 200
2, "b", 840
``` or ```js
table a
id, value
1, 500
2, 200
table b
id, value
1, 400
2, 840
there are many options
in general separated tables are faster to access (if accessing individual data) but consume more space
yeah that’s how I’m doing it right now
just wondering if it’ll be better to separate them because there will be quite a bit of data and I’ll need to access it regularly
can you give me some contxt and i can help
what more context ? ☠️
the example he sent is what I’m doing right now except i have a time stamp column
Ok let me look for a second
Sometimes you have to read the lyrics to make sense of the song - owo define
^^ignore that was just trying to help another bot^^^
☠️bro
Im doing alot of small side projects right now to just understand more concepts and currently im making a simple text compressor, I have this code. it does work - just not correctly since it makes the files 2x bigger, is my concept that this code uses generally even the right direction?
https://pastes.dev/iu02QpXQZn
my current Idea was just to assing each word a number, have all number: words at the bottom and just use the numbers for the actual text
wont work
you see, with this method ur limited to 10 numbers, or 16 if ur using hex
this is how the current output looks for large files
https://pastes.dev/et73fQLGsf
ah, you're using _ to separate characters
you could use unicode chars intead, which supports up to 65k different values
can I somehow turn a simple number to unicode in js?
or do I have to manually do that?
you don't convert to unicode
I mean, in js ig u need to since it doesn't have char data type
see if there's a parseChar or smth
regardless, your method is quite similar to deflate compression method
although less efficient
mh
oh
surrogate pairs/triplets/quartets would be different
what would I do if I go over 65k?
you wont be reading the content itself, you'll read the bytes
compressed files aren't supposed to be humanly readable
yes but I mean when decompressing if I go over 65k I would go back to the first word, right? and then it would show wrong words
yes it'll break
but that's because you're using an inefficient method
as I said, you're doing what deflate already does
yeah, I also thought about checking if a word gets used over X times and only then map it
right
in a compression algo you don't care about words at all, you need to focus on bytes
deflate counts repeated sequences of bytes and map them into pairs of bytes (0xFFFF)
you can also simply ditch chars altogether and use 4 bytes (0xFFFFFFFF), which will allow up to 4 billion words
note that the more bytes you use, the bigger the output will be
hm, Id just want it to compress with only changing text for now, no bytes since I havent done anything with bytes, really
up to you, but it'll expand most content instead of compressing
how would using bytes change that though? isnt it the same in the end?
this for example: _555__82__556__557__554__71__152_ = 33 chars
in bytes becomes: ȫRȬȭȪG = 7 chars
🧐
those are char representation of the bytes
numbers are just bytes though arent they
only inside memory
inside files they are chars
so 555 isn't the number 555, but the character 5 repeated 3 times
I simply used the char representation instead of the readable number
?
yes, because chars below 40 or so are mostly control characters
but they are there
a quick example I wrote, based on ur algo + what I said
I added an offset of 60 to have visible chars at all
the text has a poor compression because it's separated by whitespace, this is what I mean when I said yours wont compress as much
its def progress though, from compressed being 100kb bigger to only 6kb bigger, still bigger though
what should I seperate by then?
nothing
now we getting to bytes again aint we
if u use 2 bytes (1 char) for every value you know for sure it'll be 1 value every 2 bytes
you don't need any separator, because every char will be the value itself
an example splitting by 2 chars
it ended up being bigget than split by spaces
now its 30kb bigger, did I do something wrong?
if it's bigger u probably did something wrong
export function compressFile(file: string): string {
let newContent = ''
const content = fs.readFileSync(path.resolve(file), 'utf8')
const lines = content.split('\n')
for (const line of lines) {
const words = line.match(/.{1,3}/g)
if (!words) continue
for (const word of words) {
if (compressContext.cached.has(word)) newContent += String.fromCharCode(compressContext.cached.get(word) + 60)
else {
compressContext.cached.set(word, compressContext.cached.size + 1)
newContent += String.fromCharCode(compressContext.cached.get(word) + 60)
}
}
newContent += '##'
}
newContent += '\n'
for (const [key, value] of compressContext.cached) {
newContent += `${key}#${value}-#`
}
return newContent
}```
1.0.0.1
js gets funky when u try to compose strings from raw codepoints
apparently, splitting by a fixed number of chars has poor repetition, you'll need a more intricate way of splitting
wow, I fixed my regex and the file is 10kb smaller
well stll alot of room for improvement
oh, btw
if ur gonna split by fixed amount of chars use /(?<=\G.{number})/
else it'll split only the first match
and remember to use (?<=) block else you'll delete the splitted part
last but not least, you can separate your dictionary in a separate file
cuz u only require it when decompressing
however this will also mean you need to transfer the two files when sharing it
technically I could treat that file as a "key" then, right?
whats the best way to make global functions that i can use in every command?
use a helper file
Ok
count on spetify bot or all Discord?
his discord bot
pixxie
there would be no way to get that data on every bot
His own bot, unless Discord shares the same that for overall Discord - which is probably hard/long - it cannot be Discord's data
Would be nice to see such data from Discord though
how can i attach an image to an embed
.setImage()?
const attachment = new MessageAttachment(chart, "graph.png")
const embed = new MessageEmbed()
.setImage("attachment://graph.png")
await message.channel.send({ embeds: [embed], files: [attachment] })```
an example
the name in attachment:// must match that of the attached image
ty
no problemo
I see I can put shard: auto like some people doing in the bot main file and it work, but this sharding can only set auto and I feel something is different from traditional way.
Apart from ShardingManager, discord.js also supports a sharding mode known as Internal sharding. Internal sharding creates multiple websocket connections from the same process, and does not require major code changes. To enable it, simply pass shards: 'auto' as ClientOptions to the Client constructor. However, internal sharding is not ideal for bigger bots due to high memory usage of the single main process and will not be further discussed in this guide.
Oh, that is explaining why I am feel strange ://
the ideal way of sharding is cluster based which means the bot is spread out among multiple VPS' and each cluster manages a couple shards (however many can fit into the VPS without destroying the RAM and CPU)
The question is if that is more cost efficient than a stronger dedicated server
Load balancing of course makes the most sense especially on multiple machines also to prevent the entire thing from being down once one server is down
I Wonder how many servers a bot has to be in to reach the limit of a common dedicated server using an optimized way of handling and caching requests and data
My bot is TINY and adding more guilds doesn't really increase memory usage. 6.7k guilds can fit into 100MB
Internal sharding working alright
It increase only some%
Not a very big number if your bot not like Dyno, Probot, ...
But this way sharding working better.
as discord.js said they will not provide any more information about this, so I am asking here :))
because it's a not recommended sharding method
for public bots
even for private bots, you're unlikely to reach any shards other than shard 0
in my experience, internal sharding works fine for at least 16 shards
it can probably handle up to 30 something without much issue, depending on your intents and stuff
the main thing that destroys your bot is presence events, so leave them disabled if you can, and the initial guild creates especially wjen you have big bot sharding
Internal Sharding works fine with up to 30k Guilds. The way djs handles shards .... they keep disconnecting and the initial connecting phase takes pretty long. @boreal iron I had to start syncing the ratelimits upon 100k Guilds. You actually dont need no cache, proper ratelimit syncing will allow a cold cache. For the sake implicity you cache guilds & roles.
16 Shards per Cluster works totally fine, tried 25 too, but there is some connection issues...
in java, does obj1.equals(obj2) return true if both objects are the same class and if both objects have the same values for the fields?
cuz i have only used .equals on strings, and i know there it will check for each character and the type of the passed parameter. So it might be the same?
Neither
It compares the memory address
You can always override it in your object though
ctrl click to see the implementation
it doesn't, that's nvm, default implementation of ==equals is return (this == obj)
Usually most objects have an overridden equals method
But yeah if the method isn’t overridden then it will compare memory addresses of the objects
ho
Hello everyone!
what’s the best way to round something in canvas I tried but couldn’t get it lined up right
this should work fine, right? generally
Im talking about the interface, how would I try it and see that
compile it with ts, and see if it compiles :^)
It is fine for arround under 50000 guilds, if your bot not having great events, it's can up to 100000.
Btw it is very sad when you can only set auto
And log internal shard events like normal right?
get the message reference id
and fetch the message
yes
thats what i said
get the message reference from message
if (message.reference) {
const msg = await message.channel.messages.fetch(message.reference.messageId)
content = `<@${msg.author.id}>`
}```
thats the code i use for tags and fetching replied to users
idk then
whats the difference between https://www.npmjs.com/package/canvas and https://www.npmjs.com/package/@napi-rs/canvas
Canvas graphics API backed by Cairo. Latest version: 2.11.0, last published: 2 months ago. Start using canvas in your project by running npm i canvas. There are 2253 other projects in the npm registry using canvas.
Explained in the first 6 words of the description
🗑️
thats a garbage can emoji
Discord uses tweemoji so it should be standardised anyhow across devices
that's weird
which is better
I probably would avoid the pre-release one
ok
how do I check if a number is negative
if (!number > 0) 
that does not work without parenthesis 99% sure
This would always return true unless the number was 0
the ! coerces the number to a boolean. 0 = false. everything else = true.
then the > symbol coerces it back to a number (0 or 1)
ahh i see
I'm stuck on the delete warn command. The issue is that when I do .warn @user#6969 reason and when i go ahead and delete it. it says that my case number is not correct. https://sourceb.in/rIglmdVdSv
That's because you've spliced the element at that index, but you're still trying to access it even though it's gone
And I recommend migrating to slash-commands, it's much easier to handle arguments with and validate their values, instead of going for hacky solutions like arg shifting and whatnot
And there's also the https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex method you can use to find the index instead of using forEach() to iterate through all the elements and find the index
but element.case is "69 warnAdd"
i tried splitting it
and it gave me an error saying that element.case.split is not an function
when i log c
it shows me an number
what is that number?
Then it's the case number, you don't know what you're putting into your database?
that's the index of guild.case number or something?
o true
The warning case... Maybe you should take a step back and look at what you're actually putting in your database, that way you would know what it's value is
updated code: https://srcb.in/zPGOVWH05H
That's not how %Array.prototype.findIndex()% works, did you even look at the examples and documentation?
That still wouldn't work because you're not returning anything to the function you're passing to the findIndex() method
It can be (c) => c.case === ... or (c) => { return c.case === ...; }
oh
mdn docs best

what if theres the number doesn't met the required thing?
what does it return
undefined?
or -1?
@lyric mountain I don't know if you would know about this or not, but is the drawImage method on Graphics2D objects super super slow normally?
If you read the documentation, it says -1
oh
roughly 90% of my CPU time is spent on drawing images, and my application gets REALLY laggy after I cross about 20 or so "bullet" entities in my swing application
Which either this method is slow as fuck or I'm using it poorly
And I'm thinking that I'm using it super poorly somehow
Show code
well
there's a lot
but I'll try to showcase the important parts
So, I have a system in my ECS that looks like this:
public class RenderSystem extends ECSSystem {
public void update(Graphics window) {
for(int entity : entities) {
TransformComponent comp = world.getComponent(entity, TransformComponent.class);
SpriteRenderComponent s = world.getComponent(entity, SpriteRenderComponent.class);
Vec2f drawPos = comp.position.add(s.position);
window.drawImage(s.sprite, (int)drawPos.x, (int)drawPos.y, s.width, s.height, null);
}
}
}
``` which is where all of the images actually get drawn. Super basic.
```java
public class Canvas extends JPanel {
private final RenderSystem renderSystem;
public Canvas(RenderSystem system) {
renderSystem = system;
}
@Override
public void paintComponent(Graphics window) {
super.paintComponent(window);
Graphics2D graph = (Graphics2D) window;
BufferedImage back = (BufferedImage) (createImage(getWidth(), getHeight()));
Graphics graphToBack = back.createGraphics();
renderSystem.update(graphToBack);
graph.drawImage(back, null, 0, 0);
}
}
``` this is the JPanel for the entire application. Basically just a raw canvas with double buffering.
🚪🚶♂️ Swing
Have been there, do not wish to be there again
Here's my bullet class, which is basically just a sprite that moves a little: ```java
public class Bullet extends GameObject {
private static BufferedImage image;
static {
try {
File file = new File("src/com/waffle/test/images/projectile.png");
image = ImageIO.read(file);
} catch(Exception e) {
System.out.println("ERROR: " + e.getMessage());
}
}
private TransformComponent transform;
private SpriteRenderComponent sprite;
private int speed;
public Bullet(int speed, float x, float y) {
this.speed = speed;
sprite = new SpriteRenderComponent(new Vec2f(), image, 50, 50);
transform = new TransformComponent(new Vec2f(x, y));
}
public void update(float dt) {
transform.position.addY(speed * dt);
}
@Override
public void start() {
}
}
All of this is put together in a Game class that has an update method called by a ScheduledExecutorService every 16ms (roughly 60fps)
Within that game class, this is basically what that looks like: ```java
@Override
public void run() {
if(window != null) {
this.update(UPDATE_DELAY_MS / 1000.0f);
}
}
public void update(float dt) {
// Update other systems here
physicsSystem.update(dt);
world.update(dt);
window.repaint();
}
I'm thinking MAYBE it's something to do with window.repaint(), but that should be just fine because it's (afaik) just calling the paintComponent method again, aka updating my render system
Oh and world is the ECS, world.update(dt) just calls the update method of every GameObject in the ECS
However I have confirmed that only 4% of the program execution time is spent on this Game.update(float dt) method, and the majority of the time is spent in renderSystem.update(graphToBack) because of the Graphics2D.drawImage() method
So yeah
that's my problem
lol
Where's the entities coming from?
It's a HashSet of integers given from the ECS
Basically just a set of IDs that point to entities with certain components that the System can use
Not really important for the scope of the issue
I feel like it's set is getting much bigger than expected so it's causing the operations in the loop to be called way too many times, making it much slower but that might not be the case
Hmm, maybe try running the update() method of the Game class (or whatever it's called) with a longer delay to see what happens?
I mean that would decrease the framerate, but I can do that
It'll still encounter the same issue after I get too many entities
It's for testing purposes anyway
Yeah doubling the delay still encounters the same issue after I rack up about 30-40 bullet entities
I haven't used Java Swing so I'm a little confused at a specific part of your code, you're creating an image using the createImage() method, but it's contents are empty? I'm not sure how that works
createImage is just a method from JPanel
I would profile more to see which method in particular is causing the biggest use of time, but unfortunately about 85% of it tracks back to a native dll that I cannot profile methods of
Oh wait you're updating it's graphics content with the render system update() method, I see
Yeah
Unfortunately I don't see what could be causing that
But you can at least profile every method you've declared in all of those classes to see which one is causing the slowness
That can definitely give you a hint
unfortunately it all boils down to a dll here
that's where the profiling ends
Might just have to take a break for the night
@earnest phoenix I think I may have figured it out
The image I was using is like 1300x1300
and I'm resizing it to 50x50
I think that maybe a compression/resizing algorithm was taking a lot of time up
When I swapped to using a very small res image of like 200x175 I'm getting no lag with 1721 entities on screen
Very nice, I guess Java Swing struggles a lot to handle high resolution images
Maybe you should try SWT
frequent image resizing in any graphics engine is a big no-no
thats why games usually have all textures and images in all supported resolutions already resized and available
or at least resize once and store the resized version in memory for reuse
Not usually
But u can speed it up by disabling some things, if u don't mind poorer graphics
G2d comes by default configured to "balanced" mode, you can set it to "performance"
Also, if you're using swing it's better to use createCompatibleImage
And yes, don't resize images in the render flow
just check if it includes https:// 🤨
Oh
You asked in a public discord text channel which anyone can reply in so. 🙂
(?! ...)
Hm, nvm then
What u trying to do?
Oh, btw
U added an space behind https
I added it in the example to keep it readable
But u shouldn't since it'll attempt to match an space
What ur using it for?
Yes, but what context?
Can't u just replace the link matches with nothing?
Still, can't u just replace?
Regex is best for matches, not inverse matches
So... is this not what you're trying to do?
https://scs.twilightgamez.net/HQcrV.png
Or are you also trying to match strings w/o http https ect.
That could be rather difficult to match due to how many options there are out there.
.com, .net, .xyz ect
The global URL class will throw an error on any invalid input provided, so you can use that approach
you are L
Tim, YoU aRe a catgirL
OwO?
That would pretty much be impossible to do with just regex, mainly because some parts of a URL is optional and declaring that will cause the regex to also match certain parts of the URL when you don't want it to
You would need an actual URL parser to do that
guys
how do I get every other row in sql
then every third row
and fourth
and fifth
etc etc
oh, interesting.
I have no idea
ok Ty
will look into this
what that guy is doing is exactly what I’m doing too lol
need it for a line chart
Maths question
I want to get the opposite of a number
E.g 360 = 0
0 = 360
180 = 180
90 = 270
How do I.
E.g in JavaScript
What are you referring to with "opposite of a number"
You mean the complimentary angle to add up to 360?
Just 360 - x
There is a problem with this
Minus minus x = Plus x
And zero is not my minimum, it's -45
Ig I can increase with 45 and decrease with 45 later
always normalize your ranges
(angle % 360 + 360) % 360
this will put any number, positive or negative, in the range 0-360
then you can further add another ( + 180) % 360
so lets say I have an interface like this:
interface TestIdk {
type: 'ok' | 'ok2'
message?: string
error?: string
}```
how would I make typescript know that message is always defined when type is ok & error is always defined when type is ok2?
Tim knows the answer, I'm just going to guess for the fun of it.
a typeguard? 🤷
interface Test1 {
type: "ok",
message: string
}
interface Test2 {
type: "ok2",
error: string
}
type TestIdk = Test1 | Test2
oh neat
you can try implementing an interface that overrides the on method
Hey hey another shitty math question
So
I have my screen height
I convert that into a percentage
I then have 360 (degrees) / 100
Aka 3.6 degrees per 1%
But now
I don't have 3.6 exactly
Here comes the tricky part
The degrees' minimum is -45 and maximum 85
And uhhh
😨
I don't know.
so you want to make like a pie slice fit fullscreen?
Lol no
So basically
(This is Roblox stuff)
I have an arm
The arm has a tool
The arm should move up and down based on the mouse's Y position
Now I don't want the arm to be able to do a looping
So I want limits
Being -45 and 85
I'm just stuck on how to do this
@Override
public void fillOval(int x, int y, int width, int height) {
GL2 gl = buffer.getGL().getGL2();
float[] xy = {
(2f * x + 1) / WIDTH - 1, (2f * y + 1) / HEIGHT - 1,
(2f * width + 1) / WIDTH - 1, (2f * height + 1) / HEIGHT - 1
};
System.out.println(Arrays.toString(xy));
float detail = 45;
gl.glBegin(GL_POLYGON);
{
double step = Math.toRadians(360 / detail);
for (double i = 0; i < 360; i += step) {
gl.glVertex2d(xy[0] + xy[2] * (1 + Math.cos(i)), xy[1] + xy[3] * (1 + Math.sin(i)));
}
}
gl.glEnd();
gl.glFlush();
}
So, regardless what I put in glVertex2d() it doesn't move the circle
Ex kept if I change the multiplication, then it makes it bigger
I actually stopped midway when trying to debug, which is why the sout is there
gl.glVertex2d(xy[2] * Math.cos(i), xy[3] * Math.sin(i))
This will put the circle in the middle of the canvas
As soon as I get to the pc I'll run the code to show what it's outputting
Think I'll change the scale to allow me to use pixel coordinates, instead of the weird ogl mid-pixel percent coords
Yeah usually you use a projection matrix for that
heh, simply fixing the coordinate matrix solved it
(x: 0, y: 0) | (w: 250, h: 250)
(x: 250, y: 250) | (w: 100, h: 100)
and I no longer need to do big conversions to get the correct coord
niceee
I now have an fps counter in my engine
pretty basic (also don't worry about the rocket ships I was stress testing a little)
for some reason though I'm not able to use ScheduledExecutorService to get accurate frametime, I'm measuring 64-65 fps when in theory it should be running at a max of 60
I would understand if it was less than 60fps, but greater than 60fps would require the service to be executing early which doesn't make much sense to me
@lyric mountain you have any idea why this might be happening?
how do i use clip twice in canvas ☹️
timer is the ScheduledExecutorService btw
converting fps to nanos might generate some precision issues
especially since ur fpsCap is float
u can simply use millis for update rate, don't think you'd ever use a cap of 1000
I suppose I could come to a compromise on frame precision and use microseconds so I can still get in-between ms values
ehh
also, instead of an sched service u could use an infinite loop + sleep
By using millis only I can't get good precision
I mean, yeah, but the difference would be minimal
I have a feeling I'll run into issues with sleep
java sleep only pauses the current thread, it doesn't work like c++ or alikes where it freezes the whole thing
I more or less meant for getting standard framerates to work like 60fps and such, since 60fps would be a delay of 16.66ms and I would only be able to do either 17ms or 16ms
ah
I'll try using sleep rq and see if I run into any issues
just make sure you create a new background thread
u can use extends Thread on your game to have itself be a thread
Alright so using sleep seems to get a little more precise on the delay
sleep is much more precise than sched because it tells the cpu to pause that thread
while sched works with queues
ugh I hate how sleep doesn't allow you to use nanos or micros
requires millis + nanos
so annoying
might just make a helper method rq to fix that
u can make a somewhat gambiarra function to get even higher precision
truncates
ok
always down
love me some gambiarra functions
ok so now I'm realizing why I originally didn't use sleep
long pause = ...;
long end = System.nanoTime() + pause;
do {
Thread.onSpinWait();
} while (System.nanotime() < end);
if ur waiting for a very small period of time it doesn't matter much
also onSpinWait() tells the cpu that loop will be going for a while
I also need to think about the math here
Since I need to sleep a different amount of time depending on how much time the last frame took to execute
did u manage to antialias with opengl?
I left off trying to use Nuklear to make basic UIs
all it does is get a bit thicker
and that was too painful
actually, I found out why it wasn't smooth
I was (again) using degrees instead of radians
now it's one sexy circle
and now I have this issue 😔
bump ☝️
google canvas save state and restore state
ok
managed to fix it by using GL_ONE instead of GL_ONE_MINUS_SRC_ALPHA for blending type
I hope just for that case? otherwise your textures are bound to look like shit in the future
I suggest looking at this video, explains blending really well: https://www.youtube.com/watch?v=o1_yJ60UIxs
For javascript w/ html css. What's the difference between getElementById and GetElementByClassName? Why does only byId let you do <element>.style while className does not
only one element can have a specific id
but many elements can have the same class
Gotcha
I just found it weird you can css both Id's and Class' however.....
in JS you can't edit the style with class'
it's cuz getElementsByClassName returns more than one element
yep
Makes sense.
Finally deciding to try to get better with web design basics and that kinda tripped me up
that's why ids are generally better if ur going to access a certain element many times
ya makes sense.
also, they both do different document transversal
byID is faster because html ids are kind of put in a fast access table
byClassName requires a document scan to find them
stuff like document.getElementByID(...).getElementsByClassName() can be used for optimization purposes, to narrow down the area that is scanned
how much cpu does canvas use ⁉️
ok so GL_ONE totally disregards the destination color
but then idk how to fix the circle strike issue, it's probably because it's trying to blend with the background
hm, maybe if I increase the line width
registerFont doesnt play nicely with multiple fonts from the same family
instead you should use the weigth and style optinos
registerFont("...", { family: "Manrope", weight: "SemiBold" })
registerFont("...", { family: "Manrope", weight: "ExtraBold" })
no idea, never tested
but in theory it should support anything that the font file supports
i've used it with custom fonts and custom font files with custom symbols
well with the other canvas emojis seemed to work by default
with this one they’re the weird black ones
Emoji is dependant on the font itself
no
this is the same font
with napi-rs/canvas the emojis had color
with node-canvas they don't
which is a little disappointing but seeing how horrific napi-rs/canvas does with memory it's ok 👍
Yes, it's reference checker is very nice
Bit buggy sometimes, quite often actually
Not experienced yet
It is able to find references from the same repo
Ofc not the ones that are for example included in a package and not directly in the repo
Well that's obvious 
gopher issue

nice, now I can also draw arcs
pizza
.
how should I approach shapes like this? (green is the desired shape, red is the actual shape)
both have the exact same coordinates
the issue of the red shape I imagine is because the poly area is calculated from the point of origin (top left)
the obvious fix would be starting from the middle in this case, but there's probably a mathematical way of finding the correct initial point
GL2 gl = canvas.getGL().getGL2();
gl.glBegin(GL_POLYGON);
{
for (int i = 0; i < nPoints; i++) {
gl.glVertex2i(xPoints[i], yPoints[i]);
}
}
gl.glEnd();
gl.glFlush();
``` current code, just in case
hm, maybe calculate the bounding box's center and grabbing the nearest point?
hey
am getting this error but idk what's wrong with the package
._. and its needed for database thing
it means you changed your node version
libraries that use native code must be recompiled when the node version changes
you can do that by uninstalling and reinstalling the library
hmm
i guess v17 would be good?
doesnt work
how did you reinstall it?
deleted and installed again
deleted how?
shall i try npm rebuild?
clicked on node_modules and deleted
ok
then>
npm install better-sqlite3
done
then?
uhm its giving error
@quartz kindle ?
what error?
its long ;-;
show
you have two versions of better-sqlite3
v8 normally installed and v7 installed by the package enmap
the one that is giving the error is the v7 one used by enmap
if you really need enmap, check if there is an update that uses the newer version
otherwise try removing it and see if the newer version of bettersqlite works
@quartz kindle @earnest phoenix do you guys think this is safe from race conditions? ```c
// a global bool
bool gInitiated = false;
void someCleanupFn() {
if (gInitiated) {
gInitiated = false;
// ... code ...
}
}
// someCleanupFn is added to several close event handlers - that may be called from different threads
or should i use a Mutex instead
[and also @wheat mesa]
generally it is safe yes, although it depends what exactly it is cleaning up and how it affects other threads
also the cleanup function itself might need a race condition protection if there is a possibility a new gInitiated is created while the cleanup function is not done cleaning the old one yet
A variable that is to be modified by function(s) in multiple threads are generally safer when they use a mutex, if the value is being modified but something else tries to modify it at the same time that causes a problem
The general advice is whenever you have data that can be read and modified by more than one thread at a time you want to use a lock
Also is a lock the same thing as a mutex
Only reason I ask being that my CS class generally uses the term lock for these situations
when the OS uses files for mutex purposes its also called lockfile
Depends on what you refer to as a "lock", it's not the same terminology used for only these situations, it could also be used to keep track of lock files
also, back to the original question, usually multithreaded languages and systems have functions that only modify something if the current value of something matches the expected value
atomic operations are usually done that way, something like modifyVariable(new value, expected value) // only executes if the varuable's current value matches the expected value
and it executes the value change in an guaranteed atomic manner
I’m assuming this is C or C++ from looking at the syntax, and I’ve only really done multithreading in Java so I can’t really help too much
im also mostly basing myself from how JS does it with sharedArrayBuffer
but its probably better and safer to use a higher level C++ mutex than low level instructions like these
trynna do in-place array rotation, but I can't figure out how to do it with O(n) complexity
like, I always lose some indexes based on the jump size
for example, with jump size of 1 I lose the value of the leftmost index
with jump size 2 I lose the leftmost 2
this is what I have currently, I have no idea how to achieve that without resorting to a second array or O(nx) complexity
cant you use a simple variable to hold the missing value, then re-place it at the end of the loop?
issue is the missing value is "values" for jump > 1
guess I'll just go with O(n+x) for now, wost case it'll be O(2n)
which is creating a new array with size equal to jump size
but no matter how many jumps you do, you are always reading+writing one element at a time, so you will need at most one temporary element
no, I mean, it'll always iterate array.length times
I'm not using recursion to prevent falling into O(nx)
like, an array with 5 elements and jump size of 3 would be shifted 3 times, so 15 operations (3 read/writes per entry)
hm
check out the last answer here:
https://www.geeksforgeeks.org/array-rotation/
it claims to be o(n) speed with o(1) storage, but its still creating temporary values
I think that's somehow what I did lmao
but with one less loop and inverse iteration
its really interesting tho, im reading more in depth now trying to understand it
it doesnt iterate through the whole array
i mean it does, but not in a loop form
now I can return to the original issue lul, spent 3 hours finding out how to rotate an array
such an apparently trivial question but never stopped to think on how to do it in-place
the second answer from here explains better the GCD concept
saw that answer
i guess you cant get faster that that
each element is only read/written once
unless creating a new array is somehow faster
but i doubt it
I couldn't undestand that specific answer
? Would you like to use experimental app/ directory with this project? » No / Yes
noticed this while installing nextjs
what's it about
yay, it worked
too much java out here
made an algo to calculate boundaries and center, then rotated the coordinate arrays to leave the nearest point as first index
now I can draw relatively complex shapes
as long as lines don't intersect tho, but that's something for another day
it gets funky when lines intersect
xD
doesnt your lib have functions for path filling tho?
or do you have to reinvent even that
I'm using opengl so...well
just found out opengl has a thing called GLU that tesselates irregular polygons
isnt GL_POLYGON supposed to support filling?
it does
but it works the same way as GL_TRIANGLE_FAN
basically connects all vertices to the first vertex
which is why that's happening
i see
why isn't the font applying was working earlier ☹️
Are u supposed quote it?
no
i thought u meant the weight, i think you need to quote the font name
they quote it in the examples
i'm not sure if it's something obvious but it was working earlier 😵💫
“It was working earlier” is literally the most common thing we see in this channel. You have to have changed something since then otherwise it would still be working
Try this but without the “extrabold” part
same thang
❓
Are you registering the font before creating the canvas?
yes
I assume you’re looking at this https://github.com/Automattic/node-canvas/#registerfont
yeah
Is ExtraBold even a real weight? That doesn’t make much sense
look
I know but I’m pretty sure that’s not a thing
what's not a thing?
Just because you “register” it as ExtraBold doesn’t mean that ExtraBold exists
how
Weight should be a number or something like "bold"
Look at this
can you explain how my other font is working then?
I don’t know
It probably had a default
It doesn’t matter how it was working because it’s still wrong
My man
I’m not going to argue with you over this because you’re going to drag it on for an hour
well I'm just asking your saying it's wrong yet it was working with setting the font weights as I was right now earlier
what did you change between the "it was working and now its not"?
idk tbh
The only weights I know are bold, bolder, boldest and black
And the thin variants
Tho never checked if js has them too
Hi, I am trying to make a bots site, but I don't know how to make a system to avoid the dm all by the bots. I am using python and flask
Huh?
I mean when I add the bots to the server, is there any way to prevent the bots from doing dm all in case they are scam bots?
You can prevent bots from DMing a ton of members in your server by not adding them to your public server in the first place
That’s why you test bots in a private server
Also it’s a bad idea to add a ton of bots to one server anyways, top.gg learned the hard way on that one
haha, yes, I've seen this kind of situations in servers of this style, that's why I try to find a solution
yes, that's what I'm doing but I'm afraid that once the bot passes the tests and is added to the main server the bot developer will do a dm all
then just don't add it there's no way to stop a bot from dming people
unless they disable their dms
alr
thx guys
That’s why you never invite them to the main server
its not possible to prevent that, thats why when it happens users report it and the bot is banned fro the server
The site is working now plz update in #site-status
is it a good idea to put everything in a try catch
Depends on what you’re doing
it doesnt make much difference today, but a few yeats ago try catch would make your code slower
depends on the context
applying java logic, you should let exceptions float up the call stack until some code which is appropriately fitted to handle it catches it
so if you do catch try only catching what matters
Yes.
putting your main call in a try catch is probably not useful in of itself
@quartz kindle @earnest phoenix how is this valid
see this meme as a demonstration
why object promise
Await, or .then the promise
i do await ☹️
a better question is how do i await something in a map
Like, a .map?
yes
Yeah no don’t do that
bruh
You are not meant to use async functions in map operations like that
Just loop through and push the result to a new array?
@quartz kindle could probably elaborate better than me on the async thing
if you want to concurrently resolve multiple promises, you can combine .map with Promise.all()
idk what a Promise.all() is
a built in function to resolve multile promises at once
bot said no
because it itself is also a promise
"bruh"
const result = await Promise.all([promise1, promise2, ...])
result.join(...)
ok
let me see
it says .join is not a function
👁️👄👁️
i think waffles suggestion is easier than this even tho it's extra effort
then yoi did something wrong, but yeah you can also await in a for loop
althougj awaiting in a for loop is sequential and not concurrent
He probably did await Promise.all(…).join(…)
probably
Nope
My opengl work was very limited so far
I plan to return to it later on to learn it more
Either with jogl or C++
Meh, I need to add arbitrary shape support to the lib
But glScissors only allows rectangles
Can you not just define vertices and use glDraw(GL_TRIANGLES, …)?
The one abt making polys will be solved with tesselation
If I undestood glStencil correctly it can be done through bitmasking, but there's probably a more efficient way other than iterating over a shape's area
this is what i did
🤦♂️
what's wrong
i honestly dont know

