Bay 12 Games Forum

Please login or register.

Login with username, password and session length
Advanced search  
Pages: 1 ... 789 790 [791] 792 793 ... 796

Author Topic: if self.isCoder(): post() #Programming Thread  (Read 838552 times)

Bumber

  • Bay Watcher
  • REMOVE KOBOLD
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #11850 on: December 16, 2020, 09:06:18 am »

Code: [Select]
for Ryblue in range (256):
    for Rxblue in range (256):
        bitmap[Rxblue][Ryblue][0] = floor((Rxblue/256)*Rblue)
           
for Gyblue in range(256):
    for Gxblue in range(256):
        bitmap[Gxblue][Gyblue][1] = floor((Gxblue/256)*Gblue)
       
for Byblue in range(256):
    for Bxblue in range(256):
        bitmap[Bxblue][Byblue][2] = floor((Bxblue/256)*Bblue)
can be reduced to:
Code: [Select]
for yblue in range (256):
    for xblue in range (256):
        bitmap[xblue][yblue][0] = floor((xblue/256)*Rblue)
        bitmap[xblue][yblue][1] = floor((xblue/256)*Gblue)
        bitmap[xblue][yblue][2] = floor((xblue/256)*Bblue)

Same for y-axis. You could even do the x and y-axis at the same time:
Code: [Select]
for y in range (256):
    for x in range (256):
        bitmap[x][y][0] = ( (y/256)*Rpink + (x/256)*Rblue )//2
        bitmap[x][y][1] = ( (y/256)*Gpink + (x/256)*Gblue )//2
        bitmap[x][y][2] = ( (y/256)*Bpink + (x/256)*Bblue )//2
