Posts tagged python
I'm still a novice in Python. But have come across a question about format specifiers. For example, if I have two variables that are called animal and age. And print a string in the console using f...
Problem How can I compress each column of a dataframe to the output of a function (i.e., mean), preserving columns? MWE import pandas as pd data = {"A": [1, 2, 3, 4], "B": [5, 6, 7, 8]} ...
Hello everyone, I am seeking help with understanding why multithreading does not work correctly in this example: import time import matplotlib.pyplot as plt import concurrent.futures voltage...
I have written a screensaver program that, in part, uses the current wallpaper for some visual effects. However, finding the current wallpaper in different operating systems and environments is les...
I started adding types to my (working) solution to Exercism's "Kindergarten Garden" exercise, to learn how typing with python and Mypy (strict) works. While doing so, I ran into a Mypy error that I...
Background The coefficient of variation is: defined as the ratio of the standard deviation to the mean Question Is there a built-in function for this? Tried I know I can do df.std() / df...
I want a way to make it so that I can use list B to find out if a copy of itself exists in list A. listA = ['1', '1', '0', '1', '0', '1', 'down'] 2 ['0', '0', '1', '1', '1', '1', 'up'] 2 ['1', '...
MWE filename = "bad_dir" print(f"File not found: {filename}.") raise(FileNotFoundError) Question How do I raise an exception while adding additional information? In the example above, the...
There's this new challenge on Code Golf CD and I'm using Python to do it. A little bit of golfing already took place, so the code might look a bit messy for you. Anyway, I'm proud of what I've writ...
MWE import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.DataFrame(np.random.rand(9, 4), columns=['a', 'b', 'c', 'd']) df.plot.bar(table=True) # don't want plot, ...
What exactly is the Python Global Interpreter Lock (GIL)? As someone who is relatively new to Python, is this something I need to be aware of, or is this just some implementation detail of the inte...
MWE import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.DataFrame(np.random.rand(9, 4), columns=['a', 'b', 'c', 'd']) df.plot.bar() plt.show() Question Ho...
class ExtendUserSession(MiddlewareMixin): """ Extend authenticated user's sessions so they don't have to log back in following 15 minutes (set by Django's default `SESSION_COOKIE_A...
I've written the following code implementing a state machine in Python, and I'd like some feedback on it. The basic idea is that each state has a set of corresponding actions that trigger a state ...
Having recently learned about protocols in Python, I now wonder if you can write a protocol for enumerations. That is, a protocol that says that you are supposed to pass an enum that has certain it...
In Python 2, I was able to create a file named .env within a project folder like so: # .env MY_ID=abc123 TOKEN=4567890 Then in a Python file in the same directory, I could read these variable...
I have console scripts in my virtual environment in \env\Scripts, installed with packages (e.g. black, pytest, coverage). If I try to execute these in Git Bash, the output is not returned to the te...
The problem Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets are closed by ...
I've written a class that allows to access dictionary entries of arbitrary dicts with appropriate string keys through attribute access syntax on an instance of the class. My questions are: Is...
I have two tables: Table1: Name Description Amount 123 Description123 123 456 Description456 456 789 Description789 666 101 Description777 101 133 De...
The problem You are given the following information, but you may prefer to do some research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All t...
I have a Python script that needs to access some data (or configuration) file in its very own folder. For example, say script.py does something like this: with open('data.txt') as file: data ...
docutils's rst2pseudoxml.py is reporting this error: Unknown interpreted text role "meth". even though the build command: sphinx-build -b html -d build/doctrees source build/html runs fine and pro...
Based on my last question comes new one. How to loop over 300 000 rows and edit each row string one by one? I have a list of 11-digit numbers stored in one single column in Excel, and I need to s...
The following list comprehension worked when I tried it: [num for num in hand if num != 11] But this doesn't work: [num for num in hand if num != 11 else 22] which led me to believe that you ca...
I have a list of 11-digit numbers stored in one single column in Excel, and I need to separate the digits according to this pattern: 2-2-1-3-3. Example: 00002451018 becomes 00 00 2 451 018. How c...
I spend a lot of time writing CLI tools in Python, and I would like to support tab-completion in a style similar to Git. For example, subcommands should be tab-completable, options should expand ba...
I often see the construct if __name__ == '__main__' in Python code. For example, the queens.py demo in the Python repository ends with these two lines: if __name__ == "__main__": main() Ho...
I manage a wsgi application that accepts JSON data via POST from potentially untrusted sources. Normally it is treated as a text blob and never parsed, but there is a value in the expected input th...
Now I build a Python script to execute automaticaly a dynamic analysis on apk and I block because I use this library and call objection. When I run my script, the objection command creates an inst...
MarkFuncs has really gotten huge progress, at least in my eyes, and now, I want to make math possible in the language. Background MarkFuncs is a programming language that I have been working on f...
I've just started playing around with pygame and have written a small game in it, of which I'd like a review. Note that I'm not only a complete beginner in pygame, but I also have very little exper...
I'm trying to parse lines like "THIS. THAT..OTHER " so that "THIS. THAT." is found. There can be more than one <word><dot> separated by a space except no space after the last one. ...
I'm still in the process of making MarkFuncs and having given up from copy-pasting open-source interpreters, them using OOP too, I decided to make one without OOP and with scratch alongside with th...
from tkinter import * from tkinter import messagebox, filedialog import pyttsx3 import PyPDF2 import os import webbrowser root = Tk() # root.geometry("500x500") root.title("Audio Book") ...
Here in Python, I created a program for this challenge and I'm having trouble debugging it. I already fixed most errors I have on my program but here's what I have left: x=y=z=[];i=0.0;a=int(input...
I'm using Python to invoke another program in a sub-process. I've noticed my memory sometimes gets so large as to crash the system, and I'm wondering if I'm not correctly cleaning up the memory som...
I have around 20,000 .npy files in a directory. That main directory has no subfolders:- Main_dir | |--1.npy |--2.npy |--3.npy |--........ The absolute file paths are stored ...
I'm trying to log error messages from Requests exceptions. Example: try: make_web_request() except RequestException as ex: logging.error(ex) Example output: ERROR : ('Connection abo...
I work with CentOS operating system and my only shell is Bash. I want to create a script which prompts a user with a question like "What is your web application root?" The user should answer dire...
I'd like some help understanding why the third call to print() raises AttributeError: 'NoneType' object has no attribute 'format' from os import path import inspect def myfunction(): pri...
It is possible to create a new formatter class by subclassing string.Formatter class and then to use it like myformatter.format("{foo:customformat}", foo=foo). It's not super-convenient though, and...
When writing Python-based apps (e.g. Django, Flask, etc.), it's often the case that import statements can be found all over the place, often more than once for the same module. For example, you can...
I am looking to take a partial derivative of a sympy polynomial with respect to a symbol in the polynomial. In the sympy documentation for poly.diff(...) it gives sample code like this: from sympy ...
When I want to print a number or a string, I can use f-strings (Python >= 3.6) or str.format, and I can use just the variable between braces, or use format specifiers. Ex: num, text = 10, 'abc' ...
I have a small new Python 3.8 Flask project with some relative import quirks. For the DB I use SQLAlchemy with Flask-Migrate. My project has the following general structure: controllers/ static/ te...