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: Installing Apyori package in Jupyter Notebook Question: How to install apyori algorithm in Python using Jupyter Notebook. Code: ! pip install apyori Error: Solution: what can be the solution to it? A: This is on the first github page I've found. Install with pip pip install apyori. Put apyori.py into your proj...
Installing Apyori package in Jupyter Notebook
Question: How to install apyori algorithm in Python using Jupyter Notebook. Code: ! pip install apyori Error: Solution: what can be the solution to it?
[ "This is on the first github page I've found.\nInstall with pip pip install apyori.\nPut apyori.py into your project.\nRun python setup.py install.\n\nfrom apyori import apriori\n" ]
[ 0 ]
[]
[]
[ "jupyter_notebook", "python" ]
stackoverflow_0074390111_jupyter_notebook_python.txt
Q: Extracting only single tags in beautifulsoup I'm looking for a way to extract only tags that don't have another tag in it For example: from bs4 import BeautifulSoup html = """ <p><a href='XYZ'>Text1</a></p> <p>Text2</p> <p><a href='QWERTY'>Text3</a></p> <p>Text4</p> """ soup = BeautifulSoup(html, 'html.parser') so...
Extracting only single tags in beautifulsoup
I'm looking for a way to extract only tags that don't have another tag in it For example: from bs4 import BeautifulSoup html = """ <p><a href='XYZ'>Text1</a></p> <p>Text2</p> <p><a href='QWERTY'>Text3</a></p> <p>Text4</p> """ soup = BeautifulSoup(html, 'html.parser') soup.find_all('p') Gives [<p><a href="XYZ">Text1</a...
[ "You can filter Tags without other tags in them as follows:\nfor tag in soup.find_all('p'):\n if isinstance(tag.next, str):\n print(tag)\n\nWhich returns\n<p>Text2</p>\n<p>Text4</p>\n\n", "I would simply filter it afterwards using if/else on the length of the tags, if it's only p then it'll be empty, ot...
[ 2, 0, 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074388919_beautifulsoup_python_web_scraping.txt
Q: I am not able to use machine learning model in QGIS I have trained a machine learning model and saved it as an hdf5 file model.save('landcover_100_epochs_RESNET_backbone_batch16.hdf5') Now when I try to load the model in jupyter notebook, it works without errors from keras.models import load_model model = load_m...
I am not able to use machine learning model in QGIS
I have trained a machine learning model and saved it as an hdf5 file model.save('landcover_100_epochs_RESNET_backbone_batch16.hdf5') Now when I try to load the model in jupyter notebook, it works without errors from keras.models import load_model model = load_model("landcover_100_epochs_RESNET_backbone_batch16.hdf5",...
[ "The thing is that load_model can only load h5 files\nYou can try :\nfrom keras.models import load_weights\nmodel = load_weights(\"landcover_100_epochs_RESNET_backbone_batch16.hdf5\", compile=False)\n\n" ]
[ 0 ]
[]
[]
[ "keras", "pyqgis", "python", "qgis" ]
stackoverflow_0074389883_keras_pyqgis_python_qgis.txt
Q: How to create a predictive model using Mahalanobis Distance outlier in python I found online and worked on Multivariate outlier (Mahalanobis Distance) using Linear Discriminant Analysis (LDA) as an input. Here are example LDA coordinates: LDA coord: (EX:2) 0 1 2 0 -3.132160 0....
How to create a predictive model using Mahalanobis Distance outlier in python
I found online and worked on Multivariate outlier (Mahalanobis Distance) using Linear Discriminant Analysis (LDA) as an input. Here are example LDA coordinates: LDA coord: (EX:2) 0 1 2 0 -3.132160 0.032012 C0 1 -1.924197 1.092878 C0 2 0.506485 2...
[ "I worked on the model for some time and managed to narrow it down to the following code:\nclass MahalanobisOneclassClassifier():\n def __init__(self, X_train, threshold):\n self.X_train = X_train\n self.threshold = threshold\n print('Critical value is: ', self.threshold)\n\n def predict_...
[ 0 ]
[]
[]
[ "classification", "model", "prediction", "python" ]
stackoverflow_0071142274_classification_model_prediction_python.txt
Q: python: win32com bulk save attachment error - server admin has limited number of items I am looping through entryIds stored in a dataframe (loaded from a csv file) and accessing the messages by dispatching win32com.client to access Outlook MAPI and save email attachments to a local directory using the below code. ...
python: win32com bulk save attachment error - server admin has limited number of items
I am looping through entryIds stored in a dataframe (loaded from a csv file) and accessing the messages by dispatching win32com.client to access Outlook MAPI and save email attachments to a local directory using the below code. I also am storing the attachment name, path, and entryId in a new dataframe for later analys...
[ "After lots of research on how to release COM objects in python, I never found a solution. To me, the SaveAsFile() method has a bug that perpetuates references to each message, thereby making this error unresolvable once I've scanned 248 messages and hit the administrator limit.\nInstead, I made a workaround soluti...
[ 1, 0 ]
[]
[]
[ "mapi", "office_automation", "outlook", "python", "win32com" ]
stackoverflow_0074350213_mapi_office_automation_outlook_python_win32com.txt
Q: Check Data for Last Quarter I have a dataframe in which the data is in the following format process_date ItemNo ItemType 01-Mar-2019 1 abc 01-Jun-2019 2 cde 01-Sep-2019 1 abc The data file is supplied every quarter with the above date format (...
Check Data for Last Quarter
I have a dataframe in which the data is in the following format process_date ItemNo ItemType 01-Mar-2019 1 abc 01-Jun-2019 2 cde 01-Sep-2019 1 abc The data file is supplied every quarter with the above date format (Frist day of Quarter, instead of ...
[ "Find quarter and year for:\n\nPresent day\nLast quarter\nPrevious to last quarter\n\nCheck if record exists for quarter of that year:\ncurrent_qtr = pd.Timestamp(datetime.datetime.now()).quarter\nlast_qtr = 4 if current_qtr - 1 == 0 else current_qtr - 1\nprev_qtr = 4 if last_qtr - 1 == 0 else last_qtr - 1\ncurrent...
[ 2 ]
[]
[]
[ "databricks", "pyspark", "python" ]
stackoverflow_0074386199_databricks_pyspark_python.txt
Q: Installing opencv for pypyp3 I've installed pypy3 on Mac, and would like to use it to speed up a python script to analyse a live video feed. I've tried to install opencv-python with pip and pip_pypy3, but get the following error: Building wheels for collected packages: opencv-python Building wheel for opencv-pyt...
Installing opencv for pypyp3
I've installed pypy3 on Mac, and would like to use it to speed up a python script to analyse a live video feed. I've tried to install opencv-python with pip and pip_pypy3, but get the following error: Building wheels for collected packages: opencv-python Building wheel for opencv-python (pyproject.toml) ... error e...
[ "How did you tried to install opencv?. Try this full path if you are in Mac\npip install opencv-python==4.5.3.56\n\n", "opencv-python does not release binary wheels for PyPy, so you are on your own to compile it, which is non-trivial. I would recommend using conda-forge instead since there are many more binary pa...
[ 1, 0 ]
[]
[]
[ "opencv", "pypy", "python" ]
stackoverflow_0074375268_opencv_pypy_python.txt
Q: Slicing Pandas Columns to Obtain Summary Statistics I have a dataframe that looks similar to the following: ColA ColB Year ... ===================== 1 2 2007 2 5 2007 3 4 2007 4 3 2007 5 2 2008 6 1 2008 7 0 2008 8 9 2008 ... I am using dat[['ColA'...
Slicing Pandas Columns to Obtain Summary Statistics
I have a dataframe that looks similar to the following: ColA ColB Year ... ===================== 1 2 2007 2 5 2007 3 4 2007 4 3 2007 5 2 2008 6 1 2008 7 0 2008 8 9 2008 ... I am using dat[['ColA', 'ColB']].describe(). When I do this, as expected, it di...
[ "you can group by year before calling describe :\ndf_example = pd.DataFrame({\"colA\": [1, 2, 3, 4, 5, 6, 7, 8],\n \"Year\": [2007, 2007, 2007, 2007, 2008, 2008, 2008, 2008]})\ndes = df_example.groupby(\"Year\").describe()\nprint(des)\n\n colA \n ...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python", "python_3.x", "summary" ]
stackoverflow_0074389669_dataframe_pandas_python_python_3.x_summary.txt
Q: How linear regression treats X and Y data from csv file I trained a model and got 92% accuracy. But I am not sure if it is what I am looking for. Because I have two csv files I used one of them as X and one as Y. They have these shapes X=(207399, 25), Y=(207399, 85). What I wanted to achieve here was to predict Y(...
How linear regression treats X and Y data from csv file
I trained a model and got 92% accuracy. But I am not sure if it is what I am looking for. Because I have two csv files I used one of them as X and one as Y. They have these shapes X=(207399, 25), Y=(207399, 85). What I wanted to achieve here was to predict Y(output) by using X(input). But I wanted the model to find a r...
[ "As a simple example, a linear regression with two input variables and one output variable is the following\na_1 * x_1 + a_2 * x_2 = y\n\nWhat it does is try to find an a_1 and a_2 that minimizes the error. In your file, if what you're trying to do is look at how predictive x_1 is of y_1, and you're not really look...
[ 0 ]
[]
[]
[ "linear_regression", "machine_learning", "python", "scikit_learn" ]
stackoverflow_0074390239_linear_regression_machine_learning_python_scikit_learn.txt
Q: How to turn a text file with number ranges into a list variable? I have a text file with: 8-9, 12, 14-16, 19, 27-28, 33, 41, 43, 45-46, 48-49, 51,54-60, 62-74, 76-82, 84-100, 102-105, 107-108 It is basically a list of integers in a text file. Using Python, I want to turn this into a list where every variable is ...
How to turn a text file with number ranges into a list variable?
I have a text file with: 8-9, 12, 14-16, 19, 27-28, 33, 41, 43, 45-46, 48-49, 51,54-60, 62-74, 76-82, 84-100, 102-105, 107-108 It is basically a list of integers in a text file. Using Python, I want to turn this into a list where every variable is stored separately. But the problem is that the dashes between the numb...
[ "Try this:\nnum_list = [\"8-9\", \"12\", \"14-16\", \"19\", \"27-28\", \"33\", \"41\", \"43\", \"45-46\", \"48-49\", \"51\",\"54-60\", \"62-74\", \"76-82\", \"84-100\", \"102-105\", \"107-108\"]\noutput_list = []\n\nfor number in num_list:\n if \"-\" in number: # Checks if the string contains \"-\"\n num1...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074388911_python.txt
Q: Creating an object outside before a function and use it in the function Hello I have a class where I load a huggingface translation model, it also has a function that perform the actual translation: class Translator: def __init__(self, language): model = f"Helsinki-NLP/opus-mt-{language}-en" se...
Creating an object outside before a function and use it in the function
Hello I have a class where I load a huggingface translation model, it also has a function that perform the actual translation: class Translator: def __init__(self, language): model = f"Helsinki-NLP/opus-mt-{language}-en" self.translator = pipeline("translation", model=model, device=0) def trans...
[ "It's fine to create a single translator that can be used in many places. But have your function take a translator as an argument rather than relying on a global variable.\ndef load_text_and_translate(tr, list_of_non_translated_text):\n final_translated_text_list = []\n\n for text in list_of_non_translated_te...
[ 2 ]
[]
[]
[ "language_translation", "nlp", "oop", "python" ]
stackoverflow_0074390303_language_translation_nlp_oop_python.txt
Q: What am I doing incorrect in this directory search python code? What am I doing wrong in the following source code and how can I fix that? my_script.py import subprocess import os import time from pathlib import Path def get_files(dir_str): onlyfiles = next(os.walk(dir_str))[2] return onlyfiles input_fi...
What am I doing incorrect in this directory search python code?
What am I doing wrong in the following source code and how can I fix that? my_script.py import subprocess import os import time from pathlib import Path def get_files(dir_str): onlyfiles = next(os.walk(dir_str))[2] return onlyfiles input_files_path_str = "$HOME" def main(): input_files_list = get_file...
[ "os.walk does not expand the shell variables(In this case it's $HOME) automatically.\nYou need to use os.path.expandvars api to expand it before supplying to get_files.\nimport os.path\ninput_files_list = get_files(os.path.expandvars(input_files_path_str))\n\n" ]
[ 1 ]
[]
[]
[ "directory", "directory_structure", "python" ]
stackoverflow_0074390315_directory_directory_structure_python.txt
Q: How to get an output from ONEAI NLP API? I found a very cool NLP API that helps analyze text using special skills. However, I am new to Python and I don't know how to get the output. Can someone help? This is what I tried: # Edit this One AI API call using our studio at https://studio.oneai.com/?pipeline=nGM7cx #...
How to get an output from ONEAI NLP API?
I found a very cool NLP API that helps analyze text using special skills. However, I am new to Python and I don't know how to get the output. Can someone help? This is what I tried: # Edit this One AI API call using our studio at https://studio.oneai.com/?pipeline=nGM7cx # pip install oneai import oneai oneai.api_key...
[ "It looks like your code is valid. So the only thing you need to do is just print the pipeline. Just add the following line to the end of your code:\nprint(output)\n\nHere's the code after the change:\n# Edit this One AI API call using our studio at https://studio.oneai.com/?pipeline=nGM7cx\n\n# pip install oneai\n...
[ 0 ]
[]
[]
[ "api", "artificial_intelligence", "nlp", "pipeline", "python" ]
stackoverflow_0074390115_api_artificial_intelligence_nlp_pipeline_python.txt
Q: how to save file list inside list as a json file in python? I 'm trying to parse data from website using beautifulsoap in python and finally I pulled data from website so I want to save data in json file but it saves the data as follows according to the code I wrote json file [ { "collocation": "\nabov...
how to save file list inside list as a json file in python?
I 'm trying to parse data from website using beautifulsoap in python and finally I pulled data from website so I want to save data in json file but it saves the data as follows according to the code I wrote json file [ { "collocation": "\nabove average", "meaning": "more than average, esp. in amount...
[ "import requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport json\n\n\nurl = \"https://www.englishclub.com/ref/Collocations/\"\n\nmylist = [\n \"A\",\n \"B\",\n \"C\",\n \"D\",\n \"E\",\n \"F\",\n \"G\",\n \"H\",\n \"I\",\n \"J\",...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "json", "python" ]
stackoverflow_0074390165_beautifulsoup_json_python.txt
Q: How to make sure a string is both an eight digit number and also not eight alphabets So Im supposed to write a program that does the following • Read an eight-digit integer entered by the user. If less or more then eight digits are entered prompt the user again for input Ive tried the following methods yet they ...
How to make sure a string is both an eight digit number and also not eight alphabets
So Im supposed to write a program that does the following • Read an eight-digit integer entered by the user. If less or more then eight digits are entered prompt the user again for input Ive tried the following methods yet they dont work, what do I do. Either it accepts asdfghjk as an eight digit number or it crashes...
[ "I think you got the \"continue\" command wrong.\nContinue jumps to the next iteration, e.g. starts again at the while loop. You should exchange it to \"break\", which breaks out of the loop continuing with the code after the while loop.\nEdit: and also you can delete the semicolon after continue. There is no need ...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074390003_python.txt
Q: Repeat calculations for every row of dataframe The following calculations were for the 1st row, i.e., train_df.y1[0]. I want to repeat this operation for all 400 rows of train_df squared_deviations_y1_0_train = ((ideal_df.loc[:0,"y1":"y50"] - train_df.y1[0]) ** 2).sum(axis=1) The result is correct, just need to r...
Repeat calculations for every row of dataframe
The following calculations were for the 1st row, i.e., train_df.y1[0]. I want to repeat this operation for all 400 rows of train_df squared_deviations_y1_0_train = ((ideal_df.loc[:0,"y1":"y50"] - train_df.y1[0]) ** 2).sum(axis=1) The result is correct, just need to repeat it.
[ "Since your end result seems to be a scalar, you can convert both of these dataframes to Numpy and take advantage of braodcasting.\nSomething like this,\nsquared_deviations = ((ideal_df.to_numpy() - train_df.y1.to_numpy().reshape(-1,1)) ** 2).sum(axis=1)\n\nwould do pretty nicely. If you MUST stay within pandas, yo...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074382573_dataframe_pandas_python.txt
Q: How to correctly install rpy2 in python? There are a lot of other questions like mine but they're quite outdated so I think a new updated guide would be helpful for everyone trying to install rpy2 in Python. In my case, I'm trying to work with the package pymer4 but i couldn't manage to correctly import it. I foun...
How to correctly install rpy2 in python?
There are a lot of other questions like mine but they're quite outdated so I think a new updated guide would be helpful for everyone trying to install rpy2 in Python. In my case, I'm trying to work with the package pymer4 but i couldn't manage to correctly import it. I found out that the error lies in rpy2.robjects so ...
[ "I think I found the solution.\nThe problem is with conda and rpy2, apparently rpy2 installed with conda is outdated.\nYou can install correctly rpy2 on a new environment (venv or conda env) using pip.\nI did it and so far it's working perfectly.\n" ]
[ 1 ]
[]
[]
[ "python", "r", "rpy2" ]
stackoverflow_0074358650_python_r_rpy2.txt
Q: from 1 point in a numpy array to another Let's say I have this numpy array: [[0. 1. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0.] [0. 1. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0.]] And I want to print the coordinates going from the first 1 to the second 1. this is my code: def walking(start...
from 1 point in a numpy array to another
Let's say I have this numpy array: [[0. 1. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0.] [0. 1. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0.]] And I want to print the coordinates going from the first 1 to the second 1. this is my code: def walking(start, end): for j in range(end[0]): ...
[ "This code should do it:\nHeader:\nimport numpy as np # Import\n\n# Creating an array for the example\narr = np.array([[0., 0., 1., 0., 0., 0.,], [0., 0., 0., 0., 0., 0.,], [0., 0., 0., 0., 0., 0.,], [0., 0., 0., 0., 0., 0.,], [0., 0., 0., 0., 1., 0.,], [0., 0., 0., 0., 0., 0.,]])\nx,y = np.where(arr == 1.) # Selec...
[ 0 ]
[]
[]
[ "arrays", "coordinates", "numpy", "numpy_ndarray", "python" ]
stackoverflow_0074390139_arrays_coordinates_numpy_numpy_ndarray_python.txt
Q: 2 raised to what power, is greater than 1,000,000,000? print the answer(answer must be int) I am trying to find this answer using while loop but I have not been able to write the code. I was trying the below code: base=2 num=1 while base**num > 1000000000: print(num) num +=1 A: Here's a solution using log...
2 raised to what power, is greater than 1,000,000,000? print the answer(answer must be int)
I am trying to find this answer using while loop but I have not been able to write the code. I was trying the below code: base=2 num=1 while base**num > 1000000000: print(num) num +=1
[ "Here's a solution using log.\n import math\n res = math.log(1000000000,2)\n num = int(res)+1 # taking ceiling and not floor of the log as 2^floor will result in a number less than 1000000000\n print(num)\n\nUsing a while loop will be inefficient and computationally very expensive, especially for large ...
[ 2, 1, 0, 0 ]
[ "after define the variable and value is getting output as expected, check the below code.\nbase = 2\nnum = 0\nwhile (base**num < 1000000000):\n num += 1\nprint(num)\n\nOutput will come:- 30\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0072213807_python.txt
Q: Make straight lines in frames in cartopy in python I want to create a map and frame: import matplotlib.colors import matplotlib.pyplot as plt import cartopy.crs as ccrs fig, ax1 = plt.subplots(1, 1,subplot_kw={'projection': ccrs.Mercator()}, figsize=(7,7), gridspec_kw={'wspace': 0.2, 'hspace': 0.2}) ax1.set_exten...
Make straight lines in frames in cartopy in python
I want to create a map and frame: import matplotlib.colors import matplotlib.pyplot as plt import cartopy.crs as ccrs fig, ax1 = plt.subplots(1, 1,subplot_kw={'projection': ccrs.Mercator()}, figsize=(7,7), gridspec_kw={'wspace': 0.2, 'hspace': 0.2}) ax1.set_extent([-50.0, 45.0, 30.0, 70.0]) ax1.coastlines('50m', color...
[ "The default threshold value is too large. You must set it smaller to get more smooth curve.\nimport matplotlib.colors\nimport matplotlib.pyplot as plt\nimport cartopy.crs as ccrs\n\nuse_proj = ccrs.Mercator()\nuse_proj._threshold /= 20.\n\nfig, ax1 = plt.subplots(1, 1,subplot_kw={'projection': use_proj}, figsize=(...
[ 1 ]
[]
[]
[ "cartopy", "maps", "python" ]
stackoverflow_0074389783_cartopy_maps_python.txt
Q: Add column to DataFrame and assign number to each row I have the following table Father Son Year James Harry 1999 James Alfi 2001 Corey Kyle 2003 I would like to add a fourth column that makes the table look like below. It's supposed to show which child of each father was born first, second, third, and so on....
Add column to DataFrame and assign number to each row
I have the following table Father Son Year James Harry 1999 James Alfi 2001 Corey Kyle 2003 I would like to add a fourth column that makes the table look like below. It's supposed to show which child of each father was born first, second, third, and so on. How can I do that? Father Son Year Child ...
[ "here is one way to do it. using cumcount\n# groupby Father and take a cumcount, offsetted by 1\ndf['Child']=df.groupby(['Father'])['Son'].cumcount()+1\ndf\n\n\n Father Son Year Child\n0 James Harry 1999 1\n1 James Alfi 2001 2\n2 Corey Kyle 2003 1\n\nit assumes that DF is sor...
[ 1, 0 ]
[]
[]
[ "dataframe", "python" ]
stackoverflow_0074390204_dataframe_python.txt
Q: How to write a function that swaps the first and last elements of a list argument Write a function swap that swaps the first and last elements of a list argument. Sample output with input: 'all,good,things,must,end,here' ['here', 'good', 'things', 'must', 'end', 'all'] def swap (values_list): values_list[0] ...
How to write a function that swaps the first and last elements of a list argument
Write a function swap that swaps the first and last elements of a list argument. Sample output with input: 'all,good,things,must,end,here' ['here', 'good', 'things', 'must', 'end', 'all'] def swap (values_list): values_list[0] = values_list[-1] values_list[-1] = values_list[0] return values_list values_l...
[ "This should work.\nWhat you did was make item 0 the last item with the first statement, then made the last item the first item which was just made the last item.\nYou need to swap both items at the same time, or store them in a temp variable first, then swap them.\ndef swap (values_list):\n temp0 = values_list[...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074033631_python.txt
Q: google_link,google_text = google(result) make cannot unpack non-iterable NoneType object djanog BeautifulSoup i try to make search google with BeautifulSoup in socialnetwork django site project i download it as open source and when i try to make that i receve a error message cannot unpack non-iterable NoneType obj...
google_link,google_text = google(result) make cannot unpack non-iterable NoneType object djanog BeautifulSoup
i try to make search google with BeautifulSoup in socialnetwork django site project i download it as open source and when i try to make that i receve a error message cannot unpack non-iterable NoneType object thats search.py import requests from bs4 import BeautifulSoup done def google(s): links = [] text = [] USER_A...
[ "not None returns True if the objects are not identical. In your case, r=None and 'if r is not None' is immediately checked, so False is returned. All lines below the if statement are not involved. Probably because of this: cannot unpack non-iterable NoneType object. Because he doesn't exist.\nThe rest of the code ...
[ 0 ]
[]
[]
[ "django", "django_templates", "html", "python", "python_3.x" ]
stackoverflow_0074345133_django_django_templates_html_python_python_3.x.txt
Q: I am getting a Name error during an If statement I am getting a name error not defined error when entering bond into the program. If anyone could shed some light onto where I have gone wrong that would be great. elif greeting == "Bond": house_value = int (input('''Please enter the value of the house: ''')...
I am getting a Name error during an If statement
I am getting a name error not defined error when entering bond into the program. If anyone could shed some light onto where I have gone wrong that would be great. elif greeting == "Bond": house_value = int (input('''Please enter the value of the house: ''')) monthly_rate=float(input('''Enter the percenta...
[ "If you enter elif greeting == \"Bond\": then y is not defined\n", "You can use nested if-statements, watch the indentation, for example, by moving the last if-elif statement under if greeting.\nif greeting == investment:\n\n...\n\n if y == simple:\n\n ...\n\n elif y == compound:\n\n ...\n\n ...
[ 5, 0 ]
[]
[]
[ "nameerror", "python" ]
stackoverflow_0074390114_nameerror_python.txt
Q: Responses is returned as string and not as json - Python I am trying to send back (get requests) a json but instead is sending a json as string "{"series": [{"name": "Count of Signups", "type": "column", "data": [4, 29, 10]}, {"name": "Average of signups over last 3 Months", "type": "line", "data": [NaN, NaN, 14.0...
Responses is returned as string and not as json - Python
I am trying to send back (get requests) a json but instead is sending a json as string "{"series": [{"name": "Count of Signups", "type": "column", "data": [4, 29, 10]}, {"name": "Average of signups over last 3 Months", "type": "line", "data": [NaN, NaN, 14.0]}], "labels": ["2020-06", "2020-07", "2020-08"]}" The disire...
[ "I fixed, it was the NaN values on the dict, now works fine if i replace them for \"0\"\n" ]
[ 0 ]
[]
[]
[ "django", "json", "python", "response" ]
stackoverflow_0074390381_django_json_python_response.txt
Q: Equivalent of C macros __DATE__ and __TIME__ in Python? Is there an equivalent of __DATE__ and __TIME__ in Python? A: Python doesn't have the same compilation process as C so there aren't macros to use, but if you wanted something quick and dirty the __file__ global variable stores the name of the current Python...
Equivalent of C macros __DATE__ and __TIME__ in Python?
Is there an equivalent of __DATE__ and __TIME__ in Python?
[ "Python doesn't have the same compilation process as C so there aren't macros to use, but if you wanted something quick and dirty the __file__ global variable stores the name of the current Python file so you could check when this file was modified to give you something a bit like a build date:\nimport os, time\npr...
[ 4, 3, 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0003281074_datetime_python.txt
Q: LinAlgError: SVD did not converge in Linear Least Squares : fit() function gives me error In the process of VAR modeling, I opt to employ Information Criterion Akaike (AIC) as a model selection criterion to conduct optimal model identification. In simple terms, I select the order (p) of VAR based on the best AIC s...
LinAlgError: SVD did not converge in Linear Least Squares : fit() function gives me error
In the process of VAR modeling, I opt to employ Information Criterion Akaike (AIC) as a model selection criterion to conduct optimal model identification. In simple terms, I select the order (p) of VAR based on the best AIC score.So I run this code: forecasting_model = VAR(train) results_aic = [] for p in range(1,10): ...
[ "I can't leave comments yet, so apologies that this is not a full-fledged answer, but this answer here to a similar question has a lot of upvotes suggesting there are some NaNs or infinities in your dataset. You could probably do a sanity check of print(np.sum(np.isnan(train))) to check if you have NaNs in your dat...
[ 0 ]
[]
[]
[ "forecasting", "jupyter_notebook", "python", "time_series", "var" ]
stackoverflow_0073978903_forecasting_jupyter_notebook_python_time_series_var.txt
Q: No package metadata was found for apache-superset (superset) cwj0@ubuntu:~/anaconda3/envs/superset/lib/python3.7/site-packages/incubator-superset$ superset init Traceback (most recent call last): File "/home/cwj0/anaconda3/envs/superset/bin/superset", line 33, in <module> sys.exit(load_entry_point('apache-su...
No package metadata was found for apache-superset
(superset) cwj0@ubuntu:~/anaconda3/envs/superset/lib/python3.7/site-packages/incubator-superset$ superset init Traceback (most recent call last): File "/home/cwj0/anaconda3/envs/superset/bin/superset", line 33, in <module> sys.exit(load_entry_point('apache-superset', 'console_scripts', 'superset')()) File "/hom...
[ "Solved.\nBecause this is the need to refresh the permissions after I add a new page, I don't know why the dependencies are missing, and the installation is solved.\npip install -r requirements/local.txt,pip install -e .\n(superset) cwj0@ubuntu:~/anaconda3/envs/superset/lib/python3.7/site-packages/incubator-superse...
[ 1, 0 ]
[]
[]
[ "apache_superset", "python" ]
stackoverflow_0070694733_apache_superset_python.txt
Q: Assigning multiple values to the same string during dictionary mapping (pandas) I have the following code below. I am trying to carry out a mapping where the value 0 in the dataframe column 'caffeine' is replaced by 'no' and any other value aside 0 is replaced by 'yes'. However, the following command, the values t...
Assigning multiple values to the same string during dictionary mapping (pandas)
I have the following code below. I am trying to carry out a mapping where the value 0 in the dataframe column 'caffeine' is replaced by 'no' and any other value aside 0 is replaced by 'yes'. However, the following command, the values that are not 0 are replaced with 'NaN' rather than 'yes'. Would be so grateful for a h...
[ "here is one way to do it\n# check value of caffeine, if it zero, then map the boolean result to Yes, No\ndf['caffeine']=df['caffeine'].eq(0).map({True:'no', False:'yes'})\n\n", "You can actually use np.where() to achieve the logic you are stating, without the need to state all potential values besides 0. It func...
[ 2, 1, 1 ]
[]
[]
[ "dataframe", "dictionary", "group_by", "pandas", "python" ]
stackoverflow_0074390625_dataframe_dictionary_group_by_pandas_python.txt
Q: FastApi/Sqlalchemy "class is not mapped" error I'm getting this error when I try to post and create a new registry using fastapi and sqlalchemy: Class 'endpoints.resultados.ResultadoPruebaSerializer.InsertTResultadoRegla' is not mapped Here is my code, thanks for your help. Sqlalchemy Models @as_declarative() cl...
FastApi/Sqlalchemy "class is not mapped" error
I'm getting this error when I try to post and create a new registry using fastapi and sqlalchemy: Class 'endpoints.resultados.ResultadoPruebaSerializer.InsertTResultadoRegla' is not mapped Here is my code, thanks for your help. Sqlalchemy Models @as_declarative() class Base: def as_dict(self) -> dict: return {c...
[ "The issue is when you are trying to add it to the db, precisely,\ndb.add(db_item)\n\nYou have to add it like shown below:\ndb_item = InsertTResultadoRegla(idtareas=1, idreglas=regla[\"idreglas\"], fecCreacion=datetime.date.today(), resultado=\"CUMPLE\")\nactual_db_item = models.TableName(** db_item.dict())\ndb.add...
[ 0 ]
[]
[]
[ "api", "fastapi", "pydantic", "python", "sqlalchemy" ]
stackoverflow_0063196650_api_fastapi_pydantic_python_sqlalchemy.txt
Q: filtering python list/dictionary and retrieve value for selected key working on Python script. I get a result that is list: a = [{'S_RAF': {'C_C106': {'D_1103': 'AVE', 'D_1104': '3-AB3242'}}}, {'S_RAF': {'C_C106': {'D_1103': 'OI', 'D_1104': '31503302130'}}}, {'S_RAF': {'C_C106': {'D_1103': 'PQ', 'D_1104': 'IBAN31...
filtering python list/dictionary and retrieve value for selected key
working on Python script. I get a result that is list: a = [{'S_RAF': {'C_C106': {'D_1103': 'AVE', 'D_1104': '3-AB3242'}}}, {'S_RAF': {'C_C106': {'D_1103': 'OI', 'D_1104': '31503302130'}}}, {'S_RAF': {'C_C106': {'D_1103': 'PQ', 'D_1104': 'IBAN3102495934895'}}}] And I would like to get the value of Key: D_1104, when th...
[ "Should do it:\na[2]['S_RAF']['C_C106']['D_1104'] # IBAN3102495934895\n\n", "Get ISBNs where D_1103 == \"PQ\".\nibans = [x[\"S_RAF\"][\"C_C106\"][\"D_1104\"] for x in a if x[\"S_RAF\"][\"C_C106\"][\"D_1103\"]==\"PQ\"]\nibans = ibans[0] # \"IBAN3102495934895\"\n\n", "You can iterate through the list and check t...
[ 0, 0, 0 ]
[]
[]
[ "function", "json", "list", "python", "xml" ]
stackoverflow_0074390627_function_json_list_python_xml.txt
Q: Difference between df[x], df[[x]], df['x'] , df[['x']] and df.x Struggling to understand the difference between the 5 examples in the title. Are some use cases for series vs. data frames? When should one be used over the other? Which are equivalent? A: df[x] — index a column using variable x. Returns pd.Series d...
Difference between df[x], df[[x]], df['x'] , df[['x']] and df.x
Struggling to understand the difference between the 5 examples in the title. Are some use cases for series vs. data frames? When should one be used over the other? Which are equivalent?
[ "\ndf[x] — index a column using variable x. Returns pd.Series\ndf[[x]] — index/slice a single-column DataFrame using variable x. Returns pd.DataFrame\ndf['x'] — index a column named 'x'. Returns pd.Series\ndf[['x']] — index/slice a single-column DataFrame having only one column named 'x'. Returns pd.DataFrame \ndf....
[ 29, 0 ]
[]
[]
[ "dataframe", "pandas", "python", "series" ]
stackoverflow_0050302180_dataframe_pandas_python_series.txt
Q: Create instance of classes based on some parameters Here's a simplified version of the problem I'm trying to solve. I have a config file where some parameters are defined for persons. As you can see there are some common attributes that are common e.g. role and age and there are some attributes that are unique to ...
Create instance of classes based on some parameters
Here's a simplified version of the problem I'm trying to solve. I have a config file where some parameters are defined for persons. As you can see there are some common attributes that are common e.g. role and age and there are some attributes that are unique to employee or student. Example of config file: role = emplo...
[ "If the 'roles' are always going to have the same name as the classes, then you can look them up in the locals dict like this:\ncls = locals()[role.title()]\nnew_person = cls(p1, p2, ...)\n\nYou can use the globals dict the same way if the classes are out of your current scope.\n" ]
[ 0 ]
[]
[]
[ "inheritance", "oop", "python" ]
stackoverflow_0074390741_inheritance_oop_python.txt
Q: Writing csv-file with IronPython (in Ansys Mechanical) I am trying to export data from Ansys Mechanical by writing into a csv file. Unfortunately with my code the charakters in my lists don´t get seperated by the comma. They just end up in one cell and I can't figure out why. Thanks allot Here are an example of my...
Writing csv-file with IronPython (in Ansys Mechanical)
I am trying to export data from Ansys Mechanical by writing into a csv file. Unfortunately with my code the charakters in my lists don´t get seperated by the comma. They just end up in one cell and I can't figure out why. Thanks allot Here are an example of my code and results import csv csv_outfile = r'Z:\Ansys\05-11-...
[ "with open('test.csv', 'w') as ofile:\n write = csv.writer(ofile)\n write.writerow(i for i in ['1' ,'2' ,'3']) # \n\nChange wb to w Because you write numbers\n" ]
[ 1 ]
[]
[]
[ "ansys", "ironpython", "python" ]
stackoverflow_0074389830_ansys_ironpython_python.txt
Q: How to return a group by query via Django REST API? I have a Django REST API which works perfectly when I want to query some data from the database. Here I have an example: views.py class ProductListAPIView(generics.ListAPIView): def get_queryset(self): # Collect data from products tab...
How to return a group by query via Django REST API?
I have a Django REST API which works perfectly when I want to query some data from the database. Here I have an example: views.py class ProductListAPIView(generics.ListAPIView): def get_queryset(self): # Collect data from products table and filter it queryset = Product.objects.filte...
[ "Is category a ForeignKey to a model? I think the problem is with this field in that case.\nI believe that when you call .values() you get the id of foreignKey-fields and you can't access that field as an object anymore.\nSo REST Framework is trying to access the property pk on what it thinks is an instance of Cate...
[ 1 ]
[]
[]
[ "api", "django", "django_rest_framework", "python", "rest" ]
stackoverflow_0074390590_api_django_django_rest_framework_python_rest.txt
Q: AttributeError: module 'sklearn.feature_extraction.image' has no attribute 'extract_patches' AttributeError: module 'sklearn.feature_extraction.image' has no attribute 'extract_patches' How to solve it without patchify. A: extract_patches_2d and reconstruct_from_patches_2d are the current methods which can be us...
AttributeError: module 'sklearn.feature_extraction.image' has no attribute 'extract_patches'
AttributeError: module 'sklearn.feature_extraction.image' has no attribute 'extract_patches' How to solve it without patchify.
[ "extract_patches_2d and reconstruct_from_patches_2d are the current methods which can be used in the sklearn image feature_extraction library. Try one of those and see if it works. Source here: https://github.com/scikit-learn/scikit-learn/blob/f3f51f9b6/sklearn/feature_extraction/image.py#L323\n" ]
[ 0 ]
[]
[]
[ "python", "sklearn_pandas" ]
stackoverflow_0074388105_python_sklearn_pandas.txt
Q: Django Ninja API framework Foreing Key ValueError: Cannot assign must be instance My project running Django 4.1 and Ninja 0.19.1. I'm trying to make a post request via Swagger or Postman and getting an error ValueError: Cannot assign "115": "Offer.currency_to_sell" must be a "Currency" instance. Post data is: { ...
Django Ninja API framework Foreing Key ValueError: Cannot assign must be instance
My project running Django 4.1 and Ninja 0.19.1. I'm trying to make a post request via Swagger or Postman and getting an error ValueError: Cannot assign "115": "Offer.currency_to_sell" must be a "Currency" instance. Post data is: { "currency_to_sell_id": 115, "currency_to_buy_id": 116, "user_id": 1, "amount": 10...
[ "As you can see in your Offer model you have a field called currency_to_sell, it contains an object of the Currency model so when you are sending an id in your POST request you're getting the following error:\nCannot assign \"115\": \"Offer.currency_to_sell\" must be a \"Currency\" instance.\n\nTherefore you have t...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074387951_django_python.txt
Q: Create new pandas df by referencing 2 existing Been spinning my wheels over the most efficient way to accomplish the below, so looking for some guidance. For context, df1 shape is (599379,319). Thank you in advance. df1: A B val 1 val 1 val 2 val 2 df2: C D E A val 1 val 3 A val 2 val 4 B val 1 val 3 B va...
Create new pandas df by referencing 2 existing
Been spinning my wheels over the most efficient way to accomplish the below, so looking for some guidance. For context, df1 shape is (599379,319). Thank you in advance. df1: A B val 1 val 1 val 2 val 2 df2: C D E A val 1 val 3 A val 2 val 4 B val 1 val 3 B val 2 val 4 Desired Output: ...
[ "You can loop over your columns from df1 and merge it individually with a filter on df2['C']:\nfor x in df1.columns:\n temp = df1.merge(df2[df2['C'] == x], left_on=x, right_on='D').drop(['C','D'], axis=1)\n df[f'{x}1'] = temp['E']\n\nResult:\n A B A1 B1\n0 val 1 val 1 val 3 val 3\n...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074390740_dataframe_pandas_python.txt
Q: How to do convolution matrix operation in numpy? Is there a way to do convolution matrix operation using numpy? The numpy.convolve only operates on 1D arrays, so this is not the solution. I rather want to avoid using scipy, since it appears to be more difficult getting installed on Windows. A: You have scipy's n...
How to do convolution matrix operation in numpy?
Is there a way to do convolution matrix operation using numpy? The numpy.convolve only operates on 1D arrays, so this is not the solution. I rather want to avoid using scipy, since it appears to be more difficult getting installed on Windows.
[ "You have scipy's ndimage which allows you to perform N-dimensional convolution with convolve:\nfrom scipy.ndimage import convolve\nconvolve(data, kernel)\n\nI know that you said that you want to avoid scipy... but I would advise against it. Scipy is great in so many ways. If you want to install it on windows, try ...
[ 14, 4, 1, 0, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0043373521_numpy_python.txt
Q: What does dereference of free object in Ghostscript mean? I am getting the following error when trying to compress a pdf with Ghostscript: The output pdf has images and text missing. (Note: The missing images are pdf format themselves.) My code is working as I am getting an output pdf. My input pdf is 30 MB and m...
What does dereference of free object in Ghostscript mean?
I am getting the following error when trying to compress a pdf with Ghostscript: The output pdf has images and text missing. (Note: The missing images are pdf format themselves.) My code is working as I am getting an output pdf. My input pdf is 30 MB and my output pdf is 9 MB, if this is required please indicate how I...
[ "Just to close this issue, not that it solved my problem, but I went down a rabbit hole and the only explanation I could find for my specific error was that there is a bug in Ghostscript when compressing pdfs that contain vector images or pdf images, not clear which.\nI have given up on using Ghostscript at the mom...
[ 0 ]
[]
[]
[ "ghostscript", "pdf", "pdflatex", "python", "python_3.x" ]
stackoverflow_0072811117_ghostscript_pdf_pdflatex_python_python_3.x.txt
Q: X-axis labels not aligning with values on seaborn plot I have the following code below. I am trying to create a line plot. However, when I label the x-axis, the x-axis values seem crammed and I'm not sure why? fig, axes = plt.subplots(nrows=2,figsize=(15, 15)) fig.tight_layout(pad=10) newerdf = newdf.copy() bins ...
X-axis labels not aligning with values on seaborn plot
I have the following code below. I am trying to create a line plot. However, when I label the x-axis, the x-axis values seem crammed and I'm not sure why? fig, axes = plt.subplots(nrows=2,figsize=(15, 15)) fig.tight_layout(pad=10) newerdf = newdf.copy() bins = [18,28,38,48,58] names = ['<28','28-37.99','38-47.99','48-...
[]
[]
[ "To solve this, I assigned tick positions manually and then assigned labels to them :)\nfig, axes = plt.subplots(nrows=2,figsize=(15, 15))\nfig.tight_layout(pad=10)\n\nnewerdf = newdf.copy()\nbins = [18,28,38,48,58]\nnames = ['<28','28-37.99','38-47.99','48-57.99','58+']\nnewerdf['age'] = np.digitize(newerdf['age']...
[ -1 ]
[ "matplotlib", "numpy", "pandas", "python", "seaborn" ]
stackoverflow_0074390559_matplotlib_numpy_pandas_python_seaborn.txt
Q: Python Beginner: Why is this my output? function generate at 0x0000021EE6848700 I'm trying to generate random numbers using user input. This is for a homework question and is structured as the professor instructed. I'm returning x amount of this instead of numbers. function generate at 0x0000021EE6848700 I feel l...
Python Beginner: Why is this my output? function generate at 0x0000021EE6848700
I'm trying to generate random numbers using user input. This is for a homework question and is structured as the professor instructed. I'm returning x amount of this instead of numbers. function generate at 0x0000021EE6848700 I feel like this is a stupid question and I'm missing something obvious. When I try to define...
[ "You're not calling the generate method - you're literally printing the method itself. I think that you meant print(generate()).\nThat being said, print(generate()) doesn't make sense either because generate() doesn't return anything - it already prints. If you want to print the result of generate in main, you shou...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074390963_python.txt
Q: QTableView - checkbox is never checked I have a QTableView object with custom model - for which I'd like to have first column of each row with checkbox. Following several Google/SO searches, I found a way that let's me show the checkbox, but the problem is that checkbox never becomes checked in the UI, even if I f...
QTableView - checkbox is never checked
I have a QTableView object with custom model - for which I'd like to have first column of each row with checkbox. Following several Google/SO searches, I found a way that let's me show the checkbox, but the problem is that checkbox never becomes checked in the UI, even if I force state to checked from the model. Table ...
[ "Answering to myself - there is a big in PySide 6.4.0 and is solved with fix for 6.4.0.1\nMore here: https://forum.qt.io/topic/140632/qtableview-checkbox-is-never-checked\nBug report: https://bugreports.qt.io/browse/PYSIDE-1930\n" ]
[ 0 ]
[]
[]
[ "python", "qt" ]
stackoverflow_0074380799_python_qt.txt
Q: Python Regex: Find integer with possible zeros after comma I have the following case: Test (2.00001) Test (2.000) Test 2.1 Test (2,0001) Test 2,000 Test 2,1000 test 2 I try to use regex to find only the integers: 2.000 2,000 2 but not the other float numbers. I tried different things: re.search('(?<![0-9.])2(?!...
Python Regex: Find integer with possible zeros after comma
I have the following case: Test (2.00001) Test (2.000) Test 2.1 Test (2,0001) Test 2,000 Test 2,1000 test 2 I try to use regex to find only the integers: 2.000 2,000 2 but not the other float numbers. I tried different things: re.search('(?<![0-9.])2(?![.,]?[1-9])(?=[.,]*[0]*)(?![1-9]),...) but this returns true fo...
[ "I would use:\nimport re\n\ntext = 'Test (2.00001) Test (2.000) Test 2.1 Test (2,0001) Test 2,000 Test 2,1000'\n\nre.findall(r'(\\d+[.,]0+)(?!\\d)', text)\n\nOutput:\n['2.000', '2,000']\n\nRegex:\n( # start capturing\n\\d+ # match digit(s)\n[.,] # match . or ,\n0+ # match one or more zeros\n) ...
[ 2, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074389572_python_regex.txt
Q: Explain DeprecationWarning: private variables, such as '_Cmd__call_set', will be normal attributes in 3.10 Python interpreter version used in the code base I am working on has recently been updated from Python 3.7 to 3.9. A few new warnings similar to one in the title have started showing up when some of the tools...
Explain DeprecationWarning: private variables, such as '_Cmd__call_set', will be normal attributes in 3.10
Python interpreter version used in the code base I am working on has recently been updated from Python 3.7 to 3.9. A few new warnings similar to one in the title have started showing up when some of the tools written in Python are executed. I've searched the net extensively, read the What's New in 3.10 but haven't foun...
[ "writing an attribute as so:\n_attr makes it a private attribute, and __attr makes it a protected attribute. This deprecation warning seems to indicate the attributes in question will be made not private and not protected in 3.10.\nTL;DR\nThey won't have the underscore in 3.10, and they will be completely visible.\...
[ 1 ]
[]
[]
[ "deprecation_warning", "private_members", "python", "python_3.x" ]
stackoverflow_0074390633_deprecation_warning_private_members_python_python_3.x.txt
Q: Some error with code on Python, JavaScript, HTML and CSS I'm learning JavaScript and Python and I wrote a code that creates a file and enters information into it. But the recv_data function does not work - the file is not created. What should I do? The code will be below. Python import eel eel.init("web") @eel.exp...
Some error with code on Python, JavaScript, HTML and CSS
I'm learning JavaScript and Python and I wrote a code that creates a file and enters information into it. But the recv_data function does not work - the file is not created. What should I do? The code will be below. Python import eel eel.init("web") @eel.expose def recv_data(surname, name, grade): f=open("results.t...
[ " async function sendData() {\n let surname = document.querySelector(\"#surname\").value;\n let name = document.querySelector(\"#name\").value;\n let klass = document.querySelector(\"#grade\").value;\n await eel.recv_data(surname, name, grade);\n }\n\nWhen awaiting async data w...
[ 0 ]
[]
[]
[ "css", "eel", "html", "javascript", "python" ]
stackoverflow_0074273228_css_eel_html_javascript_python.txt
Q: How to solve: UnboundLocalError: local variable 't' referenced before assignment? in python? I am trying to implement the Simulated Annealing (SA) algorithm to solve a random instance of the Traveling Salesman Problem (TSP) in python. In my code, I have a function that computes the total longitude of the tour, giv...
How to solve: UnboundLocalError: local variable 't' referenced before assignment? in python?
I am trying to implement the Simulated Annealing (SA) algorithm to solve a random instance of the Traveling Salesman Problem (TSP) in python. In my code, I have a function that computes the total longitude of the tour, given a list with the route and the distance matrix. When I run my code I have the following error re...
[ "It means that you tried to read from t when the computer has never seen t before.\nSuppose you wrote something like:\nx = t*99 + 3\n\n.... but t never appeared answered earlier in the program. The computer can't multiply t by 99 unless it knows what t is. You tried to do something using t before ever assigning any...
[ 0, 0, 0 ]
[]
[]
[ "global_variables", "local_variables", "optimization", "python", "traveling_salesman" ]
stackoverflow_0058760085_global_variables_local_variables_optimization_python_traveling_salesman.txt
Q: How to merge dataset in Python based on column value I have a dataframe structured as follows: "Location","filePath","startLine","endLine","startColumn","endColumn","codeElementType","description", "codeElement","repository","sha1","url","type","description.1" An example of the dataframe is the following: I need...
How to merge dataset in Python based on column value
I have a dataframe structured as follows: "Location","filePath","startLine","endLine","startColumn","endColumn","codeElementType","description", "codeElement","repository","sha1","url","type","description.1" An example of the dataframe is the following: I need to merge the entry that has the same sha1. An example of...
[ "agg_functions should be references to functions, not column names.\nfor example:\nagg_functions = [np.sum, \"mean\"]\n\nsee DataFrameGroupBy.aggregate\nI can't help with an exact fix. I must confess the text in the images you posted is too small for me to understand what your final result needs to be.\n" ]
[ 0 ]
[]
[]
[ "dataframe", "python" ]
stackoverflow_0074391068_dataframe_python.txt
Q: How to put every line of a excel table into a python dictionary? Just beginning with python and working on a small project. Trying to figure out to get a list of dictionarys for every line in a Excel file. For example: first_name last_name age Peter Johnsen 42 Mark Conner 32 Susanna Rock 36 Into: [ {'first_na...
How to put every line of a excel table into a python dictionary?
Just beginning with python and working on a small project. Trying to figure out to get a list of dictionarys for every line in a Excel file. For example: first_name last_name age Peter Johnsen 42 Mark Conner 32 Susanna Rock 36 Into: [ {'first_name' : 'Peter' , 'last_name' : 'Johnsen' , 'age' : '42'} , {...
[ "here is one way to do it\n# to_dict with orientation as records\nout=df.to_dict('records')\nout\n\n[{'first_name': 'Peter ', 'last_name': 'Johnsen ', 'age': 42},\n {'first_name': 'Mark ', 'last_name': 'Conner ', 'age': 32},\n {'first_name': 'Susanna ', 'last_name': 'Rock ', 'age': 36}]\n\n" ]
[ 0 ]
[]
[]
[ "dictionary", "excel", "pandas", "python" ]
stackoverflow_0074391239_dictionary_excel_pandas_python.txt
Q: Drawing from a Laplace distribution using Scipy yields negatively skewed density When I make draws from a Laplace distribution with mean zero and scale drawn from any distribution that maps into the positive orthant, the resulting empirical distribution is negatively skewed, regardless of the number of draws, dist...
Drawing from a Laplace distribution using Scipy yields negatively skewed density
When I make draws from a Laplace distribution with mean zero and scale drawn from any distribution that maps into the positive orthant, the resulting empirical distribution is negatively skewed, regardless of the number of draws, distribution for the scale and seed. Regarding the large sample size symmetry is expected,...
[ "In both examples, you are giving the same integer random_state argument to the distribution. So, for example, the generation of lam_0 and lap_0 are based on the same sequence of samples from the uniform distribution generated by the underlying random number generator. This results in a correlation between the ar...
[ 1 ]
[]
[]
[ "kernel_density", "numpy", "python", "scipy", "skew" ]
stackoverflow_0074387510_kernel_density_numpy_python_scipy_skew.txt
Q: Writing large amounts of data to a smart card I'm sending this apdu command to write data to a smart card: 0xFF, 0xD6, 0x00, 0x01, 0x10, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc,0xc This is the part of the command where the data is: 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0x...
Writing large amounts of data to a smart card
I'm sending this apdu command to write data to a smart card: 0xFF, 0xD6, 0x00, 0x01, 0x10, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc,0xc This is the part of the command where the data is: 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc,0xc Now how do I go abo...
[ "The technical issue is well addressed by the linked question given by @vlp,\n(rehash: LC has to signal extended length, so it is transmitted as long-indicator 0, hi-lc, lo-lc, followed by command data field, followed by le-high, le-low) so I step a bit back.\nThe more basic question is: what benefit would you have...
[ 0 ]
[]
[]
[ "apdu", "hex", "python", "smartcard", "smartcard_reader" ]
stackoverflow_0074381283_apdu_hex_python_smartcard_smartcard_reader.txt
Q: Getting an image back from Lambda is not shown on windows outlook I have a lambda function that returns an image When creating a new email with an image that its source is the lambda function i was able to see the image on all of the existing mail clients including linux and mac outlook but on windows outlook it i...
Getting an image back from Lambda is not shown on windows outlook
I have a lambda function that returns an image When creating a new email with an image that its source is the lambda function i was able to see the image on all of the existing mail clients including linux and mac outlook but on windows outlook it is not shown, I get a red X sign with the text "The picture can't be dis...
[ "HTML messages are rendered in Outlook by Word, and (at least in the older versions), it does not support msg tags with inlined image data.\nYou'd need to add the image as an attachment, set its Content-ID MIME header, and refer to that image in the HTML body through <img src=\"cid:MyContenttId\">\n" ]
[ 0 ]
[]
[]
[ "amazon_web_services", "aws_lambda", "outlook", "python", "python_imaging_library" ]
stackoverflow_0074389727_amazon_web_services_aws_lambda_outlook_python_python_imaging_library.txt
Q: How can I install packages using pip according to the requirements.txt file from a local directory? Here is the problem: I have a requirements.txt file that looks like: BeautifulSoup==3.2.0 Django==1.3 Fabric==1.2.0 Jinja2==2.5.5 PyYAML==3.09 Pygments==1.4 SQLAlchemy==0.7.1 South==0.7.3 amqplib==0.6.1 anyjson==0.3...
How can I install packages using pip according to the requirements.txt file from a local directory?
Here is the problem: I have a requirements.txt file that looks like: BeautifulSoup==3.2.0 Django==1.3 Fabric==1.2.0 Jinja2==2.5.5 PyYAML==3.09 Pygments==1.4 SQLAlchemy==0.7.1 South==0.7.3 amqplib==0.6.1 anyjson==0.3 ... I have a local archive directory containing all the packages + others. I have created a new virtual...
[ "This works for everyone:\npip install -r /path/to/requirements.txt\n\nExplanation:\n\n-r, --requirement < filename >\n\nInstall from the given requirements file. This option can be used multiple times.\n", "This works for me:\n$ pip install -r requirements.txt --no-index --find-links file:///tmp/packages\n\n--no...
[ 1980, 1082, 182, 76, 52, 32, 29, 24, 23, 16, 14, 9, 8, 7, 6, 1 ]
[ "I have solved with running the below command:\npy -m pip install ./requirements.txt\n\nthe above command will install all dependencies and libraries for the Django project.\n" ]
[ -3 ]
[ "pip", "python", "virtualenv" ]
stackoverflow_0007225900_pip_python_virtualenv.txt
Q: ls there a way to connect to database from SQL and get data and execute r or python script using Microsoft SSIS What I want to do is to connect the database from SQL and transfer the r or python code I wrote to SSIS and make it callable and transfer the output to the table in SSMS. I don't know how to make the cod...
ls there a way to connect to database from SQL and get data and execute r or python script using Microsoft SSIS
What I want to do is to connect the database from SQL and transfer the r or python code I wrote to SSIS and make it callable and transfer the output to the table in SSMS. I don't know how to make the code in a format that can generate output by using the data I added to SSIS
[ "Currently, you have some Python or R code that gets data, does something and now you want to store it into a table.\nDepending on volume of data, etc, maybe you just enumerate through your data and issue singleton INSERT statements. I've had a devil of a time getting a bulk insert to work with Python and don't R e...
[ 0 ]
[]
[]
[ "python", "r", "ssis", "ssms" ]
stackoverflow_0074387747_python_r_ssis_ssms.txt
Q: Tweepy 401 error on search_recent_tweets <> BUT no 401 when I create_tweet? How come I can create a tweet and like a tweet with no 401 errors? When I try to search for tweets Im getting a 401? Here's my create_tweet.py file (works fine) import tweepy import config # calling a client client = tweepy.Client( co...
Tweepy 401 error on search_recent_tweets <> BUT no 401 when I create_tweet?
How come I can create a tweet and like a tweet with no 401 errors? When I try to search for tweets Im getting a 401? Here's my create_tweet.py file (works fine) import tweepy import config # calling a client client = tweepy.Client( consumer_key=config.consumer_key, consumer_secret=config.consumer_secret, a...
[ "I face the same problem as you faced.\nMaybe this problem has been solved, just to be sure, I describe the solution.\nI solved this problem by looking at the answers below.\nTweepy: tweepy.errors.Unauthorized: 401 Authorization Required\nplease add \"user_auth=True\" like below\nclient.search_recent_tweets(query=q...
[ 0, 0 ]
[]
[]
[ "authentication", "error_handling", "python", "tweepy" ]
stackoverflow_0070693231_authentication_error_handling_python_tweepy.txt
Q: how to extract data from a txt file into a dataframe using python? Hi I want to colect data from a txt file in order to create a dataframe of 3 columns using python a column for the name of my file 'f' which holds the name of the molecules a column for the values of the ' Zero-point correction' a column for the v...
how to extract data from a txt file into a dataframe using python?
Hi I want to colect data from a txt file in order to create a dataframe of 3 columns using python a column for the name of my file 'f' which holds the name of the molecules a column for the values of the ' Zero-point correction' a column for the values of the 'Sum of electronic and zero-point Energies' in order to hav...
[ "what is the data structure of the file?\none way of doing the following -> but it depends on your data structure in the file/files we are reading\nimport os\nimport pandas as pd\nfiles = [f for f in os.listdir(\".\") if '.out' in f]\nwords = [' Zero-point correction', 'Sum of electronic and zero-point Energies']\n...
[ 0 ]
[]
[]
[ "data_extraction", "dataframe", "pandas", "python" ]
stackoverflow_0074391250_data_extraction_dataframe_pandas_python.txt
Q: Read line seperated by space using python using stdin I want to be able to write a size for a input and after that enter each number seperated by space which is less or equal than the size. Like this: First input (length): 3 inputs: 1 2 3 This should also be converted as an integer and stored in a list I have trie...
Read line seperated by space using python using stdin
I want to be able to write a size for a input and after that enter each number seperated by space which is less or equal than the size. Like this: First input (length): 3 inputs: 1 2 3 This should also be converted as an integer and stored in a list I have tried this: import sys inputs = sys.stdin.readline() print(l...
[ "You can pass the size to sys.stdin.readline() to limit the input by size.\nimport sys\n\nsize = int(input())\n\ninputs = sys.stdin.readline(size * 2)\nmynumbers = inputs.strip().split(' ')\n\nnewlist = [int(x) for x in mynumbers]\nprint(newlist)\n\n", "Without using of stdin\nA first possible answer (without use...
[ 0, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074391073_python_python_3.x.txt
Q: ModuleNotFoundError: No module named 'bootstrap4' I installed bootstrap4 with $ pip install django-bootstrap4 It is being installed in this directory C:\Users\trade\techpit-match-env\Lib\site-packages Django seems to be looking at this directory C:\Users\trade\Anaconda3\lib\site-packages\django When I put 'bootstr...
ModuleNotFoundError: No module named 'bootstrap4'
I installed bootstrap4 with $ pip install django-bootstrap4 It is being installed in this directory C:\Users\trade\techpit-match-env\Lib\site-packages Django seems to be looking at this directory C:\Users\trade\Anaconda3\lib\site-packages\django When I put 'bootstrap4' in the INSTALLED_APPS = ('bootstrap4') variable an...
[ "python -m pip install bootstrap4\n\nThis locates pip on the python module path, thus ensuring that you install bootstrap4 in the same python environment that you use to run the manage.py commands. See this.\n", "Check for a comma after 'bootstrap 4' in settings.py INSTALLED_APPS\nShould be something like that:\n...
[ 11, 2, 1, 0, 0 ]
[]
[]
[ "django", "django_bootstrap4", "python" ]
stackoverflow_0059264892_django_django_bootstrap4_python.txt
Q: PyCharm, NameError: name 'name' is not defined I am working on a library management system project, I keep getting an error that the name 'name' is not defined when I call the program in the last part. Any help would be appreciated, I will post any screenshots or pages if needed. The program will also take the boo...
PyCharm, NameError: name 'name' is not defined
I am working on a library management system project, I keep getting an error that the name 'name' is not defined when I call the program in the last part. Any help would be appreciated, I will post any screenshots or pages if needed. The program will also take the book names I added from a text file titled 'pythonDatab...
[ "It is because you did not define the name variable out of your class.\nIt should look like this:\nif __name__ == '__main__':\n booksList = []\n databaseName = input('Enter the name of the database file with the extension: ')\n bookDatabase = open(databaseName, 'r')\n for book in bookDatabase:\n ...
[ 0 ]
[]
[]
[ "class", "oop", "pycharm", "python" ]
stackoverflow_0074391249_class_oop_pycharm_python.txt
Q: Error while trying to replace multiple values of a pandas data-frame column based on matching condition I have a column in a pandas data frame, among other columns, as such: Remarks Left_only Right_only Left_only Right_only For this column, I want to replace all Left_only values to Yesterday And Ri...
Error while trying to replace multiple values of a pandas data-frame column based on matching condition
I have a column in a pandas data frame, among other columns, as such: Remarks Left_only Right_only Left_only Right_only For this column, I want to replace all Left_only values to Yesterday And Right_only To Today I use this code line: DF.loc[df[‘Remarks’] == ‘Left_only’, ‘Remarks’] = ‘Yesterday’ Simila...
[ "# create a dictionary to map the two values\nd={'Left_only': 'Yesterday', 'Right_only':'Today'}\ndf['Remarks']=df['Remarks'].map(d)\ndf\n\n0 Yesterday\n1 Today\n2 Yesterday\n3 Today\nName: Remarks, dtype: object\n\n" ]
[ 3 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074391443_dataframe_pandas_python.txt
Q: More Efficient For-Loop Calculation? Is there a more efficient way of writing the following? I current have this set up to calculate using a for-loop and at this pace, it will take a few days to compile. I am forecasting demand over a period of 6 years on a weekly basis (52 weeks) broken down by product type (586 ...
More Efficient For-Loop Calculation?
Is there a more efficient way of writing the following? I current have this set up to calculate using a for-loop and at this pace, it will take a few days to compile. I am forecasting demand over a period of 6 years on a weekly basis (52 weeks) broken down by product type (586 types) and zip code (892 unique ZIPs). The...
[ "I think you can do more than than by studying how to use arrays and/or threading. For now, the best I got was 3x faster. I used lower boundaries to not spend the night on this.\nimport numpy as np\nimport timeit\n\ndef f1():\n demand_growth = np.array([10,15,20,23,26,30])\n rand_week_total = np.random.rand(5...
[ 1 ]
[]
[]
[ "for_loop", "numpy", "python" ]
stackoverflow_0074384777_for_loop_numpy_python.txt
Q: How to calculate Mean Bias Error(MBE) in Python? I am trying to calculate Mean Bias Error(MBE) for a set of actual and test prediction in Python. I looked in sklearn.metrics library or NumPy, but there is no method listed to calculate it. Can anyone suggest any library or a way for how to calculate it? Thanks, Deb...
How to calculate Mean Bias Error(MBE) in Python?
I am trying to calculate Mean Bias Error(MBE) for a set of actual and test prediction in Python. I looked in sklearn.metrics library or NumPy, but there is no method listed to calculate it. Can anyone suggest any library or a way for how to calculate it? Thanks, Debayan
[ "MBE is defined as a mean value of differences between predicted and true values so you can calculate it using simple mean difference between two data sources:\nimport numpy as np\ndata_true = np.random.randint(0,100,size=100)\ndata_predicted = np.random.randint(0,100,size=100) - 50\nMBE = np.mean(data_predicted - ...
[ 2, 0, 0 ]
[]
[]
[ "numpy", "python", "scikit_learn", "statistics" ]
stackoverflow_0059935155_numpy_python_scikit_learn_statistics.txt
Q: Problem running single django files from VS Code I have a big Django project that I work in, and I have a problem when I try to run a single .py file from the terminal (I have the correct env set in my VSCode), and it usually breaks when trying to import a module (another django app). When I try to run the same fi...
Problem running single django files from VS Code
I have a big Django project that I work in, and I have a problem when I try to run a single .py file from the terminal (I have the correct env set in my VSCode), and it usually breaks when trying to import a module (another django app). When I try to run the same file from PyCharm I have no issues and runs perfectly (u...
[ "When you run a single file in a project but you have dependency on other files, you need to add the dependent modules path in PATH. You can do that by simply adding the following on top of your file.\nimport sys\n# path to folder containing debt module(the parent folder of the debt folder)\ntemp_path = \"C:/path/t...
[ 0 ]
[]
[]
[ "django", "python", "visual_studio_code" ]
stackoverflow_0074391218_django_python_visual_studio_code.txt
Q: Finding matching motifs on sequence and their positions I am trying to find some matching motifs on a sequence, as well as the position that the motif is located in and then output that into a fasta file. The code below shows that the motif [L**L*L] is present in the sequence, when I run it returns as "YES" but I ...
Finding matching motifs on sequence and their positions
I am trying to find some matching motifs on a sequence, as well as the position that the motif is located in and then output that into a fasta file. The code below shows that the motif [L**L*L] is present in the sequence, when I run it returns as "YES" but I do not know where it is positioned The ** inside the square b...
[ "You can use re.finditer() to search for multiple regex pattern matches within a string. Your peptide1 example does not contain an \"L*L*L\" motif, so I designated a random simple string as a demo.\nsimple_demo_string = \"ABCLXLYLZLABC\" # use a simple string to demonstrate code\n\nThe demo string contains two over...
[ 1 ]
[]
[]
[ "bioinformatics", "biopython", "fasta", "position", "python" ]
stackoverflow_0074381962_bioinformatics_biopython_fasta_position_python.txt
Q: Python : Calling Parent Function in child Class In Python I try to call a method from a Parent Class in a Child class but I get error. class Parent: def __init__(self) -> None: self.value = 0 def __updateValue(self): self.value +=1 class Child(Parent): def __init__(self) -> No...
Python : Calling Parent Function in child Class
In Python I try to call a method from a Parent Class in a Child class but I get error. class Parent: def __init__(self) -> None: self.value = 0 def __updateValue(self): self.value +=1 class Child(Parent): def __init__(self) -> None: super().__init__() def stuff...
[ "Thank you all for the help.\nUsing __ at the begining of the function name was the issue.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074391442_python.txt
Q: NumPy: function for simultaneous max() and min() numpy.amax() will find the max value in an array, and numpy.amin() does the same for the min value. If I want to find both max and min, I have to call both functions, which requires passing over the (very big) array twice, which seems slow. Is there a function in t...
NumPy: function for simultaneous max() and min()
numpy.amax() will find the max value in an array, and numpy.amin() does the same for the min value. If I want to find both max and min, I have to call both functions, which requires passing over the (very big) array twice, which seems slow. Is there a function in the numpy API that finds both max and min with only a s...
[ "\nIs there a function in the numpy API that finds both max and min with only a single pass through the data?\n\nNo. At the time of this writing, there is no such function. (And yes, if there were such a function, its performance would be significantly better than calling numpy.amin() and numpy.amax() successivel...
[ 68, 35, 33, 30, 22, 15, 13, 9, 6, 3, 2, 0, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0012200580_numpy_python.txt
Q: Scraping Produce image by BeautifulSoup I'm trying to Scrap the product image of this page: https://www.noon.com/egypt-ar/golden-wood-edp-100ml/N39185122A/p/?o=d55236b5f16d3c9d but i still have an error, I using beaurifaulSoup, but it give me none: That what i got: import requests from bs4 import BeautifulSoup im...
Scraping Produce image by BeautifulSoup
I'm trying to Scrap the product image of this page: https://www.noon.com/egypt-ar/golden-wood-edp-100ml/N39185122A/p/?o=d55236b5f16d3c9d but i still have an error, I using beaurifaulSoup, but it give me none: That what i got: import requests from bs4 import BeautifulSoup import time import json import re page_numbe...
[ "For me, the following selector works:\nproduct_image = Product_Details.select(\".swiper-wrapper .lazyload-wrapper div\")\nprint(product_image)\n\nFor the first 3 products, it prints\n[<div class=\"sc-8cbb8e24-2 eDXUdi\"><img alt=\"عطر جولدن وود EDP 100مل - v1666705361/N39185122A_1\" aria-hidden=\"true\" class=\"sc...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074379884_beautifulsoup_python_web_scraping.txt
Q: pytest pyproject.toml configuration to ignore a specific path Are there any ways to set a path to ignore in pyproject.toml like #pyproject.toml [tool.pytest.ini_options] ignore = ["path/to/test"] instead of using addopts: #pyproject.toml [tool.pytest.ini_options] addopts = "--ignore=path/to/test" A: Use the ...
pytest pyproject.toml configuration to ignore a specific path
Are there any ways to set a path to ignore in pyproject.toml like #pyproject.toml [tool.pytest.ini_options] ignore = ["path/to/test"] instead of using addopts: #pyproject.toml [tool.pytest.ini_options] addopts = "--ignore=path/to/test"
[ "Use the following in pyproject.toml\nnorecursedirs = [\n \"path/to/test/*\",\n]\n\n", "The list of configuration options you can add in the [tool.pytest.ini_options] (or pytest.ini) is documented in https://docs.pytest.org/en/7.1.x/reference/reference.html#configuration-options, which includes addopts, norecu...
[ 1, 1 ]
[]
[]
[ "pyproject.toml", "pytest", "python" ]
stackoverflow_0068287352_pyproject.toml_pytest_python.txt
Q: ValueError: list.remove(x): x not in list when removing strings in a list of a list I have a list of list : the sublist conatins strings. I would like to remove elements from this sublist if they are in a set of Stopword that I created. So I iterate through the sublist and If the string is in the set than I remove...
ValueError: list.remove(x): x not in list when removing strings in a list of a list
I have a list of list : the sublist conatins strings. I would like to remove elements from this sublist if they are in a set of Stopword that I created. So I iterate through the sublist and If the string is in the set than I remove it using .remove(). But I get the error that the word is not in the list which is incorr...
[ "You must remove the word inside the sublist not on the original list.\nstopwords = set([\"s\", \"a\", \"about\", \"above\" ])\nMM=[[\"s\",\"mam\"],[\"about\",\"645\"]]\n\nfor idx, i in enumerate(MM):\n for j in i:\n if j in stopwords:\n MM[idx].remove(j)\n\nOutput:\n[['mam'], ['645']]\n\n" ]
[ 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074391588_list_python.txt
Q: How to solve the total amount of seconds using python I am learning python as a novice and I was asked to solve the total of seconds in the problem. I was given the format but it still seems that I can not get a hand of it. it keeps telling me that I didn't get the minute and seconds part I tried this: def get_sec...
How to solve the total amount of seconds using python
I am learning python as a novice and I was asked to solve the total of seconds in the problem. I was given the format but it still seems that I can not get a hand of it. it keeps telling me that I didn't get the minute and seconds part I tried this: def get_seconds(hours, minutes, seconds): return 3600*hours + 60*min...
[ "Your function already does the job of multiplying hours by 3600 and minutes by 60. The point is for you to pass the hours, minutes, and seconds as separate arguments, like this:\namount_a = get_seconds(2, 30, 0) # 2 hours and 30 minutes\namount_b = get_seconds(0, 45, 15) # 45 minutes and 15 seconds\nresult = a...
[ 1, 0 ]
[]
[]
[ "coursera_api", "python" ]
stackoverflow_0074391605_coursera_api_python.txt
Q: How do I filter out subsets of a dataframe in python this is my dataframe import pandas as pd df = pd.DataFrame({'Date' : ['2014-03-27', '2014-03-28', '2014-03-31', '2014-04-01', '2014-04-02', '2014-04-03', '2014-04-04', '2014-04-07', '2014-04-07', '2014-04-07'], 'income': [1849.04, 1857.62, 187...
How do I filter out subsets of a dataframe in python
this is my dataframe import pandas as pd df = pd.DataFrame({'Date' : ['2014-03-27', '2014-03-28', '2014-03-31', '2014-04-01', '2014-04-02', '2014-04-03', '2014-04-04', '2014-04-07', '2014-04-07', '2014-04-07'], 'income': [1849.04, 1857.62, 1872.34, 1885.52, 1890.9, 1888.77, 1865.09, 1845.04, 1235.04,...
[ "# boolean filter on index, and then loc to filter the rows\ndf.loc[df.index < '2014-04-07']\n\n income\nDate \n2014-04-04 1865.09\n2014-04-03 1888.77\n2014-04-02 1890.90\n2014-04-01 1885.52\n2014-03-31 1872.34\n2014-03-28 1857.62\n2014-03-27 1849.04\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "python" ]
stackoverflow_0074391582_dataframe_python.txt
Q: Python library or tool to get bounding boxes in a searchable/selectable PDF, without using tesseract or any other OCR related solution I am unable to find a python script or library or a tool which can give me bounding boxes around the texts in a searchable/selectable PDF. All of the tools I found first convert t...
Python library or tool to get bounding boxes in a searchable/selectable PDF, without using tesseract or any other OCR related solution
I am unable to find a python script or library or a tool which can give me bounding boxes around the texts in a searchable/selectable PDF. All of the tools I found first convert the PDF to an image, either using GhostScript or some other tool, and then extract the bounding boxes using an OCR solution like Tesseract. B...
[ "When text is written inside a pdf by whatever means it has no boundary or box (can even be outside page related boxes) simply a design height and position:-\n{\n \"text\": {\n \"text\": \"Hello World!\",\n \"points\": 96 ,\n \"x\": 36 ,\n \"y\": 684\n }\n ...
[ 0 ]
[]
[]
[ "bounding_box", "computer_vision", "ocr", "pdf", "python" ]
stackoverflow_0074388691_bounding_box_computer_vision_ocr_pdf_python.txt
Q: Spyder IDE 5.3.3 (Python 3.8) execution of TCL script hangs in Windows 10 I have a python script that runs without problems when I run it from the Windows command shell or Visual Studio 2019. When I run it in the Spyder IDE, executing the TCL script hangs. I'm using the following to run the TCL script: subprocess....
Spyder IDE 5.3.3 (Python 3.8) execution of TCL script hangs in Windows 10
I have a python script that runs without problems when I run it from the Windows command shell or Visual Studio 2019. When I run it in the Spyder IDE, executing the TCL script hangs. I'm using the following to run the TCL script: subprocess.call("script.tcl")
[ "Is that script running with tclsh or wish? Only the former really works properly as a subprocess thing on Windows because tclsh is built as a console program and terminates when the end of the script is reached, whereas wish is built as a GUI program and does not (it instead runs the event loop until the last wind...
[ 1 ]
[]
[]
[ "python", "spyder", "tcl", "windows" ]
stackoverflow_0074391285_python_spyder_tcl_windows.txt
Q: How to convert a dictionary that is in string form into dictionary form in python? I have a string as this, and I want to convert it into dictionary. test= '{"age":59.0,"bp":70.0,"sg":1.01,"al":3.0,"su":0.0,"rbc":1.0,"ba":0.0,"bgr":76.0,"bu":186.0,"sc":15.0,"sod":135.0,"pot":7.6,"hemo":7.1,"pcv":22.0,"wbcc":3800.0...
How to convert a dictionary that is in string form into dictionary form in python?
I have a string as this, and I want to convert it into dictionary. test= '{"age":59.0,"bp":70.0,"sg":1.01,"al":3.0,"su":0.0,"rbc":1.0,"ba":0.0,"bgr":76.0,"bu":186.0,"sc":15.0,"sod":135.0,"pot":7.6,"hemo":7.1,"pcv":22.0,"wbcc":3800.0,"rbcc":2.1,"htn":1.0,"dm":0.0,"cad":0.0,"appet":0.0,"pe":1.0,"ane":1.0}' I tried dict(...
[ "Try using ast.literal_eval\nimport ast\n\nnew_dict = ast.literal_eval(test)\n\n", "Your string is in JSON format, so you can use the json module to turn it into a dict:\n>>> test = '{\"age\":59.0,\"bp\":70.0,\"sg\":1.01,\"al\":3.0,\"su\":0.0,\"rbc\":1.0,\"ba\":0.0,\"bgr\":76.0,\"bu\":186.0,\"sc\":15.0,\"sod\":13...
[ 3, 2 ]
[]
[]
[ "data_structures", "dictionary", "python", "python_3.x" ]
stackoverflow_0074391674_data_structures_dictionary_python_python_3.x.txt
Q: how to automate the htpasswd password entry in python scripts This is my python function that creates the htpasswd file and adds the username and password in it . def __adduser(self, passfile, username): command=["htpasswd", "-c", passfile, username] execute=subprocess.Popen(command, stdout=subpr...
how to automate the htpasswd password entry in python scripts
This is my python function that creates the htpasswd file and adds the username and password in it . def __adduser(self, passfile, username): command=["htpasswd", "-c", passfile, username] execute=subprocess.Popen(command, stdout=subprocess.PIPE) result=execute.communicate() if execute...
[ "htpasswd has an -i option:\n\nRead the password from stdin without verification (for script usage).\n\nSo:\ndef __adduser(self, passfile, username, password):\n command = [\"htpasswd\", \"-i\", \"-c\", passfile, username]\n execute = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n ...
[ 1, 0 ]
[]
[]
[ ".htpasswd", "python", "subprocess" ]
stackoverflow_0045833403_.htpasswd_python_subprocess.txt
Q: Firestore Python SDK - count() aggregation I'm using Firebase Firestore in my Python project (with their official Python SDK) and having trouble performing count() aggregation. This funciton is supported according to their docs. However, they do not provide Python example ( they do in other parts of documentation ...
Firestore Python SDK - count() aggregation
I'm using Firebase Firestore in my Python project (with their official Python SDK) and having trouble performing count() aggregation. This funciton is supported according to their docs. However, they do not provide Python example ( they do in other parts of documentation ). I tried to play with it in Python console, tr...
[ "Firebase Admin Python SDK doesn't support that query yet. You can still use the runAggregationQuery REST API meanwhile. The Google Cloud Firestore Python SDK has Aggregation result types available from v2.7.0+ so it should be available in Admin SDK soon.\n" ]
[ 2 ]
[]
[]
[ "aggregate_functions", "firebase_admin", "google_cloud_firestore", "python" ]
stackoverflow_0074384590_aggregate_functions_firebase_admin_google_cloud_firestore_python.txt
Q: How can I check is there any number in series and count any number(float,integer etc)? Here is my code: I check number with isnumeric() function but it only return integer number is there any other way to count any number(it doesn't matter if it is integer or float) in series? def check_number(item): try: ...
How can I check is there any number in series and count any number(float,integer etc)?
Here is my code: I check number with isnumeric() function but it only return integer number is there any other way to count any number(it doesn't matter if it is integer or float) in series? def check_number(item): try: num1=float(item) except: return 'Not number' series=input('Enter a ...
[ "It looks like you haven't returned anything in your function. This change should make your program work:\ndef check_number(item):\n try:\n return float(item)\n except:\n return 'Not number'\n\nI have just replaced your variable assignment with a return statement.\n" ]
[ -2 ]
[]
[]
[ "python" ]
stackoverflow_0074391548_python.txt
Q: Writing phenaki video to file: Expected numpy array with ndim `3` but got `4` I'm trying to write the output of the Phenaki make_video to an mp4 file. I'm using this Phenaki implementation from github https://github.com/lucidrains/phenaki-pytorch/search?q=make_video phenaki = Phenaki( cvivit = cvivit, mask...
Writing phenaki video to file: Expected numpy array with ndim `3` but got `4`
I'm trying to write the output of the Phenaki make_video to an mp4 file. I'm using this Phenaki implementation from github https://github.com/lucidrains/phenaki-pytorch/search?q=make_video phenaki = Phenaki( cvivit = cvivit, maskgit = maskgit ) entire_video, scenes = make_video(phenaki, texts = [ 'blah bl...
[ "According to write_video documentation, video_array argument format is \"tensor containing the individual frames, as a uint8 tensor in [T, H, W, C] format\".\nThe dimensions of entire_video is (1, 3, 45, 256, 128), so there are 5 dimensions instead of 4 dimensions.\nThe exception says ndim 3 but got 4 (not 4 and 5...
[ 0 ]
[]
[]
[ "generative", "pyav", "python", "pytorch", "torchvision" ]
stackoverflow_0074366397_generative_pyav_python_pytorch_torchvision.txt
Q: PySide2 main window not working after pop-up I am building a graphical interface for an application using PySide2. My main window is a QMainWindow and I am trying to open a pop-up window, which is a QDialog, whenever a specific action is performed on the main window. The pop-up opens perfectly fine. However, after...
PySide2 main window not working after pop-up
I am building a graphical interface for an application using PySide2. My main window is a QMainWindow and I am trying to open a pop-up window, which is a QDialog, whenever a specific action is performed on the main window. The pop-up opens perfectly fine. However, after it is open, the main window is no longer responsi...
[ "TL;DR\nDo not overwrite self.ui.\nExplanation\nHow uic composition works\nOne of the common ways of properly using pyuic generated files is to use composition (as opposed to multiple inheritance):\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QDialog\nfrom ui_mainWindow import Ui_MainWindow\n\nclass MyWi...
[ 0 ]
[]
[]
[ "pyqt5", "pyside2", "python", "qt5" ]
stackoverflow_0074379650_pyqt5_pyside2_python_qt5.txt
Q: Best method to try and decipher this cipher text? This is an example of a portion of the cipher text I need to decipher: gsv wzlf zaw nbagsf zev gezivoovef bu vgveargl, qhfg orpv gsv lvzef gszg xbnv zaw tb. ube gsbfv jsb czff gsvre orivf zuobzg ba ybzgf, be uzxv bow ztv ovzwrat sbefvf grtsg yl gsv yerwov, gsvre q...
Best method to try and decipher this cipher text?
This is an example of a portion of the cipher text I need to decipher: gsv wzlf zaw nbagsf zev gezivoovef bu vgveargl, qhfg orpv gsv lvzef gszg xbnv zaw tb. ube gsbfv jsb czff gsvre orivf zuobzg ba ybzgf, be uzxv bow ztv ovzwrat sbefvf grtsg yl gsv yerwov, gsvre qbheavlrat rf oruv, gsvre qbheavlrat rf sbnv. zaw nzal ...
[ "The letters are still formatted as if they were words, the punctuation gives it away. So pretty much each letter seems to just be substituted for another.\nThis is a mono-alphabetic cipher\nUsing the most frequent letters you worked out, you can try match it against the average usage of each word of the alphabet o...
[ 2 ]
[]
[]
[ "caesar_cipher", "encryption", "python" ]
stackoverflow_0074391635_caesar_cipher_encryption_python.txt
Q: my OpenCV color detection (red) program doesn't work. it detects all colors instead of red import numpy as np import cv2 img=cv2.imread('image.jpg') hsvFrame=cv2.cvtColor(img ,cv2.COLOR_BGR2HSV) #SET RANGE FOR RED #DEFINE MASk red_lower=np.array([0,0,204],np.uint8) red_upper=np.array([0,0,255],np.uint8) red_ma...
my OpenCV color detection (red) program doesn't work. it detects all colors instead of red
import numpy as np import cv2 img=cv2.imread('image.jpg') hsvFrame=cv2.cvtColor(img ,cv2.COLOR_BGR2HSV) #SET RANGE FOR RED #DEFINE MASk red_lower=np.array([0,0,204],np.uint8) red_upper=np.array([0,0,255],np.uint8) red_mask=cv2.inRange(hsvFrame,red_lower,red_upper) kernel=np.ones((5,5),"uint8") red_mask=cv2.dilate(r...
[ "Why are you converting your image to HSV? There appears to be a mismatch between the color range you are trying to match (which appears to be specified in BGR color space) vs the color space your image is in (HSV). I suspect that is the source of your issue.\n" ]
[ 0 ]
[]
[]
[ "color_detection", "numpy", "opencv", "python" ]
stackoverflow_0074391725_color_detection_numpy_opencv_python.txt
Q: Why is the dictionary not updating outside the definition even if i've returned the dictionary? So the this dictionary is basically from a txt file and I formatted in order to have the same format as its supposed to have in order for my other definitions to work. The problem I'm having is that the for the loadInve...
Why is the dictionary not updating outside the definition even if i've returned the dictionary?
So the this dictionary is basically from a txt file and I formatted in order to have the same format as its supposed to have in order for my other definitions to work. The problem I'm having is that the for the loadInventory function, dictionary works inside the function but outside even though I've returned the dictio...
[ "Your code creates new dictionaries at three different points:\n # this looks like it never gets used for anything\n dicty = {} \n\n # this overwrites the \"dictionary\" passed to loadInventory()\n dictionary= dict((value[0], value[1:]) for value in final)\n\n # this creates a new dictionary to pass...
[ 1, 0 ]
[]
[]
[ "definition", "dictionary", "python", "python_3.x" ]
stackoverflow_0074391782_definition_dictionary_python_python_3.x.txt
Q: Python: can an object have an object as a "default" representation? I am just getting started with OOP, so I apologise in advance if my question is as obvious as 2+2. :) Basically I created a class that adds attributes and methods to a panda data frame. That's because I am sometimes looking to do complex but repet...
Python: can an object have an object as a "default" representation?
I am just getting started with OOP, so I apologise in advance if my question is as obvious as 2+2. :) Basically I created a class that adds attributes and methods to a panda data frame. That's because I am sometimes looking to do complex but repetitive tasks like merging with a bunch of other tables, dropping duplicate...
[ "In your MySupperTable class, do:\nclass MySupperTable:\n\n # ... other stuff in the class\n\n def __str__(self) -> str:\n return str(self.original_dataframe)\n\nThat will make it so that when a MySupperTable is converted to a str, it will convert its original_dataframe to a str and return that.\n", ...
[ 5, 1 ]
[]
[]
[ "class", "methods", "oop", "python" ]
stackoverflow_0074391865_class_methods_oop_python.txt
Q: Why is my function not working in Python? I defined the list, but it says I haven't def get_student_list(): iStr = "" stdlist = [] x = 1 while not iStr == "quit": iStr = input(f'Please enter a new student name, ("quit" if no more student)') if not iStr == "quit": stdlist...
Why is my function not working in Python? I defined the list, but it says I haven't
def get_student_list(): iStr = "" stdlist = [] x = 1 while not iStr == "quit": iStr = input(f'Please enter a new student name, ("quit" if no more student)') if not iStr == "quit": stdlist.append(iStr) elif iStr == "": print("Empty student name is not allow...
[ "your list is defined in the function and your print is global so it won't work ^^\nyou can either define stdlist as a global (outside your function) or indent your print\n", "The list stdlist is local to the function get_student_list(). Your last print does not have access to it.\nTo fix:\ndef get_student_list()...
[ 1, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074391760_python_python_3.x.txt
Q: How do I activate a virtualenv inside PyCharm's terminal? I've set up PyCharm, created my virtualenv (either through the virtual env command, or directly in PyCharm) and activated that environment as my Interpreter. Everything is working just fine. However, if I open a terminal using "Tools, Open Terminal", the sh...
How do I activate a virtualenv inside PyCharm's terminal?
I've set up PyCharm, created my virtualenv (either through the virtual env command, or directly in PyCharm) and activated that environment as my Interpreter. Everything is working just fine. However, if I open a terminal using "Tools, Open Terminal", the shell prompt supplied is not using the virtual env; I still have ...
[ "Edit:\nAccording to https://www.jetbrains.com/pycharm/whatsnew/#v2016-3-venv-in-terminal, PyCharm 2016.3 (released Nov 2016) has virutalenv support for terminals out of the box\n\nAuto virtualenv is supported for bash, zsh, fish, and Windows cmd. You\ncan customize your shell preference in Settings (Preferences) |...
[ 114, 60, 43, 28, 9, 8, 7, 7, 6, 5, 3, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 ]
[ "Windows Simple and Easy Solution:\n\nIn Pycharm inside the Projects menu on the left there will be folders.\nFind the Scripts folder\nInside there you'll find activate.bat\nRight click on activate.bat\nCopy/Path Reference\nSelect Absolute Path\nFind the Terminal tab located in the middle at the bottom of Pycharm.\...
[ -1, -2 ]
[ "django", "pycharm", "python", "shell", "virtualenv" ]
stackoverflow_0022288569_django_pycharm_python_shell_virtualenv.txt
Q: Alembic doesn't recognize False default value While maintaining a SQLAlchemy data model and utilizing alembic for version control, the following code change I made resulted in an empty revision: some_column = Column(Boolean, nullable=False, default=False) While previously it was: some_column = Column(Boolean, nul...
Alembic doesn't recognize False default value
While maintaining a SQLAlchemy data model and utilizing alembic for version control, the following code change I made resulted in an empty revision: some_column = Column(Boolean, nullable=False, default=False) While previously it was: some_column = Column(Boolean, nullable=False) So adding a default value produces no...
[ "To do this automatically you have to turn on a setting to detect server default changes.\nIn your env.py, for the context.configure calls (online and offline migrations, so in 2 places), add a compare_server_default=True kwarg.\nIt is probably safer to just put in the alter_column yourself as well as definitely us...
[ 6, 1 ]
[]
[]
[ "alembic", "database", "postgresql", "python", "sqlalchemy" ]
stackoverflow_0062212263_alembic_database_postgresql_python_sqlalchemy.txt
Q: Python: Is there a way to join threads while using semaphores Background: I have an inventory application that scrapes data from our various IT resources (VMware, storage, backups, etc...) We have a vCenter that has over 2000 VMs registered to it. I have code to go in and pull details for each VM in its own threa...
Python: Is there a way to join threads while using semaphores
Background: I have an inventory application that scrapes data from our various IT resources (VMware, storage, backups, etc...) We have a vCenter that has over 2000 VMs registered to it. I have code to go in and pull details for each VM in its own thread to parallelize the collections. I have them joined to a parent th...
[ "I had to switch this to a consumer/producer implementation utilizing a queue. That allowed me to limit the number of collections that would be kicked off simultaneously.\n" ]
[ 0 ]
[]
[]
[ "python", "python_multithreading", "pyvmomi", "semaphore" ]
stackoverflow_0073531352_python_python_multithreading_pyvmomi_semaphore.txt
Q: Joining traces in plotly I am trying to make a shape conformed by a few traces, many of which are not continuous. By the moment, I've managed to create this shape with different traces. I've tried calling them the same name, but this didn't work. For instance: import plotly.graph_objects as go fig = go.Figure(go.S...
Joining traces in plotly
I am trying to make a shape conformed by a few traces, many of which are not continuous. By the moment, I've managed to create this shape with different traces. I've tried calling them the same name, but this didn't work. For instance: import plotly.graph_objects as go fig = go.Figure(go.Scatter(x=[1,2,0], y=[3,1,1],na...
[ "In Plotly, if you have two independent segments belong to the same shape, and you want to plot each one without any connection, you must do that with 2 traces but you can color the segments of the same shape with the same color and use legendgroup to control all segment under the same shape:\nimport plotly.graph_o...
[ 1 ]
[]
[]
[ "plotly", "plotly_python", "python" ]
stackoverflow_0074389153_plotly_plotly_python_python.txt
Q: How to add column names to pipe delimited file of specific format I have a file that contains user data NS|Mrs|Jane|0001|07061980|random co|AS|001|4034|2/342 PT MMMMMY I could do this to write colnames , but - colnames = [name,code,DOB... ] colnames = [i+'|' for i in colnames] # then write this header to same txt...
How to add column names to pipe delimited file of specific format
I have a file that contains user data NS|Mrs|Jane|0001|07061980|random co|AS|001|4034|2/342 PT MMMMMY I could do this to write colnames , but - colnames = [name,code,DOB... ] colnames = [i+'|' for i in colnames] # then write this header to same txt file But the problem is in the file is that user segments can occur a...
[ "I would first create a clean data file.\nwith open('myfile.txt') as f_in:\n with open('output.txt', 'w') as f_out:\n #declare output order\n f_out.write('Title|Name|code|DOB|company|state_code|house_num|pincode|address\\n')\n for line in f_in.readlines():\n if line.startswith('NS...
[ 0 ]
[]
[]
[ "dataframe", "dictionary", "pandas", "python", "string" ]
stackoverflow_0074361767_dataframe_dictionary_pandas_python_string.txt
Q: Struggling with plt.annotate command, unsure of syntax for first 'label' argument x_G = np.array([12, 210, 80, 165, 150, 272, 10, 7.5]) y_G = np.array([20.0, 40.0, 60.0, 60.0, 60, 80, 8, 20]) names_G = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] for x, y in zip (x_G, y_G): plt.annotate(names_G, (x, y), textcoord...
Struggling with plt.annotate command, unsure of syntax for first 'label' argument
x_G = np.array([12, 210, 80, 165, 150, 272, 10, 7.5]) y_G = np.array([20.0, 40.0, 60.0, 60.0, 60, 80, 8, 20]) names_G = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] for x, y in zip (x_G, y_G): plt.annotate(names_G, (x, y), textcoords='offset points', xytext=(0, 10), ha='center') So I know the first argument, names_G ...
[ "There isn't any problem in including the text in the zip:\nfor x, y, t in zip (x_G, y_G, names_G):\n plt.annotate(t, (x, y), textcoords = 'offset points', xytext=(0,10), ha='center')\n\nAs an alternative to defining your list of names manually, you may want to get a list of characters:\nimport string\n\nnames =...
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074391733_matplotlib_python.txt
Q: OverflowError: long int too large to convert to float in python I tried to calculate poisson distribution in python as below: p = math.pow(3,idx) depart = math.exp(-3) * p depart = depart / math.factorial(idx) idx ranges from 0 But I got OverflowError: long int too large to convert to float I tried to convert de...
OverflowError: long int too large to convert to float in python
I tried to calculate poisson distribution in python as below: p = math.pow(3,idx) depart = math.exp(-3) * p depart = depart / math.factorial(idx) idx ranges from 0 But I got OverflowError: long int too large to convert to float I tried to convert depart to float but no results.
[ "Factorials get large real fast:\n>>> math.factorial(170)\n72574156153079989673967282111292631147169916812964513765435777989005618434017061578523507492426174595114909912378385207766660225654427530253289007732075109024004302800582956039666125996582571043985582942575689663134396122625710949468067112055688804571933402...
[ 42, 7, 4, 2, 0 ]
[]
[]
[ "factorial", "overflow", "python" ]
stackoverflow_0016174399_factorial_overflow_python.txt
Q: How can I get the name of the script calling the function in python? I know that __file__ contains the filename containing the code, but is there a way to get the name of the script/file that's calling the function? If I have a file named filenametest_b.py: def printFilename(): print(__file__) And I import t...
How can I get the name of the script calling the function in python?
I know that __file__ contains the filename containing the code, but is there a way to get the name of the script/file that's calling the function? If I have a file named filenametest_b.py: def printFilename(): print(__file__) And I import the function in filenametest_a.py: from filenametest_b import * printFilen...
[ "You could print sys.argv[0] to get the script filename.\nTo get the filename of the caller, you need to use the sys._getframe() function to get the calling frame, then you can retrieve the filename from that:\nimport inspect, sys\n\nprint inspect.getsourcefile(sys, sys._getframe(1))\n\n", "Asked a bit too soon, ...
[ 4, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0013981500_python.txt
Q: PySide6 Exclude Folders from QTreeView I have an application where i need to display 2 different TreeViews. One for showing the folders (folderView) and the other will display the Files (fileView) inside the selected folder from the folderView. The following Code works fine but i am having a strange issue: in the ...
PySide6 Exclude Folders from QTreeView
I have an application where i need to display 2 different TreeViews. One for showing the folders (folderView) and the other will display the Files (fileView) inside the selected folder from the folderView. The following Code works fine but i am having a strange issue: in the screen shot below, if i click on the bin fol...
[ "This is a \"bug\" probably caused by the asynchronous nature of QFileSystemModel, which uses threading to fill the model and delays calls for the model structure updates.\nIt seems that it's also been already reported as QTBUG-93634, but it has got no attention yet.\nA possible workaround is to \"reset\" the filte...
[ 0 ]
[]
[]
[ "pyside6", "python", "qtreeview" ]
stackoverflow_0074391441_pyside6_python_qtreeview.txt
Q: What is print(f"...") I am reading through a python script that takes an input of XML files and outputs an XML file. However, I do not understand the printing syntax. Can someone please explain what f in print(f"...") does? args = parser.parser_args() print(f"Input directory: {args.input_directory}") print(f"Outp...
What is print(f"...")
I am reading through a python script that takes an input of XML files and outputs an XML file. However, I do not understand the printing syntax. Can someone please explain what f in print(f"...") does? args = parser.parser_args() print(f"Input directory: {args.input_directory}") print(f"Output directory: {args.output_...
[ "The f means Formatted string literals and it's new in Python 3.6.\n\n\nA formatted string literal or f-string is a string literal that is\n prefixed with 'f' or 'F'. These strings may contain replacement\n fields, which are expressions delimited by curly braces {}. While\n other string literals always have a c...
[ 104, 37, 17, 3, 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0057150426_python.txt
Q: How can I check a string for two letters or more? I am pulling data from a table that changes often using Python - and the method I am using is not ideal. What I would like to have is a method to pull all strings that contain only one letter and leave out anything that is 2 or more. An example of data I might get:...
How can I check a string for two letters or more?
I am pulling data from a table that changes often using Python - and the method I am using is not ideal. What I would like to have is a method to pull all strings that contain only one letter and leave out anything that is 2 or more. An example of data I might get: 115 19A6 HYS8 568 In this example, I would like to pu...
[ "Try this:\nstring_list = [\"115\", \"19A6\", \"HYS8\", \"568\"]\noutput_list = []\n\nfor item in string_list: # goes through the string list\n letter_counter = 0 \n for letter in item: # goes through the letters of one string\n if not letter.isdigit(): # checks if the letter is a digt\n let...
[ 0, 0, 0, 0 ]
[]
[]
[ "digits", "filter", "letter", "python", "string" ]
stackoverflow_0074391013_digits_filter_letter_python_string.txt
Q: How do I only get the latest input from tkinter Text widget? I need to get only the latest input from my text widget, and then append that character to a list. I am using Text.get(1.0,'end-1c') , and it does not work because the loop constantly gets all the input, instead of only getting the latest input when ther...
How do I only get the latest input from tkinter Text widget?
I need to get only the latest input from my text widget, and then append that character to a list. I am using Text.get(1.0,'end-1c') , and it does not work because the loop constantly gets all the input, instead of only getting the latest input when there is a new latest input. def main_screen(): start_time=time.ti...
[ "You can bind the text_area with a <KeyPress> event, but you need to pass the list typed_text as an argument so you can append the presses.\nSo you should do something like this:\ntext_area.bind(\"<KeyPress>\", lambda _: getKey(_, typed_text))\n while True:\n tk.update()\n time_elapsed = max(time.t...
[ 1, 0 ]
[]
[]
[ "python", "tkinter", "user_interface" ]
stackoverflow_0074390997_python_tkinter_user_interface.txt
Q: How to check account API limit when using sendgrid python API? How to check account API limit when using sendgrid python API? I need to know the limits and according will tweak my program to avoid hitting the API limits. Probably the limit is 600 calls per minute. But I want to know the python api endpoint which ...
How to check account API limit when using sendgrid python API?
How to check account API limit when using sendgrid python API? I need to know the limits and according will tweak my program to avoid hitting the API limits. Probably the limit is 600 calls per minute. But I want to know the python api endpoint which will retrieve that. The only documentation I found is: https://send...
[ "Here is what I use to get usage rates\n\nLOGIN = # paste your login \nPASSWORD = # paste your password g\nsg = SendGridAPIClient(PASSWORD, impersonate_subuser = \"\")\nresponse = sg.client.user.credits.get() today = date.today()\nddate = today.strftime(\"%Y-%m-%d\") \nd = datetime.today() - timedelta(days=n)\nddat...
[ 0 ]
[]
[]
[ "python", "sendgrid" ]
stackoverflow_0051241363_python_sendgrid.txt
Q: Python program finishes before GDown has finished downloading I have an array of google drive links: links = ["https://drive.google.com/open?id=...", "https://drive.google.com/open?id=..."] To download each file in the array I loop through each one to download: for link in links: try: gdown.download(li...
Python program finishes before GDown has finished downloading
I have an array of google drive links: links = ["https://drive.google.com/open?id=...", "https://drive.google.com/open?id=..."] To download each file in the array I loop through each one to download: for link in links: try: gdown.download(link, fullfilename, quiet=False) except (ValueError, IOError, Run...
[ "Download a file stored on Google Drive\nFrom the way your code is trying to run the array, you are missing the parameters to log data if the file has been downloaded or the percentage of the file. This could be the reason why your code just reads the download request but does not verify any progress itself.\nAs su...
[ 0 ]
[]
[]
[ "download", "google_drive_api", "python", "python_3.x" ]
stackoverflow_0074390985_download_google_drive_api_python_python_3.x.txt
Q: Finding the midpoint of tuple of any length in python I need to take a tuple of any length and preforming an operation to return the midpoint. However, I need to function to work with a tuple of any length so I'm not sure how to go about it. def findMidpoint(P: tuple, Q: tuple) -> tuple: user_input1 = input('...
Finding the midpoint of tuple of any length in python
I need to take a tuple of any length and preforming an operation to return the midpoint. However, I need to function to work with a tuple of any length so I'm not sure how to go about it. def findMidpoint(P: tuple, Q: tuple) -> tuple: user_input1 = input('Enter space-separated integers: ') P = tuple(int(item) ...
[]
[]
[ "Okay, taking some liberties here with what you're asking, but assuming what you want is to find the midpoint of any two points in an N-dimensional space, you can average the value of each point axis-wise. For example:\nP = (px, py)\nQ = (qx, qy)\n\nmidpoint = ( (px + qx)*0.5, (py + qy)*0.5 ) \n\nObviously, for mor...
[ -1 ]
[ "function", "python", "tuples", "variable_length" ]
stackoverflow_0074391314_function_python_tuples_variable_length.txt
Q: Warning for input shape in LSTM model I have timeseries data of electricity consumption per hour with length (17544, 1) in the following format: [[17.6] [38.2] [39.4] ... [46. ] [44. ] [40.2]] My goal is to use as input the last 7 days of data, namely 24*7=168 and predict the next 24 hours of electricity co...
Warning for input shape in LSTM model
I have timeseries data of electricity consumption per hour with length (17544, 1) in the following format: [[17.6] [38.2] [39.4] ... [46. ] [44. ] [40.2]] My goal is to use as input the last 7 days of data, namely 24*7=168 and predict the next 24 hours of electricity consumption. I am using the following script ...
[ "In Keras LSTMs take a 3D input with shape [batch, timesteps, feature]. In Keras batch is generally shown as None since it can vary (you can see this in the warning). Your timesteps is 168 and feature is 1 since the your only feature is a value. I think the problem is you give an input of (168,1) which doesn't have...
[ 1 ]
[]
[]
[ "deep_learning", "keras", "lstm", "numpy", "python" ]
stackoverflow_0074360684_deep_learning_keras_lstm_numpy_python.txt