how to make key event wxpython in textctrl? - event-handling

here is my code
python 2.7 & wxpython 2.8
http://pastie.org/4248326
these 3 textctrl, at the chat_c(textctrl)
i want to make chat_c and text_c like a chatting room
input is chat_c output is text_c
that is why i use
def OnReturnDown(self,e):
key = e.GetKeyCode()
self.text_c.SetValue(key) #for check out but doesn't work
if key == wx.WXK_RETURN:
self.text_c.SetValue(self.chat_c.GetValue())
#key bind
self.chat_c.Bind(wx.EVT_KEY_DOWN, self.OnReturnDown)
this is error message
Traceback (most recent call last):
File "C:\workspace\wx_python_test\main_chat_client.py", line 239, in OnReturnDown
self.text_c.SetValue(key) #for check out but doesn't work
File "C:\Python27\Lib\site-packages\wx-2.8-msw-unicode\wx\_controls.py", line 1754, in SetValue
return _controls_.TextCtrl_SetValue(*args, **kwargs)
TypeError: String or Unicode type required
what is that? Unicode type required???
maybe change the style of textctrl?
how can fix this?

e.GetKeyCode() returns an int. You don't pass an int to a text control. A text control only takes a string or a unicode string. So you'll need to cast the int into a string or do something else. Here's how to cast it:
key = str( e.GetKeyCode() )

Related

How to use the __post_init__ method in Dataclasses in Python

I am trying to get my hands dirty with dataclasses in Python and what i want to do is have a computed field inside my class and also add the sort_index field to the call but would also want to make it frozen so that i cannot modify any attributes of this class after definition. Below is my code:
from dataclasses import dataclass, field
def _get_year_of_birth(age: int, current_year: int=2019):
return current_year - age
#dataclass(order=True, frozen=True)
class Person():
sort_index: int = field(init=False, repr=False)
name: str
lastname: str
age: int
birthyear: int = field(init=False)
def __post_init__(self):
self.sort_index = self.age
self.birthyear = _get_year_of_birth(self.age)
if __name__ == "__main__":
persons = [
Person(name="Jack", lastname="Ryan", age=35),
Person(name="Jason", lastname="Bourne", age=45),
Person(name="James", lastname="Bond", age=60)
]
sorted_persons = sorted(persons)
for person in sorted_persons:
print(f"{person.name} and {person.age} and year of birth is : {person.birthyear}")
It seems that i cannot set a custom sort field inside my class and also cannot create any attribute which is computed from other attributes since i am using frozen . When i run the above i get the below error:
Traceback (most recent call last):
File "dataclasses_2.py", line 30, in <module>
Person(name="Jack", lastname="Ryan", age=35),
File "<string>", line 5, in __init__
File "dataclasses_2.py", line 23, in __post_init__
self.sort_index = self.age
File "<string>", line 3, in __setattr__
dataclasses.FrozenInstanceError: cannot assign to field 'sort_index'
Is there a better way of doing this ? Please help
The problem is you are trying to set a field of a frozen object.
There are two options here. First option would be to remove frozen=True from the dataclass specification. Secondly, if you still want to freeze Person instances, then you should initialize fields with method __setattr__. Therefore, your post_init method will become:
def __post_init__(self):
object.__setattr__(self, 'sort_index', self.age)
object.__setattr__(self, 'birthyear', _get_year_of_birth(self.age)

Where do I put end_editing() in Pythonista?

I’m making a little pricing tool in Pythonista. Here’s what I wrote.
# starts actions with go button
def getPrices(mtmPriceUser):
viewSelector = mtmPriceUser.superview
userInput = viewSelector['textview1'].text
userInput = float(userInput)
textLabel1 = v['label1']
discNamesList, discOutcomesdict = creatDiscList(standardDisc, userInput)
# create string of discounts and prices
priceString = createString(discNamesList,discOutcomesDict)
textLabel1.text = priceString
textLabel1.end_editing()
v = ui.load_view()
v.present('sheet')
I get the following error
Traceback (most recent call last):
File "/private/var/mobile/Containers/Shared/AppGroup/7C463C71-C565-47D8-A1D8-C2D588A974C1/Pythonista3/Documents/Pricing App/UI_Attempt.py", line 79, in getPrices
textLabel1.end_editing()
AttributeError: '_ui.Label' object has no attribute 'end_editing'
Where do I use the end editing method? If I can’t, how else can I get the keyboard to go away after I push the button?
You seem to be calling end_editing() on a label, which does not have this method.
You need to call the method on the TextField or TextView object that was used for data entry.
In your case, this seems to be viewSelector['textview1'] which might be worth storing in a variable for simplicity, like you do with the label.
For example:
text_entry = viewSelector['textview1']
userInput = text_entry.text
# Your other code
text_entry.end_editing()

'PipelinedRDD' object has no attribute '_get_object_id'

I´ve got an issue trying to replicate the example I saw here - https://learn.microsoft.com/en-us/azure/hdinsight/spark/apache-spark-load-data-run-query.
It seems to fail when it comes to : hvacTable = sqlContext.createDataFrame(hvac)
and the error it returns is:
'PipelinedRDD' object has no attribute '_get_object_id'
Traceback (most recent call last):
File "/usr/hdp/current/spark2-client/python/pyspark/sql/context.py", line 333, in createDataFrame
return self.sparkSession.createDataFrame(data, schema, samplingRatio, verifySchema)
File "/usr/hdp/current/spark2-client/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1124, in __call__
args_command, temp_args = self._build_args(*args)
File "/usr/hdp/current/spark2-client/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1094, in _build_args
[get_command_part(arg, self.pool) for arg in new_args])
File "/usr/hdp/current/spark2-client/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py", line 289, in get_command_part
command_part = REFERENCE_TYPE + parameter._get_object_id()
AttributeError: 'PipelinedRDD' object has no attribute '_get_object_id'
I´m following the example to a T, it´s a pyspark notebook in Jupyter.
Why is this error occurring?
you probably running it on newer cluster. Please update "sqlContext" to "spark" to get it to work. We'll update this doc article as well.
Also in Spark 2.x you can now do this operation with DataFrames which simpler. You can replace the snippet creating hvac table with following equivalent:
csvFile = spark.read.csv('wasb:///HdiSamples/HdiSamples/SensorSampleData/hvac/HVAC.csv', header=True, inferSchema=True)
csvFile.write.saveAsTable("hvac")

