Python pass value in class and def using .self - python

I want to pass some values to a def but am having issues with properly adding this.
In
class MyAddin():
def __init__(self, imapinfopro, thisApplication): #also tried including _self.Table_Path in this.
try:
self._pro = imapinfopro
self._thisApplication = thisApplication
self._tab = None
#self._table_path =(r'D:\junk\28355.tab')
# Some standard variables to allow functions to be created for each action for easier use. r_ is for Ribbon actions
r_item_name="Infrastructure_Data" #Name of button on main ribbon (no spaces allowed)
r_button_name="Water" #same as operations in the ribbon_customization.py
r_subroup_name="Not Abandoned" #same as "Table" and "CallBack" in the ribbon_customization.py
r_subgroup_action="Open\nClose" #same as 'MB Handler\nNo Parameter'in the ribbon_customization.py
tab = self._pro.Ribbon.Tabs.Add(r_item_name)
self._tab = tab
if tab:
group = tab.Groups.Add(r_button_name, r_button_name)
if group:
button = group.Controls.Add("ButtonOpenTable", r_subroup_name, ControlType.Button)
button.IsLarge = True
button.LargeIcon = CommonUtil.path_to_uri("pack://application:,,,/MapInfo.StyleResources;component/Images/Mapping/infoTool_32x32.png")
button.SmallIcon = CommonUtil.path_to_uri("pack://application:,,,/MapInfo.StyleResources;component/Images/Mapping/infoTool_16x16.png")
button.Command = AddinUtil.create_command(self.open_table_click)
except Exception as e:
print("Failed to load: {}".format(e))
def open_table_click(self, sender):
#table_path=(r'D:\junk\28355.tab') #if left in this is used to open the table but I want to get this value from button.Command above.
table = self._pro.Catalog.OpenTable(table_path)
CommonUtil.do("map from {}".format(table.Alias))
CommonUtil.do("browse * from {}".format(table.Alias))
pass
I want to send the value for table_path in to def open_table_click from button.Command = AddinUtil.create_command(self.open_table_click). If it wasn't a self call it would be ..._command(self.open_table_click, tablepath) and def open_table_click(self, sender, table_path):

Related

Dynamically add and remove list items in an IPython widget

I'm trying to achieve a basic todo list app in Ipython Jupyter Notebook using ipywidgets.
I can easily achieve the functionality of adding items to my list, however, I can't properly handle removing of existing items if the 'Remove' button is clicked. The entire code is run in a single cell.
import ipywidgets as widgets
from ipywidgets import VBox, HBox, Text, Button
from IPython.display import display
todo = []
def completed_sentence(sentence):
""" To display existing notes with a 'Remove' button """
sentenceField = Text(value=sentence)
removeButton = Button(description='Remove',
button_style='danger')
return HBox([sentenceField, removeButton])
def render_sentences(_):
""" To update the view """
global a,b
if a.value != '':
todo.append(a.value)
a.value = ''
todoWidget.children = tuple\
([VBox([VBox([completed_sentence(each)
for each in todo]),
HBox([a, b])])])
# Setting up a basic view- with an empty field and a button
a = widgets.Text(value='')
b = widgets.Button(description='Add')
b.on_click(render_sentences)
todoWidget = widgets.HBox([a, b])
display(todoWidget)
Now, in order to enable the removal of sentences, I update the definition of the function completed_sentence as follows:
def completed_sentence(sentence):
""" To display existing notes """
def remove_sentence(_):
global render_sentences
try:
if todo.index(sentenceField.value) >= 0:
todo.remove(sentenceField.value)
render_sentences()
except:
return
sentenceField = Text(value=sentence)
removeButton = Button(description='Remove', button_style='danger')
removeButton.on_click(remove_sentence)
return HBox([sentenceField, removeButton])
But now, this has the issue that its call to render_sentences is ignored! What is the optimal way to deal with such a kind of 'reactive' programming, if you will, using Ipython Widgets.
Updating the definition of completed_sentence seems to do the job. But it still remains a mystery why the original definition didn't work.
def completed_sentence(sentence):
def remove_sentence(_):
global render_sentences
try:
if todo.index(sentenceField.value) >= 0:
todo.remove(sentenceField.value)
except:
pass
render_sentences(_)
sentenceField = Text(value=sentence)
removeButton = Button(description='Remove', button_style='danger')
removeButton.on_click(remove_sentence)
sentence_view = HBox([sentenceField, removeButton])
return sentence_view

