/r/programminghorror

Photograph via snooOG

Share strange or straight-up awful code.

RULES:

  • All posts MUST show terrible code. There are no exceptions.

  • No Editor Themes - If it's just your editor that looks bad, it doesn't belong here.

  • No Advertisement Code. This is generally written by people in marketing who only know what "code" looks like from other ads. It's not real code, so it doesn't belong.

  • No Student Code. Yes, they're learning, but bad code is part of the process.

  • No Generated Code. If it's minified JS, generated XML, or what have you, we don't want it here. Yes, the YouTube homepage has an extra right-angle bracket. We know.

  • No Asking for Help. Go to r/learnprogramming. What are you doing here?

  • No Spamming/Advertising. We don't care about your shitty Youtube video or new crypto that will "change the world".

  • Be Nice. No hate speech of any kind is allowed, as well as generally being a jerk. Talk about the code, not eachother.

  • No Direct Contact of the Mods. Please use the modmail, we don't want to be contacted directly.

  • Please direct stories without code to /r/talesfromtechsupport, and programming questions to /r/learnprogramming

Programming Horror is where developers come together to revel in the idiocy of our peers.

This subreddit is meant for sharing funny programming related stories and strange or straight-up awful code.


For the sake of not being mauled by rabid lawyer bears, please make sure to anonymize your stories - changing the names of people and companies.

For code examples, indent all your lines with 4 spaces to make it more readable:

foo = 'bar'

Sister subreddits

  • talesfromtechsupport - Not everything that involves a computer is a programming horror story. For IT support related submissions, head on over here.
  • talesfromdesigners - For our more artistically inclined brothers and sisters.
  • badcode - When you don't have a story to go along with the horrible, horrible code.
  • shittyprogramming - ninjas that only write in the <b>BEST</b> code
  • usemysoftware - A subreddit for software developers to come post their software and for users to test it.

/r/programminghorror

353,748 Subscribers

1

whatAboutThisCode

Updating some stuff , suddenly seeing error massages with : what about this code 🤣🤣🤣🤔😐

0 Comments
2024/12/01
04:07 UTC

128

It's mine real useful alias of git.

28 Comments
2024/11/30
22:34 UTC

68

Found in Unreal Engine source.

/**
 * Convert an array of bytes to a string
 * @param In byte array values to convert
 * @param Count number of bytes to convert
 * @return Valid string representing bytes.
 */
[[nodiscard]] inline FString BytesToString(const uint8* In, int32 Count)
{
FString Result;
Result.Empty(Count);

while (Count)
{
// Put the byte into an int16 and add 1 to it, this keeps anything from being put into the string as a null terminator
int16 Value = *In;
Value += 1;

Result += FString::ElementType(Value);

++In;
Count--;
}
return Result;
}

https://github.com/EpicGames/UnrealEngine/blob/release/Engine/Source/Runtime/Core/Public/Containers/UnrealString.h

I ran across this while processing data from a network source. I assumed there was a built-in function to convert bytes to FString, and sure enough, there is! It's just not actually useful, since you have to go through and decrement each character afterwards while also cleaning it up.

I've been scratching my head trying to find a reason you might actually want to do this.

10 Comments
2024/11/30
09:29 UTC

0

Please help me doing this using recursion

11 Comments
2024/11/30
09:05 UTC

311

BrainF**k in Regex

22 Comments
2024/11/30
00:29 UTC

0

Macro(help)

Hi to everyone, myb I'm in the wrong category but i will try , I'm looking for someone who can help me with a macro (i can pay for it !!)

1 Comment
2024/11/29
18:27 UTC

78

Recursive type conversion in Bend

17 Comments
2024/11/29
10:22 UTC

4

"I don't want to live on this planet anymore"

38 Comments
2024/11/29
09:55 UTC

199

No clue if code comments count

28 Comments
2024/11/29
06:13 UTC

312

Programming Language Powered by Regex (sorry)

28 Comments
2024/11/28
08:48 UTC

979

Which one are you?

105 Comments
2024/11/27
20:30 UTC

10

Extremely clear and concise documentation

1 Comment
2024/11/27
16:26 UTC

0

AI/ML or Java?

