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:
Specifying sorting direction in psycopg2 by parameter
I want to specify in a query the sorting direction (ASC/DESC) by parameter, but psycopg2 throws an error as I'm sending a string as a replacement for a reserved word:
ProgrammingError: syntax error at or near "'ASC'"
this is my code:
cursor.execute("""
SEL... | Specifying sorting direction in psycopg2 by parameter | I want to specify in a query the sorting direction (ASC/DESC) by parameter, but psycopg2 throws an error as I'm sending a string as a replacement for a reserved word:
ProgrammingError: syntax error at or near "'ASC'"
this is my code:
cursor.execute("""
SELECT * FROM foo
ORDER BY
CASE %(order_by... | [
"You will need to use string interpolation. Parameter substitution is only possible with literals. Unfortunately.\n - Craig Ringer\ncursor.execute(\"\"\"\nSELECT * FROM foo\n ORDER BY\n CASE %(order_by)s\n WHEN 'a' THEN textfield_a {0}\n WHEN 'b' THEN textfield_b {0}\n EL... | [
2,
0
] | [] | [] | [
"postgresql",
"psycopg2",
"python"
] | stackoverflow_0032137628_postgresql_psycopg2_python.txt |
Q:
Why can't i insatll auto-sklearn on flask virtual enviroment?
Collecting auto-sklearn
Using cached auto-sklearn-0.15.0.tar.gz (6.5 MB)
Installing build dependencies ... done
Getting requirements to build wheel ... error
error: subprocess-exited-with-error
× Getting requirements to build wheel did not run successfu... | Why can't i insatll auto-sklearn on flask virtual enviroment? | Collecting auto-sklearn
Using cached auto-sklearn-0.15.0.tar.gz (6.5 MB)
Installing build dependencies ... done
Getting requirements to build wheel ... error
error: subprocess-exited-with-error
× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─> [17 lines of output]
Traceback (most recent... | [
"Windows\nauto-sklearn relies heavily on the Python module resource. resource is part of Python’s Unix Specific Services and not available on a Windows machine. Therefore, it is not possible to run auto-sklearn on a Windows machine.\nPossible solutions:\nWindows 10 bash shell (see 431 and 860 for suggestions)\nvirt... | [
0
] | [] | [] | [
"auto_sklearn",
"python",
"virtualenv"
] | stackoverflow_0074178777_auto_sklearn_python_virtualenv.txt |
Q:
can anyone tell the meaning of ord in ord() function in python
ord() is used to get the ascii value of the character we insert.
like ord("A") => 65
does anyone know what ord stands for? like ordinal or something else?
A:
It stands for ASCII code, which is a code for the most general characters, like letters, dig... | can anyone tell the meaning of ord in ord() function in python | ord() is used to get the ascii value of the character we insert.
like ord("A") => 65
does anyone know what ord stands for? like ordinal or something else?
| [
"It stands for ASCII code, which is a code for the most general characters, like letters, digits, point, comma, ...\nMore information can be found on Wikipedia.\n",
"From the python docs for ord()\n\nGiven a string representing one Unicode character, return an integer representing the Unicode code point of that c... | [
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074178771_python_python_3.x.txt |
Q:
Python classes combined with a list of dictionaries
I want to make a python class from a list of dictionaries. I tried the following but it tells me that i cant have list indices that are dictionaries.
class Dict_to_Class(object):
def __init__(self, s_dict):
for key in s_dict:
setattr(self,... | Python classes combined with a list of dictionaries | I want to make a python class from a list of dictionaries. I tried the following but it tells me that i cant have list indices that are dictionaries.
class Dict_to_Class(object):
def __init__(self, s_dict):
for key in s_dict:
setattr(self, key, s_dict[key])
if __name__ == '__main__':
s_dict ... | [
"s_dict is not a dictionary, but a list of dictionaries. You have to update your code accordingly to that, and access to each position using numeric indices.\nIf you choose one element of your list, your code works:\nclass Dict_to_Class(object):\n def __init__(self, s_dict):\n \n for key in s_dict:... | [
1
] | [] | [] | [
"class",
"dictionary",
"list",
"python"
] | stackoverflow_0074178781_class_dictionary_list_python.txt |
Q:
Can someone explain this recursion problem to me? (Factorial)
Edit - I have solved this problem but if its okay, I would like the experts here to still explain this problem so that other beginners could learn. You would do a way better job explaining.
I'm trying to learn recursion and I kind of get the idea of rec... | Can someone explain this recursion problem to me? (Factorial) | Edit - I have solved this problem but if its okay, I would like the experts here to still explain this problem so that other beginners could learn. You would do a way better job explaining.
I'm trying to learn recursion and I kind of get the idea of recursion (dividing a big problem into smaller solutions and then comb... | [
"This recursion has its termination condition at n = 1.\nThis means it returns a constant value at n=1 and will not start another recursive call. If the n is > 1 it will return n*fact(n-1).\nThe calls for fact(5):\n\n5*fact(4)\n5*(4*fact(3))\n5*(4*(3*fact(2)))\n5*(4*(3*(2*fact(1))))\n5*(4*(3*(2*1)))\n\n",
"The fi... | [
1,
1,
1
] | [] | [] | [
"python",
"recursion",
"tail_recursion"
] | stackoverflow_0074178651_python_recursion_tail_recursion.txt |
Q:
Create a python code that counts prime numbers in range(3000000) using for-looped multithreading(e.g. if Nthreads is N, it is gonna divide 3000000/N)
I'm trying to run this program but it is showing me "Thread 0 has 0 prime numbers" in the console followed by "Killed" after 5 minutes. Moreover, it is very slow. Pl... | Create a python code that counts prime numbers in range(3000000) using for-looped multithreading(e.g. if Nthreads is N, it is gonna divide 3000000/N) | I'm trying to run this program but it is showing me "Thread 0 has 0 prime numbers" in the console followed by "Killed" after 5 minutes. Moreover, it is very slow. Please help me develop and correct this code.
import time
Nthreads=4
maxNumber=3000000
starting_range=0
ending_range=0
division=0
lst=[]
def prime(x, y):
... | [
"In Python, if you use multithreading for CPU-bound tasks, it will be slower than if you don't use multithreading. You need to use multiprocessing for this problem. You can read this article for more informations: https://www.geeksforgeeks.org/difference-between-multithreading-vs-multiprocessing-in-python/\n",
"M... | [
1,
1
] | [] | [] | [
"counter",
"multithreading",
"primes",
"python",
"time"
] | stackoverflow_0074178283_counter_multithreading_primes_python_time.txt |
Q:
How to display bars for 0 value in matplotlib?
I am trying to show the value of a result even when zero or close to zero, however I can't get the plot to show the values. How do I get matplotlib to show the bar for these cases? I have tried adjusting the bottom of the plot so that it might show zero values, howeve... | How to display bars for 0 value in matplotlib? | I am trying to show the value of a result even when zero or close to zero, however I can't get the plot to show the values. How do I get matplotlib to show the bar for these cases? I have tried adjusting the bottom of the plot so that it might show zero values, however the length of the bars is still zero.
import matpl... | [
"Matplotlib won't show bar which has zero height because it does not have any height. However, if there are bars with height order of magnitude lesser than others bars in the data, changing the scale of Y-axis would help.\nFor example, using symmetric log axis scaling, we can get:\n\nCode to reproduce the figure ab... | [
0
] | [] | [] | [
"bar_chart",
"matplotlib",
"python"
] | stackoverflow_0074137818_bar_chart_matplotlib_python.txt |
Q:
Networkx graph with different nodes from three lists
i want to describe you my problem...
I tried to optimize routes with gurobipy and I got active arcs like this:
active_arcs=[(0, 2),(0, 4),(0, 11),(1, 24),(2, 7),(3, 1),(4, 5),(5, 3),(6, 0),(7, 6),
(8, 14),(9,6),(10, 0),(11, 13),(12, 9),(13, 12),(14, 15),(15, 16)... | Networkx graph with different nodes from three lists | i want to describe you my problem...
I tried to optimize routes with gurobipy and I got active arcs like this:
active_arcs=[(0, 2),(0, 4),(0, 11),(1, 24),(2, 7),(3, 1),(4, 5),(5, 3),(6, 0),(7, 6),
(8, 14),(9,6),(10, 0),(11, 13),(12, 9),(13, 12),(14, 15),(15, 16),(16, 17),(17, 18),
(18, 0),(19, 23),(20, 19),(21, 20),(22... | [
"Change the values of you labels dict in order to adapt the labels and create a list of color in the order of the nodes of you graph:\nimport networkx\n\nactive_arcs=[(0, 2),(0, 4),(0, 11),(1, 24),(2, 7),(3, 1),(4, 5),(5, 3),(6, 0),(7, 6),\n(8, 14),(9,6),(10, 0),(11, 13),(12, 9),(13, 12),(14, 15),(15, 16),(16, 17),... | [
0
] | [] | [] | [
"networkx",
"python",
"python_3.x"
] | stackoverflow_0074172594_networkx_python_python_3.x.txt |
Q:
export data from MongoDB to Excel by python
export data from MongoDB to Excel by python , so far I can extract data and print out the data.
I'm stocking on saving data to excel file
(problem: can save as new file, but only save one line of data)
the code is below:
import pandas as pd
from pymongo import MongoCli... | export data from MongoDB to Excel by python | export data from MongoDB to Excel by python , so far I can extract data and print out the data.
I'm stocking on saving data to excel file
(problem: can save as new file, but only save one line of data)
the code is below:
import pandas as pd
from pymongo import MongoClient
import pymongo
from json2excel import Json2Ex... | [
"you put list_01 = [] inside for loop, so this will clear everytime when u insert new data, that why only left the last one\nthe correct code:\nimport pandas as pd\nfrom pymongo import MongoClient\nimport pymongo\nfrom json2excel import Json2Excel\nimport json\nfrom bson.objectid import ObjectId\nfrom bson import j... | [
1
] | [] | [] | [
"json2csv",
"python",
"python_3.x"
] | stackoverflow_0074178532_json2csv_python_python_3.x.txt |
Q:
subtract a constant from a column to create a new one
I have a geodata frame. I have a column and I would like to create a new one subtracting one if that column is strictly greater than 0, otherwise, maintain the same value.
I have tried the following:
df['new_column'] = df.apply(lambda y: (df['old_column'].subt... | subtract a constant from a column to create a new one | I have a geodata frame. I have a column and I would like to create a new one subtracting one if that column is strictly greater than 0, otherwise, maintain the same value.
I have tried the following:
df['new_column'] = df.apply(lambda y: (df['old_column'].subtract(1)) if y['old_column'] > 0 else y['old_column'], axis=... | [
"The error is that you need to take one cell and not the entire column df['old_column'] => y['old_column']. In addition, there is no subtract method for a numpy object.\ndf['new_column'] = df.apply(lambda y: (y['old_column'] - 1) if y['old_column'] > 0 else y['old_column'], axis=1)\n\nA simpler expression if data f... | [
2,
1
] | [] | [] | [
"lambda",
"pandas",
"python"
] | stackoverflow_0074178614_lambda_pandas_python.txt |
Q:
How to drop identical columns in Pandas dataframe if first x rows of values are identical?
I'm working with a large dataset (921600 rows, 23 columns) with the occasional duplicate column (different column names however). I would like to remove the columns with identical values. However, 'df.T.drop_duplicates().T' ... | How to drop identical columns in Pandas dataframe if first x rows of values are identical? | I'm working with a large dataset (921600 rows, 23 columns) with the occasional duplicate column (different column names however). I would like to remove the columns with identical values. However, 'df.T.drop_duplicates().T' and similar solutions simply take too long as they presumably are checking all 921600 rows. Is i... | [
"Use DataFrame.duplicated with filter top values in DataFrame.head, filter rows by DataFrame.loc:\nN = 2\ndf = df.loc[:, ~df.head(N).T.duplicated()]\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"duplicates",
"pandas",
"python"
] | stackoverflow_0074178922_dataframe_duplicates_pandas_python.txt |
Q:
Minimum domino rotations - with python
In this exercise, we need to rotate dominos so that the numbers on one of the rows (either top or bottom) is all equal. The dominos will be given as two lists of integers, one for the top row and one for the bottom row. The rotation is done by swapping the top and bottom row ... | Minimum domino rotations - with python | In this exercise, we need to rotate dominos so that the numbers on one of the rows (either top or bottom) is all equal. The dominos will be given as two lists of integers, one for the top row and one for the bottom row. The rotation is done by swapping the top and bottom row of a domino. Ensure you do the most efficien... | [
"I think this solution would be simpler. It's all explained in the code:\ndef min_domino_rotations(top, bottom):\n if len(top) == 1:\n return 0 # already solved\n\n # we want to find which value 1-6 exists on all dominos\n # (if domino has 2 equal values, count only once)\n counters = [-1, 0, 0, 0, 0, 0, 0]\... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074178725_python.txt |
Q:
how to shift backward in time a date column and keep the same date in the last row of each group?
i'm scratching my head on this problem for a while now. I have a log with a case id, an activity id and the date in which the activity occurred. i need to add a column which will represent the end timestamp (DATEEND),... | how to shift backward in time a date column and keep the same date in the last row of each group? | i'm scratching my head on this problem for a while now. I have a log with a case id, an activity id and the date in which the activity occurred. i need to add a column which will represent the end timestamp (DATEEND), but i don't know how to make the last date in the column DATEEND of each case id as the last date in t... | [
"Use Series.fillna by column DATESTART:\ndf['DATEEND'] = df.groupby('CASEID')['DATESTART'].shift(-1).fillna(df['DATESTART'])\nprint (df)\n CASEID ACTIVITYID DATESTART DATEEND\n0 725/2022 _0 2022-03-09 2022-03-23\n1 725/2022 0F 2022-03-23 2022-06-21\n2 725/2022 YB 2022-06-21... | [
2
] | [] | [] | [
"date",
"group_by",
"pandas",
"python"
] | stackoverflow_0074178970_date_group_by_pandas_python.txt |
Q:
How to run python3 code in VSCode? /bin/sh: 1: python: not found
I'm trying to run a python file in VSCode using python3.
I know I can fix by simply setting to run using integrated terminal like it says in the microsoft vscode tutorial on python. However, I would like the program to print in the output tab and not... | How to run python3 code in VSCode? /bin/sh: 1: python: not found | I'm trying to run a python file in VSCode using python3.
I know I can fix by simply setting to run using integrated terminal like it says in the microsoft vscode tutorial on python. However, I would like the program to print in the output tab and not take up the terminal window.
The standard coder runner launch.json l... | [
"Nearly had it. This code\n\"python.pythonPath\": \"python3\",\n\"code-runner.executorMap\": {\n \"python3\": \"/usr/bin/python3\"\n}\n\nshould be\n\"python.pythonPath\": \"python3\",\n\"code-runner.executorMap\": {\n \"python\": \"/usr/bin/python3\"\n}\n\n(The difference is at the beginning of line 3)\n",
... | [
20,
10,
2,
1,
0,
0
] | [] | [] | [
"python",
"python_3.x",
"ubuntu",
"visual_studio_code"
] | stackoverflow_0061620036_python_python_3.x_ubuntu_visual_studio_code.txt |
Q:
Matplotlib - Adding quadrants to a strikezone?
I am working on a baseball analytics project and would like to display information based on the location of pitches over the course of a season to certain batters. While I can group the data points based on their location, I would like to display this in the form of a... | Matplotlib - Adding quadrants to a strikezone? | I am working on a baseball analytics project and would like to display information based on the location of pitches over the course of a season to certain batters. While I can group the data points based on their location, I would like to display this in the form of a strikezone heatmap.
# define the strikezone quadran... | [
"I would do some of the calculations slightly different, but just working off your code:\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\n\nyTikMarks = [] \nfeet = 1.6\nwhile feet <= 4: \n yTikMarks.append(feet)\n feet += round((2.1)/3, 2) \n \nxTikMarks = []\nfeet = -0.7 # from pit... | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074119453_matplotlib_python.txt |
Q:
Python asyncio and aiohttp slowing down after 150+ requests
I'm using asyncio and aiohttp to make a async scraper.
For some reason after I hit 150+ request its start slowing down. The first async
runs fine where i get the links. The second one is where i get the problem where the slowness happens. Like after 200 ... | Python asyncio and aiohttp slowing down after 150+ requests | I'm using asyncio and aiohttp to make a async scraper.
For some reason after I hit 150+ request its start slowing down. The first async
runs fine where i get the links. The second one is where i get the problem where the slowness happens. Like after 200 it needs 1min for one request. Any idea why? Am I using Asyncio o... | [
"Could it be due to the limit on aiohttp.ClientSession connections?\nhttps://docs.aiohttp.org/en/latest/http_request_lifecycle.html#how-to-use-the-clientsession\nIt may try passing connector with larger limit: https://docs.aiohttp.org/en/latest/client_advanced.html#limiting-connection-pool-size\n"
] | [
0
] | [] | [] | [
"aiohttp",
"performance",
"python",
"python_asyncio"
] | stackoverflow_0048255660_aiohttp_performance_python_python_asyncio.txt |
Q:
Update the yolov5 annotations ".txt" files of cropped images
I want to crop images which is already annotated for yolov5 format ".txt", but the coordinates will change on cropped so how can i update it and the image crop coordinate will also be one of the class in annotation .txt file. For example: there is two mo... | Update the yolov5 annotations ".txt" files of cropped images | I want to crop images which is already annotated for yolov5 format ".txt", but the coordinates will change on cropped so how can i update it and the image crop coordinate will also be one of the class in annotation .txt file. For example: there is two model i want to train first will just detect odometer and second wil... | [
"As I have mentioned in the comments, I think I can write that as an answer as well.\nYou can crop your images from yolov5 with --save-crop flag of yolov5. And then for the annotations, you can actually give out full image size as the bounding box sizes. I suggest you check out this thread as well.\n"
] | [
0
] | [] | [] | [
"image_processing",
"python",
"yolov5"
] | stackoverflow_0074173025_image_processing_python_yolov5.txt |
Q:
Why is image.astype(uint8) different from np.clip(image.astype(uint32), 0, 255) in Python?
I am a bit confused about a behavior of my code.
I have an image tensor with values in range [0, 255] to which I have added some Gaussian noise so that the resulting tensor has values in larger and now continuous range, e.g.... | Why is image.astype(uint8) different from np.clip(image.astype(uint32), 0, 255) in Python? | I am a bit confused about a behavior of my code.
I have an image tensor with values in range [0, 255] to which I have added some Gaussian noise so that the resulting tensor has values in larger and now continuous range, e.g. ca. [-253.234, 581.613].
This tensor should then be visualized via plt.imshow(...).
For this an... | [
"if you have any negative values in the image, then casting to uint32 is or uint8 will create different results.\n"
] | [
1
] | [] | [] | [
"matplotlib",
"noise",
"python",
"unsigned_integer",
"visualization"
] | stackoverflow_0074178516_matplotlib_noise_python_unsigned_integer_visualization.txt |
Q:
Python Tkinter Grid Expand to window
I have a notebook that I played in grid (0;0). I want to the notebok to fill the entire screen even if its content (frames) would not fill the screen.
class App(Tk):
def __init__(self) -> None:
super().__init__()
# Widgets
self.notebook = Notebook(... | Python Tkinter Grid Expand to window | I have a notebook that I played in grid (0;0). I want to the notebok to fill the entire screen even if its content (frames) would not fill the screen.
class App(Tk):
def __init__(self) -> None:
super().__init__()
# Widgets
self.notebook = Notebook(self) # <-- Widget I want to fill the win... | [
"I think you need to use the sticky argument in you grid:\n\nThe width of a column (and height of a row) depends on all the widgets\ncontained in it. That means some widgets could be smaller than the\ncells they are placed in. If so, where exactly should they be put\nwithin their cells?\nBy default, if a cell is la... | [
0
] | [] | [] | [
"python",
"tcl",
"tkinter",
"tkinter_layout"
] | stackoverflow_0074178940_python_tcl_tkinter_tkinter_layout.txt |
Q:
OpenCV Find a middle line of a contour [Python]
In my image processing project, I have already obtained a masked image (black-and-white image) and its contours using the cv.findContours function. My goal now is to create an algorithm that can draw a middle line for this contour. The masked image and its contour ar... | OpenCV Find a middle line of a contour [Python] | In my image processing project, I have already obtained a masked image (black-and-white image) and its contours using the cv.findContours function. My goal now is to create an algorithm that can draw a middle line for this contour. The masked image and its contour are shown in the following images.
Masked image:
Conto... | [
"I believe you're trying to determine the contour's center of gravity and orientation. We can easily do this using Central Moments. More info on that here.\nThe code below generates this plot. Is this the result you wanted?\n# Determine contour\nimg = cv2.imread(img_file, cv2.IMREAD_GRAYSCALE)\nimg_bin = (img>128).... | [
3,
1,
1,
0
] | [] | [] | [
"contour",
"image_processing",
"opencv",
"python"
] | stackoverflow_0064396183_contour_image_processing_opencv_python.txt |
Q:
How to create a json file from csv file where csv file has following format
Name,abc
Title,teacher
Email,abc.edu
Phone,000-000-0000
Office,21building
About,"abc is teacher"
Name,def
Title,plumber
Email,plumber@plumber.com
Phone,111-111-1111
Office,22building
About,"The best plumber in the town"
Name,ghi
Title,prod... | How to create a json file from csv file where csv file has following format | Name,abc
Title,teacher
Email,abc.edu
Phone,000-000-0000
Office,21building
About,"abc is teacher"
Name,def
Title,plumber
Email,plumber@plumber.com
Phone,111-111-1111
Office,22building
About,"The best plumber in the town"
Name,ghi
Title,producer
Phone,333-333-3333
Office,33building
About,"The best producer"
| [
"I would use pandas library to read the .csv (foo.csv in this example) data and then convert it to json using to_json.\nIn this case you have a dictionary\nimport pandas as pd\npd.read_csv('aaa.csv', header=None, index_col=0, squeeze=True)\\\n .to_json(orient='columns')\n\nIf you want to export a .json file\nimp... | [
0,
0
] | [] | [] | [
"csv",
"dataframe",
"json",
"pandas",
"python"
] | stackoverflow_0074176242_csv_dataframe_json_pandas_python.txt |
Q:
How do I use intents in discord's Python API
I have tried running this script without the intents at first, but then VS Code told me that I needed it without giving me any hint as to what to put after intents.
Code:
import discord
client = discord.Client(intents=)
@client.event
async def on_connect():
for use... | How do I use intents in discord's Python API | I have tried running this script without the intents at first, but then VS Code told me that I needed it without giving me any hint as to what to put after intents.
Code:
import discord
client = discord.Client(intents=)
@client.event
async def on_connect():
for user in client.user.friends:
try:
... | [
"There are two parts to this:\nFirst, you need to enable which intents you need in the Discord Developer portal. This is under Bots > Privileged Gateway Intents. Next, you need to go in your code, and type in the intents.\nFor example, if you just selected Message Content Intent, you would put this next to intents:... | [
0
] | [] | [] | [
"discord",
"python"
] | stackoverflow_0074177286_discord_python.txt |
Q:
value true if unequal to the three previous values
from this reproducible example:
import pandas as pd
data={'col1':[False, False, False, False,False, False, True, True]}
df=pd.DataFrame(data,columns=['col1'])
print (df)
df['match'] = df.col1.eq(df.col1.shift(3))
print (df)
the above code gives:
col1
0 False... | value true if unequal to the three previous values | from this reproducible example:
import pandas as pd
data={'col1':[False, False, False, False,False, False, True, True]}
df=pd.DataFrame(data,columns=['col1'])
print (df)
df['match'] = df.col1.eq(df.col1.shift(3))
print (df)
the above code gives:
col1
0 False
1 False
2 False
3 False
4 False
5 False
6 True
7... | [
"You can use:\nN = 3\ndf['match3'] = (df['col1']\n .rolling(N+1, min_periods=1)\n .apply(lambda x: x.iloc[:-1].ne(x.iloc[-1]).all())\n .astype(bool)\n )\n\noutput:\n col1 match match3\n0 False False True\n1 False False False\n2 False False ... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074179055_pandas_python.txt |
Q:
Plot functions using Matplotlib similar to Matlab
I have a function which plots a figure
import matplotlib.pyplot as plt
def myplot(x, y):
plt.figure()
plt.plot(x, y)
plt.show()
myplot([1, 2, 3], [4, 5, 6])
myplot([1, 2, 3], [4, 5, 6])
However after I run the script only one figure shows up, and the... | Plot functions using Matplotlib similar to Matlab | I have a function which plots a figure
import matplotlib.pyplot as plt
def myplot(x, y):
plt.figure()
plt.plot(x, y)
plt.show()
myplot([1, 2, 3], [4, 5, 6])
myplot([1, 2, 3], [4, 5, 6])
However after I run the script only one figure shows up, and the second one shows when I close the first figure. I ca... | [
"this is not a simple thing, as Matlab is already running a GUI eventloop, while for python ... it depends on the IDE, for example Spyder will run it similar to Matlab as it is running an event loop, while Pycharm / VScode don't allow python to snatch their event loop, and jupyter notebook is running an asyncio ser... | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074179058_matplotlib_python.txt |
Q:
Selecting BeautifulSoup tag based on attributes value
Suppose that we have an .htm page with an index and some content below. Each element of the index has its link to the related section on the document;
Suppose that our starting point is a tag with an href, (<a href="#001">SECTION 1</a>); I want to look into all... | Selecting BeautifulSoup tag based on attributes value | Suppose that we have an .htm page with an index and some content below. Each element of the index has its link to the related section on the document;
Suppose that our starting point is a tag with an href, (<a href="#001">SECTION 1</a>); I want to look into all tags to find the reference to this href, therefore I want ... | [
"You can use lambda function in soup.find_all(), for example:\nfrom bs4 import BeautifulSoup\n\nhtml_doc = \"\"\"\\\n <a id=\"#001\">SECTION 1</a>\n\n <a>something other</a>\n\n <a name=\"#001\">SECTION 1</a>\n <div name=\"#001\">SECTION 1</div>\n\n <div name=\"#002\">something other</div>\n\n <di... | [
1
] | [] | [] | [
"beautifulsoup",
"html",
"python"
] | stackoverflow_0074179078_beautifulsoup_html_python.txt |
Q:
Internal Server Error while doing post request in flask using nginx and uwsgi
I am using this tutorial
Background: I am using flask post API to activate selenium to extract information and send them to website. This work perfectly when I don't apply nginx configuration and just run the below code on server (as in ... | Internal Server Error while doing post request in flask using nginx and uwsgi | I am using this tutorial
Background: I am using flask post API to activate selenium to extract information and send them to website. This work perfectly when I don't apply nginx configuration and just run the below code on server (as in local machine using port 5000).
Problem: when I try to deploy the flask application... | [
"Pay attention at the names of the file!\nI have followed the same tutorial.\nFrom your answer are not clear names of the different files that you have created.\nI suggest you to follow exactly the tutorial and in particular the names schema (for the files) that it suggests.\nI try to give you some advices.\n\nThe ... | [
0
] | [] | [] | [
"flask",
"linux",
"nginx",
"python",
"uwsgi"
] | stackoverflow_0074078549_flask_linux_nginx_python_uwsgi.txt |
Q:
How to split text using a list of keywords
I am trying split my data so that I can categorize/classify. Below sample data, although is most are well labelled, but all is written in one string under description.
df = pd.DataFrame({"name":['Kelly', 'David', 'Mandy', "John"], "description":["age: 12 gender:female hob... | How to split text using a list of keywords | I am trying split my data so that I can categorize/classify. Below sample data, although is most are well labelled, but all is written in one string under description.
df = pd.DataFrame({"name":['Kelly', 'David', 'Mandy', "John"], "description":["age: 12 gender:female hobbies: loves to read", "age:16, gender:male, hobb... | [
"You could try using regular expressions to help search and parse the strings, like below:\n# Import statements\nimport pandas as pd\nimport re\n\n# Your initial data frame\ndf = pd.DataFrame({\"name\":['Kelly', 'David', 'Mandy', \"John\"], \"description\":[\"age: 12 gender:female hobbies: loves to read\", \"age:16... | [
0
] | [] | [] | [
"python",
"split"
] | stackoverflow_0074177152_python_split.txt |
Q:
Get lines of multi-line string, Python
I'm trying to convert large string in lines, but failing if \n is occurred in it.
Example string
s1 = """
x = 10
y = 20
print(f"Sample Calculator:\n{x} + {y} = {x+y}")"""
lines = s1.splitlines() # Similar results on lines = s1.split('\n')
print(*lines, sep='\n------\n')
out... | Get lines of multi-line string, Python | I'm trying to convert large string in lines, but failing if \n is occurred in it.
Example string
s1 = """
x = 10
y = 20
print(f"Sample Calculator:\n{x} + {y} = {x+y}")"""
lines = s1.splitlines() # Similar results on lines = s1.split('\n')
print(*lines, sep='\n------\n')
output:
------
x = 10
------
y = 20
------
pri... | [
"To preserve backslashes literally, you use a raw-string, denoted by the prefix r, so that you don't have to escape every occurrence of a backslash with another backslash:\ns1 = r\"\"\"\nx = 10\ny = 20\nprint(f\"Sample Calculator:\\n{x} + {y} = {x+y}\")\"\"\"\n\n",
"Change this line to:\nprint(f\"Sample Calculato... | [
2,
1
] | [] | [] | [
"python",
"split",
"string"
] | stackoverflow_0074178624_python_split_string.txt |
Q:
convert path to excel using python and pysimplegui gives typeError
I am trying to write a script which writes path data to an excel file. The function is working, I just want to create an simple GUI using PySimpleGUI where the user can give a path. The path variable is used in the function. Now I have the error:
s... | convert path to excel using python and pysimplegui gives typeError | I am trying to write a script which writes path data to an excel file. The function is working, I just want to create an simple GUI using PySimpleGUI where the user can give a path. The path variable is used in the function. Now I have the error:
str_path = int(values['-INF1-'])
TypeError: tuple indices must be integer... | [
"This is how PySimpleGUI docs tell us to read event and values from Window:\nevent, values = window.read()\n\nInstead you do (in different places):\nvalues = window.read()\n...\nevent = window.read()\n\nIn your code values/event is assigned a tuple of (<EVENT>, <VALUES>), which you try to process as if it were PySi... | [
2
] | [] | [] | [
"pysimplegui",
"python"
] | stackoverflow_0074179067_pysimplegui_python.txt |
Q:
How to form a dictionary for use in JSON body from a Pandas data frame?
I have the starting data frame looking like this:
my_list = [
['Japan', 'Flowers'],
['United States', 'Guns', 'yes'],
['Japan', 'Sushi'],
['South Korea', 'Sunscreen']
]
df = pd.DataFrame(my_list, columns=["country", "sector", ... | How to form a dictionary for use in JSON body from a Pandas data frame? | I have the starting data frame looking like this:
my_list = [
['Japan', 'Flowers'],
['United States', 'Guns', 'yes'],
['Japan', 'Sushi'],
['South Korea', 'Sunscreen']
]
df = pd.DataFrame(my_list, columns=["country", "sector", "flag"])
I need the output to be in this exact format of a dictionary for a... | [
"Try:\nout = []\nfor idx, g in df.groupby(\"country\"):\n out.append({\"name\": idx})\n ids = {}\n for i, s in g[\"sector\"].iteritems():\n ids.setdefault(s, []).append(i)\n out[-1][\"groups\"] = [{\"name\": k, \"ids\": v} for k, v in ids.items()]\n\n\nout = {\"groups\": out}\nprint(out)\n\nPrint... | [
1
] | [] | [] | [
"json",
"pandas",
"python"
] | stackoverflow_0074179048_json_pandas_python.txt |
Q:
How to structure data clustering python project?
The project: Read in 2D data, cluster datapoints based on different cluster techniques/models, and evaluate how well the clustering has worked.
Since I am unhappy with my project structure so far, and have little experience with project structures, I hope to get som... | How to structure data clustering python project? | The project: Read in 2D data, cluster datapoints based on different cluster techniques/models, and evaluate how well the clustering has worked.
Since I am unhappy with my project structure so far, and have little experience with project structures, I hope to get some feedback on how to proceed. The structure is as foll... | [
"Your project's structure should balance the tension between competing stakeholder's needs.\ni) The Coder : This person (probably you) will want to have a number of small, composable functions spread across the codebase where they can be easily tested in isolation, and reused in lots of different ways. The code sho... | [
0
] | [] | [] | [
"python",
"structure"
] | stackoverflow_0074178856_python_structure.txt |
Q:
Message: stale element reference: element is not attached to the page document while refreshing TABLE DATA
First of all, sorry for my bad english.
I have a project to retrieve row data in a table continuously using
driver.refresh()
The first loop is successful, the data appears for each row. Now for the 2nd loop ... | Message: stale element reference: element is not attached to the page document while refreshing TABLE DATA | First of all, sorry for my bad english.
I have a project to retrieve row data in a table continuously using
driver.refresh()
The first loop is successful, the data appears for each row. Now for the 2nd loop a message appears
Message: stale element reference: element is not attached to the page document
For some reaso... | [
"As you understand, and it is correct, after refreshing all the web elements on the page are being re-rendered. Selenium WebEelement is actually a pointer, a reference to a physical web element on the actual web page. So, after the page was re-built all the previously collected WebElements become no more relevant. ... | [
0
] | [] | [] | [
"html",
"python",
"selenium",
"selenium_chromedriver",
"staleelementreferenceexception"
] | stackoverflow_0074177076_html_python_selenium_selenium_chromedriver_staleelementreferenceexception.txt |
Q:
Do I return None or {} in Python?
What should I return in a function that I annotate to return a dict under a condition?
For example,
def function(ls1: list, ls2: list) -> dict:
if condition:
# this tells me that the dict will not
# be possible to make
return None
di = {}
some_d... | Do I return None or {} in Python? | What should I return in a function that I annotate to return a dict under a condition?
For example,
def function(ls1: list, ls2: list) -> dict:
if condition:
# this tells me that the dict will not
# be possible to make
return None
di = {}
some_di_stuff
return di
Should I return ... | [
"What you are searching for is called Union.\nfrom typing import Union\n\ndef function(ls1: list, ls2: list) -> Union[dict, None]:\n if condition:\n # this tells me that the dict will not\n # be possible to make\n return None\n di = {}\n some_di_stuff\n return di\n\nIn this case you... | [
2
] | [] | [] | [
"annotations",
"function",
"python",
"types"
] | stackoverflow_0074179003_annotations_function_python_types.txt |
Q:
ModuleNotFoundError: No module named '_distutils_hack'
Someone could help me, please? I was running some python scripts and I found the following warning:
Traceback (most recent call last):
File "/Users/yohelcruz/opt/anaconda3/lib/python3.9/site.py", line 169, in addpackage
exec(line)
File "<string... | ModuleNotFoundError: No module named '_distutils_hack' | Someone could help me, please? I was running some python scripts and I found the following warning:
Traceback (most recent call last):
File "/Users/yohelcruz/opt/anaconda3/lib/python3.9/site.py", line 169, in addpackage
exec(line)
File "<string>", line 1, in <module>
ModuleNotFoundError: No module nam... | [
"I ended up creating an issue on conda: https://github.com/conda/conda/issues/11931\nEdit: After some additional digging I found that running \"pip install -U pip setuptools\" solved the issue\n",
"This works for me. It should solve the issue\n pip install -U pip setuptools\n\n"
] | [
8,
4
] | [] | [] | [
"python"
] | stackoverflow_0073496322_python.txt |
Q:
How can I store a link in a variable and open it using os.system()
I want to make an app in Python to open links the user assigned to buttons. For that I have to assign links to variables and open them. I tried opening them with the webbrowser module, but they would open in Microsoft Edge and not in the default br... | How can I store a link in a variable and open it using os.system() | I want to make an app in Python to open links the user assigned to buttons. For that I have to assign links to variables and open them. I tried opening them with the webbrowser module, but they would open in Microsoft Edge and not in the default browser, so I decided to use os.system(), but I can't seem to succeed in o... | [
"You are currently using the variable name as a string.\nUse something like this:\nos.system(\"start \\\"\\\" \"+link1)\n\nAlternatively this should also work:\nos.system(\"start \\\"\\\" {}\").format(link1)\n\nI just tried your Darwin approach on my macOS system. Im not quite sure what you are trying to achieve wi... | [
2
] | [] | [] | [
"browser",
"os.system",
"python",
"python_3.x"
] | stackoverflow_0074179249_browser_os.system_python_python_3.x.txt |
Q:
Connect to FTP server through same network
I'm hosting my FTP through XAMPP, and I'm trying to access the FTP from my other PC, but I cant seem to connect. I wrote a python script, which works on the PC hosting the FTP, but not on my other PC.
# Import Module
import ftplib
# Fill Required Information
HOSTNAME = "... | Connect to FTP server through same network | I'm hosting my FTP through XAMPP, and I'm trying to access the FTP from my other PC, but I cant seem to connect. I wrote a python script, which works on the PC hosting the FTP, but not on my other PC.
# Import Module
import ftplib
# Fill Required Information
HOSTNAME = "10.224.18.9"
USERNAME = "z2067"
PASSWORD = "pass... | [
"It looks like you are using the public IP address for the server. If both devices are in the same network I suggest trying the IP address visible inside that network instead.\nIf you follow this tutorial: https://lazyadmin.nl/it/ipconfig-command/ you can find out what that IP address is for the computer you are ru... | [
-1
] | [] | [] | [
"ftp",
"python",
"xampp"
] | stackoverflow_0074179296_ftp_python_xampp.txt |
Q:
Check if attribute exists python
I have some elements each has some attribute
Example:
a1 = Quadrupole(Name= 'qd1.1', Length = 2.9)
Some of them had additional attribute called R1:
a2 = Quadrupole(Name= 'qd1.1', Length = 2.9, R1=some value)
I want to loop through this element and append the attribute R, first i go... | Check if attribute exists python | I have some elements each has some attribute
Example:
a1 = Quadrupole(Name= 'qd1.1', Length = 2.9)
Some of them had additional attribute called R1:
a2 = Quadrupole(Name= 'qd1.1', Length = 2.9, R1=some value)
I want to loop through this element and append the attribute R, first i got the error "'Quadrupole' object has n... | [
"You can use hasattr:\nfor i in range(len(elements_indexes)):\n if a[i].FamName.startswith('q') and hasattr(a[i], \"R1\"):\n skew_quad_coof = a[i].R1\n else:\n skew_quad_coof = 0\n k_qs.append(skew_quad_coof)\n\nOr, even better, using a default value of getattr, and rewriting slightly the re... | [
3,
1
] | [] | [] | [
"conditional_statements",
"if_statement",
"python"
] | stackoverflow_0074179336_conditional_statements_if_statement_python.txt |
Q:
GitPython debug logs not available
In case I run a simple git command like
git fetch origin
remote: Counting objects: 26, done.
remote: Compressing objects: 100% (6/6), done.
remote: Total 26 (delta 13), reused 12 (delta 12), pack-reused 8
Unpacking objects: 100% (26/26), done.
From https://github.com/edorado93/... | GitPython debug logs not available | In case I run a simple git command like
git fetch origin
remote: Counting objects: 26, done.
remote: Compressing objects: 100% (6/6), done.
remote: Total 26 (delta 13), reused 12 (delta 12), pack-reused 8
Unpacking objects: 100% (26/26), done.
From https://github.com/edorado93/jocular
* branch master -... | [
"You're missing the logging, without which GitPython doesn't seem to want to log anything:\nimport logging\nlogging.basicConfig(level=logging.INFO)\n\nAn example after this:\nfrom git.cmd import Git\ng = Git()\ntype(g).GIT_PYTHON_TRACE=\"full\"\ng.fetch('origin')\n\nwhich outputs:\nINFO:git.cmd:git fetch origin -> ... | [
0
] | [] | [] | [
"git",
"gitpython",
"python"
] | stackoverflow_0034964465_git_gitpython_python.txt |
Q:
Way to change already printed string
Yesterday I coded a Hangman game. I got it finished and it works but now im asking myself "could it be better"?
I thought of a line of underscores to let the user know how many digits there are and than a way to chose. If the chosen letter is in the word that needs to be guesse... | Way to change already printed string | Yesterday I coded a Hangman game. I got it finished and it works but now im asking myself "could it be better"?
I thought of a line of underscores to let the user know how many digits there are and than a way to chose. If the chosen letter is in the word that needs to be guessed it replaces the underscore with the lett... | [
"You can add end='\\r' to the line which should be overwritten.\nFor the last line you should use the default end switch, otherwise the line is overwritten in the terminal (at least on linux).\nimport time\nprint('This is line 1', end='\\r')\ntime.sleep(1)\nprint('This is line 2')\n\n"
] | [
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0074179403_python_string.txt |
Q:
Python Selenium - Interact with the next WebElement object in a list
I have a list of web elements like this:
menu = self.driver.find_elements(By.CSS_SELECTOR, '[class="partEl__1o8vO"]')
For all the web elements contained in list menu
I have to perform a click, but with my code below the first element in the list... | Python Selenium - Interact with the next WebElement object in a list | I have a list of web elements like this:
menu = self.driver.find_elements(By.CSS_SELECTOR, '[class="partEl__1o8vO"]')
For all the web elements contained in list menu
I have to perform a click, but with my code below the first element in the list is clicked n times instead of clicking one time on all the elements in th... | [
"Your question is missing debugging details, but I guess the following should work:\nmenu = self.driver.find_elements(By.CSS_SELECTOR, '[class=\"partEl__1o8vO\"]')\nfor value in menu:\n value.find_element(By.CSS_SELECTOR, '[class=\"TableRow_clickableRow__1uMJO\"]').click()\n\nIn case clicking the menu options pe... | [
1
] | [] | [] | [
"for_loop",
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074179234_for_loop_python_selenium_selenium_webdriver.txt |
Q:
Probability in if statement
I have an if statement which should be executet to 80-%.
Easy example:
x = True # 80% of the time
y = False # 20% of the time
z = # Either x or y
i = 0
while i < 10:
if z == True:
print(True)
else:
print(False)
i = i+1
A:
The choices function from the random module... | Probability in if statement | I have an if statement which should be executet to 80-%.
Easy example:
x = True # 80% of the time
y = False # 20% of the time
z = # Either x or y
i = 0
while i < 10:
if z == True:
print(True)
else:
print(False)
i = i+1
| [
"The choices function from the random module accepts weights for the possible outcomes. So you could just use:\nfor i in range(10):\n print(random.choices((True, False), (80, 20))\n\nor as choices can return a number of values:\nfor i in random.choices((True, False), (80, 20), k=10):\n print(i)\n\n",
"You c... | [
0,
0
] | [] | [] | [
"if_statement",
"probability",
"python",
"while_loop"
] | stackoverflow_0074178813_if_statement_probability_python_while_loop.txt |
Q:
Adding prefix to row value based on other dataframes. Python
I have two dataframe the 1st one
CallId ScoreId ScoreName Weight
19 4198451 180 First 1.0
110 4198451 348 Second 3.0
124 4198451 15 Third 1.0
The second
CallId ScoreComponen... | Adding prefix to row value based on other dataframes. Python | I have two dataframe the 1st one
CallId ScoreId ScoreName Weight
19 4198451 180 First 1.0
110 4198451 348 Second 3.0
124 4198451 15 Third 1.0
The second
CallId ScoreComponentName ScoreId Weight
58 4198451 Dissat 1... | [
"You can merge and sum columns like this:\ndf = pd.DataFrame(\n {\"A\":[45,67,12,78,92,65,89,12,34,78],\n \"component\":[\"h\",\"b\",\"f\",\"d\",\"e\",\"t\",\"y\",\"p\",\"w\",\"q\"]})\ndf2 = pd.DataFrame(\n {\"A\":[45,67,12],\n \"name\":['First','Second','Third']})\n\nnew=d... | [
0
] | [] | [] | [
"arrays",
"dataframe",
"python"
] | stackoverflow_0074179451_arrays_dataframe_python.txt |
Q:
pandas to_excel not working with pyinstaller
I'm making an exe from a python script using pyinstaller everything in the code works fine except for to_excel(). I've listed the imports and what exactly is not working when I make it an exe. Script runs on its own and creates excel file the problem is file is not crea... | pandas to_excel not working with pyinstaller | I'm making an exe from a python script using pyinstaller everything in the code works fine except for to_excel(). I've listed the imports and what exactly is not working when I make it an exe. Script runs on its own and creates excel file the problem is file is not created if i make it an exe
import pandas as pd
import... | [
"As the pandas documentation specifies, in order for to_excel and read_excel methods to work you have to install one or more of the following packages alongside pandas:\nXLsxWriter 0.9.8 Excel writing\nopenpyxl 2.5.7 Reading / writing for xlsx files\npyxlsb 1.0.6 Reading for xlsb files\nxlrd 1.1.0 Excel r... | [
3,
0,
0,
0
] | [] | [] | [
"pandas",
"pandas.excelwriter",
"pyinstaller",
"python",
"python_3.x"
] | stackoverflow_0064367728_pandas_pandas.excelwriter_pyinstaller_python_python_3.x.txt |
Q:
Function to replace multiple characters
My code:
def replaces(_str:str,a=list,b=list):
output = ''
for num,i in enumerate(_str):
output += i.replace(a[num],b[num])
return output
but it outputs this:
>>> print(replaces('12345',['1','2','3'],['one','two','three']))
Traceback (most recent call la... | Function to replace multiple characters | My code:
def replaces(_str:str,a=list,b=list):
output = ''
for num,i in enumerate(_str):
output += i.replace(a[num],b[num])
return output
but it outputs this:
>>> print(replaces('12345',['1','2','3'],['one','two','three']))
Traceback (most recent call last):
File "g:\+ Project\beat_machine\test.p... | [
"To map a set of strings to a different set of strings, it would be easiest to create a mapping dict and use re.sub with all the source strings joined into an alternation pattern and with a replacement function that returns the mapped value of each match:\nimport re\n\ndef replaces(s, a, b):\n mapping = dict(zip... | [
1,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074179154_python.txt |
Q:
Agensgraph, graph databases, web development and webgis, advice on which way to go?
More of an advice question here.
I'm well versed in Postgres/PostGIS, so I thought I'd look at Agensgraph aka Apache Graph Extension (AGE). This is a graph implementation in Postgresql which uses SQL for 'read-only' querying, but C... | Agensgraph, graph databases, web development and webgis, advice on which way to go? | More of an advice question here.
I'm well versed in Postgres/PostGIS, so I thought I'd look at Agensgraph aka Apache Graph Extension (AGE). This is a graph implementation in Postgresql which uses SQL for 'read-only' querying, but Cypher for pattern matching (adding/updating etc.).
Usefully this means I can use psycopg2... | [
"You could give NebulaGraph a try, it’s an OpenSource GraphDatabase.\nIt supports Geo-Spatial datatype/indexing, too. The Geo info could be persistent in Vertex/Edge properties.\nRef in docs:\n\nGeo Functions\nGeo Datatype\n\n"
] | [
0
] | [] | [] | [
"agens_graph",
"graph_databases",
"python",
"web_frameworks"
] | stackoverflow_0074090457_agens_graph_graph_databases_python_web_frameworks.txt |
Q:
customtkinter - some binds don't work on frames
The problem I am having is that using customtkinter the event <ButtonPress-1> doesn't seem to work in customtkinter Frames
This can be re-produced with (doesn't work):
from customtkinter import CTk, CTkFrame
root = CTk()
root.geometry('300x300')
frame = CTkFrame(ro... | customtkinter - some binds don't work on frames | The problem I am having is that using customtkinter the event <ButtonPress-1> doesn't seem to work in customtkinter Frames
This can be re-produced with (doesn't work):
from customtkinter import CTk, CTkFrame
root = CTk()
root.geometry('300x300')
frame = CTkFrame(root)
frame.bind('<ButtonPress-1>', lambda _ : print('c... | [
"- is not allowed in a function in python(3), so you need to change it to ButtonPress1, and not ButtonPress-1.\nThat's because a function name in python only allows characters a-z, A-Z (uppercase), numbers, and an underscore.\n\nApart from these restrictions, Python allows Identifiers to be a combination of lowerca... | [
0,
0,
0
] | [] | [] | [
"customtkinter",
"python"
] | stackoverflow_0074163391_customtkinter_python.txt |
Q:
Why am I receiving 'TypeError: Object is not callable' when trying to append a class object to a global list from within a function?
I want to append a class object (Yuman) to a global list from within a function but receive the error:
Exception has occurred: TypeError 'Yuman' object is not callable
The exceptio... | Why am I receiving 'TypeError: Object is not callable' when trying to append a class object to a global list from within a function? | I want to append a class object (Yuman) to a global list from within a function but receive the error:
Exception has occurred: TypeError 'Yuman' object is not callable
The exception only occurs when the append is within this specific function, when the same sort of append works in a different simpler function (The si... | [
"In your loops:\nfor Yuman in yumanList:\n\nThe loop variable is called Yuman (same as the class name!). Pick another name instead so that Yuman does not get overridden.\nEssentially what happens is that after the loop, the variable Yuman does not point to the class anymore, but to the last item iterated in the loo... | [
0
] | [] | [] | [
"python",
"typeerror"
] | stackoverflow_0074179608_python_typeerror.txt |
Q:
Python Multithreading: Check active domains with multithreading in python optimally
The idea of the program is to check for domains/subdomains living (via http/https protocol) in the subdomains.txt file.
I did this by using HEAD requests to domains/subdomains and receiving the response status code. If the status c... | Python Multithreading: Check active domains with multithreading in python optimally | The idea of the program is to check for domains/subdomains living (via http/https protocol) in the subdomains.txt file.
I did this by using HEAD requests to domains/subdomains and receiving the response status code. If the status code is available, the domain or subdomain is live. (load_url_http function)
To speed up t... | [
"In python multithreading doesn't actually run in parallel, all the threads run under 1 process and that process runs only on 1 core (of the cpu).\nYou can create as many threads as you want and is won't solve the problem and can actually make it worse, because those 300 threads are running on 1 cpu core but that 1... | [
2
] | [] | [] | [
"file",
"multithreading",
"optimal",
"python",
"python_requests"
] | stackoverflow_0074179256_file_multithreading_optimal_python_python_requests.txt |
Q:
After refreshing angular application in browser: django response
I´m currently working on an application: Django backend and angular frontend. Everything works fine, but after refreshing one page in the browser I don´t get the angular response anymore. But what I get is a successful answer from my Django server (H... | After refreshing angular application in browser: django response | I´m currently working on an application: Django backend and angular frontend. Everything works fine, but after refreshing one page in the browser I don´t get the angular response anymore. But what I get is a successful answer from my Django server (HTTPResponse: 200).
My Django urls.py is as followed:
from django.urls ... | [
"Angular production build is served as a static file. it makes the api request to the backend server for the CRUD operations.\nwhat you need to do is serve the static files in angular dist(most probably the index.html file in the dist folder) folder.\nusing some sort of routing in django (suggestion have a prefix ... | [
0
] | [] | [] | [
"angular",
"django",
"django_urls",
"python",
"url_routing"
] | stackoverflow_0072726455_angular_django_django_urls_python_url_routing.txt |
Q:
How to apply 1/σ^2 weight matrix to find Weighted Least Squares Solution
I am trying to solve a Weighted Least Squares problem on Python (using numpy) but I am unsure on how to apply the following weight
on
This is what i have done so far
import numpy as np
import matplotlib.pyplot as plt
X = np.random.rand(50)... | How to apply 1/σ^2 weight matrix to find Weighted Least Squares Solution | I am trying to solve a Weighted Least Squares problem on Python (using numpy) but I am unsure on how to apply the following weight
on
This is what i have done so far
import numpy as np
import matplotlib.pyplot as plt
X = np.random.rand(50) #Generate X values
Y = 2 + 3*X + np.random.rand(50) #Y Values
plt.plot(X,Y,'... | [
"You can use a diagonal matrix for W.\nimport numpy as np\n\nsigma = # array of [nx1] sigmas\nW = np.zeros((len(sigma), len(sigma)) # nxn matrix containing zeros\nnp.fill_diagonal(W, sigma)\n\nhttps://numpy.org/doc/stable/reference/generated/numpy.fill_diagonal.html\n"
] | [
0
] | [] | [] | [
"least_squares",
"linear_algebra",
"matrix",
"numpy",
"python"
] | stackoverflow_0074179715_least_squares_linear_algebra_matrix_numpy_python.txt |
Q:
How to create a custom Class - Selenium chromedriver
using pycharm, python 3.10, selenium 4.5 chrome Version 106.0.5249.119 and chromedriver 106.0.5249.61.
If someone could assist me in structuring my class with multiple files please I would be very appreciative! I think I am not passing through the attributes in ... | How to create a custom Class - Selenium chromedriver | using pycharm, python 3.10, selenium 4.5 chrome Version 106.0.5249.119 and chromedriver 106.0.5249.61.
If someone could assist me in structuring my class with multiple files please I would be very appreciative! I think I am not passing through the attributes in the class correctly or importing the packages correctly in... | [
"this action webdriver.Chrome(service=Service('C:\\\\SeleniumDrivers\\\\chromedriver.exe')) creates an object \nso by this line class Scrape(webdriver.Chrome(service=Service('C:\\\\SeleniumDrivers\\\\chromedriver.exe'))) you actually inherit Scrape class not from webdriver.Chrome but from newly created object of th... | [
1
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074179641_python_selenium.txt |
Q:
Function similar to split
Hello guys I'm trying to creat a function that works similarly to split() function but I'm unable to make it count " " as an item and seperate it
here is my code:
def mysplit(argstr, delimitor):
A = ""
B = []
for i in argstr, delimitor:
if i != " ":
A += ... | Function similar to split | Hello guys I'm trying to creat a function that works similarly to split() function but I'm unable to make it count " " as an item and seperate it
here is my code:
def mysplit(argstr, delimitor):
A = ""
B = []
for i in argstr, delimitor:
if i != " ":
A += i
elif A != "":
... | [
"You problem is that your for loop is ill defined.\nWhat are you looping on? You are trying to look at argstr character by character. The delimitor is a constant.\nResult:\ndef mysplit(argstr, delimitor):\n A = \"\"\n B = []\n for i in argstr: \n if i != \" \": \n A += i \n elif A ... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074179731_python.txt |
Q:
How to close connected multiprocessing pipes in Python properly
I have a worker process that is fed with work and sends back the processed results to the parent process.
How can I close those two pipes properly?
What I did so far:
import multiprocessing as mp
def worker(v: str, work_in, result_in):
while True... | How to close connected multiprocessing pipes in Python properly | I have a worker process that is fed with work and sends back the processed results to the parent process.
How can I close those two pipes properly?
What I did so far:
import multiprocessing as mp
def worker(v: str, work_in, result_in):
while True:
number_str = work_in.recv()
print('Processing', num... | [
"When not closing work_in connection, the Process will never finish because it is in an infinite loop (while True). Thus, it will just wait forever for any incoming message.\nWhen you do close work_in, the while True loop will reach EOFError as mentioned in the documentation https://docs.python.org/3/library/multip... | [
1
] | [] | [] | [
"python",
"python_multiprocessing"
] | stackoverflow_0074179607_python_python_multiprocessing.txt |
Q:
Pass None to DRF SerializerField's to_representation
I have the following SerializerField:
class TimestampField(Field):
def to_representation(self, value):
if not value:
return ''
return value.timestamp()
And I use it like this in my serializer:
class ArticlePhotobookSerializer(Mo... | Pass None to DRF SerializerField's to_representation | I have the following SerializerField:
class TimestampField(Field):
def to_representation(self, value):
if not value:
return ''
return value.timestamp()
And I use it like this in my serializer:
class ArticlePhotobookSerializer(ModelSerializer):
delivery_date_from = TimestampField(... | [
"By default serializer's to_representation method skip fields with None value (see source).\nYou can write mixin class to override default to_representation:\nclass ToReprMixin(object): \n def to_representation(self, instance):\n ret = OrderedDict()\n fields = [field for field in self.fields.value... | [
6,
0
] | [] | [] | [
"django",
"django_rest_framework",
"django_serializer",
"python"
] | stackoverflow_0046201067_django_django_rest_framework_django_serializer_python.txt |
Q:
How to get the maximum value of a continuous condition being true?
How the TRUE_MAX column is calculated?
Input:
import pandas as pd
A=[28,30,15,25,24,13,31,19,20,11,19,21]
COND=[False,True,True,True,False,False,True,True,True,False,True,True]
df=pd.DataFrame({'A':A,'COND':COND})
Expected Output
A COND T... | How to get the maximum value of a continuous condition being true? | How the TRUE_MAX column is calculated?
Input:
import pandas as pd
A=[28,30,15,25,24,13,31,19,20,11,19,21]
COND=[False,True,True,True,False,False,True,True,True,False,True,True]
df=pd.DataFrame({'A':A,'COND':COND})
Expected Output
A COND TRUE_MAX
0 28 FALSE
1 30 TRUE 30
2 15 TRUE 30
3 25 T... | [
"You could try as follows:\nimport pandas as pd\nA=[28,30,15,25,24,13,31,19,20,11,19,21]\nCOND=[False,True,True,True,False,False,True,True,True,False,True,True]\ndf=pd.DataFrame({'A':A,'COND':COND})\n\n# splitting your data in groups: 1 through to 6\nsequences = (df.COND != df.COND.shift()).cumsum()\n\n# use only g... | [
2,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0073218007_pandas_python.txt |
Q:
How can I ensure that a pandas date range has even spacing?
I am writing some code to interpolate some data with space (x, y) and time. The data needs to be on a regular grid. I cant seem to make a generalized function to find a date range with regular spacing. The range that fails for me is:
date_min = numpy.date... | How can I ensure that a pandas date range has even spacing? | I am writing some code to interpolate some data with space (x, y) and time. The data needs to be on a regular grid. I cant seem to make a generalized function to find a date range with regular spacing. The range that fails for me is:
date_min = numpy.datetime64('2022-10-24T00:00:00.000000000')
date_max = numpy.datetime... | [
"Your date range doesn't divide evenly by the periods in nanosecond resolution:\n# as the contains start and end, there's a step fewer than there are periods \nsteps = periods - 1\nint(date_max - date_min) / steps\n# 20093023255813.953\n\nA solution could be to round up (or down) your max date, to make it divide ev... | [
1
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074179316_numpy_pandas_python.txt |
Q:
Flask flash message wont show
I have a web application with flask in which I can upload a file to an s3 storage. However, I want the users to track the upload progress of their files. For this, I'm using flash which I want to update frequently with the new upload percentage.
The problem now is that the upload prog... | Flask flash message wont show | I have a web application with flask in which I can upload a file to an s3 storage. However, I want the users to track the upload progress of their files. For this, I'm using flash which I want to update frequently with the new upload percentage.
The problem now is that the upload progress I wrote to the terminal is per... | [
"I seems that you sending html in the flash message you should add safe to jinja\n{% with messages = get_flashed_messages() %}\n {% if messages %}\n {{ messages[0]|safe }}\n {% endif %}\n{% endwith %}\n\nI hope this helps.\n"
] | [
0
] | [] | [] | [
"amazon_s3",
"flash_message",
"flask",
"html",
"python"
] | stackoverflow_0074179368_amazon_s3_flash_message_flask_html_python.txt |
Q:
Using prefect 2.0 flow on dataclass in python
I'm trying to wrap a class with a prefect flow, the flow currently works via class that looks something like this:
class Algorightm:
@task
def do_first(self, something):
....
@task
def do_second(self, something_else):
....
@flow
def s... | Using prefect 2.0 flow on dataclass in python | I'm trying to wrap a class with a prefect flow, the flow currently works via class that looks something like this:
class Algorightm:
@task
def do_first(self, something):
....
@task
def do_second(self, something_else):
....
@flow
def start_flow(self):
do_first(..)
do_second... | [
"A Prefect flow must be a function rather than a class method. Otherwise, you won't be able to create a deployment for it. However, you can call your class within that function and Prefect even supports parameter validation with Pydantic (sharing this pydantic info in case you were using this class to get pydantic-... | [
1
] | [] | [] | [
"prefect",
"python",
"python_3.x"
] | stackoverflow_0074168859_prefect_python_python_3.x.txt |
Q:
How to stop Python script in PowerBI auto-converting columns to float
I have a table with a 19-digit numerical ID column, formatted as text, and another text column, fizz.
id fizz
1003674024206094336 foobarpingpong
When I run a Python script in PowerQuery which manipulates the data in fizz, I've noticed that ... | How to stop Python script in PowerBI auto-converting columns to float | I have a table with a 19-digit numerical ID column, formatted as text, and another text column, fizz.
id fizz
1003674024206094336 foobarpingpong
When I run a Python script in PowerQuery which manipulates the data in fizz, I've noticed that the ID column gets auto-converted to float even when I don't reference that... | [
"The solution to this was that the ID column, despite being formatted as text in the data model, was not formatted as text properly.\nWhen I tried to make it the key column of the table, PowerBI told me that it had nulls, and therefore it couldn't be used.\nI removed the null, and hey presto - the Python script wor... | [
0
] | [] | [] | [
"pandas",
"powerbi",
"python"
] | stackoverflow_0074179248_pandas_powerbi_python.txt |
Q:
numpy diagonal function is slow
I want to implement the connect 4 game in python as a hobby project, and I have no idea, why the search for matches on the diagonals is so slow.
When analyzing my code with psstats, I found that this is the bottleneck.
I want to build a computer enemy which analyzes thousands of fut... | numpy diagonal function is slow | I want to implement the connect 4 game in python as a hobby project, and I have no idea, why the search for matches on the diagonals is so slow.
When analyzing my code with psstats, I found that this is the bottleneck.
I want to build a computer enemy which analyzes thousands of future steps in the game, therefore perf... | [
"As stated in comment by Andrey, the code is calling a lot of np functions that require additional memory allocations. I believe that is the bottleneck.\nI would suggest precomputing indices of all diagonals, since they won't change much in your case (matrix shape remains the same, the sequence may change I guess).... | [
2
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074178272_numpy_python.txt |
Q:
how to show liste filtre admin django ManyToOne
how to show liste filtre admin django ManyToOne in this case :
in models.py -----------
class Personne(models.Model):
name= models.CharField(max_length=50,blank=False)
def __str__(self):
return self.name
class Project(models.Model):
title= models.CharField(ma... | how to show liste filtre admin django ManyToOne | how to show liste filtre admin django ManyToOne in this case :
in models.py -----------
class Personne(models.Model):
name= models.CharField(max_length=50,blank=False)
def __str__(self):
return self.name
class Project(models.Model):
title= models.CharField(max_length=50,blank=False)
note= models.CharField(max_l... | [
"You have to add the ForeignKey fields to list_filter\nclass ExampleAdmin(admin.ModelAdmin):\n ...\n list_filter = ['projecttasktask', 'personnetask']\n\n"
] | [
0
] | [] | [] | [
"django",
"many_to_one",
"python"
] | stackoverflow_0074179274_django_many_to_one_python.txt |
Q:
SQLServer: query runs on console but not on SQLAlchemy
I'm trying to run a very expensive SQL Server query via Python + SQLAlchemy. It runs just fine on sql server console but it errors out when called via sqlalchemy.
Test run looks like this:
Run query on SQL Server console.
Wait about 15 minutes for it to finis... | SQLServer: query runs on console but not on SQLAlchemy | I'm trying to run a very expensive SQL Server query via Python + SQLAlchemy. It runs just fine on sql server console but it errors out when called via sqlalchemy.
Test run looks like this:
Run query on SQL Server console.
Wait about 15 minutes for it to finish.
Query runs just fine and returns ~50,000 rows.
When runn... | [
"Yep adding \"SET NOCOUNT ON;\" as per Gord Thompson's comment, to the front of my query solved it for me. I got the same error running a stored procedure containing multiple queries. So this will do the trick:\ndata = pd.read_sql(\"SET NOCOUNT ON; Your SQL Query.....\n\nThis answer https://stackoverflow.com/a/5559... | [
2
] | [] | [] | [
"python",
"sql_server",
"sqlalchemy"
] | stackoverflow_0067337467_python_sql_server_sqlalchemy.txt |
Q:
ffmpeg.probe not working when run from python on windows 10
I am relatively new to python, I am working on extracting some metadata from a video and I am trying to use ffmpeg.probe (or ffprobe) because it provides all the data I need.
After many errors I went to the basic and tried:
import ffmpeg
import json
movi... | ffmpeg.probe not working when run from python on windows 10 | I am relatively new to python, I am working on extracting some metadata from a video and I am trying to use ffmpeg.probe (or ffprobe) because it provides all the data I need.
After many errors I went to the basic and tried:
import ffmpeg
import json
movie_path="E:\Archive\Peliculas\Clasicos\Casablanca.avi"
probe = ffm... | [
"try to use r mark, like this:\nmovie_path=r\"E:\\Archive\\Peliculas\\Clasicos\\Casablanca.avi\"\nThis marker is a 'raw string literal', which are exactly the string literals marked by an 'r', before the opening quote and resolves this issues with \\ backslash.\n",
"Turns out that when I came in the next day it w... | [
2,
0,
0,
0
] | [] | [] | [
"ffmpeg",
"ffprobe",
"python"
] | stackoverflow_0070309467_ffmpeg_ffprobe_python.txt |
Q:
How to convert list of dictionary to dict using the list of dict values
I dont know how to start with this and would love to any help.
i have this list of dict:
mylist_of_dict =
[{"plat": "Linux",
"os_name": "Android",
}, {
"plat": "Linux",
"os_name": "Chrome OS",
}, {
"plat": "Win32",
"os_name": "Windo... | How to convert list of dictionary to dict using the list of dict values | I dont know how to start with this and would love to any help.
i have this list of dict:
mylist_of_dict =
[{"plat": "Linux",
"os_name": "Android",
}, {
"plat": "Linux",
"os_name": "Chrome OS",
}, {
"plat": "Win32",
"os_name": "Windows",
}]
My main goal is to transform it into this dict where the plat key va... | [
"Try:\nout = {}\nfor d in mylist_of_dict:\n out.setdefault(d[\"plat\"], []).append(d[\"os_name\"])\n\nprint(out)\n\nPrints:\n{\"Linux\": [\"Android\", \"Chrome OS\"], \"Win32\": [\"Windows\"]}\n\n"
] | [
2
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074180023_dictionary_list_python.txt |
Q:
The correct way to default None in Python 3.10 type hinting
My understanding is that in Python >= 3.10, I can use | for default None (e.g., this question).
def abc(str | None) -> str:
pass
I have the following example:
import pandas as pd
from typing import Iterable
def winsorise_df(df: pd.DataFrame, level: ... | The correct way to default None in Python 3.10 type hinting | My understanding is that in Python >= 3.10, I can use | for default None (e.g., this question).
def abc(str | None) -> str:
pass
I have the following example:
import pandas as pd
from typing import Iterable
def winsorise_df(df: pd.DataFrame, level: float = 0.01, exc: Iterable[str] | None) -> pd.DataFrame:
pas... | [
"\nI would have thought because Iterable[str] | None is interpreted as Optional[Iterable[str]], it's implicit that default value is None.\n\nYou think wrong. It's not. You need to specify the default value.\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x",
"type_hinting"
] | stackoverflow_0074179690_python_python_3.x_type_hinting.txt |
Q:
Lightning LND Rest API in Django API Handling POST requests when encoding/decoding, getting Incorrect Padding
I am trying to make a Django API for handling lightning payments, and I need to implement some functionalities such as unlocking wallet, changing password etc. I am getting "Incorrect padding" and I don't ... | Lightning LND Rest API in Django API Handling POST requests when encoding/decoding, getting Incorrect Padding | I am trying to make a Django API for handling lightning payments, and I need to implement some functionalities such as unlocking wallet, changing password etc. I am getting "Incorrect padding" and I don't know how to fix it. This is my view.py:
from rest_framework.views import APIView
from rest_framework.response impor... | [
"The solution is to change the way we encoded/decoding by:\n...\n\ndata = {\n \"wallet_password\": base64.b64encode(\n bytes(request.data[\"wallet_password\"], \"UTF-8\")\n ).decode(),\n\n...\n\n"
] | [
0
] | [] | [] | [
"api",
"django",
"lightning",
"post",
"python"
] | stackoverflow_0074178655_api_django_lightning_post_python.txt |
Q:
how to bind button in tkinter
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title("Tic Tac Toe")
root.geometry("505x500")
root.resizable(0,0)
Blank = tk.PhotoImage(file='Blank.png')
X = tk.PhotoImage(file='X.png')
O = tk.PhotoImage(file='O.png')
def configB(event):
print('hello')
btn1 = ... | how to bind button in tkinter | import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title("Tic Tac Toe")
root.geometry("505x500")
root.resizable(0,0)
Blank = tk.PhotoImage(file='Blank.png')
X = tk.PhotoImage(file='X.png')
O = tk.PhotoImage(file='O.png')
def configB(event):
print('hello')
btn1 = tk.Button(root,image=Blank)
btn1.pl... | [
"As @jasonharper said it will work only if button is focused\nbtn1.focus()\nbtn1.bind('<Return>', configB)\n\nand if you click other button then it will not work again\nso better bind to main winodw\nroot.bind('<Return>', configB)\n\n\nMinimal working code\nimport tkinter as tk\n\n# --- functions --- # PEP8: lower... | [
2,
0,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0067972436_python_tkinter.txt |
Q:
Split a large xml file into multiple based on tag in Python
I have a very large xml file which I need to split into several based on a particular tag.
The XML file is something like this:
<xml>
<file id="13">
<head>
<talkid>2458</talkid>
<transcription>
<seekvideo id="645">So in college,</seekvideo... | Split a large xml file into multiple based on tag in Python | I have a very large xml file which I need to split into several based on a particular tag.
The XML file is something like this:
<xml>
<file id="13">
<head>
<talkid>2458</talkid>
<transcription>
<seekvideo id="645">So in college,</seekvideo>
...
</transcription>
</head>
<content> *** This i... | [
"You can use Beautiful Soup to parse xml.\nIt would like this(i added a second talk id to the xml to demonstrate finding multiple tags)\nxml_file = '''<xml>\n<file id=\"13\">\n <head>\n <talkid>2458</talkid>\n <transcription>\n <seekvideo id=\"645\">So in college,</seekvideo>\n ...\n </transcrip... | [
1,
1,
1
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0074179827_python_xml.txt |
Q:
ImportError: cannot import name 'ParseMode' from 'telegram'
I am trying to create a telegram bot. The code i am trying to execute is :
from telegram import ParseMode
But it is throwing up this error:
ImportError: cannot import name 'ParseMode' from 'telegram'
(C:\ProgramData\Anaconda3\lib\site-packages\telegram\_... | ImportError: cannot import name 'ParseMode' from 'telegram' | I am trying to create a telegram bot. The code i am trying to execute is :
from telegram import ParseMode
But it is throwing up this error:
ImportError: cannot import name 'ParseMode' from 'telegram'
(C:\ProgramData\Anaconda3\lib\site-packages\telegram\__init__.py)
Could you please advise how to fix this error?
| [
"as per Version 20 you need to use:\nfrom telegram.constants import ParseMode\n\n",
"you have to import with this way:\nfrom telegram.ext import ParseMode\n\n\nif problem not solved:\ninstall the package like this:\n\npip install python_telegram_bot\n\nor\n\npip install \"python_telegram_bot==12.4.2\"\n\n"
] | [
1,
0
] | [] | [] | [
"python",
"python_3.x",
"python_telegram_bot",
"telegram",
"telegram_bot"
] | stackoverflow_0069155789_python_python_3.x_python_telegram_bot_telegram_telegram_bot.txt |
Q:
Check if dictionary items occurs "similarly"
I am trying to implement a function which checks whether a counter contains "similar" percentage of each items. That is
from collections import Counter
c = Counter(["Dog", "Cat", "Dog", "Horse", "Dog"])
size = 5
lst = list(c.values())
percentages = [x / size * 100 for ... | Check if dictionary items occurs "similarly" | I am trying to implement a function which checks whether a counter contains "similar" percentage of each items. That is
from collections import Counter
c = Counter(["Dog", "Cat", "Dog", "Horse", "Dog"])
size = 5
lst = list(c.values())
percentages = [x / size * 100 for x in lst] # [60.0, 20.0, 20.0]
How can I check w... | [
"One way is to pick the minimum and maximum value of the percentages list and pass those to isclose()\nfrom math import isclose\nfrom collections import Counter\n\n\ndef is_balanced(lst, abs_tol):\n c = Counter(lst)\n total = c.total()\n percentages = [(v / total) * 100 for v in c.values()]\n return isc... | [
1,
0
] | [] | [] | [
"counter",
"dictionary",
"list",
"python"
] | stackoverflow_0074179903_counter_dictionary_list_python.txt |
Q:
Python format_map method, how to deal with both for string and numbers missing cases?
In order to use the format_map method, I create a new dict class:
class MyDict(dict):
def __missing__(self, key):
return '{' + key + '}'
I have one dict variable d:
d = MyDict({"k2":2,"k3":3})
Then in the logic, I c... | Python format_map method, how to deal with both for string and numbers missing cases? | In order to use the format_map method, I create a new dict class:
class MyDict(dict):
def __missing__(self, key):
return '{' + key + '}'
I have one dict variable d:
d = MyDict({"k2":2,"k3":3})
Then in the logic, I could use it like this:
# Case 1: the below format_map line will not raise errors
# and s st... | [
"I'm not sure that I fully understand what you are trying to do. But I will assume i is a variable previously defined and you want the value to replace a missing dictionary key. Then you could use:\ni = 5\ns = f'xx{i:02d}yy'.format_map(d)\n\ngiving output\nxx05yy\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074172348_python.txt |
Q:
Getting selenium python to run previous line of code after catching an exception
I am trying to scrape this Website. It has two dropdown lists that I need to navigate as shown in the image below:
I solved an issue where I get a StaleElementReferenceException on each of the dropdowns since I need to execute a clic... | Getting selenium python to run previous line of code after catching an exception | I am trying to scrape this Website. It has two dropdown lists that I need to navigate as shown in the image below:
I solved an issue where I get a StaleElementReferenceException on each of the dropdowns since I need to execute a click before the elements come into view. However, after catching the exception, I need th... | [
"driver.get('https://www.compareandrecycle.co.uk/mobile-phones/apple-iphone-11')\n\nwait.until(EC.element_to_be_clickable((By.XPATH, \"//span[contains(@class,'cookie_accept')]\"))).click()\nj=0\nwhile True:\n try:\n wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, \"div.network-options > div > div ... | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074175802_python_selenium_selenium_webdriver.txt |
Q:
Resource Not Found Error: When Reading CSV from Azure Blob using Pandas with its SAS URL
I am trying to perform Dataset versioning where I read a CSV file into a pandas DataFrame and then create a new version of an Azure ML Dataset. I am running the below code in an Azure CLI job within Azure DevOps.
df = pd.read_... | Resource Not Found Error: When Reading CSV from Azure Blob using Pandas with its SAS URL | I am trying to perform Dataset versioning where I read a CSV file into a pandas DataFrame and then create a new version of an Azure ML Dataset. I am running the below code in an Azure CLI job within Azure DevOps.
df = pd.read_csv(blob_sas_url)
At this line, I get a 404 Error.
Error Message:
urllib.error.HTTPError: HTT... | [
"The reason of shortening or technically trimming your input argument is that the bash variable is split at the & level. so all the rest of your sas url goes as \"commands\" or other \"arguments\". Apparently that is how azure parses it.\neg:\npython3 test_input.py --blob_sas_url \"somepath/to/storage/account/file.... | [
1
] | [] | [] | [
"azure",
"azure_devops",
"azure_machine_learning_service",
"pandas",
"python"
] | stackoverflow_0074179120_azure_azure_devops_azure_machine_learning_service_pandas_python.txt |
Q:
Select method and run directly the according post method
I'm using FastAPI for Machine Leaning model deployment, I have two cases of models and each one has its own request post method, I want to make a menu of choice and run the selected method according to the clicked choice, the process should run as follow:
Se... | Select method and run directly the according post method | I'm using FastAPI for Machine Leaning model deployment, I have two cases of models and each one has its own request post method, I want to make a menu of choice and run the selected method according to the clicked choice, the process should run as follow:
Select choice of method:
method_1
or
method_2
=>
if method_1: ... | [
"If you need to create this menu using the same server that is hosting your choices, then you can create a new endpoint that returns an HTML response, in which contains two buttons for example each button has an OnClick action of hitting your other endpoints (Choices).\n"
] | [
2
] | [] | [] | [
"api",
"fastapi",
"post",
"python",
"request"
] | stackoverflow_0074180230_api_fastapi_post_python_request.txt |
Q:
xarray: Force the writing of string attribute as NC_CHAR (because of netcdf-fortran incompatibility with NC_STRING)
When I have a string attribute in my xarray.Dataset with special characters like ° or German Umlauts (Ä, Ü, etc) it will get written to file with to_netcdf() as type NC_STRING. Other string attribute... | xarray: Force the writing of string attribute as NC_CHAR (because of netcdf-fortran incompatibility with NC_STRING) | When I have a string attribute in my xarray.Dataset with special characters like ° or German Umlauts (Ä, Ü, etc) it will get written to file with to_netcdf() as type NC_STRING. Other string attributes not containing any special characters will be saved as NC_CHAR.
This leads to problems when I subsequently want to open... | [
"This is an explanation and workaround, that was suggested at the GitHub issue:\n\nThe reason for this behavior is that the netcdf4 python package\nautomatically determines the type of the attribute (NC_CHAR or\nNC_STRING) by attempting the conversion to ASCII:\nUnidata/netcdf4-python#529 However, if the value is a... | [
0
] | [] | [] | [
"netcdf",
"netcdf4",
"python",
"python_xarray"
] | stackoverflow_0074150414_netcdf_netcdf4_python_python_xarray.txt |
Q:
How to share the same object in more than two functions? (Python)
I am working on a project called "Flash card". Does anyone know how to share the same object between more than two functions? It seems setting the variable as global is not the answer. May I know why it isn't? In my case, I want the same "dict2" to ... | How to share the same object in more than two functions? (Python) | I am working on a project called "Flash card". Does anyone know how to share the same object between more than two functions? It seems setting the variable as global is not the answer. May I know why it isn't? In my case, I want the same "dict2" to be used in Known(), Switch_Word() and Reset(), as it will be refilled t... | [
"use a lambda function, e.g.:\ncross_btn = Button(window, image=cross_image, command=lambda:Switch_Word(dict_2))\nThis just needs to be replicated for all applicable buttons. The lambda allows for you to pass arguments to the command, rather than just the function. You will of course have to modify your functions t... | [
2,
2
] | [] | [] | [
"copy",
"object",
"oop",
"python",
"tkinter"
] | stackoverflow_0074180283_copy_object_oop_python_tkinter.txt |
Q:
Collision detection with octrees realized with python-fcl
I want to finish the collision detection with point cloud represented by Octrees. With the python-fcl lib, I tried the following code snippet by myself
x = np.random.random([5, 3])
y = np.random.random([5, 3])
object1 = fcl.OcTree(0.1).insertPointCloud(poi... | Collision detection with octrees realized with python-fcl | I want to finish the collision detection with point cloud represented by Octrees. With the python-fcl lib, I tried the following code snippet by myself
x = np.random.random([5, 3])
y = np.random.random([5, 3])
object1 = fcl.OcTree(0.1).insertPointCloud(points=x)
object2 = fcl.OcTree(0.1).insertPointCloud(points=y)
t1... | [
"nah bro its something to do with your machine. try using replit.com for running your code or use jupyter notebooks. appreciate your code\n"
] | [
1
] | [] | [] | [
"collision_detection",
"octree",
"point_cloud_library",
"python",
"ubuntu_20.04"
] | stackoverflow_0074180290_collision_detection_octree_point_cloud_library_python_ubuntu_20.04.txt |
Q:
python: exception inside try doesn't jump to except
I am trying to search within the EU parliment votes' description.
They are standard xml files. So far I noticed 2 versions of the votes' result: where the description is text and where it is an url.
Fails at this file: https://www.europarl.europa.eu/doceo/documen... | python: exception inside try doesn't jump to except | I am trying to search within the EU parliment votes' description.
They are standard xml files. So far I noticed 2 versions of the votes' result: where the description is text and where it is an url.
Fails at this file: https://www.europarl.europa.eu/doceo/document/PV-9-2022-09-12-RCV_FR.xml
Works fine on the following ... | [
"This would happen if there is a new exception raised within your catch block, I would presume specifically the votes object at some point of you accessing it, raises this exception.\nTry printing out votes and then each time you access it by indexing print it out you'll see to which extent you can continue accessi... | [
1
] | [] | [] | [
"elementtree",
"python",
"xml_parsing"
] | stackoverflow_0074180195_elementtree_python_xml_parsing.txt |
Q:
Import a subpackage with an unknown number of modules
I'm building a package that is a wrapper for an API. I want this wrapper to be as accomodating as possible towards future versions of this API. For these reason, I have a generic wrapper.py that defines a generic wrapper class and has the user choose the versio... | Import a subpackage with an unknown number of modules | I'm building a package that is a wrapper for an API. I want this wrapper to be as accomodating as possible towards future versions of this API. For these reason, I have a generic wrapper.py that defines a generic wrapper class and has the user choose the version of the API that they want to use.
The API methods are def... | [
"The contents of an imported package are, essentially, the global variables of its __init__.py. (There's also __all__, if you'd like to include only some of these globals, but the key point remains). I assume your version/__init__.py is empty, so when you import versions, it has no members. The simple solution woul... | [
0
] | [] | [] | [
"import",
"python"
] | stackoverflow_0061925073_import_python.txt |
Q:
How to send data from the front-end to the back-end using ajax and Dango?
INTRO: I am writing a Django application which needs to send some data from the front-end to a views.py file in the back-end. To do so, I have a button which performs a transaction when clicked. This is what it looks like:
<button id="submit... | How to send data from the front-end to the back-end using ajax and Dango? | INTRO: I am writing a Django application which needs to send some data from the front-end to a views.py file in the back-end. To do so, I have a button which performs a transaction when clicked. This is what it looks like:
<button id="submit_transaction" type="button" class="btn btn-outline-info" onclick="transaction()... | [
"You need to provide an url\n\n\n<script>\n \n body = {\n 'csrfmiddlewaretoken': crsfToken,\n 'public_key': ...\n }\n\n async function transaction(){\n // Perform some task\n\n // Submit transaction\n $.ajax({\n url: 'https://mysite',\n type: 'POST',\n d... | [
1
] | [] | [] | [
"ajax",
"django",
"javascript",
"jquery",
"python"
] | stackoverflow_0074179980_ajax_django_javascript_jquery_python.txt |
Q:
try to use GDAL to mege geotiff
I have several consecutive geotiffs that I want to merge .I use GDAL to try out but the final geotiff has no color, only black and white. I want to ask if there is a python plug-in that can directly synthesize multiple Geotiffs.
Or how to use GDAL to synthesize multiple Geotiffs
A:... | try to use GDAL to mege geotiff | I have several consecutive geotiffs that I want to merge .I use GDAL to try out but the final geotiff has no color, only black and white. I want to ask if there is a python plug-in that can directly synthesize multiple Geotiffs.
Or how to use GDAL to synthesize multiple Geotiffs
| [
"You can build a VRT and check in QGIS if looks like expected. If the VRT is fine then you can translate the VRT into TIFF file.\ngdalbuildvrt _merged.vrt *.tif\ngdal_translate -of GTiff -co COMPRESS=LZW -co BIGTIFF=YES -co TILED=YES _merged.vrt _merged.tif\n\n"
] | [
0
] | [] | [] | [
"gdal",
"geotiff",
"python",
"tiff"
] | stackoverflow_0074022363_gdal_geotiff_python_tiff.txt |
Q:
Adding autofill/autocomplete suggestion to text input in python
I have tried several ways to add autocomplete/autofill suggestion functionality on text input. I have set a list 'names' for which I want autofill suggestions when being searched.
I tried this code which I got from pypi.org (https://pypi.org/project/f... | Adding autofill/autocomplete suggestion to text input in python | I have tried several ways to add autocomplete/autofill suggestion functionality on text input. I have set a list 'names' for which I want autofill suggestions when being searched.
I tried this code which I got from pypi.org (https://pypi.org/project/fast-autocomplete/). It has library named fast-autocomplete. I tried u... | [
"input() sends text to search() only when you click Enter and I don't know if you can change it\nBut using widget.Text I could assign function which is executed always when there is new text in widget. To display result I use widget.Label but you could try to use Combobox\nDoc: Widget List — Jupyter Widgets 8.0.2 d... | [
1
] | [] | [] | [
"autocomplete",
"list",
"python",
"python_3.x",
"textfield"
] | stackoverflow_0074179209_autocomplete_list_python_python_3.x_textfield.txt |
Q:
Python Django Form "This field is required"
i made a form in django with one field required (imagefield) but when I fill it by selecting an image, once I fill it it considers that the form is not valid and asks to fill it again I don't understand why, here is my code below:
view.py:
def success(request):
retur... | Python Django Form "This field is required" | i made a form in django with one field required (imagefield) but when I fill it by selecting an image, once I fill it it considers that the form is not valid and asks to fill it again I don't understand why, here is my code below:
view.py:
def success(request):
return HttpResponse('successfully uploaded')
def con... | [
"I think your error is on the parameters of form init. The first paramters is for POST data, not FILES:\nform = ContactUsForm(request.POST, request.FILES)\n\nAnd after, you have to call form.save(), probably better than make the update yourself...\n",
"in views.py\nif request.method == 'POST':\n form = Con... | [
1,
1
] | [] | [] | [
"django",
"django_forms",
"field",
"forms",
"python"
] | stackoverflow_0074180125_django_django_forms_field_forms_python.txt |
Q:
Beautiful Soup-Regex-How to extract particular part from href in tag
Hey so I am using Beautiful soup to make a scrapper which aims to extract the id of an app searched on playstore. The code:
def linkgen(name):
base = "https://play.google.com/store/search?q="
req = requests.get(base + name)
soup = Bea... | Beautiful Soup-Regex-How to extract particular part from href in tag | Hey so I am using Beautiful soup to make a scrapper which aims to extract the id of an app searched on playstore. The code:
def linkgen(name):
base = "https://play.google.com/store/search?q="
req = requests.get(base + name)
soup = BeautifulSoup(req.content, "html.parser")
soup2=soup.find( class_ = "Si6A... | [
"To get only href tag content you can try using this regex sample in your python code:\nr\"(?<=id=)(.*?)(\\\")\"\n\nThen remove the last char at the end of the string.\nIf you want to try the regex just go here :)\nHopes this will help you! Have a nice day.\n"
] | [
2
] | [] | [] | [
"beautifulsoup",
"extract",
"href",
"html",
"python"
] | stackoverflow_0074180093_beautifulsoup_extract_href_html_python.txt |
Q:
Why Tesseract psm config is giving error when run through python subprocess
I am trying to run tesseract through python subprocess using the following code:
import subprocess
extract = subprocess.run(['tesseract', 'imCropped.png', 'stdout', '-l', 'eng', '--psm 6'], capture_output=True, text=True)
print(extract.s... | Why Tesseract psm config is giving error when run through python subprocess | I am trying to run tesseract through python subprocess using the following code:
import subprocess
extract = subprocess.run(['tesseract', 'imCropped.png', 'stdout', '-l', 'eng', '--psm 6'], capture_output=True, text=True)
print(extract.stdout, extract.stderror)
But, it throws the following error and doesn't run:
Err... | [
"Split\n\n'--psm 6'\n\nto two string.\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x",
"subprocess",
"tesseract"
] | stackoverflow_0063988037_python_python_3.x_subprocess_tesseract.txt |
Q:
Converting Maple to Sage
I have some Maple code below that I'm trying to convert to Sage (which is some kind of Python) code.
This is the Maple code
restart:
m:=15:
a:=array(1..m):
eqn:=array(1..m):
expr:=sum(a['i']*u^('i'-1),'i'=1..m)-
product((1-u^'i')^(-a['i']),'i'=1..m):
for i from 1 to m do eqn[... | Converting Maple to Sage | I have some Maple code below that I'm trying to convert to Sage (which is some kind of Python) code.
This is the Maple code
restart:
m:=15:
a:=array(1..m):
eqn:=array(1..m):
expr:=sum(a['i']*u^('i'-1),'i'=1..m)-
product((1-u^'i')^(-a['i']),'i'=1..m):
for i from 1 to m do eqn[i]:=coeff(series(expr,u=0,m+2)... | [
"To give an answer, one has to understand first what happens behind the maple code, the solve the problem more or less in an optimal manner in sage. Here is what can be done in sage, to look as close as possible to the maple way.\nm = 15\nr = [1..m] # range to be used in the sequel\n\nu = var('u');\na = dict(zip... | [
2,
0
] | [] | [] | [
"maple",
"python",
"sage"
] | stackoverflow_0074178248_maple_python_sage.txt |
Q:
How to map categorical columns from two dataframes?
I have two dataframes and in the column 'column_to_compare value from df1' I have "sub-categorical" data which I want to match to the "names" to its "categories".
I listed the matching categories below in the matching_cat variable. I don't know if it is the right... | How to map categorical columns from two dataframes? | I have two dataframes and in the column 'column_to_compare value from df1' I have "sub-categorical" data which I want to match to the "names" to its "categories".
I listed the matching categories below in the matching_cat variable. I don't know if it is the right way to associate my variable to a category.
I want to cr... | [
"Ok using your example, here is what I came up with:\nimport pandas as pd\n\ndata1 = {'key_col': ['12563','12564','12565','12566'],\n 'categories': ['bird', 'dog', 'insect','insect'],'column3': ['some','other','data','there']\n}\ndf1 = pd.DataFrame(data1)\n\ndata2 = { 'key_col': ['12563','12564','12565','12566',... | [
1
] | [] | [] | [
"comparison",
"dataframe",
"mapping",
"python"
] | stackoverflow_0074179463_comparison_dataframe_mapping_python.txt |
Q:
Django form throwing errors on display
I have created a POST Django form with several input fields. Many of them are required and they throw the error that they are required on the website render. Also they throw the error above them, even though I specified they threw it in the block underneath. Please help.
FORM... | Django form throwing errors on display | I have created a POST Django form with several input fields. Many of them are required and they throw the error that they are required on the website render. Also they throw the error above them, even though I specified they threw it in the block underneath. Please help.
FORM DEFINITION
class Install_Version_Form(forms... | [
"When you first create a form instance you don't have to give request.POST.\nIf you do, it will handle things as if it was filled by your user even if it wasn't.\ndef installation(request):\n ctx = {\n \"installVersionForm\": None\n }\n ctx[\"installVersionForm\"] = Install_Version_Form() <=====\n ... | [
2
] | [] | [] | [
"django",
"forms",
"python"
] | stackoverflow_0074179783_django_forms_python.txt |
Q:
How to select the dictionary that minimizes a key along a set of dictionaries in python
I have two(n) Python dictionaries dict_1 = {"obj_value": 1, "other_key": 10} and dict_2 = {"obj_value": 0, "other_key": 10} and I need a rutine that returns the dictionary that minimizes the obj_value key, in this case, dict_2
... | How to select the dictionary that minimizes a key along a set of dictionaries in python | I have two(n) Python dictionaries dict_1 = {"obj_value": 1, "other_key": 10} and dict_2 = {"obj_value": 0, "other_key": 10} and I need a rutine that returns the dictionary that minimizes the obj_value key, in this case, dict_2
Any ideas about this problem without using conditionals (if)? I would want to extend this to ... | [
"You can use min\nmin(dict1, dict2,.., key=lambda x : x.get(\"obj_value\"))\n\nAlso if there are list of dictionaries then\nl_o_d = [{dict}]\nThen\nYou can use\nmin(*l_o_d, key=lambda x : x.get(\"obj_value\"))\n\n",
"For the case of two dictionaries as you have it, a conditional is good enough:\nchosen_dict = dic... | [
2,
1
] | [] | [] | [
"dictionary",
"key",
"minimize",
"python"
] | stackoverflow_0074180368_dictionary_key_minimize_python.txt |
Q:
Print 'std err' value from statsmodels OLS results
(Sorry to ask but http://statsmodels.sourceforge.net/ is currently down and I can't access the docs)
I'm doing a linear regression using statsmodels, basically:
import statsmodels.api as sm
model = sm.OLS(y,x)
results = model.fit()
I know that I can print out the... | Print 'std err' value from statsmodels OLS results | (Sorry to ask but http://statsmodels.sourceforge.net/ is currently down and I can't access the docs)
I'm doing a linear regression using statsmodels, basically:
import statsmodels.api as sm
model = sm.OLS(y,x)
results = model.fit()
I know that I can print out the full set of results with:
print results.summary()
whic... | [
"Applying the answer given here I used dir() to print all the attributes of the results object.\nAfter that I searched for the one that contained the std err value and it turned out to be:\nprint results.bse\n\n(Not sure what the b stands for in bse, but I guess the se stands for \"standard error\")\n",
"results.... | [
76,
7,
0,
0,
0
] | [] | [] | [
"io",
"python",
"statsmodels"
] | stackoverflow_0031523921_io_python_statsmodels.txt |
Q:
Breakpoint-induced interactive debugging of Python with IPython
Say I have an IPython session, from which I call some script:
> run my_script.py
Is there a way to induce a breakpoint in my_script.py from which I can inspect my workspace from IPython?
I remember reading that in previous versions of IPython one cou... | Breakpoint-induced interactive debugging of Python with IPython | Say I have an IPython session, from which I call some script:
> run my_script.py
Is there a way to induce a breakpoint in my_script.py from which I can inspect my workspace from IPython?
I remember reading that in previous versions of IPython one could do:
from IPython.Debugger import Tracer;
def my_function():
... | [
"The Tracer() still exists in ipython in a different module. You can do the following:\nfrom IPython.core.debugger import Tracer\n\ndef my_function():\n x = 5\n Tracer()()\n print 5\n\nNote the additional call parentheses around Tracer\nedit: For IPython 6 onwards Tracer is deprecated so you should use set... | [
35,
21,
13,
9,
5,
5,
0
] | [] | [] | [
"breakpoints",
"debugging",
"ipdb",
"ipython",
"python"
] | stackoverflow_0014635299_breakpoints_debugging_ipdb_ipython_python.txt |
Q:
How to assign a string value to each element in a list when the function iterates through the list of elements
I am a beginner, hence i want to know how to assign either a 'PASS' or a 'FAIL' value to each element in the list. The function I have below just pings the echo servers.
for example if 10.10.10.5 is reach... | How to assign a string value to each element in a list when the function iterates through the list of elements | I am a beginner, hence i want to know how to assign either a 'PASS' or a 'FAIL' value to each element in the list. The function I have below just pings the echo servers.
for example if 10.10.10.5 is reachable then for example: 10.10.10.5 should be 'PASS'and 'FAIL' when it is not reachable, if 192.168.11.10 is not reach... | [
"There are two ways out of this problem. The best one of them is use a dictionary. Why I'm saying this to be best us you can access the connection results using the ip addresses. Example-\nconn_results = {\"ip1\":\"pass\", \"ip2\":\"fail}\nTo print the results of ip1 it's quite easy\nprint(conn_results[\"ip1\"])\nE... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074180293_python_python_3.x.txt |
Q:
Sorted array from two lists
I am trying to solve the following question and can't seem to find what the problem with my code is:
You are given an array of strings names, and an array heights that consists of distinct positive integers. Both arrays are of length n.
For each index i, names[i] and heights[i] denote t... | Sorted array from two lists | I am trying to solve the following question and can't seem to find what the problem with my code is:
You are given an array of strings names, and an array heights that consists of distinct positive integers. Both arrays are of length n.
For each index i, names[i] and heights[i] denote the name and height of the ith per... | [
"how about this?\n>>> names=['a', 'b', 'c']\n>>> heights=[10, 5, 7]\n>>> [name for _, name in sorted(zip(heights,names), reverse=True)]\n['a', 'c', 'b']\n>>> \n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074180332_python.txt |
Q:
Latency under low traffic in Google PubSub
I have noticed that under high load pubsub gives great throughput with pretty low latency. But if I want to send a single message, the latency can often be several seconds. I have used the publish_time in the incoming message to see how long the message spent in the queue... | Latency under low traffic in Google PubSub | I have noticed that under high load pubsub gives great throughput with pretty low latency. But if I want to send a single message, the latency can often be several seconds. I have used the publish_time in the incoming message to see how long the message spent in the queue and it is usually pretty low. Can't tell if, un... | [
"There can be several factors that impact latency of low-throughput Pub/Sub streams. First of all, the publish-side client library does wait a period of time to try to batch messages by default. You can get a little bit of improvement by setting the max_messages property of the pubsub_v1.types.BatchSettings to 1, w... | [
0
] | [] | [] | [
"google_cloud_pubsub",
"publish_subscribe",
"python"
] | stackoverflow_0074146304_google_cloud_pubsub_publish_subscribe_python.txt |
Q:
locate an a element and click on it in selenium pyhton
I have this page and I want to click on the a element that sends an email(the one that is highlighted in the screenshot below
and I have tried to find this element using By.XPATH
email = driver.find_element(By.XPATH, "//a[contains(@class, 'email-old-32')]").c... | locate an a element and click on it in selenium pyhton | I have this page and I want to click on the a element that sends an email(the one that is highlighted in the screenshot below
and I have tried to find this element using By.XPATH
email = driver.find_element(By.XPATH, "//a[contains(@class, 'email-old-32')]").click()
and By.CLASS_NAME
email = driver.find_element(By.CLAS... | [
"There are several possible thing that may cause this:\n\nYou need to wait for element to be loaded and to become clickable. WebDriverWait expected_conditions can be used for that.\nIf this is your case instead of email = driver.find_element(By.XPATH, \"//a[contains(@class, 'email-old-32')]\").click() try this:\n\n... | [
2
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074180393_python_selenium_selenium_webdriver.txt |
Q:
editing the table in pandas PYTHON
I need copy the value "a" lower and next I would like that the value of "b" will be also copied lower so many times until it encounters another value etc until the end of column 1
I tried to iterate through the rows and add conditions, unfortunately I wasn't get the result as I w... | editing the table in pandas PYTHON | I need copy the value "a" lower and next I would like that the value of "b" will be also copied lower so many times until it encounters another value etc until the end of column 1
I tried to iterate through the rows and add conditions, unfortunately I wasn't get the result as I want.
My dataframe looks like:
col1
c... | [
"Use pandas.fillna with method=ffill:\nWhen used on a column, this replaces the NaN values in a given row with non-NAN values preceding the row.\nimport pandas as pd \n\ndata = pd.DataFrame({\"col1\": [1, None, 2, None, None, 3, None, 4, 5, None, None]})\n\ndata[\"col1\"] = data[\"col1\"].fillna(method=\"ffill\")\n... | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074180561_dataframe_pandas_python.txt |
Q:
Python code "freezes" after calling pyautogui
I want to automate some clicks on Windows. I use pyautogui for that.
But when my code meets pyautogui.click(...), it execute it, and after that doesn't execute any other code except for pyautogui.
When I launch this code (I launch it through cmd with python myFile.py):... | Python code "freezes" after calling pyautogui | I want to automate some clicks on Windows. I use pyautogui for that.
But when my code meets pyautogui.click(...), it execute it, and after that doesn't execute any other code except for pyautogui.
When I launch this code (I launch it through cmd with python myFile.py):
import pyautogui
print("Hello, World!")
pyautogui... | [
"Just ensure that the click is outside the command prompt window. You may use pyautogui.mouseDown paired with pyautogui.dragRel for this.\nSo, what is really going on there? If you click in the command prompt window, it starts \"selection mode\", and the code runs in the background until a key is pressed. More on w... | [
1,
0
] | [] | [] | [
"pyautogui",
"python",
"python_3.x",
"windows"
] | stackoverflow_0064824130_pyautogui_python_python_3.x_windows.txt |
Q:
convert data to 1NF
I have a dataset like this
import pandas as pd
df = pd.read_csv("music.csv")
df
name
date
singer
language
phase
1
Yes or No
02.01.20
Benjamin Smith
en
1
2
Parabens
01.06.21
Rafael Galvao;Simon Murphy
pt;en
2
3
Love
12.11.20
Michaela Condell
en
1
4
Paz
11.07.19
Ana Perez; Eduarda Pinto
es... | convert data to 1NF | I have a dataset like this
import pandas as pd
df = pd.read_csv("music.csv")
df
name
date
singer
language
phase
1
Yes or No
02.01.20
Benjamin Smith
en
1
2
Parabens
01.06.21
Rafael Galvao;Simon Murphy
pt;en
2
3
Love
12.11.20
Michaela Condell
en
1
4
Paz
11.07.19
Ana Perez; Eduarda Pinto
es;pt
3
5
Stop... | [
"Split language and singer by values and use pd.explode:\ndf['language']=df['language'].str.split(';')\ndf['singer']=df['singer'].str.split(\";\")\ndf.explode(['language','singer'])\n\n\n\n\n\nId\nname\ndate\nsinger\nlanguage\nphase\n\n\n\n\n1\nYes or No\n02.01.20\nBenjamin Smith\nen\n1\n\n\n2\nParabens\n01.06.21\n... | [
0
] | [] | [] | [
"database",
"first_normal_form",
"python",
"sql"
] | stackoverflow_0074179423_database_first_normal_form_python_sql.txt |
Q:
Python dataframe to dictionary (keys: position of the column, value the names of the variables of the dataframe)
I need to create a dictionary whose keys contain the position of the column and the value the names of the variables of the dataframe.
DataFrame:
ID A B C
0 p 1 3 2
1 q 4 3 2... | Python dataframe to dictionary (keys: position of the column, value the names of the variables of the dataframe) | I need to create a dictionary whose keys contain the position of the column and the value the names of the variables of the dataframe.
DataFrame:
ID A B C
0 p 1 3 2
1 q 4 3 2
2 r 4 0 9
Output should be like this:
Dictionary = {'1': [ID], '2': [A], '3': [B],'4': [C]}
| [
"Use enumerate with dict comprehension - create strings keys and one element lists:\nd = {str(k): [v] for k, v in enumerate(df.columns, 1)}\nprint (d)\n{'1': ['ID'], '2': ['A'], '3': ['B'], '4': ['C']}\n\nOr if need intgers without lists use:\nd1 = dict(enumerate(df.columns, 1))\nprint (d1)\n{1: 'ID', 2: 'A', 3: 'B... | [
2,
1
] | [] | [] | [
"dataframe",
"dictionary",
"pandas",
"python"
] | stackoverflow_0074180296_dataframe_dictionary_pandas_python.txt |
Q:
how do I slice a list of lists into separate columns?
I think I'm basically trying to do the opposite of concatenation...Here, I have a list of lists and I want them to be separated into different columns, such as Column 1, Column 2...until Column 10 with each column holding different attributes.
What I have curre... | how do I slice a list of lists into separate columns? | I think I'm basically trying to do the opposite of concatenation...Here, I have a list of lists and I want them to be separated into different columns, such as Column 1, Column 2...until Column 10 with each column holding different attributes.
What I have currently:
['1', 'Her', 'her', 'XX', '_', '_', '3', 'XXXX', '_',... | [
"May be like that?\nlol = [['1', 'Her', 'her', 'XX', '_', '_', '3', 'XXXX', '_', '_'],\n ['2', 'hat', 'hat', 'XX', '_', '_', '4', 'XXXX', '_', '_'],\n ['3', \"'s\", \"'s\", 'XXX', '_', '_', '3', 'XXX', '_', '_'],\n ['4', 'color', 'color', 'XX', '_', '_', '8', 'XX', '_', '_'],\n ['5', 'w... | [
0
] | [] | [] | [
"nlp",
"parsing",
"python"
] | stackoverflow_0074180542_nlp_parsing_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.