iOS JavascriptCore exception detailed stacktrace info

It seems the exception stacktrace in iOS only contains the method name or there is a bug. Below is my code of handling exceptions in JSContext.
context.exceptionHandler = { (ctx: JSContext!, value: JSValue!) in
// type of String
let stacktrace = value.objectForKeyedSubscript("stack").toString()
// type of Number
let lineNumber = value.objectForKeyedSubscript("line")
// type of Number
let column = value.objectForKeyedSubscript("column")
let moreInfo = "in method \(stacktrace)Line number in file: \(lineNumber), column: \(column)"
Logger.error("JS ERROR: \(value) \(moreInfo)")
}
And I got logs like below
ERROR : JSContextRenderer.swift:308 : setupContext : JS ERROR: Error in method clearBackground
Line number in file: 162, column: 12"
Note there is a new line right after the "clearBackground" name, I think there probably more information there.
Can anybody having similar experience confirm? Any help is appreciated. Thanks.
Looks like it does show more information in the stack. Here is one of the log information I got:
JS ERROR: TypeError: undefined is not a function (evaluating 'msg.__assert__()') in method assert
syncShots
updateSync
initSync
setState
onLogicStateChanged
onLogicStateChanged
[native code]
updateMove
sendMove
shoot
onTouchUp
[native code]
_handleEvent
_dispatchEvent
. Line number in file: 183, column: 20
Long ago, #igrek asked where the keys in value come from. They're part of the Error object that was thrown by the JavaScript engine, and that now appears as value in the native error handler callback. What exactly Error includes depends on the implementation, but typically includes message, fileName, and lineNumber. It appears that stack is also supported. More details on the MDN page for Error .

Why do I get mysterious "TypeError: can only update value with String or number"?

This is really bizarre. If I run this code (as a nose test), it prints "-0:34:00.0" and all is well
def test_o1(self):
observer = ephem.Observer()
observer.lon, observer.lat = math.radians(73.9), math.radians(40.7)
observer.horizon = '-0:34'
print observer.horizon
but, if I run this:
def test_o2(self):
location = UserLocation()
location.foo()
where UserLocation is:
# Document is mongoengine.Document
class UserLocation(Document):
[...]
def foo(self):
observer = ephem.Observer()
observer.lon, observer.lat = math.radians(73.9), math.radians(40.7)
observer.horizon = '-0:34'
I get:
Traceback (most recent call last):
File "/home/roy/deploy/current/python/local/lib/python2.7/site-packages/nose/case.py", line 197, in runTest
self.test(*self.arg)
File "/home/roy/deploy/current/code/pyza/models/test_user_location.py", line 82, in test_o2
location.foo()
File "/home/roy/deploy/current/code/pyza/models/user_location.py", line 134, in foo
observer.horizon = '-0:34'
TypeError: can only update value with String or number
Any idea what might be going on?
Arrggghhh. I figured it out. My UserLocation source file starts with:
from future import unicode_literals
apparently, _libastro insists on ascii strings, not unicode.