content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Can I use split method without delete data in pandas?
My example datatable is below
df
col1
100g strawberry
800g apple
904g melon
If I try this code below,
df[['col2']] = pd.DataFrame(df.col1.str.split('g', expand=True))
I got this result below.
df
col1 col2
100 strawberry
800 apple
904 melon
I ... | Can I use split method without delete data in pandas? | My example datatable is below
df
col1
100g strawberry
800g apple
904g melon
If I try this code below,
df[['col2']] = pd.DataFrame(df.col1.str.split('g', expand=True))
I got this result below.
df
col1 col2
100 strawberry
800 apple
904 melon
I lost my data - 'g' that is necessary.
I want to keep my dat... | [
"First, remove the numbers and write them in a new column(col2) using regex. Then remove the non-numeric expressions for col1.\ndf['col2']=df.col1.str.replace('\\d+', '')\ndf['col1']=df.col1.str.replace('\\D+', '').astype('int32')\nprint(df)\n'''\n col1 col2\n0 100 g strawberry\n1 800 g apple\... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074509488_pandas_python.txt |
Q:
finding duplicates in a string at python 3
def find_duplicate():
x =input("Enter a word = ")
for char in x :
counts=x.count(char)
while counts > 1:
return print(char,counts)
I've got small problem in there i want to find all duplicates in string but this program give me only on... | finding duplicates in a string at python 3 | def find_duplicate():
x =input("Enter a word = ")
for char in x :
counts=x.count(char)
while counts > 1:
return print(char,counts)
I've got small problem in there i want to find all duplicates in string but this program give me only one duplicate ex: aassdd is my input function gave... | [
"return is a keyword that works more or less as immediately exit this function (and optionally carry some output with you). You thus need to remove the return statement:\ndef find_duplicate():\n x =input(\"Enter a word = \")\n for char in x :\n counts=x.count(char)\n print(char,counts)\n\nFurthe... | [
3,
0,
0,
0,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0041682532_python_python_3.x.txt |
Q:
What's the best way to send an object over a network in Python?
I need to send objects around a network. I'm going to be using Twisted, and I've just started looking around the documentation for it.
As far as I know, the only way python implements sockets is through text. So how would I send an object using strin... | What's the best way to send an object over a network in Python? | I need to send objects around a network. I'm going to be using Twisted, and I've just started looking around the documentation for it.
As far as I know, the only way python implements sockets is through text. So how would I send an object using strings? Pickle? Or is there something better?
| [
"The most general serialization on offer between Python end-points is the pickle format (in Python 2.any, be sure to use the cPickle module, and the -1 aka pickle.HIGHEST_PROTOCOL protocol; if you need interoperability between Python 2.any and Python 3.any more care is needed). For especially simple objects, the m... | [
19,
0
] | [] | [] | [
"networking",
"python",
"twisted"
] | stackoverflow_0003191478_networking_python_twisted.txt |
Q:
Discord.py mention application command
I am trying to make a help menu for my discord bot, and would like to make it similar to MEE6's, where it mentions application commands.
But rather than typing myself each command by hand, I would like to automate the process, so that if I add a new command it automatically a... | Discord.py mention application command | I am trying to make a help menu for my discord bot, and would like to make it similar to MEE6's, where it mentions application commands.
But rather than typing myself each command by hand, I would like to automate the process, so that if I add a new command it automatically adds it to the list.
I can easily obtain the ... | [
"For anyone who ecounters this problem: I was not using the correct command.\nI wanted to get type discord.AppCommand, but tree.get_commands() returns discord.Command.\nSo you get all the Application Commands using await tree.fetch_commands(), and those actually have the id that can be used to mention the command.\... | [
0
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074495241_discord.py_python.txt |
Q:
calling calculating functions in Python
it asks for sales tax, but then prints a long number for total tax
#This program will ask user for sales and calcutate state, county, and total sales tax.
#This module calculates the county tax
def askTotalSales():
totalSales=float(input("Enter sales for the month: "))... | calling calculating functions in Python | it asks for sales tax, but then prints a long number for total tax
#This program will ask user for sales and calcutate state, county, and total sales tax.
#This module calculates the county tax
def askTotalSales():
totalSales=float(input("Enter sales for the month: "))
print()
return totalSales
def county... | [
"The problem is with this line:\ntotalTax = float(input(calcTotalTax))\n\ncalcTotalTax is a function, not a number. The program will print the function address (which should seem like a random large number) rather than an output. This should be,\ntotalTax = float(calcTotalTax(stateSales, countrySales))\n\n",
"Pay... | [
0,
0
] | [] | [] | [
"function",
"python"
] | stackoverflow_0074509980_function_python.txt |
Q:
discord.py: RuntimeWarning: Enable tracemalloc to get the object allocation traceback
for filename in os.listdir("./cogs"):
if filename.endswith('.py'):
Bot.load_extension(f'cogs.{filename[:-3]}')
Bot.run(TOKEN)
error:
main.py:259: RuntimeWarning: coroutine 'BotBase.load_extension' was never a... | discord.py: RuntimeWarning: Enable tracemalloc to get the object allocation traceback | for filename in os.listdir("./cogs"):
if filename.endswith('.py'):
Bot.load_extension(f'cogs.{filename[:-3]}')
Bot.run(TOKEN)
error:
main.py:259: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
Bot.load_extension(f'cogs.{filename[:-3]}')
RuntimeWarning: Enable tracemalloc to ge... | [
"Read the error. It says you're not awaiting a coroutine, and if you look at your code you're indeed not awaiting it.\n\ncoroutine 'BotBase.load_extension' was never awaited\n\nThe migration guide explains how to load extensions in 2.0: https://discordpy.readthedocs.io/en/stable/migrating.html#extension-and-cog-loa... | [
0
] | [] | [] | [
"bots",
"discord.py",
"python"
] | stackoverflow_0074510137_bots_discord.py_python.txt |
Q:
Why my app is not find (ModuleNotFoundError: No module named '')?
I'm trying to create an API for my blog with django rest framwork and when I execute the following command :
python manage.py makemigrations posts
This Error appears :
Traceback (most recent call last):
File "/Users/xxx/dev/api/blog/blog/../manag... | Why my app is not find (ModuleNotFoundError: No module named '')? | I'm trying to create an API for my blog with django rest framwork and when I execute the following command :
python manage.py makemigrations posts
This Error appears :
Traceback (most recent call last):
File "/Users/xxx/dev/api/blog/blog/../manage.py", line 22, in <module>
main()
File "/Users/xxx/dev/api/blog/... | [
"Finally I found a solution.\nDelete the content of app.py\nand add blog.posts (<sitename>.<app_name>) in INSTALLED_APPS array inside settings.py file\nINSTALLED_APPS = [\n \"django.contrib.admin\",\n \"django.contrib.auth\",\n \"django.contrib.contenttypes\",\n \"django.contrib.sessions\",\n \"djang... | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"python"
] | stackoverflow_0074509294_django_django_rest_framework_python.txt |
Q:
how to set selection criteria in regex (how to set t the number of character in selection) in python
I am having a text file in which some binary numbers are there. I want to count number of occurrence of some digits/characters using pattern, and I want to sort it in descending order (till this point code working ... | how to set selection criteria in regex (how to set t the number of character in selection) in python | I am having a text file in which some binary numbers are there. I want to count number of occurrence of some digits/characters using pattern, and I want to sort it in descending order (till this point code working fine. but I want result should show only more than 7 characters. it means i can change in my selection pat... | [
"Counter will do exactly the job.\nfrom collections import Counter\n\ncnt = Counter(re.findall(pattern, test_str))\nprint(cnt.most_common()) # [('110110', 3), ('110100', 2), ('101110', 2)]\n\n"
] | [
0
] | [
"If you just want to print the highest value you can do this:\nprint(max(cnt.items()))\n\n"
] | [
-1
] | [
"python",
"python_re",
"sorting",
"string"
] | stackoverflow_0074510159_python_python_re_sorting_string.txt |
Q:
Python turtle drawing glitch?
I wanted to create a type of "grid" using turtle in python but when I start the program the parts of the drawing had a sort of broken line like this:
Glitchy part
This is the full image:
Full drawing
I don't know is this a glitch or something wrong in my code but this is what I did:
f... | Python turtle drawing glitch? | I wanted to create a type of "grid" using turtle in python but when I start the program the parts of the drawing had a sort of broken line like this:
Glitchy part
This is the full image:
Full drawing
I don't know is this a glitch or something wrong in my code but this is what I did:
for column in range(5):
penup()
... | [
"The problem appears to be -207.5. Make that a whole number.\nI also removed some redundant code such as drawing the same square 5 times and used instance mode instead of the error-prone from turtle import * wildcard import that pollutes the namespace.\nimport turtle\n\nt = turtle.Turtle()\nt.color('darkgray')\nt.p... | [
0
] | [] | [] | [
"grid_layout",
"python",
"python_turtle",
"turtle_graphics",
"visual_glitch"
] | stackoverflow_0074509600_grid_layout_python_python_turtle_turtle_graphics_visual_glitch.txt |
Q:
Operations with two graphs
I am having issues with understanding and visualization of graph operations (union, intersection, difference and addition).
I tried to use union1d as one of operations and reshape as a 1d-array product from union1d function into 2d-array. The code works, but not as wanted.
I don't really... | Operations with two graphs | I am having issues with understanding and visualization of graph operations (union, intersection, difference and addition).
I tried to use union1d as one of operations and reshape as a 1d-array product from union1d function into 2d-array. The code works, but not as wanted.
I don't really understand what could be my pro... | [
"You should use networkx operator for the union or intersection of 2 Graphs.\nimport networkx as nx\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\nG = nx.Graph()\n\nplt.figure(figsize =(1, 5))\nG.add_edges_from([(1, 2), (2, 3), (2, 3), (2, 4), (2, 5), (3, 4),\n (4, 5), (4, 6), (5, ... | [
0
] | [] | [] | [
"graph",
"python"
] | stackoverflow_0074510011_graph_python.txt |
Q:
How to plot events on time on using matplotlib
I have 3 lists, each containing numbers, representing a time. The time represents occuring of an event. For example, in this A, I have a number for each occurence of event A. I want to represent this data on a graph. In either of the following two ways:
1)
aabaaabbcca... | How to plot events on time on using matplotlib | I have 3 lists, each containing numbers, representing a time. The time represents occuring of an event. For example, in this A, I have a number for each occurence of event A. I want to represent this data on a graph. In either of the following two ways:
1)
aabaaabbccacac
2)
a-> xx xxx x x
b-> x xx
c-> ... | [
"As an extension to the previous answers, you can use plt.hbar:\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport string\n\nx = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])\ny = np.array([0, 0, 1, 0, 0, 0, 1, 1, 2, 2, 0, 2, 0, 2])\n\nlabels = np.array(list(string.uppercase)) \nplt.barh(y, ... | [
19,
12,
4,
2,
1,
0
] | [] | [] | [
"matplotlib",
"plot",
"python",
"time"
] | stackoverflow_0008772421_matplotlib_plot_python_time.txt |
Q:
The program is only printing one of my statements from the loop
I'm not sure why my code isn't fully printing. It isn't printing the quadrants.
Here are my instructions:
You are writing a program that checks if a point (a,b) is inside a circle of radius R that is centered on the point (c,d).
-a,b,c,d,R are all i... | The program is only printing one of my statements from the loop | I'm not sure why my code isn't fully printing. It isn't printing the quadrants.
Here are my instructions:
You are writing a program that checks if a point (a,b) is inside a circle of radius R that is centered on the point (c,d).
-a,b,c,d,R are all integers entered from the keyboard
-Do not allow negative R values to ... | [
"Your code has a while loop that never exits, so what comes after it is never executed.\nYou should ident everything after distance= math.sqrt(together) into the loop as well.\n",
"You haven't told the code when to stop receiving input so it just awaits your input over and over again. Using a while loop is easy t... | [
0,
0
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0074509657_loops_python.txt |
Q:
Blackjack Capstone Project from 100 Days of Code with Dr. Angela Yu
This question is in relation to Dr Angela Yu's 11th day of Python tutorials. I am not able to execute the code I typed in. The code is typed in replit. Where am I making mistakes? This code is supposed to play the game of Blackjack.
import random
... | Blackjack Capstone Project from 100 Days of Code with Dr. Angela Yu | This question is in relation to Dr Angela Yu's 11th day of Python tutorials. I am not able to execute the code I typed in. The code is typed in replit. Where am I making mistakes? This code is supposed to play the game of Blackjack.
import random
from replit import clear
from art import logo
def draw_card():
cards =... | [
"You never recompute computer_score, so computer_score < 17 will stay True forever.\n"
] | [
0
] | [
"There are bugs in your code.Here are the solutions.\nDo this:\n\n#The main bug is that the program gets stuck at while loop in around lineNO 62 where it says \"while computer_score < 17:\"\n#I could solve it for you but i don't know the game, so do something there.\n#My suggestion: use if statement instead of whil... | [
-1
] | [
"blackjack",
"function",
"project",
"python",
"while_loop"
] | stackoverflow_0074506716_blackjack_function_project_python_while_loop.txt |
Q:
Sending GZIP json using Pika and RabbitMQ
I am currently generating a json which I am sending over RabbitMQ. However it suffers with a limit of 128 MB and my json messages are more than 500 MB. The only feasible step is moving forward with sending the gzip version of the file. Howvever I am not able to find proper... | Sending GZIP json using Pika and RabbitMQ | I am currently generating a json which I am sending over RabbitMQ. However it suffers with a limit of 128 MB and my json messages are more than 500 MB. The only feasible step is moving forward with sending the gzip version of the file. Howvever I am not able to find proper documentation to do so using PIKA, python and ... | [
"Python has standard library for gzip\nimport json\nimport gzip\n\ndata: dict = get_data(...)\ndata_bytes = json.dumps(data).encode()\ncompressed = gzip.compress(data_bytes)\nsend(compressed)\n\n# ... sending the data over AMQP\n\ncompressed = receive(...)\ndecompressed = gzip.decompress(compressed)\ndata_decompres... | [
1
] | [] | [] | [
"gzip",
"pika",
"python",
"rabbitmq"
] | stackoverflow_0074510105_gzip_pika_python_rabbitmq.txt |
Q:
Regular expression to capture different lines
I'm trying to find a better way to capture variable values from a file that stores some information but facing the problem with line breaks and spaces. For example, a DataSetList variable is given that stores a value in two different ways:
Input
Templates = <
item
... | Regular expression to capture different lines | I'm trying to find a better way to capture variable values from a file that stores some information but facing the problem with line breaks and spaces. For example, a DataSetList variable is given that stores a value in two different ways:
Input
Templates = <
item
Name = 'fruits'
TemplateList = '7,12'
end>
... | [
"You can improve the regex a bit.\nID[\\s=]*(?P<UID>\\d*)\\s*Name[\\s=]*'(?P<Name>.*)'\\s*DataSetList[\\s=]*(?P<DataSetList>'(?:[\\d,]|'[\\s+]*')*')\n\nThis gets rid of the unnecessary = and , escapes. The last part now won't match the whitespace after the final bit of the DataSetList.\nI can't see a nice way to av... | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074510096_python_regex.txt |
Q:
Python Dask - how to get row content on string match
I have a very large dataset (>1m entries), then I have a list of postcodes and I want to loop through the postcodes and create a list of matching output areas code from the dataset.
The dataset source: https://geoportal.statistics.gov.uk/datasets/06938ffe68de49d... | Python Dask - how to get row content on string match | I have a very large dataset (>1m entries), then I have a list of postcodes and I want to loop through the postcodes and create a list of matching output areas code from the dataset.
The dataset source: https://geoportal.statistics.gov.uk/datasets/06938ffe68de49de98709b0c2ea7c21a/about
The code:
import dask.dataframe as... | [
"The encoding seems to be \"iso-8859-1\". On top of that the type inference does not work for two (of the) columns (in this particular file) so you have to force it. See code below:\nimport dask.dataframe as dd\ndf= dd.read_csv(\"PCD_OA_LSOA_MSOA_LAD_AUG19_UK_LU.csv\", \\\n dtype={'doterm': 'float64'... | [
2
] | [] | [] | [
"dask",
"dataframe",
"python"
] | stackoverflow_0074509955_dask_dataframe_python.txt |
Q:
Adding "argparser.add_argument()" in script
I am coding something using the YouTubeV3 API to upload a video. I was going through the demo script Google gives, but don't fully understand this piece of code. It uses argparser.add_argument() to add information like the file or title through the command line, however ... | Adding "argparser.add_argument()" in script | I am coding something using the YouTubeV3 API to upload a video. I was going through the demo script Google gives, but don't fully understand this piece of code. It uses argparser.add_argument() to add information like the file or title through the command line, however I want to add this info in the script itself. How... | [
"I finally figured it out, its actaully really simple.\nYou can just do args.[varaible] = [value]\ne.g. args.file = \"video.mp4\" or args.title = \"hello world\"\nYou dont need to create the varaible first, just args.[varaible] = [value] and it will add that new varaible to args\n",
"Python's argparse library is ... | [
1,
0
] | [] | [] | [
"argparse",
"python",
"python_3.x",
"youtube_api"
] | stackoverflow_0074510270_argparse_python_python_3.x_youtube_api.txt |
Q:
how to get mouse location once but dont return and until I get the mouse location twice in napari using python
I am writing on a napari plugin. I have the following to retrieve mouse location
img = cv2.imread("../medium/24708.1_4 at 20X.jpg", cv2.IMREAD_COLOR)
viewer = napari.view_image(img)
layer = viewer
@layer.... | how to get mouse location once but dont return and until I get the mouse location twice in napari using python | I am writing on a napari plugin. I have the following to retrieve mouse location
img = cv2.imread("../medium/24708.1_4 at 20X.jpg", cv2.IMREAD_COLOR)
viewer = napari.view_image(img)
layer = viewer
@layer.mouse_drag_callbacks.append
def callback(layer, event): # (0,0) is the center of the upper left pixel
x,y = vi... | [
"I don't know what you are going to do with the points, or what how you are going to decide how many are needed, but you will need to collect the points. A list seems to fit the bill:\npoints = []\n\n@layer.mouse_drag_callbacks.append\ndef callback(layer, event): # (0,0) is the center of the upper left pixel\n ... | [
1
] | [] | [] | [
"mouse",
"python",
"python_napari"
] | stackoverflow_0074510371_mouse_python_python_napari.txt |
Q:
Understanding pseudocode for beginner
Is pseudocode really as simple as it sounds? Or am I completely missing something? I need to write pseudocode for a simple program to display months of the year including the number of month. Will this work??
Create list containing months
Use for statement to create loop
Displ... | Understanding pseudocode for beginner | Is pseudocode really as simple as it sounds? Or am I completely missing something? I need to write pseudocode for a simple program to display months of the year including the number of month. Will this work??
Create list containing months
Use for statement to create loop
Display month number w/ name
Reading various so... | [
"Pseudocode is useful for thinking about your approach to a problem without language specific syntax. It's quite an individual thing and lots of people would skip it altogether.\nI think what you have is pretty good for that but I would probably write it:\nmonths_list = [list containing each month]\n\nfor month in ... | [
2,
1
] | [] | [] | [
"list",
"pseudocode",
"python"
] | stackoverflow_0074510396_list_pseudocode_python.txt |
Q:
How do I get values by rows in a data frame python
I have a huge data frame with several columns and rows, and I would like to get all values by rows skipping the first column.
import pandas as pd
df = pd.DataFrame([['A', 2, 4, 7], ['B', 6, 1, 5], ['C', 4, 2, 2], ['D', 3, 9, 8]], columns = ["Pen", "A", 'B', 'C'])
... | How do I get values by rows in a data frame python | I have a huge data frame with several columns and rows, and I would like to get all values by rows skipping the first column.
import pandas as pd
df = pd.DataFrame([['A', 2, 4, 7], ['B', 6, 1, 5], ['C', 4, 2, 2], ['D', 3, 9, 8]], columns = ["Pen", "A", 'B', 'C'])
values = []
for row in df.iterrows(0, 1):
value... | [
"you can use stack():\nvals=list(df.iloc[:,1:].stack())\n#[2, 4, 7, 6, 1, 5, 4, 2, 2, 3, 9, 8]\n\n",
"You can use pandas.DataFrame.select_dtypes to select only the numeric columns then pandas.DataFrame.stack with pandas.Series.tolist to make a list of every number found :\nimport numpy as np\n\nout= df.select_dty... | [
0,
0,
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"row"
] | stackoverflow_0074510362_dataframe_pandas_python_row.txt |
Q:
List of lists after multiprocessing not usable outside the context manager
I've optimized my code to use multiple cores using multiprocessing:
import pandas as pd
import requests
from multiprocessing import Process
from multiprocessing import Manager
url1 = "https://api.unverpackt-verband.de/map"
# url2: "https:/... | List of lists after multiprocessing not usable outside the context manager | I've optimized my code to use multiple cores using multiprocessing:
import pandas as pd
import requests
from multiprocessing import Process
from multiprocessing import Manager
url1 = "https://api.unverpackt-verband.de/map"
# url2: "https://api.unverpackt-verband.de/map/info/" + id
url2 = "https://api.unverpackt-verban... | [
"The managed list is no longer valid when the manager closes. You should copy any information from the manager that is needed after close. Managed lists are pretty expensive to access so copying to a regular list after the management is no longer needed is a good idea.\nWhen posting questions on SO, its good to rem... | [
1
] | [] | [] | [
"python",
"python_multiprocessing"
] | stackoverflow_0074510149_python_python_multiprocessing.txt |
Q:
How to get rid of array appending python
Hi have an a vector that looks like:
[array([ -99.21898 , -200.566483, 0.58519 ]), array([-1.00395332e+02, -2.05700867e+02, 6.47600000e-02]), array([-9.99833530e+01, -2.00824783e+02, 6.77800000e-02]), array([ -99.951599, -200.833435, 0.52976 ]), array([-100.375549, ... | How to get rid of array appending python | Hi have an a vector that looks like:
[array([ -99.21898 , -200.566483, 0.58519 ]), array([-1.00395332e+02, -2.05700867e+02, 6.47600000e-02]), array([-9.99833530e+01, -2.00824783e+02, 6.77800000e-02]), array([ -99.951599, -200.833435, 0.52976 ]), array([-100.375549, -205.394653, 0.58454 ]), array([-100.453751... | [
"Looks like you have a length 7 list containing arrays of size 3. You can just pass exactly what you have into np.array() to create a 7x3 array.\n"
] | [
0
] | [] | [] | [
"arrays",
"matrix",
"python",
"row"
] | stackoverflow_0074510324_arrays_matrix_python_row.txt |
Q:
Is this python code iterative or recursive?
I have written the following program in python:
def summ(a,b):
return summation(a,a,a,b)
def summation(v,c,a,b):
if (c == b):
return v
else:
return summation(v+c+1,c+1,a,b)
Research on types of algorithms
I am new to algorithms and programmi... | Is this python code iterative or recursive? | I have written the following program in python:
def summ(a,b):
return summation(a,a,a,b)
def summation(v,c,a,b):
if (c == b):
return v
else:
return summation(v+c+1,c+1,a,b)
Research on types of algorithms
I am new to algorithms and programming in general and I wrote this code thinking it w... | [
"Iterative functions are the functions that execute a set of statements using some loops i.e \"for loop\", \"while loop\".\nRecursive functions are the functions which call's itself repeatedly until base condition become false.\nRecursive functions are the advanced one, and difficult to understand the flow of progr... | [
0
] | [] | [] | [
"algorithm",
"iteration",
"python",
"recursion"
] | stackoverflow_0074510436_algorithm_iteration_python_recursion.txt |
Q:
Override dict square [] operator to perform equality operations
given data and my own DataFrame class which takes the dict as a parameter like this.
frame = {
"a": ["X4E", "T3B", "F8D", "C7X"],
"b": [7.0, 3.5, 8.0, 6.0],
"c": [5, 3, 1, 10],
"d": [False, False, True, False]
}
df = DataFrame(frame)
... | Override dict square [] operator to perform equality operations | given data and my own DataFrame class which takes the dict as a parameter like this.
frame = {
"a": ["X4E", "T3B", "F8D", "C7X"],
"b": [7.0, 3.5, 8.0, 6.0],
"c": [5, 3, 1, 10],
"d": [False, False, True, False]
}
df = DataFrame(frame)
How would one override the __getitem__ method for dicts to allow act... | [
"Not exactly sure if your question is about dictionaries or dataframes... But for dicts I would go about it like this:\nget the value of \"b\" which is a list in your example,\niterate through list and if value + 5 is greater than 10 return true, else return false.\nThis code should work:\nfor x in range(len(frame[... | [
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074510287_pandas_python.txt |
Q:
Remove text lines and strip lines with condition in python
I have a text file in this format:
000000.png 712,143,810,307,0
000001.png 599,156,629,189,3 387,181,423,203,1 676,163,688,193,5
000002.png 657,190,700,223,1
000003.png 614,181,727,284,1
000004.png 280,185,344,215,1 365,184,406,205,1
I want to remove the ... | Remove text lines and strip lines with condition in python | I have a text file in this format:
000000.png 712,143,810,307,0
000001.png 599,156,629,189,3 387,181,423,203,1 676,163,688,193,5
000002.png 657,190,700,223,1
000003.png 614,181,727,284,1
000004.png 280,185,344,215,1 365,184,406,205,1
I want to remove the lines that don't have a [number1,number2,number3,number4,1] or [... | [
"No need for Regex, this might help you:\nwith open(\"data.txt\", \"r\") as input: # Read all data lines.\n data = input.readlines()\nwith open(\"newdata.txt\", \"w\") as output: # Create output file.\n for line in data: # Iterate over data lines.\n line_elements = line.... | [
0
] | [] | [] | [
"file",
"python",
"strip",
"text"
] | stackoverflow_0074510139_file_python_strip_text.txt |
Q:
How to sort an array of array by element closest to 0
I have an array of integer arrays like:
i = [[1,3,8],[1,7,4],[1,9,1],[1,0,3],[1,11,-2]]
And I want a result like:
i = [[1,9,1],[1,11,-2],[1,0,3],[1,7,4],[1,3,8]]
where the "i" array is sorted in a way that i[x][2] is closest to 0.
I tried to change the lambda i... | How to sort an array of array by element closest to 0 | I have an array of integer arrays like:
i = [[1,3,8],[1,7,4],[1,9,1],[1,0,3],[1,11,-2]]
And I want a result like:
i = [[1,9,1],[1,11,-2],[1,0,3],[1,7,4],[1,3,8]]
where the "i" array is sorted in a way that i[x][2] is closest to 0.
I tried to change the lambda in: sorted_i = sorted(i, key=lambda x: x[2]) but with no suc... | [
"What you want is:\nsorted_i = sorted(i, key=lambda x: abs(x[2]))\n\nWhich compares the absolute values (converts negatives to positives).\n",
"You could also do If ... Else in One Line x[2] if x[2] > 0 else -x[2]\narr = [[1, 3, 8], [1, 7, 4], [1, 9, 1], [1, 0, 3], [1, 11, -2]]\nsorted_arr = sorted(arr, key=lambd... | [
3,
0
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0074510559_python_sorting.txt |
Q:
How do I a display a list as a table within an email body string?
I currently have a list derived from a data frame field and want to display that list as a table within a string.
I am stuck on displaying that list as a table within the body string of the email instead of outside.
My ultimate goal is to automatica... | How do I a display a list as a table within an email body string? | I currently have a list derived from a data frame field and want to display that list as a table within a string.
I am stuck on displaying that list as a table within the body string of the email instead of outside.
My ultimate goal is to automatically create table rows from the name list instead of manually creating h... | [
"If you want an HTML table created automatically:\nfrom tabulate import tabulate\n\nnames = ['John Appleseed', 'Amy Adams', 'Robert Feller']\nnames = [[x] for x in names]\n\ntable= tabulate(names,tablefmt='html',headers=[\"Names\"],stralign=(\"left\",))\n\nbody = body + table\n\nIf you want plain text change tablef... | [
0
] | [] | [] | [
"html",
"python"
] | stackoverflow_0074510364_html_python.txt |
Q:
Popen subprocess Named Window
This is the Popen code I'm using to open a subprocess (file subprocessShortLaunch.py) in a separate terminal. I've been looking around and I can't find the answer to two questions:
Is there a way to 'name' the terminal window that opens? The terminal window just says 'terminal'.
Is t... | Popen subprocess Named Window | This is the Popen code I'm using to open a subprocess (file subprocessShortLaunch.py) in a separate terminal. I've been looking around and I can't find the answer to two questions:
Is there a way to 'name' the terminal window that opens? The terminal window just says 'terminal'.
Is there a way to keep the window open ... | [
"name the window\n(1.) You're using gnome-terminal.\nIf you choose xterm instead,\nyou could supply a -title foo argument.\n(2.) X11 applications support X properties,\nmanipulated by utilities like xprop.\nYou can set such properties,\nexternal to gnome-terminal.\nIn the -title section xterm's man page explains th... | [
1
] | [] | [] | [
"popen",
"python"
] | stackoverflow_0074510499_popen_python.txt |
Q:
Matplotlib: 3D surface plot turn off background but keep axes
I want to do a 3D surface plot that shows axes but does not show the faces that are between the axes. What I found is how to turn off axes as well as the faces using ax.set_axis_off(). Is there any chance to turn off only those faces, or to make them tr... | Matplotlib: 3D surface plot turn off background but keep axes | I want to do a 3D surface plot that shows axes but does not show the faces that are between the axes. What I found is how to turn off axes as well as the faces using ax.set_axis_off(). Is there any chance to turn off only those faces, or to make them transparent? (In the first picture you can see the faces if you look ... | [
"You cannot \"turn the panes off\", but you can change their color and thereby make them transparent.\nax.xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n\nComplete code:\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfig = plt.figure()\nax = fig.gca(projection='3d')\na... | [
31,
0
] | [] | [] | [
"matplotlib",
"plot",
"python"
] | stackoverflow_0044001613_matplotlib_plot_python.txt |
Q:
How do i store the value of appended list in a for loop, outside the for loop?
this a tkinter gui to input prices. It will add the prices to the empty list and tell the user the the sum of the list. but now i want to use the data outside of the for loop but whatever version of the list i can think of using it alwa... | How do i store the value of appended list in a for loop, outside the for loop? | this a tkinter gui to input prices. It will add the prices to the empty list and tell the user the the sum of the list. but now i want to use the data outside of the for loop but whatever version of the list i can think of using it always shows up as an empty list.
EXTRAS = []
def add():
for x in range(1):
... | [
"import tkinter as tk\nfrom tkinter import *\n\nwindow = Tk()\n\nwindow.title(\"Test Window\")\nwindow.geometry('300x300')\n\nEXTRAS = []\nEXTRAS_SUM = 0\n\ndef add():\n global EXTRAS_SUM\n EXTRAS.append(float(user_input1g.get())) \n entry_label1g.config(text=str(sum(EXTRAS)))\n user_input1g.delete(0,... | [
1
] | [
" import tkinter as tk\nfrom tkinter import *\n\nwindow = Tk()\n\nwindow.title(\"Test Window\")\nwindow.geometry('300x300')\n\nEXTRAS = []\n\ndef add():\n for x in range(1):\n EXTRAS.append(float(user_input1g.get()))\n entry_label1g.config(text=str(sum(EXTRAS)))\n user_input1g.delete(0, 1... | [
-1,
-1
] | [
"for_loop",
"list",
"python",
"tkinter"
] | stackoverflow_0074506960_for_loop_list_python_tkinter.txt |
Q:
ValueError: Value of 'dimensions_0' is not the name of a column in 'data_frame'. after displaying scatterplot
I'm trying to visualize my data so I tried the following code and I get an error.
dataset = pd.read_csv(r'/Users/Downloads/dataset/datasets/mydatasets/out_4.csv')
df = dataset[["diffTime","diffP","diff... | ValueError: Value of 'dimensions_0' is not the name of a column in 'data_frame'. after displaying scatterplot | I'm trying to visualize my data so I tried the following code and I get an error.
dataset = pd.read_csv(r'/Users/Downloads/dataset/datasets/mydatasets/out_4.csv')
df = dataset[["diffTime","diffP","diffS","diffH","diffE","diffA"]].to_numpy()
out=dataset["labels"]
import plotly.express as px
df = df.reshape(-1... | [
"You need to keep the same column names in your df. When you convert it to numpy, the structure changes.\nOr, after the reshape, change it to pandas and add the columns.\ndf = dataset[[\"diffTime\",\"diffP\",\"diffS\",\"diffH\",\"diffE\",\"diffA\"]]\ndim = df.columns\n\nfig = px.scatter_matrix(\n df,\n dimens... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074019275_python.txt |
Q:
Can't print model summary using PyTorch?
Hello I am building a DQN model for reinforcement learning on cartpole and want to print my model summary like keras model.summary() function
Here is my model class.
class DQN():
''' Deep Q Neural Network class. '''
def __init__(self, state_dim, action_dim, hidden_d... | Can't print model summary using PyTorch? | Hello I am building a DQN model for reinforcement learning on cartpole and want to print my model summary like keras model.summary() function
Here is my model class.
class DQN():
''' Deep Q Neural Network class. '''
def __init__(self, state_dim, action_dim, hidden_dim=64, lr=0.05):
super(DQN, self).... | [
"If you look at the stack trace , you can see it throws this error at the beginning.\n/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py in _forward_unimplemented(self, *input)\n 200 \"\"\"\n--> 201 raise NotImplementedError(f\"Module [{type(self).__name__}] is missing the required \\\"for... | [
0,
0
] | [] | [] | [
"python",
"pytorch"
] | stackoverflow_0074508749_python_pytorch.txt |
Q:
Compute balance column python dataframe with initial static value
i am trying to get a balance column in a python dataframe with an initial static value.
The logic:
start balance = 1000
current balance = previous current balance*(1+df['return'])
My attempt:
df.at[1,'current balance'] = 1000
df['current balance'] =... | Compute balance column python dataframe with initial static value | i am trying to get a balance column in a python dataframe with an initial static value.
The logic:
start balance = 1000
current balance = previous current balance*(1+df['return'])
My attempt:
df.at[1,'current balance'] = 1000
df['current balance'] = df['current balance'].shift(1)*(1+df['return])
I can't get this outpu... | [
"Standard compound return:\ninitial_balance = 1000\ndf['current balance'] = (1 + df['return']).cumprod() * initial_balance\n\n>>> df\n return current balance\n0 0.010 1010.0000\n1 0.030 1040.3000\n2 0.045 1087.1135\n\n",
"I would approach this by getting my df columns ready in lists ... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074510610_python.txt |
Q:
Python - Copy a row from a csv and paste it in another csv
I'd like to understand how to copy a row from a .csv file and paste it in another .csv.
Specifically, I have a large number of .csv files with the same column format. For each of these files, I should search for a string in a column and, if I find it, I ha... | Python - Copy a row from a csv and paste it in another csv | I'd like to understand how to copy a row from a .csv file and paste it in another .csv.
Specifically, I have a large number of .csv files with the same column format. For each of these files, I should search for a string in a column and, if I find it, I have to append the corresponding row in another csv file.
E.g. -->... | [
"Try this:\ndf1 = df1[df1['First Name'] == 'Bob']\ndf2 = df2[df2['First Name'] == 'Bob']\ncombined = pd.concat([df1, df2])\n\nNote - pd.concat can be used on a list of any amount, therefore you can create a function to filter a df and iterate it over all your dfs, adding them to a list and then concatenating it.\n"... | [
0
] | [] | [] | [
"csv",
"pandas",
"python"
] | stackoverflow_0074510743_csv_pandas_python.txt |
Q:
What's the best way to take advantage of parallel processing with dash on windows?
I have a dashboard built on plotly dash. The dashboard updates in real-time and it includes a lot of processing of independent files. For example, there are five different time series in the dashboard and they could feasibly update ... | What's the best way to take advantage of parallel processing with dash on windows? | I have a dashboard built on plotly dash. The dashboard updates in real-time and it includes a lot of processing of independent files. For example, there are five different time series in the dashboard and they could feasibly update separately and in parallel because they are completely independent from one another.
I a... | [
"TLDR; I would recommend using Celery, here is a small example.\nThe tools you have listed are used for slightly different purposes,\n\nWaitress is a WSGI server, i.e. it can be used to serve the Dash application, or more specifically the underlying Flask server\n\nThreading is a library for building threaded progr... | [
1
] | [] | [] | [
"plotly",
"plotly_dash",
"plotly_python",
"python",
"waitress"
] | stackoverflow_0074441478_plotly_plotly_dash_plotly_python_python_waitress.txt |
Q:
Does strict typing increase Python program performance?
Based on questions like this What makes C faster than Python? I've learned that dynamic/static typing isn't the main reason that C is faster than Python. It appears to be largely because python programs are interpreted, and c programs are compiled.
I'm wonder... | Does strict typing increase Python program performance? | Based on questions like this What makes C faster than Python? I've learned that dynamic/static typing isn't the main reason that C is faster than Python. It appears to be largely because python programs are interpreted, and c programs are compiled.
I'm wondering if strict typing would close the gap in performance for i... | [
"With current versions of Python, type annotations are mostly hints for the programmer and possibly some validation tools but are ignored by the compiler and not used at runtime by the byte-code interpreter, which is similar to the behavior of Typescript.\nIt might be possible to change the semantics of Python to t... | [
2
] | [] | [] | [
"c",
"compiler_construction",
"interpreter",
"python"
] | stackoverflow_0074510664_c_compiler_construction_interpreter_python.txt |
Q:
import pandas - ModuleNotFoundError: No module named 'numpy.testing.decorators'
I'm having troubles importing pandas:
import pandas
---
In [7]: import pandas
Traceback (most recent call last):
File "<ipython-input-7-d6ac987968b6>", line 1, in <module>
import pandas
File "//anaconda/lib/python3.6/site- pac... | import pandas - ModuleNotFoundError: No module named 'numpy.testing.decorators' | I'm having troubles importing pandas:
import pandas
---
In [7]: import pandas
Traceback (most recent call last):
File "<ipython-input-7-d6ac987968b6>", line 1, in <module>
import pandas
File "//anaconda/lib/python3.6/site- packages/pandas/__init__.py", line 56, in <module>
import pandas.util.testing
File "//... | [
"Upgrade to pandas 1.0.0 (If you have no other reason not to) via, \npip install -U pandas\n\nSee if it helps. \n",
"pip uninstall numpy\npip install numpy==1.17.0\n\n"
] | [
0,
0
] | [] | [] | [
"anaconda",
"pandas",
"python"
] | stackoverflow_0060071815_anaconda_pandas_python.txt |
Q:
Python/C++ Extension, Undefined symbol error when linking a library
I made a project that has glfw as a library, my directory looks like this:
main_dir
|--include
|--|--glfw_binder.h
|--src
|--|--glfw_binder.cpp
|--lib
|--|--glfw
|--|--|--src
|--|--|--|--libglfw.so
|--|--|--|--libglfw.so.3
|--|--|--|--libglfw.so.3... | Python/C++ Extension, Undefined symbol error when linking a library | I made a project that has glfw as a library, my directory looks like this:
main_dir
|--include
|--|--glfw_binder.h
|--src
|--|--glfw_binder.cpp
|--lib
|--|--glfw
|--|--|--src
|--|--|--|--libglfw.so
|--|--|--|--libglfw.so.3
|--|--|--|--libglfw.so.3.3
|--|--|--|--...
|--|--|--include
|--|--|-- ...
|--main.cpp
|--setup.py... | [
"For anyone facing a similar issue, you need to specify runtime_library_dirs so the setup.py file looks like this:\nfrom setuptools import setup, Extension, find_packages\n\n\nmodule1 = Extension('nerveblox',\n sources = ['main.cpp', 'src/nerveblox_VM.cpp'],\n include_dirs=[\"include\", \"lib/glfw/inclu... | [
0
] | [] | [] | [
"c++",
"cmake",
"python",
"setuptools"
] | stackoverflow_0074487257_c++_cmake_python_setuptools.txt |
Q:
IndentationError: unindent does not match any outer indentation level
When I compile the Python code below, I get
IndentationError: unindent does not match any outer indentation level
import sys
def Factorial(n): # Return factorial
result = 1
for i in range (1,n):
result = result * i
print "... | IndentationError: unindent does not match any outer indentation level | When I compile the Python code below, I get
IndentationError: unindent does not match any outer indentation level
import sys
def Factorial(n): # Return factorial
result = 1
for i in range (1,n):
result = result * i
print "factorial is ",result
return result
Why?
| [
"Other posters are probably correct...there might be spaces mixed in with your tabs. Try doing a search & replace to replace all tabs with a few spaces.\nTry this:\nimport sys\n\ndef Factorial(n): # return factorial\n result = 1\n for i in range (1,n):\n result = result * i\n print \"factorial is \"... | [
840,
328,
151,
49,
28,
19,
18,
11,
11,
11,
10,
9,
7,
7,
5,
5,
5,
5,
2,
2,
2,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"indentation",
"python"
] | stackoverflow_0000492387_indentation_python.txt |
Q:
Unable to get keys from RocksDB given large database size and column families
I want to get all the keys from RocksDB but I get an empty list when I try to create a list of the iterator:
it = db.iterkeys()
it.seek_to_first()
The database contains data, I am sure of that. For the sake of providing minimal viable c... | Unable to get keys from RocksDB given large database size and column families | I want to get all the keys from RocksDB but I get an empty list when I try to create a list of the iterator:
it = db.iterkeys()
it.seek_to_first()
The database contains data, I am sure of that. For the sake of providing minimal viable code, here is the database. My complete code is:
import rocksdb
from pprint import p... | [
"You need to specify which column family you are going to iterating. Say, if you want to read all keys stored with column family 'col9', you can try the following:\ncol9_cf_handle = db.get_column_family(b'col9')\nit = db.iterkeys(col9_cf_handle)\nit.seek_to_first()\n\n\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x",
"rocksdb"
] | stackoverflow_0068885890_python_python_3.x_rocksdb.txt |
Q:
Adding a range as list to a dataframe and calculating a second list with a formulat to this list in a dataframe
I have been struggling with this for some time now and hope someone will take the time to help me so I can learn something.
I have a data frame and I want to add a range list ("num") to the frame, depend... | Adding a range as list to a dataframe and calculating a second list with a formulat to this list in a dataframe | I have been struggling with this for some time now and hope someone will take the time to help me so I can learn something.
I have a data frame and I want to add a range list ("num") to the frame, depending on the int of the column "num".
In the second step, I want to apply a function to the range list here "x" to crea... | [
"df = pd.DataFrame(\n {\"Foo\": [\"ba1\", \"ba2\", \"ba3\"],\n \"Foo2\": [\"ba4\", \"ba5\", \"ba6\"]})\n\ndf['num'] = df.index + 1\ndf['x'] = df['num'].apply(lambda x: list(range(1, x + 1)))\ndf['y'] = df['x'].apply(lambda x: [i + 1 for i in x])\n\ngives\n Foo Foo2 num x y\n0 ba1 ba4 ... | [
2
] | [] | [] | [
"dataframe",
"list",
"pandas",
"python"
] | stackoverflow_0074510676_dataframe_list_pandas_python.txt |
Q:
extract values of specific columns from dataframe to insert to a new dataframe row by row with pandas
i have a dataframe, namely data, with a datetime index and the below columns :
id activity x y z
datetime
1970-01-01 00:42:00.219142823 ... | extract values of specific columns from dataframe to insert to a new dataframe row by row with pandas | i have a dataframe, namely data, with a datetime index and the below columns :
id activity x y z
datetime
1970-01-01 00:42:00.219142823 1623 A -0.152512 -8.585220 -1.219192
1970-01-01 00:42:00.269496827 1623 A 0.999466 -8.1... | [
"If your data frame is called data, then you can use\ndata.iloc[::119, [data.columns.get_loc(col) for col in ['x', 'y', 'z', 'activity']]]\n\n",
"Edit: after understanding that the question is really about getting data every 5 seconds, we can say so more directly:\nwanted = ['x', 'y', 'z', 'activity']\nnewdf = df... | [
0,
0
] | [] | [] | [
"data_preprocessing",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074510602_data_preprocessing_dataframe_pandas_python.txt |
Q:
How can I redirect the user to another template after a search?
I have a search form where the models an user searches are displayed bellow the search form but I want it to be shown in another page.
I tried looking for a way to redirect the user to another url when the search is done and display the filtered data ... | How can I redirect the user to another template after a search? | I have a search form where the models an user searches are displayed bellow the search form but I want it to be shown in another page.
I tried looking for a way to redirect the user to another url when the search is done and display the filtered data there but I wasn't able to do that.
model:
class Product(models.Model... | [
"You can simply make two views one for displaying form and another for displaying queryset, only need to use action attribute correctly so:\n\nNote: Assuming urlpatterns by myself(as you haven't shared), hope you'll understand.\n\nurls.py:\nurlpatterns=[\n path(\"form/\", views.form_display, name=\"form_display\... | [
2
] | [] | [] | [
"django",
"django_forms",
"django_templates",
"django_views",
"python"
] | stackoverflow_0074510248_django_django_forms_django_templates_django_views_python.txt |
Q:
Text-Based RPG Python Bug
i'm new to python and am trying to make a text-based RPG using VScode. I keep running into this bug and i'm not sure what is causing it, please help me :O
Here is the code:
from csv import reader
def import_csv_layout(path):
terrain_map = []
with open(path) as level_map:
... | Text-Based RPG Python Bug | i'm new to python and am trying to make a text-based RPG using VScode. I keep running into this bug and i'm not sure what is causing it, please help me :O
Here is the code:
from csv import reader
def import_csv_layout(path):
terrain_map = []
with open(path) as level_map:
layout = reader(level_map,delim... | [
"Your issue is due to a misunderstanding of variable scope. Specifically, the changes you think you're applying to your global list inspectable_objects inside of the inspect_object function actually do not affect your global list. See this example:\nsome_list = [1, 2, 3]\n\ndef change_the_list():\n some_list = [... | [
0
] | [] | [] | [
"csv",
"python",
"text_based"
] | stackoverflow_0074510765_csv_python_text_based.txt |
Q:
Improve Row Append Performance On Pandas DataFrames
I am running a basic script that loops over a nested dictionary, grabs data from each record, and appends it to a Pandas DataFrame. The data looks something like this:
data = {"SomeCity": {"Date1": {record1, record2, record3, ...}, "Date2": {}, ...}, ...}
In tot... | Improve Row Append Performance On Pandas DataFrames | I am running a basic script that loops over a nested dictionary, grabs data from each record, and appends it to a Pandas DataFrame. The data looks something like this:
data = {"SomeCity": {"Date1": {record1, record2, record3, ...}, "Date2": {}, ...}, ...}
In total it has a few million records. The script itself looks ... | [
"I also used the dataframe's append function inside a loop and I was perplexed how slow it ran.\nA useful example for those who are suffering, based on the correct answer on this page.\nPython version: 3\nPandas version: 0.20.3\n# the dictionary to pass to pandas dataframe\nd = {}\n\n# a counter to use to add entri... | [
75,
11,
7,
6,
5,
1
] | [
"N=100000\n\nt0=time.time()\nd=[]\nfor i in range(N):\n d.append([i, i+1,i+2,i+3,i+0.1,1+0.2])\ntestdf=pd.DataFrame.from_records(d, columns=[\"x1\",\"x2\",\"x3\",\"x4\", \"x5\", \"x6\"])\nprint(time.time()-t0)\n\nt0=time.time()\nd={}\nfor i in range(N):\n d[len(d)+1]={\"x1\":i, \"x2\":i+1, \"x3\":i+2,\"x4\":i... | [
-1
] | [
"numpy",
"pandas",
"python",
"python_2.7"
] | stackoverflow_0027929472_numpy_pandas_python_python_2.7.txt |
Q:
RuntimeError: error checking inheritance of module 'datetime'
I am getting following error when trying to run my python app:
RuntimeError: error checking inheritance of <module 'datetime' from '/usr/local/lib/python3.9/datetime.py'> (type: module)
This is my code:
import datetime
from pydantic.types import Optio... | RuntimeError: error checking inheritance of module 'datetime' | I am getting following error when trying to run my python app:
RuntimeError: error checking inheritance of <module 'datetime' from '/usr/local/lib/python3.9/datetime.py'> (type: module)
This is my code:
import datetime
from pydantic.types import Optional
from sqlmodel import SQLModel, Field
class BlogBase(SQLModel):... | [
"The datetime module supplies classes/objects for manipulating dates. One of them is datetime.datetime. The datetime class also includes other class methods such as utcnow(), which you seem to be using in the example you provided.\nHence, you should instead use, for instance:\nfrom datetime import datetime\n\nnow =... | [
2
] | [] | [] | [
"fastapi",
"python",
"python_datetime"
] | stackoverflow_0074510774_fastapi_python_python_datetime.txt |
Q:
Pythonic way to handle default arguments and argument overwrite with many named parameters?
On classes/methods that work with several properties, what's the best or more pythonic way to work with default parameters (on object instantiation) and overwrite those defaults on calls to that object's methods?
I'd like t... | Pythonic way to handle default arguments and argument overwrite with many named parameters? | On classes/methods that work with several properties, what's the best or more pythonic way to work with default parameters (on object instantiation) and overwrite those defaults on calls to that object's methods?
I'd like to be able to create an object with a set of default parameters (being a large amount of possible ... | [
"One option would be to define a descriptor that would store the default value for a given attribute, and could be used for type validation as well. The descriptor could be used to automatically register parameters that can be set via kwargs.\nHere is an example that I adapted for this class from an existing class... | [
1,
0
] | [] | [] | [
"keyword_argument",
"parameter_passing",
"python"
] | stackoverflow_0074510540_keyword_argument_parameter_passing_python.txt |
Q:
How to see a distribution of outcomes of a while loop?
Imagine you have a while loop that includes a random outcome so that the output of the while loop is different each time. How can you simulate the while loop many times and see the distribution of outcomes?
I know how to run the while loop but I don't know how... | How to see a distribution of outcomes of a while loop? | Imagine you have a while loop that includes a random outcome so that the output of the while loop is different each time. How can you simulate the while loop many times and see the distribution of outcomes?
I know how to run the while loop but I don't know how to simulate the loop multiple times and see the outcome dis... | [
"You can make an empty list of all_rolls = [] and then .append() each now roll to it. This will result in a list of numbers, each number being the result of that roll (so all_rolls[0] would be the first roll).\nThen use matplotlib to make your histogram.\nI would also avoid the while loop since you are just increme... | [
0
] | [] | [] | [
"distribution",
"probability",
"python",
"simulation"
] | stackoverflow_0074510819_distribution_probability_python_simulation.txt |
Q:
Is there a way to remove the primary key from the SQLAlchemy query results?
I am working on a application with FastAPI, Pydantic and SQLAlchemy.
I want to return data matching a Pydantic scheme like
class UserResponseBody(BaseModel):
name: str
age: int
The database model looks like
class User(Base):
... | Is there a way to remove the primary key from the SQLAlchemy query results? | I am working on a application with FastAPI, Pydantic and SQLAlchemy.
I want to return data matching a Pydantic scheme like
class UserResponseBody(BaseModel):
name: str
age: int
The database model looks like
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
... | [
"You already have your response model defined, you just need to tell FastAPI that you want to use it, and that Pydantic should attempt to use .property-notation to resolve values as well:\nclass UserResponseBody(BaseModel):\n name: str\n age: int\n\n class Config:\n orm_mode = True\n\n\n@app.get('/u... | [
3
] | [] | [] | [
"fastapi",
"pydantic",
"python",
"python_3.x",
"sqlalchemy"
] | stackoverflow_0074510401_fastapi_pydantic_python_python_3.x_sqlalchemy.txt |
Q:
How to make warnings expire? Discord.py
I'm trying to setup a warning system for a moderation bot with discord.py. Is there some way I can make it so when I use a !warn [user] [reason] command, it is stored in some type of database, but the warning is removed automatically after 30 days.
Is there also a way to mak... | How to make warnings expire? Discord.py | I'm trying to setup a warning system for a moderation bot with discord.py. Is there some way I can make it so when I use a !warn [user] [reason] command, it is stored in some type of database, but the warning is removed automatically after 30 days.
Is there also a way to make it so each warning has a specific case numb... | [
"You could store all of the warns in a .json file then where there is a list of all the warns with reasons, user ids, time when warn was given and so much more. Then you can just make it so that when the !warn command is called, the bot removes any of the warns that have past 30 days using the date that is stored... | [
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074510880_discord_discord.py_python.txt |
Q:
How to refresh the window to show a new image in pysimlegui
When I click the button to change the image, the window refresh does not work. I don't know how to implement it properly. How can I refresh the api with the button. I'm new to pysimplegui; can somebody point me in the correct direction?
from io import By... | How to refresh the window to show a new image in pysimlegui | When I click the button to change the image, the window refresh does not work. I don't know how to implement it properly. How can I refresh the api with the button. I'm new to pysimplegui; can somebody point me in the correct direction?
from io import BytesIO
import PySimpleGUI as sg
from PIL import Image
import reque... | [
"Method window.refresh() called to update the GUI if you do some changes to element(s) and you want to update it immediately before the script execute next window.read() which also update the GUI.\nIt is necessary to download next picture from website again by your code, window.refresh() won't automatically update ... | [
1
] | [] | [] | [
"api",
"bytesio",
"pysimplegui",
"python",
"python_imaging_library"
] | stackoverflow_0074509894_api_bytesio_pysimplegui_python_python_imaging_library.txt |
Q:
Tkinter radio buttons created in a for loop change to the same value when any one of them is pressed
I'm creating a linear regression tool with a simple UI using Tkinter, and today I've been trying to create a frame in which there will be several things: the 0th column will contain labels with variable names that ... | Tkinter radio buttons created in a for loop change to the same value when any one of them is pressed | I'm creating a linear regression tool with a simple UI using Tkinter, and today I've been trying to create a frame in which there will be several things: the 0th column will contain labels with variable names that I've extracted from an Excel/CSV dataset, and next to every label there will be three radio buttons, each ... | [
"Most of this looks fine. Your crucial mistake is not creating a fitting variable per row. In case of a radio button, use tk.IntVar(). Additionally, to make your code a bit cleaner, I would get rid of either the 'i' or 'j' variable. Your code then becomes:\ndef variablenameframe():\n ...\n for i in range(len(... | [
0
] | [] | [] | [
"python",
"radio_button",
"tkinter"
] | stackoverflow_0074510909_python_radio_button_tkinter.txt |
Q:
Function returning None at the end
This code here:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def evenlis(x, n = 0):
if n == len(x):
return
if x[n] % 2 == 0:
print(x[n], end = " ")
evenlis(x, n + 1)
print(evenlis(arr))
prints all even numbers from the given array, but it also returns Non... | Function returning None at the end | This code here:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def evenlis(x, n = 0):
if n == len(x):
return
if x[n] % 2 == 0:
print(x[n], end = " ")
evenlis(x, n + 1)
print(evenlis(arr))
prints all even numbers from the given array, but it also returns None at the end. How can I fix this?
There ... | [
"You are getting the None portion since your code as it stands is requesting a value to print when your function is called within the print function. Instead of:\nprint(evenlis(arr))\n\nYou could just do the following.\nevenlis(arr)\nprint()\n\nMaking that change provided the following terminal output.\n@Dev:~/Pyt... | [
0
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0074510984_python_recursion.txt |
Q:
Python, speech_recognition tool does not recognize .wav file
I have generated a .wav audio file containing some speech with some other interference speech in the background.
This code worked for me for a test .wav file:
import speech_recognition as sr
r = sr.Recognizer()
with sr.WavFile(wav_path) as ... | Python, speech_recognition tool does not recognize .wav file | I have generated a .wav audio file containing some speech with some other interference speech in the background.
This code worked for me for a test .wav file:
import speech_recognition as sr
r = sr.Recognizer()
with sr.WavFile(wav_path) as source:
audio = r.record(source)
text = r.recognize_g... | [
"From a brief look at the code in the speech_recognition package, it appears that it uses wave from the Python standard library to read WAV files. Python's wave library does not handle floating point WAV files, so you'll have to ensure that you use speech_recognition with files that were saved in an integer format... | [
7,
0,
0
] | [] | [] | [
"google_api",
"python",
"speech_recognition"
] | stackoverflow_0052249985_google_api_python_speech_recognition.txt |
Q:
Program returns a blank page
I wrote a program to be able to register with an accont or login. For some reason, when I run the program I get a blank page with nothing on it. I'm expecting to have a menu page where I can either click on "Login" which will get me to the login page, or "Register" which doesn't do any... | Program returns a blank page | I wrote a program to be able to register with an accont or login. For some reason, when I run the program I get a blank page with nothing on it. I'm expecting to have a menu page where I can either click on "Login" which will get me to the login page, or "Register" which doesn't do anything yet. Here is my full code:
f... | [
"from tkinter import *\n\nroot = Tk()\nroot.geometry('300x200')\n\n\ndef menu():\n def login():\n TitleF1.destroy()\n MenuButton1.destroy()\n MenuButton2.destroy()\n def back():\n loginUsernameL.destroy()\n loginUsernameE.destroy()\n loginPasswordL.des... | [
0
] | [] | [] | [
"frame",
"python",
"tkinter"
] | stackoverflow_0074510688_frame_python_tkinter.txt |
Q:
python pandas search for specific blocks of data inside a dataframe
Hello I want to look for a specific block of data inside a dataframe with python and pandas.
Lets assume I have a dataframe like this:
A B C D E
1 3 5 7 9
5 6 7 8 9
2 4 6 8 8
5 4 3 2 1
and I want to iterate over the dataframe... | python pandas search for specific blocks of data inside a dataframe | Hello I want to look for a specific block of data inside a dataframe with python and pandas.
Lets assume I have a dataframe like this:
A B C D E
1 3 5 7 9
5 6 7 8 9
2 4 6 8 8
5 4 3 2 1
and I want to iterate over the dataframe and look for a specific block of data and return the location of that da... | [
"Assuming this DataFrame and array as input:\ndf = pd.DataFrame({'A': [1, 5, 2, 5], 'B': [3, 6, 4, 4], 'C': [5, 7, 6, 3], 'D': [7, 8, 8, 2], 'E': [9, 9, 8, 1\n\na = np.array([[7, 8, 9], [6, 8, 8]])\n\nYou can use numpy's sliding_window_view:\nfrom numpy.lib.stride_tricks import sliding_window_view as swv\n\nidx, c... | [
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074510887_dataframe_pandas_python.txt |
Q:
How to insert raw array into excell using pandas
I'm trying to insert array data into an excel file, I have already done it but I need a comma for every item of an array.
this is my code
import numpy as np
import pandas as pd
pd_berat_badan_laki_laki = pd.read_excel("Tabel Antropometri Laki-Laki.xlsx", sheet_name... | How to insert raw array into excell using pandas | I'm trying to insert array data into an excel file, I have already done it but I need a comma for every item of an array.
this is my code
import numpy as np
import pandas as pd
pd_berat_badan_laki_laki = pd.read_excel("Tabel Antropometri Laki-Laki.xlsx", sheet_name='Berat badan menurut umur')
pd_panjang_badan_laki_lak... | [
"Can you do string formatting first before assigning the arrays to the dictionaries?\n>>> import numpy as np\n>>> a = np.array([1,2,3])\n>>> a_stringified = ', '.join([str(_) for _ in a])\n>>> a_stringified\n'1, 2, 3'\n\nAnd then assign that instead?\nYour code isn't exactly DRY (it repeats itself a lot), so it'll ... | [
0
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074509945_numpy_pandas_python.txt |
Q:
Any way to transform nested list to dictionary in python?
I have sparsed dataframe that I needed to convert it to list which I already did it. Now I want to transform this list to dictionary, so I can do key-value comparison in my actual use case. To do so, I attempted to convert list to dictionary but I have valu... | Any way to transform nested list to dictionary in python? | I have sparsed dataframe that I needed to convert it to list which I already did it. Now I want to transform this list to dictionary, so I can do key-value comparison in my actual use case. To do so, I attempted to convert list to dictionary but I have value error instead. How can I do this correctly in python? Does an... | [
"The data you have in mydf need cleaning. I'm using ast.literal_eval to try to convert the strings to tuples, and then int() the strings to integers:\n\nfrom ast import literal_eval\n\nout = []\nfor _, row in mydf.iterrows():\n tmp = {}\n for k, v in zip(row.index, row):\n try:\n tmp[k] = li... | [
2,
1
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074510816_dictionary_list_python.txt |
Q:
opencv and mediapipe download error keep happens
i am using mac and i got python 3.9.15 in anaconda. I tried to download cv2 by "pip install opencv-python" but respond was:
ERROR: Ignored the following versions that require a different python version: 1.21.2 Requires-Python >=3.7,<3.11; 1.21.3 Requires-Python >=3.... | opencv and mediapipe download error keep happens | i am using mac and i got python 3.9.15 in anaconda. I tried to download cv2 by "pip install opencv-python" but respond was:
ERROR: Ignored the following versions that require a different python version: 1.21.2 Requires-Python >=3.7,<3.11; 1.21.3 Requires-Python >=3.7,<3.11; 1.21.4 Requires-Python >=3.7,<3.11; 1.21.5 Re... | [
"This is a python version problem that generally occurs on new installations. I def suggest you downgrade your python to 3.8 and try again be sure to comment more problems if they come along!\n"
] | [
0
] | [] | [] | [
"mediapipe",
"numpy",
"opencv",
"pip",
"python"
] | stackoverflow_0074509274_mediapipe_numpy_opencv_pip_python.txt |
Q:
Python script that increases a number by a percent and then with a new number till goal
I found this problem and wanted to try to execute, but got stuck:
Compile a program that allows you to determine how many days will be enough for 200 something if consumed on the first day 5 tons, but every next day 20% more th... | Python script that increases a number by a percent and then with a new number till goal | I found this problem and wanted to try to execute, but got stuck:
Compile a program that allows you to determine how many days will be enough for 200 something if consumed on the first day 5 tons, but every next day 20% more than the previous day.
In Python, using loop operators, lists and
functions.
I tried with the d... | [
"Declaring Needed Variables\nnumberOfDays = 0 \ntotalTons = 200\ndayTonsUsed = 5 \n\nConsuming the tons and modifying the variables\nwhile (totalTons > 0):\n totalTons -= dayTonsUsed\n dayTonsUsed *= 1.2 # Adding extra 20% of consumption for the next day \n numberOfDays += 1 \n\n\nGetting total days\nprint... | [
1,
0,
0,
0
] | [] | [] | [
"function",
"loops",
"operators",
"python",
"python_3.x"
] | stackoverflow_0074510050_function_loops_operators_python_python_3.x.txt |
Q:
Python subprocess run() with multiple arguments on Windows
I've run into a problem trying to start a game with some additional parameters. Normally you enter them in the "target line" on Windows, such as:
"C:\Path\To\game.exe" --arg --arg2 --arg3 abc --arg4 xyz
There are both arguments that are simply the argumen... | Python subprocess run() with multiple arguments on Windows | I've run into a problem trying to start a game with some additional parameters. Normally you enter them in the "target line" on Windows, such as:
"C:\Path\To\game.exe" --arg --arg2 --arg3 abc --arg4 xyz
There are both arguments that are simply the argument like --arg and --arg2, then there are other arguments that req... | [
"The subprocess.run function expects the whole command as list of arguments. So assuming you'd want to execute the command\n$ \"C:\\Path\\To\\game.exe\" --arg --arg2 --arg3 abc --arg4 xyz\n\nyou need to call subprocess.run with the list ['C:\\Path\\To\\game.exe', '--arg', '--arg2', '--arg3', 'abc', '--arg4', 'xyz']... | [
0,
-1
] | [] | [] | [
"arguments",
"python",
"subprocess",
"windows"
] | stackoverflow_0074422502_arguments_python_subprocess_windows.txt |
Q:
Correct way of parsing an ITE (if then else statement) SymPy object from a string
I am trying to parse a SymPy expression object from strings, in particular, those of the type:
e = "ITE(1<2, K, X)"
It al works fine when running the following lines:
from sympy.parsing.sympy_parser import parse_expr
import ... | Correct way of parsing an ITE (if then else statement) SymPy object from a string | I am trying to parse a SymPy expression object from strings, in particular, those of the type:
e = "ITE(1<2, K, X)"
It al works fine when running the following lines:
from sympy.parsing.sympy_parser import parse_expr
import sympy as sp
e = "ITE(1<2, K, X)"
e = parse_expr(e, evaluate=False)
pri... | [
"The ITE class is intended to be for symbolic Booleans and semantically represents the Boolean statement like B if A else C as ITE(A, B, C). In SymPy an ordinary symbol can be considered either a Boolean or as representing a number. If you use the symbol like K + K then it cannot be a Boolean so ITE complains.\nIn ... | [
1
] | [] | [] | [
"python",
"sympy"
] | stackoverflow_0074509469_python_sympy.txt |
Q:
Infinite loop (?) and overlapped drawings in turtle python
I need help with my program, here is the link: https://onlinegdb.com/L0dCYLf6X . I'm trying to make a drawing for every main-key in the nested dictionary. To be precise, main-keys are proteins and I'm trying to draw them with their domains. The problem is ... | Infinite loop (?) and overlapped drawings in turtle python | I need help with my program, here is the link: https://onlinegdb.com/L0dCYLf6X . I'm trying to make a drawing for every main-key in the nested dictionary. To be precise, main-keys are proteins and I'm trying to draw them with their domains. The problem is that all of the drawings are made in one window and are overlapp... | [
"sorry for deleting the comments, I thought this might be an actual answer.\nFirst for the overlapping :\nyou are using in your loop the same values for your x_point_to_start and y_point_to_start.\nWhat does this mean?\nEverytime you draw something you're starting from the same position so things are overlapping. y... | [
0
] | [] | [] | [
"bioinformatics",
"python",
"python_turtle",
"turtle_graphics"
] | stackoverflow_0074510893_bioinformatics_python_python_turtle_turtle_graphics.txt |
Q:
ValueError: too many values to unpack (expected 2) in Django
I am reorganizing one of my projects to be more re-usable and just generally structured better and am now getting the error below whenever I run makemigrations - I've spent half the day trying to figure this out on my own but have run out of Google resul... | ValueError: too many values to unpack (expected 2) in Django | I am reorganizing one of my projects to be more re-usable and just generally structured better and am now getting the error below whenever I run makemigrations - I've spent half the day trying to figure this out on my own but have run out of Google results on searches and am in need of some assistance. What I've done ... | [
"This error would only occur if split() returns more than 2 elements:\napp_label, model_name = model.split(\".\")\nValueError: too many values to unpack (expected 2)\n\nThis means that either app_label or model_name has a dot (.) in it. My money is on the former as model names are automatically generated\n",
"Thi... | [
10,
8,
4,
4,
0
] | [] | [] | [
"django",
"django_models",
"django_views",
"python",
"python_3.x"
] | stackoverflow_0037244808_django_django_models_django_views_python_python_3.x.txt |
Q:
Linear regression for time series
I am pretty new to Machine Learning and have some confusion, so sorry for trivial question.
I have time series data set, very simple with two columns - Date and Price. I'm predicting the price and want to add some features to my model like moving average for last 10 days. If I sp... | Linear regression for time series | I am pretty new to Machine Learning and have some confusion, so sorry for trivial question.
I have time series data set, very simple with two columns - Date and Price. I'm predicting the price and want to add some features to my model like moving average for last 10 days. If I split dataset learn:validation 80:20. For... | [
"interesting question. It seems like you are creating an autoregressive model, i.e. a model that predicts future values based on previous predictions. As such, you are right in concluding that in the validation set you will need to compute the previous ten-day moving average on the prediction. As far as I know, the... | [
0,
0
] | [] | [] | [
"linear_regression",
"machine_learning",
"python",
"scikit_learn"
] | stackoverflow_0074510992_linear_regression_machine_learning_python_scikit_learn.txt |
Q:
Python ValueError("time data %r does not match format %r" % even thought it is the correct format
I'm creating a database with GUI.To collect the date, I wanted to use tkcalendar. Yesterday, It worked perfectly fine but today, I changed some parts of the code without touching this part of the code.
from datetime i... | Python ValueError("time data %r does not match format %r" % even thought it is the correct format | I'm creating a database with GUI.To collect the date, I wanted to use tkcalendar. Yesterday, It worked perfectly fine but today, I changed some parts of the code without touching this part of the code.
from datetime import datetime
from tkinter import *
from tkinter import messagebox
from tkcalendar import DateEntry
r... | [
"Sorry, this should be a comment, but I cannot comment yet. This worked on my end: datetime.datetime.strptime('11/21/22', '%m/%d/%y'). Given your date example.\n"
] | [
1
] | [] | [] | [
"datetime",
"python",
"tkcalendar",
"tkinter",
"valueerror"
] | stackoverflow_0074511230_datetime_python_tkcalendar_tkinter_valueerror.txt |
Q:
Trying to dockerize Django app receive error "ERROR [3/6] RUN apk update"
I'm completely new to Dockers, I'm trying to dockerize a Django application using:
FROM python:3.10.4-alpine3.15
ENV PYTHONUNBUFFERED=1
WORKDIR /app
RUN apk update \
&& apk add --no-cache gcc musl-dev postgresql-dev python3-dev libff... | Trying to dockerize Django app receive error "ERROR [3/6] RUN apk update" | I'm completely new to Dockers, I'm trying to dockerize a Django application using:
FROM python:3.10.4-alpine3.15
ENV PYTHONUNBUFFERED=1
WORKDIR /app
RUN apk update \
&& apk add --no-cache gcc musl-dev postgresql-dev python3-dev libffi-dev \
&& pip install --upgrade pip
COPY ./requirements.txt ./
RUN pip i... | [
"Well, it obvious is failing at your bash commands.\nBe careful with indentation, it is very important in bash commands.\nRUN apk update \\\n && apk add --no-cache gcc musl-dev postgresql-dev python3-dev libffi-dev \\\n && pip install --upgrade pip\n\nIf not that, than one of your libs.\n"
] | [
-1
] | [] | [] | [
"docker",
"postgresql",
"python"
] | stackoverflow_0074511337_docker_postgresql_python.txt |
Q:
Python detect direct method call
I have following code:
a = A()
a.foo(123)
A.foo(a, 123)
How can I detect which line caused foo() execution: 2 or 3? Thank you for your answers.
A:
Preface: There are very few use cases where the difference between these is actually important. Having different behavior based on ... | Python detect direct method call | I have following code:
a = A()
a.foo(123)
A.foo(a, 123)
How can I detect which line caused foo() execution: 2 or 3? Thank you for your answers.
| [
"Preface: There are very few use cases where the difference between these is actually important. Having different behavior based on whether a method is called directly on an instance or by explicitly passing the instance to the method accessed through the class would likely violate the Principle of least astonishm... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074504136_python.txt |
Q:
Why do I need to input 'q' more than once to quit the while loop?
I am making a text-based menu and wanted to have the program end when the letter 'q' is inputted however I need to do it more than once (2 or 3, I am not sure why it can be either) yet my while loop will stop if the input is 'q'.
Here is the functio... | Why do I need to input 'q' more than once to quit the while loop? | I am making a text-based menu and wanted to have the program end when the letter 'q' is inputted however I need to do it more than once (2 or 3, I am not sure why it can be either) yet my while loop will stop if the input is 'q'.
Here is the function:
userInput = input("Enter a letter to choose an option: \n e - \n... | [
"userInput = \"\"\nwhile userInput != 'q':\n userInput = input(\"Enter a letter to choose an option: \\n e - \\n r - \\n p - \\n h - \\n m - \\n s - \\n q - \\n\")\n if userInput == 'e':\n print(\"e has been pressed\")\n elif userInput == 'r':\n print(\"r has been pressed\")\n elif userInp... | [
0
] | [] | [] | [
"menu",
"python",
"user_input"
] | stackoverflow_0074511254_menu_python_user_input.txt |
Q:
Adding Rols using Select Menu
I make a multitool bot for discord, this is a module of the the code and the library installed are discord, discord.ui, traceback, random, discordutils, asyncio
I have this code, whrite and adapted using a YouTube video:
@client.command()
class select(discord.ui.Select):
... | Adding Rols using Select Menu | I make a multitool bot for discord, this is a module of the the code and the library installed are discord, discord.ui, traceback, random, discordutils, asyncio
I have this code, whrite and adapted using a YouTube video:
@client.command()
class select(discord.ui.Select):
def __init__(self):
... | [
"You put @client.command() above a Select menu. A Select menu can't be a command...\n @client.command()\n class select(discord.ui.Select):\n\nWhat would that even do?\nCreate a command, create a Select menu, and send the Select menu in the command. You seem to already be doing all of that, though, so just rem... | [
0
] | [] | [] | [
"discord",
"discord.py",
"drop_down_menu",
"python"
] | stackoverflow_0074511273_discord_discord.py_drop_down_menu_python.txt |
Q:
Find index within full array of the argmax of an array subset
Goal: to find the index of the highest value in 1d array from index 25 to [-1]
The way I do it is wrong, I get the index of the highest value of the slice.
If there is no other way than slicing it, how do I then get the correct index of the original arr... | Find index within full array of the argmax of an array subset | Goal: to find the index of the highest value in 1d array from index 25 to [-1]
The way I do it is wrong, I get the index of the highest value of the slice.
If there is no other way than slicing it, how do I then get the correct index of the original array?
| [
"If you know you're indexing the array from index 25 on, you could add 25 to the result:\nargmax = close[25:].argmax() + 25\n\nBut if you're using an arbitrary slice of your array, another way to do this would be to create a similar array of indices, then slice that the same way:\nindices = np.arange(len(close))\n#... | [
1
] | [] | [] | [
"numpy",
"numpy_ndarray",
"python"
] | stackoverflow_0074511378_numpy_numpy_ndarray_python.txt |
Q:
Exporting values & keys from dictionary in specified way
New to Python and hitting a wall with this problem.
Scenario: I have a list with multiple unknown integers. I need to take these, sort them and extract the most frequent occurences. If there are more than one instance of an item, then the higher value should... | Exporting values & keys from dictionary in specified way | New to Python and hitting a wall with this problem.
Scenario: I have a list with multiple unknown integers. I need to take these, sort them and extract the most frequent occurences. If there are more than one instance of an item, then the higher value should be chosen first.
So far, I have made a dictionary to deal wit... | [
"from collections import Counter\nfrom itertools import groupby\n\nrequests = [2,3,6,5,2,7,2,3,6,5,2,7,11,2,77]\n\nc = Counter(requests)\n\nfreq = list()\nfor i,g in groupby(c.items(), key=lambda t:t[1]):\n freq.extend(sorted([j for j,k in g],reverse=True))\nprint(freq)\n\nTry to use built-ins as they are really... | [
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074511267_dictionary_list_python.txt |
Q:
How can I generate a variable conditioning on different columns?
My dataset:
country_d
regime_d
country_o
regime_o
year
col_dep_ever
col_dep_end_year
Afghanistan
0.0
United Kingdom
1.0
1948
1.0
1919.0
Afghanistan
0.0
United Kingdom
1.0
1949
1.0
1919.0
Afghanistan
0.0
United Kingdom
1.0
1950
1.0
1919.0
India
0... | How can I generate a variable conditioning on different columns? | My dataset:
country_d
regime_d
country_o
regime_o
year
col_dep_ever
col_dep_end_year
Afghanistan
0.0
United Kingdom
1.0
1948
1.0
1919.0
Afghanistan
0.0
United Kingdom
1.0
1949
1.0
1919.0
Afghanistan
0.0
United Kingdom
1.0
1950
1.0
1919.0
India
0.0
United Kingdom
1.0
1948
1.0
1920.0
India
0.0
United King... | [
"I will give an answer to 1 row, you can generalise it with a loop.\nAlso based on the 0 lines of code you provided us I had to make some assumption. but this should resolve your issue\n## I have no idea why it is not just a boolean but ok\nmy_binary_data = 1 if col_dep_ever == '1.0' and regime_o=! regime_d else 0\... | [
0
] | [] | [] | [
"conditional_statements",
"python"
] | stackoverflow_0074511220_conditional_statements_python.txt |
Q:
How to assert a condition pass or fail in pytest for web UI testing
def test_review():
review_score = driver.find_element(By.ID, "acrCustomerReviewText")
assert "review_score" >= "4"
price = driver.find_element(By.ID, "corePriceDisplay_desktop_feature_div")
assert "price" <= "4000"
I want to review the rating if ... | How to assert a condition pass or fail in pytest for web UI testing | def test_review():
review_score = driver.find_element(By.ID, "acrCustomerReviewText")
assert "review_score" >= "4"
price = driver.find_element(By.ID, "corePriceDisplay_desktop_feature_div")
assert "price" <= "4000"
I want to review the rating if it's less than 4 fail the test otherwise pass it
The second one is simil... | [
"The following creates a fake html that fits your requirement and then uses two separate test with pytest.\nNote that fixture_get_driver is called automatically by the test and serves to provide a global webdriver object. setup_module() is also automatically called by pytest.\nAnother valid, and arguably better app... | [
0
] | [] | [] | [
"pytest",
"python",
"selenium"
] | stackoverflow_0074503559_pytest_python_selenium.txt |
Q:
what should I do if after turning on the bot after 4 minutes, the buttons stop working?
I'm making a discord bot on python using discordpy. Here are the imports:
import discord
from random import randint
import json
from discord.ext import commands
from discord.User interface import button, view
Here is an example... | what should I do if after turning on the bot after 4 minutes, the buttons stop working? | I'm making a discord bot on python using discordpy. Here are the imports:
import discord
from random import randint
import json
from discord.ext import commands
from discord.User interface import button, view
Here is an example of a button:
class ButtonSandStone8(Button):
def __init__(self,label):
super()._... | [
"The default value for the timeout kwarg to View is 180, meaning the view times out after 180 seconds. If you want a different timeout, pass a value for it. A value of None means it doesn't time out.\nView(timeout=None)\n\nDocs: https://discordpy.readthedocs.io/en/stable/interactions/api.html?highlight=view#discord... | [
0
] | [] | [] | [
"bots",
"discord.py",
"python"
] | stackoverflow_0074510696_bots_discord.py_python.txt |
Q:
Drawing a percentage bar chart in python
I am looking present the information about the proportion of students getting different grades, and I am trying to avoid using a pie chart. Instead, the following style seemed appealing to me:
Is there any way to achieve something like this visualisation in matplotlib or a... | Drawing a percentage bar chart in python | I am looking present the information about the proportion of students getting different grades, and I am trying to avoid using a pie chart. Instead, the following style seemed appealing to me:
Is there any way to achieve something like this visualisation in matplotlib or adjacent libraries? I know I can use barh() for... | [
"You can use pandas.DataFrame.plot.barh to make a horizontal single stacked bar. For the example, I used one of the datasets similar to yours that I found in the Office of National Statistics to show you the general logic.\nTry this:\nimport pandas as pd\nimport requests\n\nurl= \"https://www.ons.gov.uk/file?uri=/p... | [
2
] | [] | [] | [
"bar_chart",
"matplotlib",
"python",
"visualization"
] | stackoverflow_0074509757_bar_chart_matplotlib_python_visualization.txt |
Q:
How to make tkinter menu label run only the function attached to it?
I am new to python and learning to make some basic tkinter apps in windows.
I have defined a menubar and add one menu to it. Then added multiple labels to this menu, but when I click any button in the menu, all the commands are ran, I am wonderin... | How to make tkinter menu label run only the function attached to it? | I am new to python and learning to make some basic tkinter apps in windows.
I have defined a menubar and add one menu to it. Then added multiple labels to this menu, but when I click any button in the menu, all the commands are ran, I am wondering how to run only the clicked menu?
MWE
(Problem: whichever menu I click, ... | [
"The problem lies in your lambda functions, I think you are not able to understand the difference between func and func().\nabcd basically represents a function which can be called.\nabcd() is actually calling that abcd function.\nlambda behaves like abcd, so do not need to do abcd: abcd().\nHere is the corrected p... | [
2,
1,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074509778_python_tkinter.txt |
Q:
How do you send more than one embed per Interaction in Discord.py?
I want to make a Discord interaction that sends a picture for as often as you say in 'howmany', but with my current code it send 1 embed with a picture and the rest without one. How to fix this?
@tree.command(name='embed', description='embed')
asyn... | How do you send more than one embed per Interaction in Discord.py? | I want to make a Discord interaction that sends a picture for as often as you say in 'howmany', but with my current code it send 1 embed with a picture and the rest without one. How to fix this?
@tree.command(name='embed', description='embed')
async def embed(interaction: discord.Interaction, seeable: bool, howmany: ty... | [
"Have a close look at the docs for send_message: https://discordpy.readthedocs.io/en/stable/interactions/api.html?highlight=send_message#discord.InteractionResponse.send_message\n\nParameters:\n\nembeds (List[Embed]) β A list of embeds to send with the content. Maximum of 10. This cannot be mixed with the embed par... | [
1,
0
] | [] | [] | [
"discord",
"discord.py",
"discord_interactions",
"embed",
"python"
] | stackoverflow_0074505236_discord_discord.py_discord_interactions_embed_python.txt |
Q:
Start a bash session from python
I want to drop into a shell for a ctf competition I am working on. I am not allowed to use pwntools for this. I want to achieve something like following from python:
import os
os.system("/bin/bash &")
print("hello world") # assume I am writing to a file
os.system("f... | Start a bash session from python | I want to drop into a shell for a ctf competition I am working on. I am not allowed to use pwntools for this. I want to achieve something like following from python:
import os
os.system("/bin/bash &")
print("hello world") # assume I am writing to a file
os.system("fg") # does not wo... | [
"You want to use the subprocess module instead. fg is a shell built-in command that only works with job control in the shell itself.\nimport subprocess\n\n\np = subprocess.Popen([\"bash\"])\nprint('hello world')\np.wait()\n\n"
] | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074511509_python_python_3.x.txt |
Q:
does python have an equivalent to javascript's every and some method?
I was trying to search the docs for a method similar but I was only able to find pythons all() and any(). But that's not the same because it just checks if the val is truthy instead of creating your own condition like in js' every and some metho... | does python have an equivalent to javascript's every and some method? | I was trying to search the docs for a method similar but I was only able to find pythons all() and any(). But that's not the same because it just checks if the val is truthy instead of creating your own condition like in js' every and some method.
i.e
// return true if all vals are greater than 1
const arr1 = [2, 3, 6,... | [
"Just combine it with a mapping construct, in this case, you would typically use a generator expression:\narr1 = [2, 3, 6, 10, 4, 23]\nprint(all(val > 1 for val in arr1))\n\narr2 = [2, 3, 6, 10, 4, 23]\nprint(any(val > 20 for val in arr2))\n\nGenerator comprehensions are like list comprehensions, except they create... | [
3,
1
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0074511561_javascript_python.txt |
Q:
How to pass a variable to class based views (ListView)
My Views.py code
class ListaFuncionariosView(ListView):
model = Funcionarios
template_name = '../templates/funcionarios/lista_funcionarios.html'
paginate_by = 10
ordering = ['FuncionarioCartao']
queryset = Funcionarios.objects.filter(Empres... | How to pass a variable to class based views (ListView) | My Views.py code
class ListaFuncionariosView(ListView):
model = Funcionarios
template_name = '../templates/funcionarios/lista_funcionarios.html'
paginate_by = 10
ordering = ['FuncionarioCartao']
queryset = Funcionarios.objects.filter(EmpresaCodigo=1)
funcionarios_number = Funcionarios.objects.ag... | [
"By aggregating at the class-level, the query will run when you start the server, and the count will thus always remain that exact number.\nYou can define this in a function:\nclass ListaFuncionariosView(ListView):\n model = Funcionarios\n template_name = '../templates/funcionarios/lista_funcionarios.html'\n ... | [
2
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0074511497_django_django_views_python.txt |
Q:
I am working on 'https://berkeleyai.github.io/cs188-website/project3.html' reinforcement learning in Pacman project
In this project we are asked to will implement value iteration and Q-learning, and test our agents first on Gridworld (from class), then apply them to a simulated robot controller (Crawler) and Pacma... | I am working on 'https://berkeleyai.github.io/cs188-website/project3.html' reinforcement learning in Pacman project | In this project we are asked to will implement value iteration and Q-learning, and test our agents first on Gridworld (from class), then apply them to a simulated robot controller (Crawler) and Pacman. The instructions are to download a zip folder and edit the valueIterationAgents.py and qlearningAgents.py which I have... | [
"I fixed it by moving my file from downloads to desktop\n"
] | [
0
] | [] | [] | [
"artificial_intelligence",
"bash",
"python",
"q_learning",
"reinforcement_learning"
] | stackoverflow_0074510399_artificial_intelligence_bash_python_q_learning_reinforcement_learning.txt |
Q:
Python count occurence of a string without overlapping from a string
I was trying to find the occurrence of every 2 consecutive characters from a string.
The result will be in a dictionary as key = 2 characters and value = number of occurrence.
I tried the following :
seq = "AXXTAGXXXTA"
d = {seq[i:i+2]:seq.coun... | Python count occurence of a string without overlapping from a string | I was trying to find the occurrence of every 2 consecutive characters from a string.
The result will be in a dictionary as key = 2 characters and value = number of occurrence.
I tried the following :
seq = "AXXTAGXXXTA"
d = {seq[i:i+2]:seq.count(seq[i:i+2]) for i in range(0, len(seq)-1)}
The problem is that the resu... | [
"You can use collections.Counter.\nfrom collections import Counter\n\nseq = \"AXXTAGXXXTA\"\n\nCounter((seq[i:i+2] for i in range(len(seq)-1)))\n\nOutput:\nCounter({'AX': 1, 'XX': 3, 'XT': 2, 'TA': 2, 'AG': 1, 'GX': 1})\n\nOr without additional libraries. You can use dict.setdefault.\nseq = \"AXXTAGXXXTA\"\n\nd = {... | [
4
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074511630_dictionary_python.txt |
Q:
Why can't I call the PyUSB function dev.read() repeatedly without getting a timeout error?
I have a USB connection between a Macbook Air and a microcontroller sensor that streams hex data continuously. I'm trying to use PyUSB in Python to acquire the data. I used PyUSB to connect to microcontroller like so:
impor... | Why can't I call the PyUSB function dev.read() repeatedly without getting a timeout error? | I have a USB connection between a Macbook Air and a microcontroller sensor that streams hex data continuously. I'm trying to use PyUSB in Python to acquire the data. I used PyUSB to connect to microcontroller like so:
import usb
dev = usb.core.find(idVendor=0xXXXX, idProduct=0xXXXX)
dev.set_configuration()
cfg = dev.... | [
"What is the length of the response you get back? The way you are structuring dev.read you are telling PyUSB that the response should be 100 bytes long and if you don't get 100 bytes in 100 ms, throw a timeout exception. If your device responds with a smaller message, you will get an error after 100ms is reached, e... | [
2,
0,
0,
0,
0
] | [] | [] | [
"python",
"pyusb",
"serial_port",
"usb"
] | stackoverflow_0026526217_python_pyusb_serial_port_usb.txt |
Q:
How to read and modify csv files in function in loop and save as separated DataFrame in Python Pandas?
I try to create function in Python Pandas where:
I read 5 csv
make some aggregations on each readed csv (just to make it easier, we can delete one column)
save each modified csv as DataFrames
Currently I have s... | How to read and modify csv files in function in loop and save as separated DataFrame in Python Pandas? | I try to create function in Python Pandas where:
I read 5 csv
make some aggregations on each readed csv (just to make it easier, we can delete one column)
save each modified csv as DataFrames
Currently I have something like below, nevertheless it return only one DataFrame as output not 5, how can I change below code ... | [
"You can create an empty dictionnary and feed it gradually with the five processed dataframes.\nTry this:\ndef xx():\n dico_dfs={}\n\n for el in [file for file in os.listdir(\"mypath\") if file.endswith(\".csv\")]:\n #1. read 5 csv \n df = pd.read_csv(f\"path/{el}\")\n\n #2. making aggreg... | [
0
] | [] | [] | [
"dataframe",
"for_loop",
"loops",
"pandas",
"python"
] | stackoverflow_0074511651_dataframe_for_loop_loops_pandas_python.txt |
Q:
No sending duplicates
I'm trying to make my first bot on telegram. His task is simple: it scrapes from ebay the last items posted and sends me an update on telegram.
I thought to use a telegram job to do that:
context.job_queue.run_repeating(items_call, context=chat_id, name=str(chat_id), interval=6)
where items_... | No sending duplicates | I'm trying to make my first bot on telegram. His task is simple: it scrapes from ebay the last items posted and sends me an update on telegram.
I thought to use a telegram job to do that:
context.job_queue.run_repeating(items_call, context=chat_id, name=str(chat_id), interval=6)
where items_call is the function that c... | [
"Here you want a set.\nAt some point in your code, you want to declare the set:\nsent_jobs = set()\n\nThen, in your items call function, you'll want to use the set:\ndef items_call:\n # ... Code you already had here\n for its in items:\n if its in sent_jobs: # Check if the item has been sent before\n... | [
0
] | [] | [] | [
"python",
"python_telegram_bot",
"telegram"
] | stackoverflow_0074511649_python_python_telegram_bot_telegram.txt |
Q:
How to bypass Cloudflare hcaptcha by sloving it manually while using Selenium
I wanted to build a semi-automatic solution for scraping a website protected by Cloudflare's hcaptcha. I thought that I could solve captcha manually whenever it appears and then let my scraper scrape the website for some time until anoth... | How to bypass Cloudflare hcaptcha by sloving it manually while using Selenium | I wanted to build a semi-automatic solution for scraping a website protected by Cloudflare's hcaptcha. I thought that I could solve captcha manually whenever it appears and then let my scraper scrape the website for some time until another captcha must be solved.
To try out my solution I open the url with Selenium whil... | [
"Without the site url it is impossible to tell exactly what is happening, although from previous experience I believe, the Hcaptcha prompt is probably appearing as a result of the site protection and may not be on the site itself.\nIf its appearing as a result of the site protection then start you browser using yo... | [
0
] | [] | [] | [
"cloudflare",
"hcaptcha",
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074332477_cloudflare_hcaptcha_python_selenium_web_scraping.txt |
Q:
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES) when connecting to MySQL through Python
I have been trying to connect to a MySQL server through Python, using:
try:
with connect(
host = "localhost",
user = "root",
password = "<password>",
) as conn... | ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES) when connecting to MySQL through Python | I have been trying to connect to a MySQL server through Python, using:
try:
with connect(
host = "localhost",
user = "root",
password = "<password>",
) as connection:
print(connection)
except Error as E:
print(E)
It then throws the error:
1045 (28000): Access denied for user... | [
"Thanks to BerndBuffen for linking the docs which helped me figure out the issue I'm experiencing (and everyone else who tried to help).\nI realised that my issue is the port default is 3306 and when configuring 3306 was in use, so I changed it to 3307. When I was trying to connect it was attempting to use the wron... | [
0
] | [] | [] | [
"database",
"mysql",
"python",
"sql"
] | stackoverflow_0074511290_database_mysql_python_sql.txt |
Q:
Python insert tuple into mysql table
I'm trying to insert this tuple into a mysql table.
extract of the tuple:
('2022-06-29 04:50:00', 'var1', 'var2', 'value'), ('2022-06-29 10:58:00', 'var1', 'var2', 'value'), ('2022-06-29 10:59:00', 'var1', 'var2', 'value'), ('2022-06-29 11:01:00', 'var1', 'var2', 'value'),...
... | Python insert tuple into mysql table | I'm trying to insert this tuple into a mysql table.
extract of the tuple:
('2022-06-29 04:50:00', 'var1', 'var2', 'value'), ('2022-06-29 10:58:00', 'var1', 'var2', 'value'), ('2022-06-29 10:59:00', 'var1', 'var2', 'value'), ('2022-06-29 11:01:00', 'var1', 'var2', 'value'),...
This is my code:
import MySQLdb
... | [
"You forget some \" here:\ninto \" and here \"(collection_date so you have into \" + table + \"(collection_date and not into your_table_name(collection_date\nAnd at the end, the format doesn't work, you should concatenate your join\nI let you check\ntuples = ('2022-06-29 04:50:00', 'var1', 'var2', 'value'), ('2022... | [
-1
] | [] | [] | [
"mysql",
"python",
"tuples"
] | stackoverflow_0074511670_mysql_python_tuples.txt |
Q:
Python binance api rsi calculation with last 15 value is wrong
I want to use 15 minutes data to calculate my own RSI strategy. I am using binance API with python. So I need the last 15 closes data of BTCUSDT. I am getting it like this.
start = str(dt.datetime.now(dt.timezone.utc) - dt.timedelta(minutes=15*15))
end... | Python binance api rsi calculation with last 15 value is wrong | I want to use 15 minutes data to calculate my own RSI strategy. I am using binance API with python. So I need the last 15 closes data of BTCUSDT. I am getting it like this.
start = str(dt.datetime.now(dt.timezone.utc) - dt.timedelta(minutes=15*15))
end = str(dt.datetime.now())
trades = client.get_historical_klines(sym... | [
"As Binance is integrated with Trading View, the rsi should be calculated using an exponential moving average (EMA), whereas talib is using the SMMA (smoothed moving average).\nNote that you will probably find less discrepancies if you use a larger sample (assumption made that the first bar is 0 gain and 0 loss wil... | [
0
] | [] | [] | [
"binance",
"binance_api_client",
"python"
] | stackoverflow_0074340073_binance_binance_api_client_python.txt |
Q:
Is there a way to make asking multiple if statements more succinct?
I wanted to make a pretty simple program where it picks from a random list (I decided to use fruits) without showing the user, and gives hints about what fruit is picked like what color the fruit is, until the user provides the correct answer, I t... | Is there a way to make asking multiple if statements more succinct? | I wanted to make a pretty simple program where it picks from a random list (I decided to use fruits) without showing the user, and gives hints about what fruit is picked like what color the fruit is, until the user provides the correct answer, I tried to wright it in a way that asks 'if the correct answer is a yellow f... | [
"Group them by color with a dictionary:\nfruits = {\n 'cherry': 'red',\n 'apple': 'red',\n 'banana': 'yellow',\n ...\n}\n\ncolor = fruits.get(correct, 'Invalid')\n\n# or\n\ntry:\n color = fruits[correct]\nexcept KeyError:\n print(\"Invalid\")\n raise\n\n"
] | [
1
] | [] | [] | [
"if_statement",
"list",
"python",
"python_3.10"
] | stackoverflow_0074511771_if_statement_list_python_python_3.10.txt |
Q:
Installing LXML, facing a "legacy-install-failure" error
Trying to install lxml on Python 311. Faced with this error.
PS C:\Users\chharlie\Desktop\code> pip install lxml
Collecting lxml
Using cached lxml-4.9.1.tar.gz (3.4 MB)
Preparing metadata (setup.py) ... done
Building wheels for collected packages: lxml
... | Installing LXML, facing a "legacy-install-failure" error | Trying to install lxml on Python 311. Faced with this error.
PS C:\Users\chharlie\Desktop\code> pip install lxml
Collecting lxml
Using cached lxml-4.9.1.tar.gz (3.4 MB)
Preparing metadata (setup.py) ... done
Building wheels for collected packages: lxml
Building wheel for lxml (setup.py) ... error
error: subproc... | [
"So... we will be walking down this road you and I for the foreseeable future. I am only slightly ahead of you in your OP...\nlibxml2 and libxslt are not installed (or some error message to this effect)\nlxml requires these libraries to be installed and, no, you cannot intall them in python. They have to be compi... | [
1,
1,
1,
1,
1
] | [] | [] | [
"lxml",
"pandas_datareader",
"python",
"python_wheel",
"yfinance"
] | stackoverflow_0074332756_lxml_pandas_datareader_python_python_wheel_yfinance.txt |
Q:
How to open python file in default editor from Python script
When I try on Windows
webbrowser.open(fname) or os.startfile(fname) or os.system ('cmd /c "start %s"' % fname)
my python script is getting executed.
How to open it for edit in default editor (like SQL script)
Edit:
import ctypes
shell32 = ctypes.windll.... | How to open python file in default editor from Python script | When I try on Windows
webbrowser.open(fname) or os.startfile(fname) or os.system ('cmd /c "start %s"' % fname)
my python script is getting executed.
How to open it for edit in default editor (like SQL script)
Edit:
import ctypes
shell32 = ctypes.windll.shell32
fname = r'C:\Scripts\delete_records.py'
shell32.ShellExec... | [
"\"\"\"\nOpen the current file in the default editor\n\"\"\"\n\nimport os\nimport subprocess\n\nDEFAULT_EDITOR = '/usr/bin/vi' # backup, if not defined in environment vars\n\npath = os.path.abspath(os.path.expanduser(__file__))\neditor = os.environ.get('EDITOR', DEFAULT_EDITOR)\nsubprocess.call([editor, path])\n\n"... | [
2,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0029086063_python.txt |
Q:
How to insert new string to DB by button Django
How to insert new string to DB by button Django and get id new record
<a href="{% url "main:create_bd_line" %}"><button type="button" class="btn btn-secondary">ΠΠ°ΡΠ°ΡΡ</button></a>
def create_bd_line(request):
user_group = request.user.groups.values_list()
un... | How to insert new string to DB by button Django | How to insert new string to DB by button Django and get id new record
<a href="{% url "main:create_bd_line" %}"><button type="button" class="btn btn-secondary">ΠΠ°ΡΠ°ΡΡ</button></a>
def create_bd_line(request):
user_group = request.user.groups.values_list()
university = user_group[0][1]
num = Answers.object... | [
"I do this and its work\nnum = Answers.objects.all().count() # number of strings in table \nnew_user_answer = num + 1\n new_line = Answers(id=new_user_answer)\n new_line.save()\n\n"
] | [
-1
] | [] | [] | [
"django",
"postgresql",
"python"
] | stackoverflow_0074511463_django_postgresql_python.txt |
Q:
Setting a conditional for a random item selected from a list in Python
I'm working on a text-based Choose Your Own Adventure game in Python for an online class. The game has a list of random "villains" that you may encounter. The original project just has you going to the cave and finding a magical sword that you ... | Setting a conditional for a random item selected from a list in Python | I'm working on a text-based Choose Your Own Adventure game in Python for an online class. The game has a list of random "villains" that you may encounter. The original project just has you going to the cave and finding a magical sword that you use to fight the villain. I wanted to set it so that the "weapon" would chan... | [
"The core of the problem is that if you write:\nif {creature} == \"wicked fairy\" or \"gorgon\" or \"troll\" or \"dragon\":\n\nyou have created a logical or of four items with only the first one being an actual comparison.\nAs a non-empty string evaluates in Python to True the 'condition' will always return True on... | [
1,
0
] | [] | [] | [
"python",
"random"
] | stackoverflow_0074511656_python_random.txt |
Q:
how can I print both positive and negative indexes together with its corresponding element?
In the following code I want to print in the way mentioned in the question what am I getting is this:
https://prnt.sc/oEjjTyr_dtdu
Tried this hoping they would come together with their corresponding element on the same line... | how can I print both positive and negative indexes together with its corresponding element? | In the following code I want to print in the way mentioned in the question what am I getting is this:
https://prnt.sc/oEjjTyr_dtdu
Tried this hoping they would come together with their corresponding element on the same line with like this
(index) (element)
-1 2 3
-2 1 2
-3 0 1
can you show me ... | [
"t=[]\nn=int(input(\"enter how many elements: \"))\nfor i in range(0,n):\n a=int(input(\"enter element: \"))\n t.append(a)\nfor num in t[::-1]: # Here t is a list, you can use tuple in the likewise manner. \n print(t.index(num)-len(t),t.index(num),num)\n\nResult:\nenter how many elements:3\nenter element:1\n... | [
0,
0,
0
] | [] | [] | [
"list",
"python",
"stdtuple",
"tuples"
] | stackoverflow_0074507490_list_python_stdtuple_tuples.txt |
Q:
Unnamed: 0" column impossible to erase
Hello I have a code that filters some rows of a csv and creates a csv without those rows but when I create that csv I get a column called "Unnamed: 0" and it is impossible to delete it.
import pandas as pd
df = pd.read_csv("table.csv")
df.drop(df[df['Stock'].eq('No')].index,... | Unnamed: 0" column impossible to erase | Hello I have a code that filters some rows of a csv and creates a csv without those rows but when I create that csv I get a column called "Unnamed: 0" and it is impossible to delete it.
import pandas as pd
df = pd.read_csv("table.csv")
df.drop(df[df['Stock'].eq('No')].index, inplace=True)
df.to_csv('pedro.csv', index=... | [
"You need to reassign your dataframe after using pandas.DataFrame.drop or set inplace=True.\nTry this :\nimport pandas as pd\n\ndf = pd.read_csv(\"table.csv\")\ndf.drop(df[df['Stock'].eq('No')].index, inplace=True)\ndf.drop(\"Unnamed: 0\", axis=1, inplace=True)\ndf.to_csv('pedro.csv', index=False)\n\nOr this:\nimpo... | [
0
] | [] | [] | [
"csv",
"pandas",
"python"
] | stackoverflow_0074511461_csv_pandas_python.txt |
Q:
"TypeError: Can't instantiate abstract class" in Python
I have a module fi with the following classes defined:
class Asset(metaclass=abc.ABCMeta):
pass
@abc.abstractmethod
def get_price(self, dt : datetime.date, **kwargs):
''' Nothing here yet
'''
class CashFlows(Asset):
def __init__(self... | "TypeError: Can't instantiate abstract class" in Python | I have a module fi with the following classes defined:
class Asset(metaclass=abc.ABCMeta):
pass
@abc.abstractmethod
def get_price(self, dt : datetime.date, **kwargs):
''' Nothing here yet
'''
class CashFlows(Asset):
def __init__(self, amounts : pandas.Series, probabilities : pandas.Series = No... | [
"Your CashFlows class needs to define an implementation of get_price; it's an abstract method and concrete subclasses must implement it.\n",
"You need to override get_price() abstract method in CashFlows class as shown below:\nclass Asset(metaclass=abc.ABCMeta):\n \n @abc.abstractmethod\n def get_price(s... | [
18,
0
] | [] | [] | [
"abstract_class",
"abstract_methods",
"python",
"python_2.x",
"python_3.x"
] | stackoverflow_0031973548_abstract_class_abstract_methods_python_python_2.x_python_3.x.txt |
Q:
find prime numbers in python
I need to write a code that will find all prime numbers in a range of numbers and then list them in order saying which are prime and which are not, and also if they are not prime, show by what numbers they are divisible. It should look something like this:
>>> Prime(1,10)
1 is not a pr... | find prime numbers in python | I need to write a code that will find all prime numbers in a range of numbers and then list them in order saying which are prime and which are not, and also if they are not prime, show by what numbers they are divisible. It should look something like this:
>>> Prime(1,10)
1 is not a prime number
2 is a prime number
3 ... | [
"Using a sieve will do the trick:\nExample:\nfrom __future__ import print_function\n\n\ndef primes():\n \"\"\"Prime Number Generator\n\n Generator an infinite sequence of primes\n\n http://stackoverflow.com/questions/567222/simple-prime-generator-in-python\n \"\"\"\n\n # Maps composites to primes wit... | [
1,
0,
0,
0,
0,
0
] | [] | [] | [
"primes",
"python",
"string"
] | stackoverflow_0030720719_primes_python_string.txt |
Q:
updating the value of a variable inside of a function
Every time I try to use the variable i in the function modulus, it sets the variable to equal 0.
I tried using the line of code: newi = i, but that didn't work because i was already equal to 0. I tried i = i in the modulus function, but that also didn't work. I... | updating the value of a variable inside of a function | Every time I try to use the variable i in the function modulus, it sets the variable to equal 0.
I tried using the line of code: newi = i, but that didn't work because i was already equal to 0. I tried i = i in the modulus function, but that also didn't work. I've tried defining both i and a at the top of the program, ... | [
"... \n\ni = 3\na = 0\n \nfor i in range(intnumber):\n print(\"1 check\")\n primeChecker(i, a, prime, modulusCounter)\n\n...\n\nThe \"for\" loop is setting i to 0. You can see for yourself by adding print statements\n...\ni = 3\na = 0\n\nprint(i)\n\nfor i in range(10):\n print(i)\n # ...your code\n\... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074511773_python_python_3.x.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.