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: button 'pay now!' not working for redirect to payment-done view in payment-braintree and django I am writing an online store based on the Django 3 By Example 3rd Edition book. I encountered a problem with the book's codes in the payment section, I searched the internet and updated some of the codes, but I still ha...
button 'pay now!' not working for redirect to payment-done view in payment-braintree and django
I am writing an online store based on the Django 3 By Example 3rd Edition book. I encountered a problem with the book's codes in the payment section, I searched the internet and updated some of the codes, but I still have a problem! After filling out the debit card form, when I click on the "pay now!" button, I am not ...
[ "indent the code in the payment_process function\n" ]
[ 0 ]
[]
[]
[ "django", "django_forms", "django_templates", "django_views", "python" ]
stackoverflow_0074581726_django_django_forms_django_templates_django_views_python.txt
Q: getting ('Connection aborted.', OSError(0, 'Error')) in Azure ML I am unable to load BERT model in Azure ML notebook. from sentence_transformers import SentenceTransformer model = SentenceTransformer('all-mpnet-base-v2') I am getting this error: File /anaconda/envs/azureml_py38/lib/python3.8/site-packages/request...
getting ('Connection aborted.', OSError(0, 'Error')) in Azure ML
I am unable to load BERT model in Azure ML notebook. from sentence_transformers import SentenceTransformer model = SentenceTransformer('all-mpnet-base-v2') I am getting this error: File /anaconda/envs/azureml_py38/lib/python3.8/site-packages/requests/sessions.py:645, in Session.send(self, request, **kwargs) 642 st...
[ "The problem with this package upgrading and that supports the version of python. There is a chance of upgrading the TLS and SSL version in the app functioning portal.\n\nCheck the TLS version and all the certificates.\nThis is also because of older version. Try to execute the below code block so solve the error.\n...
[ 0 ]
[]
[]
[ "azure_machine_learning_studio", "bert_language_model", "python" ]
stackoverflow_0074550731_azure_machine_learning_studio_bert_language_model_python.txt
Q: How to make a multiple bar chart? How to make a bar chart using 'altair' to use the information in a table? If you need to change the table format is it ok, I want to make a bar chart as below. (My end goal is to create a bar chart in streamlit.) Example, import pandas as pd import streamlit as st df = pd.DataFra...
How to make a multiple bar chart?
How to make a bar chart using 'altair' to use the information in a table? If you need to change the table format is it ok, I want to make a bar chart as below. (My end goal is to create a bar chart in streamlit.) Example, import pandas as pd import streamlit as st df = pd.DataFrame([['sst', '100', '1000'],['can','500'...
[ "as step 1 - you need to melt your dataframe, so that it would consist only of 3 columns, model, variable (0/1) and value.\nStep 2 - Grouped bar chart - is nothing than 2 individual bar charts for each model, stack together as columns.\nStep 3 - final tweaks:\nAdditional chart configuration to make it look as a sin...
[ 1 ]
[]
[]
[ "altair", "grouped_bar_chart", "python", "streamlit" ]
stackoverflow_0074574486_altair_grouped_bar_chart_python_streamlit.txt
Q: How to select every n-th row in dataframe with condition of previous rows based on daily interval I have a large dataframe and I need a new column sig with values 0 or 1. The conditions: Add value = 1 in 3rd row of each day starting at 08:30, if data in row 3 > data row 2 > data row 1, else 0 Limitations: In the o...
How to select every n-th row in dataframe with condition of previous rows based on daily interval
I have a large dataframe and I need a new column sig with values 0 or 1. The conditions: Add value = 1 in 3rd row of each day starting at 08:30, if data in row 3 > data row 2 > data row 1, else 0 Limitations: In the original dataframe the intervals of the seconds in the timestamps are not equal, so you can't go by time...
[ "I took your code to create the input data, but it looks bit different to the printed version of yours:\n data\ndate \n2022-01-01 08:30:00 14\n2022-01-01 08:30:01 27\n2022-01-01 08:30:02 33\n2022-01-01 08:30:03 77\n2022-01-01 08:30:04 66\n2022-01-01 08:30:05 ...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074581583_pandas_python.txt
Q: Get Path to Python File Before Installation I have a project that includes c++ binaries and python scripts, it's setup such that it should be installed using setuptools. One of the python files is intended to be both used as a script " python3 script_name.py params and for it's primary function to be used in other...
Get Path to Python File Before Installation
I have a project that includes c++ binaries and python scripts, it's setup such that it should be installed using setuptools. One of the python files is intended to be both used as a script " python3 script_name.py params and for it's primary function to be used in other python projects from script_name import function...
[ "Since you are installing your package, you also need to include your C++ binary in the installation. You cannot have a mixed setup. I suggest something like this.\nIn your setup.py:\nfrom setuptools import setup, find_packages\n\nsetup(\n name=\"mypkg\",\n packages=find_packages(exclude=[\"tests\"]),\n p...
[ 1, 0 ]
[]
[]
[ "packaging", "path", "pip", "python", "setuptools" ]
stackoverflow_0074577488_packaging_path_pip_python_setuptools.txt
Q: Is it possible to write to multiple coils using pyModbusTCP library There is a method from the documents that looks like client.write_coils(1, [True]*8) My assumption is that this will write True 8 times because how do I supply a list of addresses? I want to supply a list of 8 modbuss address and assign them all T...
Is it possible to write to multiple coils using pyModbusTCP library
There is a method from the documents that looks like client.write_coils(1, [True]*8) My assumption is that this will write True 8 times because how do I supply a list of addresses? I want to supply a list of 8 modbuss address and assign them all True, for the sake of example. The alternate way is use the singular write...
[ "I agree that the documentation for write_multiple_coils(addr, values) is ambiguous.\nYou can look at the Modbus specification for Write Multiple Coils (function code 0x15) which says:\n\nWrites each coil in a sequence of coils to either ON or OFF.\n\nSo it might be helpful to think of the address as the starting a...
[ 1 ]
[]
[]
[ "modbus", "modbus_tcp", "pymodbus", "python", "tcp" ]
stackoverflow_0074576917_modbus_modbus_tcp_pymodbus_python_tcp.txt
Q: Load mobile net (keras) in tensorflow.js I'm trying to load a keras model which is based on mobilen in Tensorflow.js. Sadly this does not work I generated the model with the following python code import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers import numpy as np import ten...
Load mobile net (keras) in tensorflow.js
I'm trying to load a keras model which is based on mobilen in Tensorflow.js. Sadly this does not work I generated the model with the following python code import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers import numpy as np import tensorflowjs as tfjs input_shape = 224,224 #sor...
[ "not a layers or a model problem per-say, more of a nodejs problem. latest version of node define global fetch, but implementation is still not complete and it lacks support for file://. and tfjs will use global fetch if its defined. try using node --no-experimental-fetch so global fetch is not defined and tfjs wil...
[ 1 ]
[]
[]
[ "keras", "node.js", "python", "tensorflow", "tensorflow.js" ]
stackoverflow_0074577573_keras_node.js_python_tensorflow_tensorflow.js.txt
Q: Pandas DataFrame sorting issues, grouping for no reason? I have one data frame containing stats about NBA season. I'm simply trying to sort by date, but for some reason it's grouping all games that have the same data and changing the values of that said date to the same values. df = pd.read_csv("gamedata.csv") df[...
Pandas DataFrame sorting issues, grouping for no reason?
I have one data frame containing stats about NBA season. I'm simply trying to sort by date, but for some reason it's grouping all games that have the same data and changing the values of that said date to the same values. df = pd.read_csv("gamedata.csv") df["Total"] = df["Tm"] + df["Opp.1"] teams = df['Team'] df = df.d...
[ "Please add this line to your code to sort your dataframe by date\ndf.sort_values(by='Date')\n\nI hope you will get the desired output\n" ]
[ 0 ]
[]
[]
[ "data_cleaning", "dataframe", "pandas", "python" ]
stackoverflow_0074579916_data_cleaning_dataframe_pandas_python.txt
Q: Attribute error when working with 'self' and 'with' I'm working on a Python script to generate a report in PDF using PyLatex. I set up a class ReportGeneration. Inside, a table 'overview_table' is defined. When I try to work with table from 2 functions, it gives me the error: AttributeError: args A small snippet o...
Attribute error when working with 'self' and 'with'
I'm working on a Python script to generate a report in PDF using PyLatex. I set up a class ReportGeneration. Inside, a table 'overview_table' is defined. When I try to work with table from 2 functions, it gives me the error: AttributeError: args A small snippet of the init method: self.doc = Document() self.doc.documen...
[ "It seems that the pylatex package has used the @contextlib.contextmanager decorator on the create method.\n @contextmanager\n def create(self, child):\n \"\"\"Add a LaTeX object to current container, context-manager style.\n Args\n ----\n child: `~.Container`\n An objec...
[ 1 ]
[]
[]
[ "pylatex", "python", "python_3.x" ]
stackoverflow_0074582002_pylatex_python_python_3.x.txt
Q: My code finds values in the list, but does not show any prompt when the value is not found I was trying to do a binary search on the list CardData=[11,12,25,33,52,56,57,59,85,91] this is my binary search method def binsea(x,CardData): front=0 back=len(CardData) mid=len(CardData)//2 found=False ...
My code finds values in the list, but does not show any prompt when the value is not found
I was trying to do a binary search on the list CardData=[11,12,25,33,52,56,57,59,85,91] this is my binary search method def binsea(x,CardData): front=0 back=len(CardData) mid=len(CardData)//2 found=False while front<back and found==False: if x==CardData[mid]: found=True ...
[ "In general, I think the best way to debug your code yourself is often to add print statements. Try printing the values of front, back, and mid at the end of the loop (inside the loop). That should help you find your problem.\nYou could also look up the law of trichotomy.\n", "Your program is working. The conditi...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074582043_python.txt
Q: Update user profile with user uuid I want to update user profile passing user uuid as kwarg. Here is the url: path("profile/update/<uuid:pk>", UpdateProfile.as_view(), name="update_profile"), However, after I try to update my profile, it gives me an error. Here is my view: class UpdateProfile(LoginRequiredMixin, ...
Update user profile with user uuid
I want to update user profile passing user uuid as kwarg. Here is the url: path("profile/update/<uuid:pk>", UpdateProfile.as_view(), name="update_profile"), However, after I try to update my profile, it gives me an error. Here is my view: class UpdateProfile(LoginRequiredMixin, UpdateView): model = Profile use...
[ "Assuming the following model, where a user only has one profile:\n class Profile(models.Model):\n user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)\n photo = models.ImageField()\n # ... your other fields\n\nYou can then overwrite the get_object() method:\n class Upd...
[ 1 ]
[]
[]
[ "django", "django_views", "error_handling", "python" ]
stackoverflow_0074581549_django_django_views_error_handling_python.txt
Q: Pandas dataframe with two columns but only shows one in shape function The original dataframe has a column called release_year and a column called rating, and each year might include several ratings. I tried to calculate the average rating of each year and return a two column dataframe. df = df.groupby('release_ye...
Pandas dataframe with two columns but only shows one in shape function
The original dataframe has a column called release_year and a column called rating, and each year might include several ratings. I tried to calculate the average rating of each year and return a two column dataframe. df = df.groupby('release_year')['rating'].mean() new_df = pd.DataFrame(df) The result looks like a two...
[ "when you do the groupby , the grouped column becomes INDEX.\nexample:\ndf:\n\n\n\n\nINDEX\nCOL1\nCOL2\n\n\n\n\n0\nITEM1\nITEM2\n\n\n\n\ndf.groupby('col1'):\n\n\n\n\nCOL1(NOW INDEX)\nCOL2\n\n\n\n\nITEM1\nITEM2\n\n\n\n\nyou can use df.reset_index() to get indexes and change it to a column.\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074582248_dataframe_pandas_python.txt
Q: find numbers in string in selenium In Python and Selenium, how do I find numeric characters in a text and put them in a variable? for example : text = Your verification code is: 5674 I need to find the number 5674 from the text and put it in a variable. Result »» x = 5674 import re txt = "Your verification code i...
find numbers in string in selenium
In Python and Selenium, how do I find numeric characters in a text and put them in a variable? for example : text = Your verification code is: 5674 I need to find the number 5674 from the text and put it in a variable. Result »» x = 5674 import re txt = "Your verification code is: 5674" x = is_digit(txt) print(x) x »»...
[ "If the message is always formatted like this you can do:\ntext[text.find(\":\"):].strip() # -> 5764\n\nor\ntext.strip(\"Your verification code is:\") # -> 5764\n\n", "Well if you really expect just a single verification integer at the end, you could use re.search():\ntext = \"Your verification code is: 5674\";\n...
[ 0, 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074582238_python_selenium.txt
Q: How to extract text with strikethroughs from PDF files using Python I'm currently trying to extract information from lots of PDF forms such as this: The text 'female' should be extracted here. So contrary to my title, I'm actually trying to extract text with no strikethroughs rather than text that with strikethro...
How to extract text with strikethroughs from PDF files using Python
I'm currently trying to extract information from lots of PDF forms such as this: The text 'female' should be extracted here. So contrary to my title, I'm actually trying to extract text with no strikethroughs rather than text that with strikethroughs. But if I can identify which words with strikethroughs, I can easily...
[ "Disclaimer: I am the author of borb, the library suggested in this answer\nUltimately, the exact code will end up varying depending on how strikethrough is implemented in your PDF. Allow me to clarify:\nA PDF document (typically) has no notion of structure. So while we may see a paragraph of text, made up of sever...
[ 1, 1 ]
[]
[]
[ "pdf", "python" ]
stackoverflow_0074533481_pdf_python.txt
Q: Selecting rows in 2-D numpy array based on subset of column values Suppose I have the following numpy array: a = np.array([[1, 1, 0, 0, 1], [1, 1, 0, 0, 0], [1, 0, 0, 1, 1], [1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 0, 1, 0], [1, 1, 0, 0, 0], ...
Selecting rows in 2-D numpy array based on subset of column values
Suppose I have the following numpy array: a = np.array([[1, 1, 0, 0, 1], [1, 1, 0, 0, 0], [1, 0, 0, 1, 1], [1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 0, 1, 0], [1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [1, 1, 1, 0, 1], [1, 1, 0, 0, 0], ...
[ "Try:\nout = a[(a[:, 1] == 1) & (a[:, 2] == 0)]\n\nGiven a dictionary of column, value pairs, you could use:\nevidence = {1:1,2:0}\nout = a[ np.logical_and.reduce([a[:, c] == v for c, v in evidence.items()]) ]\n\nwhich generalizes the above solution to a sequence of &.\n" ]
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074582332_numpy_python.txt
Q: How can i test a void function in python using pytest? I just started unit testing in python using pytest. Well, when I have a function with a return value, with the "assert" I can compare a certain value with the value that the function return. But if I had a void function that returns nothing and does a print at...
How can i test a void function in python using pytest?
I just started unit testing in python using pytest. Well, when I have a function with a return value, with the "assert" I can compare a certain value with the value that the function return. But if I had a void function that returns nothing and does a print at the end, for example: def function() -> None: number = ...
[ "You can redirect sys.stdout (the stream that print writes to) to a buffer and then examine or assert the contents of the buffer.\n>>> import io\n>>> import contextlib\n>>> \n>>> def f():print('X')\n... \n>>> buf = io.StringIO()\n>>> with contextlib.redirect_stdout(buf):\n... f()\n... \n>>> print(repr(buf.getva...
[ 1, 0 ]
[]
[]
[ "pytest", "python", "unit_testing" ]
stackoverflow_0074578124_pytest_python_unit_testing.txt
Q: Is there a way to get get all mentions of a certain pattern and following values in a string in python Im trying to get all values in a string that's looks like the following: example = 'jnkfksieufsieufsejfuies Title="Something" daowijdaowdnobngfoinbijfgh Title="something else" is there a way to get the values fol...
Is there a way to get get all mentions of a certain pattern and following values in a string in python
Im trying to get all values in a string that's looks like the following: example = 'jnkfksieufsieufsejfuies Title="Something" daowijdaowdnobngfoinbijfgh Title="something else" is there a way to get the values following the Title variable in the string. I thought to use some sort method to get all Title mentions in the ...
[ "Use re.findall with a pattern having a group to match what's after the Title\nexample = 'jnkfksieufsieufsejfuies Title=\"Something\" daowijdaowdnobngfoinbijfgh Title=\"something else\"'\ntitles = re.findall(f'Title=\"([^\"]+)\"', example)\nprint(titles) # ['Something', 'something else']\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074582283_python.txt
Q: Why does my count is coming 1 instead calculating all the digits in the number in Python? I am trying to calculate the number of digits in a random number, for example for number 5675, I am expecting a count value 4 as an output but instead of that , it's returning 1. I have tried to write the logic in a while loo...
Why does my count is coming 1 instead calculating all the digits in the number in Python?
I am trying to calculate the number of digits in a random number, for example for number 5675, I am expecting a count value 4 as an output but instead of that , it's returning 1. I have tried to write the logic in a while loop until the condition satisfied. Below is my code. class Solution(object): def calculate(s...
[ "Your logic is right but You put return count_no in the while loop.\nSo it will returns in the first iteration, and will not continue till the end of your loop.\ndo this:\ndef calculate(self, num):\n count_no = 0\n while num > 0:\n num = num // 10\n count_no += 1\n\n return count_no\n\ntake a...
[ 2, 1, 1 ]
[]
[]
[ "division", "python", "while_loop" ]
stackoverflow_0074582097_division_python_while_loop.txt
Q: How to alternate between multiple threads in Python? I'm trying to alternate between 2 threads: import threading def test1(): for _ in range(3): print("Test1") def test2(): for _ in range(3): print("Test2") t1 = threading.Thread(target=test1) t2 = threading.Thread(target=test2) t1.s...
How to alternate between multiple threads in Python?
I'm trying to alternate between 2 threads: import threading def test1(): for _ in range(3): print("Test1") def test2(): for _ in range(3): print("Test2") t1 = threading.Thread(target=test1) t2 = threading.Thread(target=test2) t1.start() t2.start() t1.join() t2.join() But, the result is...
[ "You can get the alternate result with a global variable, lock and while statement as shown below:\nimport threading\nowner = \"Test1\"\nlock = threading.Lock()\n\ndef test1():\n global owner\n i = 0\n while i < 3:\n lock.acquire()\n if owner == \"Test1\":\n print(\"Test1\")\n ...
[ 0 ]
[ "I think your question here is about why the two functions are not executed simultaneously, but rather in sequence. The answer is that Python has a global interpreter lock (GIL). A single Python process will not (normally) run Python code in multiple parallel threads. There are exceptions to this, such as when runn...
[ -2 ]
[ "alternate", "multithreading", "python", "python_3.x", "python_multithreading" ]
stackoverflow_0074577448_alternate_multithreading_python_python_3.x_python_multithreading.txt
Q: pygame window takes forever to start So I'm following the alien invasion project from python crash course, at the beginning the book teaches how to open a simple window with a specific background color. I literally copy-pasted the code from the book and it still does not work. import pygame import sys from settin...
pygame window takes forever to start
So I'm following the alien invasion project from python crash course, at the beginning the book teaches how to open a simple window with a specific background color. I literally copy-pasted the code from the book and it still does not work. import pygame import sys from settings import Settings def run_game(): # ...
[ "pygame.init() initializes all pygame modules. This may take some time on some systems. If you don't need all pygame modules, just leave it out. For the display and event handling it is not necessary to call pygame.init() at all. If you need other modules, you can itialize them separately (e.g. pygame.font.init(), ...
[ 0 ]
[]
[]
[ "pygame", "python", "python_3.x" ]
stackoverflow_0074568087_pygame_python_python_3.x.txt
Q: hand tracking system using opencv error:TypeError: handDetector.findHands() missing 1 required positional argument: 'img' I'm following an online advanced CV course but the code wouldn't run properly for me. These are the error messages I've gotten: #Traceback (most recent call last): #File "C:\Users\lihua\Pycha...
hand tracking system using opencv error:TypeError: handDetector.findHands() missing 1 required positional argument: 'img'
I'm following an online advanced CV course but the code wouldn't run properly for me. These are the error messages I've gotten: #Traceback (most recent call last): #File "C:\Users\lihua\PycharmProjects\AdvancedComputerVision\HandTrackingModule.py", line 60, #in <module> #main () #File "C:\Users\lihua\PycharmP...
[ "You forgot to instantiate the class handDetector in the main function line 31, you have to add () otherwise you pass him the complete object without instantiating it.\n", "The error lies in the line\nself.hands = self.mpHands.Hands(self.mode,self.maxHands,\n self.detectionCon,se...
[ 0, 0 ]
[]
[]
[ "mediapipe", "opencv", "python" ]
stackoverflow_0072234831_mediapipe_opencv_python.txt
Q: How to Convert PDF file into CSV file using Python Pandas I have a PDF file, I need to convert it into a CSV file this is my pdf file example as link https://online.flippingbook.com/view/352975479/ the code used is import re import parse import pdfplumber import pandas as pd from collections import namedtuple file...
How to Convert PDF file into CSV file using Python Pandas
I have a PDF file, I need to convert it into a CSV file this is my pdf file example as link https://online.flippingbook.com/view/352975479/ the code used is import re import parse import pdfplumber import pandas as pd from collections import namedtuple file = "Battery Voltage.pdf" lines = [] total_check = 0 with pdfpl...
[ "It may help you to see how the surface of a pdf is displayed to the screen. so that one string of plain text is placed part by part on the display. (Here I highlight where the first AM is to be placed.\n\nAs a side issue that first AM in the file is I think at first glance encoded as this block\nBT\n/F1 12 Tf\n1 0...
[ 2, 1 ]
[]
[]
[ "csv", "pandas", "pdf", "pdfplumber", "python" ]
stackoverflow_0074579676_csv_pandas_pdf_pdfplumber_python.txt
Q: How to select a range of the data in urls to views in Django path('<int:book_id>/',views.detail, name = 'detail') How can I modify this line of code to can select the digits that can be used instead of sending any number? as I want the range to be [1 - 5] path('<int:book_id>[1-5]/',views.detail, name = 'detail'),...
How to select a range of the data in urls to views in Django
path('<int:book_id>/',views.detail, name = 'detail') How can I modify this line of code to can select the digits that can be used instead of sending any number? as I want the range to be [1 - 5] path('<int:book_id>[1-5]/',views.detail, name = 'detail'), I've tried this but not correct
[ "You need to check it in the view itself.\ndef detail(request, book_id):\n if book_id < 1 or book_id > 5:\n # do something here when the number is not between or equals 1-5.\n raise PermissionDenied()\n\n\n" ]
[ 0 ]
[]
[]
[ "database", "django_urls", "django_views", "python", "python_re" ]
stackoverflow_0074582395_database_django_urls_django_views_python_python_re.txt
Q: How to display multiple images which numbers of image not same for every attempt I want to display some images with matplotlib with fig.add_subplot but for some attempts I faced some errors like below: Traceback (most recent call last): File "/home/---/Documents/---/---/dataset.py", line 134, in <module> dis...
How to display multiple images which numbers of image not same for every attempt
I want to display some images with matplotlib with fig.add_subplot but for some attempts I faced some errors like below: Traceback (most recent call last): File "/home/---/Documents/---/---/dataset.py", line 134, in <module> display_dicom(dicom,target["mask"]) File "/home/---/Documents/---/---/dataset.py", line...
[ "I rearrange the display_dicom function as below. It is works fine now. It's not the best solution.\ndef display_dicom(dicom,mask):\n\n count,width,height = mask.shape\n if count == 0:\n count = 1 # np.zeros empty mask\n \n number_of_images = count + 1 # masks + dicom\n\n fig = plt.figure(figs...
[ 0 ]
[ "How about using fig, axes = plt.subplots(nrows = rows, ncols = cols, figsize = (10, 10)) and then you iterate over the axes and do .imshow on each one of them? axes will be a 2D array of size nrows x ncols.\n" ]
[ -1 ]
[ "display", "imshow", "matplotlib", "python", "subplot" ]
stackoverflow_0074546863_display_imshow_matplotlib_python_subplot.txt
Q: Why does the model predict ineffectively even though the loss function is low? I'm applying machine learning in the physics field to predict the potential of a molecule. This potential can be described as a 2d array with a shape 64*64. For convenience, I scaled the value of the potential in the range from 0 to 1. ...
Why does the model predict ineffectively even though the loss function is low?
I'm applying machine learning in the physics field to predict the potential of a molecule. This potential can be described as a 2d array with a shape 64*64. For convenience, I scaled the value of the potential in the range from 0 to 1. A sample of the potential after being scaled: My goal is to build a neural network ...
[]
[]
[ "Probably your model is over-fitting the data:\nhttps://www.ibm.com/cloud/learn/overfitting#:~:text=Overfitting%20is%20a%20concept%20in,unseen%20data%2C%20defeating%20its%20purpose.\nA clear sign of over-fitting is when the training loss is very low, but the validation errors are large.\nWhy does this happen? Well,...
[ -1 ]
[ "keras", "loss_function", "machine_learning", "neural_network", "python" ]
stackoverflow_0074582277_keras_loss_function_machine_learning_neural_network_python.txt
Q: How to solve ReadTimeoutError: HTTPSConnectionPool(host='pypi.python.org', port=443) with pip? I recently need to install some packages pip install future pip install scikit-learn pip install numpy pip install scipy I also tried by writin sudo before them but all it came up with the following errors in red lines:...
How to solve ReadTimeoutError: HTTPSConnectionPool(host='pypi.python.org', port=443) with pip?
I recently need to install some packages pip install future pip install scikit-learn pip install numpy pip install scipy I also tried by writin sudo before them but all it came up with the following errors in red lines: Exception: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/pip/basecomm...
[ "Use --default-timeout=100 parameter with the install:\nsudo pip install --default-timeout=100 future\n\n", "sudo pip install --default-timeout=100 future \n\nor alternatively\nexport PIP_DEFAULT_TIMEOUT=100\n\nworked for me on Mac OS X\n", "They are two ways to handle this issue:\nsudo pip install --default-ti...
[ 275, 24, 5, 0, 0, 0 ]
[]
[]
[ "pip", "python" ]
stackoverflow_0043298872_pip_python.txt
Q: Does the MacOS Clipboard have a path to it? I am currently working on a python program that makes use of the clipboard. If you want to know more, I am finding a way to access clipboard history, which is very hard to find for free. I then realized I had no idea how to access the clipboard. My main question is, is t...
Does the MacOS Clipboard have a path to it?
I am currently working on a python program that makes use of the clipboard. If you want to know more, I am finding a way to access clipboard history, which is very hard to find for free. I then realized I had no idea how to access the clipboard. My main question is, is there a way to access the clipboard and read what ...
[ "In macOS, once you copy something else, the previous item disappears. macOS clipboard is designed to hold one item at a time.\nTo get the last clipboard item in python use this:\nimport pyperclip as pc\n\nclipboard = pc.paste()\nprint(clipboard)\n\nA solution to your query:\n\nRun a code that checks the pc.paste()...
[ 2 ]
[]
[]
[ "clipboard", "macos", "pyperclip", "python", "python_3.x" ]
stackoverflow_0074580872_clipboard_macos_pyperclip_python_python_3.x.txt
Q: Using tempfile to insert barcodes into PDF file I'm working on a project where I need to use one large PDF file with 100,000's of images, where I need to insert a custom/variable barcode on every nth page (conditional dependant). The contents of the barcode will change for every insertion, for this example, let's ...
Using tempfile to insert barcodes into PDF file
I'm working on a project where I need to use one large PDF file with 100,000's of images, where I need to insert a custom/variable barcode on every nth page (conditional dependant). The contents of the barcode will change for every insertion, for this example, let's just say based on iteration. I've used PyMuPDF to man...
[ "Your problems are in the area of tempfile handling. Instead of going into detail, I suggest to stick with Pillow and use its facilities exclusively:\n\nconvert the PIL image to a JPEG / PNG as you did, but let PIL save to a memory file\ninsert that memory image using PyMuPDF\n\nimport io # need this for memory ou...
[ 1 ]
[]
[]
[ "barcode", "pdf", "python", "temporary_files" ]
stackoverflow_0074518716_barcode_pdf_python_temporary_files.txt
Q: Python: How to add value to a specific excel sheet using openpyxl? So I wanted to add a value to a specific sheet in this case we have 2 sheets, Student Profile and Student Grades from openpyxl import load_workbook file = load_workbook("Registry.xlsx") sheet = file.active sheet.create_sheet("Student Grades") #Stu...
Python: How to add value to a specific excel sheet using openpyxl?
So I wanted to add a value to a specific sheet in this case we have 2 sheets, Student Profile and Student Grades from openpyxl import load_workbook file = load_workbook("Registry.xlsx") sheet = file.active sheet.create_sheet("Student Grades") #Student Profile sheet["A1"] = "ID No.:" sheet["B1"] = "Last Name:" sheet["C...
[ "You need to create a sheet for the profiles with Workbook.create_sheet as you did for the grades.\nTry this :\nfrom openpyxl import load_workbook\n\nwb = load_workbook(\"Registry.xlsx\")\n\n#Student Profile\nws_sp = wb.create_sheet(\"Student Profiles\")\nws_sp[\"A1\"] = \"ID No.:\"\nws_sp[\"B1\"] = \"Last Name:\"\...
[ 0 ]
[]
[]
[ "excel", "openpyxl", "python" ]
stackoverflow_0074582258_excel_openpyxl_python.txt
Q: Openpyxl chart axis in percent I'm creating charts in excel using openpyxl and I want some of my charts to have y-axes with the units in percent. Is this possible in openpyxl? It's quite easy in xlsxwriter, but I can't figure out how to do it in openpyxl. The code below is for a chart with two y-axes. Thanks! Edit...
Openpyxl chart axis in percent
I'm creating charts in excel using openpyxl and I want some of my charts to have y-axes with the units in percent. Is this possible in openpyxl? It's quite easy in xlsxwriter, but I can't figure out how to do it in openpyxl. The code below is for a chart with two y-axes. Thanks! Edit: Turns out it was as simple as chan...
[ "I tried the following code and it worked for me\nc1 .y_axis.number_format = '0%'\n" ]
[ 0 ]
[]
[]
[ "charts", "excel", "openpyxl", "python" ]
stackoverflow_0038620551_charts_excel_openpyxl_python.txt
Q: Try... except is wrong I was working on a function that test functions and I found that y try except was wrong at all... In fact, when I am trying to test a sorting function (the one by selection) it returns me that the index was out of range and it's not the case when I try the function independently with the sam...
Try... except is wrong
I was working on a function that test functions and I found that y try except was wrong at all... In fact, when I am trying to test a sorting function (the one by selection) it returns me that the index was out of range and it's not the case when I try the function independently with the same list... Here is the code :...
[ "if L[elm] > L[elm + 1]: gives a list index out of range error when elm == len(L) - 1. The easiest fix is to change verifyList to:\ndef verifyList(L: list) -> bool:\n return L == sorted(L)\n\nWith this change your function passes the test.\n" ]
[ 2 ]
[]
[]
[ "debugging", "python", "try_except" ]
stackoverflow_0074581818_debugging_python_try_except.txt
Q: updating a nested dictionary getting ReferenceError: weakly-referenced object no longer exists I am connecting to my mongodb using pymongo and trying to append to a nested dictionary using the code: myquery = User.objects.filter(username=current_user) my_dict = myquery[0]['spare_2'] my_dict[quiz_id] = {'question1'...
updating a nested dictionary getting ReferenceError: weakly-referenced object no longer exists
I am connecting to my mongodb using pymongo and trying to append to a nested dictionary using the code: myquery = User.objects.filter(username=current_user) my_dict = myquery[0]['spare_2'] my_dict[quiz_id] = {'question1': 9, 'question2': 9, 'question3': 9, 'question4': 9, 'question5': 9, 'question6': 9, 'question7': 9,...
[ "I changed the way I was updating the dictionary and it solved the problem:\nmyquery = User.objects.filter(username=current_user)\nmy_dict = myquery[0]['spare_2']\nappend_dict = {quiz_id: 9, 'question2': 9, 'question3': 9, 'question4': 9, 'question5': 9, 'question6': 9, 'question7': 9, 'question8': 9, 'question9': ...
[ 0 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0074581184_mongodb_pymongo_python.txt
Q: how do i print the 2d list as an even table? #Create a program that allows 2 players to throw a 6 sided dice and record the roll value 10 times. #The winner is the player with the highest total #This task must store the results in a 2D array #Extra: #Work out the average roll across the 10 throws per player a...
how do i print the 2d list as an even table?
#Create a program that allows 2 players to throw a 6 sided dice and record the roll value 10 times. #The winner is the player with the highest total #This task must store the results in a 2D array #Extra: #Work out the average roll across the 10 throws per player and display the result #Frequency analysis broken ...
[ "You can use the following sintax:\nprint('%5s' % str(c))\n\nBasically:\n\nthe % character informs python it will have to substitute something\nto a token\nthe s character informs python the token will be a string\nthe 5 (or whatever number you wish) informs python to pad the string\nwith spaces up to 5 characters....
[ 1 ]
[ "to calculate difference between 2 names\ndiff = abs(len(results[2][0]) - len(results[3][0])) #abs = absolute value\n\ncompare 2 lengths of names:\nif len(results[2][0] ) > len(results[3][0]):\n results[3][0] = results[3][0] + \" \"*diff # add spaces much as difference between 2 names\nelse:\n results[2][0] =...
[ -1 ]
[ "arrays", "list", "multidimensional_array", "python" ]
stackoverflow_0074582309_arrays_list_multidimensional_array_python.txt
Q: How to start a maximum of X threads ? Python Hello i have the following question: My goal is to submit an email to an online list. The way that I have it right now starts as many threads as emails in my 01.csv file but i want it to have a maximum of 10 threads and once 1 thread is done continue with the next one b...
How to start a maximum of X threads ? Python
Hello i have the following question: My goal is to submit an email to an online list. The way that I have it right now starts as many threads as emails in my 01.csv file but i want it to have a maximum of 10 threads and once 1 thread is done continue with the next one but never goes above 10 active threads. This is my ...
[ "You can either implement your own queue and have 10 threads started, that each pull from the queue, or - for this simple task - you could also use a ThreadPoolExecutor with a given number of workers.\nfrom concurrent.futures import ThreadPoolExecutor\n\nwith ThreadPoolExecutor(max_workers=10) as ex:\n for user ...
[ 0 ]
[]
[]
[ "multithreading", "python", "python_3.x", "python_multithreading" ]
stackoverflow_0074581847_multithreading_python_python_3.x_python_multithreading.txt
Q: Python variable scoping in nested function calls I come to this code in a LeetCode problem class Solution: def maxProduct(self, root): self.res = total = 0 def s(root): if not root: return 0 left, right = s(root.left), s(root.right) self.res = max(self.res, ...
Python variable scoping in nested function calls
I come to this code in a LeetCode problem class Solution: def maxProduct(self, root): self.res = total = 0 def s(root): if not root: return 0 left, right = s(root.left), s(root.right) self.res = max(self.res, left * (total - left), right * (total - right)) ...
[ "The problem is that the nested function s has it's own variable scope.\nWhile it can read variables (like res) from the enclosing scope (maxProduct),\nany assignment (e.g. res = max(...))\nwill introduce a variable in the scope of s, instead of\nwriting to the outer (res).\nBecause in this case maxProduct wants to...
[ 0, 0 ]
[]
[]
[ "python", "scope", "variables" ]
stackoverflow_0074582432_python_scope_variables.txt
Q: Jump to another message via a button and assign another role at the same time I have a problem. I have created a button that lets a user jump to another message in another text channel. The user has Role1 as soon as he presses the button he should get the role Role2 and jump to the textchannel which is only enable...
Jump to another message via a button and assign another role at the same time
I have a problem. I have created a button that lets a user jump to another message in another text channel. The user has Role1 as soon as he presses the button he should get the role Role2 and jump to the textchannel which is only enabled for Role2. Unfortunately this does not work because the following error occurs di...
[ "As I mentioned in the comments, you are passing a class object to your view not an interaction object. And since add_roles is a coroutine you can't await it in __init__ so you better do it in the command itself instead. Hence, your view doesn't even need the interaction object.\nclass Google(discord.ui.View):\n ...
[ 0 ]
[]
[]
[ "discord", "discord.py", "python", "python_3.x" ]
stackoverflow_0074473466_discord_discord.py_python_python_3.x.txt
Q: ACCESS_TOKEN_SCOPE_INSUFFICIENT error with updating sheet using google sheets api (python) I've been making a program in python that is intended to have each user be able to use it to access a single google sheet and read and update data on it only in the allowed ways, so ive used google api on the google develope...
ACCESS_TOKEN_SCOPE_INSUFFICIENT error with updating sheet using google sheets api (python)
I've been making a program in python that is intended to have each user be able to use it to access a single google sheet and read and update data on it only in the allowed ways, so ive used google api on the google developer console and managed to get test accounts reading the information that ive manually put in, how...
[ "You are using the sheets.values.update method. If you check the documentation. you will see that this method requires one of the following scopes of authorization\n\nYour code apears to only request 'https://www.googleapis.com/auth/spreadsheets.readonly' read only access is not going to let you write to the file. ...
[ 1 ]
[]
[]
[ "google_api_python_client", "google_oauth", "google_sheets", "google_sheets_api", "python" ]
stackoverflow_0074582213_google_api_python_client_google_oauth_google_sheets_google_sheets_api_python.txt
Q: discord.py change nickname after a modal submit I wanted to change my modal a nickname but unfortunately do not know exactly how this is my code class RenameModal(ui.Modal, title="Rename"): vorname = ui.TextInput(label="Vorname", placeholder="Mein Vorname lautet...", required=True, style=discord.TextStyle.short)...
discord.py change nickname after a modal submit
I wanted to change my modal a nickname but unfortunately do not know exactly how this is my code class RenameModal(ui.Modal, title="Rename"): vorname = ui.TextInput(label="Vorname", placeholder="Mein Vorname lautet...", required=True, style=discord.TextStyle.short) nachname = ui.TextInput(label="Nachname", placehol...
[ "Try changing\nawait interaction.user.edit\n\nto\nawait interaction.member.edit\n\nas user is the global term that is used for all over Discord, and member is the term used for a user in a specific Guild.\n" ]
[ 0 ]
[]
[]
[ "discord", "discord.py", "discord_interactions", "python" ]
stackoverflow_0074571147_discord_discord.py_discord_interactions_python.txt
Q: How to implement CSV Writer in a named temporary - Python? Basically, I need final a csv file, whose contents look like Header, and then the data: (Boto3 upload_file does the job of writing temporary file, into csv) Expectation: Name,Code Adam,12 I am able to get this, by using: with tempfile.NamedTemporaryFile(m...
How to implement CSV Writer in a named temporary - Python?
Basically, I need final a csv file, whose contents look like Header, and then the data: (Boto3 upload_file does the job of writing temporary file, into csv) Expectation: Name,Code Adam,12 I am able to get this, by using: with tempfile.NamedTemporaryFile(mode="a+t", suffix =".csv", delete=True) as fileName: for data...
[ "This doesn't have anything to do with the temporary directory.\nHere is part of the introduction about CSV writer objects (bold added):\n\nA row must be an iterable of strings or numbers for Writer objects and a dictionary mapping fieldnames to strings or numbers... for DictWriter objects\n\nBut you are passing in...
[ 2 ]
[]
[]
[ "airflow", "csv", "python", "python_3.x" ]
stackoverflow_0074582234_airflow_csv_python_python_3.x.txt
Q: Convert parquet to list of objects in python I am reading a parquet file with panda: import pandas as pd df = pd.read_parquet('myfile.parquet', engine='pyarrow') The file has the following structure: company_id user_id attribute_name attribute_value timestamp 1 116664 111f07000612 first_name Tom 2022-03-23 17:1...
Convert parquet to list of objects in python
I am reading a parquet file with panda: import pandas as pd df = pd.read_parquet('myfile.parquet', engine='pyarrow') The file has the following structure: company_id user_id attribute_name attribute_value timestamp 1 116664 111f07000612 first_name Tom 2022-03-23 17:11:58 2 116664 111f07000612 last_name Crui...
[ "Hi Hope you are doing well!\nYou can achieve it with something similar to this \n\nfrom pprint import pprint\n\nimport pandas as pd\n\n\n# because I don't have the exact parquet file, I will just mock it\n# df = pd.read_parquet(\"myfile.parquet\", engine=\"pyarrow\")\ndf = pd.DataFrame(\n {\n \"company_...
[ 0 ]
[]
[]
[ "pandas", "parquet", "python" ]
stackoverflow_0074563600_pandas_parquet_python.txt
Q: what will happen if we pass an argument to a C++ recursive function like "pass_by_keyword" in python? int dfs(int idx, int mv, char gest){ if (idx > n || mv > k){ return 0; } int tmp1 = 0; if(mv<k){ if(fj[idx]=='H'){ if(gest!='P'){ tmp1=1+dfs(idx+1,mv+1, ...
what will happen if we pass an argument to a C++ recursive function like "pass_by_keyword" in python?
int dfs(int idx, int mv, char gest){ if (idx > n || mv > k){ return 0; } int tmp1 = 0; if(mv<k){ if(fj[idx]=='H'){ if(gest!='P'){ tmp1=1+dfs(idx+1,mv+1, gest='P'); } else{ tmp1=1+dfs(idx+1, mv, gest='P'); } ...
[ "C++ does not support named parameters. What you are doing is equivalent to this:\ngest='P';\ntmp1=1+dfs(idx+1,mv+1, gest);\n\n" ]
[ 1 ]
[ "In C++ you cannot specify the names of the parameters to use a value for when calling a function the way it's possible in python.\ndfs(idx+1,mv+1, gest='P')\n\nwill overwrite the value of the gest parameter with 'P' and then evaluate to the new value, so after this expression gest has a different value.\nI.e. the ...
[ -1 ]
[ "c++", "python" ]
stackoverflow_0074582565_c++_python.txt
Q: Reading csv file with no column names python Hi I wanted to ask that i got a data of 80 columns and all of them have no names and its 80 columns and 12500 rows long and there are blank columns between them 8,1,,0,1993,146,,2,1,,,,,,,,,,2.1,0.65,0.15,0.65,19.1,,18.03,,,19.6,,,0.06,,,,,,19.1,19.6294717,19.36473585,...
Reading csv file with no column names python
Hi I wanted to ask that i got a data of 80 columns and all of them have no names and its 80 columns and 12500 rows long and there are blank columns between them 8,1,,0,1993,146,,2,1,,,,,,,,,,2.1,0.65,0.15,0.65,19.1,,18.03,,,19.6,,,0.06,,,,,,19.1,19.6294717,19.36473585,0.06,,,,51.25,19.3,23.3,-0.04,-0.04,0.34,0.07,0.16...
[ "IIUC, use this pandas.read_csv with header=None and pandas.DataFrame.dropna on axis=1:\ndata = pd.read_csv(\"CollectedData.csv\", header=None).dropna(axis=1, how=\"all\")\n\nIf you need to give names to each column, use names parameter:\ncols_names= [\"ColA\", \"ColB\", \"ColC\", ..]\n\ndata = (\n pd.read_c...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074582725_dataframe_pandas_python.txt
Q: how to run two activities at the same time in python i want to make two lists from the same source of html data but i want to collect the data at the same time so as to avoid a possible change in the data. this is the code i have: lok = [] num = 6 for _ in range(num): inner = driver.find_element_by_xpath( ...
how to run two activities at the same time in python
i want to make two lists from the same source of html data but i want to collect the data at the same time so as to avoid a possible change in the data. this is the code i have: lok = [] num = 6 for _ in range(num): inner = driver.find_element_by_xpath( "/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/...
[ "You can append to lokk at the same time as lok and then only collect one more value in the second loop\nlok = []\nnum = 6\nfor _ in range(num):\n inner = driver.find_element_by_xpath(\n \"/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div[2]/div/div/div[2]/div[5]/span[1]\").get_attribute(...
[ 0 ]
[]
[]
[ "html", "list", "python" ]
stackoverflow_0074582700_html_list_python.txt
Q: How do I make Selenium Driver in Python wait until .get() page loads fully to get entire page source? My Selenium Driver is suddenly receiving None when requesting from a page. I want to store urlx inside dictionary data but my driver.get(x) is returning None. self.data= { "google.com": page_source, "stackoverflow...
How do I make Selenium Driver in Python wait until .get() page loads fully to get entire page source?
My Selenium Driver is suddenly receiving None when requesting from a page. I want to store urlx inside dictionary data but my driver.get(x) is returning None. self.data= { "google.com": page_source, "stackoverflow.com/....": page_source, etc... } I tried using self.data[link] = self.driver.get(link) try...
[ "Reference this answer to the above question.\ndriver.get(\"https://stackoverflow.com\")\npageSource = driver.page_source\nfileToWrite = open(\"page_source.html\", \"w\")\nfileToWrite.write(pageSource)\nfileToWrite.close()\nfileToRead = open(\"page_source.html\", \"r\")\nprint(fileToRead.read())\nfileToRead.close()...
[ 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074581921_python_selenium.txt
Q: Pygame: update in the while loop not succesful A helicopter is shot at. If he is hit, he falls. At the same time, a parachute releases from the helicopter. If the parachute is shot at and also hit by a bullet, the image of the parachute should be replaced with another image. The jump with the parachute is done by ...
Pygame: update in the while loop not succesful
A helicopter is shot at. If he is hit, he falls. At the same time, a parachute releases from the helicopter. If the parachute is shot at and also hit by a bullet, the image of the parachute should be replaced with another image. The jump with the parachute is done by the function absprung. The parachute is created with...
[ "beschuss is an attribute of a single Falschirm object, but not an attribute of fallschirme. pygame.sprite.groupcollide returns a dictionary of objects that were hit. You must set the attribute to these objects.\nhits = pygame.sprite.groupcollide(fallschirme, bullets,False,True) \nfor fallschirm in hits: \n...
[ 2 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074580019_pygame_python.txt
Q: Python throwing expected indented block error for no reason My python script throwing expected indented block for no reason? My Code def start(): if sibr == "0x1": ibrs = "1" print(error) time.sleep(0.1) os.system("cls" if os name == "NT" else "clear") if sibr != "0x1": ...
Python throwing expected indented block error for no reason
My python script throwing expected indented block for no reason? My Code def start(): if sibr == "0x1": ibrs = "1" print(error) time.sleep(0.1) os.system("cls" if os name == "NT" else "clear") if sibr != "0x1": cmd() My output Traceback (most recent call last): File "/...
[]
[]
[ "The error probably occurs above this block of code since IndetationError is already thrown for the def start(): line\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0074582795_python.txt
Q: How to find the namespace of a class easily in Python without using an IDE? Normally, I use IntelliJ for python programming. But sometimes I don't have access to it or just to make a quick edit I open a Python file in a text editor. At those times, it is really difficult to find the namespace of a class. I am goo...
How to find the namespace of a class easily in Python without using an IDE?
Normally, I use IntelliJ for python programming. But sometimes I don't have access to it or just to make a quick edit I open a Python file in a text editor. At those times, it is really difficult to find the namespace of a class. I am googling it. But it takes time. Is there a better way to do this? Edit: Looking at t...
[ "Let us not forget about dir(), which is heavily used by those of us who use vim as our IDE. \n", "Try inspect.getmodule:\n>>> import inspect\n>>> class Foo:\n pass\n\n>>> inspect.getmodule(Foo)\n<module '__main__' (built-in)>\n\nLots of other cool stuff in there, too.\n", "I use ctags and I've got my site-p...
[ 3, 2, 2, 1, 0 ]
[ "You can try :\nimport array\nprint(array.__dict__) \n\n" ]
[ -2 ]
[ "python" ]
stackoverflow_0002038002_python.txt
Q: Show label value in segmented final image I'd like to show label value in final results displaying. I segmented input image using k means clustering and output are 25 classes. My code: import matplotlib.pyplot as plt from skimage.segmentation import slic from skimage import color img_bounds = slic(img_blur...
Show label value in segmented final image
I'd like to show label value in final results displaying. I segmented input image using k means clustering and output are 25 classes. My code: import matplotlib.pyplot as plt from skimage.segmentation import slic from skimage import color img_bounds = slic(img_blurred, # filtered input image ...
[ "I don't have time to write a full answer at the moment, but your variable img_bounds will have 1 where the pixel is of class 1, and 2 where the pixel is of class 2 and so on...\nYou can make a binary image of the pixels in, say, class 4 with:\nc4 = ((img_bounds == 4) * 255).astype(np.uint8)\n\nimport cv2\ncv2.imwr...
[ 0 ]
[]
[]
[ "python", "scikit_image" ]
stackoverflow_0074581701_python_scikit_image.txt
Q: Python Logistic Regression Future Prediction What would be a way to make something take data points, plot them, and show the predicted future, as such: I tried all current algorithms available and noticed that everything is a straight (best fit) line - how does this site do it? A: As per this site - There are m...
Python Logistic Regression Future Prediction
What would be a way to make something take data points, plot them, and show the predicted future, as such: I tried all current algorithms available and noticed that everything is a straight (best fit) line - how does this site do it?
[ "As per this site - There are many time-series forecasting methods to choose from...\n- Autoregression (AR)\n- Moving Average (MA)\n- Autoregressive Moving Average (ARMA)\n- Autoregressive Integrated Moving Average (ARIMA)\n- Seasonal Autoregressive Integrated Moving-Average (SARIMA)\n- Seasonal Autoregressive Inte...
[ 0 ]
[]
[]
[ "logistic_regression", "python" ]
stackoverflow_0074582839_logistic_regression_python.txt
Q: how can i convert a list of letters into a dictionary List that contains strings (https://i.stack.imgur.com/pOzik.png) This is a string list of items and I want to extract the dictionary {} that is from the 6th character and after. Should I convert list to dictionary? data= '[\n {\n "registration_number"...
how can i convert a list of letters into a dictionary
List that contains strings (https://i.stack.imgur.com/pOzik.png) This is a string list of items and I want to extract the dictionary {} that is from the 6th character and after. Should I convert list to dictionary? data= '[\n {\n "registration_number": "aj13870",\n "status": "registreret",\n "st...
[ "First, you can make you data a python list object via json.loads():\nimport json\n\n\ntext = '[\\n {\\n \"registration_number\": \"aj13870\",\\n \"status\": \"registreret\",\\n \"status_date\": \"2013-10-07t10:33:46.000+02:00\",\\n \"type\": \"personbil\",\\n \"use\": \"privat...
[ 1, 0, 0 ]
[]
[]
[ "dictionary", "list", "python", "string" ]
stackoverflow_0074582893_dictionary_list_python_string.txt
Q: CodeWars Challenge Error: Replacing with Alphabet Position I am trying to solve this challenge, but my code doesn't seem to work, is there a fix? Here is the question: In this kata you are required to, given a string, replace every letter with its position in the alphabet. If anything in the text isn't a letter, i...
CodeWars Challenge Error: Replacing with Alphabet Position
I am trying to solve this challenge, but my code doesn't seem to work, is there a fix? Here is the question: In this kata you are required to, given a string, replace every letter with its position in the alphabet. If anything in the text isn't a letter, ignore it and don't return it. "a" = 1, "b" = 2, etc. Example alp...
[ "As previous posts (@John Coleman) suggested, it's easier to just use ord to solve it:\nCredit to him and earlier comments.\n\ndef alphabet_position(s):\n return \" \".join(str(ord(c)-ord(\"a\")+1) for c in s.lower() if c.isalpha())\n\n# Or you still like your original mapping approach:\n\ndef alphabet_position(te...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0074582552_python.txt
Q: ModuleNotFoundError: No module named 'pynput' error on PyCharm import pynput from pynput.keyboard import Key, Listener def keyenter(key): print("{0} pressed".format(key)) def keyexit(key): if key == Key.esc: return False with Listener(keyenter=keyenter, keyexit=keyexit) as listener: listener.joi...
ModuleNotFoundError: No module named 'pynput' error on PyCharm
import pynput from pynput.keyboard import Key, Listener def keyenter(key): print("{0} pressed".format(key)) def keyexit(key): if key == Key.esc: return False with Listener(keyenter=keyenter, keyexit=keyexit) as listener: listener.join() I keep getting the error -- ModuleNotFoundError: No module name...
[ "Make sure that you did install pynput:\n$ python3 -m pip install pynput\n\nAnd config the Python interpreter in Pycharm correctly, to the global python3 or your specific venv.\n", "A way that worked for me is installing pynput directing from inside PyCharm by using the terminal found on the bottom right.\nInside...
[ 0, 0, 0, 0 ]
[]
[]
[ "modulenotfounderror", "pycharm", "pynput", "python" ]
stackoverflow_0070321580_modulenotfounderror_pycharm_pynput_python.txt
Q: When using CDK and a docker image, cache pip dependencies between PythonFunction builds? The issue I'm facing is similar to https://github.com/aws/aws-cdk/issues/9406 but the resolution to that seems? to just be to use a layer. I have about 75 Python Lambda functions which I'm deploying using CDK. The functions ha...
When using CDK and a docker image, cache pip dependencies between PythonFunction builds?
The issue I'm facing is similar to https://github.com/aws/aws-cdk/issues/9406 but the resolution to that seems? to just be to use a layer. I have about 75 Python Lambda functions which I'm deploying using CDK. The functions have a mix of dependencies from both requirements.txt and some private libraries which I copy in...
[ "So I ended up just using the layers approach. I create one 'common' layer with most of my utility code in it, and then a couple of other layers (which come with a big dependency tree each) that are only used in a couple of places.\nWhen building, if some common code has changed, it'll rebuild the common layer, and...
[ 0 ]
[]
[]
[ "aws_cdk", "aws_cdk_python", "docker", "python" ]
stackoverflow_0074256281_aws_cdk_aws_cdk_python_docker_python.txt
Q: pygame.QUIT() - TypeError: 'int' object is not callable I'm fairly new to python. I'm writing a code for a simple alien invasion game but I'm getting this error. import sys import pygame from settings import Settings from ship import Ship import game_functions as gf def run_game(): pygame.init() ai_settin...
pygame.QUIT() - TypeError: 'int' object is not callable
I'm fairly new to python. I'm writing a code for a simple alien invasion game but I'm getting this error. import sys import pygame from settings import Settings from ship import Ship import game_functions as gf def run_game(): pygame.init() ai_settings = Settings() screen = pygame.display.set_mode((ai_sett...
[ "As shown in your error message, this line event.type==pygame.QUIT() is the issue. The error TypeError: 'int' object is not callable means that you are trying to call an int, which means that you are trying to treat an int as a function, which in turn means that you have parentheses () after an int value. The only ...
[ 4, 0, 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0057135789_pygame_python.txt
Q: Two threads print even and odd numbers between 0 to 5 alternately in Python I'm trying to get the result below running 2 threads alternately. *Between 0 to 5, thread A prints even numbers and thread B prints odd numbers (I use Python 3.8.5): A:0 B:1 A:2 B:3 A:4 B:5 So, with global variables, locks and while state...
Two threads print even and odd numbers between 0 to 5 alternately in Python
I'm trying to get the result below running 2 threads alternately. *Between 0 to 5, thread A prints even numbers and thread B prints odd numbers (I use Python 3.8.5): A:0 B:1 A:2 B:3 A:4 B:5 So, with global variables, locks and while statements, I created the code below to try to get the result above: import threading ...
[ "The reason you are seeing the issue, is that the thread is still within the while loop when i moves from 5 to 6. The thread seems to obtain lock before the value is updated. i.e. The speed of release and lock is quicker than the assignment of i. So the thread goes through one more round, but the only check you hav...
[ 2 ]
[]
[]
[ "alternate", "multithreading", "python", "python_3.x", "python_multithreading" ]
stackoverflow_0074582964_alternate_multithreading_python_python_3.x_python_multithreading.txt
Q: How to delete dictionary values simply at a specific key 'path'? I want to implement a function that: Given a dictionary and an iterable of keys, deletes the value accessed by iterating over those keys. Originally I had tried def delete_dictionary_value(dict, keys): inner_value = dict for key in keys: ...
How to delete dictionary values simply at a specific key 'path'?
I want to implement a function that: Given a dictionary and an iterable of keys, deletes the value accessed by iterating over those keys. Originally I had tried def delete_dictionary_value(dict, keys): inner_value = dict for key in keys: inner_value = inner_value[key] del inner_value return dic...
[ "Don't use a string-evaluation approach. Try to iteratively move to the last dictionary and delete the key-value pair from it. Here a possibility:\ndef delete_key(d, value_path):\n # move to most internal dictionary\n for kp in value_path[:-1]:\n if kp in dd and isinstance(d[kp], dict): \n d...
[ 0, 0 ]
[]
[]
[ "dictionary", "key_value", "python" ]
stackoverflow_0074581982_dictionary_key_value_python.txt
Q: How to create a dictionary from a CSV file, appending multiple values to three keys? I need to be able to append multiple values from a CSV file to a dictionary that has three keys. The keys are morning, midday, and night. The values should come from each row of the CSV file. Ideally, it should look like below. I ...
How to create a dictionary from a CSV file, appending multiple values to three keys?
I need to be able to append multiple values from a CSV file to a dictionary that has three keys. The keys are morning, midday, and night. The values should come from each row of the CSV file. Ideally, it should look like below. I can't use numpy or csv modules, so those options are not available. It has to work with no...
[ "How about changing your strategy and doing it like this:\nmorning_list= []\nmidday_list= []\nnight_list= []\ntime_dict = dict()\n\nwith open(\"stats.csv\", \"r\") as data_file:\n headers = data_file.readline()\n\n for line in data_file:\n Time, VS = line.split(\",\")\n if Time == \"morning\":\n...
[ 1, 1 ]
[]
[]
[ "csv", "dictionary", "python" ]
stackoverflow_0074582868_csv_dictionary_python.txt
Q: How do I parse a string to a float or int? How can I convert a str to float? "545.2222" → 545.2222 How can I convert a str to int? "31" → 31 For the reverse, see Convert integer to string in Python and Converting a float to a string without rounding it. Please instead use How can I read inputs as numbe...
How do I parse a string to a float or int?
How can I convert a str to float? "545.2222" → 545.2222 How can I convert a str to int? "31" → 31 For the reverse, see Convert integer to string in Python and Converting a float to a string without rounding it. Please instead use How can I read inputs as numbers? to close duplicate questions where OP r...
[ ">>> a = \"545.2222\"\n>>> float(a)\n545.22220000000004\n>>> int(float(a))\n545\n\n", "Python2 method to check if a string is a float:\ndef is_float(value):\n if value is None:\n return False\n try:\n float(value)\n return True\n except:\n return False\n\nFor the Python3 version of is_float...
[ 3020, 589, 572, 161, 83, 82, 35, 27, 27, 21, 19, 17, 14, 11, 8, 7, 7, 6, 6, 6, 6, 4, 3, 2, 1, 1, 0, 0, 0, 0 ]
[ "Use:\n>>> str_float = \"545.2222\"\n>>> float(str_float)\n545.2222\n>>> type(_) # Check its type\n<type 'float'>\n\n>>> str_int = \"31\"\n>>> int(str_int)\n31\n>>> type(_) # Check its type\n<type 'int'>\n\n", "Here's another interpretation of your question (hint: it's vague). It's possible you're looking for som...
[ -1, -12 ]
[ "floating_point", "integer", "parsing", "python", "type_conversion" ]
stackoverflow_0000379906_floating_point_integer_parsing_python_type_conversion.txt
Q: msvcrt Module equivalent on Ubuntu With python on windows, I have been making a game. However, this game requires the msvcrt module, which is only available on windows. I need the function msvcrt.getch(). If I was to make it possible to run this game on Ubuntu, or any linux computer in general, what module, if any...
msvcrt Module equivalent on Ubuntu
With python on windows, I have been making a game. However, this game requires the msvcrt module, which is only available on windows. I need the function msvcrt.getch(). If I was to make it possible to run this game on Ubuntu, or any linux computer in general, what module, if any, would I be able to use? I would be fin...
[ "The library msvcrs is only available on Windows. If you want to use a release for Ubuntu, check getch function.\nimport getch\n\nThis function get the pressed-key in keyboard.\nHope it help!\n", "From the command line, if necessary (as Luan Souza said above):\npip install getch\n\nIn your code:\ntry:\n from g...
[ 2, 0 ]
[]
[]
[ "linux", "python", "ubuntu" ]
stackoverflow_0038172907_linux_python_ubuntu.txt
Q: AttributeError: module 'cv2.cv2' has no attribute 'cv' I think I have some issues with the windows system or python 3.6 version. I am facing some attribute error. I have checked and double checked my code and there is no error and i also compare my code to others and i have seen there is no error. then why i am fa...
AttributeError: module 'cv2.cv2' has no attribute 'cv'
I think I have some issues with the windows system or python 3.6 version. I am facing some attribute error. I have checked and double checked my code and there is no error and i also compare my code to others and i have seen there is no error. then why i am facing this kind of error. I am adding my code here: and i am...
[ "in Opencv3 the cv module is deprecated. So, in line 11 you can initialize the font like following:\nfont = cv2.FONT_HERSHEY_SIMPLEX\n\n", "font = cv2.cv.CV_FONT_HERSHEY_SIMPLEX\nI worked on different variable (CV_CAP_PROP_FRAME_WIDTH), and it took me soo long to understand that you also need to remove the \"CV_\...
[ 22, 5, 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0044640911_opencv_python.txt
Q: Catch an exception if no debugger is attached Is it possible to catch an exception in Python only if a debugger is not attached, and bypass it to the debugger otherwise? An equivalent C# code: // Entry point try { ... } catch (Exception e) when (!Debugger.IsAttached) { MessageBox.Show(e); } A: You could ...
Catch an exception if no debugger is attached
Is it possible to catch an exception in Python only if a debugger is not attached, and bypass it to the debugger otherwise? An equivalent C# code: // Entry point try { ... } catch (Exception e) when (!Debugger.IsAttached) { MessageBox.Show(e); }
[ "You could check if you are having a Debugger. The question how that is done was awnsered here: How to detect that Python code is being executed through the debugger?\nif not you gould pass the error thorug by using raise and the e object.\ntry:\n pass\nexcept Exception as e:\n if !Debugger.IsAttached:\n ...
[ 1 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0074583075_exception_python.txt
Q: How to write the coding problem with python? Three empty cans can be exchanged for a new one. Suppose you have N cans of soda, try to use the program to solve how many cans of soda you can drink in the end? Input description: Input a positive integer N. ex.5 / ex.100 Output description: The maximum number of sodas...
How to write the coding problem with python?
Three empty cans can be exchanged for a new one. Suppose you have N cans of soda, try to use the program to solve how many cans of soda you can drink in the end? Input description: Input a positive integer N. ex.5 / ex.100 Output description: The maximum number of sodas that can be drunk, and must have a newline charac...
[ "You can try this way -\ndef get_total_cans(n):\n s = n # we can get at least n cans\n while n > 2:\n s += 1\n n -= 3 # 3 exchanged\n n += 1 # got 1 for the exchange\n return s\n\nn = int(input())\nprint(get_total_cans(n))\n\nThe logic is simple and comments are added to explain.\nIn y...
[ 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074582909_python.txt
Q: pset 6 DNA, checking database for matching profiles I am currently on pset 6 dna in cs50, I have completed the majoraty of the problem, but I can't seem to wrap my head round the final step, checking the database for matching profiles. all of my code is located below to provide context for variables, I am unsure o...
pset 6 DNA, checking database for matching profiles
I am currently on pset 6 dna in cs50, I have completed the majoraty of the problem, but I can't seem to wrap my head round the final step, checking the database for matching profiles. all of my code is located below to provide context for variables, I am unsure on the usage of my if loop and what I should be comparing,...
[ "Before checking the database for matching profiles, you need to check your previous steps. When you do, you will find several problems:\n\nFirst, sequence is not what you think it is. (You probably think\nit is a string. Instead, it is a list of single character\nstrings.) This occurs because you create sequence ...
[ 1 ]
[]
[]
[ "cs50", "python" ]
stackoverflow_0074577516_cs50_python.txt
Q: How to make event.respond but just first sender will be responded? with Telethon I have a question regarding the event on the telethon. So, I want to make something like event.respond(). But only the first sender will be responded by the bot. If there is a second sender - and the rest are not responded to by bots....
How to make event.respond but just first sender will be responded? with Telethon
I have a question regarding the event on the telethon. So, I want to make something like event.respond(). But only the first sender will be responded by the bot. If there is a second sender - and the rest are not responded to by bots. How to make such a method? Thanks a lot for your answer. I use Telethon. I've tried u...
[ "You can save the first sender somewhere and check it in subsequent events. One way to do it us using a global:\nallowed_id = None\n\n@client.on(events.NewMessage)\nasync def handler(event):\n global allowed_id\n if allowed_id is None:\n allowed_id = event.sender_id\n\n if event.sender_id == allowed...
[ 0 ]
[]
[]
[ "python", "python_telegram_bot", "telegram", "telethon" ]
stackoverflow_0074579571_python_python_telegram_bot_telegram_telethon.txt
Q: conda install spyder=5.3.3 stuck on solving env I couldn't find much help on the internet, which is why I'm asking this here. Spyder has an issue where input() will cause an issue to the app. I've heard that spyder 5.3.3 has this issue fixed. I have done: conda update conda conda update anaconda However, when I t...
conda install spyder=5.3.3 stuck on solving env
I couldn't find much help on the internet, which is why I'm asking this here. Spyder has an issue where input() will cause an issue to the app. I've heard that spyder 5.3.3 has this issue fixed. I have done: conda update conda conda update anaconda However, when I try conda install spyder=5.3.3, it says failed with in...
[ "I tried all the solution posted but they does not work for my problem. I finally solved it by first uninstalling the existing spyder version and installing a new one. To do this, use this:\nconda uninstall spyder\nconda install spyder = 5.3.3\n\n", "I don't have a great solution, ran into the same issue myself, ...
[ 3, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "anaconda", "python" ]
stackoverflow_0073874177_anaconda_python.txt
Q: Python: Call function on each/any file in a module (dynamically) I want to make a library of files, where each file does basically the same - solving math problems - but each implementation is slightly different. The way I want to set this up is as follows: main.py (has a list of all problems, user can en...
Python: Call function on each/any file in a module (dynamically)
I want to make a library of files, where each file does basically the same - solving math problems - but each implementation is slightly different. The way I want to set this up is as follows: main.py (has a list of all problems, user can enter parameters) solves\ prob001.py Problem, with definition of i...
[ "Files: https://gist.github.com/thenarfer/330a4f978eab7c40e84e1dbaee062ebd\nCheck out the files for this script. Make sure to create the directory tree as follows:\nmath_solver_main.py \nsolves\\\n prob001.py \n prob002.py\n ...\n\n\n\nYou can add more problems and the script will recognize it. ...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074581427_python_python_3.x.txt
Q: How to define expected body of response containing list of indefinite number of JSON items in pytest? I just started learning how to test API in python so please bear with me. I want to test the endpoint that returns all users from database. My expected body looks like below: [ { "_id": "63811d56f6bea6b0dcb3...
How to define expected body of response containing list of indefinite number of JSON items in pytest?
I just started learning how to test API in python so please bear with me. I want to test the endpoint that returns all users from database. My expected body looks like below: [ { "_id": "63811d56f6bea6b0dcb35342", "email": "jan_kowalski@poczta.com", "email_confirmed": "False", "is_active": true, "...
[ "Without knowing the number of users that will be returned each time the test is run, the best you can do is check if each user in the response contains all the properties that are expected. Something like below:\nfrom app import main\n\ndef test_get_all_users(test_app):\n response = test_app.get(\"/user/all\")\...
[ 1 ]
[]
[]
[ "pytest", "python" ]
stackoverflow_0074577727_pytest_python.txt
Q: kivy + python: how to update form label based on external function response in multi-screen configuration Hi to all kivy/python experts. I am looking for an advice/solution, after trying everything I found for the last week. Here's my scenario: I have a kivy app with 2 screens, therefore I am using a Screen manag...
kivy + python: how to update form label based on external function response in multi-screen configuration
Hi to all kivy/python experts. I am looking for an advice/solution, after trying everything I found for the last week. Here's my scenario: I have a kivy app with 2 screens, therefore I am using a Screen manager, with each screen (1 and 2) defined in my .kv file after clicking log-in on my 1st screen, app jumps to 2nd ...
[ "I was not sure of the utility of having the separate class - but tried to give some examples here of passing information around. I think the key is to set up object references in your main App.\nmain.py\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom kivy.uix.screenmanager import ScreenManager, Screen\nfro...
[ 0, 0 ]
[]
[]
[ "kivy", "kivy_language", "kivymd", "python", "python_3.x" ]
stackoverflow_0074582505_kivy_kivy_language_kivymd_python_python_3.x.txt
Q: simplify python code - slice several lists and turn into tuple I was wondering how to simplify the following python code. I tried to loop it but it didn't quite work out and I thought there must be a way without repeating the same thing over and over again. coordinates = [ (9, 2, 17), (4, 14, 11), (8, ...
simplify python code - slice several lists and turn into tuple
I was wondering how to simplify the following python code. I tried to loop it but it didn't quite work out and I thought there must be a way without repeating the same thing over and over again. coordinates = [ (9, 2, 17), (4, 14, 11), (8, 10, 6), (2, 7, 0) ] cdns = coordinates[0][0:2], coordinates[1][...
[ "You can use numpy:\n>>> import numpy as np\n>>> coordinates = [\n... (9, 2, 17),\n... (4, 14, 11),\n... (8, 10, 6),\n... (2, 7, 0)\n... ]\n>>> coordinates_np = np.array(coordinates)\n>>> coordinates_np[:, 0:2]\narray([[ 9, 2],\n [ 4, 14],\n [ 8, 10],\n [ 2, 7]])\n\nIn general sp...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074583212_python.txt
Q: Align LaTeX formula to text in Manim I use the Poppins font for text and LaTeX for formulas (picture: number 1). The LaTeX text is vertically aligned higher than the Poppins text. I want both texts to be aligned on a horizontal line, like in (Image: number 2). How can I do that? I use the function next_to() so tha...
Align LaTeX formula to text in Manim
I use the Poppins font for text and LaTeX for formulas (picture: number 1). The LaTeX text is vertically aligned higher than the Poppins text. I want both texts to be aligned on a horizontal line, like in (Image: number 2). How can I do that? I use the function next_to() so that I can use the Poppins text and the LaTeX...
[ "The LaTeX-Schrift font aligns better if you use align_edge=UP in the next_to() function.\nreason.next_to(definitionbn, aligned_edge=UP, buff=0.1)\n\n" ]
[ 0 ]
[]
[]
[ "latex", "manim", "python", "text" ]
stackoverflow_0074576992_latex_manim_python_text.txt
Q: (staticfiles.W004) The directory in the STATICFILES_DIRS setting does not exist error in django so i am working on a project where i want to use some css files. but i couldn't link them with my html page in django. i've used everything i knew but still static is not loading my error is: (staticfiles.W004) The dir...
(staticfiles.W004) The directory in the STATICFILES_DIRS setting does not exist error in django
so i am working on a project where i want to use some css files. but i couldn't link them with my html page in django. i've used everything i knew but still static is not loading my error is: (staticfiles.W004) The directory 'C:\Users\ASUS\PycharmProjects\e-payment\epayment\static' in the STATICFILES_DIRS setting does...
[ "you need to simply create a folder with a name with which the error has caused, In simple words you need to create a folder named by static in your following path which is also shown in error itslef \"(staticfiles.W004) The directory 'C:\\Users\\ASUS\\PycharmProjects\\e-payment\\epayment\\static' in the STATICFILE...
[ 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0074144591_django_django_templates_python.txt
Q: How to convert text to list in python input=""" intro: hey,how are you i am fine intro: hey, how are you Hope you are fine """ output= [['hey,how are you i am fine'],['hey, how are you Hope you are fine']] for text in f: text = text.strip() A: I would look into something like regex or just use input.split...
How to convert text to list in python
input=""" intro: hey,how are you i am fine intro: hey, how are you Hope you are fine """ output= [['hey,how are you i am fine'],['hey, how are you Hope you are fine']] for text in f: text = text.strip()
[ "I would look into something like regex or just use\ninput.split(\"intro:\") or input.splitlines() to generate a list of strings. That would not result in the form you have below. But since your question is not clear thats the best i can do.\n", "You could do this by splitting the input data by the string intro:....
[ 0, 0 ]
[ "We can use re.findall here in multiline mode:\ninp = \"\"\"intro: hey,how are you i am fine\n\nintro: hey, how are you Hope you are fine\"\"\"\n\nlines = re.findall(r'^\\w+:\\s*(.*)$', inp, flags=re.M)\nprint(lines)\n\nThis prints:\n['hey,how are you i am fine', 'hey, how are you Hope you are fine']\n\n" ]
[ -1 ]
[ "file", "list", "logic", "python", "text" ]
stackoverflow_0074582935_file_list_logic_python_text.txt
Q: AttributeError: 'Grid' object has no attribute 'tk' Who can help me to find this error , I will be thankful. from tkinter import* import math root = Tk() root.title("Jupiter Notebook Calculator") root.resizable(width=False, height=False) root.geometry("452x580+500+40") mainFareme = Frame(root, bd=20, bg='gainsbo...
AttributeError: 'Grid' object has no attribute 'tk'
Who can help me to find this error , I will be thankful. from tkinter import* import math root = Tk() root.title("Jupiter Notebook Calculator") root.resizable(width=False, height=False) root.geometry("452x580+500+40") mainFareme = Frame(root, bd=20, bg='gainsboro',relief=RIDGE) mainFrame = Grid() innerFareme = Fram...
[ "mainFrame and innerFrame are an instance of Grid. An instance of Grid isn't a widget so you can't use it as the parent of another widget. A widget's parent (or master) must be a widget.\n" ]
[ 0 ]
[]
[]
[ "attributeerror", "python", "tkinter" ]
stackoverflow_0074566971_attributeerror_python_tkinter.txt
Q: Calculating Autocorrelation of Pandas DataFrame along each Column I want to calculate the autocorrelation coefficients of lag length one among columns of a Pandas DataFrame. A snippet of my data is: RF PC C D PN DN P year ...
Calculating Autocorrelation of Pandas DataFrame along each Column
I want to calculate the autocorrelation coefficients of lag length one among columns of a Pandas DataFrame. A snippet of my data is: RF PC C D PN DN P year 1890 NaN NaN NaN ...
[ "This is a late answer, but for future users, you can also use the pandas.Series.autocorr(), which calculates lag-N (default=1) autocorrelation on Series:\ndf['C'].autocorr(lag=1)\n\nhttp://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.autocorr.html#pandas.Series.autocorr\n", ".autocorr applies to ...
[ 22, 15, 4, 0 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0026083293_numpy_pandas_python.txt
Q: How do I get rid of the "{}" in my windows output? (Python / SQLite3) I'm creating a flashcard game to ask CompSci questions. I'm trying to retrieve a random "CardFront" which acts as a varchar stored in an SQLite3 DB table, and output that result to a messagebox to "Prompt" the user with the question. Only proble...
How do I get rid of the "{}" in my windows output? (Python / SQLite3)
I'm creating a flashcard game to ask CompSci questions. I'm trying to retrieve a random "CardFront" which acts as a varchar stored in an SQLite3 DB table, and output that result to a messagebox to "Prompt" the user with the question. Only problem I can't seem to figure out is why it is returning with squiggly brackets ...
[ "I think you can implement something like this in order to remove that \"{}\". But since I'm not aware of using SQLite, I could give you a more precise answer.\ndata = \"{Data}\"\ndata = data.replace(data[0], \"\")\ndata = data.replace(data[-1], \"\")\nprint(data)\n\n", "tkinter will add curly braces when it expe...
[ 0, 0, -1 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0074555272_python_sqlite.txt
Q: Count value column iteratively for rows within column I have a dataframe that looks like this: info_version commits commitdates 18558 17.1.3 42 2017-07-14 20783 17.1.3 57 2017-07-14 20782 17.2.2 57 2017-09-27 18557 17.2.2 42 2017-09-27 18556 17.2.3 ...
Count value column iteratively for rows within column
I have a dataframe that looks like this: info_version commits commitdates 18558 17.1.3 42 2017-07-14 20783 17.1.3 57 2017-07-14 20782 17.2.2 57 2017-09-27 18557 17.2.2 42 2017-09-27 18556 17.2.3 42 2017-10-30 20781 17.2.3 57 2017-10-30...
[ "You can use sort_values with cumsum but the output is different from yours :\ndata1[\"commitdates\"]= pd.to_datetime(data1[\"commitdates\"]) #only if not parsed yet\n​\ndata2= (\n data1\n .loc[:, [\"info_version\", \"commits\", \"commitdates\"]]\n .sort_values(by=[\"info_version\", \"...
[ 2, 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074583244_pandas_python.txt
Q: why my function don't return the last value? I have written class called Atoms and I put inside it, in short, all the information you need in order to work on distributing the electrons of some atoms, and I put it in a dictionary dict, its symbol is the key and its atomic number is the value, and I made a set of c...
why my function don't return the last value?
I have written class called Atoms and I put inside it, in short, all the information you need in order to work on distributing the electrons of some atoms, and I put it in a dictionary dict, its symbol is the key and its atomic number is the value, and I made a set of conditional sentences in order to distribute the at...
[ "The following code is my int4erpretation of your code.\n\nglobal statements should be avoided at all cost.\nYou can make your attributs class atributes by adding them drictly to the class. It fullfills the same purpuse but it is much clearer and your functions loose code and are easyier to read. Thats just style t...
[ 0 ]
[]
[]
[ "class", "if_statement", "oop", "python" ]
stackoverflow_0074583005_class_if_statement_oop_python.txt
Q: AttributeError: module 'cv2' has no attribute 'imread' (i'm on mac os 10.8.5) I'm using Python 3 (through jupyter notebook) and trying to import cv2 I did import cv2 succefully, but when I type im_g = cv2.imread("smallgray.png", 0) I get this error: ---------------------------------------------------------------...
AttributeError: module 'cv2' has no attribute 'imread'
(i'm on mac os 10.8.5) I'm using Python 3 (through jupyter notebook) and trying to import cv2 I did import cv2 succefully, but when I type im_g = cv2.imread("smallgray.png", 0) I get this error: --------------------------------------------------------------------------- AttributeError Trace...
[ "It might be the case that you installed it in the wrong way. In my case as well, I installed OpenCV wrongly so I uninstalled it completely then reinstalled it which caused it to work.\nPlease notice the sequence of uninstalling and installing:\nUninstall:\npip uninstall opencv-python\npip uninstall opencv-contrib-...
[ 9, 4, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "Perhaps you have just installed opencv-contrib-python and not opencv-python.\nTry this out, it worked for me-\n\nFirst uninstall:\n\npip uninstall opencv-python\npip uninstall opencv-contrib-python\n\n\nthen install:\n\npip install opencv-contrib-python==3.4.2.16\npip install opencv-python==3.4.2.16\n\nYou can ref...
[ -1 ]
[ "opencv", "python" ]
stackoverflow_0047857141_opencv_python.txt
Q: Populate Adjacent Value in Pandas Column When String is Duplicated I'm attempting to overwrite the value named in a column called 'Group' when the value in a column called 'Keyword' is a duplicate with the adjacent value. For example, because the string 'commercial office cleaning services' is duplicated, I'd like...
Populate Adjacent Value in Pandas Column When String is Duplicated
I'm attempting to overwrite the value named in a column called 'Group' when the value in a column called 'Keyword' is a duplicate with the adjacent value. For example, because the string 'commercial office cleaning services' is duplicated, I'd like to overwrite the adjacent column to 'commercial cleaning services'. Exa...
[ "IIUC, use duplicated with mask and ffill :\n#is the keyword duplicated ?\nm = df['Keyword'].duplicated()\n\ndf['Group'] = df['Group'].mask(m).ffill()\n\n# Output:\nprint(df)\n\n Keyword Group\n0 commercial cleaning services commercial cleaning services...
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074583388_pandas_python.txt
Q: Tensorflow Callback as Custom Metric for CTC In an attempt to yield more metrics during the training of my model (written in TensorFlow version 2.1.0), like the Character Error Rate (CER) and Word Error Rate (WER), I created a callback to pass to the fit function of my model. It is able to generate the CER and WER...
Tensorflow Callback as Custom Metric for CTC
In an attempt to yield more metrics during the training of my model (written in TensorFlow version 2.1.0), like the Character Error Rate (CER) and Word Error Rate (WER), I created a callback to pass to the fit function of my model. It is able to generate the CER and WER at the end of an epoch. It's my second choice as ...
[ "Solved in TF 2.3.1, but should apply for previous versions of 2.x as well.\nSome remarks:\n\nInformation on how to properly implement a Tensorflow Custom Metric is scarce. The question implied the use of a callback to implement the metric. This has longer epochs as a consequence (due to the explicit extra calculat...
[ 1, 0 ]
[]
[]
[ "ctc", "keras", "python", "tensorflow", "tensorflow2.0" ]
stackoverflow_0060285167_ctc_keras_python_tensorflow_tensorflow2.0.txt
Q: How to define functions to ask for user input for months, year, and days (convert them to total year) and find simple interest defining function and asking user input def get_time(year, months, days): year = int(input("enter year: ")) months = int(input("enter month: ")) days = int(input("enter days: ")) Hey ever...
How to define functions to ask for user input for months, year, and days (convert them to total year) and find simple interest
defining function and asking user input def get_time(year, months, days): year = int(input("enter year: ")) months = int(input("enter month: ")) days = int(input("enter days: ")) Hey everyone, thanks for the suggestions and advice, this is my first time using this site. Here is my problem: The question is asking me to...
[ "def convertToYear():\n year = float(input(\"Enter Year here YY: \"))\n month = float(input(\"Enter Month here MM: \"))\n day = float(input(\"Enter day here: \"))\n day = day/365\n month = month/12\n year = (month + day) + year\n return year\n \n\ndef simpleInterest(timeInYears):\n princip...
[ 0 ]
[]
[]
[ "math", "python" ]
stackoverflow_0074583045_math_python.txt
Q: How to import loopcontrol in jinja2 I need to use break for a for loop in jinja2. Below is my code: {% for i in range (0, desc) %}{{ desclist[i] }} {% set length = length + desclist[i]|length %}{% if length >= 70 %}{% break %}{% endif %}{% endfor %} and to import the loopcontrol extension: However, I got an err...
How to import loopcontrol in jinja2
I need to use break for a for loop in jinja2. Below is my code: {% for i in range (0, desc) %}{{ desclist[i] }} {% set length = length + desclist[i]|length %}{% if length >= 70 %}{% break %}{% endif %}{% endfor %} and to import the loopcontrol extension: However, I got an error as followed: jinja2.exceptions.Templat...
[ "Encountered the same issue, and realized on top of the document\nit says:\n\nThe following example creates a Jinja environment with the i18n extension loaded:\njinja_env = Environment(extensions=['jinja2.ext.i18n'])\n\nSo I tried this and it finally resolved the error of ... Encountered unknown tag ...:\njinja_env...
[ 0 ]
[]
[]
[ "jinja2", "python" ]
stackoverflow_0036940435_jinja2_python.txt
Q: Slice image in dynamic number of squares (grid) and save corner coordinates of those squares in list I'm reading in an image with the Pillow library in Python. I want to "slice" it into squares, and save the corner coordinates of each of the squares in a list. For example in the image below, I would like to save t...
Slice image in dynamic number of squares (grid) and save corner coordinates of those squares in list
I'm reading in an image with the Pillow library in Python. I want to "slice" it into squares, and save the corner coordinates of each of the squares in a list. For example in the image below, I would like to save the corner coordinates for square 15. (Top left corner is 0,0) The first think I do after reading in the i...
[ "There were (from my understanding) inconsistencies in your use of \"horizontal/vertical\"; I also removed the points list, since you can easily convert the rectangle number to its upper-left corner coords (see the function in the end); I draw the grid directly by drawing all horizontal lines and all vertical lines...
[ 1 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0074583095_python_python_imaging_library.txt
Q: Python Flask Cors error - set according to documentation I have created API using Flask in Python. Now I am trying to create front end, where I want to call API. I set CORS according Flask-Cors documentation, unfortunately it doesn't work. from flask_cors import CORS CORS(app) I got this error CORS error - Safari...
Python Flask Cors error - set according to documentation
I have created API using Flask in Python. Now I am trying to create front end, where I want to call API. I set CORS according Flask-Cors documentation, unfortunately it doesn't work. from flask_cors import CORS CORS(app) I got this error CORS error - Safari CORS error - Chrome I have found some similar topics, where w...
[ "Make sure the URL you are trying to access begins with 'http://' or 'https://' according to your web server's configuration\n" ]
[ 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074583218_flask_python.txt
Q: Using yield to run code after method of function execution I'm trying to create a class method that can run some code after its execution. In pytest we have this functionality with fixtures: @pytest.fixture def db_connection(conn_str: str): connection = psycopg2.connect(conn_str) yield connection conne...
Using yield to run code after method of function execution
I'm trying to create a class method that can run some code after its execution. In pytest we have this functionality with fixtures: @pytest.fixture def db_connection(conn_str: str): connection = psycopg2.connect(conn_str) yield connection connection.close() # this code will be executed after the test is don...
[ "What you are trying to do is implement a context manager; the similarly to a Pytext fixture is incidental.\nYou can do this with contextmanager.contextlib\nfrom contextlib import contextmanager\n\n@contextmanager\ndef db_connection(conn_str):\n connection = psycopg2.connect(conn_str)\n yield connection\n ...
[ 2, 1 ]
[]
[]
[ "generator", "oop", "psycopg2", "pytest", "python" ]
stackoverflow_0074583333_generator_oop_psycopg2_pytest_python.txt
Q: Exception in Tkinter callback with KEY ERROR The below is my code with the name of abc.py and i am getting and error of type error on line 15. i don't know how to sort out the problem The below is my code with the name of abc.py and i am getting and error of type error on line 15. i don't know how to sort out the ...
Exception in Tkinter callback with KEY ERROR
The below is my code with the name of abc.py and i am getting and error of type error on line 15. i don't know how to sort out the problem The below is my code with the name of abc.py and i am getting and error of type error on line 15. i don't know how to sort out the problem import tkinter as tk from tkinter import t...
[ "Since select is the result of listBox.set(row_id), it is a dictionary of column/value pairs for the selected item. The keys are then the column names of the treeview listBox instead of the column names from the database table:\ndef GetValue(event):\n e1.delete(0, END)\n e2.delete(0, END)\n e3.delete(0, E...
[ 0 ]
[]
[]
[ "python", "python_3.x", "tkinter" ]
stackoverflow_0074558178_python_python_3.x_tkinter.txt
Q: How to solve the problem "TypeError: setEnabled(self, bool): argument 1 has unexpected type 'str'"? I have encountered such a problem ` > python .\main.py Traceback (most recent call last): File "C:\main.py", line 79, in writeF self.ui.lineEdit.setEnabled(value) TypeError: setEnabled(self, bool): argument 1 ...
How to solve the problem "TypeError: setEnabled(self, bool): argument 1 has unexpected type 'str'"?
I have encountered such a problem ` > python .\main.py Traceback (most recent call last): File "C:\main.py", line 79, in writeF self.ui.lineEdit.setEnabled(value) TypeError: setEnabled(self, bool): argument 1 has unexpected type 'str' ` My code is hosted on github, here's the repo link. The relevant file part: f...
[ "Short Answer: You are overwriting the previously defined value of value in line 61.\n\nLonger answer: Consider this minimized example:\nvalue = True\ndictionary = {'foo': 'bar', 'baz': 'qwurx'}\nfor key, value in dictionary.items():\n print(key, value)\nprint(value, type(value))\n\nOutput:\n# foo bar\n# baz q...
[ -1 ]
[]
[]
[ "pyqt", "pyqt5", "python", "qt", "qt5" ]
stackoverflow_0074581241_pyqt_pyqt5_python_qt_qt5.txt
Q: Why isn't streamlit running in VScode? I installed streamlit in VScode, and tried to run this. import streamlit as st st.title("Hello") But I dont get streamlit to pop up in a new browser, instead I get this message in the terminal. Is this something to do with my files? Warning: to view this Streamlit app on a b...
Why isn't streamlit running in VScode?
I installed streamlit in VScode, and tried to run this. import streamlit as st st.title("Hello") But I dont get streamlit to pop up in a new browser, instead I get this message in the terminal. Is this something to do with my files? Warning: to view this Streamlit app on a browser, run it with the following command: s...
[ "Following the suggestion, just execute the streamlit run c:\\Users\\MyName\\Documents\\VS code\\test.py in the terminal directly.\n", "There is a way to run Streamlit code in VSCode.\nThis enables utilizing the debugging features of VSCode.\nUpdate the launch.json file with the following:\n\n{\n \"configurati...
[ 1, 0, 0, 0 ]
[ "python -m streamlit run app.py\n\n" ]
[ -1 ]
[ "python", "streamlit", "visual_studio_code" ]
stackoverflow_0071917749_python_streamlit_visual_studio_code.txt
Q: How to replace all list of list items with the index value of that list I am trying to replace items in list of lists by the value of the index of that specific list. I can do it with a for loop, but I was wondering if there is a faster way to do this. such that the following list example = [[1, 2, 3], [4, 5, 6], ...
How to replace all list of list items with the index value of that list
I am trying to replace items in list of lists by the value of the index of that specific list. I can do it with a for loop, but I was wondering if there is a faster way to do this. such that the following list example = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] becomes: solution = [[0, 0, 0], [1, 1, 1], [2, 2, 2]]
[ "Your way with for loop should work, but if you want another way in a short version then you can do it this way with list comprehension and enumerate,\nexample = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\nresult = [[index] * len(value) for index, value in enumerate(example)]\nprint(result)\n\n", "List comprehensions are ...
[ 1, 0, 0 ]
[ "Here is a solution with the map function:\nres = list(map(lambda i : [i] * len(example[i]),\n range(len(example))\n ))\nprint(res)\n\nIt's more verbose than the comprehension method, but coming from other languages I prefer it - I find the map to be more explicit and easier to follow, as it's bui...
[ -1 ]
[ "list", "python", "replace" ]
stackoverflow_0074583527_list_python_replace.txt
Q: "Name 'x' is parameter and global" exception I was wondering why this won't work? I'm fairly new to programming and I'm learning Python. def convert(x,y): while True: try: global x x = int(input("Number: ")) except ValueError: print("Make sure it is a number...
"Name 'x' is parameter and global" exception
I was wondering why this won't work? I'm fairly new to programming and I'm learning Python. def convert(x,y): while True: try: global x x = int(input("Number: ")) except ValueError: print("Make sure it is a number.") while True: try: globa...
[ "In Python, parameters to functions (the things in parentheses next to the definition) are added as local variables to the scope of the function within the code. The Python interpreter makes a few major scans of your code. The first is a syntax scan in which it tests to see if your program is syntactically correct ...
[ 12, 4, 3, 1, 1, 0 ]
[]
[]
[ "global_variables", "parameters", "python" ]
stackoverflow_0018807749_global_variables_parameters_python.txt
Q: Python loop to Comprehensive list I'm new to Python Programming, this is my code; myList = " Bob said, breakthrough study reveals that human and octopus brains have common features" for word in myList.split(): if word[0] == "b": print(word) Can I simplify this code above to a list comprehension in Py...
Python loop to Comprehensive list
I'm new to Python Programming, this is my code; myList = " Bob said, breakthrough study reveals that human and octopus brains have common features" for word in myList.split(): if word[0] == "b": print(word) Can I simplify this code above to a list comprehension in Python? Can't find the solution.
[ "Your existing approach seems OK to me but not sure if you want something like this or not with list comprehension. Note: your mylist name has a typo.\nmylist = \" Bob said, breakthrough study reveals that human and octopus brains have common features\"\nword = [word for word in mylist.split() if word[0] == \"b\"]\...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074583620_python.txt
Q: how to create a flow generator in python for my custom data I do a cat/dog binary classification I created a training data this way, I applied an average filter to the images. the problem is that the database is quite large and I get displayed right after that, your notebook tried to allocate more memory than is a...
how to create a flow generator in python for my custom data
I do a cat/dog binary classification I created a training data this way, I applied an average filter to the images. the problem is that the database is quite large and I get displayed right after that, your notebook tried to allocate more memory than is available. I read that generators in python take less disk memory ...
[ "with the requirements you want to use ImageDataGenerator() with blur functions, check out CV2 CV2.blur(). You can do it by the provided custom function \" preprocessing_function=custom_image_preprocess \" parameter in ImageDataGenerator() itself.\n\nSample: CV2 using standard deviations when you can do it with a c...
[ 1 ]
[]
[]
[ "generator", "image_processing", "python", "tensorflow", "training_data" ]
stackoverflow_0074581274_generator_image_processing_python_tensorflow_training_data.txt
Q: Filtering a dataframe with the values of another dataframe I have a bit of a complicated selecting in two dataframes. Say I have a dataframe like this country pop continent lifeExp gdpPercap 0 Afghanistan 31889923.0 Asia 43.828 974.580338 1 Albania 3600523.0 Europe 76.423 ...
Filtering a dataframe with the values of another dataframe
I have a bit of a complicated selecting in two dataframes. Say I have a dataframe like this country pop continent lifeExp gdpPercap 0 Afghanistan 31889923.0 Asia 43.828 974.580338 1 Albania 3600523.0 Europe 76.423 5937.029526 2 Algeria 33333216.0 Africa 72.301 6223...
[ "You can use boolean indexing with pandas.DataFrame.loc and pandas.Series.isin :\nout= df2.loc[df2[\"country\"].isin(df1[\"country\"])]\n\n# Output :\nprint(out)\n\n country year Production\n0 Afghanistan 1980 20\n1 Afghanistan 1981 10\n2 Afghanistan 1983 5\n3 Albania ...
[ 3 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074583562_pandas_python.txt
Q: Python: How to convert column with dictionary into columns I have a DataFrame with a column that contains a dictionary as follows: df: date dictionary 0 2021-01-01 00:00:00 + 00:00 'Total':{'USD':100, 'size':20}, 'country':{'USA': {'income': 20000}, 'fees': {'...
Python: How to convert column with dictionary into columns
I have a DataFrame with a column that contains a dictionary as follows: df: date dictionary 0 2021-01-01 00:00:00 + 00:00 'Total':{'USD':100, 'size':20}, 'country':{'USA': {'income': 20000}, 'fees': {'total': 55}} 1 2021-01-01 00:00:00 + 00:00 'Total...
[ "1)\nThe first possibility I see, is if your dataframe contains valid json strings like so:\ndf = pd.DataFrame({\n 'date': [\n '2021-01-01 00:00:00', \n '2021-01-01 00:00:00',\n '2021-01-02 00:00:00', \n ],\n 'dictionary': [ \n '{\"Total\":{\"USD\":100, \"size\":20}, \"country\"...
[ 1, 0 ]
[]
[]
[ "dataframe", "dictionary", "list", "pandas", "python" ]
stackoverflow_0074577324_dataframe_dictionary_list_pandas_python.txt
Q: Why is Python saying modules are imported when they are not? Python 3.6.5 Using this answer as a guide, I attempted to see whether some modules, such as math were imported. But Python tells me they are all imported when they are not. >>> import sys >>> 'math' in sys.modules True >>> 'math' not in sys.modules False...
Why is Python saying modules are imported when they are not?
Python 3.6.5 Using this answer as a guide, I attempted to see whether some modules, such as math were imported. But Python tells me they are all imported when they are not. >>> import sys >>> 'math' in sys.modules True >>> 'math' not in sys.modules False >>> math.pi Traceback (most recent call last): File "<stdin>", ...
[ "to explain this, let's define this function:\ndef import_math():\n import math\n\nimport_math()\n\nthe above function will import the module math, but only in its local scope, anyone that tries to reference math outside of it will get a name error, because math is not defined in the global scope.\nany module th...
[ 8 ]
[]
[]
[ "python" ]
stackoverflow_0074583630_python.txt
Q: "IndentationError: unindent does not match any outer indentation level" after try block So I get this error when I run the program. The error is supposed to be at line 11 after the 'try' block but that's exactly how the author of the book I use for learning python displayed it. Can someone help me? print("Give me ...
"IndentationError: unindent does not match any outer indentation level" after try block
So I get this error when I run the program. The error is supposed to be at line 11 after the 'try' block but that's exactly how the author of the book I use for learning python displayed it. Can someone help me? print("Give me two number, and I'll divide them.") print("Enter 'q' to quit.") while True: first_number ...
[ "There was an issue with the indentation from line 11 onwards. It was 1 extra space to the right compared to the code above it. I suggest you use an IDE like PyCharm or VSCode (both for free), since it will help you a lot in finding not just such bugs but even harder to detect, like default mutable argument.\nPerso...
[ 0 ]
[ "Your try block is 1 space to the right with respect to the previous indent:\nwhile True:\n first_number = input(\"\\nFirst number: \")\n if first_number == 'q':\n break\n second_number = input(\"Second number: \")\n if second_number == 'q':\n break\n try:\n answer = int(first_nu...
[ -1 ]
[ "indentation", "python", "try_except" ]
stackoverflow_0074583683_indentation_python_try_except.txt
Q: Keep Selenium Webdriver across Celery Tasks I developed a Flask web app that uses Celery to handle tasks. One of these tasks consists of scraping a bunch of pages (around 200) using a custom Class derived from a selenium chrome driver. @celery_app.task def scrape_async(): driver = MyDriver(exec_path=os.environ....
Keep Selenium Webdriver across Celery Tasks
I developed a Flask web app that uses Celery to handle tasks. One of these tasks consists of scraping a bunch of pages (around 200) using a custom Class derived from a selenium chrome driver. @celery_app.task def scrape_async(): driver = MyDriver(exec_path=os.environ.get('CHROMEDRIVER_PATH'), options=some_chrome_opt...
[ "One approach would be to use a selenium grid if you are using distributed crawling by doing so you will reduce the amount of resource usage for loading, rendering htmls, executing the js script to other server.\nAnd in doing so you dont need to bother about the stuffs to be picked by the worker if you are using ta...
[ 0 ]
[]
[]
[ "celery", "python", "selenium", "selenium_chromedriver" ]
stackoverflow_0065656175_celery_python_selenium_selenium_chromedriver.txt
Q: sum elements in python list if match condition I have a variable with lists with varied number of elements: ['20', 'M', '10', 'M', '1', 'D', '14', 'M', '106', 'M'] ['124', 'M', '19', 'M', '7', 'M'] ['19', 'M', '131', 'M'] ['3', 'M', '19', 'M', '128', 'M'] ['12', 'M', '138', 'M'] Variable is always number, letter ...
sum elements in python list if match condition
I have a variable with lists with varied number of elements: ['20', 'M', '10', 'M', '1', 'D', '14', 'M', '106', 'M'] ['124', 'M', '19', 'M', '7', 'M'] ['19', 'M', '131', 'M'] ['3', 'M', '19', 'M', '128', 'M'] ['12', 'M', '138', 'M'] Variable is always number, letter and order matters. I would to add the values only of...
[ "You can slice Python lists using a step (sometimes called a stride), you can use this to get every second element, starting at index 1 (for the first letter):\n>>> example = ['30', 'M', '1', 'D', '120', 'M']\n>>> example[1::2]\n['M', 'D', 'M']\n\nThe [1::2] syntax means: start at index 1, go on until you run out o...
[ 3, 0, 0 ]
[]
[]
[ "bam", "pysam", "python" ]
stackoverflow_0074583505_bam_pysam_python.txt
Q: Add position to a NetworkX graph using dictionary I have a DiGraph object called G1, a graph network with edges. G1 is composed by a list of nodes and I want to give them coordinates stored in a python dictionary. This is the list of nodes: LIST OF NODES For every node I have built a python dictionary with node's ...
Add position to a NetworkX graph using dictionary
I have a DiGraph object called G1, a graph network with edges. G1 is composed by a list of nodes and I want to give them coordinates stored in a python dictionary. This is the list of nodes: LIST OF NODES For every node I have built a python dictionary with node's name as keys and a tuple of coordinates as values: DICT...
[ "I think it's mostly syntax errors here. Try this:\nfor node, pos in avg.items():\n G1.nodes[node]['pos'] = pos\n\nThen, when building your visual, build your list of positions beforehand like this and just use the pos=pos convention when calling nx.draw().\npos = {node: G.nodes[node]['pos'] for node in G.nodes...
[ 0 ]
[]
[]
[ "coordinates", "dictionary", "networkx", "python" ]
stackoverflow_0074581466_coordinates_dictionary_networkx_python.txt
Q: what does .models mean in Django? I am trying to import a class named 'Questions' from my models.py to admin.py from .models import Questions I don't understand why we have to use a period in '.models', what does it mean and what exactly is it pin pointing to? I tried this combinations but it was no avail from mod...
what does .models mean in Django?
I am trying to import a class named 'Questions' from my models.py to admin.py from .models import Questions I don't understand why we have to use a period in '.models', what does it mean and what exactly is it pin pointing to? I tried this combinations but it was no avail from models import Questions from Model.models ...
[ "This is due to relative import. you see their are 2 types of import statement:\n\nAbsolute import: they start from the root of the project. Like in Django where the manage.py is, that is the root. So your import statement can be written as\nfrom {AppName}.models import Questions\n\nBut here you are using relative ...
[ 1, 1 ]
[]
[]
[ "django", "python", "python_import" ]
stackoverflow_0074583711_django_python_python_import.txt