General Programming Discussion

8712 readers
16 users here now

A general programming discussion community.

Rules:

  1. Be civil.
  2. Please start discussions that spark conversation

Other communities

Systems

Functional Programming

Also related

founded 6 years ago
MODERATORS
1
 
 

Hello everyone :)

Firstly, I'm not anyhow related to programming at ALL ! I can put together some easy to use bash scripts, to automate some stuff, while copy/pasting from the web and doing A LOT of trial an error. It sometimes took me a whole week to have a functional script. I also sometimes asked for some help here on Lemmy and still uses some of those script people helped me out to build up from the ground !

Secondly, I'm not really into the AI slope and have a lot of arguments why I hate it (Unauthorized webscrapping, High energy consumption, Privacy nightmare....).

However, I have to say I'm quite impressed how good my first experience with AI was, considering my very limited knowledge in programming. The script works perfectly for my use case. I had to switch between Claude and O4-mini to get the best results and took me a whole day of prompting around and testing before it behaved like I wanted it to !

Without going to much into details, I was looking for a way to interface with Qbittorrent's API and manage my torrents and move them around in new categories in an automated way. What this python script does is to export the .torrent file in specific directory (not the files) and stop the torrent and move it in a new category if desired based on specific criteria (ratio, category, tags, seeding time...) . If correctly configured, directories and sub-directories are also created on the fly.


My own opinion after this experience is that it probably won't write a fully functional software (not yet?), but for something like scripting or learning basic programming skills it's a very capable assistant!

  1. What do you think of the code overall? (see below)

  2. Also, do you think it's still relevant to get proficient and learn all the details or just stick to the basic and let AI do the heavy lifting?


DISCLAIMER

Keep in mind this works perfectly for my use case and maybe won't work like you expect. It has it's flaws and will probably break in more niche or specific use cases. Don't use it if you don't know what you're doing and proper testing ! I'm not responsible if all your torrents are gone !!!


## Made by duckduckgo AI ##
## Required to install requests with pip install requests ##
## see duck.ai_2025-07-13_16-44-24.txt ##

import requests
import os

# Configuration
QB_URL = "http://localhost:8080/"  # Ensure this is correctly formatted
USERNAME = ""  # Replace with your qBittorrent username
PASSWORD = ""  # Replace with your qBittorrent password
MIN_RATIO = 0.0  # Minimum ratio to filter torrents
MIN_SEEDING_TIME = 3600  # Minimum seeding time in seconds
OUTPUT_DIR = "./directory"  # Replace with your desired output directory
NEW_CATEGORY = ""  # Specify the new category name
NEW_PATH = "~/Downloads"

# Optional filtering criteria
FILTER_CATEGORIES = ["cats"]  # Leave empty to include all categories
FILTER_TAGS = []  # Leave empty to include all tags
FILTER_UNTAGGED = False  # Set to True to include untagged torrents
FILTER_UNCATEGORIZED = False  # Set to True to include uncategorized torrents

# Function to log in to qBittorrent
def login():
    session = requests.Session()
    response = session.post(f"{QB_URL}/api/v2/auth/login", data={'username': USERNAME, 'password': PASSWORD})
    if response.status_code == 200:
        print("Login successful.")
        return session
    else:
        print("Login failed.")
        return None

# Function to get torrents
def get_torrents(session):
    response = session.get(f"{QB_URL}/api/v2/torrents/info")
    if response.status_code == 200:
        print("Retrieved torrents successfully.")
        return response.json()
    else:
        print("Failed to retrieve torrents.")
        return []

# Function to stop a torrent
def stop_torrent(session, torrent_hash):
    response = session.post(f"{QB_URL}/api/v2/torrents/stop", data={'hashes': torrent_hash})
    if response.status_code == 200:
        print(f"Stopped torrent: {torrent_hash}")
    else:
        print(f"Failed to stop torrent: {torrent_hash}")

# Function to start a torrent
def start_torrent(session, torrent_hash):
    response = session.post(f"{QB_URL}/api/v2/torrents/start", data={'hashes': torrent_hash})
    if response.status_code == 200:
        print(f"Started torrent: {torrent_hash}")
    else:
        print(f"Failed to start torrent: {torrent_hash}")


