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:
Tkinter - Python, how do I cause a button click to assign a value to a variable?
Using Tkinter and Python. Already created a window for the buttons to be placed on. I want there to be four buttons to appear, and I want to be able to click one of the four buttons, and be able for it to set the selection variable = ... | Tkinter - Python, how do I cause a button click to assign a value to a variable? | Using Tkinter and Python. Already created a window for the buttons to be placed on. I want there to be four buttons to appear, and I want to be able to click one of the four buttons, and be able for it to set the selection variable = "whatever I clicked", so that I can then use this variable later to call an API. When ... | [
"There are several ways to accomplish your goal.\nOne way is to write a single function that will take a value to assign to your variable. This way you can have as many buttons as you like and only a single function.\nNot if you are using functions you have to either pass the variable to the function or let the fun... | [
0
] | [] | [] | [
"python",
"tkinter",
"user_interface"
] | stackoverflow_0074153543_python_tkinter_user_interface.txt |
Q:
How can I subclass numbers.Number so that an instance receives an initial value?
I am playing with Peter Norvig's small implementation of Lisp/Scheme in python (https://norvig.com/lispy2.html). I've created Python classes for LispAtom, LispConsObj, etc.
For consistency, I thought would create a class named LispNu... | How can I subclass numbers.Number so that an instance receives an initial value? | I am playing with Peter Norvig's small implementation of Lisp/Scheme in python (https://norvig.com/lispy2.html). I've created Python classes for LispAtom, LispConsObj, etc.
For consistency, I thought would create a class named LispNumber, that subclasses numbers.Number. And I thought that I should write an __init__()... | [
"I looked at the source code, and that answered my question. numbers.Number is an empty class, and is only a superclass of the rest of the number-types in the tower.\nThe practical value at runtime is that it is possible to do\nif isinstance(x, numbers.Number):\nand that can be useful.\n"
] | [
0
] | [] | [] | [
"numbers",
"python",
"subclass"
] | stackoverflow_0073977628_numbers_python_subclass.txt |
Q:
Efficient Way to Build Large Scale Hierarchical Data Tree Path
I have a large dataset (think: big data) of network elements that form a tree-like network.
A toy dataset looks like this:
| id | type | parent_id |
|-----:|:-------|:------------|
| 1 | D | <NA> |
| 2 | C | 1 |
|... | Efficient Way to Build Large Scale Hierarchical Data Tree Path | I have a large dataset (think: big data) of network elements that form a tree-like network.
A toy dataset looks like this:
| id | type | parent_id |
|-----:|:-------|:------------|
| 1 | D | <NA> |
| 2 | C | 1 |
| 3 | C | 2 |
| 4 | C | 3 |
| ... | [
"My current solution for this challenge relies now no longer on Spark but on SQL.\nI load the whole dataset to a Postgres DB and place a Unique Index on id, type and parent_id.\nThen using the following query, I can calculate the path:\nwith recursive recursive_hierarchy AS (\n -- starting point\n select \n ... | [
0
] | [] | [] | [
"hierarchical_data",
"pyspark",
"python",
"sql",
"tree"
] | stackoverflow_0074123066_hierarchical_data_pyspark_python_sql_tree.txt |
Q:
Click "OK" on Error Loading Extension pop up using python webbot
Trying to click "OK" on a pop up using a webbot script in order to pull down a file from a website. On one machine the following code worked:
from webbot import Browser
import time
import keyboard
import threading
def push_ok_button():
keyboard.... | Click "OK" on Error Loading Extension pop up using python webbot | Trying to click "OK" on a pop up using a webbot script in order to pull down a file from a website. On one machine the following code worked:
from webbot import Browser
import time
import keyboard
import threading
def push_ok_button():
keyboard.press_and_release('enter')
class CustomThread(threading.Thread):
... | [
"Daraan commented above that I needed to add underscores on either side of my init, now the \"OK\" button is pressed.\n"
] | [
0
] | [] | [] | [
"popup",
"python",
"webbot"
] | stackoverflow_0074127913_popup_python_webbot.txt |
Q:
SSL: CERTIFICATE_VERIFY_FAILED error when loading data into seaborn?
I'm trying to load data from a github page (it's part of the standard seaborn datasets you can get.) I am on PyCharm and I don't understand what the hell is going on.
import seaborn as sns
data = sns.load_dataset("tips")
Then I get the error. ... | SSL: CERTIFICATE_VERIFY_FAILED error when loading data into seaborn? | I'm trying to load data from a github page (it's part of the standard seaborn datasets you can get.) I am on PyCharm and I don't understand what the hell is going on.
import seaborn as sns
data = sns.load_dataset("tips")
Then I get the error. Why am I getting this error?
/usr/local/bin/python3.7 "/Users/shahbhuiyan/... | [
"I encountered the same issue and found the solution here: \nhttp://www.programmersought.com/article/2877138500/\nBasically, just add these two lines of code, then try importing the data set:\nimport ssl\nssl._create_default_https_context = ssl._create_unverified_context\n\nThis way, python will ignore verification... | [
10,
0,
0
] | [] | [] | [
"matplotlib",
"pycharm",
"python",
"seaborn"
] | stackoverflow_0057483667_matplotlib_pycharm_python_seaborn.txt |
Q:
How to implement Python import libraries on Xampp localhost?
I'm trying to implement running machine learning on my web.
I set my Xampp addhandler .py so that can handle python files.
Basically, I checked everything python works on my web.
But the problem is that cannot import any libraries such as cv2, easyocr, a... | How to implement Python import libraries on Xampp localhost? | I'm trying to implement running machine learning on my web.
I set my Xampp addhandler .py so that can handle python files.
Basically, I checked everything python works on my web.
But the problem is that cannot import any libraries such as cv2, easyocr, and imutils.
#!C:\Users\parkc\AppData\Local\Programs\Python\Python3... | [
"Maybe you would like to read this, it will help you a lot I think:\nthe article\n“How to Easily Run Python Visualizations On a Web Browser with PyScript”\n"
] | [
0
] | [] | [] | [
"apache",
"php",
"python",
"xampp"
] | stackoverflow_0074151432_apache_php_python_xampp.txt |
Q:
regex pattern to get date after a particular text and a combination of word-number string ending with text MRN
I would like to create a regex which can match the following pattern
HR060178 RGP LUKA RIJEKA
30.09.2022 09:42:52
22HR060178U0078350MRN
to be specific the date which comes after text LUKA RIJEKA
and the M... | regex pattern to get date after a particular text and a combination of word-number string ending with text MRN | I would like to create a regex which can match the following pattern
HR060178 RGP LUKA RIJEKA
30.09.2022 09:42:52
22HR060178U0078350MRN
to be specific the date which comes after text LUKA RIJEKA
and the MRN number starting with 22
The screenshot is of another problem where in the highlighted numbers need to be extracte... | [
"since you only provided this one sample, its diffucult to test edge cases and fine tune the regex, but the following should give you a good starting point:\n((?<=LUKA\\sRIJEKA\\s)\\d\\d\\.\\d\\d\\.\\d\\d\\d\\d)|((?<=\\sLUKA\\sRIJEKA\\s\\d\\d\\.\\d\\d\\.\\d\\d\\d\\d\\s\\d\\d:\\d\\d:\\d\\d\\s)22[^\\s]+?MRN)\n\ni hav... | [
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074151742_python_regex.txt |
Q:
How to Setup a Discord BOT with Phyton
I did this following a tutorial, but when I play run it says there is an error on line 5
import discord
import os
my_secret = os.environ['token']
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.e... | How to Setup a Discord BOT with Phyton | I did this following a tutorial, but when I play run it says there is an error on line 5
import discord
import os
my_secret = os.environ['token']
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if mes... | [
"A bit of advice: post the errors you're getting so people don't have to run the code to get an idea of what's happening. Anyway I ran it and saw\n➜ test-discordbot poetry run python main.py\nTraceback (most recent call last):\n File \"/home/l4sh/Projects/test-discordbot/main.py\", line 6, in <module>\n client... | [
2
] | [] | [] | [
"bots",
"discord",
"discord.py",
"python"
] | stackoverflow_0074153916_bots_discord_discord.py_python.txt |
Q:
Custom loss for keras model to penalize certain predictions
I'm using a neural network for multiclass classification and I'd like to create a custom loss function that penalizes certain misclassifications. This can be done by calculating the cross-entropy loss and then multiplying it by a weight given by a custom-... | Custom loss for keras model to penalize certain predictions | I'm using a neural network for multiclass classification and I'd like to create a custom loss function that penalizes certain misclassifications. This can be done by calculating the cross-entropy loss and then multiplying it by a weight given by a custom-made penalty matrix, which holds a value for each pair of (predic... | [
"def custom_loss(y_true, y_pred):\n loss = tf.keras.losses.categorical_crossentropy(y_true, y_pred)\n\n predicted = tf.math.argmax(y_true , axis=-1)\n true = tf.math.argmax(y_true , axis=-1)\n penalty_weight = tf.stack([true , predicted] , axis=1)\n loss = tf.math.multiply(loss , penalty_weight)\n \n return... | [
1
] | [] | [] | [
"keras",
"machine_learning",
"neural_network",
"python",
"tensorflow"
] | stackoverflow_0074142189_keras_machine_learning_neural_network_python_tensorflow.txt |
Q:
Selenium importing google profile DeprecationWarning: executable_path has been deprecated
The error I am receiving is:
C:\Users\CharlieWait\AppData\Local\Temp\ipykernel_90388\1267197158.py:9: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
w = webdriver.Chrome(executable_... | Selenium importing google profile DeprecationWarning: executable_path has been deprecated | The error I am receiving is:
C:\Users\CharlieWait\AppData\Local\Temp\ipykernel_90388\1267197158.py:9: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
w = webdriver.Chrome(executable_path="C:\\Users\\CharlieWait\\chromedriver.exe", options=options)
My code:
from selenium impor... | [
"You should use Service.\nfrom selenium.webdriver.chrome.service import Service\n\nw = webdriver.Chrome(service=Service(\"C:\\\\Users\\\\CharlieWait\\\\chromedriver.exe\"), options=options)\n\n"
] | [
0
] | [] | [] | [
"google_chrome",
"profile",
"python",
"selenium"
] | stackoverflow_0074152991_google_chrome_profile_python_selenium.txt |
Q:
How can I shorten this code (for loop help)
string1 = str(input("Type a word"))
for i in range(len(string1)):
print(string1[-1+i], end= "")
print('')
for i in range(len(string1)):
print (string1[-2+i] , end= "")
print('')
for i in range(len(string1)):
print (string1[-3+i] , end= "")
print('')
for i in ... | How can I shorten this code (for loop help) | string1 = str(input("Type a word"))
for i in range(len(string1)):
print(string1[-1+i], end= "")
print('')
for i in range(len(string1)):
print (string1[-2+i] , end= "")
print('')
for i in range(len(string1)):
print (string1[-3+i] , end= "")
print('')
for i in range(len(string1)):
print (string1[-4+i] , e... | [
"Only one loop.\nstring1 = str(input(\"Type a word\"))\nfor i in range(1,len(string1)+1):\n print(string1[-i:] + string1[:-i])\n\n",
"To rotate a string slice of the last letter and put it in the front:\ns = s[-1] + s[:-1]\nExample:\nword = \"Example\"\n\n# we do not care about the letters, just want to loop o... | [
2,
0,
0
] | [
"Python's range function can be used to generate the index starting numbers that you're using (-1, -2, etc.).\nIt accepts a step parameter that can be used to count backwards:\nstring1 = str(input(\"Type a word\"))\n\nfor n in range(-1, -6, -1):\n for i in range(len(string1)):\n print(string1[n+i], end= \"\")\n... | [
-2
] | [
"for_loop",
"loops",
"python"
] | stackoverflow_0074154166_for_loop_loops_python.txt |
Q:
How to return all weekdays in a range of dates, sorted in ascending order
from datetime import datetime
from datetime import timedelta
#this is the start day
day = input()
#this is number of days input
num=int(input())
#this is the start date of the shipment
temp = input()
#this is the date format the string into... | How to return all weekdays in a range of dates, sorted in ascending order | from datetime import datetime
from datetime import timedelta
#this is the start day
day = input()
#this is number of days input
num=int(input())
#this is the start date of the shipment
temp = input()
#this is the date format the string into a day using the strptime object
start_day = datetime.strptime(day, '%A')
#this... | [
"The issue seems to be that you're looping through an ascending range of numbers, but that number is subtracted to get the result. For example 10-1=9, 10-2=8, 10-3=7, etc. You can instead loop through range(num) in descending order. Also, range() by default goes from index zero up to and not including num. To have ... | [
2,
0,
0,
0
] | [] | [] | [
"python",
"weekday"
] | stackoverflow_0074153044_python_weekday.txt |
Q:
Python IDLE won´t start
I´m a noob in python and about a week ago IDLE stop working, I have readed some other people questions about this, but none of them had the same error that I´m getting, which is:
Traceback (most recent call last):
File "c:\python26\Lib\idlelib\idle.py", line 21, in <module>
idle... | Python IDLE won´t start | I´m a noob in python and about a week ago IDLE stop working, I have readed some other people questions about this, but none of them had the same error that I´m getting, which is:
Traceback (most recent call last):
File "c:\python26\Lib\idlelib\idle.py", line 21, in <module>
idlelib.Pyshell.main()
File "... | [
"This TCL issue has appeared in a number of Python forums and is generally prevents the IDLE GUI from starting e.g. http://www.gossamer-threads.com/lists/python/python/902912 and is related to the TCL_LIBRARY enviroment variables. Try and edit the enviroment variables\nRight click on (My) Computer, go to properties... | [
6,
2,
1,
0,
0
] | [] | [] | [
"python",
"python_idle"
] | stackoverflow_0007509579_python_python_idle.txt |
Q:
How do I use method overloading in Python?
I am trying to implement method overloading in Python:
class A:
def stackoverflow(self):
print 'first method'
def stackoverflow(self, i):
print 'second method', i
ob=A()
ob.stackoverflow(2)
but the output is second method 2; similarly:
class... | How do I use method overloading in Python? | I am trying to implement method overloading in Python:
class A:
def stackoverflow(self):
print 'first method'
def stackoverflow(self, i):
print 'second method', i
ob=A()
ob.stackoverflow(2)
but the output is second method 2; similarly:
class A:
def stackoverflow(self):
pri... | [
"It's method overloading, not method overriding. And in Python, you historically do it all in one function:\nclass A:\n def stackoverflow(self, i='some_default_value'):\n print 'only method'\n\nob=A()\nob.stackoverflow(2)\nob.stackoverflow()\n\nSee the Default Argument Values section of the Python tutoria... | [
175,
98,
67,
50,
23,
17,
16,
13,
9,
7,
6,
5,
4,
2,
2,
1,
0
] | [] | [] | [
"class",
"overloading",
"python"
] | stackoverflow_0010202938_class_overloading_python.txt |
Q:
How to call a user Python function from within Vim to alter and replace visually selected text (without using Vim's Python Interface)?
Let's say I have a two Python functions that can reverse a sentence. One function reverses the words, the other the letters. My task is to call one of these functions from within V... | How to call a user Python function from within Vim to alter and replace visually selected text (without using Vim's Python Interface)? | Let's say I have a two Python functions that can reverse a sentence. One function reverses the words, the other the letters. My task is to call one of these functions from within Vim to reformat and replace visually selected text, and to it without involving Vim's Python Interface, if that's possible.
To make things mo... | [
"I would:\n\nmake the Python code use sys.stdin instead of sys.argv,\n\nand call it like so (untested):\n:'<,'>!path/to/script.py\n\nwith Vim passing the visually selected lines to your Python script as stdin.\n\n\n",
"One way to get the desired result is to use both sys.stdin and sys.argv.\n if __name__ == '_... | [
0,
0
] | [] | [] | [
"python",
"vim"
] | stackoverflow_0074100117_python_vim.txt |
Q:
get a integer from a file in python
I'm learning python, and I have a simple question.
I have a file, and I need to read it, the file contains a header, and its divided by the size of the structures in the file, and the top of the pile, like this:
size=86 top=-1
so far, I only read the line, and it's working
def ... | get a integer from a file in python | I'm learning python, and I have a simple question.
I have a file, and I need to read it, the file contains a header, and its divided by the size of the structures in the file, and the top of the pile, like this:
size=86 top=-1
so far, I only read the line, and it's working
def readinput(input):
line = []
line ... | [
"A bit more information on your specific use case would be helpful (assuming that you want to define two variables, where size=86 and top=-1), but in the meantime, you could try something like this:\n#helper method to parse input\ndef readinput(input):\n #Read the input file\n line = input.readline()\n #S... | [
0,
0
] | [] | [] | [
"data_structures",
"file",
"python"
] | stackoverflow_0074154294_data_structures_file_python.txt |
Q:
Read Data from Kafka Broker at Specific Time Intervals (Python)
I have a system where a machine is reading data and continuously appends a .txt file. This dataset is read into a Kafka broker via Kafka Connect and would then be pre-processed with some Python code. The machine operates roughly every 5 mins, so we wo... | Read Data from Kafka Broker at Specific Time Intervals (Python) | I have a system where a machine is reading data and continuously appends a .txt file. This dataset is read into a Kafka broker via Kafka Connect and would then be pre-processed with some Python code. The machine operates roughly every 5 mins, so we would expect data to come in, and then be idle for 5 mins. until the ne... | [
"Have you tried passing a time interval to the poll function?\nwhile 1:\n msg = consumer.poll(300000) # listen for 5 minutes of data\n if msg is None:\n break\n elif msg.error():\n print(\"Consumer error: {}\".format(msg.error()))\n continue\n else:\n live_data.append(parse_p... | [
2
] | [] | [] | [
"apache_kafka",
"confluent_kafka_python",
"python"
] | stackoverflow_0070779721_apache_kafka_confluent_kafka_python_python.txt |
Q:
In sympy, is there a way to suppress the writing of function arguments, such as writing f instead of f(x)?
I am doing calculus with a lot of functions of one variable in a Jupyter Notebook.
I am displaying the results using latex with
from sympy import *
from IPython.display import display, Math, Latex
init_print... | In sympy, is there a way to suppress the writing of function arguments, such as writing f instead of f(x)? | I am doing calculus with a lot of functions of one variable in a Jupyter Notebook.
I am displaying the results using latex with
from sympy import *
from IPython.display import display, Math, Latex
init_printing()
When I print something like Function('f')('x'), it comes out as f(x). I want it to come out as f. Is this... | [
"For those who are still looking for a solution, you can use the following function for any number of function inputs:\ndef display_no_args(expr):\n functions = expr.atoms(Function)\n reps = {}\n\n for fun in functions:\n reps[fun] = Symbol(fun.name)\n\n display(expr.subs(reps))\n\n"
] | [
0
] | [] | [] | [
"jupyter_notebook",
"python",
"sympy"
] | stackoverflow_0064772178_jupyter_notebook_python_sympy.txt |
Q:
Why does `slice` have to be unhashable?
Why doesn't python make slice hashable? In my simple mind you can simply xor its start, stop, and step and you will have a good hash.
It will be very useful when we want unordered sets of slices.
A:
slice objects aren't hashable because it's possible for a slice to be made... | Why does `slice` have to be unhashable? | Why doesn't python make slice hashable? In my simple mind you can simply xor its start, stop, and step and you will have a good hash.
It will be very useful when we want unordered sets of slices.
| [
"slice objects aren't hashable because it's possible for a slice to be made up of mutable (unhashable) objects, such as a list.\nslice() doesn't require that the arguments be integers - any object type is allowed. This is perfectly legal:\nslice([1, 2, 3], [4, 5, 6])\n\nthough it's not very useful, since using that... | [
3
] | [] | [] | [
"hashmap",
"python"
] | stackoverflow_0074154262_hashmap_python.txt |
Q:
Selection in dataframe base on multiple condition
I am developping a dashboard using dash.
The user can select different parameters and a dataframe is updated (6 parameters).
The idea was to do :
filtering = []
if len(filter1)>0:
filtering.append("df['col1'].isin(filter1)")
if len(filter2)>0:
filtering.app... | Selection in dataframe base on multiple condition | I am developping a dashboard using dash.
The user can select different parameters and a dataframe is updated (6 parameters).
The idea was to do :
filtering = []
if len(filter1)>0:
filtering.append("df['col1'].isin(filter1)")
if len(filter2)>0:
filtering.append("df['col2'].isin(filter2)")
condition = ' & '.join(... | [
"You can merge the masks using the & operator and only apply the merged mask once\nfrom functools import reduce\n\nfilters = []\nif len(filter1)>0:\n filters.append(df.col1.isin(filter1))\nif len(filter2)>0:\n filters.append(df.col2.isin(filter2))\n\nif len(filters) > 0:\n final_filter = reduce(lambda a, b... | [
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074154455_dataframe_pandas_python.txt |
Q:
Removing substring combinations in Python
I have job description text data that is stored in a data frame. I cleaned/preprocessed my data a little bit, including lowercasing and removing whitespaces, URLs, punctuation, stopwords, and HTML tags.
Next, I want to remove particular combinations of substrings. I give y... | Removing substring combinations in Python | I have job description text data that is stored in a data frame. I cleaned/preprocessed my data a little bit, including lowercasing and removing whitespaces, URLs, punctuation, stopwords, and HTML tags.
Next, I want to remove particular combinations of substrings. I give you an example:
If the text reads "required cert... | [
"You can put the combinations in a list, then loop through it.\nevery combination can be reversed in the next. here is an example below:\nNB: regular combinations have marked by ****, while reversed ones are marked by ++++\ncombinations =[\"certification license\", \"particular combinations\"]\n \ntex... | [
1
] | [] | [] | [
"python",
"regex",
"substring"
] | stackoverflow_0074154112_python_regex_substring.txt |
Q:
Django - Get user with highest bid
I need to get the user who placed the highest bid for the listing on an auction site.
models.py:
class Listing(models.Model):
class Category(models.TextChoices):
BOOKS = 'Books'
SPORTS = 'Sports'
DEATHLY_HALLOWS = 'Deathly Hallows'
CLOTHING = 'Clothing'
WANDS... | Django - Get user with highest bid | I need to get the user who placed the highest bid for the listing on an auction site.
models.py:
class Listing(models.Model):
class Category(models.TextChoices):
BOOKS = 'Books'
SPORTS = 'Sports'
DEATHLY_HALLOWS = 'Deathly Hallows'
CLOTHING = 'Clothing'
WANDS = 'Wands'
JEWELRY = 'Jewelry'
titl... | [
"Order the Bids by the bid:\ndef listing(request, listing_id):\n highest_bid = Bid.objects.latest('bid')\n winner = highest_bid.user\n print(winner)\n # …\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074154716_django_python.txt |
Q:
I want to split data (positive/negative) and put them in empty numpy arrays. (LOGISTIC REGRESSION EXAMPLE)
So I am stuck in sorting out this problem and I have this data of email ID and there respective value as 0 & 1 (corresponding tag values used in Logistic Regression). The data is as follows:
input_x = np.arra... | I want to split data (positive/negative) and put them in empty numpy arrays. (LOGISTIC REGRESSION EXAMPLE) | So I am stuck in sorting out this problem and I have this data of email ID and there respective value as 0 & 1 (corresponding tag values used in Logistic Regression). The data is as follows:
input_x = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])
input_y = np.array([0,1,0,0,1,1,1,0,0,0,0,1,0,1,0])
Now I want to spli... | [
"First make a dictionary of x and y:\ninput_x = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])\ninput_y = np.array([0,1,0,0,1,1,1,0,0,0,0,1,0,1,0])\ny_dict = {x: input_y[x-1] for x in input_x}\n\nCreate your lists and print:\nemp_neg_data_x = [x for x, y in y_dict.items() if y == 0]\nemp_neg_data_y = [y for x, y i... | [
0
] | [] | [] | [
"logistic_regression",
"numpy",
"numpy_ndarray",
"python"
] | stackoverflow_0074154414_logistic_regression_numpy_numpy_ndarray_python.txt |
Q:
Is it possible to convert Matplotlob plot to blob format without saving the plot to the file?
As in title. I want to convert plot generated in Matplotlib in Python to blob and then send the blob plot from backend to frontend. Is there any library for that? Or maybe you have any other suggestions how to send the pl... | Is it possible to convert Matplotlob plot to blob format without saving the plot to the file? | As in title. I want to convert plot generated in Matplotlib in Python to blob and then send the blob plot from backend to frontend. Is there any library for that? Or maybe you have any other suggestions how to send the plot to frontend? The thing is I do not want to save the plot to the file. I use Django REST Framewor... | [
"It's better to send the array/data that realizes the plot to the front-end and use front-end libraries, such as Chart.js and Plotly.js, to plot data on the front-end side.\nNevertheless, if still want to send the Matplotlib image to the front-end, you can convert it to base64 and send the base64 string to the fron... | [
0
] | [] | [] | [
"blob",
"django_rest_framework",
"matplotlib",
"python",
"reactjs"
] | stackoverflow_0074154446_blob_django_rest_framework_matplotlib_python_reactjs.txt |
Q:
KeyError: Index(['StateAbb'], dtype='object')
Because of the error, I cannot drop the duplicates using following code:
cc.drop_duplicates(subset="StateAbb")
How can I sole the issue?
A:
StateAbb is the index , you can't de-duplicate index .
you can do this :
cc = cc.reset_index().drop_duplicates(subset="StateAb... | KeyError: Index(['StateAbb'], dtype='object') | Because of the error, I cannot drop the duplicates using following code:
cc.drop_duplicates(subset="StateAbb")
How can I sole the issue?
| [
"StateAbb is the index , you can't de-duplicate index .\nyou can do this :\ncc = cc.reset_index().drop_duplicates(subset=\"StateAbb\").set_index('StateAbb')\n\n",
"Use boolean indexing with Index.duplicated and boolean NOT (~):\ncc = cc[~cc.index.duplicated()]\n\n"
] | [
1,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074154558_pandas_python.txt |
Q:
How to append a new column on to an existing dataframe that contains a conditional count which is also grouped by
I am trying to add a new column to my existing dataframe that contains a conditional count, grouped by another column in the dataframe.
In my example I am counting when "Severity" ==2 and grouping by "... | How to append a new column on to an existing dataframe that contains a conditional count which is also grouped by | I am trying to add a new column to my existing dataframe that contains a conditional count, grouped by another column in the dataframe.
In my example I am counting when "Severity" ==2 and grouping by "Data Tech Group". I am achieving this count by doing the below:
df.loc[df.Severity == 2].groupby("AssignedGroup").count... | [
"I am not familiar with a direct answer, but having understood what you need follow this method. It'll get the answer. If I get a shorter fancier one, I'll amend the answer.\n\nMake a duplicate of the df. Evaluate df.loc[df.Severity == 2].groupby(\"AssignedGroup\").count() similar to what you did with Sev 1-4 count... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074154560_pandas_python.txt |
Q:
How to add a field in one text input by clicking a button in PySimpleGUI?
Dears,
I'm new in using Stackoverflow & PySimpleGUI... I want add one functionality in my project using PySimpleGUI, So that when I click in one Button, it will insert a text in another Text Field, it's similar principle as creating calculat... | How to add a field in one text input by clicking a button in PySimpleGUI? | Dears,
I'm new in using Stackoverflow & PySimpleGUI... I want add one functionality in my project using PySimpleGUI, So that when I click in one Button, it will insert a text in another Text Field, it's similar principle as creating calculator , but the only difference I need to input some letter from my keyboard too. ... | [
"Just update the text of the Input element with the new characters into the Input element.\nimport PySimpleGUI as sg\n\nsg.theme('DarkBlue3')\n\nwords = \"This is a book\".split(' ')\nlayout = [\n [sg.Input(key='-IN-')],\n [sg.Push()] + [sg.Button(word, size=4) for word in words],\n]\nwindow = sg.Window(\"Tit... | [
0
] | [] | [] | [
"button",
"calculator",
"input",
"pysimplegui",
"python"
] | stackoverflow_0074154603_button_calculator_input_pysimplegui_python.txt |
Q:
Close appication window on screen opened by subprocess (not only the internal subprocess)
I need to open and close a application on a Windows machine using Python. I tried (opening the calculator):
import subprocess, time
p = subprocess.Popen(["calc"])
time.sleep(2)
p.terminate()
also using
p.kill()
does not wor... | Close appication window on screen opened by subprocess (not only the internal subprocess) | I need to open and close a application on a Windows machine using Python. I tried (opening the calculator):
import subprocess, time
p = subprocess.Popen(["calc"])
time.sleep(2)
p.terminate()
also using
p.kill()
does not work.
However, it seems that while the (python internal) subprocess is terminated, the application... | [
"I was able to close the window in the foreground using the win32 library:\nimport subprocess, time\nimport win32gui, win32con\n\nfor x in range(2):\n # Open calculator\n p = subprocess.Popen([\"calc\"], stdout=subprocess.PIPE, shell=True)\n time.sleep(3)\n # Terminate subprocess\n p.terminate() \n ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074154141_python.txt |
Q:
Python read csv with array columns
I have some csv files including array columns. For example:
a,b,c
1,1|2|3,4.5|5.5|6.5
2,7|8|9,10.5|11.5|12.5
Delimter 1 is , to sepperate fields a, b and c. Delimiter 2 is | in this case, but could be changed.
Is there a possibility in python to read this as a pandas dataframe d... | Python read csv with array columns | I have some csv files including array columns. For example:
a,b,c
1,1|2|3,4.5|5.5|6.5
2,7|8|9,10.5|11.5|12.5
Delimter 1 is , to sepperate fields a, b and c. Delimiter 2 is | in this case, but could be changed.
Is there a possibility in python to read this as a pandas dataframe directly? Field b and c should be an arra... | [
"You can use converters parameter of .read_csv() to parse columns:\nimport pandas as pd\nimport numpy as np\n\n\ndf = pd.read_csv('data.csv', converters={\n 'b': lambda x: np.array(x.split('|'), dtype='int'),\n 'c': lambda x: np.array(x.split('|'), dtype='float')\n })\nprint(df)\n\nOutput:\n a b... | [
3,
1
] | [] | [] | [
"csv",
"pandas",
"python"
] | stackoverflow_0074154732_csv_pandas_python.txt |
Q:
How to updated a table (accessed in pandas) in DuckDB Database?
I'm working on one of use case, I have a larger volumes of records created in a duckdb database table, these tables can be accessed in pandas dataframe, do the data manipulations and send them back to DB table. here below I will explain my case.
I ha... | How to updated a table (accessed in pandas) in DuckDB Database? | I'm working on one of use case, I have a larger volumes of records created in a duckdb database table, these tables can be accessed in pandas dataframe, do the data manipulations and send them back to DB table. here below I will explain my case.
I have a DB called as MY_DB in Duck DB and a table in it as ROLL_TABLE_A,... | [
"Here is a function that takes a dataframe, table name and database path as input and writes the dataframe to the table:\ndef df_to_duckdb(df:pd.DataFrame, table:str, db_path:str):\n con = duckdb.connect(database=db_path, read_only=False)\n \n # register the df in the database so it can be queried\n con... | [
1
] | [] | [] | [
"duckdb",
"pandas",
"python"
] | stackoverflow_0074085530_duckdb_pandas_python.txt |
Q:
Gradient descent from mathematical ideation for sum of squared errors
I have the following gradient descent algorithm that I derived mathematically for sum of squared errors. However, when I implement it, the losses increase as shown below. I'm trying to understand the error but can't seem to find the mathematical... | Gradient descent from mathematical ideation for sum of squared errors | I have the following gradient descent algorithm that I derived mathematically for sum of squared errors. However, when I implement it, the losses increase as shown below. I'm trying to understand the error but can't seem to find the mathematical fallacy as the dimensions and derivation line up, so I'm not quite sure wh... | [
"Short Answer : You are probably using a larger learning rate. Try reducing the learning rate.\nLong Answer : Let's take 20 random samples, each having a dimension of 5. Then our X will have the dimension of (20,5). Let's assume W_t is the true weight we are aiming to reach. If we ignore the bias, then the linear e... | [
0
] | [] | [] | [
"gradient_descent",
"machine_learning",
"matrix_multiplication",
"python"
] | stackoverflow_0074154399_gradient_descent_machine_learning_matrix_multiplication_python.txt |
Q:
How to pass the script path to %run magic command as a variable in databricks notebook?
I want to run a notebook in databricks from another notebook using %run. Also I want to be able to send the path of the notebook that I'm running to the main notebook as a parameter.
The reason for not using dbutils.notebook.ru... | How to pass the script path to %run magic command as a variable in databricks notebook? | I want to run a notebook in databricks from another notebook using %run. Also I want to be able to send the path of the notebook that I'm running to the main notebook as a parameter.
The reason for not using dbutils.notebook.run is that I'm storing heavily nested dictionaries in the notebook that's called and I wanna u... | [
"Magic commands such as %run and %fs do not allow variables to be passed in.\nThe workaround is you can use dbutils as like dbutils.notebook.run(notebook, 300 ,{})\n",
"You can pass arguments as documented on Databricks web site:\nhttps://docs.databricks.com/notebooks/widgets.html#use-widgets-with-run\nIn the top... | [
3,
2,
0
] | [
"Problem\nYou can't pass it as a variable while running the notebook like this:\nIn notebook1:\npath_var = \"/some/path\"\n\n%run ./notebook2\n%path=path_var\n\nSolution\nHowever what you can do, and what I did, is access the dbutils object or the variable of notebook1 in notebook2:\nIn notebook1:\ndbutils.widgets.... | [
-1
] | [
"databricks",
"jupyter_notebook",
"pyspark",
"python"
] | stackoverflow_0068885950_databricks_jupyter_notebook_pyspark_python.txt |
Q:
Pytest: How to pass method which returns list as an argument in parametrized test
I have a question regarding parametrizing the test method with another method that returns the list of test data that I want to use in my test:
When I execute code in this way:
class Test:
@pytest.mark.parametrize("country_code"... | Pytest: How to pass method which returns list as an argument in parametrized test | I have a question regarding parametrizing the test method with another method that returns the list of test data that I want to use in my test:
When I execute code in this way:
class Test:
@pytest.mark.parametrize("country_code", get_country_code_list())
def test_display_country_code(self, country_code):
... | [
"Yes, the order in which you do things is important.\nFunctions are just like variables in that manner.\nWorking Example Variables\nx = 3\ny = 5\nz = x + y\n\nWorks perfectly fine, because everything is done according to order.\nBroken Example Variables\nx = 3\nz = x + y\ny = 5\n\nDoesn't work, of course, because y... | [
0,
0
] | [] | [] | [
"pytest",
"python"
] | stackoverflow_0074144940_pytest_python.txt |
Q:
pandas resample with origin and closed status
I have a dataframe for inventory like the following,
tidx = pd.date_range('2022-10-01', periods=15, freq='D')
data_frame = pd.DataFrame(1, columns=['inventory'], index=tidx)
data_frame.iloc[-2:] = 0
print(data_frame)
inventory
2022-10-01 1
2022-10-02 ... | pandas resample with origin and closed status | I have a dataframe for inventory like the following,
tidx = pd.date_range('2022-10-01', periods=15, freq='D')
data_frame = pd.DataFrame(1, columns=['inventory'], index=tidx)
data_frame.iloc[-2:] = 0
print(data_frame)
inventory
2022-10-01 1
2022-10-02 1
2022-10-03 1
2022-10-04 1
202... | [
"data_frame.resample(\"7D\", origin='2022-10-15', closed='right', loffset='7D').sum()\n\nGives:\n inventory\n2022-10-01 1\n2022-10-08 7\n2022-10-15 5\n\nAlthough loffset is deprecated. So you can do this instead.\nfrom pandas.tseries.frequencies import to_offset\ndf = data_fram... | [
1,
0
] | [] | [] | [
"pandas",
"pandas_resample",
"python"
] | stackoverflow_0074154388_pandas_pandas_resample_python.txt |
Q:
Selecting data in pandas based on conditions
I am importing data from excel using Pandas and it looks like below,
time Column1 Column2 Column3 ID
0 1.0 181.359 -1.207 9.734 10
1 2.0 181.357 -1.179 9.729 10
2 3.0 181.357 -0.713 9.732 ... | Selecting data in pandas based on conditions | I am importing data from excel using Pandas and it looks like below,
time Column1 Column2 Column3 ID
0 1.0 181.359 -1.207 9.734 10
1 2.0 181.357 -1.179 9.729 10
2 3.0 181.357 -0.713 9.732 10
3 602.0 179.148 505.520 17.774 ... | [
"Use pandas.DataFrame.loc: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.loc.html\ndf.loc[df['ID'] == 1810][['Column1', 'Column2', 'Column3']]\n\n"
] | [
0
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074154372_numpy_pandas_python.txt |
Q:
Does categorical data encoding methods effect the output of the machine learning model drastically?
I am working on this dataset:
Dataset Sample
The dataset has been split into training (6509, 10) and test set (2787, 10). The categorical features contain 111, 761, 23, 10, 55 categories respectively. I am using Ran... | Does categorical data encoding methods effect the output of the machine learning model drastically? | I am working on this dataset:
Dataset Sample
The dataset has been split into training (6509, 10) and test set (2787, 10). The categorical features contain 111, 761, 23, 10, 55 categories respectively. I am using RandomForestRegressor model in both the cases.
In the first case I used pd.get_dummies to encode categorica... | [
"Tree models do process one hot encoding somewhat worse, however:\n\nyou don't do drop_first, and redundant columns could have a negative impact on model variance;\npd.get_dummies() results may be incosistent if the set of categories in your train and test sets happen to differ.\n\n"
] | [
0
] | [] | [] | [
"machine_learning",
"python"
] | stackoverflow_0074154232_machine_learning_python.txt |
Q:
event loop is closed in a celery worker
I am facing multiple issues using an async ODM inside my celery worker
First i wasn't able to init my database models using celery worker signal
i am using beanie for the db connection.
First Implementation
from asyncer import syncify
from asgiref.sync import async_to_sync
... | event loop is closed in a celery worker | I am facing multiple issues using an async ODM inside my celery worker
First i wasn't able to init my database models using celery worker signal
i am using beanie for the db connection.
First Implementation
from asyncer import syncify
from asgiref.sync import async_to_sync
client = AsyncIOMotorClient(
DATABASE_URL... | [
"After many investigation using flower for monitoring workers and logging the workers Id ( processes ids) it turns out that Celery worker itself does not process any tasks, it spawns other child processes ( this is my case because i am using the default executor pool which is prefork), while the signal ( worker_rea... | [
0
] | [] | [] | [
"celery",
"mongodb",
"odm",
"python",
"python_asyncio"
] | stackoverflow_0074058894_celery_mongodb_odm_python_python_asyncio.txt |
Q:
Adding Column to Pandas Dataframes from Python Generator
I'm reading a number of csv files into python using a glob matching and would like to add the filename as a column in each of the dataframes. I'm currently matching on a pattern and then using a generator to read in the files as so:
base_list_of_files = glob... | Adding Column to Pandas Dataframes from Python Generator | I'm reading a number of csv files into python using a glob matching and would like to add the filename as a column in each of the dataframes. I'm currently matching on a pattern and then using a generator to read in the files as so:
base_list_of_files = glob.glob(matching_pattern)
loaded_csv_data_frames = (pd.read_csv... | [
"Generators can only go through one iteration, at the end of which they throw a StopIteration exception which is automatically handled by the for loop. If you try to consume them again they will just raise StopIteration, as demonstrated here:\ndef consume(gen):\n while True:\n print(next(gen))\n except... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074153661_pandas_python.txt |
Q:
Pandas module not found, although
For some reason I cannot get Pandas to work. A few year back I used Atom as IDE, back then everything was working fine. Now I wanted to refresh my Python skills by using PyCharm, however my first script results in:
ModuleNotFoundError: No module named 'pandas'
According to cmd pa... | Pandas module not found, although | For some reason I cannot get Pandas to work. A few year back I used Atom as IDE, back then everything was working fine. Now I wanted to refresh my Python skills by using PyCharm, however my first script results in:
ModuleNotFoundError: No module named 'pandas'
According to cmd pandas is installed:
Requirement already ... | [
"Most likely you're using a different (virtual) environment at the command line and in PyCharm. See JetBrains docs on configuring the Python interpreter for PyCharm.\nIf Python's configured the way you expect, check the installed packages as well by following these docs\n"
] | [
2
] | [] | [] | [
"pandas",
"pip",
"python"
] | stackoverflow_0074155000_pandas_pip_python.txt |
Q:
YAML just upload "part" without "urls"
Hey i have yaml code below and i want to add parts using python i.e. part-4,.... In doing so I only manage to create urls using the which I don't want.... can anyone help me? Current codeblock from python:
d = {'urls':{f'part-{i}': {'updated': 16662709610, 'url': 'http://any-... | YAML just upload "part" without "urls" | Hey i have yaml code below and i want to add parts using python i.e. part-4,.... In doing so I only manage to create urls using the which I don't want.... can anyone help me? Current codeblock from python:
d = {'urls':{f'part-{i}': {'updated': 16662709610, 'url': 'http://any-do0main1.com/', 'url-name': f'crl{i}.der'}}
... | [
"Not sure that you can append a YAML like a regular file. Here is a possible solution:\nimport yaml\nimport re\n\nwith open('test.yaml', 'r') as yaml_file_loaded:\n yaml_loaded = yaml.safe_load(yaml_file_loaded) #load yaml\n part_keys = list(yaml_loaded['urls'].keys()) #get all part-# keys\n all_numbers ... | [
0
] | [] | [] | [
"python",
"python_3.x",
"pyyaml",
"yaml"
] | stackoverflow_0074140984_python_python_3.x_pyyaml_yaml.txt |
Q:
Split one list into two lists just by unpacking?
I can split a list by slicing, but how to do it by unpacking?
What I have
When unpack, I'm getting one list and one string.
mylist=["start","next1","next2","next3","end"]
# Desired Result - two lists
part1, part2= mylist[:-1],[mylist[-1]]
print(f"Slicing 2: {type(... | Split one list into two lists just by unpacking? | I can split a list by slicing, but how to do it by unpacking?
What I have
When unpack, I'm getting one list and one string.
mylist=["start","next1","next2","next3","end"]
# Desired Result - two lists
part1, part2= mylist[:-1],[mylist[-1]]
print(f"Slicing 2: {type(part1)} {part1} {type(part2)} {part2}")
# Not the de... | [
"To elaborate Steven Rumbalski's comments:\nUnpacking with remainder *\nUnpacking with *part1,part2 = mylist will split the list into the last item part2 (which is a str) and the remaining items into part1 (remainder denoted by asterisk *). See Partial list unpack in Python.\nWrapping an item into a list\nThe slici... | [
0
] | [] | [] | [
"list",
"python",
"split"
] | stackoverflow_0074154874_list_python_split.txt |
Q:
Microsoft.Office.Interop.Excel Workbook has no Open method in python
I know there is other ways or modules to read/write xls with python.
I have seen Autodesk Dynamo (which use IronPython) can open xls with Microsoft.Office.Interop.Excel related codes. Hence I tried to do similar thing in PyCharm for testing pur... | Microsoft.Office.Interop.Excel Workbook has no Open method in python | I know there is other ways or modules to read/write xls with python.
I have seen Autodesk Dynamo (which use IronPython) can open xls with Microsoft.Office.Interop.Excel related codes. Hence I tried to do similar thing in PyCharm for testing purpose. However, some error pops.
I pick a computer that installed KMSpico f... | [
"while looking for a solution I encountered your unanswered question.\nI needed to fill some gaps with try and error solutions. Anyway it worked ... --somehow--, and the reason was the return types of the generic type <class 'System.__ComObject'>. I think some of mapping-magic inside pythonnet doesn't go well here.... | [
1
] | [] | [] | [
"excel",
"python"
] | stackoverflow_0070485108_excel_python.txt |
Q:
FastAPI with integrated websocket client freezes, how should i combine those?
I am currently using FastAPI for a small backend. The REST Api part works without any problems. In the next step I would need to query a websocket API and process it in FastAPI. I would like to filter and forward the incoming data. When ... | FastAPI with integrated websocket client freezes, how should i combine those? | I am currently using FastAPI for a small backend. The REST Api part works without any problems. In the next step I would need to query a websocket API and process it in FastAPI. I would like to filter and forward the incoming data. When I start the application, the websocket client starts running, but the actual FastAP... | [
"I faced the same issue and haven't found a solution online. The solution I came up with looks stupid but works.\nimport asyncio\n# websocket endpoint / RX thread\n@app.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n await websocket.accept()\n\n ws_tx_thread = Thread(target=websocket... | [
0
] | [] | [] | [
"fastapi",
"multithreading",
"python",
"websocket"
] | stackoverflow_0067150524_fastapi_multithreading_python_websocket.txt |
Q:
Celery worker_ready.connect signal not working properly
I have a FastApi Mongo Celery app, Using Beanie as my odm and creating a new thread that runs an event loop for async tasks inside the celery worker.
The issue is that any ressources initilization i am putting inside the @worker_ready.connect signal is not av... | Celery worker_ready.connect signal not working properly | I have a FastApi Mongo Celery app, Using Beanie as my odm and creating a new thread that runs an event loop for async tasks inside the celery worker.
The issue is that any ressources initilization i am putting inside the @worker_ready.connect signal is not available in the global scope of the application
Code :
@worker... | [
"After long investigations, it turns out that the celery worker signal is run only inside one process (The master process), i answered similar question to one of my old questions here\nTLDR :\n\nthe Signals do not run on all spawned processes by prefork\nIn case you're working with cpu bound tasks use custom Task c... | [
0
] | [] | [] | [
"celery",
"python"
] | stackoverflow_0074139036_celery_python.txt |
Q:
How do I fix my collab notebook always updating a numpy array regardless of my if conditions?
I am using collab for a perceptron problem, and am trying to record the best set of values found so far. I used the following relevant code:
if errors_[i] <= besterrors:
besterrors = errors_[i]
... | How do I fix my collab notebook always updating a numpy array regardless of my if conditions? | I am using collab for a perceptron problem, and am trying to record the best set of values found so far. I used the following relevant code:
if errors_[i] <= besterrors:
besterrors = errors_[i]
Wbest = W
bestiteration = i+1
Where W is the current array I am using. When ... | [
"Use .copy() method:\nif errors_[i] <= besterrors: \n besterrors = errors_[i] \n Wbest = W.copy()\n bestiteration = i+1 \n\n"
] | [
1
] | [] | [] | [
"arrays",
"google_colaboratory",
"numpy",
"perceptron",
"python"
] | stackoverflow_0074155118_arrays_google_colaboratory_numpy_perceptron_python.txt |
Q:
flask_sqlalchemy : .commit() not updating object in production environnement
I am building a website with flask and python.
I finished developing it, but now that I am trying to deploy it changes to the database are not done consistently.
For example, when I try to update an object it doesn't change in the databas... | flask_sqlalchemy : .commit() not updating object in production environnement | I am building a website with flask and python.
I finished developing it, but now that I am trying to deploy it changes to the database are not done consistently.
For example, when I try to update an object it doesn't change in the database every time. The same code does exactly what it should while running in developme... | [
"I found out how to solve this issue.\nYou need to merge your changed object in the session before committing.\nobject.some_property = 'some diffrent value'\ndb.session.merge(object)\ndb.session.commit()\n\nNot sure why this is needed only in production tho\n"
] | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0074155178_python_sqlalchemy.txt |
Q:
Using find_all in bs4
When I parse for more than 1 class I get an error on line 12 (when I add all to find)
Error: ResultSet object has no attribute 'find'. You're probably treating a list of elements like a single element
import requests
from bs4 import BeautifulSoup
heroes_page_list=[]
url = f'https://dota2.fa... | Using find_all in bs4 | When I parse for more than 1 class I get an error on line 12 (when I add all to find)
Error: ResultSet object has no attribute 'find'. You're probably treating a list of elements like a single element
import requests
from bs4 import BeautifulSoup
heroes_page_list=[]
url = f'https://dota2.fandom.com/wiki/Dota_2_Wiki'... | [
"You are searching a tag inside a list of div tags you need to do like this,\nheroes = soup.find_all('div', class_= 'heroentry')\na_tags = [hero.find('a') for hero in heroes]\nfor a_tag in a_tags:\n hero_url = a_tag.get('href')\n heroes_page_list.append(\"https://dota2.fandom.com\" + hero_url)\n\nheroes_page_... | [
2,
0
] | [] | [] | [
"beautifulsoup",
"parsing",
"python",
"request"
] | stackoverflow_0074155039_beautifulsoup_parsing_python_request.txt |
Q:
Modify data cell of table with condition in Jinja
I have made a page that shows a table with two columns: Users and their Points.
I want to make bold the data cell that has the name of the User session. The table is made in a Jinja for loop. So I created a .bold class in CSS and a condition inside the loop. But it... | Modify data cell of table with condition in Jinja | I have made a page that shows a table with two columns: Users and their Points.
I want to make bold the data cell that has the name of the User session. The table is made in a Jinja for loop. So I created a .bold class in CSS and a condition inside the loop. But it doesn't work at all.
I am very new at code so I am sor... | [
"Thank you all for your answers.\nIt finally worked!\nI followed the advice of RodrigoCava and Maiels and got it. It was an issue with the database query and also I was putting {{ }} where I shouldn't.\nThis is the final code:\ndef index():\n if request.method == 'GET':\n\n user = session['user_id']\n ... | [
1
] | [] | [] | [
"html",
"jinja2",
"python"
] | stackoverflow_0074154578_html_jinja2_python.txt |
Q:
unexpected behaviour when overwriting with +=
it stores the value in 'x' correctly sometimes. Is line order_sum_inputs = order_sum_inputs/10 the culprit? I expect it to overwrite order_sum_inputs = get_inputs() when it comes out of the while loop, but I don't know if it is.
import random
my_inputs = []
for _ in r... | unexpected behaviour when overwriting with += | it stores the value in 'x' correctly sometimes. Is line order_sum_inputs = order_sum_inputs/10 the culprit? I expect it to overwrite order_sum_inputs = get_inputs() when it comes out of the while loop, but I don't know if it is.
import random
my_inputs = []
for _ in range(1000):#random list of numbers
my_list = ran... | [
"You only set order_sum_inputs once outside the loop and then just replace it inside the loop. There is no overwrite since the get_inputs() is outside the loop\n order_sum_inputs = get_inputs() --<< do it once, not executed again\n while order_sum_inputs >= 10: --<< then enters the loop\n if order_sum_inputs/1... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074154673_python.txt |
Q:
I am not able to insert values into a mysql table using python
Here's the code:
a1 = input('Index : ')
b1 = input('Name : ')
c1 = input('job : ')
sql3 = 'Insert into data(index,name,job) values(%s, %s, %s)'
val3 = [a1,b1,c1]
cursor.execute(sql3,val3)
mydb.commit()
for x in cursor:
p... | I am not able to insert values into a mysql table using python | Here's the code:
a1 = input('Index : ')
b1 = input('Name : ')
c1 = input('job : ')
sql3 = 'Insert into data(index,name,job) values(%s, %s, %s)'
val3 = [a1,b1,c1]
cursor.execute(sql3,val3)
mydb.commit()
for x in cursor:
print(x)
I have entered the values as follows:
a=3
b=sam
c=singer
An... | [
"For executemany val3 should be a list of list, like this\nsql3 = 'INSERT INTO data(index,name,phone_no) VALUES (%s, \"%s\", \"%s\")'\nval3 = [[a1,b1,c1]] # val shoul be a list of list\ncursor.executemany(sql3,val3)\n\nIf you have one set of values I would suggest to use cursor.execute,\nsql3 = f'INSERT INTO data (... | [
2
] | [] | [] | [
"mysql",
"mysql_python",
"python"
] | stackoverflow_0074155155_mysql_mysql_python_python.txt |
Q:
Opencv: AttributeError: module 'cv2' has no attribute 'dnn'
I am just starting with computer vision. While running code I got the following error.
[INFO] loading model...
Traceback (most recent call last):
File "detect_faces_video.py", line 24, in
net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model... | Opencv: AttributeError: module 'cv2' has no attribute 'dnn' | I am just starting with computer vision. While running code I got the following error.
[INFO] loading model...
Traceback (most recent call last):
File "detect_faces_video.py", line 24, in
net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])
AttributeError: module 'cv2' has no attribute 'dnn'
I believe... | [
"I got it to work by making another virtual environment. Then Installing the latest version of opencv.\n$ mkvirtualenv cv\n$ sudo pip3 install opencv-contrib-python\n",
"Similar to other answers, I've had multiple successes (for reasons I'm not sure of) by just uninstalling opencv and re-installing in the exact s... | [
19,
0
] | [] | [] | [
"computer_vision",
"opencv",
"python"
] | stackoverflow_0052575800_computer_vision_opencv_python.txt |
Q:
How to cut, copy, paste, delete data from excel sheet without hampering cell formatting
Magicians out there....
I need your help with the best approaches for the below use case.
I have an excel sheet whith lakhs of rows of data and I need to filter it based on some criteria and need to create new multiple tiles.
I... | How to cut, copy, paste, delete data from excel sheet without hampering cell formatting | Magicians out there....
I need your help with the best approaches for the below use case.
I have an excel sheet whith lakhs of rows of data and I need to filter it based on some criteria and need to create new multiple tiles.
I am in no mood to do it manually hence started working out on a python script that will do th... | [
"This should do the trick. You can change the colors of the headers.\nCode for custom styling of the excel added.\nimport pandas as pd\n\n# function to style the dataframe with some conditons (simple condition for an example you can change or add conditions with multiple rows)\ndef style_df(row):\n values = pd.S... | [
1
] | [] | [] | [
"excel",
"openpyxl",
"pandas",
"python",
"xlsxwriter"
] | stackoverflow_0074154742_excel_openpyxl_pandas_python_xlsxwriter.txt |
Q:
Python - Removing multiline comments from a list
I have a list of data:
data = ['value', '"""', 'Comment 1st row', 'Comment 2nd row', 'Comment 3rd row', '"""', 'another value']
I would like to remove the whole comment from the list, including docstrings. Also not just once, but everytime a comment appears.
Could ... | Python - Removing multiline comments from a list | I have a list of data:
data = ['value', '"""', 'Comment 1st row', 'Comment 2nd row', 'Comment 3rd row', '"""', 'another value']
I would like to remove the whole comment from the list, including docstrings. Also not just once, but everytime a comment appears.
Could someone help?
| [
"You can use a simple loop with a flag that alternates every time a \"\"\" is found:\ndata = ['value', '\"\"\"', 'Comment 1st row', 'Comment 2nd row',\n 'Comment 3rd row', '\"\"\"', 'another value']\n\nflag = True\nout = []\nfor v in data:\n if v == '\"\"\"':\n flag = not flag # invert the flag's ... | [
3,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074150425_python.txt |
Q:
How to use Django json_script in a for loop
Let's say we have in a template a table like
{% for object in object_list %}
<tr>
<td id="id-{{object.id}}">{{ object.id }}</td>
</tr>
{% endfor %}
I'm thinking of using object.id for events, like onclick, to know exactly which object.id was used.
How do you... | How to use Django json_script in a for loop | Let's say we have in a template a table like
{% for object in object_list %}
<tr>
<td id="id-{{object.id}}">{{ object.id }}</td>
</tr>
{% endfor %}
I'm thinking of using object.id for events, like onclick, to know exactly which object.id was used.
How do you use json_script to get the object.id in a JavaSc... | [
"In the case of the question we have a table and we want to have a button to copy the object.id to use in JavaScript.\nThere are various ways to do that and json_script is not one of them.\nAs noted by Abdul Aziz Barkat\n\njson_script will end up giving you things like <script id=\"id-you-passed\" type=\"applicatio... | [
2
] | [] | [] | [
"django",
"django_templates",
"javascript",
"python"
] | stackoverflow_0074154267_django_django_templates_javascript_python.txt |
Q:
How to handle BC (Before Christ) dates between PostgreSQL & Python via psycopg?
I understand that PostgreSQL has a larger date range allowing it to store BC dates, whereas Python goes to minimum year 1. What is a good way to insert/select such dates from PostgreSQL using psycopg? I'm wondering if I should just sto... | How to handle BC (Before Christ) dates between PostgreSQL & Python via psycopg? | I understand that PostgreSQL has a larger date range allowing it to store BC dates, whereas Python goes to minimum year 1. What is a good way to insert/select such dates from PostgreSQL using psycopg? I'm wondering if I should just store the year as a smallint (signed 2 byte int) in a separate column & "date&month" as ... | [
"Considering that in python the smallest year number allowed in a date or datetime object.MINYEAR is 1 and the largest year number allowed in a date or datetime object.MAXYEAR is 9999.\nAnd in PostgreSQL timestamp data type range goes from 4713 BC to 294276 AD with a 1 microsecond resolution, then all dates and dat... | [
1
] | [] | [] | [
"postgresql",
"psycopg2",
"psycopg3",
"python"
] | stackoverflow_0074153937_postgresql_psycopg2_psycopg3_python.txt |
Q:
Python break statement not function
I am a beginner at python and have been stuck on a line of code for a while now and am unsure how to fix it.
The program requests user input, a HEX value and then converts this to a RGB value. I perform error checking to ensure that the input is a HEX value. However, when I inpu... | Python break statement not function | I am a beginner at python and have been stuck on a line of code for a while now and am unsure how to fix it.
The program requests user input, a HEX value and then converts this to a RGB value. I perform error checking to ensure that the input is a HEX value. However, when I input FEEZ00 it doesn't recognize that the ch... | [
"You can use regex with re module:\n>>> import re\n>>> HEX = re.compile(r'(?:[\\dA-F]){6}')\n>>> bool(HEX.match('FEEA00'))\nTrue\n>>> bool(HEX.match('FEEZ00'))\nFalse\n\n",
"break is not allowed outside of a loop. In your example, you're using it in an if statement, which should throw an error (so I'm not sure ho... | [
1,
1,
1
] | [
"Using not in string/list repeatedly is inefficient.\nYou should use set operations:\nhexChars = set('0123456789ABCDEF')\n\ndef validate(s, size=6):\n return len(s) == size and hexChars >= set(s)\n\nif not (validate(rgb1) and validate(rgb2)):\n # do something\n\nIf many inputs to validate:\nif not all(map(val... | [
-1
] | [
"break",
"python"
] | stackoverflow_0074155036_break_python.txt |
Q:
Pandas dataframe row operation with a condition
I have a dataframe with information about a stock that looks like this:
Product ID
Initial stock
Initial unit cost
Reference
Quantity
Unit cost
Current stock
a
5
22
Purch.
4
24
9
a
5
22
Purch.
8
21
17
a
5
22
Sale
-4
25
13
a
5
22
Purch.
10
20
23
a
5
22
Sale
-15
... | Pandas dataframe row operation with a condition | I have a dataframe with information about a stock that looks like this:
Product ID
Initial stock
Initial unit cost
Reference
Quantity
Unit cost
Current stock
a
5
22
Purch.
4
24
9
a
5
22
Purch.
8
21
17
a
5
22
Sale
-4
25
13
a
5
22
Purch.
10
20
23
a
5
22
Sale
-15
22
8
b
14
3.5
Sale
10
4
4
b
14
3.5
Purc... | [
"You may create a function and call it using apply in a groupby dataframe.\nI would try something like this\ndef calc_wac(df_):\n df_ = df_.copy()\n cs_wac = 0\n for counter, row in enumerate(df_.iterrows()):\n idx,row = row\n if counter==0:\n if row['Reference'] == 'Purch.':\n cs_wac += row['I... | [
2,
0
] | [] | [] | [
"group_by",
"if_statement",
"pandas",
"python"
] | stackoverflow_0074153974_group_by_if_statement_pandas_python.txt |
Q:
AWS Lambda /bin/sh: which: command not found - Python Subprocess
I get this error when running subprocess.call('where gcc', shell=True) in my Lambda Function.
/bin/sh: which: command not found
Any ideas?
Thanks!
A:
Just to confirm, @Barmar is correct:
type gcc works in my lambda function where which gcc did not... | AWS Lambda /bin/sh: which: command not found - Python Subprocess | I get this error when running subprocess.call('where gcc', shell=True) in my Lambda Function.
/bin/sh: which: command not found
Any ideas?
Thanks!
| [
"Just to confirm, @Barmar is correct:\ntype gcc works in my lambda function where which gcc did not work.\nThanks!\n"
] | [
0
] | [] | [] | [
"aws_lambda",
"python",
"subprocess"
] | stackoverflow_0074132013_aws_lambda_python_subprocess.txt |
Q:
Pyomo: Weird results for a simple 'Transportation theory' problem
I'm trying to solve the classical 'Transportation theory' to optimize the production and transportation of goods from 4 factories to 4 distribution centers, through 2 weeks.
There are:
4 max capacities in each factory (items/week), the same ones fo... | Pyomo: Weird results for a simple 'Transportation theory' problem | I'm trying to solve the classical 'Transportation theory' to optimize the production and transportation of goods from 4 factories to 4 distribution centers, through 2 weeks.
There are:
4 max capacities in each factory (items/week), the same ones for the 2 weeks
4x4 transportation costs from each factory to each distri... | [
"The answer returned by GLPK (and then Pyomo) is correct (insomuch as it matches the data in your example).\nThe reason that the \"years\" are different is due to degeneracy in your model formulation: any allocation of production to factories that assigns 1000 units (of any product) to Factory A1, 1000 units to Fac... | [
1
] | [] | [] | [
"optimization",
"pyomo",
"python"
] | stackoverflow_0074150708_optimization_pyomo_python.txt |
Q:
Python multiprocessing won't stop running and seems to take much longer
I'm trying to use multiprocessing to speed up some data labeling that I'm doing, but have noticed that it takes much longer (I actually never saw the program terminate). The original script takes about 7 hours to run, but this morning I came t... | Python multiprocessing won't stop running and seems to take much longer | I'm trying to use multiprocessing to speed up some data labeling that I'm doing, but have noticed that it takes much longer (I actually never saw the program terminate). The original script takes about 7 hours to run, but this morning I came to work and noticed it was still running after I had let it run yesterday even... | [
"Did you think about another algorithm?\nThree ideas:\n\nnot iterating over a dataframe but rather search through combined text. This search has been optimized and studied for dozens of years so should be quite fast and hopefully well implemented in python re library. However, not to add labels that appeared becaus... | [
0,
0
] | [] | [] | [
"multiprocessing",
"pandas",
"python"
] | stackoverflow_0074147782_multiprocessing_pandas_python.txt |
Q:
How to get application name from python?
In Wondows7 64.
I want to get application name from python.
here is code that I can get Processes name,but it's not I want.
from psutil import process_iter
process = filter(lambda p: p.name() == "main2.exe", process_iter())
A:
On Windows, you could make a system call:
imp... | How to get application name from python? | In Wondows7 64.
I want to get application name from python.
here is code that I can get Processes name,but it's not I want.
from psutil import process_iter
process = filter(lambda p: p.name() == "main2.exe", process_iter())
| [
"On Windows, you could make a system call:\nimport subprocess\ncmd = 'WMIC PROCESS get Caption'\nproc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)\nfor line in proc.stdout:\n print line\n\nYou could also get the 'Commandline' or 'Processid' if the 'Caption' isn't enough.\n",
"Maybe you mean this... | [
2,
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0045627730_python_windows.txt |
Q:
Gtk TreeView : Connect to double-clicked item / row
I have this Gtk.TreeView()
treeview = Gtk.TreeView(model=liststore)
And I get the selected item like this:
selected_playlist_item = treeview.get_selection()
selected_playlist_item.connect("changed", self.on_selected_playlist_item)
And here is the on_selected_pl... | Gtk TreeView : Connect to double-clicked item / row | I have this Gtk.TreeView()
treeview = Gtk.TreeView(model=liststore)
And I get the selected item like this:
selected_playlist_item = treeview.get_selection()
selected_playlist_item.connect("changed", self.on_selected_playlist_item)
And here is the on_selected_playlist_item callback
def on_selected_playlist_item(self, ... | [
"I got the answer:\nConnect the TreeView itself (not the row / selection like I was doing) to the row-activated signal:\nself.treeview.connect(\"row-activated\", self.cb)\n\n(Click click / Return)\ndef cb(self, tree_view, path, column):\n print(\"Selected!!\")\n\n"
] | [
0
] | [] | [] | [
"gtk3",
"gtktreeview",
"python"
] | stackoverflow_0074147823_gtk3_gtktreeview_python.txt |
Q:
How to insert NULL into Snowflake string column with pandas?
I am using the pandas_tools package to write data to my Snowflake table.
create table TEST_TBL(
ID integer,
VALUE string
)
import pandas as pd
from snowflake.connector import pandas_tools as pt
df = pd.DataFrame(data={'ID': [1, 2],
... | How to insert NULL into Snowflake string column with pandas? | I am using the pandas_tools package to write data to my Snowflake table.
create table TEST_TBL(
ID integer,
VALUE string
)
import pandas as pd
from snowflake.connector import pandas_tools as pt
df = pd.DataFrame(data={'ID': [1, 2],
'VALUE': ['test', None]
})
# a... | [
"Your code appears to be correct.\nimport snowflake.connector\nimport pandas as pd\nfrom snowflake.connector import pandas_tools as pt\n\nconn = snowflake.connector.connect(**connection_parameters)\ncursor = conn.cursor()\ndatabase = connection_parameters['database']\nschema = connection_parameters['schema']\ntable... | [
1
] | [] | [] | [
"pandas",
"python",
"snowflake_cloud_data_platform"
] | stackoverflow_0074147956_pandas_python_snowflake_cloud_data_platform.txt |
Q:
How to efficiently perform many replacements of values in a large Pandas dataframe (Python)
How do I check whether the row values is matching some conditions and modify the values?
For example, if value1 and value2 are matched with the conditions, then I change them by another value.
I am using this method:
df['co... | How to efficiently perform many replacements of values in a large Pandas dataframe (Python) | How do I check whether the row values is matching some conditions and modify the values?
For example, if value1 and value2 are matched with the conditions, then I change them by another value.
I am using this method:
df['column'] = df['column'].replace(['matching1', 'matching2'], 'value1')
df['column'] = df['column'].r... | [
"I can think of two options. I think both are more efficient than repeating replace, in terms of the number of scans. (Not benchmarked, though.)\nLet's assume that we want to change 'Apple' and 'Orange' into 'value1', and 'Lemon' into 'value2'.\nreplace with dict\ndf = pd.DataFrame(['Apple','Apple','Orange','Lemon'... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074153556_pandas_python.txt |
Q:
py xmlschema: element * at * is not an element of the schema
My simplified xsd/xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" vc:minVersion="1.1">
<xs:element ... | py xmlschema: element * at * is not an element of the schema | My simplified xsd/xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" vc:minVersion="1.1">
<xs:element name="modal" />
</xs:schema>
<?xml version="1.0" encoding="UTF-8"... | [
"The error is not relative to the filepaths but to the vc:minVersion=\"1.1\" present in your xmlschema that succeeds if the XSD version supported by the processor is greater than or equal to your vc:minVersion, in this case 1.1.\nIn your case it fails because the default xmlschema guarantees just the XSD 1.0 suppor... | [
1
] | [] | [] | [
"python",
"xml",
"xmlschema",
"xsd"
] | stackoverflow_0074152969_python_xml_xmlschema_xsd.txt |
Q:
Adding existing contacts to outlook distribution list in Python
I want to use python to add contacts to an existing distribution list (DL). I am using below code which stores the member's email address of the DL to an array. I am able to achieve this by the below code.
import win32com.client
outlook = win32com.cli... | Adding existing contacts to outlook distribution list in Python | I want to use python to add contacts to an existing distribution list (DL). I am using below code which stores the member's email address of the DL to an array. I am able to achieve this by the below code.
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
address_list... | [
"Can't easily do that using Outlook Object Model - DistListItem only exposes AddMember/AddMembers methods, which take a Recipient or Recipients objects respectively. This means you can only pass Recipients collection from an existing message (MailItem.Recipients) or from an address book dialog (SelectNamesDialog.Re... | [
1
] | [] | [] | [
"distribution_list",
"outlook",
"python",
"win32com"
] | stackoverflow_0074147479_distribution_list_outlook_python_win32com.txt |
Q:
Django - Default value based on another model field
This is my existing django model
class Account(models.Model):
env = CharField(max_length=10)
now I need to add period field to my model based on the value of the env field in model. I can get the period value based on the env from following dict in my settin... | Django - Default value based on another model field | This is my existing django model
class Account(models.Model):
env = CharField(max_length=10)
now I need to add period field to my model based on the value of the env field in model. I can get the period value based on the env from following dict in my settings file
mydict = {
'dev':1,
'prd':2
}
How do I a... | [
"You can make a custom migration after running makemigrations, you open the migration file created and add a function like this\nfrom django.db import migrations\n\ndef set_default_value(apps, schema_editor):\n Account = apps.get_model(\"YOURAPPNAME\", \"Account\")\n for account in Account.objects.all():\n ... | [
1,
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0074153098_django_django_models_python.txt |
Q:
Extracting specific rows by reading the large csv file in chunks and using the same header present in another csv file
I have 2 files, file1.csv and a large csv called master_file.csv. They have several columns and have a common column name called EMP_Code.
file1 example:
EMP_name
EMP_Code
EMP_dept
a
s283
abc
b... | Extracting specific rows by reading the large csv file in chunks and using the same header present in another csv file | I have 2 files, file1.csv and a large csv called master_file.csv. They have several columns and have a common column name called EMP_Code.
file1 example:
EMP_name
EMP_Code
EMP_dept
a
s283
abc
b
f367
xyz
d
c264
abc
master_file.csv example:
|EMP_name | EMP_age | EMP_Service | EMP_Code | EMP_dept |
|:-----... | [
"One solution is to use the built-in csv library for better memory handling. Although it prevents the out-of-memory issue, it might take some time to complete due to using for loop to scan the rows one by one.\nAssuming these two sample files:\nfile1.csv:\nEMP_name,EMP_Code,EMP_dept\na,s283,abc\nb,f367,xyz\nd,c264,... | [
1
] | [] | [] | [
"csv",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074155263_csv_dataframe_pandas_python.txt |
Q:
is there any way of making a app in tkinter that always reads a image and shows it in the window
so basically i want to make a app that reads a image every 100ms and shows it every time it reads it in python tkinter. i tried all the tutorials.
i tried this but still does not work:
from tkinter import ttk
from PIL ... | is there any way of making a app in tkinter that always reads a image and shows it in the window | so basically i want to make a app that reads a image every 100ms and shows it every time it reads it in python tkinter. i tried all the tutorials.
i tried this but still does not work:
from tkinter import ttk
from PIL import Image, ImageTk
win=Tk()
win.geometry("700x700")
def update_image():
canvas.itemconfig(image_... | [
"Could you please share the error and full traceback? It helps us to debug. But for now, you haven't imported tkinter. Also, don't use from tkinter import *. It may cause name clashes and you don't know which module you used the methods from while using multiple modules. This question is a duplicate of this\n"
] | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074129075_python_tkinter.txt |
Q:
StringVar not updating
This question has been popping up a few times here on SO. I notice that most are dead because there is no minimal working example included so I have included that this time.
The other thing that happens a lot, seemingly, is multiple Tk instances, so I did my best to keep it to one.
The probl... | StringVar not updating | This question has been popping up a few times here on SO. I notice that most are dead because there is no minimal working example included so I have included that this time.
The other thing that happens a lot, seemingly, is multiple Tk instances, so I did my best to keep it to one.
The problem is that I cannot update t... | [
"self.label = ttk.Label(self, text=parent.shared_data.get())\n\nThis will set the label's text to the text currently in shared_data, but it won't update it when the textvariable changes later.\nTry using the textvariable argument instead.\nself.label = ttk.Label(self, textvariable=parent.shared_data)\n\n",
"Try t... | [
3,
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074155347_python_tkinter.txt |
Q:
Accepting cookies with selenium, can't find element
I'm trying to gather some information from transfermarkt with a scraper, but when I open the page with a bot I always get a huge prompt to accept cookies. I've tried finding the element for the accept button by copying the full xpath, copying the relative xpath, ... | Accepting cookies with selenium, can't find element | I'm trying to gather some information from transfermarkt with a scraper, but when I open the page with a bot I always get a huge prompt to accept cookies. I've tried finding the element for the accept button by copying the full xpath, copying the relative xpath, and using '//button[@title="ACCEPTEER ALLE"]', but it can... | [
"It is inside an iframe, try the below code, its working:\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nWebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it(driver.find_element(By.CSS_SELECTOR, \"iframe#sp_message_i... | [
2,
0
] | [] | [] | [
"html",
"python",
"selenium"
] | stackoverflow_0074155111_html_python_selenium.txt |
Q:
Split a list into list of lists based on modulus of index in Python
I'd like to write elements of lists to alternating files, and figured I would process the list before.
With a list of strings where the order is important, like ordered_favorite_colors =["red", "blue", "green", "hazel"], and variable number of fil... | Split a list into list of lists based on modulus of index in Python | I'd like to write elements of lists to alternating files, and figured I would process the list before.
With a list of strings where the order is important, like ordered_favorite_colors =["red", "blue", "green", "hazel"], and variable number of files number_of_files, I'd like to partition the list into multiple lists so... | [
"l = [0, 1, 2, 3, 4, 5, 6]\n\nsize = 3\nres = [l[i::size] for i in range(size)]\n\n"
] | [
3
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0074155496_list_comprehension_python.txt |
Q:
Python folium - if for popup doesn't work as expected
I would like to customize one of my variables by styling it with a different color.
I tried to make the IF statement, but unfortunately, it doesn't work as expected.
df = pd.read_csv("or_geo.csv")
fo=folium.FeatureGroup(name="OR",overlay = True)
for i,row ... | Python folium - if for popup doesn't work as expected | I would like to customize one of my variables by styling it with a different color.
I tried to make the IF statement, but unfortunately, it doesn't work as expected.
df = pd.read_csv("or_geo.csv")
fo=folium.FeatureGroup(name="OR",overlay = True)
for i,row in df.iterrows():
lat =df.at[i, 'lat']
lng = df.at[... | [
"This is achieved by adding the variable of the result of the decision to the popup at the beginning of the loop process instead of making a conditional decision in the folium settings. Since no data was presented, I created the code by quoting sample data from other visualization libraries. And the group name need... | [
1
] | [] | [] | [
"folium",
"python"
] | stackoverflow_0074154826_folium_python.txt |
Q:
How to avoid nested for loops in NumPy?
I have this code.
n_nodes = len(data_x)
X = np.zeros((n_nodes, n_nodes))
for i in range(n_nodes):
for j in range(n_nodes):
X[i, j] = data_x[i] ** j
I want to do the same task with no loops used at all. How can I do that with NumPy functions?
A:
You can do this in o... | How to avoid nested for loops in NumPy? | I have this code.
n_nodes = len(data_x)
X = np.zeros((n_nodes, n_nodes))
for i in range(n_nodes):
for j in range(n_nodes):
X[i, j] = data_x[i] ** j
I want to do the same task with no loops used at all. How can I do that with NumPy functions?
| [
"You can do this in one step with numpy.power.outer:\nnp.power.outer(data_x, np.arange(len(data_x)))\n\n",
"I'd suggest\ndata_x[:,None]**np.arange(n_nodes)\n\nA check\nIn [17]: data_x = np.array((3,5,7,4,6))\n ...: n_nodes = len(data_x)\n ...: X = np.zeros((n_nodes, n_nodes))\n ...: \n ...: for i in r... | [
3,
3,
2
] | [] | [] | [
"nested_loops",
"numpy",
"python"
] | stackoverflow_0074155199_nested_loops_numpy_python.txt |
Q:
multidimensional jax.isin()
i am trying to filter an array of triples.
The criterion by which I want to filter is whether another array of triples contains at
least one element with the same first and third element. E.g
import jax.numpy as jnp
array1 = jnp.array(
[
[0,1,2],
[1,0,2],
[0,3,3],
[3,0... | multidimensional jax.isin() | i am trying to filter an array of triples.
The criterion by which I want to filter is whether another array of triples contains at
least one element with the same first and third element. E.g
import jax.numpy as jnp
array1 = jnp.array(
[
[0,1,2],
[1,0,2],
[0,3,3],
[3,0,1],
[0,1,1],
[1,0,3],
... | [
"You can do this by reducing over a broadcasted equality check:\nimport jax.numpy as jnp\narray1 = jnp.array(\n [\n [0,1,2],\n [1,0,2],\n [0,3,3],\n [3,0,1],\n [0,1,1],\n [1,0,3],\n ]\n)\narray2 = jnp.array([[0,1,2],[0,3,2]]) # note adjustment to match first entry of array1\n\nmask = (array1[:,... | [
2
] | [] | [] | [
"jax",
"python",
"set"
] | stackoverflow_0074154196_jax_python_set.txt |
Q:
Dataflow BigQuery to BigQuery
I am trying to create a dataflow script that goes from BigQuery back to BigQuery. Our main table is massive and breaks the extraction capabilities. I'd like to create a simple table (as a result of a query) containing all the relevant information.
The SQL query 'Select * from table.or... | Dataflow BigQuery to BigQuery | I am trying to create a dataflow script that goes from BigQuery back to BigQuery. Our main table is massive and breaks the extraction capabilities. I'd like to create a simple table (as a result of a query) containing all the relevant information.
The SQL query 'Select * from table.orders where paid = false limit 10' i... | [
"Running daily: https://cloud.google.com/blog/big-data/2016/04/scheduling-dataflow-pipelines-using-app-engine-cron-service-or-cloud-functions\nTesting - you can try running against a smaller data set to test it. If you are running user code (not just read / write) you can test by using data from a file and checking... | [
0,
0
] | [] | [] | [
"apache_beam",
"google_bigquery",
"google_cloud_dataflow",
"python"
] | stackoverflow_0049265480_apache_beam_google_bigquery_google_cloud_dataflow_python.txt |
Q:
tkinter Problem: When an if conditional is wrong but still right?
tl,dr: An if conditional is activated when I know the condition is not TRUE.
This is probably a question about python in general, but I came across this using tkinter, so i'm sticking with that. I was trying to understand code I got from here, when ... | tkinter Problem: When an if conditional is wrong but still right? | tl,dr: An if conditional is activated when I know the condition is not TRUE.
This is probably a question about python in general, but I came across this using tkinter, so i'm sticking with that. I was trying to understand code I got from here, when I found this problem (I stripped it down to make it plain):
import tkin... | [
"I just learned that all string statements except for an empty string are considered true in python. This is true for many non-empty objects apparently. Hope I didn't waste anyones time.\n",
"In python, an object undergoes a truth testing procedure. Here is the procedure (Taken from python docs):\nTruth Testing P... | [
2,
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074155550_python_tkinter.txt |
Q:
Undo Inserting or Updating Google Sheet Automation Using OCR and Tesseract
I writed a code to scan serial numbers images and create a dataframe which i'll call it "df_sn".
And i have a google sheet where i want to change (update or insert a cell) with a chosen serial number of the df_sn dataframe.
Question for ac... | Undo Inserting or Updating Google Sheet Automation Using OCR and Tesseract | I writed a code to scan serial numbers images and create a dataframe which i'll call it "df_sn".
And i have a google sheet where i want to change (update or insert a cell) with a chosen serial number of the df_sn dataframe.
Question for action bifurcation due to my need for Inserting new row or Updating existing rows.... | [
"Thanks for the @TheMaster that gave it the \"queue\" idea.\nSo inside my if condition i inserted an append method to a queue\nundo_storage = []\n\nupdating = ['Updating', 'updating', 'update', '2']\nundo = [\"Undo\", \"undo\"]\ninserting =['inserting', 'Inserting', 'insert', '1']\n\ndesirable_action = []\n\nwhile ... | [
1
] | [] | [] | [
"google_sheets",
"google_sheets_api",
"gspread",
"pandas",
"python"
] | stackoverflow_0074129335_google_sheets_google_sheets_api_gspread_pandas_python.txt |
Q:
Train spaCy NER model from Python script (not CLI)
I am aware that training a spaCy model (say, Named Entity Recognition), requires running some commands from CLI. However, because I need to train a spaCy model inside a Vertex AI Pipeline Component (which can be simply considered as a "Pure Python script"), traini... | Train spaCy NER model from Python script (not CLI) | I am aware that training a spaCy model (say, Named Entity Recognition), requires running some commands from CLI. However, because I need to train a spaCy model inside a Vertex AI Pipeline Component (which can be simply considered as a "Pure Python script"), training a spaCy model from CLI IS NOT an option for my use ca... | [
"I'm not sure if it resolve all problems but ...\n... you can find path to source code (see print( spacy.__file__ ) ) and you can check code in __main__.py. It imports code from spacy.cli and it loads code from other files in folder spacy/cli/\nEDIT: you can also see source code on github: spacy\nEDIT: I correct s... | [
1,
1
] | [] | [] | [
"google_cloud_vertex_ai",
"python",
"spacy_3"
] | stackoverflow_0074131949_google_cloud_vertex_ai_python_spacy_3.txt |
Q:
how can I extract key value pairs from nested JSON with for loops
I have nested json in multilevel lists of dicts
Try to extract key value pairs. I can make separate listst of keys 'code_details' and of values 'url_details' with for loops. But I want to store the result as key:value pairs.
code_details = []
url_de... | how can I extract key value pairs from nested JSON with for loops | I have nested json in multilevel lists of dicts
Try to extract key value pairs. I can make separate listst of keys 'code_details' and of values 'url_details' with for loops. But I want to store the result as key:value pairs.
code_details = []
url_details = []
for item in all_content:
code_details.append(item ['cod... | [
"You can create a dict and update it in each iteration. Notice that dict values will be a lists\ncode_details = {}\n\nfor item in all_content:\n media_details = item ['media']\n # we need to clean it every iteration\n url_details = []\n for i in media_details:\n resources_details = i['resources']... | [
0
] | [] | [] | [
"dictionary",
"json",
"nested",
"python"
] | stackoverflow_0074155618_dictionary_json_nested_python.txt |
Q:
No Selenium selectors are working for me python
I understand that this question has been asked a lot in one way or another, however, I have tried finding elements on selenium with every type that I have at my disposal and it keeps giving me the error:
selenium.common.exceptions.NoSuchElementException: Message: no ... | No Selenium selectors are working for me python | I understand that this question has been asked a lot in one way or another, however, I have tried finding elements on selenium with every type that I have at my disposal and it keeps giving me the error:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element:
Am I just gr... | [
"It is an iframe.\nWebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it(driver.find_element(By.XPATH, \".//*[starts-with(@id,'ngxFrame')]\")))\n\ndriver.find_element(By.XPATH,\".//input[@type='email' and @id='xReturningUserEmail']\").send_keys(\"test@gmail.com\")\n\n"
] | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074155535_python_selenium_selenium_webdriver.txt |
Q:
Python tarfile.extract func not extracting content of directory
I'm trying to extract a directory from tarfile using python. But some/ALL of its files inside that directory are missing after extraction. Only pathname got extracted (ie, I get folder home inside /tmp/myfolder but its empty)
Code is as follwing:
for ... | Python tarfile.extract func not extracting content of directory | I'm trying to extract a directory from tarfile using python. But some/ALL of its files inside that directory are missing after extraction. Only pathname got extracted (ie, I get folder home inside /tmp/myfolder but its empty)
Code is as follwing:
for tar in tarfiles:
mytar = tarfile.open(tar)
for file in mytar:... | [
"Found a fix, by default extract only extracts path of variable, I can get content with\ntar.extractall(members=members(tar))\n\nReference:\nhttps://stackoverflow.com/a/43094365/20223973\n"
] | [
0
] | [] | [] | [
"linux",
"python",
"tarfile"
] | stackoverflow_0074129685_linux_python_tarfile.txt |
Q:
How can I avoid ElementClickInterceptedException error when webscraping a dynamic webpage in selenium python
I'm scraping tables from a webpage and using selenium to click and open a new page to scrape tables consecutivly. I get this error every now and then. The error pops up at diferent times wile i ru the code ... | How can I avoid ElementClickInterceptedException error when webscraping a dynamic webpage in selenium python | I'm scraping tables from a webpage and using selenium to click and open a new page to scrape tables consecutivly. I get this error every now and then. The error pops up at diferent times wile i ru the code but always origionates from the same line of code. Sometime I will be able to loop through 12 times and others onl... | [
"I guess you can use exception treatment to avoid code stop working.\ntry:\n #Click to chose a season\n season_tags[i].click()\nexcept Exception as e:\n print(e)\n pass\n\nHope it helps!\n"
] | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074155571_python_selenium_selenium_webdriver.txt |
Q:
how to correctly build an expression with comparison operators and brackets?
this not work well:
a = ['123','567','10', '223', '33']
for item in a:
if ('5' or '1' or '2') in item:
print(item)
I want to get any item in which there is at least one match with the numbers 1 or 2 or 5
My version is very cu... | how to correctly build an expression with comparison operators and brackets? | this not work well:
a = ['123','567','10', '223', '33']
for item in a:
if ('5' or '1' or '2') in item:
print(item)
I want to get any item in which there is at least one match with the numbers 1 or 2 or 5
My version is very cumbersome:
if '5' in item or '1' in item or '2' in item:
| [
"You can use any,\na = ['123','567','10', '223']\nfor item in a:\n if any(i in item for i in ('5','1','2')):\n print(item)\n\n"
] | [
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0074155753_algorithm_python.txt |
Q:
How to delete Pyenv
I installed Pyenv using brew and set path using
echo 'eval "$(pyenv init --path)"' >> ~/.zshrc
Now I deleted it with brew, and I got .zshrc:1: command not found: pyenv every time I opened my terminal. I understand that I need to simply remove the pyenv init invocations from my shell startup con... | How to delete Pyenv | I installed Pyenv using brew and set path using
echo 'eval "$(pyenv init --path)"' >> ~/.zshrc
Now I deleted it with brew, and I got .zshrc:1: command not found: pyenv every time I opened my terminal. I understand that I need to simply remove the pyenv init invocations from my shell startup configuration. But can someo... | [
"Assuming you have Vim installed, you can use vim ~/.zshrc to open the file and then edit it out.\n"
] | [
0
] | [] | [] | [
"pyenv",
"python"
] | stackoverflow_0074155774_pyenv_python.txt |
Q:
How to get a whole number from a list?
I have a list:
num = ['9', '9', '2', '3']
So, how do i get a number 9923, for example in a variable?
A:
num = ['9','9','2','3']
new_num = ''.join(num)
try:
new_num = int(new_num)
except ValueError as e:
print("Not a number")
A:
n = ''.join(num)
n = int(n)
print... | How to get a whole number from a list? | I have a list:
num = ['9', '9', '2', '3']
So, how do i get a number 9923, for example in a variable?
| [
"num = ['9','9','2','3']\n\nnew_num = ''.join(num)\n\ntry:\n new_num = int(new_num)\nexcept ValueError as e:\n print(\"Not a number\")\n\n",
"n = ''.join(num)\nn = int(n)\nprint(n)\n\noutput will be 9923\n",
"Using base-10 expansion.\nnum = ['9','9','2','3']\n\ndecimal_num = sum(int(c)*10**i for i, c in z... | [
4,
1,
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0074154463_algorithm_python.txt |
Q:
Compiling frames into a video with ffmpeg
I have a folder with a number of frames in which I'd like to concatenate into an mp4 file using ffmpeg. What is the correct syntax to do this in a Jupyter notebook script? I have tried:
os.system("ffmpeg -r 30 -i ./inputs/upload%00001d.png -y ./inputs/result.mp4")
The abo... | Compiling frames into a video with ffmpeg | I have a folder with a number of frames in which I'd like to concatenate into an mp4 file using ffmpeg. What is the correct syntax to do this in a Jupyter notebook script? I have tried:
os.system("ffmpeg -r 30 -i ./inputs/upload%00001d.png -y ./inputs/result.mp4")
The above runs through with no errors but does not pro... | [
"As I've stated in the comment, correct your file format to upload%05d.png and consider specifying the codec too:\ndef saveMpeg():\n os.system(\"ffmpeg -r 30 -i ./inputs/upload%05d.png -vcodec mpeg4 -y ./inputs/result.mp4\")\n\nsaveMpeg()\n\n"
] | [
0
] | [] | [] | [
"ffmpeg",
"jupyter_notebook",
"python"
] | stackoverflow_0074154548_ffmpeg_jupyter_notebook_python.txt |
Q:
How to combine multiple output lists together?
I need the code to output a list that has all the words in one list. I've googled and tried multiple methods, but nothing works. The solutions I've found output multiple lists that contain empty lists inside for example: ["Lorem ipsum dolor"]["Morbi quis dictum"][""][... | How to combine multiple output lists together? | I need the code to output a list that has all the words in one list. I've googled and tried multiple methods, but nothing works. The solutions I've found output multiple lists that contain empty lists inside for example: ["Lorem ipsum dolor"]["Morbi quis dictum"][""]["Tempus commodo"].
What I need it to output is ["Lor... | [
"Store the results in a list:\nout = []\nfor i in soup.find(class_ = \"body\").stripped_strings:\n p = repr(i)\n print(p, end=\"\")\n if i and i[0]:\n out.append(i) # or out.append(p)\n\nIf you don't need p, you can do this in one line using list comprehension:\nout = [i for i in soup.find(class_ = ... | [
1
] | [] | [] | [
"beautifulsoup",
"list",
"python"
] | stackoverflow_0074155767_beautifulsoup_list_python.txt |
Q:
How to read a json data into a dataframe using pandas
I have json data which is in the structure below:
{"Text1": 4, "Text2": 1, "TextN": 123}
I want to read the json file and make a dataframe such as
Each key value pairs will be a row in the dataframe and I need to need headers "Sentence" and "Label". I tried w... | How to read a json data into a dataframe using pandas | I have json data which is in the structure below:
{"Text1": 4, "Text2": 1, "TextN": 123}
I want to read the json file and make a dataframe such as
Each key value pairs will be a row in the dataframe and I need to need headers "Sentence" and "Label". I tried with using lines = True but it returns all the key-value pai... | [
"you can use:\nwith open('json_example.json') as json_data:\n data = json.load(json_data)\n\ndf=pd.DataFrame.from_dict(data,orient='index').reset_index().rename(columns={'index':'Sentence',0:'Label'})\n\n",
"Easy way that I remember\nimport pandas as pd\nimport json\n\nwith open(\"./data.json\", \"r\") as f:\n... | [
1,
0
] | [] | [] | [
"json",
"pandas",
"python"
] | stackoverflow_0074155568_json_pandas_python.txt |
Q:
How do I create AnnData object from a pandas data frame count matrix?
I am trying to use the Scanpy Python package to analyze some single-cell data. I read a count matrix (a .tsv file) in as a Pandas data frame, which has genes as the columns and rows as the different cells. Each row contains the counts for the di... | How do I create AnnData object from a pandas data frame count matrix? | I am trying to use the Scanpy Python package to analyze some single-cell data. I read a count matrix (a .tsv file) in as a Pandas data frame, which has genes as the columns and rows as the different cells. Each row contains the counts for the different genes for a single cell. I would like to create an AnnData object f... | [
"You can convert your DataFrame df into AnnData adata this way:\nadata = anndata.AnnData(X: df.iloc[1:,1:],\n obs: df.iloc[:,0:1],\n var: df.iloc[0:1,:])\n\nBut you don't really need to do that. Instead, directly read the tsv file into an AnnData object:\nwith open(\"yo... | [
6,
5,
1
] | [] | [] | [
"pandas",
"python",
"scanpy"
] | stackoverflow_0065117950_pandas_python_scanpy.txt |
Q:
APScheduler cannot be installed due to lib/zoneinfo_module.c:1:10: fatal error: 'Python.h' file not found on MacOS
I want to install APScheduler in a python project but I have some issues.
I tried before to install wheel but I got the same kind of errors. Even if I installed Xcode, nothing is changed
pip install A... | APScheduler cannot be installed due to lib/zoneinfo_module.c:1:10: fatal error: 'Python.h' file not found on MacOS | I want to install APScheduler in a python project but I have some issues.
I tried before to install wheel but I got the same kind of errors. Even if I installed Xcode, nothing is changed
pip install APScheduler
Collecting APScheduler
Using cached APScheduler-3.9.1-py2.py3-none-any.whl (59 kB)
Requirement already sat... | [
"The build is looking for /Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/Headers, but if you don't have full Xcode installed, this won't exist.\nYou can work around this problem by overriding the environment variable C_INCLUDE_PATH:\n…with the system Python 3 headers:\n... | [
2
] | [] | [] | [
"apscheduler",
"macos",
"python"
] | stackoverflow_0073814018_apscheduler_macos_python.txt |
Q:
Installing Odoo on Mac raises gevent error
I'm following this tutorial to install Odoo 15 on Mac, but I'm getting this error when running pip install -r requirements.txt:
Error compiling Cython file:
------------------------------------------------------------
...
cdef load_traceback
... | Installing Odoo on Mac raises gevent error | I'm following this tutorial to install Odoo 15 on Mac, but I'm getting this error when running pip install -r requirements.txt:
Error compiling Cython file:
------------------------------------------------------------
...
cdef load_traceback
cdef Waiter
cdef wait
cdef iwait
... | [
"this solved it for me:\npip install pip setuptools wheel Cython==3.0.0a10\npip install gevent==20.9.0 --no-build-isolation\n\nif some problem with psycopg2 occurs, run this: (you can change 2.8.6 to 2.8.5 depending on what you need)\nexport LDFLAGS=\"-L/opt/homebrew/opt/openssl@1.1/lib -L/opt/homebrew/opt/libpq/li... | [
1,
0
] | [] | [] | [
"cython",
"odoo",
"python"
] | stackoverflow_0073667667_cython_odoo_python.txt |
Q:
need the sum of some dictionary values if present in input
so this is my code.
while the loop is running and I input bowl it should output 8,50. next input from loop should be added to the last output, this loop has to continue until control+d is entered. anybody got some tips for me?
I'm pretty new to coding.
I'... | need the sum of some dictionary values if present in input | so this is my code.
while the loop is running and I input bowl it should output 8,50. next input from loop should be added to the last output, this loop has to continue until control+d is entered. anybody got some tips for me?
I'm pretty new to coding.
I've tried adding the output from the validated input to a new lis... | [
"You can do this, Use a flag to exit from the loop,\nmenu = {\n \"Baja Taco\": 4.00,\n \"Burrito\": 7.50,\n \"Bowl\": 8.50,\n \"Nachos\": 11.00,\n \"Quesadilla\": 8.50,\n \"Super Burrito\": 8.50,\n \"Super Quesadilla\": 9.50,\n \"Taco\": 3.00,\n \"Tortilla Salad\": 8.00\n}\n\n\ndef order(... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074155800_python.txt |
Q:
Web Scraping Python: Div classes have different values. How to overcome the situation?
I am trying to scrape the data from World Bank (https://www.worldbank.org/en/about/leadership/managers).
Requirement is to scrape the Names, Designation, Images, Biography of each manager.
I have successfully scraped the above d... | Web Scraping Python: Div classes have different values. How to overcome the situation? | I am trying to scrape the data from World Bank (https://www.worldbank.org/en/about/leadership/managers).
Requirement is to scrape the Names, Designation, Images, Biography of each manager.
I have successfully scraped the above data. But when trying to scrape the bio, by redirecting to the individual manager's page, the... | [
"To get bios about every member found on the page you can use next example:\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nurl = \"https://www.worldbank.org/en/about/leadership/managers\"\nsoup = BeautifulSoup(requests.get(url).content, \"html.parser\")\n\nfor a in soup.select('td > a[href*=\"/about/\"]'):\n ... | [
2
] | [] | [] | [
"html",
"python",
"web_scraping"
] | stackoverflow_0074151789_html_python_web_scraping.txt |
Q:
unittest - compare list irrespective of order
I am doing a unit test on two list of list values:
self.assertEqual(sale, [['1',14], ['2',5], ['3',7], ['4',1]])
But it gives the below error:
AssertionError: Lists differ: [['1', 14], ['4', 1], ['2', 5], ['3', 7]] != [['1'
, 14], ['2', 5], ['3', 7], ['4', 1]]
First ... | unittest - compare list irrespective of order | I am doing a unit test on two list of list values:
self.assertEqual(sale, [['1',14], ['2',5], ['3',7], ['4',1]])
But it gives the below error:
AssertionError: Lists differ: [['1', 14], ['4', 1], ['2', 5], ['3', 7]] != [['1'
, 14], ['2', 5], ['3', 7], ['4', 1]]
First differing element 1:
['4', 1]
['2', 5]
- [['1', 14... | [
"Since Python lists keep track of order, you'll need some way to make sure the items are in the same order. \nA set might work, if all items are unique. If they aren't unique you'll lose information on the duplicates. \nSorting the lists before you compare them will probably be your best bet. It will keep all the d... | [
5,
1
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0050091784_python_unit_testing.txt |
Q:
Do I need a class factory function when using a descriptor that require initialization?
Consider this toy example where I use a descriptor to validate that a particular value doesn't exceed certain maximum value
class MaxValidator:
def __init__(self, max=10):
self.max = max
def __set__(self, obj, v... | Do I need a class factory function when using a descriptor that require initialization? | Consider this toy example where I use a descriptor to validate that a particular value doesn't exceed certain maximum value
class MaxValidator:
def __init__(self, max=10):
self.max = max
def __set__(self, obj, value):
if value > self.max:
raise RuntimeError(f"value {value} must be sm... | [
"Don´t forget that at execution time, the descriptors method for __get__ and __set__ have access to the instance and class where they live in.\nSo, all you need is a class attribute (and even an instance attribute) to configure the behavior of your descriptor class-wide.\nThat can be done either with a fixed name,... | [
1
] | [] | [] | [
"class_factory",
"python",
"python_descriptors"
] | stackoverflow_0074141283_class_factory_python_python_descriptors.txt |
Q:
Dump a Neo4j graph in pickle format from AURADS via pGraph or iGraph
I am using Jupyter Notebook to run cypher queries via py2neo and pygds libraries. The instance is hosted on AURADS. I am not able to dump the graph from Neo4j to local computer in a pickle file to explore later.
import neo4jupyter
import pickle
... | Dump a Neo4j graph in pickle format from AURADS via pGraph or iGraph | I am using Jupyter Notebook to run cypher queries via py2neo and pygds libraries. The instance is hosted on AURADS. I am not able to dump the graph from Neo4j to local computer in a pickle file to explore later.
import neo4jupyter
import pickle
from py2neo import Graph as pGraph
from igraph import Graph as iGraph
from... | [
"It seems the easiest thing to do is to separately export nodes and relationships.\nYou can export nodes using the following query:\nMATCH (n) RETURN n\n\nand relationships\nMATCH (n)-[r]->(m)\nRETURN n,r,m\n\nSome variation of these two queries should be good. You can also take a look at APOC export functions: htt... | [
1
] | [] | [] | [
"graph",
"jupyter_notebook",
"neo4j",
"python"
] | stackoverflow_0074143255_graph_jupyter_notebook_neo4j_python.txt |
Q:
How to populate a new column in a dataframe based on multiple conditions?
I have the below code for populating my dataframe (final_df) with either a '1' or a '0' based on the year and the month columns, into a new column called 'Lockdown'.
My code is not working - is there a more efficient way to write this?
impo... | How to populate a new column in a dataframe based on multiple conditions? | I have the below code for populating my dataframe (final_df) with either a '1' or a '0' based on the year and the month columns, into a new column called 'Lockdown'.
My code is not working - is there a more efficient way to write this?
import numpy
conditions = [
(final_df['Year'] == 2020) & (final_df['Month'] ==... | [
"I take it that you are trying to calculate the lockdown months during COVID? You can do it in a couple of ways:\n# Closer to your original code\nis_lockdown = (\n (final_df[\"Year\"].eq(2020) & final_df[\"Month\"].between(3,12))\n | (final_df[\"Year\"].eq(2021) & final_df[\"Month\"].between(1,3))\n)\n\n# Con... | [
0,
0
] | [] | [] | [
"list",
"numpy",
"pandas",
"python"
] | stackoverflow_0074145837_list_numpy_pandas_python.txt |
Q:
Why am I getting this attribute error "'list' object has no attribute 'username'"?
When I try update records I get this error :
AttributeError: 'list' object has no attribute 'username'
Part of the code that's wrong :
users.username = username
app.py :
@app.route('/account', methods=['GET', 'POST'])
def account... | Why am I getting this attribute error "'list' object has no attribute 'username'"? | When I try update records I get this error :
AttributeError: 'list' object has no attribute 'username'
Part of the code that's wrong :
users.username = username
app.py :
@app.route('/account', methods=['GET', 'POST'])
def account():
if request.method == "POST":
username = request.form.get('username')
... | [
"You're POSTing only a single user with each request, you don't need to query the whole database. Just update, say the currentUser, directly by finding him/her in the db:\n@app.route('/account', methods=['GET', 'POST'])\ndef account():\n if request.method == \"POST\":\n username = request.form.get('userna... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074155960_python.txt |
Q:
How to extract a sub part of HTML code by a raw string?
I want to extract a part of HTML code I want to find a substring - <span style="color: white; background-color: blue; font-weight: bold;">abcd1234+</span></p> from the following code:
<p>This is a test. I want to find a substring - <span style="color: white; ... | How to extract a sub part of HTML code by a raw string? | I want to extract a part of HTML code I want to find a substring - <span style="color: white; background-color: blue; font-weight: bold;">abcd1234+</span></p> from the following code:
<p>This is a test. I want to find a substring - <span style="color: white; background-color: blue; font-weight: bold;">abcd1234+</span><... | [
"Regex is not a great/Suggestable tool to parse HTML. I'm just adding solution with Regex as you looking for that.\nusing bs4\nfrom bs4 import BeautifulSoup\nhtml =\"\"\"<p>This is a test. I want to find a substring - <span style=\"color: white; background-color: blue; font-weight: bold;\">abcd1234+</span></p> This... | [
1,
0
] | [] | [] | [
"html",
"python",
"string"
] | stackoverflow_0074101097_html_python_string.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.