Blender 2.80: handle exceptions in the dialog

I created a dialog in blender 2.80 to be able to insert some values and send them through the "Ok" button.
Inside the "execute" function some operations are performed and, at the end, the window is closed. However, in case of exceptions, the problem must be handled by notifying the user and leaving the dialog box open. To do this I use a try-catch block but it does not work: in case of exception the dialog box closes whatever the returned value.
Is there any way to fix this?
#subscribe
class Test(Operator):
bl_idname = "bl_idname"
bl_label = "bl_label"
bl_description = "bl_description"
input_a = bpy.props.StringProperty(
name = "name_a",
default = "default"
)
input_b = bpy.props.StringProperty(
name = "name_b",
default = "default"
)
input_c = bpy.props.StringProperty(
name = "name_c",
default = "default"
)
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(self, width = 450)
def draw(self, context):
col = self.layout.column(align = True)
col.prop(self, "input_a")
col = self.layout.column(align = True)
col.prop(self, "input_b")
col = self.layout.column(align = True)
col.prop(self, "input_c")
def execute(self, context):
try:
#something...
return {"FINISHED"}
except Exception as e:
print(str(e))
return {"CANCELLED"} #I also tried RUNNING_MODAL or PASS_THROUGH

Python class recording attributes without specifying self ?