# Function to create a category if it doesn't exist
def create_category(session, category_name, save_path):
    # Skip category creation if category or save path is empty
    if not category_name or not save_path:
        print("Skipping category creation: category or save path is empty.")
        return

    # Check existing categories
    response = session.get(f"{QB_URL}/api/v2/torrents/categories")
    if response.status_code == 200:
        categories = response.json()
        if category_name not in categories:
            # Create the new category with savePath
            payload = {
                'category': category_name,
                'savePath': save_path
            }
            response = session.post(f"{QB_URL}/api/v2/torrents/createCategory", data=payload)
            if response.status_code == 200:
                print(f"Category '{category_name}' created with save path '{save_path}'.")
            else:
                print(f"Failed to create category '{category_name}'. Status code: {response.status_code}")
        else:
            print(f"Category '{category_name}' already exists.")
    else:
        print("Failed to retrieve categories. Status code:", response.status_code)


# Function to set the category for a torrent
def set_torrent_category(session, torrent_hash, category_name, save_path):

    # If either category or path is missing, remove the category
    if not category_name or not save_path:
        response = session.post(f"{QB_URL}/api/v2/torrents/setCategory", data={'hashes': torrent_hash, 'category': ''})
        if response.status_code == 200:
            print(f"Removed category for torrent: {torrent_hash}")
        else:
            print(f"Failed to remove category for torrent: {torrent_hash}")
        return


def is_category_match(torrent_category, filter_categories):
    """
    Check if the torrent's category matches any of the filter categories.
    Supports partial category matching.

    Args:
    torrent_category (str): The category of the torrent
    filter_categories (list): List of categories to filter by

    Returns:
    bool: True if the category matches, False otherwise
    """
    # If no filter categories are specified, return True
    if not filter_categories:
        return True

    # Check if the torrent's category starts with any of the filter categories
    return any(
        torrent_category == category or
        torrent_category.startswith(f"{category}/")
        for category in filter_categories
    )


# Modify the export_torrents function to use the new category matching
def export_torrents(session, torrents):
    # Create the output directory if it doesn't exist
    os.makedirs(OUTPUT_DIR, exist_ok=True)

    for torrent in torrents:
        ratio = torrent['ratio']
        seeding_time = torrent['seeding_time']
        category = torrent.get('category', '')
        tags = torrent.get('tags', '')

        # Use the new category matching function
        if (ratio >= MIN_RATIO and
            seeding_time >= MIN_SEEDING_TIME and
            is_category_match(category, FILTER_CATEGORIES) and
            (not FILTER_TAGS or any(tag in tags for tag in FILTER_TAGS)) and
            (not FILTER_UNTAGGED or not tags) and
            (not FILTER_UNCATEGORIZED or category == '')):

            torrent_hash = torrent['hash']
            torrent_name = torrent['name']
            export_url = f"{QB_URL}/api/v2/torrents/export?hash={torrent_hash}"


            # Export the torrent file
            response = session.get(export_url)
            if response.status_code == 200:
                # Save the torrent file with its original name in the specified output directory
                output_path = os.path.join(OUTPUT_DIR, f"{torrent_name}.torrent")
                with open(output_path, 'wb') as f:
                    f.write(response.content)
                print(f"Exported: {output_path}")

                # Stop the torrent after exporting
                stop_torrent(session, torrent_hash)

                # Create the new category if it doesn't exist
                create_category(session, NEW_CATEGORY, NEW_PATH)

                # Set the category for the stopped torrent
                set_torrent_category(session, torrent_hash, NEW_CATEGORY, NEW_PATH)
            else:
                print(f"Failed to export {torrent_name}.torrent")

# Main function
def main():
    session = login()
    if session:
        torrents = get_torrents(session)
        export_torrents(session, torrents)

if __name__ == "__main__":
    main()

2
3
4
5
6
7
8
 
 

For a school project I need to make a simple python program. I need ideas so if you have something that you want made for you then please post it here. I'll release it here under a gnu general public license once I've finished.

9
 
 

What called my attention is that assessments of AI are becoming polarized and somewhat a matter of belief.

Some people firmly believe LLMs are helpful. But programming is a logical task and LLMs can't think - only generate statistically plausible patterns.

The author of the article explains that this creates the same psychological hazards like astrology or tarot cards, psychological traps that have been exploited by psychics for centuries - and even very intelligent people can fall prey to these.

Finally what should cause alarm is that on top that LLMs can't think, but people behave as if they do, there is no objective scientifically sound examination whether AI models can create any working software faster. Given that there are multi-billion dollar investments, and there was more than enough time to carry through controlled experiments, this should raise loud alarm bells.

