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: How to plot a histogram with specific ranges? I have the following Dataframe; items1 = ['one', 'two'] items2 = ['JR Sagami Line','JR Tsurumi Line','JR Sagami Line','JR Tsurumi Line','JR Ome Line'] items3 = ['tokyo','shizuoka','saitma','oosaka'] dict_a = { 'log_timestamp_jst': np.random.randint(100, size=100), ...
How to plot a histogram with specific ranges?
I have the following Dataframe; items1 = ['one', 'two'] items2 = ['JR Sagami Line','JR Tsurumi Line','JR Sagami Line','JR Tsurumi Line','JR Ome Line'] items3 = ['tokyo','shizuoka','saitma','oosaka'] dict_a = { 'log_timestamp_jst': np.random.randint(100, size=100), 'dt': pd.date_range('2022-5-01', periods=100, fr...
[ "value_counts will give you how many times an ads has been contacted. To show the frequency (e.g. 5 ads were seen 0 time, 7 ads were seen 1 - 2 times, etc.), you need to bin them and count again.\nUse pd.cut to allow them to bins:\ns = df.loc[df[\"brand_id\"] == \"JR Tsurumi Line\", \"uid\"].value_counts()\nax = (\...
[ 0 ]
[]
[]
[ "grouping", "histogram", "pandas", "python" ]
stackoverflow_0074171736_grouping_histogram_pandas_python.txt
Q: How to display python print to flask I want to display what I am printing to the console. ex. print('Hello World') once its printing to the terminal. How can I also display that on my page. A: I'm a little confused, but I don't believe it's possible to get a text from the console in flask. The best way to do wha...
How to display python print to flask
I want to display what I am printing to the console. ex. print('Hello World') once its printing to the terminal. How can I also display that on my page.
[ "I'm a little confused, but I don't believe it's possible to get a text from the console in flask. The best way to do what you're trying to do is to collect information from flask and import it into your HTML file.\nanything you're printing to the console should be turned into a variable, so flask can send it to th...
[ 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074166179_flask_python.txt
Q: adding array into multiple column in python I have an array that I want to append as multiple columns what I am getting what I want pages = [1,2,3,4,5,6] with open(nlnewsdata, 'a',newline='') as nlnews: wr = csv.writer(nlnews, quoting=csv.QUOTE_ALL) wr.writerow(['Daily Journal (Park Hills, MO)',"Jan","2003",result...
adding array into multiple column in python
I have an array that I want to append as multiple columns what I am getting what I want pages = [1,2,3,4,5,6] with open(nlnewsdata, 'a',newline='') as nlnews: wr = csv.writer(nlnews, quoting=csv.QUOTE_ALL) wr.writerow(['Daily Journal (Park Hills, MO)',"Jan","2003",result,pages]) now the output Im expecting is like thi...
[ "You can use * to unpack the list\nwr.writerow(['Daily Journal (Park Hills, MO)',\"Jan\",\"2003\",result,*pages])\n\n" ]
[ 0 ]
[]
[]
[ "csv", "export_to_csv", "python" ]
stackoverflow_0074172224_csv_export_to_csv_python.txt
Q: Django Error: 'WSGIRequest' object has no attribute 'order' I'm trying to render out the get_cart_total to the email template I'm working on, which gets sent when the success view is triggered and the boolean is True, currently it gets an error message saying 'WSGIRequest' object has no attribute 'order', what's c...
Django Error: 'WSGIRequest' object has no attribute 'order'
I'm trying to render out the get_cart_total to the email template I'm working on, which gets sent when the success view is triggered and the boolean is True, currently it gets an error message saying 'WSGIRequest' object has no attribute 'order', what's causing this and how do I fix it? Model class Customer(models.Mode...
[ "You are trying to access order from request. TRy to remove request ?\ndef success(request):\n if order.complete == True:\n email = request.user.customer.email\n \n #error\n cart_total = order.get_cart_total\n \n html_message = render_to_string('check/emails/test.html', ...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074170901_django_python.txt
Q: Problem with PdfFileWriter of PyPDF2: addPage() missing 1 required positional argument: 'page' I need to write in a new PDF the content of each page. In 'curr_page' i am saving the PageObject of each Page, but when i try to write it in a new one i receive the error of that "addPage needs an argument". But i am giv...
Problem with PdfFileWriter of PyPDF2: addPage() missing 1 required positional argument: 'page'
I need to write in a new PDF the content of each page. In 'curr_page' i am saving the PageObject of each Page, but when i try to write it in a new one i receive the error of that "addPage needs an argument". But i am giving it the argument, which should be an PageObject. Some thoughts? pdf = PdfFileReader("suenios_luci...
[ "Add ( ) to the PdfFileWriter:\npdf_writer = PdfFileWriter()\n\n" ]
[ 0 ]
[]
[]
[ "pdf_reader", "pdf_writer", "pypdf", "python" ]
stackoverflow_0071807443_pdf_reader_pdf_writer_pypdf_python.txt
Q: Deleting Row in Dataframe and renaming columns I am trying to delete the first row of the below dataframe and column 0 so that the first row, column 0 begins with 'Stats' and column 1 is then headed with 'Team Basic'. However all of my code has resulted in the removal of the 2nd row. For example, the below code k...
Deleting Row in Dataframe and renaming columns
I am trying to delete the first row of the below dataframe and column 0 so that the first row, column 0 begins with 'Stats' and column 1 is then headed with 'Team Basic'. However all of my code has resulted in the removal of the 2nd row. For example, the below code keeps the row with the random '14' in it... away_basi...
[ "I made the dataframe data as follows:\n 0 1 2\n0 NaN NaN 14\n1 aaa bbb ccc\n2 a 1 0\n3 b 2 0\n4 c 3 0\n5 d 4 0\n6 e 5 0\n7 f 6 0\n\nApplied away_basic_teamtotals_df.index != 1 masking, which returned True for all rows except the row with index ...
[ 0 ]
[]
[]
[ "dataframe", "delete_row", "python" ]
stackoverflow_0074133287_dataframe_delete_row_python.txt
Q: Get Revit Link Instance using Python Im new to the Revit API. I can get the Revit link instance using C# with the code below. Element e = doc.GetElement(r); if (e is RevitLinkInstance) { //Get revit link instance RevitLinkInstance linkInstance = e as RevitLinkInstance; LinkedDocument = linkInstance.Ge...
Get Revit Link Instance using Python
Im new to the Revit API. I can get the Revit link instance using C# with the code below. Element e = doc.GetElement(r); if (e is RevitLinkInstance) { //Get revit link instance RevitLinkInstance linkInstance = e as RevitLinkInstance; LinkedDocument = linkInstance.GetLinkDocument(); //Do something } Ho...
[ "Your C# sample statement e as RevitLinkInstance performs a .NET cast. Hence, you can answer this question by searching the Internet for .net cast python, leading, e.g., to the question and answer can you typecast a .NET object in IronPython? The suggestion given there is to use\nimport clr\nconvertedObject = clr.C...
[ 2 ]
[]
[]
[ "python", "revit_api", "revitpythonshell" ]
stackoverflow_0074164437_python_revit_api_revitpythonshell.txt
Q: Syntax error when running code on vscode terminal msg = ("HI") print(msg) Output in Terminal PS C:\Users\Yumil\OneDrive\Desktop\Work\NewProjects> & C:/Users/Yumil/AppData/Local/Microsoft/WindowsApps/python3.10.exe Python 3.10.8 (tags/v3.10.8:aaaf517, Oct 11 2022, 16:50:30) [MSC v.1933 64 bit (AMD64)] on win32 Typ...
Syntax error when running code on vscode terminal
msg = ("HI") print(msg) Output in Terminal PS C:\Users\Yumil\OneDrive\Desktop\Work\NewProjects> & C:/Users/Yumil/AppData/Local/Microsoft/WindowsApps/python3.10.exe Python 3.10.8 (tags/v3.10.8:aaaf517, Oct 11 2022, 16:50:30) [MSC v.1933 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more ...
[ "You don't need to type anything in the terminal window.\nClose it, and right click on the file/editor to run the complete code as a file.\nAlternatively, type exit to get out of the Python REPL, then simply remove the starting & character from the command\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074172344_python.txt
Q: Statsmodels OLS "Shapes not aligned" Error (Using Built-In Dataset) I'm trying to practice basic modeling in Python. I am trying to create an OLS model using the OLS function in the statsmodels library, and I'm using a built-in dataset from the statsmodels library as well. Everything runs fine when splitting the d...
Statsmodels OLS "Shapes not aligned" Error (Using Built-In Dataset)
I'm trying to practice basic modeling in Python. I am trying to create an OLS model using the OLS function in the statsmodels library, and I'm using a built-in dataset from the statsmodels library as well. Everything runs fine when splitting the dataset into training and testing data, training the model, etc until I tr...
[ "AlexK added a link to a post that helped. Essentially all I added to the predictions = model.predict(test_x) line was a parameter that specified what parameters to use based on the results from the model.fit() line. In other words, the last line now looks like this:\npredictions = model.predict(results.params, tes...
[ 0 ]
[]
[]
[ "least_squares", "python", "statsmodels" ]
stackoverflow_0074168827_least_squares_python_statsmodels.txt
Q: Selenium + Python opening chrome with session password I'm trying to open chrome browser with password session in python3 and Selenium Here is my code : from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service options = Options(); o...
Selenium + Python opening chrome with session password
I'm trying to open chrome browser with password session in python3 and Selenium Here is my code : from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service options = Options(); options.add_argument(r"--user-data-dir=/home/username/.config...
[ "You're using linux, try undetected chromedriver as webdriver\n" ]
[ 0 ]
[]
[]
[ "python", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0071913671_python_selenium_chromedriver_selenium_webdriver.txt
Q: Pytorch: IndexError: index out of range in self. How to solve? This training code is based on the run_glue.py script found here: # Set the seed value all over the place to make this reproducible. seed_val = 42 random.seed(seed_val) np.random.seed(seed_val) torch.manual_seed(seed_val) torch.cuda.manual_seed_all(se...
Pytorch: IndexError: index out of range in self. How to solve?
This training code is based on the run_glue.py script found here: # Set the seed value all over the place to make this reproducible. seed_val = 42 random.seed(seed_val) np.random.seed(seed_val) torch.manual_seed(seed_val) torch.cuda.manual_seed_all(seed_val) # Store the average loss after each epoch so we can plot th...
[ "I think you have messed up with input dimension declared torch.nn.Embedding and with your input. torch.nn.Embedding is a simple lookup table that stores embeddings of a fixed dictionary and size.\nAny input less than zero or more than declared input dimension raise this error.\nCompare your input and the dimension...
[ 11, 1, 0, 0, 0 ]
[]
[]
[ "bert_language_model", "python", "pytorch" ]
stackoverflow_0062081155_bert_language_model_python_pytorch.txt
Q: Sum the Even Values of a String In this Exercise, you will sum the value of a string. Complete the recursive function def sumString(st): This function accepts a string as a parameter and sums the ASCII value for each character whose ASCII value is an even number. I know how to sum all the values but the even num...
Sum the Even Values of a String
In this Exercise, you will sum the value of a string. Complete the recursive function def sumString(st): This function accepts a string as a parameter and sums the ASCII value for each character whose ASCII value is an even number. I know how to sum all the values but the even numbers part is challenging. def sumSt...
[ "Maybe something like this?\ndef sumString(st):\n if not st:\n return 0\n else:\n out = ord(st[0]) if ord(st[0]) % 2 == 0 else 0\n return out + sumString(st[1:])\n \n\nprint(sumString(\"abcd\"))\n\nOutput:\n198\n\nThe ASCII value for b is 98 and the ASCII value for d is 100. So 100...
[ 1, 0, 0 ]
[]
[]
[ "ascii", "list", "python", "python_3.x", "recursion" ]
stackoverflow_0074171007_ascii_list_python_python_3.x_recursion.txt
Q: Does pytorch use the cudatoolkit in the conda environment or the system? I installed pytorch and torchvision in my conda environment with pip install torch==1.5.1+cu101 torchvision==0.6.1+cu101, to my understanding this means that the pytorch library is compiled with cuda10.1. And upon running nvcc --version , I g...
Does pytorch use the cudatoolkit in the conda environment or the system?
I installed pytorch and torchvision in my conda environment with pip install torch==1.5.1+cu101 torchvision==0.6.1+cu101, to my understanding this means that the pytorch library is compiled with cuda10.1. And upon running nvcc --version , I get nvcc: NVIDIA (R) Cuda compiler driver Copyright (c) 2005-2017 NVIDIA Corpor...
[ "\nYes, the pip wheels and conda binaries ship with their own CUDA runtime (as well as cuDNN. NCCL etc.) so you would only need to install the NVIDIA driver. If you want to build PyTorch from source or a custom CUDA extension, the local CUDA toolkit will be used.\n\nAs answered in the link here.\n" ]
[ 0 ]
[]
[]
[ "anaconda", "nvcc", "python", "pytorch" ]
stackoverflow_0070479396_anaconda_nvcc_python_pytorch.txt
Q: how to use divided in pandas pivot function I want to divide the sum value in aggfun by 2 . i want to this result :- import pandas as pd #create DataFrame df = pd.DataFrame({'team': ['A', 'B','B', 'B','A', 'A','A', 'B',], 'points_for': ['18', '22', '19', '14', '14', '11', '20', '28'], ...
how to use divided in pandas pivot function
I want to divide the sum value in aggfun by 2 . i want to this result :- import pandas as pd #create DataFrame df = pd.DataFrame({'team': ['A', 'B','B', 'B','A', 'A','A', 'B',], 'points_for': ['18', '22', '19', '14', '14', '11', '20', '28'], 'points_against': ['aa','bb','aa','bb',...
[ "You can divide after pivot\ndf2 = (pd.pivot_table(df, values='points_for', index='team', columns='points_against', aggfunc=sum)\n .astype(int).div(2))\n\nprint(df2)\n\npoints_against aa bb\nteam\nA 90710.0 5.5\nB 9.5 110714.0\n\n", "Try:\nprint(df2.astype...
[ 1, 1 ]
[]
[]
[ "dataframe", "pandas", "pivot_table", "python" ]
stackoverflow_0074172484_dataframe_pandas_pivot_table_python.txt
Q: Predicting new data with statsmodels gives ValueError: shapes I built a multiple regression model using Python statsmodels. X = df[['var1','var2','var3','var4']] X = sm.add_constant(X) ## let's add an intercept (beta_0) to our model y = df['target_trait'] model = sm.OLS(y, X).fit() #argument order: sm.OLS(output,...
Predicting new data with statsmodels gives ValueError: shapes
I built a multiple regression model using Python statsmodels. X = df[['var1','var2','var3','var4']] X = sm.add_constant(X) ## let's add an intercept (beta_0) to our model y = df['target_trait'] model = sm.OLS(y, X).fit() #argument order: sm.OLS(output, input), see (https://towardsdatascience.com/simple-and-multiple-li...
[ "I think I found the issue. When fitting the model I added a constant to the X matrix by doing X = sm.add_constant(X). By doing the same to X_new, the algorithm worked. Anyway, thank you for taking a look.\n" ]
[ 1 ]
[]
[]
[ "prediction", "python", "statsmodels" ]
stackoverflow_0074172499_prediction_python_statsmodels.txt
Q: Informix connection speed - Informatica PowerCenter vs Python by JDBC I have one workflow in Informatica Powercenter for transferring data between Informix and Oracle. Informatica needs about 20 seconds to do this work (6 tables, daily updates filtred by current date). I tried to achieve the same in Python using J...
Informix connection speed - Informatica PowerCenter vs Python by JDBC
I have one workflow in Informatica Powercenter for transferring data between Informix and Oracle. Informatica needs about 20 seconds to do this work (6 tables, daily updates filtred by current date). I tried to achieve the same in Python using JDBC... And this way it's extremely slow... For example, the first of these ...
[ "Multiple factors can be a reason for 'Why Informatica is faster' -\n\nInformatica can use native drivers like Oracle or Informix drivers to connect directly to the server. These are way faster than a JDBC driver.\nInformatica uses multi-threading to connect to the source, do the transformation, and load into the t...
[ 2 ]
[]
[]
[ "informatica", "informix", "jdbc", "python" ]
stackoverflow_0074168992_informatica_informix_jdbc_python.txt
Q: Why is my Simpson's modelling not giving the correct answer? I've been trying to do some Simpson's modelling to approximate integrals and although my code runs fine, it doesn't seem to give the correct answer. I'm new-ish to coding so I understand it's probably a dumb mistake but I can't figure out what's wrong. f...
Why is my Simpson's modelling not giving the correct answer?
I've been trying to do some Simpson's modelling to approximate integrals and although my code runs fine, it doesn't seem to give the correct answer. I'm new-ish to coding so I understand it's probably a dumb mistake but I can't figure out what's wrong. f(x) has already been defined and seems to work, it's just this int...
[ "\nThe ranges for odd numbers need to be from x=1 to x=N-1\nThe ranges for even numbers need to be from x=2 to x=N-2\nh is needs to be (xmax - xmin)/N\n\nHere is the Simpsons rule, with those corrections:\ndef f(x):\n return x**2\n\n\ndef integrate_numeric(xmin, xmax, N):\n '''\n Numerical integral of f fr...
[ 1 ]
[]
[]
[ "numerical_integration", "python", "simpsons_rule" ]
stackoverflow_0074172409_numerical_integration_python_simpsons_rule.txt
Q: Python logarithm function returning complex instead of float from sympy import diff from math import log def newt_method(f, a, b, e): if f(a) * f(b) >= 0: raise Exception("Корені відсутні.") iterations3 = 0 if diff(diff(f(a))) * f(a) > 0: x0 = a else: x0 = b while f(x0)...
Python logarithm function returning complex instead of float
from sympy import diff from math import log def newt_method(f, a, b, e): if f(a) * f(b) >= 0: raise Exception("Корені відсутні.") iterations3 = 0 if diff(diff(f(a))) * f(a) > 0: x0 = a else: x0 = b while f(x0) > e: x0 = x0 - (f(x0) / diff(f(x0))); iterations3...
[ "a or x0 are numbers, f(a) is a number, symbolic differentiation of a constant expression will at best return zero. Use for instance central difference quotients of first and second order.\nWhy do you care about a bracketing interval if an initial guess is all that is needed for the Newton iteration?\nThe test to s...
[ 2 ]
[]
[]
[ "logarithm", "math", "numerical_methods", "python" ]
stackoverflow_0074171740_logarithm_math_numerical_methods_python.txt
Q: Submitting a form from Vue component to POST data into django backend database Where is the relationship between a form (found in a vue component) and a django backend meant to be defined? For my frontend, I am using VueJS, my main component is able to fetch data from json file using an api defined in my django vi...
Submitting a form from Vue component to POST data into django backend database
Where is the relationship between a form (found in a vue component) and a django backend meant to be defined? For my frontend, I am using VueJS, my main component is able to fetch data from json file using an api defined in my django view and url file. I do not understand how after filling in my Vue form, I may directl...
[ "When you want to use SPA like Vue or React or Angular, it will be better to make communication between frontend and back end using API\nTo achieve that with django you can use\n\nDjango Rest Framework\n\nBest of luck\n" ]
[ 0 ]
[]
[]
[ "django", "javascript", "python", "vue.js" ]
stackoverflow_0074172179_django_javascript_python_vue.js.txt
Q: Use seek, write and readline methods on a CSV file stored on Google Cloud Storage (bucket) I have multiple methods on my Python script to work with a csv file. It's working on my local machine but it does not when I am working with the same csv file stored inside a Google Cloud Storage bucket. I need to keep track...
Use seek, write and readline methods on a CSV file stored on Google Cloud Storage (bucket)
I have multiple methods on my Python script to work with a csv file. It's working on my local machine but it does not when I am working with the same csv file stored inside a Google Cloud Storage bucket. I need to keep track of my current_position in the file so this is why I am using seek() and tell(). I tried to use ...
[ "Official library do not have such capabilities I think.\nYou can download file first than open it and work normally.\nApart from official one you can use gcsfs which implements missing functionality\nimport gcsfs\nfs = gcsfs.GCSFileSystem(project='my-google-project')\nwith fs.open('my-bucket/my-file.txt', 'rb') as...
[ 2, 2, 0 ]
[]
[]
[ "google_cloud_functions", "google_cloud_platform", "google_cloud_storage", "python" ]
stackoverflow_0064227396_google_cloud_functions_google_cloud_platform_google_cloud_storage_python.txt
Q: ModuleNotFoundError using Flask I'm trying to make a Flask api : app.py routes -> __init__.py -> myobject.py # app.py from flask import Flask from flask_restful import Api from routes import MyObject app = Flask(__name__) api = Api(app) api.add_resource(MyObject, '/') if __name__ == '__main__': app.run() ...
ModuleNotFoundError using Flask
I'm trying to make a Flask api : app.py routes -> __init__.py -> myobject.py # app.py from flask import Flask from flask_restful import Api from routes import MyObject app = Flask(__name__) api = Api(app) api.add_resource(MyObject, '/') if __name__ == '__main__': app.run() # __init__.py from myobject import My...
[ "For __init__.py, it also needs the relative import or absolute import path in order to work correctly.\n# __init__.py\n\n# relative import\nfrom .myobject import MyObject\n\n# absolute import\nfrom routes.myobject import MyObject\n\n\nIn another approach, you can write to import MyObject more specifically like thi...
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0074172351_python.txt
Q: SQLAlchemy 1.4 tutorial code "'Connection' object has no attribute 'commit'" error or does not commit changes Here is some custom code I wrote that I think might be problematic for this particular use case. class SQLServerConnection: def __init__(self, database): ... self.connection_string = \ ...
SQLAlchemy 1.4 tutorial code "'Connection' object has no attribute 'commit'" error or does not commit changes
Here is some custom code I wrote that I think might be problematic for this particular use case. class SQLServerConnection: def __init__(self, database): ... self.connection_string = \ "DRIVER=" + str(self.driver) + ";" + \ "SERVER=" + str(self.server) + ";" + \ ...
[ "As noted in the introduction to the 1.4 tutorial here:\n\nA Note on the Future\nThis tutorial describes a new API that’s released in SQLAlchemy 1.4 known as 2.0 style. The purpose of the 2.0-style API is to provide forwards compatibility with SQLAlchemy 2.0, which is planned as the next generation of SQLAlchemy.\n...
[ 1, 0, 0 ]
[]
[]
[ "python", "sql_server", "sqlalchemy", "tsql" ]
stackoverflow_0074146023_python_sql_server_sqlalchemy_tsql.txt
Q: Print all subarrays of a given array Given an array write an algorithm to print all the possible sub arrays. The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains an integer N denoting the size of the array A. Then in the next lines are N...
Print all subarrays of a given array
Given an array write an algorithm to print all the possible sub arrays. The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains an integer N denoting the size of the array A. Then in the next lines are N space separated values representing the a...
[ "If your issue is that you have empty lines, simplify your code to directly slice the list will all needed items.\nYou can use unpacking in print to have space separated elements by default.\nt = int(input())\nfor z in range(t):\n n = int(input()) \n a = list(map(int, input().split())) \n\n for i in range...
[ 2, 1, 0, 0 ]
[ "The code is another version of the answer given with basic syntax\nfor i in range(int(input())):#no of testcases eg:1\n n=int(input())#no of input eg:3\n x=list(map(int,input().split()))#values in the input eg:1 2 3\n l=[]\n for j in range(n):\n for k in range(j,n):\n l.append(x[k])\n print(*l)\n ...
[ -1 ]
[ "list", "python" ]
stackoverflow_0070733771_list_python.txt
Q: How to bind keypresses in a tkinter entry widget to process the entered characters instead of entering them into the field I am required to handle keypad "-", "+" and also "Escape" and "Return" key presses in a method. I've written a global handler so the key press does not have to be bound to any particular widge...
How to bind keypresses in a tkinter entry widget to process the entered characters instead of entering them into the field
I am required to handle keypad "-", "+" and also "Escape" and "Return" key presses in a method. I've written a global handler so the key press does not have to be bound to any particular widget. import tkinter as tk class Controller: def __init__(self): self.model = Model() self.view = View(self) ...
[ "\nIs there a way to prevent a regular keypress to write into the entry field?\n\nYou can create bindings for these keys directly on the entry widget, and have the function return the string \"break\". That will prevent the default bindings from functioning.\nFor a more comprehensive explanation of how key bindings...
[ 1 ]
[]
[]
[ "python", "python_3.x", "tkinter", "tkinter_entry" ]
stackoverflow_0074172456_python_python_3.x_tkinter_tkinter_entry.txt
Q: Code change of a Python script for posts on discord I have a script to build with a friend (I'm learning) that he does a daily search in an api, treats the data and sends it to discord via webhook. the issue is that the api changes once a day, and it is necessary to change part of the api manually every day. I w...
Code change of a Python script for posts on discord
I have a script to build with a friend (I'm learning) that he does a daily search in an api, treats the data and sends it to discord via webhook. the issue is that the api changes once a day, and it is necessary to change part of the api manually every day. I would like to automate this. I'll do the example below: #...
[ "You mentioned that the id increases by 1 every day, meaning that at any given moment the id is equal to the amount of days that have passed since this began.\nYou can use the datetime module to check the difference between two dates. By hardcoding the first date, you can just call today() to get the current date, ...
[ 0 ]
[]
[]
[ "discord.py", "python", "webhooks" ]
stackoverflow_0074169804_discord.py_python_webhooks.txt
Q: How to increment string like a number? Given the charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", how can I increment a string like following: aabbcde -> aabbcdf -> aabbcdg -> ... -> aabbcd0 -> aabbcea I would like a snippet in Python. Thank you! A: We have 62 digits: >>> DIGITS = "abc...
How to increment string like a number?
Given the charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", how can I increment a string like following: aabbcde -> aabbcdf -> aabbcdg -> ... -> aabbcd0 -> aabbcea I would like a snippet in Python. Thank you!
[ "We have 62 digits:\n>>> DIGITS = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\"\n>>> len(DIGITS)\n62\n\nso the easiest way to tackle the problem IMO is to implement a base-62 representation using those digits, since str->int conversion with a given set of digit characters is a well-trodden path...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074172496_python.txt
Q: Can I get multiple dedicated IP's at a single time through VPN using Python? I am doing some web scrapping. I want to rotate IP's in order to get away with blocking. My scraper is ready. I just need pool/list of dedicated IP's to make my scraper work. I already bought pro subscription of WindScribe. Till now I can...
Can I get multiple dedicated IP's at a single time through VPN using Python?
I am doing some web scrapping. I want to rotate IP's in order to get away with blocking. My scraper is ready. I just need pool/list of dedicated IP's to make my scraper work. I already bought pro subscription of WindScribe. Till now I cannot buy dedicated IP's as I only need for testing I want a solution through which ...
[ "I have a few caveats: I am not entirely clear what you are asking, and I am not familiar with WindScribe, and I haven't tried this myself. However, I believe it is possible to control the routing for a connection so it comes from one in a set of IP addresses.\nI am most familiar with Windows, however, I understand...
[ 0 ]
[]
[]
[ "ip", "python", "python_requests", "vpn", "web_scraping" ]
stackoverflow_0074169805_ip_python_python_requests_vpn_web_scraping.txt
Q: Python - listing prime numbers from 1 to 1000 including 1 This program is for listing all the prime numbers between 1 and 1000, but my teacher would like me to include 1 in the results. I tried to change it to say if num >= 1: and for i in range(1,num), but then when I ran it, the only result was 1 is a prime num...
Python - listing prime numbers from 1 to 1000 including 1
This program is for listing all the prime numbers between 1 and 1000, but my teacher would like me to include 1 in the results. I tried to change it to say if num >= 1: and for i in range(1,num), but then when I ran it, the only result was 1 is a prime number!. Thanks! for num in range(1,1001): if num > 1: f...
[ "You should not write for i in range(1, num):, because (any number) % 1 == 0. if num >= 1: can also be removed, because it's always true.\nTry the following code:\nfor num in range(1, 1001):\n for i in range(2, num):\n if num % i == 0:\n break\n else:\n print num, 'is a prime number'\...
[ 1, 0, 0 ]
[ "import math\n\nn1 = 1000\nrun_lim = math.ceil(math.sqrt(n1))\nprm_num = [2]\n\nfor i in range (1,n1+1) :\n if i == 1 :\n continue\n else :\n count = 0\n for j in range (len(prm_num)) : \n\n if (prm_num[j] <= run_lim) and (i%prm_num[j]) == 0 :\n count += 1\n\n ...
[ -1 ]
[ "python" ]
stackoverflow_0038602892_python.txt
Q: What is a "Field" associated with a class and how does it differ from methods in Python? Both field and method take arguments in same way and have similar syntax for calling them. How does one differ from the other? from tkinter import * # Window() is a blueprint for making object in tkinter library. main_window ...
What is a "Field" associated with a class and how does it differ from methods in Python?
Both field and method take arguments in same way and have similar syntax for calling them. How does one differ from the other? from tkinter import * # Window() is a blueprint for making object in tkinter library. main_window = Window() # minsize() is shown as "Field" with yellow color and capital "f" in PyCharm. wind...
[ "Fields and method parameters are not the same at all.\nIf they are named similarly, that's only a coincidence, not a requirement.\nHere's an example of different ways Python allows you to use method parameters.\nclass Foo:\n def __init__(self):\n self.field = None\n\n def method(self, parameter=None):...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074172442_python_tkinter.txt
Q: Python constructor "self = " I was writing a class and at some point I decided that it would be nice to have a possibility to create an instance of the class using other instance of this same class. So basically the class would look like this: class Test: def __init__(self, a, b): if type(b) == Test: ...
Python constructor "self = "
I was writing a class and at some point I decided that it would be nice to have a possibility to create an instance of the class using other instance of this same class. So basically the class would look like this: class Test: def __init__(self, a, b): if type(b) == Test: self = a / b el...
[ "The reason this doesn't work is that self is just an ordinary variable like any other.\nif type(b) == Test:\n self = a / b\nelse:\n self.a = a\n self.b = b\n\nIn the if branch, we reassign a local variable, but it doesn't change the instance being constructed. It just makes a new instance, that will be di...
[ 4 ]
[]
[]
[ "constructor", "oop", "python" ]
stackoverflow_0074172569_constructor_oop_python.txt
Q: Cannot find reference 'imread' in '__init__.py' hope you are doing good. I have been working on a project and I have this warning. So, please help me with this. import os import cv2 import numpy as np import pandas as pd import matplotlib.pyplot as plt img = cv2.imread('img1.jpeg') plt.imshow(img) this is the co...
Cannot find reference 'imread' in '__init__.py'
hope you are doing good. I have been working on a project and I have this warning. So, please help me with this. import os import cv2 import numpy as np import pandas as pd import matplotlib.pyplot as plt img = cv2.imread('img1.jpeg') plt.imshow(img) this is the code
[ "The code works fine on my system, the most likely explanation is a clash between the library and a cv2 folder in the same directory as the script you are running it in. Whenever you import a module in Python, the first place it looks for the module is in the folder the script is running in. Also try updating the m...
[ 0 ]
[]
[]
[ "pycharm", "python" ]
stackoverflow_0074172620_pycharm_python.txt
Q: Using AWS CodeStar Python project with JetBrain PyCharm I'm in the middle of evaluating CodeStar for some python programming on Amazon Lambda functions and have historically used JetBrain PyCharm for my Python development. Eclipse and Visual Studio integration are mentioned directly in the AWS CodeStar User Guide....
Using AWS CodeStar Python project with JetBrain PyCharm
I'm in the middle of evaluating CodeStar for some python programming on Amazon Lambda functions and have historically used JetBrain PyCharm for my Python development. Eclipse and Visual Studio integration are mentioned directly in the AWS CodeStar User Guide. I'm looking to try the Eclipse integration with PyCharm. PyC...
[ "Using PyCharm as your IDE for CodeStar in general is very doable. \nA majority of the Codestar stack is IDE-independent. Regardless of which IDE you use, the core process will be that you will push to your git repo, and this triggers actions in a pipeline which builds and deploys that code to your host(s). \nIn Py...
[ 1, 0 ]
[]
[]
[ "amazon_web_services", "aws_codestar", "pycharm", "python" ]
stackoverflow_0044146219_amazon_web_services_aws_codestar_pycharm_python.txt
Q: Why am I not getting appropriate values for the outline I am creating - mask with pygame I want to create an outline for a certain object - get a list of values (Tuple) corresponding to the outline according to the position of the object. I get a list but it doesn't match the position of the object and I have to d...
Why am I not getting appropriate values for the outline I am creating - mask with pygame
I want to create an outline for a certain object - get a list of values (Tuple) corresponding to the outline according to the position of the object. I get a list but it doesn't match the position of the object and I have to do another calculation to get the values contained on the list. self.pos = (random.randint(10, ...
[ "When you create an outline with `outline()', you have to keep 2 things in mind:\n\nMove the outline points created from the mask from the mask to the position on the screen\nmask = pygame.mask.from_surface(surface)\noutline = mask.outline()\nrect = surface.get_rect(center = (cx, cy)\nwindow_points = [(p[0] + rect....
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0073716557_pygame_python.txt
Q: How do I print my outputs of a for loop in one line ordered by index Is it possible to print my outputs of a for loop in one line and ordered by index: For example: outputs:TAWSG, HUHWO, ETOHO, RHDAD, EOETI, IRCID, SIISE, NTDAA, OYE ----> THEREISNOAUTHORITYWHODECIDESWHATISAGOODIDEA A: For every possible index i,...
How do I print my outputs of a for loop in one line ordered by index
Is it possible to print my outputs of a for loop in one line and ordered by index: For example: outputs:TAWSG, HUHWO, ETOHO, RHDAD, EOETI, IRCID, SIISE, NTDAA, OYE ----> THEREISNOAUTHORITYWHODECIDESWHATISAGOODIDEA
[ "For every possible index i, you would print a character from each string of the list. So, for each string x in the list you would print out x[i] if x[i] exists (by checking length of x).\nFull Code:\nlst = ['TAWSG', 'HUHWO', 'ETOHO', 'RHDAD', 'EOETI', 'IRCID', 'SIISE', 'NTDAA', 'OYE']\n\nmax_len = max([len(x) for ...
[ 0 ]
[]
[]
[ "indexing", "loops", "printing", "python", "python_3.x" ]
stackoverflow_0074172696_indexing_loops_printing_python_python_3.x.txt
Q: I tried and I only printed out the letter 's's instead of the words that start with s. I'm not sure how to use the .split() function Use for, .split(), and if to create a Statement that will print out words that start with 's': st = 'Print only the words that start with s in this sentence' A: Try this instead st...
I tried and I only printed out the letter 's's instead of the words that start with s. I'm not sure how to use the .split() function
Use for, .split(), and if to create a Statement that will print out words that start with 's': st = 'Print only the words that start with s in this sentence'
[ "Try this instead\nst = 'Print only the words that start with s in this sentence'\nAnswer = [word for word in st.split() if word[0] == 's']\nprint(Answer)\n\n" ]
[ 0 ]
[ "Split the list into Strings with .split(). Use \" \" as a separator because you want spaces to separate the words.\nst = \"Print only the words that start with s in this sentence\"\nwords = []\nfor word in st.split(\" \"):\n if word.startswith(\"s\"):\n words.append(word)\n\nprint(words)\n\n" ]
[ -1 ]
[ "for_comprehension", "if_statement", "python", "split", "statements" ]
stackoverflow_0073003288_for_comprehension_if_statement_python_split_statements.txt
Q: Python_Selenium - Checking if an element exists and if exists, click it I am writing a code in python with selenium. Sometimes due to site error a pop-up alike alert [java script] shows up and I have to click alert. I want to program it so every time I click "next Button" to check if the item popped up. If the but...
Python_Selenium - Checking if an element exists and if exists, click it
I am writing a code in python with selenium. Sometimes due to site error a pop-up alike alert [java script] shows up and I have to click alert. I want to program it so every time I click "next Button" to check if the item popped up. If the button had popped up, it should click it. thanks.
[ "You can do that with the use of driver.find_elements method.\nAs following:\nclose_alert_btn = driver.find_elements(By.XPATH, \"locator_of_alert_close_btn\")\nif close_alert_btn:\n close_alert_btn[0].click()\n\ndriver.find_elements method return a list of matching elements i.e. in case there were found elements...
[ 1 ]
[]
[]
[ "if_statement", "list", "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074172701_if_statement_list_python_selenium_selenium_webdriver.txt
Q: How to use "select_for_update()" to get an object in Django? As the Django Documentation says, select_for_update returns a Queryset. But get does not. Now I have a query which I am sure is going to return only one tuple. But I also need to acquire locks for this transaction. So I am doing something like: ob = MyMo...
How to use "select_for_update()" to get an object in Django?
As the Django Documentation says, select_for_update returns a Queryset. But get does not. Now I have a query which I am sure is going to return only one tuple. But I also need to acquire locks for this transaction. So I am doing something like: ob = MyModel.objects.select_for_update().filter(some conditions) Now, I ne...
[ "Just call get, slice it, etc. and save as usual. The lock is in place through the transaction.\nob = MyModel.objects.select_for_update().get(pk=1)\n\nAny changes are committed at the end of the transaction (which by default through 1.5 is per-request)\n", "You can also use select_for_update with get_object_or_40...
[ 56, 43, 0 ]
[]
[]
[ "django", "django_queryset", "python", "python_3.x", "select_for_update" ]
stackoverflow_0017159471_django_django_queryset_python_python_3.x_select_for_update.txt
Q: Odd and even number separator I had been given this problem to write a code which will get a line of numbers on the input and will separate them into odd and even. You get a line with natural numbers on the input. Sort them and write out the odd ones separately, the even ones separately This is where had I gone ...
Odd and even number separator
I had been given this problem to write a code which will get a line of numbers on the input and will separate them into odd and even. You get a line with natural numbers on the input. Sort them and write out the odd ones separately, the even ones separately This is where had I gone so far, but I have mainly I think p...
[ "Your code to separate the odds and evens into separate lists looks okay, but your code to create the list from input in the first place looks wrong. You're trying to convert a list generated by input().split() into an int.\nInstead use a list comprehension to make each element of that list into an int.\na = [int(x...
[ 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074172721_python.txt
Q: how to loop through ohlc minute data by day? I have a df containing minute bars of different symbols like so: timestamp open high low close volume trade_count vwap symbol 0 2021-10-13 08:00:00+00:00 140.20 140.40 140.000 140.40 6084 65 140.205417 ...
how to loop through ohlc minute data by day?
I have a df containing minute bars of different symbols like so: timestamp open high low close volume trade_count vwap symbol 0 2021-10-13 08:00:00+00:00 140.20 140.40 140.000 140.40 6084 65 140.205417 AAPL 1 2021-10-13 08:01:00+00:00 140.35 1...
[ "https://pandas.pydata.org/docs/user_guide/basics.html#by-values\nI think the decision depends on the actual aim of looping over days plus symbols.\ndf = df.sort_values(by=[\"timestamp\", \"symbol\"])\n\n", "Are you looking for:\n# ensure datetime\ndf['timestamp'] = pd.to_datetime(df['timestamp'])\n\n# group by s...
[ 1, 1, 0 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074168449_numpy_pandas_python.txt
Q: How to query certain metrics from tik tok report api in python? Hi I am trying to get additional metrics such as reach, video view up to 50%, video view up to 100% and url link per ad. However I am having a hard time finding the documentation to get such items. currently this is my code that runs endDate ="2022-05...
How to query certain metrics from tik tok report api in python?
Hi I am trying to get additional metrics such as reach, video view up to 50%, video view up to 100% and url link per ad. However I am having a hard time finding the documentation to get such items. currently this is my code that runs endDate ="2022-05-01" def tiktok(endDate): dftiktok=pd.DataFrame() ACCESS_TOKE...
[ "You forgot to add data to your request:\nfrom datetime import date, timedelta\nimport json\n\n\ndef get_tiktok_data(access_token):\n request_url = 'https://business-api.tiktok.com/open_api/v1.2/reports/integrated/get/'\n headers = {\n 'access-token': access_token,\n 'content_type': 'application...
[ 0 ]
[]
[]
[ "python", "tiktok" ]
stackoverflow_0072442708_python_tiktok.txt
Q: Checkbutton does not work on a nested tkinter window I am trying to create a Tkinter window with a button which when clicked will provide with a new window. The new window has a checkbox and I want some actions to be done based on the checkbox value. from tkinter import * from tkinter import messagebox def my_com...
Checkbutton does not work on a nested tkinter window
I am trying to create a Tkinter window with a button which when clicked will provide with a new window. The new window has a checkbox and I want some actions to be done based on the checkbox value. from tkinter import * from tkinter import messagebox def my_command(): def run(): pass def cb_command()...
[ "from tkinter import *\n\ndef new_window():\n second_window = Toplevel()\n def checkbutton_checked():\n # If you just want to take some action, once the checkbutton has been checked, you could do this here\n # Alternatively you could also add a button to the toplevel and on click check the value...
[ 0 ]
[]
[]
[ "checkbox", "python", "python_3.x", "tkinter", "tkinter_button" ]
stackoverflow_0074172008_checkbox_python_python_3.x_tkinter_tkinter_button.txt
Q: Finding the closest point from Point Cloud Data to point (0,0,0) I made a program to plot a figure from point cloud data (x,y,z coordinates shown as list x_list, y_list, z_list). Now, I have to find the closest point to (0,0,0). Anybody has an idea to do that? Here is the program: import matplotlib.pyplot as plt i...
Finding the closest point from Point Cloud Data to point (0,0,0)
I made a program to plot a figure from point cloud data (x,y,z coordinates shown as list x_list, y_list, z_list). Now, I have to find the closest point to (0,0,0). Anybody has an idea to do that? Here is the program: import matplotlib.pyplot as plt import pandas as pd import numpy as np import math from mpl_toolkits.mp...
[ "This should do the trick.\ndef closest(X, Y, Z, P):\n \"\"\"\n X: x-axis series\n Y: y-axis series\n Z: z-axis series\n P: centre point to measure distance from\n \n Returns: tuple(closest point, distance between P and closest point)\n \"\"\" \n # Here we combine ...
[ 0, 0 ]
[]
[]
[ "closest", "math", "pandas", "point", "python" ]
stackoverflow_0072303980_closest_math_pandas_point_python.txt
Q: How to split python string the clean way when reading from text Hi I am reading data from a text file using python and the data file looks like this: Date Time Attr Size Compressed Name ------------------- ----- ------------ ------------ ------------------------ 2022-10-15 17:41:06 D.... ...
How to split python string the clean way when reading from text
Hi I am reading data from a text file using python and the data file looks like this: Date Time Attr Size Compressed Name ------------------- ----- ------------ ------------ ------------------------ 2022-10-15 17:41:06 D.... 0 2 B18DCDT026\0011202208230S3764N 2022-10-04 03:...
[ "Use a maxsplit and take the last value like\nname = line.split(maxsplit=5)[-1]\n\n" ]
[ 2 ]
[]
[]
[ "parsing", "python", "string" ]
stackoverflow_0074172846_parsing_python_string.txt
Q: How can I simultaneously run two (or more) functions in python? I intend to be able to play video via opencv while some other process runs in the background. My current working looks like this import cv2 async def function1(): cap = cv2.VideoCapture('video.mp4') while True: ret, frame = cap.read()...
How can I simultaneously run two (or more) functions in python?
I intend to be able to play video via opencv while some other process runs in the background. My current working looks like this import cv2 async def function1(): cap = cv2.VideoCapture('video.mp4') while True: ret, frame = cap.read() if ret == True: cv2.imshow('Frame', frame) ...
[ "Try Threading instead of async/await\nso you can have multiple threads(subprograms) running at the same time\n" ]
[ 0 ]
[]
[]
[ "concurrency", "python", "python_asyncio", "video_processing" ]
stackoverflow_0074172917_concurrency_python_python_asyncio_video_processing.txt
Q: How can i get nth fibonacci number ? i want to find it without use recursion.I write code like that but i want my program shows only nth number my code: fib1 = 1 fib2 = 1 n = int(input('N =')) for i in range(2,n): c = fib1 + fib2 fib1 = fib2 fib2 = c print(c) answer: N = >>> 10 2 3 5 8 13 21 34 55...
How can i get nth fibonacci number ? i want to find it without use recursion.I write code like that but i want my program shows only nth number
my code: fib1 = 1 fib2 = 1 n = int(input('N =')) for i in range(2,n): c = fib1 + fib2 fib1 = fib2 fib2 = c print(c) answer: N = >>> 10 2 3 5 8 13 21 34 55
[ "Don't print at each iteration, only after all of them, after the loop\nfib1, fib2, c = 1, 1, None\nn = int(input('N ='))\nfor i in range(2, n):\n c = fib1 + fib2\n fib1 = fib2\n fib2 = c\nprint(c)\n\n", "Without recursion, you can used the closed form of the Fibonacci sequence.\ndef fib(n):\n return ...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074172940_python.txt
Q: How to append to a file using PyGithub? I want to append to an already existing .txt file using PyGithub in Python. I have tried this code: git = Github(TOKEN) repo = git.get_repo("Repository") file = repo.get_contents("Textfile.txt", ref="Ref") repo.update_file(file.path, "test", "Text I wanna store", file.sha, ...
How to append to a file using PyGithub?
I want to append to an already existing .txt file using PyGithub in Python. I have tried this code: git = Github(TOKEN) repo = git.get_repo("Repository") file = repo.get_contents("Textfile.txt", ref="Ref") repo.update_file(file.path, "test", "Text I wanna store", file.sha, branch="Ref") but this code deletes the old ...
[ "Your code is above is already good, you simply need to take the original Content of the File, and append new one with a + operator or an f-string\nHere is an example\ngit = Github(TOKEN)\nrepo = git.get_repo(\"Repository\")\nfile = repo.get_contents(\"Textfile.txt\", ref=\"Ref\")\nnew_data = input(\"Text you want ...
[ 0, 0 ]
[]
[]
[ "file", "github", "pygithub", "python" ]
stackoverflow_0071887432_file_github_pygithub_python.txt
Q: How do I get the user to click on the random button (1,10) in order to guess which button has diamond hidden? User has got 3 attempts A user has got 10 buttons and the diamond is hidden in one by using random function. User has got three attempts to find out in which box is the diamond. from tkinter import *...
How do I get the user to click on the random button (1,10) in order to guess which button has diamond hidden? User has got 3 attempts
A user has got 10 buttons and the diamond is hidden in one by using random function. User has got three attempts to find out in which box is the diamond. from tkinter import * import tkinter.messagebox as msgBox window = Tk() window.title("Find the diamond") window.configure(bg="gray", pa...
[ "from tkinter import *\nimport random\n\nwindow = Tk()\nglobal guesses\nguesses = 0\n\ndef start_game():\n global location\n location = random.randrange(1, 11, 1)\n\ndef clicked(button_number):\n global guesses, location\n guesses += 1\n if guesses > 3:\n # tell the player he lost here in any ...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074171782_python_tkinter.txt
Q: BERT-based NER model giving inconsistent prediction when deserialized I am trying to train an NER model using the HuggingFace transformers library on Colab cloud GPUs, pickle it and load the model on my own CPU to make predictions. Code The model is the following: from transformers import BertForTokenClassificatio...
BERT-based NER model giving inconsistent prediction when deserialized
I am trying to train an NER model using the HuggingFace transformers library on Colab cloud GPUs, pickle it and load the model on my own CPU to make predictions. Code The model is the following: from transformers import BertForTokenClassification model = BertForTokenClassification.from_pretrained( "bert-base-cased...
[ "I fixed it, there were two problems:\n\nThe index-label mapping for tokens was wrong, for some reason the list() function worked differently on Colab GPU than my CPU (??)\n\nThe snippet used to save the model was not correct, for models based on the huggingface-transformers library you can't use model.save_dict() ...
[ 3, 0 ]
[]
[]
[ "bert_language_model", "huggingface_transformers", "python", "pytorch" ]
stackoverflow_0064610841_bert_language_model_huggingface_transformers_python_pytorch.txt
Q: Is there an issue with moviepy's concatenate_videoclips() function, or is my implementation introducing this effect? I am using moviepy to make a video of images. My code is below, and clip_path_list is a list of integers referring to the line number of the image (e.g [1,2,3,4]). These are all stored in a director...
Is there an issue with moviepy's concatenate_videoclips() function, or is my implementation introducing this effect?
I am using moviepy to make a video of images. My code is below, and clip_path_list is a list of integers referring to the line number of the image (e.g [1,2,3,4]). These are all stored in a directory called genned_images. When I run this code, there is no error, but the output looks very strange for all images after a ...
[ "My solution:\nThis seems to have been fixed by using\nclip = concatenate_videoclips(clips, \"compose\", bg_color=None, padding=0)\n\nI assume that the scrolling error was due to a disparity in the sizes of the images, and using compose fixes that.\n" ]
[ 0 ]
[]
[]
[ "moviepy", "python" ]
stackoverflow_0074170641_moviepy_python.txt
Q: How to read the request body using orjson library in FastAPI? I am writing code to receive a JSON payload in FastAPI. Here is my code: from fastapi import FastAPI, status, Request from fastapi.responses import ORJSONResponse import uvicorn import asyncio import orjson app = FastAPI() @app.post("/", status_code =...
How to read the request body using orjson library in FastAPI?
I am writing code to receive a JSON payload in FastAPI. Here is my code: from fastapi import FastAPI, status, Request from fastapi.responses import ORJSONResponse import uvicorn import asyncio import orjson app = FastAPI() @app.post("/", status_code = status.HTTP_200_OK) async def get_data(request: Request): para...
[ "When calling request.json(), FastAPI (actually Starlette) first reads the body (using the .body() method of the Request object), and then calls json.loads() (using the standard json library of Python) to return a dict/list object to you inside the endpoint (see the implementation here)—it doesn't use .dumps(), as ...
[ 0 ]
[]
[]
[ "fastapi", "orjson", "python", "starlette" ]
stackoverflow_0074168582_fastapi_orjson_python_starlette.txt
Q: Issues spawning multiple objects pygame I'm very new to programing and I decided to try and make a very simple game to practice using pygame. It's just a game where you're a rectangle and have to avoid geting hit by other rectangles(enemies). However I'm having issues spawning in the enemies, something I did makes...
Issues spawning multiple objects pygame
I'm very new to programing and I decided to try and make a very simple game to practice using pygame. It's just a game where you're a rectangle and have to avoid geting hit by other rectangles(enemies). However I'm having issues spawning in the enemies, something I did makes it so when I draw them to the screen they wi...
[ "My recommendation is to learn classes. They are absolutely a life saver in game programming.\nSome info about classes from w3schools\n\nAll classes have a function called init(), which is always\nexecuted when the class is being initiated.\nUse the init() function to assign values to object properties, or\nother o...
[ 0 ]
[]
[]
[ "pygame", "python", "python_3.x" ]
stackoverflow_0074171759_pygame_python_python_3.x.txt
Q: Filter window partitions which have at least three 5-minute gaps Here's my code: from pyspark.sql import functions as F, Window as W df_subs_loc_movmnt_ts = df_subs_loc_movmnt.withColumn("new_ts", F.unix_timestamp(F.col("ts"), "HH:mm:ss")) w = W.partitionBy('subs_no', 'year', 'month', 'day', 'cgi').orderBy('new_t...
Filter window partitions which have at least three 5-minute gaps
Here's my code: from pyspark.sql import functions as F, Window as W df_subs_loc_movmnt_ts = df_subs_loc_movmnt.withColumn("new_ts", F.unix_timestamp(F.col("ts"), "HH:mm:ss")) w = W.partitionBy('subs_no', 'year', 'month', 'day', 'cgi').orderBy('new_ts') df_subs_loc_movmnt_duration = df_subs_loc_movmnt_ts.withColumn('du...
[ "Inputs:\nfrom pyspark.sql import functions as F, Window as W\ndf_subs_loc_movmnt_duration = spark.createDataFrame(\n [(20200801, '10:40:43.000000', 10000093, '510-11-610725-5', 7664622154085, 2022, 6, 2, 13243, '07:00:00'),\n (20200801, '12:55:30.000000', 10000093, '510-11-610725-5', 7664622154085, 2022, 6,...
[ 2, 1 ]
[]
[]
[ "apache_spark", "datetime", "pyspark", "python", "window_functions" ]
stackoverflow_0074063368_apache_spark_datetime_pyspark_python_window_functions.txt
Q: How to generate random numbers in pre-defined range which sums up to a fixed number in R/Python I have a simple data generation question. I would request for any kind of help with the code in R or Python. I am pasting the table first. Total Num1_betw_1_to_4 Num2_betw_1_to_3 Num3_betw_1_to_3 9 3 3 3 7 1 3 3 9 4...
How to generate random numbers in pre-defined range which sums up to a fixed number in R/Python
I have a simple data generation question. I would request for any kind of help with the code in R or Python. I am pasting the table first. Total Num1_betw_1_to_4 Num2_betw_1_to_3 Num3_betw_1_to_3 9 3 3 3 7 1 3 3 9 4 3 2 9 3 3 3 5 2 2 1 7 3 2 2 9 3 3 3 7 2 3 2 5 6 2 4 9 ...
[ "This is straightforward in R.\nFirst make a data frame of all possible allowed values of each column:\ndf <- expand.grid(Num1_1_to_4 = 1:4,\n Num2_1_to_3 = 1:3,\n Num3_1_to_3 = 1:3)\n\nNow throw away any rows that don't sum to 7:\ndf <- df[rowSums(df) == 7,]\n\nFinally, sample thi...
[ 2, 1, 1 ]
[]
[]
[ "python", "r", "random" ]
stackoverflow_0074172806_python_r_random.txt
Q: How can I enforce overridden methods to return a specific subset of types? I'm defining a simple class hierarchy for metrics of objects in images. For example, one metric is 'area', the number of pixels. Another might be 'color', e.g. a string like 'green' or 'orange'. The base class BaseMetric only has an abstrac...
How can I enforce overridden methods to return a specific subset of types?
I'm defining a simple class hierarchy for metrics of objects in images. For example, one metric is 'area', the number of pixels. Another might be 'color', e.g. a string like 'green' or 'orange'. The base class BaseMetric only has an abstract method compute for computing and returning the metric's value, while the subcl...
[ "I am not familiar with the overrides package and from reading the Readme in the repo you linked I cannot tell, if they promise handling generics properly.\nEither way, the reason why static type checkers have no problem with that return annotation of InvalidMetric.compute, is very simple: bool is a subclass of int...
[ 1 ]
[]
[]
[ "generics", "overriding", "pylance", "python", "types" ]
stackoverflow_0074100176_generics_overriding_pylance_python_types.txt
Q: Reading multiple text files and separating them into different arrays in Python I have this code in MATLAB txtFiles = dir('*.txt') ; %loads txt files N = length(txtFiles) ; for i = 1:N data = importdata(txtFiles(i).name); x = data(:,1); y(:,i) = data(:,2) ; end Which takes all 100 of my txt files an...
Reading multiple text files and separating them into different arrays in Python
I have this code in MATLAB txtFiles = dir('*.txt') ; %loads txt files N = length(txtFiles) ; for i = 1:N data = importdata(txtFiles(i).name); x = data(:,1); y(:,i) = data(:,2) ; end Which takes all 100 of my txt files and creates an array for x then stores the y data in an a separate array where each col...
[ "Your files are pretty much csv files, and could be read using np.loadtxt or pd.read_csv.\nBut as you did you can extract values from the text yourself, the following will work for any number of columns:\ndef extract_values(text, sep=\" \", dtype=float):\n return (\n np.array(x, dtype=dtype)\n for ...
[ 0 ]
[]
[]
[ "arrays", "matlab", "numpy", "python" ]
stackoverflow_0074172216_arrays_matlab_numpy_python.txt
Q: Compute sequential max value in Pandas using vectorized operations I have a dataframe that looks like this value 10 20 30 20 40 35 60 100 50 45 135 and I want to compute a column with the max value until the respective row. The final dataframe should look like this: value max_value 10 10 20 ...
Compute sequential max value in Pandas using vectorized operations
I have a dataframe that looks like this value 10 20 30 20 40 35 60 100 50 45 135 and I want to compute a column with the max value until the respective row. The final dataframe should look like this: value max_value 10 10 20 20 30 30 20 30 40 40 35 40 60 ...
[ "Use DataFrame.cummax()\ndf['max_value'] = df['value'].cummax()\n\nprint(df)\n\n value max_value\n0 10 10\n1 20 20\n2 30 30\n3 20 30\n4 40 40\n5 35 40\n6 60 60\n7 100 100\n8 50 100\n9 45 ...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074172816_dataframe_pandas_python.txt
Q: How can I make it so the script tells me the changes of the .txt file in real time? (Python) So I've been trying to make a code that specifically changes the text in a .txt file in a certain folder - and so far it works. But there's one problem: it won't update in real time (inside the code) until I repeat the cod...
How can I make it so the script tells me the changes of the .txt file in real time? (Python)
So I've been trying to make a code that specifically changes the text in a .txt file in a certain folder - and so far it works. But there's one problem: it won't update in real time (inside the code) until I repeat the code (as in, I choose 'Y'), but when I use the script, it changes in real time outside on the file it...
[ "Close your arquivo1 file after writing.\ndef coca():\n print(\"Write your anotation:\")\n escolha = input()\n arquivo1 = open('doc.txt', 'a')\n arquivo1.write(escolha)\n arquivo1.write(\" \\n\")\n arquivo1.close()\n print(\"Your anotation:\")\n f = open(\"DOC.txt\", \"r\")\n print(f.read())\n f...
[ 0 ]
[]
[]
[ "function", "loops", "printing", "python", "txt" ]
stackoverflow_0074172910_function_loops_printing_python_txt.txt
Q: How to access columns when using groupby? I have a bunch of minute data in a single df, that I wan't to split into individual days so I can trade each day by itself, but I'm struggling to access the columns properly: Reading from sql into a pandas df: df = pd.read_sql_query("SELECT * from ohlc_minutes", conn) pri...
How to access columns when using groupby?
I have a bunch of minute data in a single df, that I wan't to split into individual days so I can trade each day by itself, but I'm struggling to access the columns properly: Reading from sql into a pandas df: df = pd.read_sql_query("SELECT * from ohlc_minutes", conn) print(df) I'm then making my timestamp column a d...
[ "DataFrame.groupby returns as list of tuple, you can do\nfor name, ohlc in seperate_days:\n display(ohlc)\n print(ohlc['symbol'])\n\n" ]
[ 2 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074173086_numpy_pandas_python.txt
Q: Why am I getting an invalid syntax error on this script? I'm getting an invalid syntax error on the print("Got Here"data) line of the following code. I don't see any syntax errors. import requests import json def test(): f = open('greenbook_1956.json') print("Got Here"data) data= json.load(f) prin...
Why am I getting an invalid syntax error on this script?
I'm getting an invalid syntax error on the print("Got Here"data) line of the following code. I don't see any syntax errors. import requests import json def test(): f = open('greenbook_1956.json') print("Got Here"data) data= json.load(f) print(data['rows'][0])
[ "swap these two lines:\nprint(\"Got Here\"data)\ndata= json.load(f)\n\nand add a comma between data and 'Got Here'!\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074173055_python.txt
Q: Python re.sub always returns the original string value and ignores given pattern My code below old = """ B07K6VMVL5 B071XQ6H38 B0B7F6Q9BH B082KTHRBT B0B78CWZ91 B09T8TJ65B B09K55Z433 """ duplicate = """ B0B78CWZ91 B09T8TJ65B B09K55Z433 """ final = re.sub(r"\b{}\b".format(duplicate),"",old) print(final) The final a...
Python re.sub always returns the original string value and ignores given pattern
My code below old = """ B07K6VMVL5 B071XQ6H38 B0B7F6Q9BH B082KTHRBT B0B78CWZ91 B09T8TJ65B B09K55Z433 """ duplicate = """ B0B78CWZ91 B09T8TJ65B B09K55Z433 """ final = re.sub(r"\b{}\b".format(duplicate),"",old) print(final) The final always prints the old variable values.I want the duplicate values to be removed in the...
[ "The block string should not start/end in a new line since it will introduce a \\n character. Try with\nold = \"\"\"B07K6VMVL5\nB071XQ6H38\nB0B7F6Q9BH\nB082KTHRBT\nB0B78CWZ91 # <-\nB09T8TJ65B # <-\nB09K55Z433\"\"\" # <-\n\nduplicate = \"\"\"B0B78CWZ91\nB09T8TJ65B\nB09K55Z433\"\"\"\n\nand the result will not e...
[ 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074171796_python_regex.txt
Q: pandas dataframe doubled, when trying to concatenate without duplicates Python I was trying to concatenate two data frames and removing their duplicates. It worked but somehow it saved both the concatenated dataframe (dataF) and a dataframne that looks like the previous given dataframe (availableData). I tried goo...
pandas dataframe doubled, when trying to concatenate without duplicates Python
I was trying to concatenate two data frames and removing their duplicates. It worked but somehow it saved both the concatenated dataframe (dataF) and a dataframne that looks like the previous given dataframe (availableData). I tried googling the error and searching it on Stack Overflow but didn't find any solution. Her...
[ "The dataframe dataF probably has duplicated indexes. You can create a new index inside pd.concat with ignore_index parameter:\ndataF = pd.concat([availableData, data], ignore_index=True).drop_duplicates()\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "duplicates", "pandas", "python" ]
stackoverflow_0074172849_dataframe_duplicates_pandas_python.txt
Q: Looking for help, just started with Python today. (3.0) I am just trying to get into python, but I've found it very difficult to find any resource that is Python 3. All I've got so far is diveintopython3.org, and its limited. Anyways, I was just trying to get a feel for the language by doing some very basic stuff,...
Looking for help, just started with Python today. (3.0)
I am just trying to get into python, but I've found it very difficult to find any resource that is Python 3. All I've got so far is diveintopython3.org, and its limited. Anyways, I was just trying to get a feel for the language by doing some very basic stuff, but I can't figure out why this little program won't do what...
[ "A Byte of Python covers Python 3 in detail. There's also a 2.X version of the book, which can help compare and contrast the differences in the languages.\nTo fix your problem, you need to convert the input taken into an integer. It's stored as a string by default.\nnum = int(input(\"Enter a number: \"))\nnum2 = ...
[ 7, 3, 1, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0000895637_python_python_3.x.txt
Q: How to calculate total price with discount by the products in Python I created two classes. In class Cart i need to implement the method get_total_price that calculate total price with discount. Discount depends on count product: count discount at least 5 5% at least 7 10% at least 10 20% at leas...
How to calculate total price with discount by the products in Python
I created two classes. In class Cart i need to implement the method get_total_price that calculate total price with discount. Discount depends on count product: count discount at least 5 5% at least 7 10% at least 10 20% at least 20 30% more than 20 50% class Product: def __init__(self,...
[ "It seems cart.products_list returns a tuple containing the products list (so, a tuple in another tuple). If it's not intended, remove the '*'.\nHere is a working solution for the current structure; if you remove '*', remove [0] in the get_total_price method.\ndef discount_mult(q):\n if q > 20:\n ...
[ 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0074172963_oop_python.txt
Q: Printing binary without trailing 0s? Trying to create a small program that takes in positive integers and converts it into reverse binary. I've gotten this far: import math integer = int(input()) while integer > 0: x = integer % 2 print(int(math.floor(x)), end='') integer = integer / 2 The problem wi...
Printing binary without trailing 0s?
Trying to create a small program that takes in positive integers and converts it into reverse binary. I've gotten this far: import math integer = int(input()) while integer > 0: x = integer % 2 print(int(math.floor(x)), end='') integer = integer / 2 The problem with this is that the output would have unne...
[ "It sounds like you have reversed a binary number like this:\ndef reverse_bits(n):\n res = 0\n for i in range(n.bit_length(), -1, -1):\n if n & (1 << i):\n res += 1 << (n.bit_length() - i)\n return res\n\nbin(reverse_bits(12)) # '0b110'\n\nYou can bit shift to the right, until there is a...
[ 0 ]
[ "use // instead of / in division\n", "Here is an alternate approach:\ninteger = 3\nprint (bin(integer)[2:][::-1])\n\n" ]
[ -1, -1 ]
[ "python" ]
stackoverflow_0074173079_python.txt
Q: Why does shapely wkt require separate import? I am using shapely 1.8.2 and when I import it, I cannot use shape.wkt. For example, if I do: import shapely shapely.wkt or import shapely shapely.wkt.loads(my_polygon) I get AttributeError: module 'shapely' has no attribute 'wkt'. But if I do import shapely from shap...
Why does shapely wkt require separate import?
I am using shapely 1.8.2 and when I import it, I cannot use shape.wkt. For example, if I do: import shapely shapely.wkt or import shapely shapely.wkt.loads(my_polygon) I get AttributeError: module 'shapely' has no attribute 'wkt'. But if I do import shapely from shapely import wkt I can now access shapely.wkt. Can s...
[ "This is a design decision by the developers of that package. What does or does not appear in the root package namespace comes down to what they put in the package’s __init__.py file.\nCurrently, there are lots of things imported into the global shapely namespace, but not wkt:\nfrom .lib import GEOSException # NOQ...
[ 0 ]
[]
[]
[ "python", "shapely" ]
stackoverflow_0074169197_python_shapely.txt
Q: Converting time-stamps in the dataframe Thanks to this answer, I have the following dataframe: START_POINT END_POINT DURATION island Stage 1 SLEEP-S0 00:32:03 00:42:33 630.0 2 SLEEP-S1 00:42:33 00:45:03 150.0 3 SLEEP-S0 00:45:03 00:46:03 60.0 4 SLEE...
Converting time-stamps in the dataframe
Thanks to this answer, I have the following dataframe: START_POINT END_POINT DURATION island Stage 1 SLEEP-S0 00:32:03 00:42:33 630.0 2 SLEEP-S1 00:42:33 00:45:03 150.0 3 SLEEP-S0 00:45:03 00:46:03 60.0 4 SLEEP-S1 00:46:03 00:48:33 150.0 5 SLE...
[ "Reference this answer below\nHow to standardize/normalize a date with pandas/numpy?\nYou could standardize the array of timestamps and then you could multiply the standardized values by 10000000 to convert to an int.\n", "here you go:\ndf[\"start\"] = df[\"DURATION\"].cumsum().shift().fillna(0)\ndf[\"end\"] = df...
[ 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python", "time_series", "timestamp" ]
stackoverflow_0074148315_dataframe_pandas_python_time_series_timestamp.txt
Q: What is CRS/units in osmnx python? How to find distance between road edge and a given point in openstreetmap? Here is a docs: osmnx.distance.nearest_edges(G, X, Y, interpolate=None, return_dist=False) Find the nearest edge to a point or to each of several points. If X and Y are single coordinate values, this will...
What is CRS/units in osmnx python? How to find distance between road edge and a given point in openstreetmap?
Here is a docs: osmnx.distance.nearest_edges(G, X, Y, interpolate=None, return_dist=False) Find the nearest edge to a point or to each of several points. If X and Y are single coordinate values, this will return the nearest edge to that point. If X and Y are lists of coordinate values, this will return the nearest edg...
[ "\nWhat is CRS/units in osmnx python?\n\nAre you asking what these terms mean? Or what their default values are? If it is the former, you can refer to any introductory GIS textbook. If it is the latter, as the OSMnx documentation states, the default CRS is EPSG:4326. Regarding distance units, it depends on what you...
[ 0 ]
[]
[]
[ "gis", "openstreetmap", "osmnx", "python" ]
stackoverflow_0074172370_gis_openstreetmap_osmnx_python.txt
Q: Adding functionality for autofill suggestion on text input in python I have tried several ways to add autocomplete/autofill suggestion functionality on text input. I have set a list 'names' for which I want autofill suggestions when being searched. I have tried three different codes for the same. I am facing probl...
Adding functionality for autofill suggestion on text input in python
I have tried several ways to add autocomplete/autofill suggestion functionality on text input. I have set a list 'names' for which I want autofill suggestions when being searched. I have tried three different codes for the same. I am facing problem in the three of them. First code I got from pypi.org (https://pypi.org/...
[ "I think this works as a minimal solution. You can define a list like self.word_list and it can recommend you the words of your choosing.\nclass AppDemo(QWidget):\n def __init__(self):\n super().__init__()\n self.word_list=[\"apple\",\"banana\",\"question\"]\n self.resize(1200, 800)\n\n ...
[ 0 ]
[]
[]
[ "autocomplete", "django_autocomplete_light", "python", "python_3.x", "textfield" ]
stackoverflow_0074173111_autocomplete_django_autocomplete_light_python_python_3.x_textfield.txt
Q: Psycopg3: NaN to null conversion in COPY statements In psycopg2 it was possible to covert NaN values to nulls, using adapters like this: __REGISTERED = False def _nan_to_null(f, _NULL=psycopg2.extensions.AsIs('NULL'), _Float=psycopg2.extensions.Float): if not np.isnan(f): return _Float...
Psycopg3: NaN to null conversion in COPY statements
In psycopg2 it was possible to covert NaN values to nulls, using adapters like this: __REGISTERED = False def _nan_to_null(f, _NULL=psycopg2.extensions.AsIs('NULL'), _Float=psycopg2.extensions.Float): if not np.isnan(f): return _Float(f) return _NULL def register_nan_adapter(): g...
[ "Hmm, that was easier then I thought. Actually not as the two updates attest.\nimport numpy as np\nimport psycopg\nfrom psycopg.types.numeric import FloatDumper\n\nclass NanDumper(FloatDumper):\n def dump(self, obj):\n if np.isnan(obj):\n return None\n else:\n return super().d...
[ 0 ]
[]
[]
[ "postgresql", "psycopg2", "psycopg3", "python" ]
stackoverflow_0074172915_postgresql_psycopg2_psycopg3_python.txt
Q: NumPy: How to obtain all elements adjacent to certain elements? Assume that we have an ndarray of elements. When flattened, it's guaranteed to be one-dimensional. I'm looking for a way via NumPy API, without using loops, to obtain elements adjacent to a certain element (or a set of elements), if these exist, from ...
NumPy: How to obtain all elements adjacent to certain elements?
Assume that we have an ndarray of elements. When flattened, it's guaranteed to be one-dimensional. I'm looking for a way via NumPy API, without using loops, to obtain elements adjacent to a certain element (or a set of elements), if these exist, from that flattened ndarray. Below is my way to achieve this in loops, but...
[ "def find_adjacent(v, a, side):\n if side=='L':\n return v[np.isin(np.roll(v,1),a)]\n elif side=='R':\n return v[np.isin(np.roll(v,-1),a)]\n else:\n return v[np.isin(np.roll(v,1),a) & np.isin(np.roll(v,-1),a)]\n\nDepending on what you meant by \"only adjacent to the left and to the right\", you...
[ 1 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074173158_arrays_numpy_python.txt
Q: How to use typehinting for a generic type when you need to create instances of that type in Python I'm making a class that gets dictionaries and creates an instance of a given class. The current version works but you need to tell the class twice what type it should convert the dictionaries to. I could just get rid...
How to use typehinting for a generic type when you need to create instances of that type in Python
I'm making a class that gets dictionaries and creates an instance of a given class. The current version works but you need to tell the class twice what type it should convert the dictionaries to. I could just get rid of the Generic but I'd like to keep using type hints. from typing import Dict, Generic, List, Type, Typ...
[ "It makes sense to tell it twice, both type checker and interpreter need to know. It may be possible for the interpreter to access type annotation at runtime, but I would not do it.\nAlso, many things are wrong with your approach, and if you fix them all you will arrive at cattrs. So I suggest to use cattrs immedia...
[ 0, 0 ]
[]
[]
[ "generics", "python", "python_3.x", "type_hinting" ]
stackoverflow_0074067711_generics_python_python_3.x_type_hinting.txt
Q: Iterate through a column and change another column value based on it (Pandas Dataframe) I want to iterate through a column and if that column value meets some criteria it changes another column value. cycleNum = 0 first = 0 for entry in df1['Ns']: if entry < first: cycleNum = cycleNum +1 df1...
Iterate through a column and change another column value based on it (Pandas Dataframe)
I want to iterate through a column and if that column value meets some criteria it changes another column value. cycleNum = 0 first = 0 for entry in df1['Ns']: if entry < first: cycleNum = cycleNum +1 df1['cycleNumber'] = cycleNum first = 0 else: df1['cycleNumber'] = cycleNum ...
[ "Use df1.loc[ROW, 'cycleNumber']\nfor idx, entry in df1['Ns'].iteritems():\n\n if entry < first:\n cycleNum = cycleNum +1\n df1.loc[idx, 'cycleNumber'] = cycleNum\n first = 0\n else:\n df1.loc[idx, 'cycleNumber'] = cycleNum\n first = entry\n\n", "Starting with this fake Da...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074172800_pandas_python.txt
Q: How to Update or Create Heroku Config Var from Python I have a python worker process for my Heroku app. I need it to be able to update and add Config Vars for the application but I'm not sure how to do it. It's easy to read existing ones and update temporary values using os.environ but that doesn't cause them to s...
How to Update or Create Heroku Config Var from Python
I have a python worker process for my Heroku app. I need it to be able to update and add Config Vars for the application but I'm not sure how to do it. It's easy to read existing ones and update temporary values using os.environ but that doesn't cause them to save and be viewable on the settings page of my app on herok...
[ "The code starts by importing the heroku library.\nThen it creates a client object and assigns the API key to it.\nIt then gets an app object from that client, which is assigned to the variable app .\nIf os.environ['HEROKU_CONFIG_VAR_NAME'] exists in the config of this app, then it will assign os.environ['HEROKU_CO...
[ 0 ]
[]
[]
[ "heroku", "python" ]
stackoverflow_0074173068_heroku_python.txt
Q: root.destroy in tkinter for GUI not functioning properly I am trying to create a multi paged app here for a stupid little project but whenever I use the root.destroy function and then import method it words for about 3 clicks and then the program just closes. This is an example project with same code I am using to...
root.destroy in tkinter for GUI not functioning properly
I am trying to create a multi paged app here for a stupid little project but whenever I use the root.destroy function and then import method it words for about 3 clicks and then the program just closes. This is an example project with same code I am using to navigate in the acc project. main.py import tkinter as tk roo...
[ "Your main:\nfrom tkinter import *\nimport page_2\ndef run():\n window = Tk()\n def switch_to_page_2():\n window.destroy()\n page_2.run()\n # Create a button or something to call the function to switch to page_2\n window.mainloop()\n\nrun()\n\nYour page_2:\nfrom tkinter import *\nimport ma...
[ 0 ]
[]
[]
[ "frame", "python", "root", "tkinter", "user_interface" ]
stackoverflow_0074147042_frame_python_root_tkinter_user_interface.txt
Q: ImportError: pycurl: libcurl link-time ssl backend (openssl) is different from compile-time ssl backend (none/other) I wanted to run python file. But I could check this error when I ran it. ImportError: pycurl: libcurl link-time ssl backend (openssl) is different from compile-time ssl backend (none/other) My syste...
ImportError: pycurl: libcurl link-time ssl backend (openssl) is different from compile-time ssl backend (none/other)
I wanted to run python file. But I could check this error when I ran it. ImportError: pycurl: libcurl link-time ssl backend (openssl) is different from compile-time ssl backend (none/other) My system is Mac os 10.13.2 and I used python 2.7
[ "Looks like something went wrong with pycurl/openssl, try this:\npip uninstall pycurl\npip install --compile --install-option=\"--with-openssl\" pycurl\n\nif still fails, try this as well\nbrew reinstall openssl\n\n", "This was done by my fellow mac users.\n# pycurl\npip uninstall pycurl\nexport CPPFLAGS=-I/usr/l...
[ 32, 11, 5, 3, 1, 0 ]
[]
[]
[ "pycurl", "python" ]
stackoverflow_0047888757_pycurl_python.txt
Q: How do I use .any() to print the value I am looking for? If I have the following code if "ERB-776-RAD" in my_data.any(): print("I found it!") Where the my_data is something as follows: my_data = ['ERA-776-TRF','FDS-342-FHS','EBR-776-RAD'...] How would I print the actual value I am looking for (ERB-776-RAD) i...
How do I use .any() to print the value I am looking for?
If I have the following code if "ERB-776-RAD" in my_data.any(): print("I found it!") Where the my_data is something as follows: my_data = ['ERA-776-TRF','FDS-342-FHS','EBR-776-RAD'...] How would I print the actual value I am looking for (ERB-776-RAD) instead of printing "I found it"?
[ "Use the in statement to test if the list contains the string. Then you can print anything you want if it's True. You can use string formatting to insert the value dynamically (in the code below, I am using f-strings).\nmy_data = ['ERA-776-TRF','FDS-342-FHS','EBR-776-RAD']\ntarget = \"ERB-776-RAD\"\nif target in my...
[ 2 ]
[]
[]
[ "any", "python" ]
stackoverflow_0074173307_any_python.txt
Q: Convert PyTorch to CoreML I have this model: https://github.com/williamyang1991/DualStyleGAN and try to convert it to CoreML. So far I create copy of original Colab notebook and append at the end two blocks: !pip install coremltools import coremltools as ct and #@title Convert inverted image. inverted_latent = to...
Convert PyTorch to CoreML
I have this model: https://github.com/williamyang1991/DualStyleGAN and try to convert it to CoreML. So far I create copy of original Colab notebook and append at the end two blocks: !pip install coremltools import coremltools as ct and #@title Convert inverted image. inverted_latent = torch.Tensor(result_latents[0][4]...
[ "The code starts by loading the model into PyTorch.\nThe code then converts the model into CoreML format and saves it to a .mlmodel file.The code below will take the existing PyTorch model and convert it into a CoreML model with input and output features.\nThe outputs are saved in the file example.mlmodel which can...
[ 0 ]
[]
[]
[ "coremltools", "python", "pytorch" ]
stackoverflow_0074172977_coremltools_python_pytorch.txt
Q: pandas dataframe in a long format missing months I can't find a way to add the month in a long format dataframe. For example for each country, and each year I would like to have 12 values, once by month. And the value of total_points (which will be NaN) will be the same as the last one. It means that my column mon...
pandas dataframe in a long format missing months
I can't find a way to add the month in a long format dataframe. For example for each country, and each year I would like to have 12 values, once by month. And the value of total_points (which will be NaN) will be the same as the last one. It means that my column month should be range(1,13) for each country and each yea...
[ "Assuming that all rank_date are on the day 12, you can use reindex with MS frequency and then use pd.offsets to add days:\nnew_indexes = ( pd.date_range(start=f\"{df['year'].min()}\", \n end=f\"{df['year'].max() + 1}\", freq='MS', inclusive='left') + pd.offsets.Day(11) )\n\n# forward and backward fills and reinde...
[ 3, 2 ]
[]
[]
[ "date", "pandas", "python" ]
stackoverflow_0074172508_date_pandas_python.txt
Q: Scrapy Spider Trouble Navigating Through URLs I have been struggling to find a way to go about this issue: (the functions I may show do not work and are wrong but it is the more the process that I am confused about) I am trying to have my spider get the prices for all of the products on the "standard-sheds" page. ...
Scrapy Spider Trouble Navigating Through URLs
I have been struggling to find a way to go about this issue: (the functions I may show do not work and are wrong but it is the more the process that I am confused about) I am trying to have my spider get the prices for all of the products on the "standard-sheds" page. This is the link to the page which contains the pro...
[ "When you will start to journey to the each listing page/details page and after reaching to the details page and if you turn off JS then you will notice that the price portion aka the contents from the page has gone disappereared meaning dynamically loaded by JavaScript.So Scrapy can't render JS but you can grab th...
[ 0 ]
[]
[]
[ "python", "scrapy", "web_scraping" ]
stackoverflow_0074172222_python_scrapy_web_scraping.txt
Q: Copy files from one folder to another with matching names in .txt file I want to copy files from one big folder to another folder based on matching file names in a .txt file. My list.txt file contains file names: S001 S002 S003 and another big folder contains many files for ex. S001, S002, S003, S004, S005. I onl...
Copy files from one folder to another with matching names in .txt file
I want to copy files from one big folder to another folder based on matching file names in a .txt file. My list.txt file contains file names: S001 S002 S003 and another big folder contains many files for ex. S001, S002, S003, S004, S005. I only want to copy the files from this big folder that matches the file names in...
[ "I think the issue with your Python code is that with os.walk() your filename will be a list everytime, which will not be found in your filenames_to_copy.\nI'd recommend trying with os.listdir() instead as this will return a list of the names of filenames/folders as strings - easier to compare against your filename...
[ 0, 0, 0, 0, 0 ]
[]
[]
[ "python", "r", "shell" ]
stackoverflow_0057202159_python_r_shell.txt
Q: download images from a list of image links just using beautifulsoap and requests nothing else hello i am trying to download images of movies from a website using beautifulsoap and requests its any way to download them and save them with the name of the movie .jpg ? here is my code : import requests from bs4 impo...
download images from a list of image links just using beautifulsoap and requests nothing else
hello i am trying to download images of movies from a website using beautifulsoap and requests its any way to download them and save them with the name of the movie .jpg ? here is my code : import requests from bs4 import BeautifulSoup import html import pandas as pd data = requests.get("https://parade.com/1222580/s...
[ "You can do this in following way\nimport requests\nfilename = movie_image_link.split(\"/\")[-1]\nresponse = requests.get(movie_image_link)\nwith open(filename, 'wb') as f:\n f.write(response.content)\n\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "python_requests" ]
stackoverflow_0074173310_beautifulsoup_python_python_requests.txt
Q: Symmetric number of bins in qcut around zero I have a pandas dataframe with different number of integers and NaNs in each row. I would like to allocate values in each row into 8 bins - 4 bins for negative values and 4 bins for positive values per row. So, there will be different number of values in each bin per ro...
Symmetric number of bins in qcut around zero
I have a pandas dataframe with different number of integers and NaNs in each row. I would like to allocate values in each row into 8 bins - 4 bins for negative values and 4 bins for positive values per row. So, there will be different number of values in each bin per row. Any hints on how to adjust qcut function for th...
[ "If I understand correctly, you could just do a qcut on positive values and a qcut on negative values.\nFor example, given the dataframe:\n>>> df\n vals\n0 -0.456460\n1 0.448368\n2 0.186750\n3 1.056617\n4 -0.035620\n5 -0.609843\n6 0.126376\n7 0.160817\n8 -1.495441\n9 0.730763\n10 -0.005071\n1...
[ 1, 0 ]
[]
[]
[ "binning", "pandas", "python" ]
stackoverflow_0051432215_binning_pandas_python.txt
Q: "TypeError: list indices must be integers or slices, not str", when I try to extract values from request response I am getting the following error: "TypeError: list indices must be integers or slices, not str" and it's happening when I try to do the following: response = requests.get('https://randomuser.me/api?res...
"TypeError: list indices must be integers or slices, not str", when I try to extract values from request response
I am getting the following error: "TypeError: list indices must be integers or slices, not str" and it's happening when I try to do the following: response = requests.get('https://randomuser.me/api?results=1&gender=&password=upper,lower,12&exc=register,picture,id&nat=US', headers=headers).json() results = response['res...
[ "results = response['results']\nHere results is a list of dictionaries.\nUse results = results[0] to get the first dictionary.\nNow\nfirstname = results['name']['first']\nlastname = results['name']['last']\n...\n...\n\nwill work.\n" ]
[ 0 ]
[]
[]
[ "python", "python_requests", "typeerror" ]
stackoverflow_0074173410_python_python_requests_typeerror.txt
Q: Creating the greedy algorithm using recursion For an assignement I have to write a Greedy Algorithm using a recursive function, but I can't seem to figure out how to do this. The assignement is to make a route to go from one city to another, each time going to the city with the lowest distance between them, but no...
Creating the greedy algorithm using recursion
For an assignement I have to write a Greedy Algorithm using a recursive function, but I can't seem to figure out how to do this. The assignement is to make a route to go from one city to another, each time going to the city with the lowest distance between them, but no visit cities multiple times. For now I have the fo...
[ "I think what you are asking is something like this\nnodes = [0,1,2,3]\n\ndistanceMat = [\n [0,2,3,4],\n [2,0,4,5],\n [3,4,0,6],\n [4,5,6,0]\n ]\n\nroute = []\ndistance = []\nstartNode_ = 0\ndestinationNode_ = 3\n\n\n\ndef findRoute(currentNode, destinationNode):\n if currentNode not in route:\n ...
[ 1, 0 ]
[]
[]
[ "greedy", "list", "python", "recursion" ]
stackoverflow_0074173174_greedy_list_python_recursion.txt
Q: corresponding columns of a data frame in python with certain condition I tried this below code to get the top 5 in column G. Ndata = data.sort_values( 'G', ascending=False) newcol = Ndata.loc[:, 'G'].nlargest(5) newcol However, I am wondering, how do I get this code work to get the corresponding columns A, B and...
corresponding columns of a data frame in python with certain condition
I tried this below code to get the top 5 in column G. Ndata = data.sort_values( 'G', ascending=False) newcol = Ndata.loc[:, 'G'].nlargest(5) newcol However, I am wondering, how do I get this code work to get the corresponding columns A, B and C.?
[ "You can directly use nlargest on the data frame and specify which column you want to take values from. Example:\ndf = pd.DataFrame({'a': [1,2,3,4,5], 'b': [5,4,3,2,1]})\ndf.nlargest(n=3, columns='a')\n\n a b\n4 5 1\n3 4 2\n2 3 3\n\nIn your case:\ndata.nlargest(n=5, columns='G')\n\nshould work.\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074173454_pandas_python.txt
Q: how to make keyboard binding for pysimplegui work even if GUI window is in the background ( not the window in the foreground) Hi I have a question regarding GUIs , currently using pysimplegui , I want to bind a button to a keyboard key , I managed to do it , for example if I press F12 then it does the job of the b...
how to make keyboard binding for pysimplegui work even if GUI window is in the background ( not the window in the foreground)
Hi I have a question regarding GUIs , currently using pysimplegui , I want to bind a button to a keyboard key , I managed to do it , for example if I press F12 then it does the job of the button 'stop/play' on the GUI , but if the GUI is not the foreground window , keyboard key doesn't work , like for example if I open...
[ "PySimpleGUI not control and monitor input devices at the backend.\nYou can try library pynput.\nExample Code\nimport threading\nfrom pynput import keyboard\nimport PySimpleGUI as sg\n\n\ndef check(window):\n\n global h\n\n def key_f12():\n window.write_event_value('F12', None)\n\n def key_a():\n ...
[ 0 ]
[]
[]
[ "hotkeys", "pysimplegui", "python", "user_interface" ]
stackoverflow_0074173175_hotkeys_pysimplegui_python_user_interface.txt
Q: Convert integers to strings in particular rows of a pandas dataframe I am trying to convert particular values in given rows of a column into specific strings. I want the value 1 to be converted to 'never', the value 2 to be converted to 'former' and the value 3 to be converted to 'current'. However, when I run the...
Convert integers to strings in particular rows of a pandas dataframe
I am trying to convert particular values in given rows of a column into specific strings. I want the value 1 to be converted to 'never', the value 2 to be converted to 'former' and the value 3 to be converted to 'current'. However, when I run the following code, I get the error: 'list' object has no attribute 'loc'. ne...
[ "A map should work:\nnewdata['smoking_number'] = newdata['smoking_number'].map({1: 'never', 2: 'former', 3: 'current'})\n\n" ]
[ 1 ]
[]
[]
[ "boolean", "dataframe", "pandas", "python" ]
stackoverflow_0074173505_boolean_dataframe_pandas_python.txt
Q: How can I create a new list when giving intergers, and have to return hexadecimal Given the following list: list = [2,10,10,10,4,5] How can I write a function that returns the output: output = 210AA:45 I was working with this code so far, but don't know what else to add so that once a number between 10 and 15 is r...
How can I create a new list when giving intergers, and have to return hexadecimal
Given the following list: list = [2,10,10,10,4,5] How can I write a function that returns the output: output = 210AA:45 I was working with this code so far, but don't know what else to add so that once a number between 10 and 15 is repeated, return the repeated number in its hexadecimal form as in the output def int_to...
[ "A dictionary describing the mapping between decimal and hex could add readability.\nRemark: don't shadow the name of build-functions, in this case list. See doc for a complete list.\nlst = [2,10,10,10,4,5,13,15,0] # <- new testing list\n\n# dictionary for conversion\nnum2hex = {i: str(i) for i in range(10)}\nnum2h...
[ 0, 0 ]
[]
[]
[ "hex", "list", "python" ]
stackoverflow_0074173364_hex_list_python.txt
Q: How to count the number of tags of a specific word in a JSON file using python? I don't understand why I'm having issues finding the quantity of a specific tag in a JSON file. I have the code below where I'm successfully able to print out the list of tags and count how many there are. But how do I successfully mak...
How to count the number of tags of a specific word in a JSON file using python?
I don't understand why I'm having issues finding the quantity of a specific tag in a JSON file. I have the code below where I'm successfully able to print out the list of tags and count how many there are. But how do I successfully make this into a function for a specific word? Here where i'm able to make the code to o...
[ "You pass word as a parameter but later use it as a variable in the for loop. This will overwrite the word.\nAlso, I think your indentation is wrong. The last if condition should be 1 level outdented.\n" ]
[ 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074173527_json_python.txt
Q: Import data from XML using lxml I'm trying to extract data from several 1,000 XML files and compose a single df from it. The code I have so far is for a single XML extraction. from lxml import etree import pandas as pd serial = ["S1.xml"] content = serial.encode('utf-8') doc = etree.XML(content) targets = doc.x...
Import data from XML using lxml
I'm trying to extract data from several 1,000 XML files and compose a single df from it. The code I have so far is for a single XML extraction. from lxml import etree import pandas as pd serial = ["S1.xml"] content = serial.encode('utf-8') doc = etree.XML(content) targets = doc.xpath('/reiXmlPrenos') data = [] for ...
[ "from lxml import etree\nimport pandas as pd\n\nserial = [\"tmp.xml\", \"S2.xml\"]\ncolumns = [\"file\",'A', 'Z']\n\nall_data = []\nfor item in serial:\n data = []\n data.append(item)\n with open(item, 'r') as file:\n content = file.read().encode('utf-8')\n\n doc = etree.XML(content)\n\n # add...
[ 2, 2, 1 ]
[]
[]
[ "pandas", "python", "xml", "xml_parsing" ]
stackoverflow_0074172466_pandas_python_xml_xml_parsing.txt
Q: UnboundLocalError: local variable 'full_data' referenced before assignment I'm new to programming. I'm supposed to make a function that reads only dates and temperatures from the file. I would really appreciate the help. Thanks in advance. def read_data(text): data = open(text, 'r') for line in data: ...
UnboundLocalError: local variable 'full_data' referenced before assignment
I'm new to programming. I'm supposed to make a function that reads only dates and temperatures from the file. I would really appreciate the help. Thanks in advance. def read_data(text): data = open(text, 'r') for line in data: split_data = line.split(',') if line.isdigit(): date = sp...
[ "There are many issues with this code, I thought I would document them while re-writing it, however I am not sure what your code is exactly supposed to do.\ndef read_data(text):\n\n data_file = open(text, 'r')\n\n\n '''Data is not being read, you would first have to\n read the data and get it into a spe...
[ 2 ]
[ "return full_data\nhere you are a returning a variable full_data whether or not it has been declared and set to a value\nthe if statement controlls that behavior.\nso either:\ndef read_data(text):\n data = open(text, 'r')\n for line in data:\n split_data = line.split(',')\n if line.isdigit():\n ...
[ -1 ]
[ "python" ]
stackoverflow_0074173370_python.txt
Q: Clearing tkinter canvas content doesn't work I have a tkinter canvas where a label and a matplotlib plot are shown. I want to update the content of the canvas and therefore delete what was shown before. To do this I found that canvas.delete('all') is the way to do this. According to the code below the canvas is fi...
Clearing tkinter canvas content doesn't work
I have a tkinter canvas where a label and a matplotlib plot are shown. I want to update the content of the canvas and therefore delete what was shown before. To do this I found that canvas.delete('all') is the way to do this. According to the code below the canvas is filled with content and afterwards deleted. But inst...
[ "when using FigureCanvasTkAgg you have to clear the figure instead of the canvas using fig.clear().\nif you want to clear all the data in the canvas then you should destroy it with canvas.destroy() then create another canvas in its place, alternatively if you want to delete the label specifically you can just call ...
[ 1 ]
[]
[]
[ "canvas", "matplotlib", "python", "tkinter" ]
stackoverflow_0074173554_canvas_matplotlib_python_tkinter.txt
Q: fetchxml does not reuturn column in dynamics I am using Python to send a http GET request to extract the contacts associated with a segment. The segment for example called "Test Segment" which has a unique identifier "a1-b2-c3". Below is a fetchXML query I am using: <fetch mapping="logical" output-format="xml-plat...
fetchxml does not reuturn column in dynamics
I am using Python to send a http GET request to extract the contacts associated with a segment. The segment for example called "Test Segment" which has a unique identifier "a1-b2-c3". Below is a fetchXML query I am using: <fetch mapping="logical" output-format="xml-platform" version="1.0" page="1" count="5000" paging-c...
[ "This problem occurs in two diffrent scenario\n\nPermissions to field\nNull Value\n\nWhen you execute query over dynamics crm sdk, attribute with null value does not exist in entity. Same problem occurs when user does not have a permission to field.\n" ]
[ 0 ]
[]
[]
[ "dynamics_crm", "fetchxml", "http", "python" ]
stackoverflow_0073980402_dynamics_crm_fetchxml_http_python.txt
Q: Godot how to get screenshot of camera viewport as a numpy array I have set up a basic scene in Godot as below: Godot Scene with a floor, some obstacles (boxes) and a camera. (I am using python as a scripting language in Godot) I found a way to get a screenshot of the camera viewport like so: (in Python _process fu...
Godot how to get screenshot of camera viewport as a numpy array
I have set up a basic scene in Godot as below: Godot Scene with a floor, some obstacles (boxes) and a camera. (I am using python as a scripting language in Godot) I found a way to get a screenshot of the camera viewport like so: (in Python _process function...) old_clear_mode = self.viewport.get_clear_mode() self.viewp...
[ "I think the following links will help you:\nLink1\nLink2\n" ]
[ 0 ]
[]
[]
[ "godot", "numpy", "python", "screenshot", "viewport" ]
stackoverflow_0074085308_godot_numpy_python_screenshot_viewport.txt
Q: Error, while opening Numpy array in OpenCV I am currently stuck on detecting the hough lines in a precalculated NumPy array. However, it seems like I cannot figure out, why OpenCV doesn't accept the NumPy array to work with and detect the lines. The error message refers to the input channels, even so, I thought th...
Error, while opening Numpy array in OpenCV
I am currently stuck on detecting the hough lines in a precalculated NumPy array. However, it seems like I cannot figure out, why OpenCV doesn't accept the NumPy array to work with and detect the lines. The error message refers to the input channels, even so, I thought this should be detected automatically since OpenCV...
[ "As written in the comments there are several flaws in your code.\n\nUse an image size where Houghline has a chance to find lines.\nFor an image the np.random.choise array has to be converted to unit8.\nThe result can be used as grayscale image.\nThe colour \"white\" in grayscale image has value 255.\nIf you want t...
[ 0 ]
[]
[]
[ "numpy", "opencv", "python" ]
stackoverflow_0074172874_numpy_opencv_python.txt
Q: UnboundLocalError: local variable '...' referenced before assignment I have text in a file that looks like this: 146.204.224.152 - feest6811 [21/Jun/2019:15:45:24 -0700] "POST /incentivize HTTP/1.1" 302 4622 197.109.77.178 - kertzmann3129 [21/Jun/2019:15:45:25 -0700] "DELETE /virtual/solutions/target/web+services ...
UnboundLocalError: local variable '...' referenced before assignment
I have text in a file that looks like this: 146.204.224.152 - feest6811 [21/Jun/2019:15:45:24 -0700] "POST /incentivize HTTP/1.1" 302 4622 197.109.77.178 - kertzmann3129 [21/Jun/2019:15:45:25 -0700] "DELETE /virtual/solutions/target/web+services HTTP/2.0" 203 26554 156.127.178.177 - okuneva5222 [21/Jun/2019:15:45:27 -0...
[ "It seems to me that the space in (?<=- ) is meaningful, you need to escape it, i.e. you should use (?<=-\\ ).\nAlso, since you get no matches, lst1 is not initialized and returning lst1 fails eventually.\nYou can use\nimport re\ndef logs():\n lst = []\n with open(\"assets/logdata.txt\", \"r\") as file:\n ...
[ 0 ]
[]
[]
[ "function", "python", "regex" ]
stackoverflow_0074173602_function_python_regex.txt
Q: How can I add multiple graphs, select them via dropdown menu and display them with multiple y axis? I'm new using Plotly and I'm trying to plot multiple graphs, select each one of them via dropdown menu. The thing here is that there is data in the csv file that have more than one Y axis. I want them to be added as...
How can I add multiple graphs, select them via dropdown menu and display them with multiple y axis?
I'm new using Plotly and I'm trying to plot multiple graphs, select each one of them via dropdown menu. The thing here is that there is data in the csv file that have more than one Y axis. I want them to be added as I want them to be shown, the two y-axis in one of the selections in the dropdown menu. There's a problem...
[ "Well, the solution was simple at the end.\nPrevious button code:\n buttons=[]\n for study in estudiosAux:\n args = [False] * len(estudiosAux)\n args[i] = True\n \n #create a button object for the country we are on\n button = dict(label = str(study),\n ...
[ 0 ]
[]
[]
[ "local", "plotly", "python" ]
stackoverflow_0074147702_local_plotly_python.txt
Q: Python: get command name of Popen instance I have an instance of the Popen class created through subprocess.Popen. I would like to get the name of that process, but I can't find any method or instance variable that would let me get at that. For example, if I had: p = subprocess.Popen('ls') I would like to find a...
Python: get command name of Popen instance
I have an instance of the Popen class created through subprocess.Popen. I would like to get the name of that process, but I can't find any method or instance variable that would let me get at that. For example, if I had: p = subprocess.Popen('ls') I would like to find a method to give me the name of the process, some...
[ "The answer is no, until the latest versions of Python (non-stable).\nLooking at the source for 3.2.3, you can see that information isn't stored in the object (it is discarded). However, in the latest development version of Python, it has been added as subprocess.Popen.args.\nSo, presuming this makes it into 3.3, t...
[ 7, 6, 0 ]
[]
[]
[ "popen", "python", "python_2.7" ]
stackoverflow_0010989077_popen_python_python_2.7.txt
Q: Referencing a div title class with xpath selenium python So I have started messing around with Selenium in python and I am just not able to figure this xpath out. <div title class="popupBox" style="left: 0px; to p: 490px;"> <svg class="cp Drag" viewbox="0 0 24 24" style="height: 10px; width: 10px;">...</svg> ...
Referencing a div title class with xpath selenium python
So I have started messing around with Selenium in python and I am just not able to figure this xpath out. <div title class="popupBox" style="left: 0px; to p: 490px;"> <svg class="cp Drag" viewbox="0 0 24 24" style="height: 10px; width: 10px;">...</svg> <div title class="eqBox"> <div title class="ib cp"> ...
[ "Try:\ndriver.find_element(By.XPATH, '//*[@class=\"ds3 IQ\"]').text.splitlines[-1]\n\n" ]
[ 1 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074173496_python_selenium.txt
Q: Pandas Groupby and generate "duplicate" columns for each groupby value I have a vertical data frame that I am looking to make more horizontal by "duplicating" columns for each item in the groupby column. I have the following data frame: pd.DataFrame({'posteam': {0: 'ARI', 1: 'ARI', 2: 'ARI', 3: 'ARI', 4: 'ARI'...
Pandas Groupby and generate "duplicate" columns for each groupby value
I have a vertical data frame that I am looking to make more horizontal by "duplicating" columns for each item in the groupby column. I have the following data frame: pd.DataFrame({'posteam': {0: 'ARI', 1: 'ARI', 2: 'ARI', 3: 'ARI', 4: 'ARI'}, 'offense_grouping': {0: 'personnel_00', 1: 'personnel_01', ...
[ "Given the data you provide, the following would give the expected result. But there might be more complex cases in your data.\nz = (\n df\n .set_index(['posteam', 'offense_grouping'])\n .unstack('offense_grouping')\n .swaplevel(axis=1)\n .sort_index(axis=1, ascending=[True, False])\n)\n\n# or, alter...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074173531_dataframe_pandas_python.txt