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:
Pyinstaller is not recognized as an external or internal command, an executable program or a command file
I'm trying to compile a python program that prints "hello world !" with the Pyinstaller module. But when I type the command pyinstaller HelloWorld.pyin my command prompt, it told me "pyinstaller is not recogni... | Pyinstaller is not recognized as an external or internal command, an executable program or a command file | I'm trying to compile a python program that prints "hello world !" with the Pyinstaller module. But when I type the command pyinstaller HelloWorld.pyin my command prompt, it told me "pyinstaller is not recognized as an internal or external command, an executable program or a command file". How can I make compilation wo... | [
"Simply you can install it using pip.\npip install pyinstaller\n\nRequirements:\n\n3.7-3.11. Note that Python 3.10.0 contains a bug making it unsupportable by PyInstaller. PyInstaller will also not work with beta releases of Python 3.12.\n\nPyInstaller should work on Windows 7 or newer, but it only officially suppo... | [
0
] | [] | [] | [
"pyinstaller",
"python"
] | stackoverflow_0074499205_pyinstaller_python.txt |
Q:
Create a scatterplot from the data of two dataframes?
I have two dataframes in python. The content of them is the following:
Table=conn
A B relevance
1 3 0.7
2 7 0.1
5 20 2
6 2 7
table=point
Point Lat Lon
1 45.3 -65.2
2 34.4 -60.2
3 40.2 -60.1
20 40.4 -63.1
In the fir... | Create a scatterplot from the data of two dataframes? | I have two dataframes in python. The content of them is the following:
Table=conn
A B relevance
1 3 0.7
2 7 0.1
5 20 2
6 2 7
table=point
Point Lat Lon
1 45.3 -65.2
2 34.4 -60.2
3 40.2 -60.1
20 40.4 -63.1
In the first table, column A represents an origin, column B a destina... | [
"Do you have two DataFrames: point and conn, right?\n# To set indexes of \"point\" equal to \"Points\"\npoint.set_index(point.Point, inplace=True)\n\n# config width of lines\nmin_width = 0.5\nmax_width = 4.0\n\nmin_relevance = conn.relevance.min()\nmax_relevance = conn.relevance.max()\nslope = (max_width - min_widt... | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074496855_matplotlib_python.txt |
Q:
How to generate SQL using pandas without a database connection?
The pandas package have a method called .to_sql that help to insert the current data frame on to the database.
.to_sql doc:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html
The second parameter is con
sqlalche... | How to generate SQL using pandas without a database connection? | The pandas package have a method called .to_sql that help to insert the current data frame on to the database.
.to_sql doc:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html
The second parameter is con
sqlalchemy.engine.(Engine or Connection) or sqlite3.Connection
Is it possibl... | [
"We actually cannot print the query without a database connection, but we can use sqlalchemy create_mock_engine method and pass \"memory\" as the database URI to trick pandas, e.g:\nfrom sqlalchemy import create_mock_engine, Metadata\n\ndef dump(sql, *multiparams, **params):\n print(sql.compile(dialect=engine.di... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074478112_pandas_python.txt |
Q:
How to find the root of a function within a range in python
I need to find the alpha value in [0,1] of a linear combination alpha*Id+(1-alpha)*M, where Id is the identity matrix, M is a given matrix, such that this linear combination has given mean.
At the moment I am using scipyt.optimize.fsolve but it does not a... | How to find the root of a function within a range in python | I need to find the alpha value in [0,1] of a linear combination alpha*Id+(1-alpha)*M, where Id is the identity matrix, M is a given matrix, such that this linear combination has given mean.
At the moment I am using scipyt.optimize.fsolve but it does not admit the range [0,1] as an input. Any suggestion ?
| [
"You can define alpha using a sigmoid function:\nalpha = 1/(1+exp(-x))\n\nhttps://en.wikipedia.org/wiki/Sigmoid_function\nBased on this definition, alpha will always be in the range [0, 1]. Then, you can change the target of the optimization in scipy.optimize.fsolve to calibrate the value of x instead of alpha dire... | [
0
] | [] | [] | [
"fsolve",
"python",
"scipy"
] | stackoverflow_0074499258_fsolve_python_scipy.txt |
Q:
Regular expression to find from the end of string
I have a few strings, like:
address1 = 'Красноярский край, г Красноярск, ул Академика Вавилова, 2Д, кв. 311'
address2 = 'Москва г, ул Ольховская, 45 стр. 1, квартира 3'
address3 = 'Красноярский край, г Красноярск, ул Академика Вавилова, 2Д, квартира 311'
So I need... | Regular expression to find from the end of string | I have a few strings, like:
address1 = 'Красноярский край, г Красноярск, ул Академика Вавилова, 2Д, кв. 311'
address2 = 'Москва г, ул Ольховская, 45 стр. 1, квартира 3'
address3 = 'Красноярский край, г Красноярск, ул Академика Вавилова, 2Д, квартира 311'
So I need to cut that piece of string, which start from кв.
I us... | [
"Regular expressions usually are \"greedy\": they try to match as many characters as possible. That is what you see in your results.\nYou can make them non-greedy instead:\nflat_template = r\"кв(.*?)$\"\n\nNote the use of .*? for the non-greedy variant of .*. This will match the minum number of characters possible.... | [
1,
0
] | [] | [] | [
"python",
"qregularexpression",
"search"
] | stackoverflow_0074498977_python_qregularexpression_search.txt |
Q:
pydantic root validation get inconsistent data
I write some project on FastAPI + ormar, and there is a problem with PATCH method of my API endpoint. Briafly (without try-excepts and checks for ids), my PATCH logic is the following:
new_product_values = new_product.dict(
exclude_unset=True,
exclude_none=Tru... | pydantic root validation get inconsistent data | I write some project on FastAPI + ormar, and there is a problem with PATCH method of my API endpoint. Briafly (without try-excepts and checks for ids), my PATCH logic is the following:
new_product_values = new_product.dict(
exclude_unset=True,
exclude_none=True,
)
db_product = await Product.objects.get_or_none(... | [
"You are right, the problem stems from the fact that update calls the update_from_dict method, which just calls setattr in a loop for each key-value-pair.\nWhether or not this should be considered a bug depends on the goals behind the Pydantic integration. I am not particularly familiar with ormar. I suppose this m... | [
0
] | [] | [] | [
"fastapi",
"pydantic",
"python",
"validation"
] | stackoverflow_0074477395_fastapi_pydantic_python_validation.txt |
Q:
Python - set attributes dynamically in for loop
I have the following code:
class Test:
pass
test = Test()
for x in ["a", "b", "c"]:
test.x = x
print(test.__dict__)
{'x': 'c'}
This is not what I want. What I want is to set the name of the attribute corresponding to the value of the iteration:
Desir... | Python - set attributes dynamically in for loop | I have the following code:
class Test:
pass
test = Test()
for x in ["a", "b", "c"]:
test.x = x
print(test.__dict__)
{'x': 'c'}
This is not what I want. What I want is to set the name of the attribute corresponding to the value of the iteration:
Desired:
print(test.__dict__)
{'a': 'a', 'b': 'b', 'c'... | [
"Use setattr\nclass Test:\n pass\n\ntest = Test()\n\nfor x in [\"a\", \"b\", \"c\"]:\n setattr(test,x,x)\n \nprint(test.__dict__)\n\n"
] | [
2
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0074499396_oop_python.txt |
Q:
Get more speed in pandas Dataframe
I wrote this code to get the stock market data and after getting the data, I save it in the Mongo database, then I get the required data from the Mongo database and convert it into a dataframe.
Using the data in the rows, I calculate the values I need. This operation takes about ... | Get more speed in pandas Dataframe | I wrote this code to get the stock market data and after getting the data, I save it in the Mongo database, then I get the required data from the Mongo database and convert it into a dataframe.
Using the data in the rows, I calculate the values I need. This operation takes about 35 seconds. I need this operation to be ... | [
"Your code is slow because of all those loops. It is way outside the scope of a single question and answer to actually fix all that code, but I can tell you how to fix it:\n\nProfile each part. Break the code down into steps, perhaps into functions or just time each outer loop. This will tell you where to spend ... | [
2
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074498348_dataframe_numpy_pandas_python.txt |
Q:
I want to split into train/test my numpy array files
I have 12000 files each in .npy format. Im doing this because my images are grayscaled. Each file is (64,64). I want to know if there is a way to split into test and train to use for an Autoencoder.
(64,64) numpy image
My Autoencoder will be trained with (64,64)... | I want to split into train/test my numpy array files | I have 12000 files each in .npy format. Im doing this because my images are grayscaled. Each file is (64,64). I want to know if there is a way to split into test and train to use for an Autoencoder.
(64,64) numpy image
My Autoencoder will be trained with (64,64) images. If someone has experience with Autoencoders:
Is i... | [
"You can use sklearn's train_test_split.\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\nlist_of_images = # a list containing the paths of all your data files\n # or a numpy array of shape (12000, 64, 64)\n\ntrain_list, test_list = train_test_list(list_of_images, test_si... | [
1
] | [] | [] | [
"autoencoder",
"numpy",
"numpy_ndarray",
"python"
] | stackoverflow_0074496132_autoencoder_numpy_numpy_ndarray_python.txt |
Q:
How to fix? TypeError: argument of type 'PasswordManager' is not iterable
I keep getting the following error and I can't seem to find a solution for it.
if password not in old_passwords:
TypeError: argument of type 'PasswordManager' is not iterable
For clarity, I needed to create a class called 'PasswordManag... | How to fix? TypeError: argument of type 'PasswordManager' is not iterable | I keep getting the following error and I can't seem to find a solution for it.
if password not in old_passwords:
TypeError: argument of type 'PasswordManager' is not iterable
For clarity, I needed to create a class called 'PasswordManager'. The class should have a list called 'old_passwords'. The list contains all... | [
"I think you need to review how to use classes in python.\nYour class needs a constructor, where you can instantiate your class attributes (in your case old_passwords) and you can access them with self.\nAn example of your use case could be\nclass PasswordManager():\n \n def __init__(self):\n self.old_password... | [
2,
0
] | [] | [] | [
"class",
"list",
"methods",
"python",
"typeerror"
] | stackoverflow_0074499390_class_list_methods_python_typeerror.txt |
Q:
Keylogger but when i press esc its doesnt get out
I'm writing a keylogger. The script is nice until I press esc. But it doesn't exit. I did write a code for it but doesn't work. I tried so many options but I couldn't do it.
import pynput.keyboard
keys = []
escape = ['Esc' , 'Key.esc' , 'p' , 'Key.shift']
def on... | Keylogger but when i press esc its doesnt get out | I'm writing a keylogger. The script is nice until I press esc. But it doesn't exit. I did write a code for it but doesn't work. I tried so many options but I couldn't do it.
import pynput.keyboard
keys = []
escape = ['Esc' , 'Key.esc' , 'p' , 'Key.shift']
def on_press(letters):
global keys
keys.append(lette... | [
"You only check for escape once before you populate keys\nimport pynput.keyboard\n\nkeys = []\nescape = ['Esc' , 'Key.esc' , 'p' , 'Key.shift']\n\ndef on_press(letters):\n global keys \n keys.append(letters)\n print(letters)\n# at this point keys is empty\nfor k in keys:\n if k == escape:\n exit(... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074499445_python_python_3.x.txt |
Q:
How to use python flask to read json string
How to use pytohn module to read/filter "webserver1" that string
{
"Title":"Nginx Service"
"Instant":"[
{\"Hostname\":\"webserver1\"}
]"
}
"Title":"Nginx Service"
"Instant":"[
{\"Hostname\":\"webs... | How to use python flask to read json string | How to use pytohn module to read/filter "webserver1" that string
{
"Title":"Nginx Service"
"Instant":"[
{\"Hostname\":\"webserver1\"}
]"
}
"Title":"Nginx Service"
"Instant":"[
{\"Hostname\":\"webserver1\"}
]"
}
data = json.load(... | [
"The response depends on the inut json file, which is not clear in your post, because you haven't written a correct json. See here a json linter in order to check if a json is ok.\nOption 1: json file is a dictionary\nLet's say we have this json file as input, named myjsonfile_dict.json:\n{\n \"Title\": \"Nginx ... | [
0
] | [] | [] | [
"flask",
"json",
"python"
] | stackoverflow_0074498527_flask_json_python.txt |
Q:
How to simulate new values without normality assumption?
I have the following list:
series=[0.6, 4.1, 0.6, 6.7, 9.2, 7.6, 5.5, 0.9, 3.8, 8.4]
the mean of series is 4.74 and its np.std equals : 3.101
I want to generate 1000 observations from series so I used the following method:
>>> series_1000=np.random.normal(4... | How to simulate new values without normality assumption? | I have the following list:
series=[0.6, 4.1, 0.6, 6.7, 9.2, 7.6, 5.5, 0.9, 3.8, 8.4]
the mean of series is 4.74 and its np.std equals : 3.101
I want to generate 1000 observations from series so I used the following method:
>>> series_1000=np.random.normal(4.74, 3.101, size=(1000))
>>> series_1000
>>> array([ 3.4339521... | [
"If a uniform distribution is better suited for your needs, you can use:\n(np.random.uniform(-1, 1, size=1000) * 3.101) + 4.74\n\nOr inside a convenience function:\ndef generate_values(mean, std, size=1000):\n return(np.random.uniform(-1, 1, size=size) * std) + mean\n\n"
] | [
1
] | [] | [] | [
"montecarlo",
"normal_distribution",
"numpy",
"python",
"random"
] | stackoverflow_0074499495_montecarlo_normal_distribution_numpy_python_random.txt |
Q:
How to delete list items from list in python
I have a list with strings and super script characters(as power).
I need to concatenate scripted values with strings.
But according to my coding part It repeating same value twice.
I have no idea to remove unnecessary values from the list.
my original list -->
separate_... | How to delete list items from list in python | I have a list with strings and super script characters(as power).
I need to concatenate scripted values with strings.
But according to my coding part It repeating same value twice.
I have no idea to remove unnecessary values from the list.
my original list -->
separate_units = ['N', 'm', '⁻²⁴', 'kJ', 's', '⁻¹', 'km', '... | [
"Inside the function power_set_to_unit, you can iterate deciding whether to start a new entry in result, or append to the last element if you found an exponent:\nseparate_units = ['N', 'm', '⁻²⁴', 'kJ', 's', '⁻¹', 'km', '⁻²¹', 'kJ', '⁻²', 'm', '⁻²']\n\ndef power_set_to_unit():\n result = []\n for x in separat... | [
3,
1
] | [] | [] | [
"arraylist",
"data_science",
"python"
] | stackoverflow_0074499347_arraylist_data_science_python.txt |
Q:
Problem using numpy to obtain the complex conjugate of a matrix
I have the following code:
import numpy as np
A=np.array([[2, 2-9j, -5j], [4-1j, 0, 9+6j], [4j, 6+7j, 6]])
print(A)
print(A.getH())
It doesn't work. I have checked different webs and followed this webpage (geeksforgeeks), and this other(official nump... | Problem using numpy to obtain the complex conjugate of a matrix | I have the following code:
import numpy as np
A=np.array([[2, 2-9j, -5j], [4-1j, 0, 9+6j], [4j, 6+7j, 6]])
print(A)
print(A.getH())
It doesn't work. I have checked different webs and followed this webpage (geeksforgeeks), and this other(official numpy documentation) but I still get an error and I don't know where. Can... | [
"That's correct, a numpy array doesn't have a method getH. Your second link actually is the official documentation, and it shows that the method is not called getH. Read the documentation closely!\n",
"You have to use numpy.conj() function.\nimport numpy as np\nA=np.array([[2, 2-9j, -5j], [4-1j, 0, 9+6j], [4j, 6+... | [
1,
1,
0
] | [] | [] | [
"attributeerror",
"complex_numbers",
"numpy",
"python"
] | stackoverflow_0074499447_attributeerror_complex_numbers_numpy_python.txt |
Q:
Install PyTorch from requirements.txt
Torch documentation says use
pip install torch==1.4.0+cpu torchvision==0.5.0+cpu -f https://download.pytorch.org/whl/torch_stable.html
to install the latest version of PyTorch. This works when I do it manually but when I add it to req.txt and do pip install -r req.txt, it fai... | Install PyTorch from requirements.txt | Torch documentation says use
pip install torch==1.4.0+cpu torchvision==0.5.0+cpu -f https://download.pytorch.org/whl/torch_stable.html
to install the latest version of PyTorch. This works when I do it manually but when I add it to req.txt and do pip install -r req.txt, it fails and says ERROR: No matching distributio... | [
"Add --find-links in requirements.txt before torch\n--find-links https://download.pytorch.org/whl/torch_stable.html\n\ntorch==1.2.0+cpu\n\nSource: https://github.com/pytorch/pytorch/issues/29745#issuecomment-553588171\n",
"-f https://download.pytorch.org/whl/torch_stable.html \ntorch==1.4.0+cpu \n-f https://downl... | [
45,
9,
7,
6,
0
] | [] | [] | [
"pip",
"python",
"pytorch",
"requirements.txt"
] | stackoverflow_0060912744_pip_python_pytorch_requirements.txt.txt |
Q:
certbot Error while running on CentOS. Error: pkg_resources.DistributionNotFound: mock
I have installed certbot on my CentOS 7 VPS server using the command # *yum install certbot* after installation got the message Package certbot-1.11.0-2.el7.noarch already installed and latest version
And when trying to run # *... | certbot Error while running on CentOS. Error: pkg_resources.DistributionNotFound: mock | I have installed certbot on my CentOS 7 VPS server using the command # *yum install certbot* after installation got the message Package certbot-1.11.0-2.el7.noarch already installed and latest version
And when trying to run # *certbot* command on my server getting the following error.
Traceback (most recent call last)... | [
"Thanks everyone...\nI fixed issue by updating the Python version.\nCertbot environment seems to indicate Python3.\nSet up a Python virtual environment on Certbot Instructions | Certbot\n"
] | [
0
] | [] | [] | [
"certbot",
"lets_encrypt",
"python",
"python_packaging"
] | stackoverflow_0074411489_certbot_lets_encrypt_python_python_packaging.txt |
Q:
"DateTimeField %s received a naive datetime (%s)
'2022-11-11'
this is the input value getting from the front end,
RuntimeWarning: DateTimeField PaymentChart.date received a naive datetime (2022-11-18 00:00:00) while time zone support is active.
this is the error that coming
paydate = datetime.datetime.strptime(dat... | "DateTimeField %s received a naive datetime (%s) | '2022-11-11'
this is the input value getting from the front end,
RuntimeWarning: DateTimeField PaymentChart.date received a naive datetime (2022-11-18 00:00:00) while time zone support is active.
this is the error that coming
paydate = datetime.datetime.strptime(date,'%Y-%m-%d').isoformat()
this is how i tried to conv... | [
"You have to use Django's datetime, and not \"datetime\" library's datetime:\nfrom django.utils import timezone\nimport pytz\n\noffer.expiry=timezone.now()(tzinfo=pytz.UTC)+datetime.timedelta(days=28, tzinfo=pytz.UTC)\n\n"
] | [
1
] | [] | [] | [
"datetime",
"django",
"django_rest_framework",
"python",
"python_datetime"
] | stackoverflow_0074497164_datetime_django_django_rest_framework_python_python_datetime.txt |
Q:
Create Multi-Index empty DataFrame to join with main DataFrame
Suppose that I have a dataframe which can be created using code below
df = pd.DataFrame(data = {'date':['2021-01-01', '2021-01-02', '2021-01-05','2021-01-02', '2021-01-03', '2021-01-05'],
'product':['A', 'A', 'A', 'B', 'B', 'B... | Create Multi-Index empty DataFrame to join with main DataFrame | Suppose that I have a dataframe which can be created using code below
df = pd.DataFrame(data = {'date':['2021-01-01', '2021-01-02', '2021-01-05','2021-01-02', '2021-01-03', '2021-01-05'],
'product':['A', 'A', 'A', 'B', 'B', 'B'],
'price':[10, 20, 30, 40, 50, 60]
... | [
"First\nmake pivot table, upsampling by asfreq and fill null\ndf.pivot_table('price', 'date', 'product').asfreq('D').ffill().bfill()\n\noutput:\nproduct A B\ndate \n2021-01-01 10.0 40.0\n2021-01-02 20.0 40.0\n2021-01-03 20.0 50.0\n2021-01-04 20.0 50.0\n2021-01-05 30.0 60.0\n\n\n... | [
2,
0
] | [] | [] | [
"dataframe",
"multi_index",
"pandas",
"python"
] | stackoverflow_0074499439_dataframe_multi_index_pandas_python.txt |
Q:
Trying to stream live video using gstreamer but video keeps loading on client side
I have a raspberry pi 4 which I have a see3cam connected to via USB. I am trying to stream the live video to IP so that a computer on the same network can access the live feed.
I have tested that the camera in fact works with the ra... | Trying to stream live video using gstreamer but video keeps loading on client side | I have a raspberry pi 4 which I have a see3cam connected to via USB. I am trying to stream the live video to IP so that a computer on the same network can access the live feed.
I have tested that the camera in fact works with the raspberry pi. I'm able to watch it on the pi itself.
I've been following this tutorial.
M... | [
"As we can see \"playlist.m3u8\" is called but the segment are not\n123.456.78.910 - - [31/Oct/2022 14:03:18] \"GET /index.html HTTP/1.1\" 200. -\n123.456.78.910 - - [31/Oct/2022 14:03:19] \"GET /playlist.m3u8 HTTP/1.1\" 200 -\n123.456.78.910 - - [31/Oct/2022 14:03:26] \"GET /playlist.m3u8 HTTP/1.1\" 200 -\n\nThis ... | [
0
] | [] | [] | [
"gstreamer",
"python",
"raspberry_pi",
"raspbian",
"streaming"
] | stackoverflow_0074267957_gstreamer_python_raspberry_pi_raspbian_streaming.txt |
Q:
PyWinAuto with out using "child_window"
I have NO return on child_window when the program is in its state i expect to work in.
I need a way to edit the text field but literally all examples and google searches i have done show no examples of implementation EXCEPT when using child_window
this should put Test into t... | PyWinAuto with out using "child_window" | I have NO return on child_window when the program is in its state i expect to work in.
I need a way to edit the text field but literally all examples and google searches i have done show no examples of implementation EXCEPT when using child_window
this should put Test into the edit field
from pywinauto.application impo... | [
"Syntax error is in line Title = app.DaVinciResolveStudioTemplate.['TitleEdit', 'Edit8'].wrapper_object().\nThis line should be written as either Title = app.DaVinciResolveStudioTemplate['TitleEdit', 'Edit8'].wrapper_object() or Title = app.DaVinciResolveStudioTemplate.Edit8.wrapper_object().\n"
] | [
1
] | [] | [] | [
"python",
"pywinauto"
] | stackoverflow_0074495478_python_pywinauto.txt |
Q:
Python Docx - how to number headings?
There is a good example for Python Docx.
I have used multiple document.add_heading('xxx', level=Y) and can see when I open the generated document in MS Word that the levels are correct.
What I don't see is numbering, such a 1, 1.1, 1.1.1, etc I just see the heading text.
How c... | Python Docx - how to number headings? | There is a good example for Python Docx.
I have used multiple document.add_heading('xxx', level=Y) and can see when I open the generated document in MS Word that the levels are correct.
What I don't see is numbering, such a 1, 1.1, 1.1.1, etc I just see the heading text.
How can I display heading numbers, using Docx ?
| [
"Alphanumeric heading prefixes are automatically created based on the outline style and level of the heading. Set the outline style and insert the correct level and you will get the numbering.\nFrom documentation:\n\n_NumberingStyle objects class docx.styles.style._NumberingStyle[source] A numbering style. Not yet\... | [
4,
1,
0
] | [
"def __str__(self):\n if self.nivel == 1: \n return str(Level.count_1)+'.- '+self.titulo\n elif self.nivel==2: #Imprime si es del nivel 2\n return str(Level.count_1)+'.'+str(Level.count_2)+'.- '+self.titulo\n elif self.nivel==3: #Imprime si es del nivel 3\n return str(Level.count_1)+'.... | [
-1
] | [
"python",
"python_docx"
] | stackoverflow_0053870457_python_python_docx.txt |
Q:
Reading information from a txt file and storing it in a dictionary
I need to take information from a txt file and store it into a dictionary
Only one line of the information is being stored in the dictionary, How do I have all the lines get stored?
text = '''
admin, Register Users with taskManager.py, Use taskMana... | Reading information from a txt file and storing it in a dictionary | I need to take information from a txt file and store it into a dictionary
Only one line of the information is being stored in the dictionary, How do I have all the lines get stored?
text = '''
admin, Register Users with taskManager.py, Use taskManager.py to add the usernames and passwords for all team members that will... | [
"you have the same key admin in your result dictionary, the first one is replaced by the second one, so modify you text file to give different names.\nif you have multi assignment for one user, you can use following code:\ntext = '''\nadmin, Register Users with taskManager.py, Use taskManager.py to \nadd the userna... | [
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074499614_dictionary_python.txt |
Q:
How to split images depend on it's label so each label will have it's image's folder
I have a csv file which contain images label and path, and I have another folder contain all images, so I want to save each label's images in it's own folder, here how the csv looks like, I appreciate any help
enter image descript... | How to split images depend on it's label so each label will have it's image's folder | I have a csv file which contain images label and path, and I have another folder contain all images, so I want to save each label's images in it's own folder, here how the csv looks like, I appreciate any help
enter image description here
I didn't find any code for this one
| [
"You have to use pandas for reading the csv, os for creating the folders e shutil for copying files.\nimport os\nimport shutil\nimport pandas as pd\n\n# read the file\ncsv_file = pd.read_csv('file.csv', dtype=str)\n\n# create the folders\nlabels = csv_file['label']\nfor label in labels:\n os.makedirs(label, exis... | [
1
] | [] | [] | [
"csv",
"machine_learning",
"python"
] | stackoverflow_0074499597_csv_machine_learning_python.txt |
Q:
write multiple lines in a file in python
I have the following code:
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write(... | write multiple lines in a file in python | I have the following code:
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
Here target is the file object and line... | [
"You're confusing the braces. Do it like this:\ntarget.write(\"%s \\n %s \\n %s \\n\" % (line1, line2, line3))\n\nOr even better, use writelines:\ntarget.writelines([line1, line2, line3])\n\n",
"another way which, at least to me, seems more intuitive:\ntarget.write('''line 1\nline 2\nline 3''')\n\n",
"with open... | [
45,
10,
7,
3,
2,
1,
1,
0
] | [
"variable=10\nf=open(\"fileName.txt\",\"w+\") # file name and mode\nfor x in range(0,10):\n f.writelines('your text')\n f.writelines('if you want to add variable data'+str(variable))\n # to add data you only add String data so you want to type cast variable \n f.writelines(\"\\n\")\n\n"
] | [
-2
] | [
"python"
] | stackoverflow_0021019942_python.txt |
Q:
How to catch any words in TfidfVectorizer by token_pattern
I'd like to catch any words separated by just space in TfidfVectorizer, even if the words like "0" "a" "x" "0?0" and so on.
I wrote the below code for this purpose.
However, maybe, this code doesn't work well.
vectorizer = TfidfVectorizer(smooth_idf = Fals... | How to catch any words in TfidfVectorizer by token_pattern | I'd like to catch any words separated by just space in TfidfVectorizer, even if the words like "0" "a" "x" "0?0" and so on.
I wrote the below code for this purpose.
However, maybe, this code doesn't work well.
vectorizer = TfidfVectorizer(smooth_idf = False, token_pattern=r"[^ ]+")
| [
"You may be looking for word boundaries:\n\\b\\S+\\b\n\nExplanation:\n\n\\b looks for a word boundary, in the first instance of usage it will look for the start of a word (first words after a newline or anything after a space (or type of whitespace))\n\\S+ matches non whitespace characters at least once (the word y... | [
0
] | [] | [] | [
"python",
"regex",
"scikit_learn",
"tfidfvectorizer"
] | stackoverflow_0074498765_python_regex_scikit_learn_tfidfvectorizer.txt |
Q:
I rewrite a matlab code in python but they result different outputs
the matlab code and the output i was expecting (gauss elimination method)
my code in python:
import numpy as np
A = np.array([
[1,2,-1,1],
[-1,4,3,1],
[2,1,1,1]])
n = rows = len(A)
col = len(A[0])
for i in range(n):
A[i,:] = A[i... | I rewrite a matlab code in python but they result different outputs | the matlab code and the output i was expecting (gauss elimination method)
my code in python:
import numpy as np
A = np.array([
[1,2,-1,1],
[-1,4,3,1],
[2,1,1,1]])
n = rows = len(A)
col = len(A[0])
for i in range(n):
A[i,:] = A[i,:] / A[i,i]
for j in range(n):
if i==j:
pass
... | [
"Your problem is related to casting. Without info, numpy cast your matrix to integer numbers, so when you divide, the result is not a float. For example 2 / 6 = 0 and not 0.33333.\nIf you put\nA = np.array([\n [1,2,-1,1],\n [-1,4,3,1],\n [2,1,1,1]], dtype=float)\n\nyour result will be\n[[1. 0. 0. 0.333333... | [
0
] | [] | [] | [
"matlab",
"python"
] | stackoverflow_0074499749_matlab_python.txt |
Q:
How can I export all dataframes into an Excel file
I have a notebook open with about 45 dataframes. I would like to export all of them into a single Excel file with each dataframe being it's own tab in Excel.
Is there an easy way to do this without having to write each tab out manually?
Thank you!
A:
Please chec... | How can I export all dataframes into an Excel file | I have a notebook open with about 45 dataframes. I would like to export all of them into a single Excel file with each dataframe being it's own tab in Excel.
Is there an easy way to do this without having to write each tab out manually?
Thank you!
| [
"Please check the link Example: Pandas Excel with multiple dataframes\nYou can then as suggested by @delimiter create a list of the names\nimport pandas as pd\n# Create some Pandas dataframes from some data.\ndf1 = pd.DataFrame({'Data': [11, 12, 13, 14]})\ndf2 = pd.DataFrame({'Data': [21, 22, 23, 24]})\ndf3 = pd.Da... | [
1,
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0066343969_dataframe_pandas_python.txt |
Q:
Why I am getting 'pytest: error: unrecognized arguments: --env=qa' when running multiple pytest commands in a bash script
Hell there,
1.
I am using pipenv to create and activate a virtual environment where all dependencies are installed.
All the tests pass but my build fails because of this Error:
ERROR: usage: ... | Why I am getting 'pytest: error: unrecognized arguments: --env=qa' when running multiple pytest commands in a bash script | Hell there,
1.
I am using pipenv to create and activate a virtual environment where all dependencies are installed.
All the tests pass but my build fails because of this Error:
ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: unrecognized arguments: --env=qa
inifile: /*/*/projects/<ro... | [
"The documentation explains why this is not working. It states:\n\nThis function should be implemented only in plugins or conftest.py files situated at the tests root directory due to how pytest discovers plugins during startup.\n\nBased on the diagram of the repository structure you are showing, the conftest.py fi... | [
0
] | [] | [] | [
"pytest",
"python"
] | stackoverflow_0074481427_pytest_python.txt |
Q:
What does "not enough values to unpack (expected 2, got 1)" means?
I'm using selenium to scrape images from google, and trying to save it using wget returns a "not enough values to unpack (expected 2, got 1)" error. Does anyone know what could possibly cause this?
imageDownload = wget.download(src, "images/{0}.png... | What does "not enough values to unpack (expected 2, got 1)" means? | I'm using selenium to scrape images from google, and trying to save it using wget returns a "not enough values to unpack (expected 2, got 1)" error. Does anyone know what could possibly cause this?
imageDownload = wget.download(src, "images/{0}.png".format(counter))
File "image_scraper.py", line 38, in <module>
im... | [
"Please check the values of your variables. In your given code you use src variable. In the errormessage is actualImage.get_attribute(\"src\") used.\nPrint the src path and check if it´s valid (also try to open it manually in your browser as doublecheck).\nAdditionally please provide more of your code (and a sample... | [
0,
0
] | [] | [] | [
"python",
"wget"
] | stackoverflow_0061034555_python_wget.txt |
Q:
Selenium + Python: How to click Pay button on Google Pay pop up iframe checkout?
UPDATED:
Here is the checkout link. Click on gPay Button, log in Google with gPay to see the final Pay button to complete order that I want Selenium script to click on.
https://store.ui.com/14391668/checkouts/ae284ed7a99abc227e54933f1... | Selenium + Python: How to click Pay button on Google Pay pop up iframe checkout? | UPDATED:
Here is the checkout link. Click on gPay Button, log in Google with gPay to see the final Pay button to complete order that I want Selenium script to click on.
https://store.ui.com/14391668/checkouts/ae284ed7a99abc227e54933f1760e670
I have Selenium script to got to checkout and click the gPay button that pops... | [
"In the switch_to.frame() function you need to specify the element thet contains the iframe. So instead of:\ndriver.switch_to.frame(\"sM432dIframe\")\n\nshould be:\niframe = driver.find_element(By.ID, 'sM432dIframe') \ndriver.switch_to.frame(iframe)\n\n"
] | [
0
] | [] | [] | [
"iframe",
"python",
"selenium"
] | stackoverflow_0074498650_iframe_python_selenium.txt |
Q:
Python Dictionary showing empty values when adding lists
I'm trying to produce a JSON format for a given entity and I'm having an issue getting the dictionary to NOT overwrite itself or become empty. This is pulling rows from a table in a MySQL database and attempting to produce JSON result from the query.
Here i... | Python Dictionary showing empty values when adding lists | I'm trying to produce a JSON format for a given entity and I'm having an issue getting the dictionary to NOT overwrite itself or become empty. This is pulling rows from a table in a MySQL database and attempting to produce JSON result from the query.
Here is my function:
def detail():
student = 'John Doe'
conn... | [
"lists are mutable objects. Which means that list's are passed by reference.\nwhen you set\ndataset[student]['additional_information'] = case_dataset\n\ncase_dataset.clear()\n\nyou're setting the list and then clearing it. So the list inside additional_information is also cleared.\nCopy the list when setting it:\nd... | [
1,
0
] | [] | [] | [
"dictionary",
"json",
"python",
"python_3.x"
] | stackoverflow_0074499510_dictionary_json_python_python_3.x.txt |
Q:
Unable to initiate a boiler plate fast api code
I come from Javascript land so this bit confusing to me.
I am trying to use this as a boiler plate code for a project: https://github.com/anthonycepeda/fastapi-sqlmodel
This is there for quick start
### Quickstart
1. <b>Start the App</b>:
2. Using Python:
`pip... | Unable to initiate a boiler plate fast api code | I come from Javascript land so this bit confusing to me.
I am trying to use this as a boiler plate code for a project: https://github.com/anthonycepeda/fastapi-sqlmodel
This is there for quick start
### Quickstart
1. <b>Start the App</b>:
2. Using Python:
`pipenv run python asgi.py`
3. sing Docker:
`docker... | [
"The error log explains the problem\nENV\n field required (type=value_error.missing)\nVERSION\n field required (type=value_error.missing)\n\nThese two fields are mandatory when creating an instance of the class Settings. The exception is triggered on line settings = Settings() of \"/Users/userB/Desktop/fastapi-sq... | [
0
] | [] | [] | [
"fastapi",
"python"
] | stackoverflow_0074499456_fastapi_python.txt |
Q:
Whenever i try to search elementS in selenium it only prints out 1 out of the maybe 100 possible
Whenever I try to search elements in selenium it only prints out 1 out of the maybe 100 possible. Here is my Code :
Edit: full Code :
*import time
import sys
from selenium import webdriver
from selenium.webdriver.commo... | Whenever i try to search elementS in selenium it only prints out 1 out of the maybe 100 possible | Whenever I try to search elements in selenium it only prints out 1 out of the maybe 100 possible. Here is my Code :
Edit: full Code :
*import time
import sys
from selenium import webdriver
from selenium.webdriver.common.by import By
stdoutOrigin=sys.stdout
sys.stdout = open("log.txt", "w")
driver = webdriver.Chrome (e... | [
"Now you code collects rabatte only on the page https://ludwigbeck.mitarbeiterangebote.de/search?s=*&page=9. This code goes through search result pages and stops at opening the page 9:\nfor i in range(1, 10):\n time.sleep(1)\n driver.get(\"https://ludwigbeck.mitarbeiterangebote.de/search?s=*&page=\" + str(i))\n\nAn... | [
0
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074497977_python_selenium.txt |
Q:
How to verify integrity of files using digest in python (SHA256SUMS)
I have a set of files and a SHA256SUMS digest file that contains a sha256() hash for each of the files. What's the best way to verify the integrity of my files with python?
For example, here's how I would download the Debian 10 net installer SHA2... | How to verify integrity of files using digest in python (SHA256SUMS) | I have a set of files and a SHA256SUMS digest file that contains a sha256() hash for each of the files. What's the best way to verify the integrity of my files with python?
For example, here's how I would download the Debian 10 net installer SHA256SUMS digest file and download/verify its the MANIFEST file in BASH
user@... | [
"The following python script implements a function named integrity_is_ok() that takes the path to a SHA256SUMS file and a list of files to be verified, and it returns False if any of the files couldn't be verified and True otherwise.\n#!/usr/bin/env python3\nfrom hashlib import sha256\nimport os\n\n# Takes the path... | [
1,
0,
0
] | [] | [] | [
"checksum",
"data_integrity",
"python",
"python_3.x",
"sha256"
] | stackoverflow_0063568328_checksum_data_integrity_python_python_3.x_sha256.txt |
Q:
Changing static class variables
How is it possible to change static variables of a class? I want it to be changed by some sort of input.
class MyClass:
var1 = 1
var2 = 4
def __init__(self, var3, var4):
self.var3 = var3
self.var4 = var4
It is var1 og var2 that i want to be changa... | Changing static class variables | How is it possible to change static variables of a class? I want it to be changed by some sort of input.
class MyClass:
var1 = 1
var2 = 4
def __init__(self, var3, var4):
self.var3 = var3
self.var4 = var4
It is var1 og var2 that i want to be changable, or want to know how to change.
| [
"class Whatever():\n b = 5\n def __init__(self):\n Whatever.b = 9999\n\nboo = Whatever()\nprint(boo.b) # prints 9999\n\nboo.b = 500\nprint(boo.b) # prints 500\n\nWhatever.b = 400\nprint(boo.b) # prints 500\n\n# since its a static var you can always access it through class name\n# Whatever.b\n\n",
"If... | [
4,
0,
0,
0
] | [] | [] | [
"class",
"class_variables",
"python",
"static_variables"
] | stackoverflow_0048240905_class_class_variables_python_static_variables.txt |
Q:
Checkbox ALWAYS returns False/ not in request.POST - Django
I have a checkbox on my django app, where user can add or remove a listing from their watchlist.
However, this checkbox always returns False, and is never in request.POST, i have tried sooo many solutions from SO and all over the internet for literal days... | Checkbox ALWAYS returns False/ not in request.POST - Django | I have a checkbox on my django app, where user can add or remove a listing from their watchlist.
However, this checkbox always returns False, and is never in request.POST, i have tried sooo many solutions from SO and all over the internet for literal days now and cant figure it out
Models.py
class Watchlists(models.Mod... | [
"First, you don't have to add blank=False in your watchlist field since you gave it a default value, so rewrite it like so\nwatchlist = models.BooleanField(default=False)\n\nBy doing so, you can also remove this from your forms.py. It's not necessary\nwatchlist = forms.BooleanField(required=False)\n\nJust use as fo... | [
1
] | [] | [] | [
"checkbox",
"django",
"python"
] | stackoverflow_0074499927_checkbox_django_python.txt |
Q:
How does the name end up getting capitalized?
### Greeting people more formally ###
def get_formatted_name(first_name, last_name):
"""Return a full name, neatly formatted."""
full_name = f"{first_name} {last_name}"
return full_name.title()
# This is an infinite loop!
while True:
print("\nPlease... | How does the name end up getting capitalized? | ### Greeting people more formally ###
def get_formatted_name(first_name, last_name):
"""Return a full name, neatly formatted."""
full_name = f"{first_name} {last_name}"
return full_name.title()
# This is an infinite loop!
while True:
print("\nPlease tell me your name:")
print("(enter 'q' at any ... | [
"Short, but harsh:\nhttps://google.com/search?q=string+title+python+3+docs\nhttps://docs.python.org/3/library/stdtypes.html?highlight=title#str.title\nLonger:\nstr.title()\n\nReturn a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074500018_python.txt |
Q:
Problems with Chrome webdriver
Getting started with using Chrome webdrivers and selenium. When I execute the code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
driver = webdriver.Chrome(executable_path = \
... | Problems with Chrome webdriver | Getting started with using Chrome webdrivers and selenium. When I execute the code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
driver = webdriver.Chrome(executable_path = \
r"C:\Users\payto\Download... | [
"You can use webdriver_manager instead of constantly setting executable_path and chromedriver yourself.\nFor chrome driver:\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom webdriver_manager.chrome import ChromeDriverManager\n\ndriver = webdriver.Chrome(service=Service(Ch... | [
0,
0,
0
] | [] | [] | [
"google_chrome",
"python",
"selenium",
"webdriver"
] | stackoverflow_0074340337_google_chrome_python_selenium_webdriver.txt |
Q:
Random number generator that will always give all numbers within the specified range?
Is there a way to generate random intergers like with random.randint(i, j) but where it will always return all numbers within the range, without repetition and in random order ?
e.g:
(0,6) would give me 5, 3, 4, 2, 0, 1
random.ra... | Random number generator that will always give all numbers within the specified range? | Is there a way to generate random intergers like with random.randint(i, j) but where it will always return all numbers within the range, without repetition and in random order ?
e.g:
(0,6) would give me 5, 3, 4, 2, 0, 1
random.randint(i, j) does not do it.
| [
"Maybe\ndef random_range(begin: int, end: int) -> list[int]:\n nums: list[int] = list(range(begin, end + 1))\n random.shuffle(nums)\n return nums\n\nThe + 1 is to account for the last number, you can remove it though if you want to get it IN the range, not THE range\n"
] | [
0
] | [] | [] | [
"python",
"random"
] | stackoverflow_0074500130_python_random.txt |
Q:
How to click on hidden select under button
I need to select a URL value, but I don't understand how to do it
<span class="select select_layout_content select_size_s select_theme_normal
queries-filter-item__indicator i-bem select_js_inited _popup-destructor
_popup-destructor_js_inited"
data-bem="{"select&quo... | How to click on hidden select under button | I need to select a URL value, but I don't understand how to do it
<span class="select select_layout_content select_size_s select_theme_normal
queries-filter-item__indicator i-bem select_js_inited _popup-destructor
_popup-destructor_js_inited"
data-bem="{"select":{"live":false}}" title="">
<but... | [
"I'm not sure if this will work with the element that has the attribute aria-hidden=\"true\".\nThere is a special class in Selenium for the select elements. First, you need to import the Select class. You can try to use this code:\nfrom selenium.webdriver.support.select import Select\n\n# Click on make filter - is ... | [
0
] | [] | [] | [
"python",
"python_3.x",
"select",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074499819_python_python_3.x_select_selenium_selenium_webdriver.txt |
Q:
How to make a square bouncing in random positions using Pywin32
Can anyone tell me how i tried to make one but I didn't know
a square bouncing in random positions using Pywin32
A:
I don't have much of an explanation here but I do have some comments to show you what I am doing.
I haven't tested if this works yet ... | How to make a square bouncing in random positions using Pywin32 | Can anyone tell me how i tried to make one but I didn't know
a square bouncing in random positions using Pywin32
| [
"I don't have much of an explanation here but I do have some comments to show you what I am doing.\nI haven't tested if this works yet but you can try it. \nimport win32api, win32con, win32gui, time, random\n\n# get the screen size\nwidth = win32api.GetSystemMetrics(0)\n\n# create a window\n\nwin32gui.InitCommonCon... | [
0
] | [] | [] | [
"gdi",
"python"
] | stackoverflow_0074500001_gdi_python.txt |
Q:
Selenium crashed on M1 mac: selenium.common.exceptions.WebDriverException
Selenium doen't seems to start properly,
Keep raising **selenium.common.exceptions.WebDriverException: Message: **
Would someone knows how to fix it?
about my setting info
Mac M1 pro
Chrome version: 107.0.5304.87
ChromeDriver: 107.0.5304.62
... | Selenium crashed on M1 mac: selenium.common.exceptions.WebDriverException | Selenium doen't seems to start properly,
Keep raising **selenium.common.exceptions.WebDriverException: Message: **
Would someone knows how to fix it?
about my setting info
Mac M1 pro
Chrome version: 107.0.5304.87
ChromeDriver: 107.0.5304.62
selenium version: 4.5.0
First I tried the webdriver manual downloaded.
from s... | [
"Make sure you have the chrome browser installed.\nbrew install google-chrome\nMake sure to run the newest versions of selenium and webdriver_manager.\npython3 -m pip install --upgrade selenium webdriver_manager \nDelete all existing downloads with rm -rf ~/.wdm and try again. Make sure to not run your script as ro... | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver",
"web_scraping"
] | stackoverflow_0074298630_python_selenium_selenium_webdriver_web_scraping.txt |
Q:
Check Dataframes with Python
I got multiple excel file which needs to be need if OLD data is matching NEW data. Normally I use dataframe.equals but since the NEW data is containing additional columns this doesn't work anymore.
Very excel file contains two tabs with OLD and NEW data. I have to check if the OLD data... | Check Dataframes with Python | I got multiple excel file which needs to be need if OLD data is matching NEW data. Normally I use dataframe.equals but since the NEW data is containing additional columns this doesn't work anymore.
Very excel file contains two tabs with OLD and NEW data. I have to check if the OLD data is matching per record in NEW. Th... | [
"IIUC, you can use pandas.DataFrame.loc to select/pick the exact OLD columns from the NEW ones then use pandas.DataFrame.sort_values to reorder the rows by the two columns Column4 and Column8.\nTry this :\nfrom pathlib import Path\nimport pandas as pd\n\na_directory= \"path_to_the_folder_containing_the_excel_files\... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074499645_pandas_python.txt |
Q:
How can I create the fibonacci series using a list comprehension?
I am new to python, and I was wondering if I could generate the fibonacci series using python's list comprehension feature. I don't know how list comprehensions are implemented.
I tried the following (the intention was to generate the first five fi... | How can I create the fibonacci series using a list comprehension? | I am new to python, and I was wondering if I could generate the fibonacci series using python's list comprehension feature. I don't know how list comprehensions are implemented.
I tried the following (the intention was to generate the first five fibonacci numbers):
series=[]
series.append(1)
series.append(1)
series +=... | [
"You cannot do it like that: the list comprehension is evaluated first, and then that list is added to series. So basically it would be like you would have written:\nseries=[]\nseries.append(1)\nseries.append(1)\ntemp = [series[k-1]+series[k-2] for k in range(2,5)]\nseries += temp\nYou can however solve this by usi... | [
13,
10,
8,
8,
5,
1,
0,
0,
0,
0,
0
] | [
"Using List comprehension : \nn = int(input())\nfibonacci_list = [0,1]\n[fibonacci_list.append(fibonacci_list[k-1]+fibonacci_list[k-2]) for k in range(2,n)]\n\nif n<=0:\n print('+ve numbers only')\nelif n == 1:\n fibonacci_list = [fibonacci_list[0]]\n print(fibonacci_list)\nelse:\n print(fibonacci_list)\n\n... | [
-1
] | [
"fibonacci",
"list_comprehension",
"python"
] | stackoverflow_0042370456_fibonacci_list_comprehension_python.txt |
Q:
Extracting data from folders and putting it in excel using python
I dont know where to start and how to extract data from folder using pycharm
I am realy new to all of this can someone maybe direct me to what im looking for. I need to extract folder size data in Gb or kb and also name and write it as a defferent e... | Extracting data from folders and putting it in excel using python | I dont know where to start and how to extract data from folder using pycharm
I am realy new to all of this can someone maybe direct me to what im looking for. I need to extract folder size data in Gb or kb and also name and write it as a defferent excel cell how do i do this?
thanks for any help.
| [] | [] | [
"Take a look to the os module and pandas library. For example:\nwith os.path.dirname() you get the folder name, and then with pandas you can create a new spreadsheet with that output.\n"
] | [
-1
] | [
"file",
"python"
] | stackoverflow_0074500223_file_python.txt |
Q:
Implement guild command testing in cog slash commands
I am trying to learn discord.py V2.0. If I create a slash command without entering a guild to use then I takes some time before discord updated the bot slash command list. The qustion is how should I provide the guilds in my cog python file?
Here is my main.py:... | Implement guild command testing in cog slash commands | I am trying to learn discord.py V2.0. If I create a slash command without entering a guild to use then I takes some time before discord updated the bot slash command list. The qustion is how should I provide the guilds in my cog python file?
Here is my main.py:
import os
import asyncio
#---
import discord
from discord ... | [
"You do not need to provide the guilds yourself. You can use bot.guilds, which provides a list of all the guilds where the bot is connected to.\n"
] | [
1
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074499980_discord_discord.py_python.txt |
Q:
How to store every key that's generated in a variable?
How do I store every key that's generated here in a variable that I can access later?
for _ in range(int(amount)):
key = str(uuid.uuid4())
amount Is subject to change.
How do I make it so I can print all of the keys that it generated after the... | How to store every key that's generated in a variable? | How do I store every key that's generated here in a variable that I can access later?
for _ in range(int(amount)):
key = str(uuid.uuid4())
amount Is subject to change.
How do I make it so I can print all of the keys that it generated after the loop is done?
I tried doing:
for _ in range(int(amount)):
... | [
"You can also store them in a list\nkeys = []\nfor _ in range(int(amount)):\n keys.append(str(uuid.uuid4()))\n\nYou can read about python lists here and here.\nYou can then loop over your keys:\nfor key in keys:\n print(key)\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074500273_python.txt |
Q:
Finding the index of an element in nested lists in python
I am trying to get the index of an element in nested lists in python - for example [[a, b, c], [d, e, f], [g,h]] (not all lists are the same size).
I have tried using
strand_value= [x[0] for x in np.where(min_value_of_non_empty_strands=="a")]
but this is ... | Finding the index of an element in nested lists in python | I am trying to get the index of an element in nested lists in python - for example [[a, b, c], [d, e, f], [g,h]] (not all lists are the same size).
I have tried using
strand_value= [x[0] for x in np.where(min_value_of_non_empty_strands=="a")]
but this is only returning an empty list, even though the element is presen... | [
"def find_in_list_of_list(mylist, char):\n for sub_list in mylist:\n if char in sub_list:\n return (mylist.index(sub_list), sub_list.index(char))\n raise ValueError(\"'{char}' is not in list\".format(char = char))\n\nexample_list = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']]\n\nfind_in_li... | [
8,
2,
2,
0,
0,
0,
0
] | [] | [] | [
"nested_lists",
"python"
] | stackoverflow_0033938488_nested_lists_python.txt |
Q:
How to prevent class contructor from blocking other threads?
I am new to threading, so this question might be too basic.
I have two classes A and B. If I put their respective instances and methods in two threads as below:
from threading import Thread
from time import sleep
class A:
def __init__(self):
... | How to prevent class contructor from blocking other threads? | I am new to threading, so this question might be too basic.
I have two classes A and B. If I put their respective instances and methods in two threads as below:
from threading import Thread
from time import sleep
class A:
def __init__(self):
sleep(10)
print('class A __init__ awake')
def method... | [
"the most straight forward way to do it is to wrap the object creation and function execution in a function that does both, that will be executed entirely in another thread.\nthread_a = Thread(target=lambda: A().method_a())\nthread_b = Thread(target=lambda: B().method_b())\n\n"
] | [
1
] | [] | [] | [
"multithreading",
"python",
"python_class"
] | stackoverflow_0074500138_multithreading_python_python_class.txt |
Q:
matplotlib pyplot ParasiteAxes not allowing formatting of x label
The following can independently set the color, font and font size for the left and right y-axis, but can not set the font or font size for the x-axis. It can set the x-axis color. I'm using ParasiteAxes as they allow me to modify the plot formatti... | matplotlib pyplot ParasiteAxes not allowing formatting of x label | The following can independently set the color, font and font size for the left and right y-axis, but can not set the font or font size for the x-axis. It can set the x-axis color. I'm using ParasiteAxes as they allow me to modify the plot formatting in other ways while working with matplotlib.animation. The goal is ... | [
"I can't speak to why the way you are currently setting your xlabel properties is not working but it looks like using\nhost.set_xlabel('X Axis')\nhost.axis[\"bottom\"].label.set(fontsize=24, fontfamily='courier new', color='tab:green')\n\ninstead of host.set_xlabel('X Axis', fontsize=24, fontfamily='courier new', c... | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074485369_matplotlib_python.txt |
Q:
Jupyter notebook not showing output on vs code mac
I installed the Jupyter Notebook to VS Code, but when I try to run anything it does not show me an output. Does anyone know why? And how I can fix this?
A:
It looks like you aren't connected to any Jupyter servers, so the cells are actually waiting to be run. Pl... | Jupyter notebook not showing output on vs code mac | I installed the Jupyter Notebook to VS Code, but when I try to run anything it does not show me an output. Does anyone know why? And how I can fix this?
| [
"It looks like you aren't connected to any Jupyter servers, so the cells are actually waiting to be run. Please see Visual Studio Docs on how to set up:\n\nSetting up your environment\nTo work with Python in Jupyter Notebooks, you must activate an Anaconda environment in VS Code, or another Python environment in wh... | [
0
] | [] | [] | [
"jupyter_notebook",
"python",
"visual_studio_code"
] | stackoverflow_0074499671_jupyter_notebook_python_visual_studio_code.txt |
Q:
How to select elements property in an array? python
I have a lot of similar arrays, i need to select properties of 'geo_lon' and 'geo_lat'. This one is just for an example:
[{'value': '658747', 'unrestricted_value': 'Алтайский край, Крутихинский р-н, с Волчно-Бурлинское, ул Партизанская, д 98', 'data': {'postal_co... | How to select elements property in an array? python | I have a lot of similar arrays, i need to select properties of 'geo_lon' and 'geo_lat'. This one is just for an example:
[{'value': '658747', 'unrestricted_value': 'Алтайский край, Крутихинский р-н, с Волчно-Бурлинское, ул Партизанская, д 98', 'data': {'postal_code': '658747', 'is_closed': False, 'type_code': 'СОПС', '... | [
"Can you please try the following code.\nfor index, element in enumerate(list_1):\n data = element[\"data\"]\n geo_lat = data[\"geo_lat\"]\n geo_lon = data[\"geo_lon\"]\n print(\"geo_lat: \" + str(geo_lat) )\n print(\"geo_lon: \" + str(geo_lon) )\n\n"
] | [
0
] | [] | [] | [
"arrays",
"json",
"python"
] | stackoverflow_0074500278_arrays_json_python.txt |
Q:
Python Regex to match a colon either side (left and right) of a word
At a complete loss here - trying to match a a colon either side of any given word in a passage of text.
For example:
:wave: Hello guys! :partyface: another huge win for us all to celebrate!
An appropriate regex that would match:
:wave:
:partyfac... | Python Regex to match a colon either side (left and right) of a word | At a complete loss here - trying to match a a colon either side of any given word in a passage of text.
For example:
:wave: Hello guys! :partyface: another huge win for us all to celebrate!
An appropriate regex that would match:
:wave:
:partyface:
Really appreciate your help!
\w*:\b
| [
"To catch all the content\n:[^:]*:\n\nTo catch the content between\n(?<=:)[^:]*(?=:)\n\n"
] | [
0
] | [] | [] | [
"nlp",
"python",
"regex"
] | stackoverflow_0074500309_nlp_python_regex.txt |
Q:
Error while reading xlsm file by Pandas : "Conditional Formatting extension is not supported"
I want to read a xlsm file by Pandas:
pd.read_excel("data.xlsm", engine='openpyxl', sheet_name="sheet1")
But, I get the error:
C:\Users\anaconda3\lib\site-packages\openpyxl\worksheet\_read_only.py:79: UserWarning: Unknow... | Error while reading xlsm file by Pandas : "Conditional Formatting extension is not supported" | I want to read a xlsm file by Pandas:
pd.read_excel("data.xlsm", engine='openpyxl', sheet_name="sheet1")
But, I get the error:
C:\Users\anaconda3\lib\site-packages\openpyxl\worksheet\_read_only.py:79: UserWarning: Unknown extension is not supported and will be removed
for idx, row in parser.parse():
C:\Users\anacond... | [
"Please try this block of code.\nimport openpyxl\nfile='data.xlsm'\nwb=openpyxl.load_workbook(file, data_only=True, read_only=False, keep_vba=True)\n\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python",
"readfile",
"xlsm",
"xlsx"
] | stackoverflow_0074497948_pandas_python_readfile_xlsm_xlsx.txt |
Q:
How to solve: ValueError: Invalid format specifier?
h=1
m=1
s=30
k=5
ks = ((h * 60) + m + (s / 60)) / k
s=(ks - int(ks)) * 0.6
print(f'0{ks:.0f}:{s:.2f:.02}')
I am trying run the code, but i recieve the error: ValueError: Invalid format specifier
A:
ValueError: Invalid format specifier '.2f:.02' for object of ... | How to solve: ValueError: Invalid format specifier? | h=1
m=1
s=30
k=5
ks = ((h * 60) + m + (s / 60)) / k
s=(ks - int(ks)) * 0.6
print(f'0{ks:.0f}:{s:.2f:.02}')
I am trying run the code, but i recieve the error: ValueError: Invalid format specifier
| [
"ValueError: Invalid format specifier '.2f:.02' for object of type 'float'\n\nThis is the full error, simply you can't use 2f:.02 as specifier in brackets.\n>>> print(f'0{ks:.0f}:{s:.2f}')\n012:0.18\n\nThis is a sample output changing the specifier in brackets.\n"
] | [
1
] | [] | [] | [
"format",
"printing",
"python"
] | stackoverflow_0074500311_format_printing_python.txt |
Q:
fetch the first nonzero entry for each column and record the corresponding index value
I have a dataframe that looks something like:
IndexMonth Cus1 Cus2 Cus3 Cus4 ........ Cusn
2019-01 0 111 0 0 333
2019-02 0 111 0 666 0
2019-03 500 0 333 ... | fetch the first nonzero entry for each column and record the corresponding index value | I have a dataframe that looks something like:
IndexMonth Cus1 Cus2 Cus3 Cus4 ........ Cusn
2019-01 0 111 0 0 333
2019-02 0 111 0 666 0
2019-03 500 0 333 55 0
2019-04 600 0 333 111 0
2019-05 600 100 ... | [
"You can use masks to keep the first/last date per succession of non-zeros, then aggregate:\ndf2 = df.set_index('IndexMonth')\nm = df2.ne(0)\n\nstart = (df2\n .where(m&~m.shift(fill_value=False))\n .stack()\n .reset_index('IndexMonth')\n .groupby(level=0)['IndexMonth']\n .agg(','.join)\n .rename('... | [
2,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074499023_pandas_python.txt |
Q:
Getting "ParserError" when I try to read a .txt file using pd.read_csv()
I am trying to convert this dataset: COCOMO81 to arff.
Before converting to .arff, I am trying to convert it to .csv
I am following this LINK to do this.
I got that dataset from promise site. I copied the entire page to notepad as cocomo81.tx... | Getting "ParserError" when I try to read a .txt file using pd.read_csv() | I am trying to convert this dataset: COCOMO81 to arff.
Before converting to .arff, I am trying to convert it to .csv
I am following this LINK to do this.
I got that dataset from promise site. I copied the entire page to notepad as cocomo81.txt and now I am trying to convert that cocomo81.txt file to .csv using python.
... | [
"You first need to parse the txt file.\nColumn names can be taken after @attribute\n@attribute rely numeric\n@attribute data numeric\n@attribute cplx numeric\n@attribute time numeric\n..............................\n\nAnd in the csv file, load only the data after @data which is at the end of the file. You can just ... | [
1,
1
] | [] | [] | [
"arff",
"csv",
"dataset",
"python",
"txt"
] | stackoverflow_0074498991_arff_csv_dataset_python_txt.txt |
Q:
Deploy Django Project Using Pyinstaller
I have a django project, that works similar to Jupyter Notebook, in terms of Being a program launched offline in localhost on a web browser, moreover my webapp has an opencv webcam pop-up, that will be launched when you press a button.
I want to deploy my django project, so ... | Deploy Django Project Using Pyinstaller | I have a django project, that works similar to Jupyter Notebook, in terms of Being a program launched offline in localhost on a web browser, moreover my webapp has an opencv webcam pop-up, that will be launched when you press a button.
I want to deploy my django project, so it can be launched by just clicking a file in... | [
"I think that the best practise would be to use containers like e.g. docker. After that you have the following benefits:\n\nDependencies inside the container machine (automatically with pip install from requirements file)\nMultiplatform possibility\nVersioning with tags\nYou can run database in a second container i... | [
1
] | [] | [] | [
"batch_file",
"django",
"executable",
"pyinstaller",
"python"
] | stackoverflow_0074499789_batch_file_django_executable_pyinstaller_python.txt |
Q:
Can't install Django in visual studio code
So I'm creating a forum according to this tutorial: https://www.youtube.com/watch?v=YXmsi13cMhw&t=2594s
I'm stuck at 2:10.I've successfully created a virtual enviroment, can't go past this error.enter image description here
Where do I get project name?What on Earth is wro... | Can't install Django in visual studio code | So I'm creating a forum according to this tutorial: https://www.youtube.com/watch?v=YXmsi13cMhw&t=2594s
I'm stuck at 2:10.I've successfully created a virtual enviroment, can't go past this error.enter image description here
Where do I get project name?What on Earth is wrong here?Sorry if I got a little emotional.
I tri... | [
"python AutoDjango.py --django --project PROJECTNAME --app APPNAME solved it.\nIn the tutorial,for some reason, he used post_installation command assuming we are doind for the first time. and didnt clarify it. No offence though.\nSo, deleting post_installation solved it.\n"
] | [
0
] | [] | [] | [
"backend",
"django",
"python",
"web"
] | stackoverflow_0074500247_backend_django_python_web.txt |
Q:
dict.get or list check, which is faster?
If I want to get a bot with an ID, which is faster between:
storage = {
'bots': [
{ 'id': 123, 'auth': '81792367' },
{ 'id': 345, 'auth': '86908472' },
{ 'id': 543, 'auth': '12343321' }
]
}
id = 345
bot = next(bot['auth'] for bot in storage[... | dict.get or list check, which is faster? | If I want to get a bot with an ID, which is faster between:
storage = {
'bots': [
{ 'id': 123, 'auth': '81792367' },
{ 'id': 345, 'auth': '86908472' },
{ 'id': 543, 'auth': '12343321' }
]
}
id = 345
bot = next(bot['auth'] for bot in storage['bots'] if bot['id'] == id)
and
storage = {
... | [
"Bear in mind that the time complexity of lookup (i.e using the in keyword) for a list is O(n) whereas, the same operation has a time complexity of O(1) for a dictionary (Time Complexity of Collection Ops)\nMeanwhile the Time Complexity of Get Item is same (O(1)) for both. So, I would say you're better off with the... | [
2
] | [] | [] | [
"pep8",
"python"
] | stackoverflow_0074500257_pep8_python.txt |
Q:
Get values from variable in function and apply second conditional
I have this function,
def compare_date(x):
if pd.to_datetime(x) < pd.to_datetime('2019-09-01'):
return pd.to_datetime('2019-09-01')
else:
return pd.to_datetime(x)
file['Cash Received Date'] = file['CASH RECIEVED DATE'].apply... | Get values from variable in function and apply second conditional | I have this function,
def compare_date(x):
if pd.to_datetime(x) < pd.to_datetime('2019-09-01'):
return pd.to_datetime('2019-09-01')
else:
return pd.to_datetime(x)
file['Cash Received Date'] = file['CASH RECIEVED DATE'].apply(lambda x: compare_date(x))
that returns file as:
CASH RECIEVED DATE... | [
"Basically your problem is that you cannot use a lambda as you need to apply an operation to obtain your new column taking into account the value on several columns. You can still use apply method but as shown on code snippet below:\nimport pandas as pd\n\nfile = pd.DataFrame.from_dict({\"month\": [\"10\", \"11\", ... | [
0
] | [] | [] | [
"function",
"jupyter_notebook",
"lambda",
"pandas",
"python"
] | stackoverflow_0074499352_function_jupyter_notebook_lambda_pandas_python.txt |
Q:
Writing to Console and File in Python Script
I am looking for some help on a project I am doing where I need to output the responses to the console as well as write them to a file. I am having trouble figuring that part out. I have been able to write the responses to a file successfully, but not both at the same t... | Writing to Console and File in Python Script | I am looking for some help on a project I am doing where I need to output the responses to the console as well as write them to a file. I am having trouble figuring that part out. I have been able to write the responses to a file successfully, but not both at the same time. Can someone help with that portion? The only ... | [
"For printing a single object:\ndef mprint(text, file):\n print(text)\n print(text, file = file)\n\nA more general one for printing several objects:\ndef mprint(*args):\n print(*args[:-1])\n print(*args[:-1],file = args[-1])\n\nUsage: mprint(obj1, obj2, ... , myfile)\n",
"A completely general print func... | [
0,
0
] | [] | [] | [
"console",
"file",
"output",
"python"
] | stackoverflow_0074495268_console_file_output_python.txt |
Q:
Seaborn: Histogram doesn't start at 0
I'm trying to plot differents histograms in SeaBorn with this code (I've translated from spanish to english, so everyone can understand it):
#We assign diffent colours for the mean, the median, and the mode (red, green, and blue), for the legend of the graphics plotted
ref_mea... | Seaborn: Histogram doesn't start at 0 | I'm trying to plot differents histograms in SeaBorn with this code (I've translated from spanish to english, so everyone can understand it):
#We assign diffent colours for the mean, the median, and the mode (red, green, and blue), for the legend of the graphics plotted
ref_mean = mpatches.Patch(color='red', label='Mean... | [] | [] | [
"I've resolved this issues by setting the 'bins' attribute with the list of class intervals returned by my 'intervals' function, instead of the number of bins, like this:\n#We assign diffent colours for the mean, the median, and the mode (red, green, and blue), for the legend of the graphics plotted\nref_mean = mpa... | [
-1
] | [
"jupyter_notebook",
"matplotlib",
"pandas",
"python",
"seaborn"
] | stackoverflow_0074497202_jupyter_notebook_matplotlib_pandas_python_seaborn.txt |
Q:
Why isn't my class variable changed for all instances?
I'm learning about classes and don't understand this:
class MyClass:
var = 1
one = MyClass()
two = MyClass()
print(one.var, two.var) # out: 1 1
one.var = 2
print(one.var, two.var) # out: 2 1
I thought that class variables are accessible by all instance... | Why isn't my class variable changed for all instances? | I'm learning about classes and don't understand this:
class MyClass:
var = 1
one = MyClass()
two = MyClass()
print(one.var, two.var) # out: 1 1
one.var = 2
print(one.var, two.var) # out: 2 1
I thought that class variables are accessible by all instances, but why doesn't it change for all of them?
| [
"It doesn't change for all of them because doing this: one.var = 2, creates a new instance variable\nwith the same name as the class variable, but only for the instance one.\nAfter that, one will first find its instance variable and return that, while two will only find the class variable and return that.\nTo chang... | [
3,
2,
0
] | [] | [] | [
"class",
"class_variables",
"instance",
"python"
] | stackoverflow_0069856889_class_class_variables_instance_python.txt |
Q:
Using for loop to create scatterpolar subplot with Plotly
I want to create Scatterpolar (subplot) with Plotly, the plot shows information about 2 players.
Here is my code.
def Polar(Player_data, Selected_Player_data):
data_copy = Selected_Player_data.copy().iloc[0:1,:-3]
# select player
name = da... | Using for loop to create scatterpolar subplot with Plotly | I want to create Scatterpolar (subplot) with Plotly, the plot shows information about 2 players.
Here is my code.
def Polar(Player_data, Selected_Player_data):
data_copy = Selected_Player_data.copy().iloc[0:1,:-3]
# select player
name = data_Sample[data_Sample["Player"] == Player_data]
# select fe... | [
"You can change the type of markers by:\nfig.update_traces(mode = 'lines') # you can also change it to \"markers+lines\"\n\nThere is a legend for each subplot in the grid. If all legends are the same, you can solve this problem by adding this attribute to all subplots except the last one.\nfig.add_trace(go.Scatter... | [
0
] | [] | [] | [
"plotly",
"python",
"radar_chart",
"scatter_plot",
"visualization"
] | stackoverflow_0072022040_plotly_python_radar_chart_scatter_plot_visualization.txt |
Q:
Replace value from a column based on condition of another column, Pandas
Starting DataFrame
df = pd.DataFrame({'Column A' : ['red','green','yellow', 'orange', 'red', 'blue'],
'Column B' : [NaN, 'blue', 'purple', NaN, NaN, NaN],
'Column C' : [1, 2, 3, 2, 3, 7]})
Column A
Colum... | Replace value from a column based on condition of another column, Pandas | Starting DataFrame
df = pd.DataFrame({'Column A' : ['red','green','yellow', 'orange', 'red', 'blue'],
'Column B' : [NaN, 'blue', 'purple', NaN, NaN, NaN],
'Column C' : [1, 2, 3, 2, 3, 7]})
Column A
Column B
Column C
'red'
NaN
1
'green'
'blue'
2
'yellow'
'purple'
3
'o... | [
"As you mentioned, you could use pd.apply like this:\ndf['Column A'] = df.apply(lambda x: x['Column B'] if str(x['Column B']) not in ['nan', 'NaN'] else x['Column A'], axis=1)\n\n Column A Column B Column C\n0 red NaN 1\n1 blue blue 2\n2 purple purple 3\n3 orange ... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074494037_pandas_python.txt |
Q:
python cv2.error: Unknown C++ exception from OpenCV code
I have this code:
class CamThread(threading.Thread):
def __init__(self, previewname, camid):
threading.Thread.__init__(self)
self.previewname = previewname
self.camid = camid
def run(self):
print("Starting " + self.p... | python cv2.error: Unknown C++ exception from OpenCV code | I have this code:
class CamThread(threading.Thread):
def __init__(self, previewname, camid):
threading.Thread.__init__(self)
self.previewname = previewname
self.camid = camid
def run(self):
print("Starting " + self.previewname)
previewcam(self.previewname, self.camid)
... | [
"This is known issue, see here.\nThis is macOS specific problem, when cv2 tries to interact with UI in newly spawned thread, it throws this error. Use UI interactions on main thread only.\n"
] | [
0
] | [] | [] | [
"macos",
"opencv",
"python"
] | stackoverflow_0074256913_macos_opencv_python.txt |
Q:
Flask WTForms always give false on validate_on_submit()
I have created a signup form using wtforms. I am using FormField in it so that I don't have to repeat some of the elements of the form again. But whenever I click on the Submit button it always give me false on validate_on_submit method invocation. Not gettin... | Flask WTForms always give false on validate_on_submit() | I have created a signup form using wtforms. I am using FormField in it so that I don't have to repeat some of the elements of the form again. But whenever I click on the Submit button it always give me false on validate_on_submit method invocation. Not getting why is this happening.
My form.py is as follows:
class Pro... | [
"I solved my problem with the following function:\ndef __init__(self, *args, **kwargs):\n kwargs['csrf_enabled'] = False\n super(ProfileInfoForm, self).__init__(*args, **kwargs)\n\nI added this function in ProfileInfoForm()\nThe issue was FormField includes csrf_token field as well as Actual form, i.e., Regis... | [
5,
0,
0
] | [] | [] | [
"flask",
"flask_wtforms",
"python",
"wtforms"
] | stackoverflow_0018716920_flask_flask_wtforms_python_wtforms.txt |
Q:
I don't have the option to fold code anymore in vscode in python
Recently I discovered that the little arrow next to lines in vscode, that allows you to fold parts of the code, had disappeared. I then noticed this was the case only in my Python files.
I scoped the internet looking for an answer, but nothing worked... | I don't have the option to fold code anymore in vscode in python | Recently I discovered that the little arrow next to lines in vscode, that allows you to fold parts of the code, had disappeared. I then noticed this was the case only in my Python files.
I scoped the internet looking for an answer, but nothing worked
I'v tried fixing the setting (by checking that the "folding" setting ... | [
"Sort of expanding on the other answer, I've worked around it by changing settings for my python-specific workspace and changing the \"Folding Strategy\" to \"indentation\" instead of \"auto\", which seems to be a perfect workaround (for me at least) since Python requires proper indentation anyway and this doesn't ... | [
1,
0,
0
] | [] | [] | [
"code_folding",
"python",
"visual_studio_code"
] | stackoverflow_0074117813_code_folding_python_visual_studio_code.txt |
Q:
Loading data from dict with nested dicts and lists flattened or as many-to-many tables to sql
To simplify, I have a list as follows:
lst = [
{
“person_id”: HZT998, “name”: ‘john’, “skills”: [‘python’, ‘sql’, ‘r’],
“extras”: {“likes_swimming”: False, “likes_cooking”: True}},
... | Loading data from dict with nested dicts and lists flattened or as many-to-many tables to sql | To simplify, I have a list as follows:
lst = [
{
“person_id”: HZT998, “name”: ‘john’, “skills”: [‘python’, ‘sql’, ‘r’],
“extras”: {“likes_swimming”: False, “likes_cooking”: True}},
{
“person_id”: HTY954, “name”: ‘peter, “skills”: [‘python’, ‘r’, ‘c#’],
... | [
"Assuming that the key values in the list \"lst\" (e.g. \"person_id\" etc.) are always present, you just need to modify the complex list into normalized lists for this 3 pieces of tables:\nlst = [ \n {\n \"person_id\": \"HZT998\", \"name\": \"john\", \"skills\": [\"python\", \"sql\", \"r\"], \"e... | [
0
] | [] | [] | [
"python",
"relational_database",
"sql"
] | stackoverflow_0074498778_python_relational_database_sql.txt |
Q:
Flask validate_on_submit always False
I know that there are similar problems which have been answered. The csrf_enabled is not an issue now if the Form inheriting FlaskForm, and the template has the form.hidden_tag().
I have the following flask app.
## Filenname: app.py
from flask import Flask, render_templat... | Flask validate_on_submit always False | I know that there are similar problems which have been answered. The csrf_enabled is not an issue now if the Form inheriting FlaskForm, and the template has the form.hidden_tag().
I have the following flask app.
## Filenname: app.py
from flask import Flask, render_template, redirect, url_for, flash, request
from f... | [
"So there are multiple problems.\n\nChange your choices to strings:\nchoices=[('1', 'M'), ('2', \"F\")]\n\nChange your form method to POST, because validate_on_submit() requires it:\n<form action=\"\" method=\"POST\">\n\nAdditionally, to debug other possible errors (like CSRF), add this to your template: \n{% if fo... | [
10,
0,
0
] | [] | [] | [
"flask",
"jinja2",
"python"
] | stackoverflow_0048455689_flask_jinja2_python.txt |
Q:
Get certain date index values in a dataframe based on conditions met
python newb here.
I have a CSV with Date and Prices. The date is the index column.
I have a dataframe called data, with a column called 'Buy' which has only True and False values.
I want a column showing the associated indexed date only if True v... | Get certain date index values in a dataframe based on conditions met | python newb here.
I have a CSV with Date and Prices. The date is the index column.
I have a dataframe called data, with a column called 'Buy' which has only True and False values.
I want a column showing the associated indexed date only if True values.
I tried the following code:
data['Result'] = numpy.where(data['Buy'... | [
"The problem is that you are trying to assign both integer and datetime values to a column. Pandas cannot decide which type this column is. Therefore, you should combine them in a common data type:\ndata['Result'] = numpy.where(data['Buy'] == True, data.index.astype(str), 0)\n#Result dtype: object\n\nif you want ... | [
0
] | [] | [] | [
"date",
"indexing",
"python"
] | stackoverflow_0074498549_date_indexing_python.txt |
Q:
Selenium python hidden element cant be clicked unless hovered over
I want to create a program that will automatically host a krunker map when i run it but to host it the program has to click a button which only shows up if u hover over the map and i dont know how to do that with selenium (ps im gonna set the serve... | Selenium python hidden element cant be clicked unless hovered over | I want to create a program that will automatically host a krunker map when i run it but to host it the program has to click a button which only shows up if u hover over the map and i dont know how to do that with selenium (ps im gonna set the server to private and i dont think i can just do that with a link and i dont ... | [
"Update\nThere is a way to simulate the mousehover in selenium\nYou can try the following\nimport undetected_chromedriver as uc # pip install undetected-chromedriver\nfrom selenium.webdriver.common.action_chains import ActionChains\n\ndriver = uc.Chrome()\n\nmapp = driver.find_element(By.XPATH, 'put the map xpath h... | [
0
] | [] | [] | [
"python",
"selenium_webdriver"
] | stackoverflow_0074500532_python_selenium_webdriver.txt |
Q:
How can I save the username in the database as an email?>
I want a signup page with 3 fields (email, password and repeat password). My goal is that when the user enters the email address, it is also saved in the database as a username. I would be super happy if someone could help me, I've been sitting for x hours ... | How can I save the username in the database as an email?> | I want a signup page with 3 fields (email, password and repeat password). My goal is that when the user enters the email address, it is also saved in the database as a username. I would be super happy if someone could help me, I've been sitting for x hours trying to solve this problem. Thanks very much!
model.py
class ... | [
"If you want to use email instead of the default username, you have to overwrite the default User model with the custom one\n\nfrom django.contrib.auth.models import AbstractBaseUser, PermissionsMixin\n\nclass User(AbstractBaseUser, PermissionsMixin):\n # Use the email for logging in\n email = models.EmailFie... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074500695_django_python.txt |
Q:
How are range and len being used in for loops
I just want to know what is going on in this program
sum = 0 #setting sum to 0
for i in range(len(m)):
for j in range(len(m[i])):
if i <= j:
sum = sum + m[i][j]
return sum
print((sum_above_diagonal([[6, 2, 0, 6, 1], [6, 8, 2, 5, 8], [0, 6, 3, ... | How are range and len being used in for loops | I just want to know what is going on in this program
sum = 0 #setting sum to 0
for i in range(len(m)):
for j in range(len(m[i])):
if i <= j:
sum = sum + m[i][j]
return sum
print((sum_above_diagonal([[6, 2, 0, 6, 1], [6, 8, 2, 5, 8], [0, 6, 3, 2, 3]])))
I understand the first part, but I am co... | [
"Imagine you have this array:\narr = [[0,1,2],[9,8,7]]\n\nThe first for will run 2 times because len(arr)=2 and the second for will run 3 times because len(arr[0])=3\n",
"Pseudocode might help:\nStart with counting the sum from zero\nFor each number i between zero and the number of rows in the matrix, do this:\n ... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074500511_python.txt |
Q:
Grouping values in a clustered pie chart
I'm working with a dataset about when certain houses were constructed and my data stretches from the year 1873-2018(143 slices). I'm trying to visualise this data in the form of a piechart but because of the large number of indivdual slices the entire pie chart appears clus... | Grouping values in a clustered pie chart | I'm working with a dataset about when certain houses were constructed and my data stretches from the year 1873-2018(143 slices). I'm trying to visualise this data in the form of a piechart but because of the large number of indivdual slices the entire pie chart appears clustered and messy.
What I'm trying to implement ... | [
"For the future, always provide a reproducible example of the data you are working on (maybe use df.head().to_dict()). One solution to your problem could be achieved by using pd.resample.\n# Data Used\ndf = pd.DataFrame( {'year':np.arange(1890, 2018), 'built':np.random.randint(1,150, size=(2018-1890))} )\n>>> df.he... | [
0
] | [] | [] | [
"dataframe",
"graph",
"pandas",
"pie_chart",
"python"
] | stackoverflow_0074491126_dataframe_graph_pandas_pie_chart_python.txt |
Q:
Trying to read a config file in order to connect to twitter API
I am brand new at all of this and I am completely lost even after Googling, watching hours of youtube videos, and reading posts on this site for the past week.
I am using Jupyter notebook
I have a config file with my api keys it is called config.ipynb... | Trying to read a config file in order to connect to twitter API | I am brand new at all of this and I am completely lost even after Googling, watching hours of youtube videos, and reading posts on this site for the past week.
I am using Jupyter notebook
I have a config file with my api keys it is called config.ipynb
I have a different file where I am trying to call?? (I am not sure i... | [
"You are using the read() method incorrectly, the input should be a string of the filename, so if your filename is config.ipynb then you need to set the method to\nconfig.read('config.ipynb')\n\n",
"Per your last comment in Brance's answer, this is probably related to your file path. If your file path is not corr... | [
0,
0
] | [] | [] | [
"attributeerror",
"configuration_files",
"python"
] | stackoverflow_0074499103_attributeerror_configuration_files_python.txt |
Q:
Dense Rank changes the partition to 1 which is taking long time to save the df
I want to map string column to int:
st_id a
a 23
b 34
c 45
b 56
a 5
Expected Output:
st_id a st_id_int
a 23 1
b 34 2
c 45 3
b 56 2
a 5 1
So I used dense_rank() and ... | Dense Rank changes the partition to 1 which is taking long time to save the df | I want to map string column to int:
st_id a
a 23
b 34
c 45
b 56
a 5
Expected Output:
st_id a st_id_int
a 23 1
b 34 2
c 45 3
b 56 2
a 5 1
So I used dense_rank() and row_number() to get that:
df = df.selectExpr('st_id', 'a', 'row_number() over (orde... | [
"If I understand your problem correctly, you want to index your string column with repeated hash value. If so, then you can use StringIndexer:\nimport pyspark.sql.functions as F\nfrom pyspark.ml.feature import StringIndexer\n\ndf = spark.createDataFrame(data=[[\"a\",23],[\"b\",34],[\"c\",45],[\"b\",56],[\"a\",5]], ... | [
0
] | [] | [] | [
"apache_spark",
"dense_rank",
"pyspark",
"python"
] | stackoverflow_0074494465_apache_spark_dense_rank_pyspark_python.txt |
Q:
Remove subplot matplotlib margin
I would like to fit several subplot inside an A4 figure.
With this code I have unwanted white gap. How can I remove them (see figure). Thanks
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
gs1 = gridspec.GridSpec(8, 2)
gs1.update(wspace=0.025, hspace=0.05) ... | Remove subplot matplotlib margin | I would like to fit several subplot inside an A4 figure.
With this code I have unwanted white gap. How can I remove them (see figure). Thanks
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
gs1 = gridspec.GridSpec(8, 2)
gs1.update(wspace=0.025, hspace=0.05) # set the spacing between axes.
plt.f... | [
"import matplotlib.pyplot as plt\n\ngridspec_kw = {'wspace':0.025, 'hspace':0.05}\n\nfig, ax = plt.subplots(8, 2, \n figsize=(11.69,8.27), \n gridspec_kw=gridspec_kw,\n layout=\"constrained\")\n\ncolors = ['c', 'm', 'y', 'k', 'b', 'g', 'r', 'w']\n\nf... | [
1,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074498961_matplotlib_python.txt |
Q:
How to print new balance after adding amount to the initial one?
I'm learning Python and went with a simple ATM code. I've tested it and everything works DownStream - what I mean by this is:
I have a few options when the class is initialized - Balance, Deposit, Withdraw, Exit.
When I run Balance I receive the amo... | How to print new balance after adding amount to the initial one? | I'm learning Python and went with a simple ATM code. I've tested it and everything works DownStream - what I mean by this is:
I have a few options when the class is initialized - Balance, Deposit, Withdraw, Exit.
When I run Balance I receive the amount set.
2.1. I go with Deposit - it shows the new amount the person ... | [
"That's because every time you call the user_bank_balance method, you set the user_balance attribute to 300. So it wouldn't matter what updates you did on the user_balance, whenever you call the user_bank_balance method, you'll get 300\nclass ATM:\n\n atm_balance = 10000\n\n def __init__(self):\n self.... | [
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0074500561_oop_python.txt |
Q:
How can I find where a point will touch a line given a vector?
Here, line segment ab is cast upward on arbitrary vector n where I do somethings to find the black point on the line segment cd. My question is, how do I find the point on ab that intersects with the inverted n vector coming down from the new point?
A... | How can I find where a point will touch a line given a vector? |
Here, line segment ab is cast upward on arbitrary vector n where I do somethings to find the black point on the line segment cd. My question is, how do I find the point on ab that intersects with the inverted n vector coming down from the new point?
| [
"Looks like it will have the same x-coordinate as the black point (call this x). The slope of ab is m = (by - ay) / (bx - ax), so the y coordinate is mx + ay.\n",
"If the projection is parallel, by the Thales theorem the ratios are preserved.\n|ae| / |ab| = |cf| / |cd| = r\n\nwhich is known.\nThe searched point i... | [
0,
0
] | [] | [] | [
"algorithm",
"computational_geometry",
"math",
"python",
"vector"
] | stackoverflow_0074497596_algorithm_computational_geometry_math_python_vector.txt |
Q:
selecting mutliple items in python Tkinter Treeview with mouse event Button-1
I looked for and tested many similar questions/answers/possible duplicates here on SO and other sites but I'm interested specifically in using the solution below for simplicity's sake and minimal reproducible example constraint satisfact... | selecting mutliple items in python Tkinter Treeview with mouse event Button-1 | I looked for and tested many similar questions/answers/possible duplicates here on SO and other sites but I'm interested specifically in using the solution below for simplicity's sake and minimal reproducible example constraint satisfaction.
Why does the following modification of this previous answer's code does not wo... | [
"Try this:\nimport tkinter as tk\nfrom tkinter import ttk\n \nroot = tk.Tk()\n \ntree = ttk.Treeview(root)\ntree.pack(fill=\"both\", expand=True)\n \nitems = []\nfor i in range(10):\n item = tree.insert(\"\", \"end\", text=\"Item {}\".format(i+1))\n items.append(item)\n \n#items_to_select = []\n \nfor item... | [
1,
1
] | [] | [] | [
"mouseevent",
"python",
"python_3.x",
"tkinter",
"treeview"
] | stackoverflow_0074498330_mouseevent_python_python_3.x_tkinter_treeview.txt |
Q:
Use Group By and Aggregate Function in pyspark?
I am looking for a Solution to how to use Group by Aggregate Functions together in Pyspark?
My Dataframe looks like this:
df = sc.parallelize([
('23-09-2020', 'CRICKET'),
('25-11-2020', 'CRICKET'),
('13-09-2021', 'FOOTBALL'),
('20-11-2021', 'BASKETBAL... | Use Group By and Aggregate Function in pyspark? | I am looking for a Solution to how to use Group by Aggregate Functions together in Pyspark?
My Dataframe looks like this:
df = sc.parallelize([
('23-09-2020', 'CRICKET'),
('25-11-2020', 'CRICKET'),
('13-09-2021', 'FOOTBALL'),
('20-11-2021', 'BASKETBALL'),
('12-12-2021', 'FOOTBALL')]).toDF(['DATE', '... | [
"First, convert string to date format, and then apply min:\nimport pyspark.sql.functions as F\n\ndf = spark.createDataFrame(data=[\n ('23-09-2020', 'CRICKET'),\n ('25-11-2020', 'CRICKET'),\n ('13-09-2021', 'FOOTBALL'),\n ('20-11-2021', 'BASKETBALL'),\n ('12-12-2021', 'FOOTBALL') \n], schema=['DATE... | [
0
] | [] | [] | [
"apache_spark",
"databricks",
"pyspark",
"python"
] | stackoverflow_0074500675_apache_spark_databricks_pyspark_python.txt |
Q:
how do i add an element with a key to th elist
let's say we have a list like:
list = [{'name': 'car', 'number': '2'}]
And i want to add {'name': 'fruit', 'number': '4'} element to it.
At the end list should look like:
list = [{'name': 'car', 'number': '2'},
{'name': 'fruit', 'number': '4'}]
I tried to sol... | how do i add an element with a key to th elist | let's say we have a list like:
list = [{'name': 'car', 'number': '2'}]
And i want to add {'name': 'fruit', 'number': '4'} element to it.
At the end list should look like:
list = [{'name': 'car', 'number': '2'},
{'name': 'fruit', 'number': '4'}]
I tried to solve it like this:
list = [{'name': 'car', 'number': '... | [
"Try doing:\nlist.append({'name': 'fruit', 'number': '4'})\n\nThe append() method adds the specified value to the end of the list.\n"
] | [
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074500875_list_python.txt |
Q:
About perfect numbers
a = input('input a number :')
for i in range(1,int(a)):
b=0
for z in range(1,int(a)):
if i == z :
continue
elif i%z == 0:
print('i = ',i,'z =',z)
b += z
print('b = ',b)
if b == i:
print(i,'is ... | About perfect numbers | a = input('input a number :')
for i in range(1,int(a)):
b=0
for z in range(1,int(a)):
if i == z :
continue
elif i%z == 0:
print('i = ',i,'z =',z)
b += z
print('b = ',b)
if b == i:
print(i,'is a perfect number')
My ques... | [
"You are checking the sum of the divisors against the number itself inside the loop, before you finish iterating over all divisors. In the case of 24, its divisors are 1, 2, 3, 4, 6, 8, 12. But, their sum up to (and including) 8 is 1+2+3+4+6+8 = 24, so the condition b == i evaluates to true. Instead, you need to pe... | [
0
] | [] | [] | [
"for_loop",
"perfect_numbers",
"python"
] | stackoverflow_0074500859_for_loop_perfect_numbers_python.txt |
Q:
What is the error in these function and how can i overcome it?
I asked a question and had a successful answer (link. Unfortunatelly, im having problems while using the suggested code in google colab. Could you help me either (i) getting the suggested code working in google colab; or (ii) suggest a new code for the... | What is the error in these function and how can i overcome it? | I asked a question and had a successful answer (link. Unfortunatelly, im having problems while using the suggested code in google colab. Could you help me either (i) getting the suggested code working in google colab; or (ii) suggest a new code for the problem I explained in the link, please?
Im using the code:
import... | [
"Your code work perfectly there is no bug at all. Just upgrade \"BeautifulSoup\".\npip install --upgrade beautifulsoup4\n\nand rest of code will be same.\nNOTE: Once you upgrade BeautifulSoup library then restart runtime of your colab environment so that upgraded library come into force.\nStep to restart runtime:\n... | [
0
] | [] | [] | [
"beautifulsoup",
"google_colaboratory",
"python",
"select",
"web_scraping"
] | stackoverflow_0074453340_beautifulsoup_google_colaboratory_python_select_web_scraping.txt |
Q:
Eliminating rows and plotting a "customer country count in percentage" (Pandas, matplotlib)
If this is the dataframe
VisitorID visitNumber Country
1 1 USA
2 1 UK
3 1 CANADA
3 2 CANADA
4 1 MEXICO
... | Eliminating rows and plotting a "customer country count in percentage" (Pandas, matplotlib) | If this is the dataframe
VisitorID visitNumber Country
1 1 USA
2 1 UK
3 1 CANADA
3 2 CANADA
4 1 MEXICO
I want to plot a piechart with matplotlib about the visitors of each country (so it'd be 33% for ... | [
"You can specify the aggregation function for Country as well:\ndf2 = df.groupby('VisitorID').agg({'visitNumber': 'max', 'Country': 'first'}).reset_index()\n\nAlso shape is a property, not a method. So remove the parenthesis:\ndf2.shape\n\n"
] | [
0
] | [] | [] | [
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074500803_matplotlib_pandas_python.txt |
Q:
Checking if mentioned user is online
I am working on my own Discord bot. I want to make it reply to messages, not really specific commands. One of my ideas is to make it respond to messages in which I am pinged. However, it's not enough for me. I want it to respond to people ONLY when I am offline, and don't respo... | Checking if mentioned user is online | I am working on my own Discord bot. I want to make it reply to messages, not really specific commands. One of my ideas is to make it respond to messages in which I am pinged. However, it's not enough for me. I want it to respond to people ONLY when I am offline, and don't respond when online/DND/BRB. Bellow, you can se... | [
"Here is my code:\n@client.event \nasync def on_message(message):\n if message.content == '<@YourUserID>':\n #if you are offline:\n Me = message.guild.get_member(YourUserID)\n if Me.status == discord.Status.offline:\n response = \"What do you need from the Mighty One?\"\n ... | [
0
] | [] | [] | [
"bots",
"discord.py",
"python"
] | stackoverflow_0074482890_bots_discord.py_python.txt |
Q:
Scraping news articles using Selenium Python
I am Learning to scrape news articles from the website https://tribune.com.pk/pakistan/archives. The first thing is to scrape the link of every news article. Now the problem is that <a tag contains two href in it but I want to get the first href tag which I am unable to... | Scraping news articles using Selenium Python | I am Learning to scrape news articles from the website https://tribune.com.pk/pakistan/archives. The first thing is to scrape the link of every news article. Now the problem is that <a tag contains two href in it but I want to get the first href tag which I am unable to do
I am attaching the html of that particular par... | [
"You have to modify the below XPath:\nInstead of this -\nnews_articles = driver.find_elements(By.XPATH,\"//div[contains(@class,'flex-wrap')]//a\")\nUse this -\nnews_articles = driver.find_elements(By.XPATH,\"//div[contains(@class,'flex-wrap')]/a\")\n"
] | [
0
] | [] | [] | [
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074500600_python_selenium_web_scraping.txt |
Q:
Selenium: element click intercepted: Element is not clickable at point (774, 8907)
I am new to selenium, and I get the following error: element click intercepted: Element is not clickable at point (774, 8907) whenever I run this code on the webpage that has the show more button. My goal is to get every element of ... | Selenium: element click intercepted: Element is not clickable at point (774, 8907) | I am new to selenium, and I get the following error: element click intercepted: Element is not clickable at point (774, 8907) whenever I run this code on the webpage that has the show more button. My goal is to get every element of the "table" on the webpage, but in order to do so I need to click "show more" button if ... | [
"Because JavaScript interaction. So you have to click using JS execution.\n import time\n while not err:\n try:\n more_button = driver.find_element(by=By.CLASS_NAME, value='tpl-showmore-content')\n driver.execute_script(\"arguments[0].click();\" ,more_button)\n time.sle... | [
2,
0
] | [] | [] | [
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074500670_python_selenium_web_scraping.txt |
Q:
search data with multiple values in django
Want to filter data with multiple values in django.Currently i can only take two value from html but only one value filtering
This is my views code
p = request.GET.getlist('passout',[])
c = request.GET.getlist('course',[])
s = request.GET.getlist('skill',[])
... | search data with multiple values in django | Want to filter data with multiple values in django.Currently i can only take two value from html but only one value filtering
This is my views code
p = request.GET.getlist('passout',[])
c = request.GET.getlist('course',[])
s = request.GET.getlist('skill',[])
search_variables = {}
if p:
for l ... | [
"the thing is that you don't have that data for all search filters because Django filter work with AND operator and in your image you said give me a result that happened in 2019 AND 2020 and this is not possible.\nthe filter is working you just need to store the right data.\n"
] | [
0
] | [] | [] | [
"django",
"filter",
"python",
"search"
] | stackoverflow_0074501030_django_filter_python_search.txt |
Q:
Why i am having a maximum recursion depth exceeded error
I am trying to apply the Binary Search algorithm (the recursive way) and I'm having this error
def BinarySearchRec(tab, x):
mid = len(tab) // 2
if len(tab) == 0:
return False
if tab[mid] > x:
return BinarySearchRec(tab[:mid], x)
... | Why i am having a maximum recursion depth exceeded error | I am trying to apply the Binary Search algorithm (the recursive way) and I'm having this error
def BinarySearchRec(tab, x):
mid = len(tab) // 2
if len(tab) == 0:
return False
if tab[mid] > x:
return BinarySearchRec(tab[:mid], x)
elif tab[mid] < x:
return BinarySearchRec(tab[mid:]... | [
"When mid=0 and tab[mid] < x, the code gets stuck because BinarySearchRec(tab[mid:], x) will loop forever with the same inputs: (tab[mid:],x) -> (tab[0:],x) -> (tab,x) .\nAs a proof, you can try the following example:\ntab = [1]\nx = 2\nBinarySearchRec(tab, x)\n# recursion error raised\n\nThe easiest solution is ... | [
1
] | [] | [] | [
"arrays",
"binary_search",
"list",
"python",
"sorting"
] | stackoverflow_0074500935_arrays_binary_search_list_python_sorting.txt |
Q:
Better way of printing ascii art at given framerate
I am trying to optimize printing ascii art at given framerate. Now i am using time.sleep() but this is inconsistent because it doesnt add time when the frames are opening. I am asking is there a library which can handle this for me ?
This is my curent code:
def p... | Better way of printing ascii art at given framerate | I am trying to optimize printing ascii art at given framerate. Now i am using time.sleep() but this is inconsistent because it doesnt add time when the frames are opening. I am asking is there a library which can handle this for me ?
This is my curent code:
def play_ascii():
maxcount = len(os.listdir('temp/ascii'))... | [
"fpstimer might help\nIt can maintain certain a FPS in runtime\nhere is its PYPI link:\nhttps://pypi.org/project/fpstimer\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074501059_python.txt |
Q:
How to split data frame into x and y
I am splitting the data into training data and testing data like so:
train, test = train_test_split(dataFrame(), test_size=0.2)
Which works wonders, my training data frame looks like this:
PassengerId Survived SibSp Parch
77 78 0 0 0
748 ... | How to split data frame into x and y | I am splitting the data into training data and testing data like so:
train, test = train_test_split(dataFrame(), test_size=0.2)
Which works wonders, my training data frame looks like this:
PassengerId Survived SibSp Parch
77 78 0 0 0
748 749 0 1 0
444 ... | [
"The correct way to slice is x = train.iloc[:, 0:2].\n",
"If your target class is the last column, the most generic solution is:\nX = df.iloc[:, 0:-1]\ny = df.iloc[:, -1]\n\n"
] | [
14,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0053991131_numpy_python.txt |
Q:
Pycharm Referenced Error With Import Selenium Webdriver
Am using Python 3.6.5rcs , pip version 9.0.1 , selenium 3.11.0. The Python is installed in C:\Python and selenium is in C:\Python\Lib\site-packages\selenium. The environment variables have been set.
But the code
from selenium import webdriver
gives an unreso... | Pycharm Referenced Error With Import Selenium Webdriver | Am using Python 3.6.5rcs , pip version 9.0.1 , selenium 3.11.0. The Python is installed in C:\Python and selenium is in C:\Python\Lib\site-packages\selenium. The environment variables have been set.
But the code
from selenium import webdriver
gives an unresolved reference error.
Any suggestion on how to fix the proble... | [
"Pycharm > Preferences > Project Interpreter\nThen hit the '+' to install the package to your project path.\nOr you can add that path to your PYTHONPATH environment variable in your project.\n",
"I found this worked for me. I'm using PyCharm Community 2018.1.4 on Windows.\nNavigate to: File->Settings->Project: [p... | [
4,
2,
1,
0
] | [] | [] | [
"pycharm",
"python",
"selenium"
] | stackoverflow_0049482586_pycharm_python_selenium.txt |
Q:
How to select only a link while web scrapping a HTML which the attribute has also text?
As a part of a a bigger webscrapping project, I want to extract the html link from a html. It is not all html link on the page, but only the in the second column of the big table.
An example of how the html these links appear l... | How to select only a link while web scrapping a HTML which the attribute has also text? | As a part of a a bigger webscrapping project, I want to extract the html link from a html. It is not all html link on the page, but only the in the second column of the big table.
An example of how the html these links appear look like:
<a href="exibir?proc=18955/989/20&offset=0">18955/989/20</a>
I would like to h... | [
"Here is one way to get those links from the second column. You're welcome to functionalize it if you want.\nfrom bs4 import BeautifulSoup as bs\nimport requests\nfrom tqdm import tqdm ## if using Jupyter: from tqdm.notebook import tqdm\nimport pandas as pd\n\npd.set_option('display.max_columns', None)\npd.set_opti... | [
0
] | [] | [] | [
"html",
"hyperlink",
"loops",
"python",
"web_scraping"
] | stackoverflow_0074497612_html_hyperlink_loops_python_web_scraping.txt |
Q:
TypeError: btn_add() missing 1 required positional argument: 'first_number'
I'm making a calculator in Python using Tkinter, and I'm getting an error im not sure as to why im running into this error but ive legit tried retyping the whole code and cant find anything about it on yt:
`
from tkinter import *
w = Tk()... | TypeError: btn_add() missing 1 required positional argument: 'first_number' | I'm making a calculator in Python using Tkinter, and I'm getting an error im not sure as to why im running into this error but ive legit tried retyping the whole code and cant find anything about it on yt:
`
from tkinter import *
w = Tk()
w.title("Simple Calculator")
ent = Entry()
ent.grid(row=0,column=0,columnspan=... | [
"The error is where you inherit the Button class to button_add\nspecifically in command=button_add\nYou have to add in 'first_number' parameter to the command parameter\n",
"def button_add():\nfirst_number = ent.get()\nglobal f_num\nf_num = int(first_number)\nent.delete(END)\n\n"
] | [
0,
-1
] | [] | [] | [
"calculator",
"function",
"python",
"tkinter"
] | stackoverflow_0074501029_calculator_function_python_tkinter.txt |
Q:
Nextcord: sending a message from a .txt
I want to send a random line from a .txt from my discord bot, I am using nextcord but if discord.py works better I can use that to. Let me know if anyone can help.
I haven't tried much as I am fairly new to python but thought I would give it a try. I tried using random and .... | Nextcord: sending a message from a .txt | I want to send a random line from a .txt from my discord bot, I am using nextcord but if discord.py works better I can use that to. Let me know if anyone can help.
I haven't tried much as I am fairly new to python but thought I would give it a try. I tried using random and .json but it went horribly lol.
| [
"I'm not sure how nextcord works but there is a way you can get a random line from a .txt file in any python file.\nFirstly, make sure your .txt file is in the same folder as your python file. Secondly we should import random as we will use random.choice in this method. Then, you can create a function which chooses... | [
0
] | [] | [] | [
"discord.py",
"nextcord",
"python"
] | stackoverflow_0074496961_discord.py_nextcord_python.txt |
Q:
I cannot use opencv2 and received ImportError: libgl.so.1 cannot open shared object file no such file or directory
**env:**ubuntu16.04 anaconda3 python3.7.8 cuda10.0 gcc5.5
command:
conda activate myenv
python
import cv2
error:
Traceback (most recent call last):
File "", line 1, in
File "/home/.conda/envs/myenv/... | I cannot use opencv2 and received ImportError: libgl.so.1 cannot open shared object file no such file or directory | **env:**ubuntu16.04 anaconda3 python3.7.8 cuda10.0 gcc5.5
command:
conda activate myenv
python
import cv2
error:
Traceback (most recent call last):
File "", line 1, in
File "/home/.conda/envs/myenv/lib/python3.7/site-packages/cv2/__init__.py", line 5, in
from .cv2 import *
ImportError: libGL.so.1: cannot open shared... | [
"Usually these Pacakges are meant to be installed as System Packages and Not only Python packages. Therefore many times even after successfull installation of such packages like opencv, cmake, dlib they don't work.\nThe Best way is to Install them is using.\nsudo apt-get install python3-opencv\n\nThis is the Prefer... | [
5,
1,
0
] | [] | [] | [
"anaconda3",
"importerror",
"opencv",
"python",
"ubuntu_16.04"
] | stackoverflow_0064664094_anaconda3_importerror_opencv_python_ubuntu_16.04.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.