how to read a multiline element from PySimpleGUI - python-3.7

My program stub looks like this:
import PySimpleGUI as sg
layout = [[sg.Text("Geheime Nachricht eintippen:")],
[sg.Multiline(size=(70,4),key="GEHEIM")],
[sg.Spin([i for i in range(1,26)], initial_value=12, key="SS"), sg.Text("Schlüssel zwischen 1 und 25 wählen")],
[sg.Radio("Codieren:", "RADIO1", key="XX" ,default=True),
sg.Radio("Decodieren:","RADIO1", key="YY")],
[sg.Text("ERGEBNIS:")],
[sg.Multiline(size=(70,4),key="AUSGABE")],
[sg.Button("Weiter"), sg.Button("Ende")]]
window = sg.Window("Geheimcode", layout)
while True: # Ereignisschleife
event, values = window.Read()
geheimertext = values("GEHEIM")
print(values("GEHEIM"))
schluessel = int(values["SS"])
print ("Schlüssel = ", schluessel)
if values["XX"] == True:
codedecode = "C"
print("wir codieren:",codedecode)
else:
codedecode = "D"
print("wir decodieren:",codedecode)
if event is None or event == "Ende":
break
window.Close()
The program-line geheimertext = values("GEHEIM") gives this error:
TypeError: 'dict' object is not callable
I quess that the multiline generates a dictonary in the dictionary values?
so my simple newbie-question is how to read the multiline of a gui made with pysimpleGUI

ok, one possible solution is to iterate over the elements of the multiline:
geheimertext=""
for zeichen in values["GEHEIM"]:
geheimertext = geheimertext +zeichen
print(geheimertext)
Is there a better solution? Please teach a newbie

print(values["GEHEIM"])
values is a dict, and not a callable, so you cannot use () brackets (callables are functions or objects that have a function property). You can access to values through [] brackets. values["GEHEIM"].

Related

Write scale/nested conversion with ASAMMDF

I am using this snippet in order to create a mf4 file with a value to text table, found in the examples from asammdf's github.
vals = 5
conversion = {
'val_{}'.format(i): i
for i in range(vals)
}
conversion.update(
{
'text_{}'.format(i): 'key_{}'.format(i).encode('ascii')
for i in range(vals)
}
)
sig = Signal(
np.arange(cycles, dtype=np.uint32) % 30,
t,
name='Channel_value_to_text',
conversion=conversion,
comment='Value to text channel',
)
sigs.append(sig)
mdf.append(sigs, comment='arrays', common_timebase=True)
Is there a way to create a table with ##TX blocks and also ##CC blocks?(in order to simulate a scale conversion)
Thank you!
If anyone needs it, I found the answer and it was simpler than expected.
Create another conversion (i.e conversion2) in the same manner as the first one, then reassign the value of one of the references to it.
conversionBlock = from_dict(conversion)
conversionBlock.referenced_blocks["text_4"] = from_dict(conversion2)

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()

TYPO3/Typoscript : trim value failed

This is my typoscript code :
lib.test.renderObj = COA
lib.test.renderObj.10 = TEXT
lib.test.renderObj.10.stdWrap.field = header
lib.test.renderObj.10.stdWrap.case = lower
lib.test.renderObj.10.stdWrap.trim = 1
lib.test.renderObj.10.stdWrap.wrap = <div class="element">|</div>
The header field is well received, letters have been lowercased and the field is well wrapped by a element. The only problem is that i can't make the TRIM properties effective. I also tried to use the search/replace properties -> no success.
Any clue ? :)
You can search and replace since 4.6. The documentation you can find here: https://docs.typo3.org/typo3cms/TyposcriptReference/6.2/Functions/Replacement/
lib.test.renderObj.10.stdWrap.replacement {
10 {
search = # #
replace =
useRegExp = 1
}
}
Don't know if the replace is really working, can't test it.

cgi.parse_multipart function throws TypeError in Python 3