As per current trends in the market there has been less and less requirements for developers and more for AI is it good enough to switch roles as of now ? A little background have an experience of about 4.3 years as a full stack Java developer my current tech stack includes frameworks like hibernate, spring, MVC, JPA, React js and for db it’s been MySQL current qualifications are BE in computer engineering and currently perusing MTech in computer engineering… recently have even experimenting with some cloud tech too like Linux and RHEL in deployment without CI/CD. I have previously worked upon python so it would not be much of a trouble to pick up from that end for AI/ML I mean … seems like there’s much to do on that front or either ways companies think too much of that tech stack any advice would be appreciated my MTech is about to end so I need to figure my tech stack before applying for another job.

3 Comments
2024/11/27
13:33 UTC

604

3 Digit Decimal Addition with Regex

30 Comments
2024/11/27
10:26 UTC

428

4-Bit Addition with Regex

19 Comments
2024/11/27
04:16 UTC

147

Who needs error messages?

13 Comments
2024/11/26
16:36 UTC

0

Damn bruh Anna got plans (open image)

1 Comment
2024/11/26
13:15 UTC

0

golfed calc rate

1 Comment
2024/11/26
11:38 UTC

0

We are looking for freelancers!

4 Comments
2024/11/26
10:56 UTC

0

How to enable Cosign image signing and validation in Kubernetes, continuous validation using policies, and the analysis of artifacts in your repository.

How to enable Cosign image signing and validation in Kubernetes, continuous validation using policies, and the analysis of artifacts in your repository.

Implementing Cosign Image Validation in K8s
How to enable Cosign image signing and validation in K8s, continuous validation using policies, and the analysis of artifacts in your repository.

https://medium.com/@rasvihostings/implementing-cosign-image-validation-in-gke-ba803f6f623c

3 Comments
2024/11/26
03:57 UTC

334

Who needs async / await?

29 Comments
2024/11/25
22:21 UTC

363

A very useful function indeed

34 Comments
2024/11/24
17:04 UTC

98

KVB advertising programming jobs using JS

9 Comments
2024/11/24
16:11 UTC

131

A smart one-liner that calculates area of a triangle based on three points

34 Comments
2024/11/24
15:45 UTC

403

Finally solved a problem nobody had: introducing my genius decorator 🚀

Function Switcher

A Python decorator that allows switching function calls behavior. When you pass a string argument to a function, it's interpreted as the target function name, while the original function name becomes the argument.

Installation

pip install git+https://github.com/krakotay/function-switcher.git

Usage

from function_switcher import switch_call

@switch_call
def main():
    hello('print')  # Prints: hello
    length = mystring('len')  # Gets length of 'mystring'
    print(f"Length of 'mystring' is: {length}") # Length of 'mystring' is: 8

main()
47 Comments
2024/11/24
13:00 UTC

326

js guys are so cooked

47 Comments
2024/11/24
04:01 UTC

228

Found in production code. Deadlocks in `block`.

29 Comments
2024/11/23
22:25 UTC

0

Classic Algorithms in B+: A Showcase of Simplicity and Power

This document demonstrates how the B+ programming language—centered on minimalism, context passing, and algebraic computation—can elegantly solve classic programming problems. These examples are not just exercises but a proof of concept, highlighting B+ as a transformative language that simplifies computation to its essentials.

1. FizzBuzz

The Problem: Print numbers from 1 to 100. Replace multiples of 3 with "Fizz," multiples of 5 with "Buzz," and multiples of both with "FizzBuzz."

fizzbuzz(n) => {
    context = n; // Context explicitly defines the current number
    result = case {
        context % 15 == 0: "FizzBuzz", // Divisible by both 3 and 5
        context % 3 == 0: "Fizz",      // Divisible by 3
        context % 5 == 0: "Buzz",      // Divisible by 5
        _: context                     // Otherwise, the number itself
    };
    result; // Output the result
};

sequence(1, 100) |> map(fizzbuzz); // Apply fizzbuzz to each number in the sequence

Why This Works:

  • Context passing: Each number is passed through the computation explicitly.
  • Algebraic composition: sequence generates numbers, and map applies fizzbuzz to each.
  • Pure computation: No mutable state or hidden side effects.

2. Prime Sieve (Sieve of Eratosthenes)

The Problem: Find all prime numbers up to n.

sieve(numbers) => {
    context = numbers;           // Current list of numbers
    prime = head(context);       // First number is the current prime
    filtered = tail(context) |> filter(x => x % prime != 0); // Filter multiples of the prime
    [prime] + sieve(filtered);   // Recursively add the prime and process the rest
};