I have a question regarding a Python class I use in Blender. Basically, I wonder how the class works because some attributes are recorded without me specifically writing self.value = something. Here's the code:
class DialogOperator(bpy.types.Operator):
bl_idname = "object.dialog_operator"
bl_label = "Save/Load animation"
saving = bpy.props.BoolProperty(name="Save ? Else load.")
path_to_anim = bpy.props.StringProperty(name="Path to folder")
anim_name = bpy.props.StringProperty(name="Animation name:")
# path_to_anim += "/home/mehdi/Blender/Scripts/"
def execute(self, context):
# print('This is execute with: Saving: {} Name:{}'.format(self.saving, self.path_to_anim))
if self.saving:
self.launch_save()
message = 'Animation {} saved at {}'.format(self.anim_name, self.path_to_anim)
else:
self.launch_load()
message = 'Animation {} loaded'.format(self.anim_name)
self.report({'INFO'}, message)
return {'FINISHED'}
def invoke(self, context, event):
wm = context.window_manager
return wm.invoke_props_dialog(self)
def launch_load(self):
full_path = self.path_to_anim + self.anim_name
target_armature = Humanoid(bpy.data.objects['Armature'])
load_all(full_path, target_armature, 'LastLoaded')
def launch_save(self):
full_path = self.path_to_anim + self.anim_name
source_armature = Humanoid(bpy.data.objects['Armature'])
curves = source_armature.get_curves()
save_all(curves, source_armature,full_path)
Now, how come saving, path_to_anim and anim_name are considered as attributes (I'm able to call them in execute() and launch()) even though I did not write self.saving = saving
Thanks !
This is because saving,path_to_anim and anim_name are class attributes. They are defined for the class and not for a particular instance. They are shared among the instances. Here is a link for further explanation class-instance-attributes-python

Python UNO on LibreOffice Calc, rehoming a cursor

LibreOffice 5.3, python 3.53, VOID Linux
This is more of an uno question than a python question. The code below does a simple update of 3 cells. 3 buttons configured on the sheet calling dowriteonce() dowritetwice() and dowritethrice(), and they all update and work like you might expect writing numbers and text to selected cells.
Where the problem comes in, is that when a cell is edited in the UI by a user, any subsequent update of that cell by means of executing the function is blocked. So simply clicking cell C4 in the calc UI, prevents the writethrice() function from updating cell C4. If I delete the content and click another cell in the UI, say C5, then everything works normally again and C4 updates when the button is clicked.
What I would like to do is relocate the UI edit-cursor to an unused cell prior to execution in order to prevent this. User copy-paste is going to leave the active cursor in unpredictable places and that will bork calculations if I can't isolate the cursor.
So the question is, how do I move the UI edit cursor to a named cell via the UNO API, with Python? Or if it is easier, just deactivate it temporarily.
Python:
import socket
import sys
import re
import uno
import unohelper
class ODSCursor(unohelper.Base):
# predeclare class properties
ctx=None
desktop=None
model=None
activesheet=None
counter=0
scooby="Scooby"
# import namespaces
def __init__(self):
import socket
import uno
import unohelper
import sys
import re
# initialize uno handle only once and get the first sheet
#classmethod
def sheet1(cls,*args):
if cls.activesheet is not None:
return (cls.activesheet)
cls.ctx = uno.getComponentContext()
cls.desktop = cls.ctx.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", cls.ctx)
cls.model = cls.desktop.getCurrentComponent()
# cls.activesheet = cls.model.Sheets.getByName("Sheet1")
cls.activesheet = cls.model.Sheets.getByIndex(0)
return (cls.activesheet)
#classmethod
def writeonce(self,*args):
self.counter += 1
cell_b1 = self.activesheet.getCellRangeByName("B1")
cell_b1.String = self.counter
#classmethod
def writetwice(self,*args):
self.counter += 1
cell_b2 = self.activesheet.getCellRangeByName("B2")
cell_b2.String = self.counter
#classmethod
def writescooby(self,*args):
cell_c4 = self.activesheet.getCellRangeByName("C4")
cell_c4.String = self.scooby
### BUTTON BOUND FUNCTIONS ###
def dowriteonce(*args):
Odc = ODSCursor() # create the object
Odc.sheet1()
Odc.writeonce()
def dowritetwice(*args):
Odc = ODSCursor() # create the object
Odc.sheet1()
Odc.writetwice()
def dowritethrice(*args):
Odc = ODSCursor() # create the object
Odc.sheet1()
Odc.writescooby()
In the following code, cells are deselected before changing the values, then selected again. This way, cells can be modified even when left in edit mode by the user.
There also seems to be some confusion about Python class methods and variables, so I changed those parts as well.
import uno
import unohelper
SCOOBY = "Scooby"
class ODSCursor(unohelper.Base):
def __init__(self):
self.ctx = None
self.desktop = None
self.document = None
self.controller = None
self.sheet = None
self.counter = 0
def sheet1(self):
"""Initialize uno handle only once and get the first sheet."""
if self.sheet is not None:
return self.sheet
self.ctx = uno.getComponentContext()
self.desktop = self.ctx.ServiceManager.createInstanceWithContext(
"com.sun.star.frame.Desktop", self.ctx)
self.document = self.desktop.getCurrentComponent()
self.controller = self.document.getCurrentController()
self.sheet = self.controller.getActiveSheet()
return self.sheet
def writeonce(self):
self.writeval("B1", self.inc())
def writetwice(self):
self.writeval("B2", self.inc())
def writescooby(self):
self.writeval("C4", SCOOBY)
def writeval(self, address, value):
self.deselect()
cell = self.sheet.getCellRangeByName(address)
cell.String = value
self.controller.select(cell)
def deselect(self):
"""Select cell A1, then select nothing."""
cell_a1 = self.sheet.getCellByPosition(0, 0)
self.controller.select(cell_a1)
emptyRanges = self.document.createInstance(
"com.sun.star.sheet.SheetCellRanges")
self.controller.select(emptyRanges)
def inc(self):
"""Increment the counter and return the value."""
self.counter += 1
return self.counter
odsc = ODSCursor()
### BUTTON BOUND FUNCTIONS ###
def dowriteonce(dummy_oEvent):
odsc.sheet1()
odsc.writeonce()
def dowritetwice(dummy_oEvent):
odsc.sheet1()
odsc.writetwice()
def dowritethrice(dummy_oEvent):
odsc.sheet1()
odsc.writescooby()

Can anybody help me with this python TypeError

As a new learner's question,this question may be very simple, but I have tried for many hours and cannot find the answer, sorry.
this is the a problem form edx's python course.
I will paste all of the code, But I have finished most of it and get correct。 The Part 4 is which I am going on.
first, the file's content is:
# subject trigger named t1
t1 SUBJECT world
# title trigger named t2
t2 TITLE Intel
# phrase trigger named t3
t3 PHRASE New York City
# composite trigger named t4
t4 AND t2 t3
# the trigger set contains t1 and t4
ADD t1 t4
,
import feedparser
import string
import time
from project_util import translate_html
from Tkinter import *
#======================
# Code for retrieving and parsing RSS feeds
#======================
def process(url):
"""
Fetches news items from the rss url and parses them.
Returns a list of NewsStory-s.
"""
feed = feedparser.parse(url)
entries = feed.entries
ret = []
for entry in entries:
guid = entry.guid
title = translate_html(entry.title)
link = entry.link
summary = translate_html(entry.summary)
try:
subject = translate_html(entry.tags[0]['term'])
except AttributeError:
subject = ""
newsStory = NewsStory(guid, title, subject, summary, link)
ret.append(newsStory)
return ret
#======================
# Part 1
# Data structure design
#======================
class NewsStory(object):
def __init__(self, guid, title, subject, summary, link):
self.guid = guid
self.title = title
self.subject = subject
self.summary = summary
self.link = link
def getGuid(self):
return self.guid
def getTitle(self):
return self.title
def getSubject(self):
return self.subject
def getSummary(self):
return self.summary
def getLink(self):
return self.link
#======================
# Part 2
# Triggers
#======================
class Trigger(object):
def evaluate(self, story):
"""
Returns True if an alert should be generated
for the given news item, or False otherwise.
"""
raise NotImplementedError
# Whole Word Triggers
class WordTrigger(Trigger):
def __init__(self, word):
self.word = word
def changeText(self, text):
for i in string.punctuation:
text = text.replace(i, ' ')
return text
def isWordIn(self, text):
return self.word.upper in self.changeText(self, text.upper()).split()
class TitleTrigger(WordTrigger):
def evaluate(self, story):
return self.isWordIn(self, story.getTitle())
class SubjectTrigger(WordTrigger):
def evaluate(self, story):
return self.isWordIn(self, story.getSubject())
class SummaryTrigger(WordTrigger):
def evaluate(self, story):
return self.isWordIn(self, story.getSummary())
# Composite Triggers
class NotTrigger(Trigger):
def __init__(self, trigger):
self.trigger = trigger
def evaluate(self,story):
return not self.trigger.evaluate(story)
class AndTrigger(Trigger):
def __init__(self, trigger1, trigger2):
self.trigger1 = trigger1
self.trigger2 = trigger2
def evaluate(self, story):
return self.trigger1.evaluate(story) and self.trigger2.evaluate(story)
class OrTrigger(Trigger):
def __init__(self, trigger1, trigger2):
self.trigger1 = trigger1
self.trigger2 = trigger2
def evaluate(self, story):
return self.trigger1.evaluate(story) or self.trigger2.evaluate(story)
# Phrase Trigger
class PhraseTrigger(Trigger):
def __init__(self, phrase):
self.phrase = phrase
def evaluate(self, story):
return self.phrase in story.getSubject() or self.phrase in story.\
getSummary() or self.phrase in story.getTitle()
#======================
# Part 3
# Filtering
#======================
def filterStories(stories, triggerlist):
"""
Takes in a list of NewsStory instances.
Returns: a list of only the stories for which a trigger in triggerlist fires.
"""
temp = stories[:]
for i in stories:
for j in triggerlist:
if (not j.evaluate(i)) and j == triggerlist[-1]:
temp.remove(i)
elif j.evaluate(i):
break
stories = temp[:]
return stories
This is what I have done and get correct. because the next function needs TitleTrigger,SubjectTrigger,SummaryTrigger,NotTrigger,AndTrigger,PhraseTrigger,OrTrigger, and all the triggers need the NewsStory, so I keep them.
#======================
# Part 4
# User-Specified Triggers
#======================
def makeTrigger(triggerMap, triggerType, params, name):
"""
Takes in a map of names to trigger instance, the type of trigger to make,
and the list of parameters to the constructor, and adds a new trigger
to the trigger map dictionary.
triggerMap: dictionary with names as keys (strings) and triggers as values
triggerType: string indicating the type of trigger to make (ex: "TITLE")
params: list of strings with the inputs to the trigger constructor (ex: ["world"])
name: a string representing the name of the new trigger (ex: "t1")
Modifies triggerMap, adding a new key-value pair for this trigger.
Returns a new instance of a trigger (ex: TitleTrigger, AndTrigger).
"""
if triggerType == 'TITLE':
triggerMap[name] = TitleTrigger
if triggerType == 'SUBJECT':
triggerMap[name] = SubjectTrigger
if triggerType == 'PHRASE':
triggerMap[name] = PhraseTrigger
if triggerType == 'SUMMARY':
triggerMap[name] = SummaryTrigger
if triggerType == 'AND':
triggerMap[name] = AndTrigger
if triggerType == 'OR':
triggerMap[name] = OrTrigger
if triggerType == 'NOT':
triggerMap[name] = NotTrigger
if triggerType == 'AND' or triggerType == 'OR':
tempt = triggerMap[name](triggerMap[params[0]],triggerMap[params[1]])
elif triggerType == 'NOT':
tempt = NotTrigger(triggerMap[params[0]])
else:
params = ' '.join(params)
tempt = triggerMap[name](params)
return tempt
def readTriggerConfig(filename):
triggerfile = open(filename, "r")
all = [ line.rstrip() for line in triggerfile.readlines() ]
lines = []
for line in all:
if len(line) == 0 or line[0] == '#':
continue
lines.append(line)
triggers = []
triggerMap = {}
for line in lines:
linesplit = line.split(" ")
# Making a new trigger
if linesplit[0] != "ADD":
trigger = makeTrigger(triggerMap, linesplit[1],
linesplit[2:], linesplit[0])
# Add the triggers to the list
else:
for name in linesplit[1:]:
triggers.append(triggerMap[name])
return triggers
This is the part I am working on, readTriggerConfig is given by teacher.
import thread
SLEEPTIME = 60 #seconds -- how often we poll
def main_thread(master):
# A sample trigger list - you'll replace
# this with something more configurable in Problem 11
try:
# TODO: Problem 11
# After implementing makeTrigger, uncomment the line below:
triggerlist = readTriggerConfig("triggers.txt")
# **** from here down is about drawing ****
frame = Frame(master)
frame.pack(side=BOTTOM)
scrollbar = Scrollbar(master)
scrollbar.pack(side=RIGHT,fill=Y)
t = "Google & Yahoo Top News"
title = StringVar()
title.set(t)
ttl = Label(master, textvariable=title, font=("Helvetica", 18))
ttl.pack(side=TOP)
cont = Text(master, font=("Helvetica",14), yscrollcommand=scrollbar.set)
cont.pack(side=BOTTOM)
cont.tag_config("title", justify='center')
button = Button(frame, text="Exit", command=root.destroy)
button.pack(side=BOTTOM)
# Gather stories
guidShown = []
def get_cont(newstory):
if newstory.getGuid() not in guidShown:
cont.insert(END, newstory.getTitle()+"\n", "title")
cont.insert(END, "\n---------------------------------------------------------------\n", "title")
cont.insert(END, newstory.getSummary())
cont.insert(END, "\n*********************************************************************\n", "title")
guidShown.append(newstory.getGuid())
while True:
print "Polling . . .",
# Get stories from Google's Top Stories RSS news feed
stories = process("http://news.google.com/?output=rss")
# Get stories from Yahoo's Top Stories RSS news feed
stories.extend(process("http://rss.news.yahoo.com/rss/topstories"))
# Process the stories
stories = filterStories(stories, triggerlist)
map(get_cont, stories)
scrollbar.config(command=cont.yview)
print "Sleeping..."
time.sleep(SLEEPTIME)
except Exception as e:
print e
if __name__ == '__main__':
root = Tk()
root.title("Some RSS parser")
thread.start_new_thread(main_thread, (root,))
root.mainloop()
the last part is given by teacher.thanks
I add a method named getWord in the SubjectTrigger,TitleTrigger,PhraseTrigger,and AndTrigger to get the word, phrase to see whether the tempt is right or not, and I do this before return:
print tempt
print tempt.getWord()
return tempt
And it gives me:
<__main__.SubjectTrigger object at 0x000000000849B898>
world
<__main__.TitleTrigger object at 0x000000000849B8D0>
Intel
<__main__.PhraseTrigger object at 0x000000000849B898>
New York City
<__main__.AndTrigger object at 0x000000000849B8D0>
(<class '__main__.TitleTrigger'>, <class '__main__.PhraseTrigger'>)
Polling . . .
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\python\ProblemSet7\ps7.py", line 292, in main_thread
stories = filterStories(stories, triggerlist)
File "C:\Users\Administrator\Desktop\python\ProblemSet7\ps7.py", line 161, in filterStories
if (not j.evaluate(i)) and j == triggerlist[-1]:
TypeError: unbound method evaluate() must be called with SubjectTrigger instance as first argument (got NewsStory instance instead)
It seems like I have gotten the right tempt, but with some error in the line 161
At least part of the problem is this line of code:
WordTrigger.changeText(self, text.upper()).split()
You've defined changeText as an instance method, but you are calling it on the class itself. Try changing it to this:
self.changeText(text.upper()).split()
You'll also need to make similar transformations to the other subclasses of WordTrigger.
Your first problem is apparently an instance creation with an unexpected number of arguments, but the second problem is that you're discarding the traceback that would tell you precisely where. In your code:
def main_thread(master):
# A sample trigger list - you'll replace
# this with something more configurable in Problem 11
try:
pass # Lots of code here
except Exception as e:
print e
You catch any exception, and print only the exception. Normal behaviour would print a full traceback of where it occurred. Either remove this try-except clause entirely, or use the traceback module to restore the more informative message:
except:
import traceback
traceback.print_exc()
On further reading, it appears your core problems are in makeTrigger, specifically how it uses different types in triggerMap. It attempts to first assign a class into the map, then use that class to create an instance, but the logic is flawed:
if triggerType == 'AND' or triggerType == 'OR':
tempt = triggerMap[name](triggerMap[params[0]],triggerMap[params[1]])
if triggerType == 'NOT':
tempt = NotTrigger(triggerMap[params[0]])
else:
params = ' '.join(params)
tempt = triggerMap[name](params)
Firstly, as you have found, the first if is distinct from the later ones; this block is not three branches but two branching paths in sequence, easily fixed by using elif. Secondly, triggerMap[name] never gets set to the created instances. This breaks the assumption made in the logic triggers, where triggerMap[params[n]] are expected to be trigger instances, not classes. Trying to evaluate a triggerMap entry led to the unbound method call. One way to fix this is simply triggerMap[name] = tempt.
We could also reduce the special cases quite a bit; I would consider replacing the triggerType ifs with a dictionary, and perhaps using subclasses to choose between the parameter types (triggers, words or phrases).

Categories