I'm trying to make an exercise from Udacity's Full Stack Foundations course. I have the do_POST method inside my subclass from BaseHTTPRequestHandler, basically I want to get a post value named message submitted with a multipart form, this is the code for the method:
def do_POST(self):
try:
if self.path.endswith("/Hello"):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers
ctype, pdict = cgi.parse_header(self.headers['content-type'])
if ctype == 'multipart/form-data':
fields = cgi.parse_multipart(self.rfile, pdict)
messagecontent = fields.get('message')
output = ""
output += "<html><body>"
output += "<h2>Ok, how about this?</h2>"
output += "<h1>{}</h1>".format(messagecontent)
output += "<form method='POST' enctype='multipart/form-data' action='/Hello'>"
output += "<h2>What would you like to say?</h2>"
output += "<input name='message' type='text'/><br/><input type='submit' value='Submit'/>"
output += "</form></body></html>"
self.wfile.write(output.encode('utf-8'))
print(output)
return
except:
self.send_error(404, "{}".format(sys.exc_info()[0]))
print(sys.exc_info() )
The problem is that the cgi.parse_multipart(self.rfile, pdict) is throwing an exception: TypeError: can't concat bytes to str, the implementation was provided in the videos for the course, but they're using Python 2.7 and I'm using python 3, I've looked for a solution all afternoon but I could not find anything useful, what would be the correct way to read data passed from a multipart form in python 3?
I've came across here to solve the same problem like you have.
I found a silly solution for that.
I just convert 'boundary' item in the dictionary from string to bytes with an encoding option.
ctype, pdict = cgi.parse_header(self.headers['content-type'])
pdict['boundary'] = bytes(pdict['boundary'], "utf-8")
if ctype == 'multipart/form-data':
fields = cgi.parse_multipart(self.rfile, pdict)
In my case, It seems work properly.
To change the tutor's code to work for Python 3 there are three error messages you'll have to combat:
If you get these error messages
c_type, p_dict = cgi.parse_header(self.headers.getheader('Content-Type'))
AttributeError: 'HTTPMessage' object has no attribute 'getheader'
or
boundary = pdict['boundary'].decode('ascii')
AttributeError: 'str' object has no attribute 'decode'
or
headers['Content-Length'] = pdict['CONTENT-LENGTH']
KeyError: 'CONTENT-LENGTH'
when running
c_type, p_dict = cgi.parse_header(self.headers.getheader('Content-Type'))
if c_type == 'multipart/form-data':
fields = cgi.parse_multipart(self.rfile, p_dict)
message_content = fields.get('message')
this applies to you.
Solution
First of all change the first line to accommodate Python 3:
- c_type, p_dict = cgi.parse_header(self.headers.getheader('Content-Type'))
+ c_type, p_dict = cgi.parse_header(self.headers.get('Content-Type'))
Secondly, to fix the error of 'str' object not having any attribute 'decode', it's because of the change of strings being turned into unicode strings as of Python 3, instead of being equivalent to byte strings as in Python 3, so add this line just under the above one:
p_dict['boundary'] = bytes(p_dict['boundary'], "utf-8")
Thirdly, to fix the error of not having 'CONTENT-LENGTH' in pdict just add these lines before the if statement:
content_len = int(self.headers.get('Content-length'))
p_dict['CONTENT-LENGTH'] = content_len
Full solution on my Github:
https://github.com/rSkogeby/web-server
I am doing the same course and was running into the same problem. Instead of getting it to work with cgi I am now using the parse library. This was shown in the same course just a few lessons earlier.
from urllib.parse import parse_qs
length = int(self.headers.get('Content-length', 0))
body = self.rfile.read(length).decode()
params = parse_qs(body)
messagecontent = params["message"][0]
And you have to get rid of the enctype='multipart/form-data' in your form.
In my case I used cgi.FieldStorage to extract file and name instead of cgi.parse_multipart
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
})
print('File', form['file'].file.read())
print('Name', form['name'].value)
Another hack solution is to edit the source of the cgi module.
At the very beginning of the parse_multipart (around the 226th line):
Change the usage of the boundary to str(boundary)
...
boundary = b""
if 'boundary' in pdict:
boundary = pdict['boundary']
if not valid_boundary(boundary):
raise ValueError('Invalid boundary in multipart form: %r'
% (boundary,))
nextpart = b"--" + str(boundary)
lastpart = b"--" + str(boundary) + b"--"
...

What am I doing wrong with this Python class? AttributeError: 'NoneType' object has no attribute 'usernames'

Hey there I am trying to make my first class my code is as follows:
class Twitt:
def __init__(self):
self.usernames = []
self.names = []
self.tweet = []
self.imageurl = []
def twitter_lookup(self, coordinents, radius):
twitter = Twitter(auth=auth)
coordinents = coordinents + "," + radius
print coordinents
query = twitter.search.tweets(q="", geocode='33.520661,-86.80249,50mi', rpp=10)
print query
for result in query["statuses"]:
self.usernames.append(result["user"]["screen_name"])
self.names.append(result['user']["name"])
self.tweet.append(h.unescape(result["text"]))
self.imageurl.append(result['user']["profile_image_url_https"])
What I am trying to be able to do is then use my class like so:
test = Twitt()
hello = test.twitter_lookup("38.5815720,-121.4944000","1m")
print hello.usernames
This does not work and I keep getting: "AttributeError: 'NoneType' object has no attribute 'usernames'"
Maybe I just misunderstood the tutorial or am trying to use this wrong. Any help would be appreciated thanks.
I see the error is test.twitter_lookup("38.5815720,-121.4944000","1m") return nothing. If you want the usernames, you need to do
test = Twitt()
test.twitter_lookup("38.5815720,-121.4944000","1m")
test.usernames
Your function twitter_lookup is modifying the Twitt object in-place. You didn't make it return any kind of value, so when you call hello = test.twitter_lookup(), there's no return value to assign to hello, and it ends up as None. Try test.usernames instead.
Alternatively, have the twitter_lookup function put its results in some new object (perhaps a dictionary?) and return it. This is probably the more sensible solution.
Also, the function accepts a coordinents (it's 'coordinates') argument, but then throws it away and uses a hard-coded value instead.