prime_sieve(n) => sieve(sequence(2, n)); // Generate primes from 2 to n

Why This Works:

  • Recursive rewriting: Each pass extracts a prime and removes its multiples.
  • Algebraic operations: List concatenation and filtering are fundamental constructs.
  • Context passing: Each recursive call processes a new context of numbers.

3. Merging Two Hashmaps

The Problem: Combine two hashmaps, resolving key collisions by overwriting with the second map's value.

merge(hashmap1, hashmap2) => {
    context = (hashmap1, hashmap2); // Pair of hashmaps
    merged = context.0 |> fold((key, value), acc => {
        acc[key] = value; // Insert key-value pairs from the first map
        acc;
    });
    context.1 |> fold((key, value), merged => {
        merged[key] = value; // Overwrite with values from the second map
        merged;
    });
};

Why This Works:

  • Context passing: The pair of hashmaps forms the computational context.
  • Pure computation: Folding iteratively builds the merged hashmap, ensuring no hidden state.

4. Quicksort

The Problem: Sort an array using the divide-and-conquer paradigm.

quicksort(array) => {
    case {
        length(array) <= 1: array, // Base case: array of length 0 or 1 is already sorted
        _: {
            pivot = head(array); // Choose the first element as the pivot
            left = tail(array) |> filter(x => x <= pivot); // Elements less than or equal to the pivot
            right = tail(array) |> filter(x => x > pivot); // Elements greater than the pivot
            quicksort(left) + [pivot] + quicksort(right);  // Concatenate the sorted parts
        }
    }
};

Why This Works:

  • Context passing: The array is progressively subdivided.
  • Algebraic composition: Results are combined through concatenation.

5. Fibonacci Sequence

The Problem: Compute the n-th Fibonacci number.

fibonacci(n) => {
    fib = memoize((a, b, count) => case {
        count == 0: a,                     // Base case: return the first number
        _: fib(b, a + b, count - 1);       // Compute the next Fibonacci number
    });
    fib(0, 1, n); // Start with 0 and 1
};

Why This Works:

  • Memoization: Results are cached automatically, reducing recomputation.
  • Context passing: The triple (a, b, count) carries all required state.

6. Factorial

The Problem: Compute n! (n factorial).

factorial(n) => case {
    n == 0: 1,              // Base case: 0! = 1
    _: n * factorial(n - 1) // Recursive case
};

Why This Works:

  • Term rewriting: Factorial is directly expressed as a recursive computation.
  • Context passing: The current value of n is explicitly passed down.

7. Collatz Conjecture

The Problem: Generate the sequence for the Collatz Conjecture starting from n.

collatz(n) => {
    context = n;
    sequence = memoize((current, steps) => case {
        current == 1: steps + [1],                   // Base case: terminate at 1
        current % 2 == 0: sequence(current / 2, steps + [current]), // Even case
        _: sequence(3 * current + 1, steps + [current])             // Odd case
    });
    sequence(context, []); // Start with an empty sequence
};

Why This Works:

  • Context passing: current tracks the sequence value, and steps accumulates results.
  • Memoization: Intermediate results are cached for efficiency.

8. GCD (Greatest Common Divisor)

The Problem: Compute the greatest common divisor of two integers a and b.

gcd(a, b) => case {
    b == 0: a,             // Base case: when b is 0, return a
    _: gcd(b, a % b);      // Recursive case: apply Euclid’s algorithm
};

Why This Works:

  • Term rewriting: The problem is reduced recursively via modulo arithmetic.
  • Context passing: The pair (a, b) explicitly carries the state.

Key Takeaways

Core Principles in Action

  1. Explicit Context Passing: B+ eliminates hidden state and implicit side effects. Every computation explicitly operates on its input context.
  2. Algebraic Operations: Problems are solved using a small set of compositional primitives like concatenation, filtering, and recursion.
  3. Term Rewriting: Recursion and pattern matching define computation naturally, leveraging algebraic simplicity.
  4. Memoization: Automatic caching of results ensures efficiency without additional complexity.

Why These Examples Matter

  • Clarity: B+ examples are concise and easy to understand, with no room for hidden logic.
  • Universality: The same principles apply across vastly different problem domains.
  • Efficiency: Built-in features like memoization and algebraic composition ensure high performance without sacrificing simplicity.

Conclusion