10
 
 

Vcc - the Vulkan Clang Compiler, is a proof-of-concept C and C++ compiler for Vulkan leveraging Clang as a front-end, and Shady our own research IR and compiler. Unlike other shading languages, Vcc aims to stick closely to standard C/C++ languages and merely adds a few new intrinsics to cover GPU features. Vcc is similar to CUDA or Metal in this regard, and aims to bring the advantages of standard host languages to Vulkan shaders.

Key Features

Vcc supports advanced C/C++ features usually left out of shading languages such as HLSL or GLSL, in particular raising the bar when it comes to pointer support and control-flow:

  • Unrestricted pointers
    • Arithmetic is legal, they can be bitcasted to and from integers
  • Generic pointers
    • Generic pointers do not have an address space in their type, rather they carry the address space as a tag in the upper bits.
  • True function calls
    • Including recursion, a stack is implemented to handle this in the general case
  • Function pointers
    • Lets you write code in a functional style on the GPU without limitations
  • Arbitrary goto statements - code does not need to be strictly structured !

Many of these capabilities are present in compute APIs, but are not supported in most graphics APIs such as DirectX or Vulkan. We aim to address this gap by proving these features can and should be implemented. More on why we think that’s important.

11
12
13
 
 

As, programmers what is the project that you made that made you learn the most and also added the most value to your resume?

@technology
@programming

#technology #programming

14
15
16
17
18
19
 
 

Hi everyone, I recently launched Flogo, a visual programming app that lets you build and simulate flowcharts with real logic execution. It’s designed for both students and developers, and supports things like:

Conditional blocks (if, for, while, dowhile)

Real-time simulation (console or navigation mode)

Dynamic input

Plotting graphs (plot() function)

Complex numbers, matrices, and over 100 built-in functions

Free, no ads, available for iOS & Android

If you're into visual coding, algorithm design, or teaching programming, give it a try! Feedback is welcome.

Links:

Android: https://play.google.com/store/apps/details?id=com.flogo.myapp

iOS: https://apps.apple.com/it/app/flogo/id6744535672

Thanks!

20
 
 
21
22
23
 
 

cross-posted from: https://lemmy.ml/post/29133545

Like every major GCC release, this version will bring many additions, improvements, bug fixes, and new features. GCC 15 is already the system compiler in Fedora 42. Red Hat Enterprise Linux (RHEL) users will get GCC 15 in the Red Hat GCC Toolset. It's also possible to try GCC 15 on Compiler Explorer and similar pages.

This article describes only new features implemented in the C++ front end; it does not discuss developments in the C++ language itself.

The default dialect in GCC 15 is still -std=gnu++17. You can use the -std=c++23 or -std=gnu++23 command-line options to enable C++23 features, and similarly for C++26 and others.

24
 
 

The GCC developers are pleased to announce the release of GCC 15.1.

The C frontend now defaults to the GNU C23 dialect. Some code needs porting for this. Some remaining C23 features have been implemented, as well as some new C2Y features.

The C++ frontend now implements several further C++26 features, some missing C++23 bits, and defect report resolutions. The libstdc++ library now notably experimentally supports std and std.compat modules, more algorithms usable in constexpr functions, flat maps and sets, and std::format support for containers and other ranges.

GCC now implements the Clang [[clang::musttail]] and [[clang::flag_enum]] attributes and their GNU counterparts with the same meaning for the C family language frontends. Support for new counted_by and nonnull_if_nonzero attributes has been added too.

The Fortran frontend has experimental support for unsigned integers.

GCC 15.1 has new COBOL frontend, so far supported only on a few 64-bit targets.

OpenMP support now includes metadirectives, tile and unroll constructs, interop construct and dispatch construct.

The vectorizer can now vectorize loops with early exits when array or buffer sizes aren't statically known. At -O2 can now vectorize some cheaply vectorizable loops with unknown tripcount.

Some code that compiled successfully with older GCC versions might require source changes, see Porting to GCC 15 for details.

For details see GCC 15 Release Series Changes, New Features, and Fixes).

25
 
 

I'm currently job hunting and looking for a platform to prep for interviews.

Leetcode is nice but it locks hard problems behind a paywall that I honestly can't afford right now.

I mean I can still read the problem from https://leetcode.ca/, but it's hard to test it against a good set of test cases.

Please share alternative portals with a decent hard problem collection with testcases

view more: next ›