Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Posts tagged python
Suppose I have some code in a file myscript.py like: def my_function(): print("Test") What steps do I need to take in order to make my_function run? That is to say: how do I get Python to ...
I have to modify a legacy Django web application where there are 2 tables to store the same information using the same database structure, and the only difference is the names of the tables (and th...
When you try to do a privileged systemd operation without the privilege, you get an escalation prompt: $ systemctl stop docker ==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-units ==== ...
I have a flat list where each item is the key and value for an attribute. I want to transform this into a nested list where each attribute is a sublist. Example input: [ "attr1 apple 1", "a...
Suppose I have some code like: filename = "bad_dir" print(f"File not found: {filename}.") raise(FileNotFoundError) When the exception isn't caught, the stack trace is printed at the end of ...
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 ...
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 ...
Here's a JSON log formatter for Python. I want to be able to log details of exceptions (and have some capability to debug-by-logs). I want to be able to log extra data in JSON format (in addition...
PEP20 aka the Zen of Python has a statement: Namespaces are one honking great idea -- let's do more of those! What exactly are we supposed to "do" according to this? Is it saying we should h...
Sometimes code needs to assign (or otherwise use) a value that depends on some condition. The naive approach is to use explicit branching, which in Python would look like: if some_condition(): ...
Consider this code example: def example(param=[]): param.append('value') print(param) When example is repeatedly called with an existing list, it repeatedly appends to the list, as ...
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] It gives a SyntaxError, highlightin...
Suppose you have a jinja template like this: I am going to {{ foo }} to get some {{ bar }}. I hope I can find: {% for i in baz %} - {{i}} {% endfor %} This template will require you to pass ...
In VS Code, is it possible to run Python code on the text being edited? I realize that I can save my text, create a .py file, switch to a terminal (including VS Code's own terminal) and run the .p...
MWE import random import pandas as pd from itertools import product random.seed(12345) dies = [1, 2] cells = list(range(10)) currents = [100, 200, 300] dcc = list(product(dies, ce...
Is there a Python serialization format that has capabilities similar to Pickle, but is text based? The problem I always have with pickle is that it's binary, so I can't manually view or edit the d...
I regularly run into the problem that I have a Python function that I want to use in both, eager and graph execution mode. I therefore have to adjust the code so that it can handle both situations....
TL;DR Is (a and b) equivalent to tf.logical_and(a, b) in terms of optimization and performance? (a and b are tensorflow tensors) Details I use Python with Tensorflow. My priorities are Make t...
I would like to use tf.timestamp() when it is available (eager mode and graph mode without XLA), and use 0. (or a better fallback if there is one) when it is not available (with XLA; @tf.function(j...
I want my CLI Python program to schedule a task, and then exit. After some times has passed (say 10 minutes) the task should execute. The task can be a Python method or a shell command, whatever i...
I am writing a Python package where I have two classes in different files that (indirectly) depend on each other. If I wouldn't care about type-hints, there would be no problem, but unfortunately,...
Is it possible for a Python program to send itself in the background? For example, on Linux you can do nohup some_cmd & and any program will run in the background. Some programs also support s...
I have the following xarray Dataset: d: <xarray.Dataset> Dimensions: (x: 79, y: 63, t: 1) Coordinates: * x (x) float64 0.9412 1.882 2.824 3.765 ... 71.53 72.47 73.41 74.35 * ...
Suppose I have some variables like: >>> count = 8 >>> status = 'off' I want to combine them with some hard-coded text, to get a single string like 'I have 8 cans of Spam®; b...
I know that I can display a single string in the terminal window like print("example") (or similarly with a string in a variable), and I know how to open text files and write to them. I also know ...
Suppose I have two variables that are called animal and age, and print them as a string in the console like so: animal = "giraffe" age = 25 print("A %s can live up to %d years" %(animal,age)) ...
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]} ...
I have a function that loads JSON data and is declared to return a dictionary with string keys and values of any type (Dict[str, Any]). However, mypy is raising an error stating that I am returning...
Is there a way to add support for "move symbol" in Python code for VS Codium? PyCharm can do this, but I am looking for a VSC solution. PyLance can do this, but PyLance itself is closed source, a...
I am working on adding uncertainty to some of my dynamics within a larger Monte Carlo simulation. As a way to perform multiple operations on each value, I decided to make and use a new function to ...
I'm experiencing an issue where my program appears to freeze when executing the post_comments_to_lemmy function. This function fetches comments from the GitHub API and posts them to a Lemmy instanc...
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', '...
Question What is the current state of the art database app? How does it compare to SQL? Can pandas be used in place of either? If not, is there something that bridges the gap between SQL and pand...
I'm trying to subclass pdb to have a debugger that, in case of a call to a decorated function, can "step in" the decorated function directly and skip the decorator content altogether. A well-behave...
Using parentheses in Javascript is always needed when you want to create functions, if/else statements and for/while loops. But in Python it has a function that is called tuples. When using an if s...
The dictionary methods .keys(), .values(), and .items() all return view objects. Said objects reflect any changes to the underlying dictionary. This is often useful. Is there a way to get such a v...
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 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...
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...
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...
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...
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...