answerstu

python - How can I keep track of which text entry is clicked?

If I have a Tkinter Text widget with the text bound to a mouse click, how can I keep track of which text the user clicks on? I want the function to return the number of the label clicked, but as it stands it only prints the last value of n which is 5. For example, if the user clicks "Name 1", I want it to print "1", if the user clicks on "Name 2", I want it to return "2".Here is the code:import tkinter as tkdef prt(num): print(num)root = tk.Tk()t = tk.Text(root, height=20, width=50)t.pack()for n in range(1, 6): t.insert(tk.END, "%s %d\n" ...Read more

python - How to add a Slack reaction to a send_card

I have an Errbot function that sends a Slack card. How do I then add a reaction to the card instead of the original message(msg) that was received?@botcmddef example(self, msg): self.send_card(title='Test', body='test123', thumbnail=' ', image=' ', link=' ', color='green', in_reply_to=msg) self._bot.add_reaction(card_msg??, 'grey_question')...Read more

Python 3.4 - Pandas - Help in proper arrangement of dataframe columns and deletion of invalid columns

This question is based on Python - Pandas - Combining rows of multiple columns into single row in dataframe based on categorical value which I had asked earlier.I have a table in the following format: Var1 Var2 Var3 Var4 ID 0 0.70089 0.93120 1.867650 0.658020 1 1 0.15893 -0.74950 1.089150 -0.045123 1 2 0.13690 0.59210 -0.032990 0.672860 1 3 -0.50136 0.89913 0.440200 0.812150 1 4 1.08940 0.43036 0.669470 1.286000 1 5 ...Read more

How to conserve the pdf layout after converting content from English to French using Python

I am working on a simple application which will help me to convert all my pdf files which have text in English to French text as pdf. I have worked on a simple proof of concept which helps me to iterate over the given file and convert all text into French. Now I am stuck on saving the converted french text into a pdf with a similar structure of the original English version. import PyPDF2from googletrans import Translatortranslator = Translator()read_pdf = PyPDF2.PdfFileReader(open('any_english.pdf', 'rb'))write_pdf = PyPDF2.PdfFileWriter()numbe...Read more

python - Error while trying to install packages from conda using graphlab create launcher

I keep getting the following error while trying to install https://turi.com/download/install-graphlab-create.htmlhere was a problem updating the conda package. Restart GraphLab Create Launcher.Unable to update conda:Using Anaconda Cloud api site https://api.anaconda.orgFetching package metadata: ..Solving package specifications: .Error: Packages/dependencies missing in current osx-64 channels: - conda 4.0.8* - conda -> python 2.7* -> openssl 1.0.2d - conda -> conda-env -> python 2.7* -> openssl 1.0.2d - conda -> request...Read more

cassandra - 'CREATE' in Python String causing KeyError with " 'class' "

I'm trying to make a class of commands for Cassandra (A NoSQL database) using "Python-Driver". You can use session.execute() to run SQL commands on your Database. Anyway, I'm trying to make a function to create a keyspace. Here is the code:def createKeySpace(self, title, class_type='SimpleStrategy', replication_factor='3'): self.session.execute("CREATE KEYSPACE {} WITH REPLICATION = \ { 'class' : '{}', 'replication_factor' : {} };\ ".format(title, class_type, replication_factor))The issue is, if I try to use this function, I get the er...Read more

python - Can insertion in dictionary cause KeyError?

Can this code ever produce KeyError? I'm new to python, just want some clarification as I checked insertion can't cause KeyError Exception.def add(self, name, company): try: self.identity[self.id] = { 'name': name, 'company': company } return self.identity except KeyError: raise NameNotAddedHere identity is a Dictionary and id is an int initialized somewhere else and NameNotAdded is a custom exception....Read more

xml - Python Except Specific Key Error

I'm parsing an XML file using Beautiful Soup. Sometimes I have entries that are missing one or more of the keys I'm parsing. I want to setup exceptions to handle this. My code looks something like this:for entry in soup.findAll('entry_name'): try: entry_dict = dict(entry.attrs) x = entry_dict["x"] y = entry_dict["y"] z = entry_dict["z"] d[x] = [y, z] except KeyError: y = "0" d[x] = [y, z]The problem is I can have "y", "z" or both "y and z" missing depending on the entry. Is there a way to ...Read more

python - Django Exception Type: KeyError Exception Value: 'pk'

I am probably doing something stupid but cant figure out what and it makes me insane since it is trivial and I have other apps working with same logic.So I have a Model Customer and Model Notes. Each customer I can create a lot of Notes.In Notes Customer is defined as Foreign key .view.py @login_requireddef note_new(request,pk): contact = get_object_or_404(Contacts, pk=pk) if request.method == "POST": form = NoteForm(request.POST) if form.is_valid(): note = form.save(commit=False) note.pub_date = time...Read more

Python - KeyError: '\n'

Right, so I downloaded a Python program to decode DNA sequences. It was meant for Python 2.7 but whatever I do pip installs it into Python 3.6. So I added the brackets for the print functions, and it becomes usable. Command line code below:kevin@Kevin-Jia:~$ sudo pip install file2dnaCollecting file2dna Using cached file2dna-0.4.tar.gzInstalling collected packages: file2dna Running setup.py install for file2dna ... doneSuccessfully installed file2dna-0.4kevin@Kevin-Jia:~$ sudo nano /usr/lib/python3.6/site-packages/dna/dna.pykevin@Kevin-Jia:~$ ...Read more

python - Why didn't I get a KeyError when the key did not exist?

In the following test data, I am trying to append key 'x' value to the list ls. My question is why I didn't get a KeyError when looping through the first row of the data. Clearly, the first row does not contain the key 'x'. Originally I thought I had to use Try/Except to avoid getting an error when looping through the data, but it seems that Try/Except is not needed. Could anyone help me understand why a KeyError is not generated here?data = [{u'xyz': []}, {u'xyz': [{u'x' : 2, u'y' : 3, u'z' : 4}]}]ls...Read more

python - py2exe converted script does not run win32com.client correctly

I have seen a couple posts related to my issue on other sites, but nothing worked. To make a long story short, my program importa win32com.client to access Microsoft Word. I create a standalone executable using py2exe and every time the user selects the option to open MS Word I get a KeyError. Below is the code which the compiler claims the error is:# Call the MS Word appMS_Word = win32com.client.gencache.EnsureDispatch('Word.application')And below is the result when the program run this particular line:Exception in Tkinter callbackTraceback (m...Read more

python - KeyError: 'column_name'

I am writing a python code, it should read the values of columns but I am getting the KeyError: 'column_name' error. Can anyone please tell me how to fix this issue. import numpy as npfrom sklearn.cluster import KMeansimport pandas as pd### For the purposes of this example, we store feature data from our### dataframe `df`, in the `f1` and `f2` arrays. We combine this into### a feature matrix `X` before entering it into the algorithm.df = pd.read_csv(r'C:\Users\Desktop\data.csv')print (df)#df = pd.read_csv(csv_file)"""saved_column = df.Distance_...Read more

python - KeyError when using for loop on dataframe to plot histograms

I have a dataframe similar to: df = pd.DataFrame({'Date': ['2016-01-05', '2016-01-05', '2016-01-05', '2016-01-05', '2016-01-08', '2016-01-08', '2016-02-01'], 'Count': [1, 2, 2, 3, 2, 0, 2]})and I am trying to plot a histogram of Count for each unique DateI've tried: for date in df.Date.unique(): plt.hist([df[df.Date == '%s' %(date)]['Count']]) plt.title('%s' %(date))which results in ---------------------------------------------------------------------------KeyError Traceback (most recent call last)<ipy...Read more

python - A strange keyerror is preventing me from testing my logit regression classifier?

I'm trying to run a logit regression from statsmodel in python in a for loop. So I'm appending a row each time from the test data into my training data dataframe and rerunning the regression and storing the results.Now, funny thing is, the test data is not getting appended correctly (which I think is causing the KeyError:0 that I am getting, but inviting your opinions here). I've tried importing two versions of the test data- one with the same labels as training data and another with no declared labels.Here is my code:import pandas as pdimport ...Read more