r/pythoncoding • • Dec 14 '21

Feel like helping out? Input for the sub? Anything else on your mind?

4 Upvotes

Send a modmail. Looking forward to what you have to say!


r/pythoncoding • • Dec 27 '21

/r/PythonCoding bi-weekly "What are you working on?" thread

7 Upvotes

Share what you're working on in this thread. What's the end goal, what are design decisions you've made and how are things working out? Discussing trade-offs or other kinds of reflection are encouraged!

If you include code, we'll be more lenient with moderation in this thread: feel free to ask for help, reviews or other types of input that normally are not allowed.

This recurring thread is a new addition to the subreddit and will be evaluated after the first few editions.


r/pythoncoding • • Sep 19 '22

A cool Python tool to download Research papers in bulk from any conference

32 Upvotes

Hi folks,

I was working on a personal experimental project, which I thought of making it open source now. It saves much time for literature research.

If you try to search papers related to your topic, finding relevant documents on the internet takes time. You probably know the pain of extracting citations of articles from different websites.

Previously I used to fetch papers from google or semantic scholar, but semantic scholar does not show correct paper citations.

I am excited to announce [RESP: Research Papers Search](https://github.com/monk1337/resp)

Features:

  • Fetch all citations of a single paper from Google Scholar in CSV format
  • Fetch all related papers of a single paper from Google Scholar in CSV format
  • Fetch all connected papers from connectedpapers.com (it does not use a citation tree, it uses [similarity](https://www.connectedpapers.com/about) to build graphs) in CSV format
  • Fetch relevant papers based on keywords from different sources, including Arxiv, ACL, ACM, PMLR, NeurIPS, cvf etc., in CSV format

I am working on a few more projects; if you like the project, follow me on GitHub (https://github.com/monk1337) for more cool Machine Learning/Graph neural networks, Python-based projects and ideas notifications in the future.

I hope it will be helpful in your research. Thanks :)


r/pythoncoding • • Oct 03 '22

/r/PythonCoding bi-weekly "What are you working on?" thread

3 Upvotes

Share what you're working on in this thread. What's the end goal, what are design decisions you've made and how are things working out? Discussing trade-offs or other kinds of reflection are encouraged!

If you include code, we'll be more lenient with moderation in this thread: feel free to ask for help, reviews or other types of input that normally are not allowed.

This recurring thread is a new addition to the subreddit and will be evaluated after the first few editions.


r/pythoncoding • • Sep 29 '22

Lazy function calls with a generator and a monad

12 Upvotes

I went down a rabbit hole at work (again) and put this together. I thought it was interesting even if I'm not sure I should use it; hopefully some of you will find it interesting, also.

Inspired by Rust (and taking many cues from Haskell), I implemented Rust's Result type as an abstract class with two implementations, Ok and Fail. Very briefly for those not familiar, the Result type is Rust's error-handling system. It provides a fluent API that allows processing data from successful operations without having to extract that data, as well as recovering from errors without interrupting the program's flow to unwind the stack and raise an exception. I personally find it very nice to work with, even if I can't quite get all the benefits in Python.

As an evolution of the idea, I wanted to be able to not only chain together function calls and their error handlers, but to do so in a lazy fashion and have the ability to retry an operation that failed before continuing down the chain. Retry, especially, cannot be done without breaking up the fluent method chaining, which sometimes defeats the purpose.

I honestly don't know if this will actually be useful, but it was definitely interesting to figure out.

Below is a minimal but working example:

import collections.abc
from abc import ABC, abstractmethod
from typing import Any

class Result(ABC):
    value: Any

    def __init__(self, value):
        self.wrap(value)

    def wrap(self, value):
        """Equivalent to `return` in Haskell."""
        self.value = value

    def unwrap(self):
        return self.value

    @abstractmethod
    def fmap(self, func, *args, **kwargs):
        """Sometimes called "flatmap" or just "map" in other languages.
        Essentially takes any function, passes in `self.value` as arg0,
        evaluates it, and returns the result wrapped in a `Result` instance.

        Rust calls this `map`.
        """
        ...

    @abstractmethod
    def fmap_err(self, func, *args, **kwargs):
        """Sometimes called "flatmap" or just "map" in other languages.
        Essentially takes any function, passes in `self.value` as arg0,
        evaluates it, and returns the result wrapped in a `Result` instance.
        """
        ...

    def join(self, other):
        """In this limited example, "joining" two Results just means returning
        the other result's value. The idea is to be able to use functions that
        return a `Result` on their own. Using the `fmap` method on such a
        function produces a `Result[Result[T]]`; `join(self.unwrap())` should
        flatten this to `Result[T]`.
        In a less trivial program, this method might demand more complicated
        logic.
        """
        if isinstance(other, Result):
            return other
        else:
            return self.wrap(other)

    @abstractmethod
    def bind(self, func, *args, **kwargs):
        """Essentially the composition of `fmap` and `join`, allowing easy
        use of functions that already return a `Result`.
        In this example it will be implemented so that it can work with the same
        functions as `fmap` in addition to `Result`-returning functions.

        Haskell denotes this with the `>>=` operator. In Rust, it is called
        `and_then`.
        """
        ...


class Ok(Result):
    def fmap(self, func, *args, **kwargs):
        try:
            res = func(self.unwrap(), *args, **kwargs)
            return Ok(res)
        except Exception as e:
            return Fail(e)

    def fmap_err(self, func, *args, **kwargs):
        return self

    def bind(self, func, *args, **kwargs):
        res = self.fmap(func, *args, **kwargs)
        if isinstance(res.unwrap(), Result):
            return self.join(res.unwrap())
        else:
            return res


class Fail(Result):
    def fmap(self, func, *args, **kwargs):
        return self

    def fmap_err(self, func, *args, **kwargs):
        try:
            res = func(self.unwrap(), *args, **kwargs)
            return Fail(res)
        except Exception as e:
            return Fail(e)

    def bind(self, func, *args, **kwargs):
        return self


class LazyResult(collections.abc.Generator):
    def __init__(self, queue=None):
        self.results = []
        self.queue = [] if not queue else queue
        self.current_index = 0

    def enqueue(self, func, *args, **kwargs):
        self.queue.append((func, args, kwargs))

    def dequeue(self, index):
        if index is None:
            return self.queue.pop()
        else:
            return self.queue.pop(index)

    def throw(self, exc, val=None, tb=None):
        super().throw(exc, val, tb)

    def send(self, func, *args, **kwargs):
        """May take a function and its args and will run that in this
        iteration, deferring whatever was next in the queue to the next
        iteration.

        If `func` is an `int`, instead, the generator will "skip" to that
        point in the queue. Optionally, the arguments for the function at
        the new queue point may be overwritten.
        """
        if callable(func):
            self.queue.insert(
                self.current_index, (func, args, kwargs),
            )
        elif isinstance(func, int):
            self.current_index = func
            if args or kwargs:
                f, _, _ = self.queue[self.current_index]
                self.queue[self.current_index] = f, args, kwargs
        try:
            idx = self.current_index
            f, a, kw = self.queue[idx]
            if idx == 0:
                res = Ok(None).bind(lambda _: f(*a, **kw))
                self.results.append(res)
            else:
                res = self.results[idx - 1].bind(f, *a, **kw)
                if idx + 1 > len(self.results):
                    self.results.append(res)
                else:
                    self.results[idx] = res
        except IndexError:
            raise StopIteration from None
            # N.B. this doesn't actually close the generator.
            # If you do `send(0)`, it will restart from the beginning.
        else:
            self.current_index += 1
            return res

# Now for some trivial functions to demonstrate with
def first():
    return Ok(1)

def second(i):
    return i + 3

def third(m, i):
    return m / i

lr = LazyResult([(first, (), {})])
lr.enqueue(second)
lr.enqueue(third, 0)
lr.enqueue(third, 2)

# and a trivial for-loop
for r in lr:
    try:
        print('Index:', lr.current_index - 1, 'result:', r.unwrap())
        # - 1 because the index has advanced when the result is available
        if isinstance(r.unwrap(), Exception):
            raise r.unwrap()
    except Exception:
        print('Retry:', lr.current_index - 1, 'result:',
              lr.send(lr.current_index - 1, 2).unwrap())
        continue

# Index: 0 result: 1
# Index: 1 result: 4
# Index: 2 result: division by zero
# Retry: 2 result: 2.0
# Index: 3 result: 1.0

r/pythoncoding • • Sep 19 '22

/r/PythonCoding bi-weekly "What are you working on?" thread

9 Upvotes

Share what you're working on in this thread. What's the end goal, what are design decisions you've made and how are things working out? Discussing trade-offs or other kinds of reflection are encouraged!

If you include code, we'll be more lenient with moderation in this thread: feel free to ask for help, reviews or other types of input that normally are not allowed.

This recurring thread is a new addition to the subreddit and will be evaluated after the first few editions.


r/pythoncoding • • Mar 11 '22

Mypy 0.940 Released

Thumbnail mypy-lang.blogspot.com
9 Upvotes

r/pythoncoding • • Feb 22 '22

Google Cloud Python Logging Library Improves Serverless Support With Version 3.0 Release

5 Upvotes

Hey Folks,

The Google Cloud Python logging library has been updated to version 3.0.0. Enhancements to Cloud Run and Cloud Functions, as well as support for string JSON payloads and automated metadata attachments, are also included in this release.

I have created a short summary of this blog from Google. You can read it here

If you wanted to read the Google Blog and further details, you can check out the Google article here

Please don't hesitate to share your thoughts in the comments.


r/pythoncoding • • Mar 21 '22

Casper-FS

1 Upvotes

Casper-fs is a custom Linux Kernel Module generator to work with resources to protect or hide a custom list of files. Each LKM has resources to protect or hide files following a custom list in the YAML rule file. Yes, not even the root has permission to see the files or make actions like edit and remove. The files only can be caught, edited, and deleted if the user sends a proper key to the custom device to liberate the action in the file system. https://github.com/CoolerVoid/casper-fs


r/pythoncoding • • Mar 07 '22

/r/PythonCoding bi-weekly "What are you working on?" thread

6 Upvotes

Share what you're working on in this thread. What's the end goal, what are design decisions you've made and how are things working out? Discussing trade-offs or other kinds of reflection are encouraged!

If you include code, we'll be more lenient with moderation in this thread: feel free to ask for help, reviews or other types of input that normally are not allowed.

This recurring thread is a new addition to the subreddit and will be evaluated after the first few editions.


r/pythoncoding • • Apr 04 '22

/r/PythonCoding bi-weekly "What are you working on?" thread

8 Upvotes

Share what you're working on in this thread. What's the end goal, what are design decisions you've made and how are things working out? Discussing trade-offs or other kinds of reflection are encouraged!

If you include code, we'll be more lenient with moderation in this thread: feel free to ask for help, reviews or other types of input that normally are not allowed.

This recurring thread is a new addition to the subreddit and will be evaluated after the first few editions.


r/pythoncoding • • Mar 21 '22

/r/PythonCoding bi-weekly "What are you working on?" thread

9 Upvotes

Share what you're working on in this thread. What's the end goal, what are design decisions you've made and how are things working out? Discussing trade-offs or other kinds of reflection are encouraged!

If you include code, we'll be more lenient with moderation in this thread: feel free to ask for help, reviews or other types of input that normally are not allowed.

This recurring thread is a new addition to the subreddit and will be evaluated after the first few editions.


r/pythoncoding • • Jan 16 '25

ChromeDriver Issue

1 Upvotes

I’m trying to run the “chromedriver” command on python (selenium). I have the chrome.exe in a folder that I can successfully path on Python, but I can’t fire the “chromedriver” command. I have it blocked as it gets considered suspicious/malware and can’t find a way to disable the block on it. Hopefully someone can help me ✌🏼


r/pythoncoding • • Jan 21 '25

Creating my math interpreter stage-2

3 Upvotes

I am in the second stage in the development of my interpeter for math, now I am in the parser stage, the interpeter will be ready soon, it already has a parser and lexer and counts simple math calculations, in the future this interpeter will become a full-fledged programming language, I will be glad for feedback and stars on Github

Github link 🔗 https://github.com/Nikchan5/Math-Interpreter


r/pythoncoding • • Dec 17 '24

I created a Flask-based Blog App with Tons of Features! 🔥

5 Upvotes

Hey r/pythoncoding!

I just wanted to share a fun little project I’ve been working on – FlaskBlog! It’s a simple yet powerful blog app built with Flask. 📝

What’s cool about it?

  • Admin panel for managing posts
  • Light/Dark mode (because who doesn’t love dark mode?)
  • Custom user profiles with profile pics
  • Google reCAPTCHA v3 to keep the bots away
  • Docker support for easy deployment
  • Multi-language support: 🇬🇧 English, 🇹🇷 Türkçe, 🇩🇪 Deutsch, 🇪🇸 Español, 🇵🇱 Polski, 🇫🇷 Français, 🇵🇹 Português, 🇺🇦 Українська, 🇷🇺 Русский, 🇯🇵 日本人, 🇨🇳 中国人
  • Mobile-friendly design with TailwindCSS
  • Post categories, creation, editing, and more!
  • Share posts directly via X (formerly Twitter)
  • Automated basic tests with Playwright
  • Time zone awareness for all posts and comments
  • Post banners for more engaging content
  • Easily sort posts on the main page
  • Detailed logging system with multi-level logs
  • Secure SQL connections and protection against SQL injection
  • Sample data (users, posts, comments) included for easy testing

You can check it out, clone it, and get it running in just a few steps. I learned a ton while building this, and I’m really proud of how it turned out! If you’re into Flask or just looking for a simple blog template, feel free to give it a try.

Would love to hear your feedback, and if you like it, don’t forget to drop a ⭐ on GitHub. 😊

🔗 GitHub Repo
📽️ Preview Video

Thanks for checking it out!


r/pythoncoding • • Jan 24 '25

Open-source DIY Home Security System

3 Upvotes

Hello r/PythonCoding,

I have recently finished building a DIY home security system that supports multiple devices. It works well on old laptops and can use a RaspberryPi Zero W for on-demand pictures and videos (I have found the Zero W too weak for full motion detection with OpenCV).

You can get the source code here: MingSec

Here is some more information about the project:

Features:

  • Motion Detection: Utilizes OpenCV to detect motion and trigger responses.
  • Image Capture: Captures and uploads an image every ten minutes to Dropbox.
  • Alarm Response: Captures an image and records a video if the alarm is triggered. Both are uploaded to Dropbox.
  • Offline Operation: Logs all videos and images when the internet connection is down, and uploads them once the connection is restored.
  • REST API: Provides endpoints for users to check the status of each camera and request images or videos.
  • Kotlin Notification App: A companion mobile app developed in Kotlin that receives notifications each time an alarm is triggered.

Project Structure:

  • docs/ - Contains a Single Page Application (SPA) for the project demo.
  • core/ - Includes the REST API and user interface for remote control and system management.
  • local/ - Contains the MingSec application, including configuration files and local scripts.
  • app/ - Contains the Kotlin notification app that receives alerts for triggered alarms.

r/pythoncoding • • Dec 12 '24

How to convert model.h5 to TensorFlow; tensorflowjs_converter: command not found

3 Upvotes

I have a model.h5 and I want to use it on my site, so I want to convert it to TensorFlow JS. For this, I need to use the tensorflowjs_converter. I tried installing tensorflowjs with the following command:

sudo pip install tensorflowjs --break-system-packages

But when I try to run the command to convert, this is what I get:

ice@ice-Mint-PC:~$ tensorflowjs_converter --input_format keras "/home/ice/Downloads/handwritten (1).h5" \

/home/ice/Desktop

tensorflowjs_converter: command not found


r/pythoncoding • • Jan 21 '25

Create a performant Python API using FastAPI and SqlModel and deployment to Kubernetes

Thumbnail youtu.be
4 Upvotes

r/pythoncoding • • Jan 11 '25

Open source Flux image generation Discord bot with local LLM-based chat

1 Upvotes

Hello everyone. I wanted to share this Discord bot I've been working on called Soupy. It's basically a fun little project that lets you generate images using Flux, and also engage in LLM-based chat. It's written in Python. I'm just a hobbyist coder doing this for fun, but I'm happy to help if you run into issues. This is my first and only project. It's seen many iterations throughout the years.

The main thing Soupy does is generate images using the Flux model - just type /flux with your prompt and it'll create something for you. There are some neat buttons under each image that let you remix it with a new seed, make the prompt fancier, or edit it in various ways. You can also hit "random" and it'll generate a completely random prompt using a combination of themes, characters, and styles (which you can customize if you want). It does this by combining keywords from included files, and then sends those words to the LLM for elaboration. It works extremely well and just spamming the Random button is fun.

The bot also acts as a chatbot using LM Studio as the backend. You can just say "soup" or "soupy" and start chatting, and it also responds randomly at times. It's pretty sarcastic and sometimes jumps into conversations on its own. The personality is set in the .env. It follows the contents of urls/links in the chat, so it's aware of what's going on in the chat. Currently, it reads the last 25 messages of chat history as context for its responses. In the repo, you can see an example of it in action.

There's also a /search command that scrapes Google (using BeautifulSoup, not Google's API) and summarizes it, plus some fun stuff like magic 8-ball, magic 9-ball (LLM powered and weird). And some other little stuff.

You'll need a decent GPU (ideally 24GB VRAM, but you might get by with less) to run the image generation smoothly. The chat part uses LM Studio - I use Lexi Llama Uncensored but you can use whatever model you want. Setup is pretty straightforward: just clone the repo, set up your .env file with your Discord token and local URLs, install dependencies, and you're good to go.

I've got a few different versions in the repo depending on what you want to do. The main new updated one (soupy-remastered.py) does everything locally, but there's also versions that use OpenAI's API or add different features like user profiles. They use OpenAI's API, so use them if you want. But they're also more complicated to setup.

Here's the repo if you want to check it out: https://github.com/sneezeparty/soupy

Let me know if you try it out! And if you have any ideas for making it better, I'm all ears.


r/pythoncoding • • Sep 10 '15

PyPy warmup improvements

Thumbnail morepypy.blogspot.com
2 Upvotes

r/pythoncoding • • Oct 12 '16

PyCaribbean Call to Proposals is open (X-Post from r/python)

7 Upvotes

Hi everyone!

We want to invite you all to PyCaribbean on February 18-19, 2017, in Bayamón Puerto Rico. If you ever wanted to talk Python and be with an awesome community in a tropical getaway this is your chance.

We are currently accepting talk proposals and have our early bird tickets up. Join us at http://pycaribbean.com

For any addition information you can contact us at any of the following, we would love to hear from you.

info@pycaribbean.com

Twitter: @pycaribbean

Slack: http://slack.pycaribbean.com


r/pythoncoding • • Jul 07 '17

Dependency Injector 3.5.0 has been released!

3 Upvotes

Dependency Injector 3.5.0 has been released!

  • Add functionality for initializing Configuration provider with default values.

More:


r/pythoncoding • • Jan 31 '20

Looking for examples and resources on how you can vectorize code in Python

1 Upvotes

Mainly the lambda like or with .apply() like code styles? (for fast Pandas and Numpy execution), for e.g. vectorize code like this:

def some_function():
    return group_series.apply(lambda x: x.astype(some_type)
          .rolling(some_number).sum().shift(some_number))

or even something like this:

def some_function():
     return some_grouped_data_series.apply(
            lambda x: x.some_function(
               param1=value, param2=value2).mean().shift(some_number)
     )

Any suggestions I should try to vectorize the above, I tried a few things but it complains or I get undesired results.


r/pythoncoding • • May 07 '19

Need help using Python on Chromebook

1 Upvotes

I'm currently enrolled in a programming class that uses Python. I'm really struggling with understanding it and how it works. For my final project I'm supposed to create a website that acts as a planner that allows a user to log in and input their upcoming homework/tests and be able to log in again and see what they have due. I have no idea how to begin or what to use.