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 do you index a float value in Python? Just looking for an answer to a question no amount of googling appears to resolve. if.. a = 1.23 I would like to be able to take the 1 and multiply this number yet keep the .23 How is this possible?? Thanks in advance! A: In the comments to munkhd's answer you said: I ...
How do you index a float value in Python?
Just looking for an answer to a question no amount of googling appears to resolve. if.. a = 1.23 I would like to be able to take the 1 and multiply this number yet keep the .23 How is this possible?? Thanks in advance!
[ "In the comments to munkhd's answer you said:\n\nI have want to be able to input a value as hours then convert them to minutes.\n So if it was 1.20 I would multiply the 1 by 60 then add 20.\n Im sure there must be an easier method :)\n\nThus your program will receive 1.20 as a string. So you can use string method...
[ 2, 0, 0, 0, 0 ]
[]
[]
[ "indexing", "python" ]
stackoverflow_0025919129_indexing_python.txt
Q: process json file with pandas I have a json file with objects like this: ` {"_id":"62b2eb94955fe1001d22576a","datasetName":"training-set","x":[1.062747597694397,0.010748463682830334,0.5052880048751831,0.7953124046325684,0.4599417448043823,0.5107740, 0.005278450902551413,0,0.372520387172699,0.9956972002983093],"y":...
process json file with pandas
I have a json file with objects like this: ` {"_id":"62b2eb94955fe1001d22576a","datasetName":"training-set","x":[1.062747597694397,0.010748463682830334,0.5052880048751831,0.7953124046325684,0.4599417448043823,0.5107740, 0.005278450902551413,0,0.372520387172699,0.9956972002983093],"y":"Contemporary", "team":"A"} ` can ...
[ "I'm guessing here but am assuming you want?\ndf = pd.DataFrame(data).groupby([\"team\", \"y\"])[\"x\"].apply(list).reset_index()[\"x\"].squeeze()\nprint(df)\n\nOutput:\n[1.062747597694397, 0.010748463682830334, 0.5052880048751831, 0.7953124046325684, 0.4599417448043823, 0.510774, 0.005278450902551413, 0.0, 0.37252...
[ 0 ]
[]
[]
[ "json", "pandas", "python" ]
stackoverflow_0074585220_json_pandas_python.txt
Q: how to extract text from a div block or hyperlink in BS4 imagine I have a webpage from bs4 import BeautifulSoup import requests url = 'https://www.example.com/something' result = requests.get(url).content #print(result) soup = BeautifulSoup(result,"lxml") result = soup.find_all("div", class_="header-subtitle") p...
how to extract text from a div block or hyperlink in BS4
imagine I have a webpage from bs4 import BeautifulSoup import requests url = 'https://www.example.com/something' result = requests.get(url).content #print(result) soup = BeautifulSoup(result,"lxml") result = soup.find_all("div", class_="header-subtitle") print(result) the result will be like [<div class="header-sub...
[ "You could get your goal as mentioned by MattDMo or alternativly take a look at css selectors:\n[a.get_text(strip=True) for a in soup.select('div.header-subtitle a')]\n\nTo get the text of an element you could use get_text()\nExample\nfrom bs4 import BeautifulSoup\nhtml='''\n<div class=\"header-subtitle\"><a href=\...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "python_3.x" ]
stackoverflow_0074585152_beautifulsoup_python_python_3.x.txt
Q: Getting a ValueError after running the LabelEncoder command I'm working on a ML webapp and am training data from a CSV file. When converting the data array to float the ValueError appears CODE X[:, 0] = le_country.transform(X[:,0]) X[:, 1] = le_education.transform(X[:,1]) X = X.astype(float) X ERROR During handlin...
Getting a ValueError after running the LabelEncoder command
I'm working on a ML webapp and am training data from a CSV file. When converting the data array to float the ValueError appears CODE X[:, 0] = le_country.transform(X[:,0]) X[:, 1] = le_education.transform(X[:,1]) X = X.astype(float) X ERROR During handling of the above exception, another exception occurred: ValueError...
[ "If you are fitting an encoder then you should use:\nfrom sklearn import preprocessing\nle = preprocessing.LabelEncoder()\nle.fit([1, 2, 2, 6])\n\nYou are probably using the encoder without having it been fit or the new data which you are using to train a model does not have the labels ('United States') which you f...
[ 0 ]
[]
[]
[ "jupyter_notebook", "label_encoding", "python", "scikit_learn" ]
stackoverflow_0074585304_jupyter_notebook_label_encoding_python_scikit_learn.txt
Q: How do I convert multiple JSON files with unidentical structure to a single pandas dataframe? The input is many JSON files differing in structure, and the desired output is a single dataframe. Input Description: Each JSON file may have 1 or many attackers and exactly 1 victim. The attackers key points to a list of...
How do I convert multiple JSON files with unidentical structure to a single pandas dataframe?
The input is many JSON files differing in structure, and the desired output is a single dataframe. Input Description: Each JSON file may have 1 or many attackers and exactly 1 victim. The attackers key points to a list of dictionaries. Each dictionary is 1 attacker with keys such as character_id, corporation_id, allian...
[ "You could use pd.json_normalize() to help with the heavy lifting:\nFirst, load your data:\nimport json\nimport requests\nimport tarfile\nfrom tqdm.notebook import tqdm\n\nurl = 'https://data.everef.net/killmails/2022/killmails-2022-11-22.tar.bz2'\nwith requests.get(url, stream=True) as r:\n fobj = io.BytesIO(r....
[ 0 ]
[]
[]
[ "dataframe", "json", "pandas", "python" ]
stackoverflow_0074582715_dataframe_json_pandas_python.txt
Q: Django and DRF Why isn't my password hashing I am using DRF and I have these pieces of code as models, register view and serializer But anytime I signup a user the password does not hashed and I can't see to figure out why. models.py class UserManager(BaseUserManager): def create_user(self, email, password=Non...
Django and DRF Why isn't my password hashing
I am using DRF and I have these pieces of code as models, register view and serializer But anytime I signup a user the password does not hashed and I can't see to figure out why. models.py class UserManager(BaseUserManager): def create_user(self, email, password=None, **kwargs): if not email: ra...
[ "Instead of passing plain password you should use make_password method provided by django.\nfrom django.contrib.auth.hashers import make_password\n\nmake_password(password, salt=None, hasher='default')\n\nCreates a hashed password in the format used by this application. It takes one mandatory argument: the password...
[ 0, 0, 0 ]
[]
[]
[ "django", "django_models", "django_rest_framework", "python", "python_3.x" ]
stackoverflow_0074577582_django_django_models_django_rest_framework_python_python_3.x.txt
Q: Writing a one liner code that outputs filenames with more than 10 characters and whose content has more than 10 lines Thank you all for the help before. I now had completed a task (so I thought) in order to achieve the following: I needed to write a one liner which outputs filenames that have more than 10 characte...
Writing a one liner code that outputs filenames with more than 10 characters and whose content has more than 10 lines
Thank you all for the help before. I now had completed a task (so I thought) in order to achieve the following: I needed to write a one liner which outputs filenames that have more than 10 characters and also their contents consists out of more than 10 lines. My code is the following: import os; [filename for filename ...
[ "The issue might be the order of your if statements, String.ends with returns a boolean and cannot be compared to the string, and __pycache__ files also cause errors so I added it.\nSome of the characters in ipynb files cause UnicodeDecodeError: 'charmap' codec can't decode errors and decoding in Latin-1 seemed to ...
[ 1 ]
[]
[]
[ "filenames", "listdir", "python" ]
stackoverflow_0074585327_filenames_listdir_python.txt
Q: I need to read a file and turn it into a dictionary I have a file of recipes banana pancake 1 cups of flour 2 tablespoons of sugar 1 eggs 1 cups of milk 3 teaspoons of cinnamon 2 teaspoons of baking powder 0 slices of bread 2 bananas 0 apples 0 peaches And I need to create a dictionary, where the key is the name ...
I need to read a file and turn it into a dictionary
I have a file of recipes banana pancake 1 cups of flour 2 tablespoons of sugar 1 eggs 1 cups of milk 3 teaspoons of cinnamon 2 teaspoons of baking powder 0 slices of bread 2 bananas 0 apples 0 peaches And I need to create a dictionary, where the key is the name of the ingredient and the value is the respective unit. E...
[ "Running your code generates an error that looks something like this:\nTypeError Traceback (most recent call last)\n<ipython-input-14-08149fb7c88a> in <module>\n 6 else:\n 7 line1 = line.split(' ') #splits lines into lists\n----> 8 d[line1[1:]] = line1[0] #grabs ...
[ 0, 0 ]
[]
[]
[ "dictionary", "python", "python_3.x" ]
stackoverflow_0074585167_dictionary_python_python_3.x.txt
Q: Stack python function debugging issue I have implemented the stack in python code. class stack: arrlen = 0 def __init__(self,arr,poin): self.arr = arr self.poin = poin arrlen = len(self.arr) def push(obj): self.poin = (self.poin+1)%arrlen self.arr[self.poin] = o...
Stack python function debugging issue
I have implemented the stack in python code. class stack: arrlen = 0 def __init__(self,arr,poin): self.arr = arr self.poin = poin arrlen = len(self.arr) def push(obj): self.poin = (self.poin+1)%arrlen self.arr[self.poin] = obj def pop(): self.poin = (sel...
[ "self is the first argument of every python class method. Therefore, your method push should look like something like:\ndef push(self, obj):\n\n self.poin = (self.poin+1)%arrlen\n\n self.arr[self.poin] = obj\n\nAnd even the methods where you don't want to take any inputs, you should put self as the only param...
[ 1 ]
[]
[]
[ "debugging", "python", "stack" ]
stackoverflow_0074585374_debugging_python_stack.txt
Q: Drawing recursive circles PYTHON I can't get to draw the other smaller circles. Using recursive circles it's confusing me. How can I draw the rest of the circles? I called recursively the function draw_fractal_circles but it only draws one more smaller round of circles. Wanted result: My result: import turtle d...
Drawing recursive circles PYTHON
I can't get to draw the other smaller circles. Using recursive circles it's confusing me. How can I draw the rest of the circles? I called recursively the function draw_fractal_circles but it only draws one more smaller round of circles. Wanted result: My result: import turtle def centered_circle(circle_radius, tur...
[ "You are overthinking some parts of your program.\nThe recursive_circles() function only needs to draw its own circle, move to other relative positions and call recursive_circles() to draw all the other circles down from there,\nAlso the radius should be halved in size on forward calls.\nimport turtle\n\ndef center...
[ 1 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0074585281_python_recursion.txt
Q: Adding markers to Sympy plots I have created two lines in a Sympy plot and would to add markers to each line. Using the tip from this post, the following does what I expect. import sympy as sp x = sp.symbols('x') sp.plot(x,-x, markers=[{'args' : [5,5, 'r*'], 'ms' : 10}, {'args' : [5,-5,'r*'...
Adding markers to Sympy plots
I have created two lines in a Sympy plot and would to add markers to each line. Using the tip from this post, the following does what I expect. import sympy as sp x = sp.symbols('x') sp.plot(x,-x, markers=[{'args' : [5,5, 'r*'], 'ms' : 10}, {'args' : [5,-5,'r*'],'ms' : 10}]) However, when I bre...
[ "Sadly, the extend method only consider the data series, not the markers. You can index the plot object in order to access the data series and apply a label. For example:\nfrom sympy import *\nvar(\"x\")\np = plot(x,-x, markers=[{'args' : [5, 5, 'r*'], 'ms' : 10, \"label\": \"a\"},\n {'args' : ...
[ 1 ]
[]
[]
[ "python", "sympy" ]
stackoverflow_0074584653_python_sympy.txt
Q: Exploding a Pandas Crosstab Table I have created a pandas crosstab table. My data has groupings as shown along the left column, where a particular row can correspond to more than one organization. I would like to 'explode' these out such that values in [org1, org2] would be counted in both org1 and org2. Therefore...
Exploding a Pandas Crosstab Table
I have created a pandas crosstab table. My data has groupings as shown along the left column, where a particular row can correspond to more than one organization. I would like to 'explode' these out such that values in [org1, org2] would be counted in both org1 and org2. Therefore, I am trying to display one row in the...
[ "Have you tried using explode before using crosstab ?\n#import ast\n#df['ColName2007.1099']=df['ColName2007.1099'].apply(ast.literal_eval)\n\ndf = df.explode('ColName2007.1099')\ndf = pd.crosstab(df['ColName2007.1099'],columns=df['Category'],margins=True)\nprint(df)\n'''\nCategory Class A Class B Class D...
[ 0 ]
[]
[]
[ "list", "pandas", "pivot_table", "python", "python_3.x" ]
stackoverflow_0074584953_list_pandas_pivot_table_python_python_3.x.txt
Q: Can a parquet file exceed 2.1GB? I'm having an issue storing a large dataset (around 40GB) in a single parquet file. I'm using the fastparquet library to append pandas.DataFrames to this parquet dataset file. The following is a minimal example program that appends chunks to a parquet file until it crashes as the f...
Can a parquet file exceed 2.1GB?
I'm having an issue storing a large dataset (around 40GB) in a single parquet file. I'm using the fastparquet library to append pandas.DataFrames to this parquet dataset file. The following is a minimal example program that appends chunks to a parquet file until it crashes as the file-size in bytes exceeds the int32 th...
[ "Finally, I figured out that I was running into a genuine bug in the python library fastparquet, which resulted in a fix in the main library.\nThis is a link to the salient issue on Github.\nThe commit in which the issue is fixed is 89d16a2.\n" ]
[ 1 ]
[]
[]
[ "dataset", "fastparquet", "machine_learning", "parquet", "python" ]
stackoverflow_0074562453_dataset_fastparquet_machine_learning_parquet_python.txt
Q: Writing a constraint with cplex python I shared the parameters, variables and notation of the model: I have difficulty in writing equation 7, which is one of the constraints of the model, with cplex. The code block I wrote is as follows: mdl.add_constraints(T[i, j, k] >= mdl.sum(p[l]*y[i, l, s] + s[l]*x[i, l, s]...
Writing a constraint with cplex python
I shared the parameters, variables and notation of the model: I have difficulty in writing equation 7, which is one of the constraints of the model, with cplex. The code block I wrote is as follows: mdl.add_constraints(T[i, j, k] >= mdl.sum(p[l]*y[i, l, s] + s[l]*x[i, l, s] for l in N for s in ???)- d[j] - 100000*(...
[ "The \"kicker\" (hard part) in that constraint is the fact that the range of the sum over s is bounded by the index k. Because your indices are numerical, you could just use a range command to generate the appropriate subset.\ncaution: you have 2 elements named s in there, so you will need to rename one. I chang...
[ 0 ]
[]
[]
[ "constraints", "cplex", "optimization", "python" ]
stackoverflow_0074585013_constraints_cplex_optimization_python.txt
Q: AttributeError at /sign-up and /sign-in 'WSGIRequest' object has no attribute 'is_ajax' I am getting this problem, any help will be appreciated, Im getting an arror trying to sign-in or sign-up.Error bellow. AttributeError at /sign-up 'WSGIRequest' object has no attribute 'is_ajax' I know that function is deprecia...
AttributeError at /sign-up and /sign-in 'WSGIRequest' object has no attribute 'is_ajax'
I am getting this problem, any help will be appreciated, Im getting an arror trying to sign-in or sign-up.Error bellow. AttributeError at /sign-up 'WSGIRequest' object has no attribute 'is_ajax' I know that function is depreciated now, but i can't seem to fix the issue. mixins.py class AjaxFormMixin(object): ''' ...
[ "Use it like if request.headers.get('x-requested-with') == 'XMLHttpRequest': everywhere so:\ndef profile_view(request):\n '''\n function view to allow users to update their profile\n '''\n user = request.user\n up = user.userprofile\n\n form = UserProfileForm(instance=up)\n\n if request.headers...
[ 2, 1 ]
[]
[]
[ "ajax", "django", "django_forms", "django_views", "python" ]
stackoverflow_0074585414_ajax_django_django_forms_django_views_python.txt
Q: Multiple Linear Regression Using Scikit-learn Error I'm relatively new to Python and I am trying to make a Multiple Linear Regression model which has two predictor variables and one dependent. While doing my research on this, I found that Scikit provides a class to do this. I tried to get a model for my variables ...
Multiple Linear Regression Using Scikit-learn Error
I'm relatively new to Python and I am trying to make a Multiple Linear Regression model which has two predictor variables and one dependent. While doing my research on this, I found that Scikit provides a class to do this. I tried to get a model for my variables and I got the following message: Shape of passed values i...
[ "Would be great if you could also provide the input of the data, but even without it's most likely due to the fact that you use index column from your file. You should remove it and it will be fine.\nIf you can give the example of data that you use (columns), will be able to check it further.\nI rerun your code, wi...
[ 0 ]
[]
[]
[ "jupyter_notebook", "linear_regression", "machine_learning", "python", "scikit_learn" ]
stackoverflow_0074585492_jupyter_notebook_linear_regression_machine_learning_python_scikit_learn.txt
Q: How does Waitress handle concurrent tasks? I'm trying to build a python webserver using Django and Waitress, but I'd like to know how Waitress handles concurrent requests, and when blocking may occur. While the Waitress documentation mentions that multiple worker threads are available, it doesn't provide a lot of...
How does Waitress handle concurrent tasks?
I'm trying to build a python webserver using Django and Waitress, but I'd like to know how Waitress handles concurrent requests, and when blocking may occur. While the Waitress documentation mentions that multiple worker threads are available, it doesn't provide a lot of information on how they are implemented and how...
[ "Here's how the event-driven asynchronous servers generally work:\n\nStart a process and listen to incoming requests. Utilizing the event notification API of the operating system makes it very easy to serve thousands of clients from single thread/process.\nSince there's only one process managing all the connections...
[ 11, 0 ]
[]
[]
[ "django", "python", "waitress", "wsgi" ]
stackoverflow_0059838433_django_python_waitress_wsgi.txt
Q: How can I access primary key in template tag? I am trying to create an update view that allows users to update their data. I am trying to access the data by using primary keys. My problem is that I do not know the syntax to implement it. models.py class Detail(models.Model): """ This is the one for model.p...
How can I access primary key in template tag?
I am trying to create an update view that allows users to update their data. I am trying to access the data by using primary keys. My problem is that I do not know the syntax to implement it. models.py class Detail(models.Model): """ This is the one for model.py """ username = models.ForeignKey(User, on...
[ "Answer to the original question\n\nHow can I access primary key in template tag?\n\nWell, you have to pass it to the view that renders the template, either through the context, or in this case, since you need it in the success page, which you are getting to via a redirect, send it as a parameter in your redirect.\...
[ 2, 1, 0 ]
[]
[]
[ "django", "django_forms", "django_templates", "django_urls", "python" ]
stackoverflow_0074578041_django_django_forms_django_templates_django_urls_python.txt
Q: Can I reconnect to the main window with PyWinAuto? I reach open browser, click in the button on the screen and click in the button of the pop up window without problems. The only problem is, when I close pop up window clicking the button "Close Tor Browser", I can't reconnect with my previous window (the main and ...
Can I reconnect to the main window with PyWinAuto?
I reach open browser, click in the button on the screen and click in the button of the pop up window without problems. The only problem is, when I close pop up window clicking the button "Close Tor Browser", I can't reconnect with my previous window (the main and first window). Any tips?? from pywinauto.application imp...
[ "Best bet to contorl (assuming extension has interactable popout [e.g. options, whatever, once you click/depress specfiiced hotkey) as follows (kukos to BrowserStack folk, and RobWuRobWu - CRX / page taxomy etc.).\nThis is the soluiton I explore here - will leave link in comment for altenrative concerning pywinauto...
[ 0 ]
[]
[]
[ "automation", "bots", "python", "pywinauto", "tor" ]
stackoverflow_0071905553_automation_bots_python_pywinauto_tor.txt
Q: Compare and match range of timestamps in pandas two different dataframes How to compare and match beginning and end of two ranges of timestamps in two different dataframes, when the frequency of timestamps varies, and it is not known which range starts earlies and finishes later. Then discard unmatched beginning ...
Compare and match range of timestamps in pandas two different dataframes
How to compare and match beginning and end of two ranges of timestamps in two different dataframes, when the frequency of timestamps varies, and it is not known which range starts earlies and finishes later. Then discard unmatched beginning and end, so the two ranges are the same. Easy to do it manually in a txt file,...
[ "New answer on the new example data:\nThe problem with merging here is that you have duplicated index Dates, so there can't be unambigous assignment done.\nBut you could do it seperately as you suggested in the beginning.\nYou said you don't know which of both df's have start earlier or end later.\nFind the min val...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074585368_pandas_python.txt
Q: UserWarning: X does not have valid feature names, but DecisionTreeClassifier was fitted with feature names I am learning machine learning from Programming with Mosh channel. I got desired output in this case. output=array(['HipHop', 'Acoustic', 'Classical'], dtype=object) but there is a warning like this and I ca...
UserWarning: X does not have valid feature names, but DecisionTreeClassifier was fitted with feature names
I am learning machine learning from Programming with Mosh channel. I got desired output in this case. output=array(['HipHop', 'Acoustic', 'Classical'], dtype=object) but there is a warning like this and I cannot find which part is wrong. C:\Users\User\anaconda3\lib\site-packages\sklearn\base.py:450: UserWarning: X doe...
[ "After line 5, before \"model = DecisionTreeClassifier\" add two more lines:\nX = X.values\ny = y.values\n\nA more in-depth solution and explanation can be found here:\nUserWarning: X does not have valid feature names, but LogisticRegression was fitted with feature names\n" ]
[ 0 ]
[]
[]
[ "decision_tree", "python", "scikit_learn" ]
stackoverflow_0073914558_decision_tree_python_scikit_learn.txt
Q: How to extract only the pixels of an image where it is masked? (Python numpy array operation) I have an image and its corresponding mask for the cob as numpy arrays: The image numpy array has shape (332, 107, 3). The mask is Boolean (consists of True/False) and has this shape as binary (332, 107). [[False False ...
How to extract only the pixels of an image where it is masked? (Python numpy array operation)
I have an image and its corresponding mask for the cob as numpy arrays: The image numpy array has shape (332, 107, 3). The mask is Boolean (consists of True/False) and has this shape as binary (332, 107). [[False False False ... False False False] [False False False ... False False False] [False False False ... Fa...
[ "Thanks to the useful comment of M.Setchell, I was able to find the answer myself.\nBasically, I had to expand the dimensions of the mask array (2D) to the same dimension of the image (3D with 3 color channels).\ny=np.expand_dims(mask,axis=2)\nnewmask=np.concatenate((y,y,y),axis=2)\n\nThen I had to simply multiply ...
[ 5, 0 ]
[]
[]
[ "image", "mask", "numpy", "python" ]
stackoverflow_0059160337_image_mask_numpy_python.txt
Q: Call a function to replace every regex in a file I have a some entries in a file and I want to modify specific regex values. This file must remain identical to the original except the value I want to replace. Here is my file: dn: uid=alan,cn=users,dc=mysite,dc=dc=com objectclass: organizationalPerson objectclass: ...
Call a function to replace every regex in a file
I have a some entries in a file and I want to modify specific regex values. This file must remain identical to the original except the value I want to replace. Here is my file: dn: uid=alan,cn=users,dc=mysite,dc=dc=com objectclass: organizationalPerson objectclass: person objectclass: top objectclass: inetOrgPerson uid...
[ "You can try the following:\nwith open('file.txt', 'r') as f:\n content = f.read()\n\nfor old_value, new_value in Dict.items():\n content = content.replace(old_value, new_value)\n\nwith open('file.txt', 'w') as f:\n f.write(content)\n\n" ]
[ 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074585539_python_regex.txt
Q: Downloading Shares Gives "JSONDecodeError: Expecting value: line 1 column 1 (char 0)" I am downloading shared from Finance Yahoo. There is this error prompts: JSONDecodeError: Expecting value: line 1 column 1 (char 0) I have checked all the similar questions and applied but all in vain, that's why asking this que...
Downloading Shares Gives "JSONDecodeError: Expecting value: line 1 column 1 (char 0)"
I am downloading shared from Finance Yahoo. There is this error prompts: JSONDecodeError: Expecting value: line 1 column 1 (char 0) I have checked all the similar questions and applied but all in vain, that's why asking this question again specifying my problem. I am downloading shares details of the top 100 current s...
[ "The error\nPer your error trace, the below line is throwing an error:\n\nctn = d.json()['timeseries']['result']\n\nThe error is trying to tell you that the data in d is not JSON-formatted:\n\nJSONDecodeError: Expecting value: line 1 column 1 (char 0)\nSo basically the very first character (line 1, column 1) is not...
[ 0 ]
[]
[]
[ "http_status_code_403", "json", "python", "yahoo_finance", "yfinance" ]
stackoverflow_0074585557_http_status_code_403_json_python_yahoo_finance_yfinance.txt
Q: `DefaultCredentialsError` when attempting to import google cloud libraries in python I am attempting to import google-cloud and big-query libraries and running into default credentials error. I have attempted to set the credentials by downloading the json file from cloud portal and specifying the path to the file....
`DefaultCredentialsError` when attempting to import google cloud libraries in python
I am attempting to import google-cloud and big-query libraries and running into default credentials error. I have attempted to set the credentials by downloading the json file from cloud portal and specifying the path to the file. ## Google Big Query %reload_ext google.cloud.bigquery from google.cloud import bigquery b...
[ "Default Credentials (ADC) is a method of searching for credentials.\nYour code is setting the environment after the client has attempted to locate credentials. That means the client failed to locate credentials before you set up credentials. A quick solution is to move the line with bigquery.Client(...) to be afte...
[ 1 ]
[]
[]
[ "google_bigquery", "google_cloud_platform", "python" ]
stackoverflow_0074585427_google_bigquery_google_cloud_platform_python.txt
Q: Python datetime.fromisoformat requires colon in tzinfo? I am parsing date+time values in isoformat generated by another application, which look like this: "2022-07-31T01:51:05-0400" Note: The time zone info part is "-0400", without a colon. But I can't see to use datetime.fromisoformat to do this: # This works fi...
Python datetime.fromisoformat requires colon in tzinfo?
I am parsing date+time values in isoformat generated by another application, which look like this: "2022-07-31T01:51:05-0400" Note: The time zone info part is "-0400", without a colon. But I can't see to use datetime.fromisoformat to do this: # This works fine (with a colon): datetime.fromisoformat("2022-07-31T01:51:...
[ "You could do a workaround by making sure the colon is in the UTC offset portion of the string:\ndef fix_iso(s):\n pos = len(\"2022-07-31T01:51:05-0400\") - 2 # take off end \"00\"\n if len(s) == pos: # missing minutes completely\n s += \":00\"\n elif s[pos:pos+1] != ':': # m...
[ 0 ]
[]
[]
[ "datetime", "iso8601", "python" ]
stackoverflow_0074585548_datetime_iso8601_python.txt
Q: Sprite not being drawn I am a beginner programmer practicing with Python. I am trying to make a simple game, what I have so far is just adding the character sprite onto the map. What I'm trying to do is when no keys are being pressed, that the character sprite continuously switches between two animations. When run...
Sprite not being drawn
I am a beginner programmer practicing with Python. I am trying to make a simple game, what I have so far is just adding the character sprite onto the map. What I'm trying to do is when no keys are being pressed, that the character sprite continuously switches between two animations. When running the game, it just loads...
[ "You must do the update in the application loop and not in the event loop. The application loop is executed once per frame, the event loop is executed only when an event occurs. Also clear the display and update the display every frame and limit the frames per second with pygame.time.Clock.tick.\nAnd very important...
[ 2 ]
[]
[]
[ "pygame", "pygame_surface", "python" ]
stackoverflow_0074585698_pygame_pygame_surface_python.txt
Q: Randomly Replacing Characters in String with Character Other than the Current Character Suppose that I have a string that I would like to modify at random with a defined set of options from another string. First, I created my original string and the potential replacement characters: string1 = "abcabcabc" replaceme...
Randomly Replacing Characters in String with Character Other than the Current Character
Suppose that I have a string that I would like to modify at random with a defined set of options from another string. First, I created my original string and the potential replacement characters: string1 = "abcabcabc" replacement_chars = "abc" Then I found this function on a forum that will randomly replace n characte...
[ "In the function you retrieved, replacing:\nword[index] = random.choice(replacement_chars)\n\nwith\nword[index] = random.choice(replacement_chars.replace(word[index],'')\n\nwill do the job. It simply replaces word[index] (the char you want to replace) with an empty string in the replacement_chars string, effectivel...
[ 3 ]
[]
[]
[ "python", "random", "string" ]
stackoverflow_0074585606_python_random_string.txt
Q: combine python lists into sql table I have two lists which I want to combine into an sql table using pandas.read_sql. I tried using unnest, but it gives me the wrong output. Attempt below: import pandas as pd from sqlalchemy import create_engine engine = create_engine( "postgresql+psycopg2://postgres:password...
combine python lists into sql table
I have two lists which I want to combine into an sql table using pandas.read_sql. I tried using unnest, but it gives me the wrong output. Attempt below: import pandas as pd from sqlalchemy import create_engine engine = create_engine( "postgresql+psycopg2://postgres:password@localhost:5432/database" ) list1 = ["a"...
[ "df_expected \n list1 list2\n0 a 1\n1 b 2\n2 c 3\n\nYour original query:\ndf_query = pd.read_sql_query(\n \"\"\"\n select *...
[ 1 ]
[]
[]
[ "pandas", "postgresql", "python", "sql" ]
stackoverflow_0074585449_pandas_postgresql_python_sql.txt
Q: Cannot display images or play sound in my .exe if it is in a different folder When I convert my file in .exe and I want for example an image to be displayed or a sound to be played on my app I am forced to put them in the same folder otherwise the image will not appear and the sound will not play. How can I displa...
Cannot display images or play sound in my .exe if it is in a different folder
When I convert my file in .exe and I want for example an image to be displayed or a sound to be played on my app I am forced to put them in the same folder otherwise the image will not appear and the sound will not play. How can I display a image(png)/play a sound (a mp3) if my .exe and the used ressources (the image a...
[ "file='myimage.png' is what's called a relative path - since there are no folders listed before, the app will look in the same folder where the .exe is executed from.\nFrom the same machine\n\nuse absolute paths to the files (e.g. C:\\Temp\\myImage.png), or\nchange the working directory to another location at runti...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074585658_python_tkinter.txt
Q: Python Socket Not Reading UDP Packets on Jetson Hardware II have UDP packets that are being sent to my device via an Ethernet connection. I am attempting to read them data using the socket library in Python (version 3.8.10); however, despite them being displayed on the device when I run tcpdump, my Python program ...
Python Socket Not Reading UDP Packets on Jetson Hardware
II have UDP packets that are being sent to my device via an Ethernet connection. I am attempting to read them data using the socket library in Python (version 3.8.10); however, despite them being displayed on the device when I run tcpdump, my Python program never receives the data, and I'm not sure why. I want to recei...
[ "The packets that were being sent to the computer were sent by a Velodyne LiDAR. There are instructions to manually set the IP Address of the ethernet connection that we are receiving data from and following those enabled me to use the code that I wrote above and read packets from the LiDAR.\n" ]
[ 0 ]
[]
[]
[ "jetson_xavier", "python", "sockets", "ubuntu", "udp" ]
stackoverflow_0074585619_jetson_xavier_python_sockets_ubuntu_udp.txt
Q: How to display which key holds the most number of values and the corresponding total? I have a dictionary with four keys and would like to display which key has the most elements or values in them and how many values is stored. my dictionary looks like this {'rank': [1, 2, 3, 4, 5], 'trolley': [5, 10, 15, 25, 30],...
How to display which key holds the most number of values and the corresponding total?
I have a dictionary with four keys and would like to display which key has the most elements or values in them and how many values is stored. my dictionary looks like this {'rank': [1, 2, 3, 4, 5], 'trolley': [5, 10, 15, 25, 30], 'ward': [0, 12, 10, 8, 3], 'patients': [200, 100, 1000, 500, 375] in the variable explore...
[ "Please correct me if I interpret it wrong. Till now, you have been able to execute the code you have provided, with an exception that the values being printed is the whole list and not the maximum value among the list.\nSecondly, you have mentioned that you are trying to display the amount of rows rather than the ...
[ 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074585586_dictionary_python.txt
Q: Python Lists , FIles, For Loops, Index I am comfused with how to tackle this, I have done the first few parts by opening the file, converting it to a list and completing the first prompt but now I dont really understand how to do this. The prompt for this part is: All Words that Have a User Chosen Letter in a Spec...
Python Lists , FIles, For Loops, Index
I am comfused with how to tackle this, I have done the first few parts by opening the file, converting it to a list and completing the first prompt but now I dont really understand how to do this. The prompt for this part is: All Words that Have a User Chosen Letter in a Specified Location This task builds on the first...
[ "I think there are three steps to your second task:\n\nGet the input letter and index.\nIterate over the list of words.\nCheck each word to see if the letter is in the desired index and print the word if so.\n\nYou have part of number 1 and all of number 2 handled already.\nTo finish the first step, you need to con...
[ 0 ]
[]
[]
[ "file", "for_loop", "list", "python" ]
stackoverflow_0074579068_file_for_loop_list_python.txt
Q: Avoid globals in tkinter I made a simple code and my question is if is there a way to avoid globals in tkinter in this kind of scenario: root = Tk() root.title('Main') root.minsize(400, 450) toggle = True def change_now(): global toggle root.config(bg='blue') if toggle else root.config(bg='black') to...
Avoid globals in tkinter
I made a simple code and my question is if is there a way to avoid globals in tkinter in this kind of scenario: root = Tk() root.title('Main') root.minsize(400, 450) toggle = True def change_now(): global toggle root.config(bg='blue') if toggle else root.config(bg='black') toggle = not toggle my_button...
[ "In this specific case, there is a way: use tkinter variables, instead of globals\nfrom tkinter import Tk, Button, BooleanVar\nroot = Tk()\nroot.title('Main')\nroot.minsize(400, 450)\n\ntoggle_tkinter = BooleanVar(value=True)\n\ndef change_now():\n root.config(bg='blue') if toggle_tkinter.get() else root.config(...
[ 1, 0 ]
[]
[]
[ "global_variables", "python", "tkinter", "variables" ]
stackoverflow_0074577606_global_variables_python_tkinter_variables.txt
Q: Writing data to a file in python I keep getting this error: FileNotFoundError: [Errno 2] No such file or directory: 'Bayofagbenro.txt' Here is my code: def main(): outfile = open('Bayofagbenro.txt') Bayofagbenro =outfile.write ('Modupeola\n') Bayofagbenro =outfile.w ('Ayobami\n') Bayofagbenro =out...
Writing data to a file in python
I keep getting this error: FileNotFoundError: [Errno 2] No such file or directory: 'Bayofagbenro.txt' Here is my code: def main(): outfile = open('Bayofagbenro.txt') Bayofagbenro =outfile.write ('Modupeola\n') Bayofagbenro =outfile.w ('Ayobami\n') Bayofagbenro =outfile.w ('AKintola\n') Bayofagbenro...
[ "Try something like this:\ndef main():\n with open('Bayofagbenro.txt', 'w') as f:\n f.write('Modupeola\\n')\n f.write('Ayobami\\n')\n f.write('AKintola\\n')\n f.write('Omonike\\n')\n f.write('Fehintoluwa\\n')\n f.write('Modupeola is 44yrs, Ayobami is 42 years, AKintola i...
[ 1 ]
[]
[]
[ "file", "python" ]
stackoverflow_0074585759_file_python.txt
Q: Using python to solve for value that meets a condition new true value that meets the condition = v previous true value = vprev I am trying to look for a v so that hash of str(((power(v,2))+(power(vprev, 3))) begins with ee I tried this import hashlib values_list = []# a list where v and prev will be solved = False...
Using python to solve for value that meets a condition
new true value that meets the condition = v previous true value = vprev I am trying to look for a v so that hash of str(((power(v,2))+(power(vprev, 3))) begins with ee I tried this import hashlib values_list = []# a list where v and prev will be solved = False v = 1 # to start looping from 1 while not solved: for ...
[ "Commenting your own code:\n# ...\nsolved = False\nv = 1 # to start looping from 1\n\nwhile solved:\n # This block is never executed: the `while` condition-check fails since the initial state of `solved` is `False`\n\nprint(values_list)\n\nyou'll probably want to use while not solved: instead\n", "import hashl...
[ 0, 0 ]
[]
[]
[ "hash", "list", "loops", "python", "solver" ]
stackoverflow_0074585664_hash_list_loops_python_solver.txt
Q: What is the deference bewteen zeromq binding with * and 127.0.0.1 As title, here is 2 ways to binding a zeromq socket. socket.bind("tcp://*:port") socket.bind("tcp://127.0.0.1:port") Both these two way work for me, but I am still curious about it. A: In general, the server binds to an endpoint and the client co...
What is the deference bewteen zeromq binding with * and 127.0.0.1
As title, here is 2 ways to binding a zeromq socket. socket.bind("tcp://*:port") socket.bind("tcp://127.0.0.1:port") Both these two way work for me, but I am still curious about it.
[ "In general, the server binds to an endpoint and the client connects to an endpoint as follows:\n# Server\nsocket = context.socket(zmq.REP)\nsocket.bind(\"tcp://*:5555\")\n\nconnect the socket:\n# Client\nsocket = context.socket(zmq.REQ)\nsocket.connect(\"tcp://localhost:5555\")\n\nBy binding to 127.0.0.1 you restr...
[ 0, 0 ]
[]
[]
[ "python", "pyzmq", "zeromq" ]
stackoverflow_0074561434_python_pyzmq_zeromq.txt
Q: RegexValidator in Django Models not validating email correctly I'm making a django form with an email field and using a RegexValidator and want a specific format of of the email but it seems to be not validating the field correctly email = models.EmailField( unique=True, validators=[ ...
RegexValidator in Django Models not validating email correctly
I'm making a django form with an email field and using a RegexValidator and want a specific format of of the email but it seems to be not validating the field correctly email = models.EmailField( unique=True, validators=[ RegexValidator( regex=r"^[2][2][a-zA-Z]{3}\d{3}@[n...
[ "The [nith.ac.in] does not parse literal text, it parses any character in te group, meaning it can end with a sequence of ns, is, nis, etc.\nYour regex should look like:\nemail = models.EmailField(\n unique=True,\n validators=[\n RegexValidator(\n regex=r'^[2][2][a-zA-Z]{3}\\d{3}@nith[.]ac[....
[ 1 ]
[]
[]
[ "django", "django_models", "django_validation", "python" ]
stackoverflow_0074585815_django_django_models_django_validation_python.txt
Q: Two threads kept running without completed in Python I'm trying to get the result below running 2 threads alternately. *Thread A prints Step 1 and Step 3 and thread B prints Step 2 and Step 4 (I use Python 3.8.5): Step 1 Step 2 Step 3 Step 4 So, with global variables, locks and while statements, I created the cod...
Two threads kept running without completed in Python
I'm trying to get the result below running 2 threads alternately. *Thread A prints Step 1 and Step 3 and thread B prints Step 2 and Step 4 (I use Python 3.8.5): Step 1 Step 2 Step 3 Step 4 So, with global variables, locks and while statements, I created the code below to try to get the result above: import threading l...
[]
[]
[ "In both second while loops you have an extra break that terminates the execution after first run. (outside the if-block). And you have also souperflous extra outside-while loops.\n\ndef test1():\n global flow\n while True: # <--- DELETE ME\n while True:\n if flow == \"Step 1\":\n ...
[ -1, -1 ]
[ "alternate", "multithreading", "python", "python_3.x", "python_multiprocessing" ]
stackoverflow_0074585534_alternate_multithreading_python_python_3.x_python_multiprocessing.txt
Q: pandas read_sql_query with params matching multiple columns I'm trying to query a table using pandas.read_sql_query, where I want to match multiple columns to python lists passed in as param arguments. Running into various psycopg2 errors when trying to accomplish this. Ideally, I would provide a reproducible exam...
pandas read_sql_query with params matching multiple columns
I'm trying to query a table using pandas.read_sql_query, where I want to match multiple columns to python lists passed in as param arguments. Running into various psycopg2 errors when trying to accomplish this. Ideally, I would provide a reproducible example, but unfortunately, that's not possible here due to the SQL c...
[ "To make a comparison of exact pairs you could convert your array to a dictionary then to JSON, taking advantage of PostgreSQL JSON functions and operators, like this:\n#combine lists into a dictionary then convert to json\njson1 = json.dumps(dict(zip(list1, list2)))\n\nthen query request should be\ndf = pd.read_sq...
[ 1, 0 ]
[]
[]
[ "pandas", "postgresql", "python" ]
stackoverflow_0074575599_pandas_postgresql_python.txt
Q: how to do a continuous sum with python pandas I would like to do the same in python pandas as shown on the picture. pandas image This is sum function where the first cell is fixed and the formula calculates "continuous sum". I tried to create pandas data frame however I did not manage to do this exactly. A: I wo...
how to do a continuous sum with python pandas
I would like to do the same in python pandas as shown on the picture. pandas image This is sum function where the first cell is fixed and the formula calculates "continuous sum". I tried to create pandas data frame however I did not manage to do this exactly.
[ "I would refer to pandas cumsum()\nFor example:\ndf['NEW_COLUMN_CUMULATED'] = df['OLD_COLUMN'].cumsum()\n\n", "You can use DataFrame.cumsum() to achieve what you want:\n\nimport pandas as pd\ndf = pd.DataFrame([10, 20, 30])\nprint(df.cumsum())\n\n\n", "Based on the example you shared, use pandas.Series.cumsum w...
[ 0, 0, 0, 0 ]
[]
[]
[ "excel", "function", "pandas", "python", "sum" ]
stackoverflow_0074581136_excel_function_pandas_python_sum.txt
Q: UNIQUE constraint failed: auth_user.username while trying to register the user in django I have written following set of code in views.py of my project but when I try to register the user info as an object in the database, above mentioned error arrived views.py from django.shortcuts import render from django.http ...
UNIQUE constraint failed: auth_user.username while trying to register the user in django
I have written following set of code in views.py of my project but when I try to register the user info as an object in the database, above mentioned error arrived views.py from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib.auth impor...
[ "Most probably the username already exists in the database as you haven't used django forms so maybe the validation isn't done correctly with your manually defined html fields.\nAlso create_user() method doesn't require save() method to be called for updating the fields, the thing you can do is save(commit=False) b...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074585791_django_python.txt
Q: pandas merge two dataframe and sort by compared column in adjacent column I compare two dataframe and result can be shown below; import pandas as pd exam_1 = { 'Name': ['Jonn', 'Tomas', 'Fran', 'Olga', 'Veronika', 'Stephan'], 'Mat': [85, 75, 50, 93, 88, 90], 'Science': [96, 97, 99, 87, 90, 88], 'Reading':...
pandas merge two dataframe and sort by compared column in adjacent column
I compare two dataframe and result can be shown below; import pandas as pd exam_1 = { 'Name': ['Jonn', 'Tomas', 'Fran', 'Olga', 'Veronika', 'Stephan'], 'Mat': [85, 75, 50, 93, 88, 90], 'Science': [96, 97, 99, 87, 90, 88], 'Reading': [80, 60, 72, 86, 84, 77], 'Wiritng': [78, 82, 88, 78, 86, 82], 'Lang': [77...
[ "You can use pandas.DataFrame.sort_index on axis=1.\nReplace this :\ncmp = pd.merge(df_1, df_2, how=\"outer\", on=[\"Name\"], suffixes=(\"_1\", \"_2\"))\n\nBy this :\ncmp = (\n pd.merge(df_1, df_2, how=\"outer\", on=[\"Name\"], suffixes=(\"_1\", \"_2\"))\n .set_index(\"Name\")\n .sort_i...
[ 0 ]
[]
[]
[ "dataframe", "merge", "pandas", "python" ]
stackoverflow_0074585876_dataframe_merge_pandas_python.txt
Q: Using an Input to Retrieve a Corresponding Element From a 2D Array This might be a really obvious solution to some, but, being pretty new to python, I'm unsure how to do it - In short, I want to take a user's input, and find the corresponding element on a 2D array, i.e. an input of '1' would print 'a', '2' would p...
Using an Input to Retrieve a Corresponding Element From a 2D Array
This might be a really obvious solution to some, but, being pretty new to python, I'm unsure how to do it - In short, I want to take a user's input, and find the corresponding element on a 2D array, i.e. an input of '1' would print 'a', '2' would print 'b', and so on. Is there a way to do this? The code I've written so...
[ "Loop through the sub-lists inside var until you find one where the first element matches the user input. Then print the second element of that sub-list.\nfor sublist in var:\n if sublist[0] == inp:\n print(sublist[1])\n\n", "There are a lot of ways of doing what you want to do. Here's a way that is e...
[ 0, 0, 0 ]
[]
[]
[ "arrays", "multidimensional_array", "python" ]
stackoverflow_0074585875_arrays_multidimensional_array_python.txt
Q: ERROR: Proxy URL had no scheme. However, URL & Proxies are properly setup I'm getting the error: urllib3.exceptions.ProxySchemeUnknown: Proxy URL had no scheme, should start with http:// or https:// but the proxies are fine & so is the URL. URL = f"https://google.com/search?q={query2}&num=100" ...
ERROR: Proxy URL had no scheme. However, URL & Proxies are properly setup
I'm getting the error: urllib3.exceptions.ProxySchemeUnknown: Proxy URL had no scheme, should start with http:// or https:// but the proxies are fine & so is the URL. URL = f"https://google.com/search?q={query2}&num=100" mysite = self.listbox.get(0) headers = {"user-agent": USER_AGEN...
[ "On Linux unset http_proxy and https_proxy using terminal on the current location of your project\nunset http_proxy\n\nunset https_proxy\n\n", "I had the same problem and setting in my terminal https_proxy variable really helped me. You can set it as follows:\nset HTTPS_PROXY=http://username:password@proxy.examp...
[ 2, 1, 0 ]
[]
[]
[ "python", "python_3.x", "python_requests" ]
stackoverflow_0067010503_python_python_3.x_python_requests.txt
Q: Getting Video Links from Youtube Channel in Python Selenium I am using Selenium in Python to scrape the videos from Youtube channels' websites. Below is a set of code. The line videos = driver.find_elements(By.CLASS_NAME, 'style-scope ytd-grid-video-renderer') repeatedly returns no links to the videos (a.k.a. the ...
Getting Video Links from Youtube Channel in Python Selenium
I am using Selenium in Python to scrape the videos from Youtube channels' websites. Below is a set of code. The line videos = driver.find_elements(By.CLASS_NAME, 'style-scope ytd-grid-video-renderer') repeatedly returns no links to the videos (a.k.a. the print(videos) after it outputs an empty list). How would you modi...
[ "If you don't have a YouTube Data API v3 developer key:\nThe following procedure requires you to have a Google account.\nGo to: https://console.cloud.google.com/projectcreate\nClick on the CREATE button.\nGo to: https://console.cloud.google.com/marketplace/product/google/youtube.googleapis.com\nClick on the ENABLE ...
[ 0, 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "web_scraping", "youtube" ]
stackoverflow_0074578175_python_selenium_selenium_webdriver_web_scraping_youtube.txt
Q: While importing the Tensorflow. Failed to load the native TensorFlow runtime I've got a error mesage when I am trying to install tensorflow to my project. It's a little bit long traceback but I'm sure there are some heroes right there to help me tackle with that. import tkinter as tk from PIL import ImageTk, Image...
While importing the Tensorflow. Failed to load the native TensorFlow runtime
I've got a error mesage when I am trying to install tensorflow to my project. It's a little bit long traceback but I'm sure there are some heroes right there to help me tackle with that. import tkinter as tk from PIL import ImageTk, Image from tkinter import filedialog import numpy as np import tensorflow from tensorfl...
[ "As answered in: Stackoverflow answer\nYou can try uninstalling numpy package:\npip3 uninstall numpy\n\nand reinstalling it:\npip3 install numpy\n\n" ]
[ 0 ]
[]
[]
[ "import", "machine_learning", "python", "tensorflow", "tkinter" ]
stackoverflow_0074585808_import_machine_learning_python_tensorflow_tkinter.txt
Q: Transferring the the data from a file to pandas dataframe, which have no file extension I like to use SMS Spam Collection Data Set which can be found on UCI Machine Learning Repository, to build a classification model. The data file that is shared on the repository has no file extension. The data is look like the ...
Transferring the the data from a file to pandas dataframe, which have no file extension
I like to use SMS Spam Collection Data Set which can be found on UCI Machine Learning Repository, to build a classification model. The data file that is shared on the repository has no file extension. The data is look like the following ham Go until jurong point, crazy.. Available only in bugis n great world la e b...
[ "The file seems like a .txt tab separated, so you can use pandas.read_csv :\nimport pandas as pd\n\ndf = pd.read_csv(filepath_or_buffer= \"SMSSpamCollection\",\n header=None, sep=\"\\t\", names=[\"Message Class\", \"Messages\"])\n\n# Output :\n\n", "This should work\ndf= pd.read_csv(\"your_file.cs...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074585893_dataframe_pandas_python.txt
Q: Why is QSystemTrayIcon.isSystemTrayAvailable() False running as root but True as user? On Ubuntu 20.04 with Gnome3 and X11 and Qt5.12.8 (PyQt 5.14.1) from PyQt5.QtWidgets import QSystemTrayIcon, QApplication qapp = QApplication(['']) print(str(QSystemTrayIcon.isSystemTrayAvailable())) shows True as user and False...
Why is QSystemTrayIcon.isSystemTrayAvailable() False running as root but True as user?
On Ubuntu 20.04 with Gnome3 and X11 and Qt5.12.8 (PyQt 5.14.1) from PyQt5.QtWidgets import QSystemTrayIcon, QApplication qapp = QApplication(['']) print(str(QSystemTrayIcon.isSystemTrayAvailable())) shows True as user and False as root (via sudo as well as via pkexec). How can I find out the reason for "False as root...
[ "Regarding question 1: I have found the correct logging settings and reason\n\n\nHow can I find out the reason for \"False as root\" (is there a way to enable logging for this)?\n\n\nI have to enable the logging for the logging category qt.qpa.*\npkexec env \"QT_LOGGING_RULES=qt.qpa.*=true\" DISPLAY=$DISPLAY XDG_RU...
[ 0 ]
[]
[]
[ "pyqt5", "python", "qt", "qt5" ]
stackoverflow_0074573870_pyqt5_python_qt_qt5.txt
Q: '>' not supported between instances of 'type' and 'datetime.date' I'm creating a CRUD application that displays activities available on or after today; I'm working through the filtering mechanism on displaying these activities, however I'm having a nightmare trying to only show the activities that are on/after to...
'>' not supported between instances of 'type' and 'datetime.date'
I'm creating a CRUD application that displays activities available on or after today; I'm working through the filtering mechanism on displaying these activities, however I'm having a nightmare trying to only show the activities that are on/after today. I'm getting the below error when I try to use the '>=' operand, ho...
[ "You can filter with the __gt lookup [Django-doc] so:\ntoday = date.today()\navailable_activities = Activity.objects.filter(\n available=True, date__gt=today\n).order_by('date', 'start_time')\n" ]
[ 2 ]
[]
[]
[ "date", "datetime", "django", "python" ]
stackoverflow_0074585991_date_datetime_django_python.txt
Q: Scala code returns false for 1012 > 977 and a few other values I have scala code and python code that are attempting the same task (2021 advent of code day 1 https://adventofcode.com/2021/day/1). The Python returns the correct solution, the Scala does not. I ran diff on both of the outputs and have determined that...
Scala code returns false for 1012 > 977 and a few other values
I have scala code and python code that are attempting the same task (2021 advent of code day 1 https://adventofcode.com/2021/day/1). The Python returns the correct solution, the Scala does not. I ran diff on both of the outputs and have determined that my Scala code is incorrectly evaluating the following pairs: 1001 >...
[ "As @Edward Peters https://stackoverflow.com/users/6016064/edward-peters correctly identified, my problem was that I was doing string comparisons, and not numerical comparisons, so I needed to convert my values to Int and not String. I did this with the very simple .toInt and it fixed all my issues.\nfixed scala co...
[ 1 ]
[]
[]
[ "python", "scala" ]
stackoverflow_0074585988_python_scala.txt
Q: Why can't my beam DoFn see my global imports? I have a beam pipeline that uses a custom DoFn and references imports (like time) inside of its body. Full code is here, the idea is below. import time class MyView(beam.DoFn): @beam.DoFn.yields_elements def process_batch(self, batch: List[Dict[str, Any]]) -> ...
Why can't my beam DoFn see my global imports?
I have a beam pipeline that uses a custom DoFn and references imports (like time) inside of its body. Full code is here, the idea is below. import time class MyView(beam.DoFn): @beam.DoFn.yields_elements def process_batch(self, batch: List[Dict[str, Any]]) -> Iterator[Tuple[str, MyType]]: start_time = ...
[ "The root cause was a python version mismatch. I'm using 3.8 for this project and, despite specifying 3.8 in CI using (abatilo/actions-poetry)[https://github.com/abatilo/actions-poetry], I was getting 3.9. I assume the issue there was that I had the poetry step before the setup-python step, but whenever I put it af...
[ 1 ]
[]
[]
[ "apache_beam", "google_cloud_dataflow", "python" ]
stackoverflow_0074586062_apache_beam_google_cloud_dataflow_python.txt
Q: Matplotlib: AttributeError: 'PolarAxesSubplot' object has no attribute 'polar' I have to plot one polar and one scatter. Here is the code: fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection='polar') iterator = lidar.iter_scans() line = ax.scatter([0, 0], [0, 0], s=5, color="xkcd:salmon") ax.set_rmax(DMAX...
Matplotlib: AttributeError: 'PolarAxesSubplot' object has no attribute 'polar'
I have to plot one polar and one scatter. Here is the code: fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection='polar') iterator = lidar.iter_scans() line = ax.scatter([0, 0], [0, 0], s=5, color="xkcd:salmon") ax.set_rmax(DMAX) ax.grid(True) data = [] def environment(): for i, scan in enumerate(lidar.it...
[ "I think depends on the python version\nUsing python 3.9 works just fine\nI did try python 3.6 and I got the error, but initialiazing in this way worked for me:\nfig, ax1 = plt.subplots(figsize=(6, 6), subplot_kw=dict(polar=True))\n\nwithout using the\nax1.polar(angles, values)\n\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0054989283_matplotlib_python.txt
Q: pyFirmata gives error: module 'inspect' has no attribute 'getargspec' I'm trying to use pyFirmata, but I can't get it to work. Even the most basic of the library does not work. I guess there is something wrong with the library code. from pyfirmata import Arduino,util import time port = 'COM5' board = Arduino(port...
pyFirmata gives error: module 'inspect' has no attribute 'getargspec'
I'm trying to use pyFirmata, but I can't get it to work. Even the most basic of the library does not work. I guess there is something wrong with the library code. from pyfirmata import Arduino,util import time port = 'COM5' board = Arduino(port) I get this error: Traceback (most recent call last): File "c:\Users\Pu...
[ "According to the first line of pyFirmata docs:\n\nIt runs on Python 2.7, 3.6 and 3.7\n\nYou are using Python 3.11. The inspect (core library module) has changed since Python 3.7.\n" ]
[ 0 ]
[ "As already pointed out in another answer, the pyFirmata modules is currently documented to run on Python 2.7, 3.6 and 3.7. This doesn't mean it won't work on other versions, but probably that it hasn't been tested on other versions by the author and it isn't officially supported. So it may or may not work on newer...
[ -1 ]
[ "arduino", "attributeerror", "pyfirmata", "python", "python_3.11" ]
stackoverflow_0074585622_arduino_attributeerror_pyfirmata_python_python_3.11.txt
Q: pip command does nothing I just installed Python 2.7.10 on windows 10. I have added my python and pip directory to my PATH like so: My Scripts folder looks like this: My problem is, when I type in "pip" in command prompt and press enter absolutely nothing happens, even if I wait several minutes. If I remove ...
pip command does nothing
I just installed Python 2.7.10 on windows 10. I have added my python and pip directory to my PATH like so: My Scripts folder looks like this: My problem is, when I type in "pip" in command prompt and press enter absolutely nothing happens, even if I wait several minutes. If I remove the Scripts directory from the...
[ "One command that is bound to work is writing:\npython -m pip install requests\n\nThis works because you hand off the script invocation to python, which you know works, instead of relying on the PATH environment variable of windows, which can be dodgy.\nPackages like numpy that require c-extensions to be built, wil...
[ 14, 4, 2, 0, 0 ]
[]
[]
[ "pip", "python" ]
stackoverflow_0033918678_pip_python.txt
Q: How do you update column headers to change a Single index dataframe into a MultiIndex dataframe? I have a dataset that arrives with commingled column headers as a wide dataframe that also has row groups. For instance, several types of furniture that have yearly row data and the column levels are product size and c...
How do you update column headers to change a Single index dataframe into a MultiIndex dataframe?
I have a dataset that arrives with commingled column headers as a wide dataframe that also has row groups. For instance, several types of furniture that have yearly row data and the column levels are product size and colors... But for flattening the data to be processed/graphed, I have to create a color column (I know ...
[ "Per the suggestions in the comments on the question, I have pieced together the answer. To rename the columns, and to label both the columns and the indices, the code should be using .columns and .names, respectively:\n# Minimum Working Example of incoming data in wide format\nimport pandas as pd\nimport numpy as ...
[ 0 ]
[]
[]
[ "dataframe", "multi_index", "pandas", "python", "rename" ]
stackoverflow_0074553654_dataframe_multi_index_pandas_python_rename.txt
Q: How to start python Eel in any available browser of user system? I am trying to create a windows based application using eel. I want it to start in any available browser in the system of the user. How can I do it ? ( consider that user have not installed chrome in his system ) A: You can pass in mode='default' t...
How to start python Eel in any available browser of user system?
I am trying to create a windows based application using eel. I want it to start in any available browser in the system of the user. How can I do it ? ( consider that user have not installed chrome in his system )
[ "You can pass in mode='default' to the eel.start function, and it will try to open the system's default browser. Something like this:\neel.start('index.html', mode='default')\n\nIn this case, behind-the-scenes Eel will be proxying the open request to Python's webbrowser.open function, so it's best to check there if...
[ 1, 0 ]
[]
[]
[ "eel", "python" ]
stackoverflow_0068740121_eel_python.txt
Q: Wireshark/pcap file format for serial data? I would like a Python file that uses a serial port to generate Wireshark/pcap compatible "trace" files of the serial data being exchanged. Can someone point me at the format of the pcap file I need to create for such data? For example do I have to fake a SLIP/PPP type ...
Wireshark/pcap file format for serial data?
I would like a Python file that uses a serial port to generate Wireshark/pcap compatible "trace" files of the serial data being exchanged. Can someone point me at the format of the pcap file I need to create for such data? For example do I have to fake a SLIP/PPP type file or is there such a thing as a "raw serial da...
[ "\nFor example do I have to fake a SLIP/PPP type file\n\nNo.\n\nor is there such a thing as a \"raw serial data\" file?\n\nNo.\nWhat you can do is use one of the user-defined private LINKTYPE_USER0 through LINKTYPE_USER15 values for your packets. Note that other pcap or pcapng files may use those values for differ...
[ 0 ]
[]
[]
[ "pcap", "python", "wireshark" ]
stackoverflow_0074573201_pcap_python_wireshark.txt
Q: parallelize a time-consuming Python loop I have a nested for loop that is time-consuming. I think parallelization can make it faster, but I do not know how I use it. this is my for loop in my code : for itr2 in range(K): tmp_cl=clusters[itr2+1] if len(tmp_cl)>1: BD_cent=np.z...
parallelize a time-consuming Python loop
I have a nested for loop that is time-consuming. I think parallelization can make it faster, but I do not know how I use it. this is my for loop in my code : for itr2 in range(K): tmp_cl=clusters[itr2+1] if len(tmp_cl)>1: BD_cent=np.zeros((len(tmp_cl),1)) for itr3...
[ "CPython implementation detail: In CPython, due to the Global Interpreter Lock, only one thread can execute Python code at once (even though certain performance-oriented libraries might overcome this limitation). If you want your application to make better use of the computational resources of multi-core machines, ...
[ 0 ]
[]
[]
[ "parallel_processing", "python", "python_3.x" ]
stackoverflow_0073941643_parallel_processing_python_python_3.x.txt
Q: How to count occurrences of a specific dict key in dicts list and some dicts values ​contains list and append the count in value I'm trying to count the number of times a specified key occurs in my list of dicts. I've used loops and sum to count up all the keys, but how can I find the count for a specific key? I h...
How to count occurrences of a specific dict key in dicts list and some dicts values ​contains list and append the count in value
I'm trying to count the number of times a specified key occurs in my list of dicts. I've used loops and sum to count up all the keys, but how can I find the count for a specific key? I have this code, which does not work currently: for dico in data: for ele in dico['people']: print(ele['name']+str...
[ "This will do what you want; feel free to ask if you need explanations:\nfor dico in data:\n children = 0\n for ele in dico['people']:\n animals = len(ele['animals'])\n children += 1 + animals\n ele['name'] += f\" [{animals}]\"\n dico['name'] += f\" [{children}]\"\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074586097_python_python_3.x.txt
Q: CNN model that inputs image list outputs a list of [int,int,float] I'm still new to deep learning and CNN and I don't know what this error is so anyone can help me? This model is designed to take input of image array and output is a list of items and each items contains an int,int,float and I cannot make a model t...
CNN model that inputs image list outputs a list of [int,int,float]
I'm still new to deep learning and CNN and I don't know what this error is so anyone can help me? This model is designed to take input of image array and output is a list of items and each items contains an int,int,float and I cannot make a model than contains no error. The error ValueError: Dimensions must be equal, ...
[ "You have to add a final dense layer before the compiler. And the n_number is the number of the output of your model:\nmodel.add(Dense(n_number,activation='sigmoid'))\n\n" ]
[ 0 ]
[]
[]
[ "conv_neural_network", "deep_learning", "python", "tensorflow" ]
stackoverflow_0066985400_conv_neural_network_deep_learning_python_tensorflow.txt
Q: How to upload images using wordpress REST api in python? I think I've got this 90% working, but it ends up 'uploading' a blank transparent image. I get a 201 response after the upload. I think that's probably a proxy for when WP finds a missing image. I'm unsure if i'm passing the image incorrectly (ie it doesn't ...
How to upload images using wordpress REST api in python?
I think I've got this 90% working, but it ends up 'uploading' a blank transparent image. I get a 201 response after the upload. I think that's probably a proxy for when WP finds a missing image. I'm unsure if i'm passing the image incorrectly (ie it doesn't leave my computer) or if I'm not tagging it properly to WP's l...
[ "I've figured it out! \nWith this function I'm able to upload images via the WP REST api to my site (Photo Gear Hunter.) The function returns the ID of the image. You can then pass that id to a new post call and make it the featured image, or do whatever you wish with it.\ndef restImgUL(imgPath):\n url='http://x...
[ 18, 1, 1, 0, 0 ]
[ "import base64\nimport os\n\nimport requests\n\ndef rest_image_upload(image_path):\n message = '<user_name>' + \":\" + '<application password>'\n message_bytes = message.encode('ascii')\n base64_bytes = base64.b64encode(message_bytes)\n base64_message = base64_bytes.decode('ascii')\n\n # print(base64...
[ -1 ]
[ "python", "python_requests", "rest", "wordpress", "wp_api" ]
stackoverflow_0043915184_python_python_requests_rest_wordpress_wp_api.txt
Q: Convert categorical data using 'if' I have categorical data df(notes) with the resulting number of a sum from 0 to 6. How to convert this to another categorical data (0,1) using the conditional'if' ? For example: if df(notes)=> 1, result=1, f df(notes)= 0, result=o, I don't know how to integrate the conditional wi...
Convert categorical data using 'if'
I have categorical data df(notes) with the resulting number of a sum from 0 to 6. How to convert this to another categorical data (0,1) using the conditional'if' ? For example: if df(notes)=> 1, result=1, f df(notes)= 0, result=o, I don't know how to integrate the conditional with only values from o to 6
[ "If I correctly understood your question, you seem to have a dataframe with a column named notes that holds categorical integer values between 0 and 6. And you need to transform them to 0 or 1 values, 0 if the note is 0 and 1 if it is strictly positive.\nIf it is the case, you can achieve this by using the apply fu...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074586158_python.txt
Q: Can't grab anything (title, price, etc) from a webpage using scrapy I'm trying to extract the title of some products but it doesn't work and it yields an empty list every time. I tried grabbing the css and xpath of the 'title' using selectorgadget extension but failed, tried to grab the path by inspecting the elem...
Can't grab anything (title, price, etc) from a webpage using scrapy
I'm trying to extract the title of some products but it doesn't work and it yields an empty list every time. I tried grabbing the css and xpath of the 'title' using selectorgadget extension but failed, tried to grab the path by inspecting the element yet I failed. These are some css, xpath (by selector gadget tool) and...
[ "They are using javascript to load their page dynamically. Fortunately their search api is fairly straight forward and provides all of the information you are looking for most likely.\nimport scrapy\n\nclass NoonspiderSpider(scrapy.Spider):\n name = 'noonspider'\n allowed_domains = ['noon.com']\n start_ur...
[ 2 ]
[]
[]
[ "python", "scrapy", "web_scraping" ]
stackoverflow_0074586059_python_scrapy_web_scraping.txt
Q: (Python) Im trying to make a game, and if a choice is chosen a certain amount of time, a print statement will appear How can I make it so that after choosing choice A 3 times, the program tells the user they need to sleep? Choice = input("Are you ready to play? (yes/no) ") if Choice.lower() == "yes": Choice ...
(Python) Im trying to make a game, and if a choice is chosen a certain amount of time, a print statement will appear
How can I make it so that after choosing choice A 3 times, the program tells the user they need to sleep? Choice = input("Are you ready to play? (yes/no) ") if Choice.lower() == "yes": Choice = input(" \n A. Work overtime \n B. Get Some Rest \n C.Grab Something to Eat \n D. Status Check \n Q. Quit \n What will be...
[ "First of all, Welcome to stackoverflow !\nI totally understand @Edward Peters suggestion of learning basics of python before posting this question.\nI can help you with an method to approach this method:\n\nCreate a counter variable and initialize it to 1\nAdd a check in the if choice == \"a\" loop to check if cou...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074586177_python.txt
Q: Why does removing grid() make my program turn blank? I'm using .place() in my tkinter program, so I wanted to remove references to grid(). So far my program works but for some reason there's a single .grid() line that makes my whole program turn blank if it's removed. This shouldn't happen, since I'm entirely usin...
Why does removing grid() make my program turn blank?
I'm using .place() in my tkinter program, so I wanted to remove references to grid(). So far my program works but for some reason there's a single .grid() line that makes my whole program turn blank if it's removed. This shouldn't happen, since I'm entirely using .place(). Here is that line: AllFrames.grid(row=0, c...
[ "The place() manager does not reserve any space, unless you tell it directly.\nThe grid(sticky='nsew') makes the widget expand to fill the entire available space, in this case the containing widget. The widgets inside all use place() which will not take any space. When you change to grid(sticky='n') you place the z...
[ 2 ]
[]
[]
[ "python", "screen", "tkinter" ]
stackoverflow_0074586068_python_screen_tkinter.txt
Q: python - No module named 'pywidevine.L3' Have been trying a python script which has required a bunch of additional modules, that I've installed according to the error messages, leading to the next one until I got stuck. The specific error is: "ModuleNotFoundError: No module named 'pywidevine.L3" Have already insta...
python - No module named 'pywidevine.L3'
Have been trying a python script which has required a bunch of additional modules, that I've installed according to the error messages, leading to the next one until I got stuck. The specific error is: "ModuleNotFoundError: No module named 'pywidevine.L3" Have already installed "pywidevine". Did this on a whim without ...
[ "The error is correct there is no module called L3 in pywidevine. please refer to the source code of the package repository. Please make edit to your question so that we can know what are you trying to achieve?\n" ]
[ 0 ]
[]
[]
[ "homebrew", "python", "widevine" ]
stackoverflow_0074586258_homebrew_python_widevine.txt
Q: Read certain column in excel given two other values match using pandas Month Year Open High Low Close/Price Volume 6 2019 86.78 87.11 86.06 86.55 1507828 6 2019 86.63 87.23 84.81 85.06 2481284 6 2019 85.38 85.81 84.75 85.33 2034693 6 2019 85.65 86.86 85.13...
Read certain column in excel given two other values match using pandas
Month Year Open High Low Close/Price Volume 6 2019 86.78 87.11 86.06 86.55 1507828 6 2019 86.63 87.23 84.81 85.06 2481284 6 2019 85.38 85.81 84.75 85.33 2034693 6 2019 85.65 86.86 85.13 86.43 1394847 6 2019 86.66 87.74 86.66 87.55 3025379 7 2...
[ "You can use .groupby() with multiple columns, and then you can use .mean() to get the desired averages:\ndf.groupby([\"Month\", \"Year\"]).mean()\n\nThis outputs:\n Open High Low Close/Price Volume\nMonth Year\n6 2019 86.220 86.9500 85.4820 86.184 2088806.20\n7 2019 8...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074586321_pandas_python.txt
Q: Timing operation with increasing list size - unexpected behaviour Problem: How long does it take to generate a Python list of prime numbers from 1 to N? Plot a graph of time taken against N. I used SymPy to generate the list of primes. I expected the time to increase monotonically. But why is there a dip? import n...
Timing operation with increasing list size - unexpected behaviour
Problem: How long does it take to generate a Python list of prime numbers from 1 to N? Plot a graph of time taken against N. I used SymPy to generate the list of primes. I expected the time to increase monotonically. But why is there a dip? import numpy as np import matplotlib.pyplot as plt from time import perf_counte...
[ "The sieve itself requires an exponential amount of time to compute ever larger numbers of primes, so plotting the pure runtime of a sieve should come out to roughly a straight line for large numbers.\nIn your copy of the plot, it looks like it's actually getting a bit worse over time, but when I run your script it...
[ 0 ]
[]
[]
[ "primes", "python", "sympy", "timing" ]
stackoverflow_0074585845_primes_python_sympy_timing.txt
Q: Convert pandas dataframe to a specific layout I'm using a software that takes data in a certain format. In order for this software to work, I will need to convert a dataframe, like the first screenshoot, to a different format, like the second screenshoot. Any ideas how I can do that? Thanks in advance! Original da...
Convert pandas dataframe to a specific layout
I'm using a software that takes data in a certain format. In order for this software to work, I will need to convert a dataframe, like the first screenshoot, to a different format, like the second screenshoot. Any ideas how I can do that? Thanks in advance! Original data format Converted data format
[ "Given a simple dataframe:\n\n 0 1 2 3\n 0 1 2.0 4 1.0\n 1 2 3.0 r NaN\n 2 3 NaN 6 NaN\n\n\nCreated a single column dataframe using:\n\n import pandas as pd\n import numpy as np\n \n df = pd.read_csv('test.csv',header=None,sep=\";\")\n joined = pd.concat([df[column]....
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074585358_dataframe_pandas_python.txt
Q: Scrapy + Playwright error: "node:events:505 throw er; // Unhandled 'error' event" I'm doing scrapping with scrapy + playwright of an ecommerce website, approximately in one hour returns 42k registers and broken with the message: node:events:505 throw er; // Unhandled 'error' event ^ Error: write EPIPE...
Scrapy + Playwright error: "node:events:505 throw er; // Unhandled 'error' event"
I'm doing scrapping with scrapy + playwright of an ecommerce website, approximately in one hour returns 42k registers and broken with the message: node:events:505 throw er; // Unhandled 'error' event ^ Error: write EPIPE at WriteWrap.onWriteComplete [as oncomplete] (node:internal/stream_base_commons:94...
[ "I had the same issue and it was because of an unclosed page instance, however, I see in your code page is closed.\nPlease make sure you did the following steps:\n\nClose all playwright instances\nClose all BrowserContext objects\nClose all opened Page objects\n\nOpened Playwright instance looks like this:\nplaywri...
[ 0 ]
[]
[]
[ "playwright", "python", "scrapy" ]
stackoverflow_0073962320_playwright_python_scrapy.txt
Q: File reading only first digit of a number rather than the whole number The problem is that i have a text file with each line being PlayerName wins with x points with each player name and number being different and obviously with them being different are different number if digits long Problem is as a part of the c...
File reading only first digit of a number rather than the whole number
The problem is that i have a text file with each line being PlayerName wins with x points with each player name and number being different and obviously with them being different are different number if digits long Problem is as a part of the code it needs to read the entire code and print the players with the top 5 sc...
[ "Below is the fixed part of the code to get the correct value for points.\nI did not touch the other parts of the code.\ntext_file = open('CH30.txt.', 'r')\nLines = text_file.readlines()\nPlayersScores = []\nfor line in Lines:\n line = line.split()\n playerName = line[0]\n points = int(line[3])\n .....\...
[ 0 ]
[]
[]
[ "numbers", "python", "text_files" ]
stackoverflow_0074585551_numbers_python_text_files.txt
Q: Django Rest how to show list of comment which belongs only from related Blog and Author? Assume Author Jhone write an Blog which title is "This blog written by author Jhone" and Author Joe write an Blog "This blog written by author Joe" . Jhone blog received 20 comments and Joe blog received 10 comments. When Jh...
Django Rest how to show list of comment which belongs only from related Blog and Author?
Assume Author Jhone write an Blog which title is "This blog written by author Jhone" and Author Joe write an Blog "This blog written by author Joe" . Jhone blog received 20 comments and Joe blog received 10 comments. When Jhone will be login his account he can only able to see comments those belongs from his blog pos...
[ "I was missing author id. instead of this Comment.objects.all().filter(blog__author=request.user.id) it will be Comment.objects.all().filter(blog__author_id=request.user.id)\n" ]
[ 0 ]
[]
[]
[ "django", "django_rest_framework", "python", "python_3.x" ]
stackoverflow_0074586209_django_django_rest_framework_python_python_3.x.txt
Q: Euclidean distance between features vectors I have a dataset such as: ` team y A African Dance [[1.059685349464416, 0.328705966472625, 0.3115... Ballet [[0.486603736877441, 1.678925514221191, 0.0157... Contemporary [[0.06553386151790601, 2.121821165084839, 0, 0... B ...
Euclidean distance between features vectors
I have a dataset such as: ` team y A African Dance [[1.059685349464416, 0.328705966472625, 0.3115... Ballet [[0.486603736877441, 1.678925514221191, 0.0157... Contemporary [[0.06553386151790601, 2.121821165084839, 0, 0... B African Dance [[1.129618763923645, 0.775617...
[ "This will skip duplicates:\nfor i,fv1 in enumerate(features_vectors):\n for fv2 in features_vectors[i+1:]:\n print(np.linalg.norm(fv1 - fv2))\n\nYou haven't really told us anything about the input data (is it one column? Several columns?), so this might need adapting.\n" ]
[ 0 ]
[]
[]
[ "arrays", "euclidean_distance", "numpy", "python" ]
stackoverflow_0074586430_arrays_euclidean_distance_numpy_python.txt
Q: PyTorch - Receiving 0 Filled List from Prediction ISSUE: EXPECTED:tensor([[1., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 1., 0., 1., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 1., 1.]], dtype=torch.float64) ACTUAL:tensor([0, 0, 0, 0, 0, 0, 0, 0, ...
PyTorch - Receiving 0 Filled List from Prediction
ISSUE: EXPECTED:tensor([[1., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 1., 0., 1., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 1., 1.]], dtype=torch.float64) ACTUAL:tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...
[ "I got it working by modifying my testing loop. I removed the torch.max() function, and simply returned the values I got from the net.\ncorrectAttributes = 0\nthreshold = .5\nwith torch.no_grad():\n\nfor i, data in enumerate(testloader, 0):\n\n # Get inputs\n inputs, targets = data\n\n # Generate outputs\n...
[ 0 ]
[]
[]
[ "artificial_intelligence", "numpy", "python", "pytorch" ]
stackoverflow_0074579784_artificial_intelligence_numpy_python_pytorch.txt
Q: graph that combine bar and line I would like to reproduce this chart with python ie the unemployment rate with shaded period corresponding with recession period. I downloaded the 2 series from Fred data base with : import numpy as np import pandas as pd import pandas_datareader as wb import datetime as dt import ...
graph that combine bar and line
I would like to reproduce this chart with python ie the unemployment rate with shaded period corresponding with recession period. I downloaded the 2 series from Fred data base with : import numpy as np import pandas as pd import pandas_datareader as wb import datetime as dt import matplotlib.pyplot as plt data_fred =...
[ "Unfortunately I do not have your data, so generated something on my own. Nevertheless, just look at the plotting part and I propose using patches from matplotlib. Here is the script:\n#!/usr/bin/env ipython\n# ---------------------\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotl...
[ 0 ]
[]
[]
[ "matplotlib", "pandas", "python" ]
stackoverflow_0074585379_matplotlib_pandas_python.txt
Q: Create an instance of a class passing values of list as arguments in Python I'm currently try to pass the items of a list create an instance of a class. My code looks like this args = ["1", "John", "Doe"] class Token: def __init__ = (self, id, name, last_name) self.id = id self.name = name ...
Create an instance of a class passing values of list as arguments in Python
I'm currently try to pass the items of a list create an instance of a class. My code looks like this args = ["1", "John", "Doe"] class Token: def __init__ = (self, id, name, last_name) self.id = id self.name = name self.last_name = last_name instance1 = Token(args) I get the error TypeEr...
[ "Use the iterable unpacking operator:\nToken(*args)\n\n" ]
[ 0 ]
[]
[]
[ "class", "instance_variables", "list", "python" ]
stackoverflow_0074586544_class_instance_variables_list_python.txt
Q: How do I make this pandas function faster? I'm trying to make a function that solves for n in this equation (and then p, q and r) Equation. x, y, z, are known. It used binary search, to try to find n with a tolerance of +-0.0001 # game is a series with implied probabilites for each outcome in a football match def ...
How do I make this pandas function faster?
I'm trying to make a function that solves for n in this equation (and then p, q and r) Equation. x, y, z, are known. It used binary search, to try to find n with a tolerance of +-0.0001 # game is a series with implied probabilites for each outcome in a football match def logfunc(game): n_range = [1, 0] n = 0.5 ...
[ "On big issue is that working with Pandas series is generally slow. A faster alternative is to work with Numpy arrays (that Pandas uses internally). Numpy arrays are not labelled like series so one need to adapt the game[ODDS] expression if ODDS is not an integer (the index of the label must be computed in this cas...
[ 0 ]
[]
[]
[ "big_o", "optimization", "pandas", "python" ]
stackoverflow_0074585408_big_o_optimization_pandas_python.txt
Q: Multiply Columns Together Based on Condition Is there a way for me to dynamically multiply columns together based on a value in another column in Python? I'm using Polars if that makes a difference. For example, if calendar_year is 2018, I'd want to multiply columns 2018, 2019, 2020, and 2021 together, but if cale...
Multiply Columns Together Based on Condition
Is there a way for me to dynamically multiply columns together based on a value in another column in Python? I'm using Polars if that makes a difference. For example, if calendar_year is 2018, I'd want to multiply columns 2018, 2019, 2020, and 2021 together, but if calendar_year is 2019, I'd only want to multiply colum...
[ "It looks like you want to multiply CY factors for all years beyond calendar_year, and not have to update this logic for each year.\nIf that's the case, one way to avoid hard-coding the CY selections is to use melt and filter the results.\n(\n df\n .select([\n 'id',\n 'calendar_year',\n p...
[ 2 ]
[ "I think you could use the np.where(condition,then,else) function to do that.\nDo you want to create a new column with the result of that operation? This could work\ndf['2018_result'] = np.where(df.calendar_year.isin(['2019','2020','2021']),df.2019*df.2020*df.2021, 'add more calculations')\n\nWould be great if you ...
[ -2 ]
[ "dataframe", "python", "python_polars" ]
stackoverflow_0074586017_dataframe_python_python_polars.txt
Q: Betting system won't seem to process the user input correctly, how can this be improved? I'm trying to code a game of craps in which the player has a virtual 'wallet' to gamble with. I've gotten to the user input part and it's not going as planned. Here is what I have so far: import random import sys money = ...
Betting system won't seem to process the user input correctly, how can this be improved?
I'm trying to code a game of craps in which the player has a virtual 'wallet' to gamble with. I've gotten to the user input part and it's not going as planned. Here is what I have so far: import random import sys money = "500" # start the game a = input("Hello travler, to start the game, please type 'yes'. If yo...
[ "For checking if the user's bet is a number use the .isnumeric() function on your bet like:\nbet.isnumeric()\n\nto do the second thing you needed help with you could do:\nif bet < wallet: blah blah blah elif \nbet > wallet: print(\"You do not enough money\")\n\naround like that it with actual good syntax\nto do dic...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074586524_python.txt
Q: Normalising Histograms Matplotlib Hi I am plotting three different histograms which have different total frequencies but I want to normalise them such that the frequencies are the same. As you can see from the picture, the three sets have different total frequencies but I want to normalise them so that they have ...
Normalising Histograms Matplotlib
Hi I am plotting three different histograms which have different total frequencies but I want to normalise them such that the frequencies are the same. As you can see from the picture, the three sets have different total frequencies but I want to normalise them so that they have the same total frequencies but that I w...
[ "You could normalise the histograms using the normed=True option. This will mean that the area of all histograms will add up to 1.\nYou could also make the plot look a bit tidier by using the same fixed bins for all three histograms (using the bins option to hist: bins = np.arange(0,48,2), for example).\nTry this:\...
[ 5, 0 ]
[]
[]
[ "histogram", "matplotlib", "python" ]
stackoverflow_0035482543_histogram_matplotlib_python.txt
Q: Module not found Error when using Google Search API (SERPAPI) When I run this example code on my local machine: from serpapi import GoogleSearch params = { "api_key": "secret_api_key", "engine": "google", "q": "Coffee", "location": "Austin, Texas, United States", "google_domain": "google.com", "gl": "...
Module not found Error when using Google Search API (SERPAPI)
When I run this example code on my local machine: from serpapi import GoogleSearch params = { "api_key": "secret_api_key", "engine": "google", "q": "Coffee", "location": "Austin, Texas, United States", "google_domain": "google.com", "gl": "us", "hl": "en" } search = GoogleSearch(params) results = search...
[ "Use can use the below command to solve the above issue \\\npip install google-search-results\n\nYou can find more details on the GitHub link\n", "I was having the same issue even after installing google-search-results\nProblem: the selected interpreter on pycharm was on a different virtual environment that did n...
[ 4, 1 ]
[]
[]
[ "google_api", "google_search_api", "python" ]
stackoverflow_0068912059_google_api_google_search_api_python.txt
Q: typing recursive class and inheritance I have the following class hierarchy: #!/usr/bin/env python3 from typing import List, Optional, Tuple, Type class Attribute: def __init__(self, name: bytes) -> None: self._name = name @property def name(self) -> bytes: return self._name class E...
typing recursive class and inheritance
I have the following class hierarchy: #!/usr/bin/env python3 from typing import List, Optional, Tuple, Type class Attribute: def __init__(self, name: bytes) -> None: self._name = name @property def name(self) -> bytes: return self._name class Element: def __init__(self, name: bytes, ...
[ "This question is quite interesting, I thought that PEP646 support is slightly better.\nI assume python 3.10 and most recent released version of specific checker as of now, unless explicitly specified: mypy==0.991; pyre-check==0.9.17; pyright==1.1.281\nMake elements proper\nFirst of all, here's the (simple enough) ...
[ 1 ]
[]
[]
[ "mypy", "python" ]
stackoverflow_0074569502_mypy_python.txt
Q: The shuffling order of DataLoader in pytorch I am really confused about the shuffle order of DataLoader in pytorch. Supposed I have a dataset: datasets = [0,1,2,3,4] In scenario I, the code is: torch.manual_seed(1) G = torch.Generator() G.manual_seed(1) ran_sampler = RandomSampler(data_source=datasets,generator...
The shuffling order of DataLoader in pytorch
I am really confused about the shuffle order of DataLoader in pytorch. Supposed I have a dataset: datasets = [0,1,2,3,4] In scenario I, the code is: torch.manual_seed(1) G = torch.Generator() G.manual_seed(1) ran_sampler = RandomSampler(data_source=datasets,generator=G) dataloader = DataLoader(dataset=datasets,sampl...
[ "Based on your code, I did a little modification (on scenario II) and inspection:\ndatasets = [0,1,2,3,4]\n\ntorch.manual_seed(1)\nG = torch.Generator()\nG = G.manual_seed(1)\n\nran_sampler = RandomSampler(data_source=datasets, generator=G)\ndataloader = DataLoader(dataset=datasets, sampler=ran_sampler)\nprint(id(d...
[ 3 ]
[]
[]
[ "python", "pytorch", "pytorch_dataloader" ]
stackoverflow_0074580942_python_pytorch_pytorch_dataloader.txt
Q: How to rid output of quotation mark I'm trying to work a program which converts number words to their related integer form for a school project on Grok. It works great but when the program outputs the result it gives it back in quotation marks due to the number being a string and not an integer. Sorry if this post...
How to rid output of quotation mark
I'm trying to work a program which converts number words to their related integer form for a school project on Grok. It works great but when the program outputs the result it gives it back in quotation marks due to the number being a string and not an integer. Sorry if this post isn't formatted correctly, it's my first...
[]
[]
[ "As I understand it, b is an early defined variable with a word.\nYou can try use int for return.\nreturn int(a.join(b))\n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0074586528_python.txt
Q: point to point line-of-sight verification with barrier python I'm trying to create code that does calculation to know if the line is passing through the rectangle (obstacle), since I only know the position of sta1 and sta2 and I also know the x_min, x_max and y_min, y_max of the rectangle. sta1 position(x,y) = (1...
point to point line-of-sight verification with barrier python
I'm trying to create code that does calculation to know if the line is passing through the rectangle (obstacle), since I only know the position of sta1 and sta2 and I also know the x_min, x_max and y_min, y_max of the rectangle. sta1 position(x,y) = (1,5) sta2 position(x,y) = (5,1) retangle x_min = 3 retangle x_max = ...
[ "I solved using the equation of the line:\n# line/rectangle intersection (obstacle)\n\n# node coordinates\nsource_x = 1\nsource_y = 5\n\ndestination_x = 5\ndestination_y = 1\n\n# rectangle vertices\n\nvertices_x = [3, 3, 4, 4]\nvertices_y = [3, 2, 3, 2]\n\n# Reduced equation of the line\n# y = ax + b\n\n# 1 - find ...
[ 0 ]
[]
[]
[ "geometry", "python" ]
stackoverflow_0074579101_geometry_python.txt
Q: Python: plot a dict of keys and values I would like to plot an x, y graph of a data dictionary (key and values). The key is a datetime value. Each value for key contains an object, ie my_data, that has attributes - name, count, totalCount On the graph, on the x-axis, I would like to use the key (datetime) On the y...
Python: plot a dict of keys and values
I would like to plot an x, y graph of a data dictionary (key and values). The key is a datetime value. Each value for key contains an object, ie my_data, that has attributes - name, count, totalCount On the graph, on the x-axis, I would like to use the key (datetime) On the y-axis, I would like to multi plot the my_dat...
[ "Here is an example of what I had in mind for the solution:\n#!/usr/bin/env ipython\n# --------------------\nimport numpy as np\nimport matplotlib as mpl\nmpl.rcParams['font.size'] = 20\nimport matplotlib.pylab as plt\nimport datetime\n# -------------------------------------\n# =====================================...
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074553478_matplotlib_python.txt
Q: Crop a video in Python, centered on a 16x9 video, cropped to 9x16, moviepy? I am wanting to crop a video that is 16x9 resolution to 9x16. This can be done by cropping a centered 607px wide rectangle on the 16x9 video. Can this be done? EDIT: I do not care to stay within moviepy. I want to use something with speed....
Crop a video in Python, centered on a 16x9 video, cropped to 9x16, moviepy?
I am wanting to crop a video that is 16x9 resolution to 9x16. This can be done by cropping a centered 607px wide rectangle on the 16x9 video. Can this be done? EDIT: I do not care to stay within moviepy. I want to use something with speed. Currently, writing a 5 min video file with moviepy is taking 10+ minutes. croppi...
[ "You can use moviepy.video.fx.all.crop. Documentation are here. For example,\nimport moviepy.editor as mpy\nfrom moviepy.video.fx.all import crop\n\nclip = mpy.VideoFileClip(\"path/to/video.mp4\")\n(w, h) = clip.size\n\ncrop_width = h * 9/16\n# x1,y1 is the top left corner, and x2, y2 is the lower right corner of t...
[ 0 ]
[]
[]
[ "crop", "ffmpeg", "moviepy", "python", "video" ]
stackoverflow_0074586467_crop_ffmpeg_moviepy_python_video.txt
Q: Multiple Python Flask sites on IIS I want to run three separate Python Flask URLS, let's call them test, staging, and production. I want one IIS website to serve up these three different applications. So I have created a website, created three IIS Applications under this site, and set the root folders for these to...
Multiple Python Flask sites on IIS
I want to run three separate Python Flask URLS, let's call them test, staging, and production. I want one IIS website to serve up these three different applications. So I have created a website, created three IIS Applications under this site, and set the root folders for these to d:\execution\test, d:\execution\staging...
[ "I think the root of your problem lies in the fact that your site has a CGIbased handler specified that is going to override the wsgi_handler values that you provide for each of your applications.\n..are you really intending to run wsgi over cgi? \nIf your answer is no, then that definitely could be your problem.\n...
[ 0, 0 ]
[]
[]
[ "asp.net", "flask", "iis", "python" ]
stackoverflow_0037325602_asp.net_flask_iis_python.txt
Q: using print() after invoking recursion Can Someone tell me what exactly is happening here.Is the print statement executing after all the draw [3,2,1] are completed or it's happening simultaneously.I tried adding print(n) but still couldn't figure out. Is it unpacking after storing the values of ('#'*n).I am gettin...
using print() after invoking recursion
Can Someone tell me what exactly is happening here.Is the print statement executing after all the draw [3,2,1] are completed or it's happening simultaneously.I tried adding print(n) but still couldn't figure out. Is it unpacking after storing the values of ('#'*n).I am getting what I desired but just needed to understa...
[ "the print comes after executing all the draw calls. if you want to print it in the same order make sure print comes first before calling the draw again\ndef draw(n:int):\n if n<0:\n return\n print ('#'*n) # this should come first before the next call\n draw(n-1)\n\nto understand the sequence of th...
[ 0 ]
[]
[]
[ "python", "python_3.x", "recursion", "tail_recursion" ]
stackoverflow_0074586621_python_python_3.x_recursion_tail_recursion.txt
Q: Python Kivy: 2 sets of buttons and connection with each other Maybe someone would give me a hint what direction have I go in, couz I"ve stucked on my problem. I will be very grateful. So, the thing is I am working on my Kivy project. The task is to evoke a line with 2 buttons, one of them have to rename another in...
Python Kivy: 2 sets of buttons and connection with each other
Maybe someone would give me a hint what direction have I go in, couz I"ve stucked on my problem. I will be very grateful. So, the thing is I am working on my Kivy project. The task is to evoke a line with 2 buttons, one of them have to rename another in the line. Actually it works, but only with 1 row. If we have set o...
[ "The on_press method gets the Button that was pressed as an argument. You can use that to find the other Button:\ndef rename_btn(self, pressed_button):\n index = self.btn_cn_lst.index(pressed_button) # get index in list of Buttons\n butt = self.btn_lst[index] # get the Button from the other list at the same...
[ 0 ]
[]
[]
[ "kivy", "python" ]
stackoverflow_0074585788_kivy_python.txt
Q: ModuleNotFoundError when import from constants file in python app-main-folder /local /__init__.py /run.py constants.py I am trying to import from constants in run.py it's throwing this error Traceback (most recent call last): File "local/run.py", line 4, in <module> from init import ...
ModuleNotFoundError when import from constants file in python
app-main-folder /local /__init__.py /run.py constants.py I am trying to import from constants in run.py it's throwing this error Traceback (most recent call last): File "local/run.py", line 4, in <module> from init import app File "/home/manavarthivenkat/ANUESERVICES--BACKEND/local/init...
[ "pip install constants\n\nTry this on your shell\nand try running run.py\nmake sure you load the constants library\n", "this is because Python assumes all your python files are in the current directory. you should tell the compiler you are looking for the file somewhere else.\nfrom app-main-folder.constants impor...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074586603_python.txt
Q: i made a function and then i used the same code that is in the function to get the minimum value through a for loop but i am getting different answers the function is to calculate cost based on earning, loan taken, fees, rates and duration, but when applying the exact same code that is there in the function to a f...
i made a function and then i used the same code that is in the function to get the minimum value through a for loop but i am getting different answers
the function is to calculate cost based on earning, loan taken, fees, rates and duration, but when applying the exact same code that is there in the function to a for loop the answers are coming different, can help me out as i am new to programming #income tax calculation and cost calc # earning, loan y n, interest rat...
[ "In your for loop, you are changing the value of earn on every loop with the line earn = earn-(amount_payable//t), so that it is not starting at 1200000 for each case.\nEither reset it inside the for loop, or as OneMadGypsy suggests, change the IT_calc function to return the value instead of printing and use it in ...
[ 1 ]
[]
[]
[ "jupyter_notebook", "python" ]
stackoverflow_0074586664_jupyter_notebook_python.txt
Q: metadata-generation-failed while installing Scipy I have been trying to install Scipy and I got an error called metadata-generation-failed, and I came over to stackoverflow looking for a solution but non of them worked for me. Neither updating pip, nor using commands such as --use-deprecated=legacy-resolver nor --...
metadata-generation-failed while installing Scipy
I have been trying to install Scipy and I got an error called metadata-generation-failed, and I came over to stackoverflow looking for a solution but non of them worked for me. Neither updating pip, nor using commands such as --use-deprecated=legacy-resolver nor --use-deprecated=backtrack-on-build-failures. I ran out o...
[ "Are you trying to install scipy on macOS 11. If so, then we don't support scipy on that version of macOS. For M1 wheels you need to be on macOS 12 or later. I think Intel is ok on macOS 11.\nIf you are trying to install scipy from source you need to install various packages for installation, the absence of gfortra...
[ 1 ]
[]
[]
[ "macos", "python", "scipy" ]
stackoverflow_0074565108_macos_python_scipy.txt
Q: Hitting connection paused fork issues with pymongo cause I need to access to db to configure before multiprocessing starts I've been struggling with this for a couple months now and have tried a lot of different things to try to alleviate but am not sure what to do anymore. All the examples that I see are differen...
Hitting connection paused fork issues with pymongo cause I need to access to db to configure before multiprocessing starts
I've been struggling with this for a couple months now and have tried a lot of different things to try to alleviate but am not sure what to do anymore. All the examples that I see are different than what I need and in my case it just wouldn't work. To preface the problem, I have processor applications that get spawned ...
[ "If anybody sees this, I was using pymongo 4.0.2 and upgraded to 4.3.3 and not seeing the errors I was previously seeing.\n" ]
[ 0 ]
[]
[]
[ "fork", "mongodb", "multiprocessing", "pymongo", "python" ]
stackoverflow_0074555523_fork_mongodb_multiprocessing_pymongo_python.txt
Q: BUG: Cannot install SciPy 1.9.3 in Python 3.10 in macOS Tried to install SciPy from the terminal using pip and from the idle using Github, but none of it worked. In the documentation it says that it should support Python 3.10, so I do not know the reason of the issue. Every other package, I have had no issue to in...
BUG: Cannot install SciPy 1.9.3 in Python 3.10 in macOS
Tried to install SciPy from the terminal using pip and from the idle using Github, but none of it worked. In the documentation it says that it should support Python 3.10, so I do not know the reason of the issue. Every other package, I have had no issue to install. Any ideas about how to solve? This is the error shown:...
[ "I'm guessing you're on macOS 11 with M1? (Please always give the OS and version as part of a question). If so, then scipy doesn't make wheels for macOS11 + M1, there are a few bugs that can't be removed. I advise upgrading to macOS 12 in this situation.\n" ]
[ 0 ]
[]
[]
[ "installation", "python", "scipy" ]
stackoverflow_0074512612_installation_python_scipy.txt
Q: Only show certain variables in Stargazer output (Python, not R) I am using Stargazer for Python (not R). I trained six statsmodels models and stored them in a list named models. I want to filter the independent variables that are displayed by Stargazer. How can this be done? This is what I have so far: # Import fr...
Only show certain variables in Stargazer output (Python, not R)
I am using Stargazer for Python (not R). I trained six statsmodels models and stored them in a list named models. I want to filter the independent variables that are displayed by Stargazer. How can this be done? This is what I have so far: # Import from stargazer.stargazer import Stargazer # There are six statsmodels ...
[ "You can use the .covariate_order() function to select which covariates you want to display.\nstar_out.covariate_order(['var1','var8'])\n\nsee more at https://github.com/mwburke/stargazer/blob/master/examples.ipynb\n" ]
[ 0 ]
[]
[]
[ "python", "stargazer" ]
stackoverflow_0073585682_python_stargazer.txt
Q: Python colored output doesn't work except when piping I'm using Git Bash on Windows inside Windows Terminal and I'm writing a python script which needs to output colored text. As an example, I have the following one-line script named example.py: print('\033[35m\033[K' + 'hello world' + '\033[m\033[K') When I run ...
Python colored output doesn't work except when piping
I'm using Git Bash on Windows inside Windows Terminal and I'm writing a python script which needs to output colored text. As an example, I have the following one-line script named example.py: print('\033[35m\033[K' + 'hello world' + '\033[m\033[K') When I run the command python example.py, I expect to see colored outp...
[ "For the record, I tried the following basic script,\n#!/usr/bin/python3.8\nprint('\\033[35m\\033[K' + 'hello world' + '\\033[m\\033[K')\n\nand I got the result which you were likely looking for, namely\n\nSince you mentioned bash, to get what you wanted, you need to read the section of the bash man page for printf...
[ 0 ]
[]
[]
[ "bash", "colors", "git_bash", "python", "windows_terminal" ]
stackoverflow_0074584828_bash_colors_git_bash_python_windows_terminal.txt
Q: sublist to dictionary So I have: a = [["Hello", "Bye"], ["Morning", "Night"], ["Cat", "Dog"]] And I want to convert it to a dictionary. I tried using: i = iter(a) b = dict(zip(a[0::2], a[1::2])) But it gave me an error: TypeError: unhashable type: 'list' A: Simply: >>> a = [["Hello", "Bye"], ["Morning", "Ni...
sublist to dictionary
So I have: a = [["Hello", "Bye"], ["Morning", "Night"], ["Cat", "Dog"]] And I want to convert it to a dictionary. I tried using: i = iter(a) b = dict(zip(a[0::2], a[1::2])) But it gave me an error: TypeError: unhashable type: 'list'
[ "Simply:\n>>> a = [[\"Hello\", \"Bye\"], [\"Morning\", \"Night\"], [\"Cat\", \"Dog\"]]\n>>> dict(a)\n{'Cat': 'Dog', 'Hello': 'Bye', 'Morning': 'Night'}\n\nI love python's simplicity\nYou can see here for all the ways to construct a dictionary:\n\nTo illustrate, the following examples all return a dictionary equal t...
[ 8, 0 ]
[]
[]
[ "dictionary", "list", "python", "sublist" ]
stackoverflow_0015875678_dictionary_list_python_sublist.txt
Q: AWS Batch Job Execution Results in Step Function I'm newbie to AWS Step Functions and AWS Batch. I'm trying to integrate AWS Batch Job with Step Function. AWS Batch Job executes simple python scripts which output string value (High level simplified requirement) . I need to have the python script output available t...
AWS Batch Job Execution Results in Step Function
I'm newbie to AWS Step Functions and AWS Batch. I'm trying to integrate AWS Batch Job with Step Function. AWS Batch Job executes simple python scripts which output string value (High level simplified requirement) . I need to have the python script output available to the next state of the step function. How I should be...
[ "I was able to do it, below is my state machine, I took the sample project for running the batch job Manage a Batch Job (AWS Batch, Amazon SNS) and modified it for two lambdas for passing input/output.\n{\n \"Comment\": \"An example of the Amazon States Language for notification on an AWS Batch job completion\",\n...
[ 4, 2, 0 ]
[]
[]
[ "amazon_web_services", "aws_batch", "aws_step_functions", "python" ]
stackoverflow_0065835855_amazon_web_services_aws_batch_aws_step_functions_python.txt