(Double check this, I haven't run it.)
« Last Edit: December 16, 2020, 09:33:37 am by Bumber »
Logged
Reading his name would trigger it. Thinking of him would trigger it. No other circumstances would trigger it- it was strictly related to the concept of Bill Clinton entering the conscious mind.

THE xTROLL FUR SOCKx RUSE WAS A........... DISTACTION        the carp HAVE the wagon

A wizard has turned you into a wagon. This was inevitable (Y/y)?

methylatedspirit

  • Bay Watcher
  • it/its
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #11851 on: December 16, 2020, 05:50:55 pm »

Code: [Select]
for yblue in range (256):
    for xblue in range (256):
        bitmap[xblue][yblue][0] = floor((xblue/256)*Rblue)
        bitmap[xblue][yblue][1] = floor((xblue/256)*Gblue)
        bitmap[xblue][yblue][2] = floor((xblue/256)*Bblue)
Works exactly as expected. No errors here.

Quote from: Bumber
Same for y-axis. You could even do the x and y-axis at the same time:
Code: [Select]
for y in range (256):
    for x in range (256):
        bitmap[x][y][0] = ( (y/256)*Rpink + (x/256)*Rblue )//2
        bitmap[x][y][1] = ( (y/256)*Gpink + (x/256)*Gblue )//2
        bitmap[x][y][2] = ( (y/256)*Bpink + (x/256)*Bblue )//2
(Double check this, I haven't run it.)

It works. Also, it turns out that you don't need to use floor() or integer division at all if you're using Pillow. It's perfectly able to handle floating-point numbers in its images. One catch: the RGB values must be in the interval [0,255], or stuff like this happens:

(remove the division by 2 when adding the RGB values together)

No saturation arithmetic here, no siree!
« Last Edit: December 16, 2020, 06:01:19 pm by methylatedspirit »
Logged

methylatedspirit

  • Bay Watcher
  • it/its
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #11852 on: December 16, 2020, 08:11:22 pm »

I've implemented the ghettoest version of saturating arithmetic possible (technically only saturating at 255 but not 0) in my program, and I get this unsightly blue line going through where it would overflow. Here's the current code for cycling through the colors:

Code: [Select]
# cycling through x-axis (black to blue) + cycling through y-axis (black to pink)
for x in range (256):
    for y in range (256):
        R = (y/256)*Rpink + (x/256)*Rblue
        G = (y/256)*Gpink + (x/256)*Gblue
        B =  (y/256)*Bpink + (x/256)*Bblue
        # Ghettoest way of doing saturated arithmetic
        if R > 255:
            R = 255
        if G > 255:
            G = 255
        if B > 255:
            B = 255
        bitmap[x][y][0] = R
        bitmap[x][y][1] = G
        bitmap[x][y][2] = B

And the output is mostly what I wanted, but there's a blue streak going from bottom-left to top-right:


I'm not quite sure what happened, but I wouldn't be surprised if this hack job of a way of doing saturating arithmetic is part of the problem.
Logged

Bumber

  • Bay Watcher
  • REMOVE KOBOLD
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #11853 on: December 17, 2020, 12:46:44 am »

You can use "min" instead of the if statements:
Code: [Select]
bitmap[x][y][0] = min(R,255)
You wanted blue on the x-axis, right? You could swap (y/256) with (x/256). You could also check if there's a setting in the Pillow functions that draws the axes differently.
« Last Edit: December 17, 2020, 01:08:10 am by Bumber »
Logged
Reading his name would trigger it. Thinking of him would trigger it. No other circumstances would trigger it- it was strictly related to the concept of Bill Clinton entering the conscious mind.

THE xTROLL FUR SOCKx RUSE WAS A........... DISTACTION        the carp HAVE the wagon

A wizard has turned you into a wagon. This was inevitable (Y/y)?

methylatedspirit

  • Bay Watcher
  • it/its
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #11854 on: December 17, 2020, 01:16:55 am »

I mean, a swapped axis never hurt anybody. I can always go to Paint, then use the right combination of flip vertical/horizontal and rotates to get everything right again. The "blue line" problem... for the time being, I'll just do a blur on the whole image and no-one's the wiser. It's sidestepping the problem (thus, inelegant), but it's good enough for my purposes. Maybe. The perfectionist in me's yelling that it's not an ideal solution, but what do they know?
« Last Edit: December 17, 2020, 01:19:02 am by methylatedspirit »
Logged

McTraveller

  • Bay Watcher
  • This text isn't very personal.
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #11855 on: December 17, 2020, 08:35:45 am »

Re swapped axes:

In almost all computer programming languages, an array like:

Code: [Select]
array[i1][i2]

does not store data with i1 as the x axis and i2 as the y axis - storage is row-major, so the 'x' axis is the rightmost array index.  That is, array(row, col) is coded as array[ col][ row]. So you really just want:

Code: [Select]
bitmap[y][x]...

You don't have to change any other formulae.

EDIT because this was still the last post:

FOR THE LOVE OF ALL THAT IS HOLY PEOPLE, PLEASE DO NOT USE O(N^2) ALGORITHMS INSTEAD OF A DICTIONARY. ALSO, Please CACHE THE RESULTS of a search for "find all items of this type" on a STATIC ARRAY instead of performing the same search 1000 times....
« Last Edit: December 17, 2020, 09:32:27 pm by McTraveller »
Logged

WealthyRadish

  • Bay Watcher
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #11856 on: January 08, 2021, 02:21:26 pm »

I stumbled into some fun with nested and recursive C++ lambdas this morning, while looking for ways to avoid typing out pointer null checks on an ostream* pointer:

Code: [Select]
bool loadFile(const std::string& fname, std::ostream* errLog = nullptr) {

auto err = [errLog](const auto& first, auto&&... rest)->void {
auto err_impl = [errLog](auto& func, const auto& f, auto&&... r)->void {
*errLog << f;
if constexpr (sizeof...(r) > 0) {               
func(func, r...);
}
};
if (errLog) { err_impl(err_impl, first, rest...); }
};

std::string str = "(and bay12) ";

err("Hello error! ", str, 3.14, " 0x", std::hex, 123456789);

return true;
}

Code: [Select]
Hello error! (and bay12) 3.14 0x75bcd15
Logged

methylatedspirit

  • Bay Watcher
  • it/its
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #11857 on: April 13, 2021, 11:31:30 pm »

I feel this question straddles the line between the Generic Computer Advice Thread and this one. It's about a Python 3 script. It automates the tedious process of interpreting raw video data as audio to be encoded (step 1), decoding it back to a raw format (step 2), then putting it into a lossless video codec for later use (step 3). It's an odd thing to do, but it produces interesting results, I think. Without it, those are 3 long and error-prone commands in FFmpeg.

I want to ask about how to implement error checking in the arguments. Here are the instructions:

Code: [Select]
Usage: vid-autoencode [resolution] [framerate] [pixel format] [filename w/ extension] [audio codec] [bitrate]
I want it to expect the following things and warn (raise an exception(?) and ask Y/N to continue) if it's out of range:

[resolution] : string in format n + "x" + m. n, m are unsigned integers. Example: 1920x1080.
[framerate] : positive integer (yes, this completely ignores edge cases like NTSC framerate (29.97... FPS), but I'm not working with those things yet.)
[pixel_format] : matches a list of possible pixel formats (there are too many to count; I will not list them here)
[filename w/ extension]: has ".raw" at the end.
[audio codec]: matches a list of possible audio codecs (again, too many to count)
[bitrate]: either unsigned integer, or in the form n + "k", n being an unsigned integer. Examples: 128k, 48000.

What's the best way to do these checks?

Spoiler: The code (click to show/hide)
Logged

MagmaMcFry

  • Bay Watcher
  • [EXISTS]
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #11858 on: April 14, 2021, 05:56:03 am »

Resolution:
Code: [Select]
import re
regex = re.compile("^(\d+)x(\d+)$")
match = regex.match(resolution_arg)
if match:
  width = int(match[1])
  height = int(match[2])
  # do stuff
else:
  # error handling

Framerate:
Code: [Select]
try
  framerate = int(framerate_arg)
  if framerate <= 0:
    raise ValueError()
  # do stuff
except ValueError:
  # error handling

Pixel format:
Code: [Select]
valid_pixel_formats = ["format1", "format2", "format3"]
if format_arg in valid_pixel_formats:

Filename w/ extension:
Code: [Select]
if filename_arg[-4:] == ".raw":

Audio codec:
Code: [Select]
valid_audio_codecs = ["codec1", "codec2", "codec3"]
if codec_arg in valid_audio_codecs:

Bitrate:
Code: [Select]
try:
  bitrate = 1
  if bitrate_arg[-1] == 'k':
    bitrate = 1000
    bitrate_arg = bitrate_arg[:-1]
  bitrate *= int(bitrate_arg)
  if bitrate < 0:
    raise ValueError()
  # do stuff
except ValueError:
  # error handling
Logged

McTraveller

  • Bay Watcher
  • This text isn't very personal.
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #11859 on: May 01, 2021, 07:17:43 pm »

Just started reading the Rust book...

Wow it's disappointing for trivial reasons.

Aside from a name that conjures images of corrosion, inconvenient syntax (immutable is default, which is far less common than mutable, so will require lots of extra typing). And whoever decided that .expect() is what you do when a call fails, which seems semantically backwards, since I don't expect failure...

The other recommended things are just not my preference (a pox on spaces recommended over tabs! and double pox on opening brace not on its own line!).

I also just can't get over dumb things like requiring cargo (WTF?) or TOML (really? it's called "Tom's Obvious Minimalist Language"?  Reeks of hubris...) 


EDIT: ok there are some neat features, the ownership model is, in fact, pretty cool. I like match too.  Some of the syntax is goofy though, and again, I think the hubris is high.  I think I've said before, I think the use of 'unsafe' is incorrect - it may not actually be unsafe code. I think 'unchecked' or something would be accurate but not imply something that may not be true.
« Last Edit: May 01, 2021, 07:55:15 pm by McTraveller »
Logged

MorleyDev

  • Bay Watcher
  • "It is not enough for it to just work."
    • View Profile
    • MorleyDev
Re: if self.isCoder(): post() #Programming Thread
« Reply #11860 on: May 01, 2021, 08:46:25 pm »

(immutable is default, which is far less common than mutable, so will require lots of extra typing).

I'd disagree with you here. 90% of software programming is sequential and doesn't require prior state changes for values. 90% of 'variable' assignment isn't to mutate the variable later, but to save on typing or recalculation. Immutable-by-default should be standard for modern languages, only gone against with good reason.

Unchecked code is unsafe because it's not checked. The language isn't protecting the programmer, ergo it's unsafe. Like driving a car without as seat belt. Sure, you probably won't crash. But it's still unsafe.
« Last Edit: May 01, 2021, 08:52:29 pm by MorleyDev »
Logged

Telgin

  • Bay Watcher
  • Professional Programmer
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #11861 on: May 01, 2021, 09:06:37 pm »

I don't know anything about Rust, but I'll agree that const/immutable should probably be the default for variables in most languages going forward.  As I've been rebuilding an API at work to use ES6 JavaScript features, I've found surprisingly few variables that couldn't be made const.

Immutable variables also have an advantage over protecting the programmer from accidentally clobbering values they didn't mean to: in theory compilers can optimize generated code using constant variables better than those with mutable variables.  The specifics vary by language and probably aren't massive, but it's there.
Logged
Through pain, I find wisdom.

McTraveller

  • Bay Watcher
  • This text isn't very personal.
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #11862 on: May 01, 2021, 09:17:22 pm »

The immutable thing - I might concede that point given the way you put it.  It could be that the domain in which I code firstly doesn't have dynamic memory allocation at all and variables are always "variable" - which is likely an artifact of architecture and program domain.   "Extra variables to save typing later" are not popular in my line of work due to execution time and memory limitations.  Maybe it's just because I don't like "immutable variable" (or "const variable") - because that just causes me mental dissonance.

I will argue vehemently though that is not what 'safety' means.  Safety isn't about "protecting the programmer", it's an attribute of the code behavior.  Since it's demonstrably possible to have code that behaves safely without checks, and since it's demonstrable that code that is written with strong language checks can be "unsafe" in the real world, calling it 'safe' and 'unsafe' is actually more dangerous than some other word; I would call it 'managed' and 'unmanaged'.  If you argue instead that the checks make it easier to write safe code, I would agree - but the checks don't make safe code.
Logged

bloop_bleep

  • Bay Watcher
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #11863 on: May 01, 2021, 10:12:07 pm »

The immutable thing - I might concede that point given the way you put it.  It could be that the domain in which I code firstly doesn't have dynamic memory allocation at all and variables are always "variable" - which is likely an artifact of architecture and program domain.   "Extra variables to save typing later" are not popular in my line of work due to execution time and memory limitations.  Maybe it's just because I don't like "immutable variable" (or "const variable") - because that just causes me mental dissonance.

I will argue vehemently though that is not what 'safety' means.  Safety isn't about "protecting the programmer", it's an attribute of the code behavior.  Since it's demonstrably possible to have code that behaves safely without checks, and since it's demonstrable that code that is written with strong language checks can be "unsafe" in the real world, calling it 'safe' and 'unsafe' is actually more dangerous than some other word; I would call it 'managed' and 'unmanaged'.  If you argue instead that the checks make it easier to write safe code, I would agree - but the checks don't make safe code.

The future is now, old man.
Logged
Quote from: KittyTac
The closest thing Bay12 has to a flamewar is an argument over philosophy that slowly transitioned to an argument about quantum mechanics.
Quote from: thefriendlyhacker
The trick is to only make predictions semi-seriously.  That way, I don't have a 98% failure rate. I have a 98% sarcasm rate.

MorleyDev

  • Bay Watcher
  • "It is not enough for it to just work."
    • View Profile
    • MorleyDev
Re: if self.isCoder(): post() #Programming Thread
« Reply #11864 on: May 02, 2021, 09:22:42 am »

'value' and 'mutable value' is probably a better term than "variable", you just tend to see them used interchangably nowadays because the name of 'variable' is a bit of a historical artefact. Scala literally use 'val' and 'var' for differentiating between their mutable and immutables (values and variables), although that's visually a bit too indistinct for my liking. Although syntax highlighting can help with that (make mutable variables bright and ugly, F# dark theme has them bright orange).

As for safe and unsafe, the terminology in how Rust is using it is from a language/runtime pov. From the pov of the runtime, the code is 'unsafe' since it's being ran without the checks and guarantees of the runtime but is instead dealing in raw memory pointers.

This is a different context of safe/unsafe than when talking about mathematically proved safety of code, hence the same terms being used for different meanings.

Since Rust is about taking the lessons from newer managed languages that make them more pleasent to work in, and then applying that to a systems language, it inhereted that terminology. This usage of unsafe isn't an invention of Rust, but rather an accepted and standard usage of the term within this context.
« Last Edit: May 02, 2021, 12:50:45 pm by MorleyDev »
Logged
Pages: 1 ... 789 790 [791] 792 793 ... 796