These classic problems illustrate the essence of B+: computation as algebra. By stripping away unnecessary abstractions, B+ allows problems to be solved elegantly, highlighting the simplicity and universality of its design.

3 Comments
2024/11/23
03:04 UTC

0

Why Parameterization in B+ Isn't Parameterization Per Se

In typical programming contexts, parameterization refers to the act of defining a generic template or structure that can accept "parameters" to customize its behavior or content (e.g., generics in Java or templates in C++). However, in B+, parameterization is approached differently, emphasizing structural reuse and contextual adaptation rather than literal genericity.

Here’s why B+ parameterization differs fundamentally:

1. Focus on Structural Contextualization

In B+, structures (like ex-sets, sums, and products) are reused and extended contextually rather than instantiated from a generic template. This means:

  • Instead of defining a "parameterized type" and passing arguments to it, you define a structure that grows or transforms based on the surrounding context.
  • The concept of breadcrumbs or context passing plays a role in determining how structures adapt rather than relying on explicit arguments.

Example: Sum Object without Explicit Parameterization

Option = Sum(None: {}, Some: Product(Value: {}))

Here, Some can hold a value of any type. Rather than "parameterizing" Option with a type (Option<T> in other languages), B+ allows the context to define what kind of Value is valid.

2. Reusable Patterns Without Explicit Parameters

Rather than parameterizing objects, B+ encourages defining reusable structural patterns. These patterns act like templates but are implicitly resolved through composition.

Example: Reusable Structure

KeyValue = Product(Key: {}, Value: {})
  • Instead of KeyValue<K, V> (generic parameterization), you adapt this structure by defining Key and Value in the specific context where it’s used.

StringToNumber = KeyValue(Key: {String}, Value: {Number})

Why is this different?

There’s no abstract type-level substitution happening. Instead, you specialize the structure by reinterpreting its fields in the immediate context.

3. Implicit Adaptation Through Constraints

Constraints in B+ enable implicit customization of structures. Rather than parameterizing a type with restrictions (e.g., List<T: Number>), B+ introduces constraints directly into the structure definition, making the type context-aware.

Example: Constraining a List-Like Object

List = Sum(Empty: {}, Node: Product(Value: {}, Next: List))

Add a constraint in context:

NumberList = List where Value: {Number}
  • Instead of parameterizing List with a type T, you constrain its Value field to a specific set ({Number}).

4. Context Breadcrumbs and Growth

In B+, parameterization is replaced by contextual growth, where:

  • Structures grow recursively by embedding themselves into larger contexts.
  • Breadcrumbs track how the context adapts the structure at each step.

Example: Recursive Contextual Growth

Tree = Sum(Empty: {}, Node: Product(Value: {}, Left: Tree, Right: Tree))

Adapt in context:

BinarySearchTree = Tree where Value: Ordered

Instead of explicitly parameterizing Tree with an Ordered type, the context imposes constraints that propagate as the structure grows.

5. Why This Approach?

The B+ paradigm avoids explicit parameterization for several reasons:

  1. Avoid Type-Level Overhead: Explicit generics add a layer of complexity that doesn’t align with B+’s minimalist philosophy.
  2. Context-Driven Semantics: The meaning and constraints of a structure should emerge from its use rather than being baked into a generic definition.
  3. Decoupling: By avoiding parameterization, B+ ensures structures are self-contained and composable without dependence on external arguments.

How This Feels in Practice

  1. Generalization by Reuse
    • In B+, you define simple, general-purpose structures (like Product and Sum) and adapt them directly in use contexts, rather than creating parameterized blueprints.
  2. Customizing by Constraints
    • Contextual constraints allow you to impose specific rules on structures without needing to rework their definitions or pass parameters.
  3. Context Passing Over Explicit Arguments
    • Breadcrumbs serve as a record of adaptation, growing naturally with the structure rather than requiring explicit input.

Conclusion

B+ moves away from traditional parameterization by embracing:

  • Structural reuse: Genericity arises from how structures are composed, not from explicitly parameterizing them.
  • Contextual constraints: Instead of parameter substitution, constraints shape structures.
  • Dynamic growth: Structures evolve recursively and contextually, ensuring simplicity and expressiveness without generics.

This approach is consistent with B+’s design philosophy, prioritizing clarity, minimalism, and adaptability over formal parameterization mechanics.

7 Comments
2024/11/22
22:20 UTC

Back To Top