Context:
I click on a button -> a WindowDialogue appears -> there are 2 LineEdit Nodes and a button
Supposed procedure:
I fill these LineEdits, press the button, and the function tied to the button receives the texts from the LineEdits (and creates a dictionary key-value pair).
Problem:
The texts from the LineEdits do not pass down to the function (through connect()).
I tried passing the text directly with LineEdit.text. I tried writing it in a different variable and passing the variable. The debug shows the function is getting executed (no problem with that), but the strings passed from the LineEdits are always empty. Somehow, it worked for some time when I explicitly pressed ENTER after filling the LineEdits. But after I tried to fix the aforementioned problem, it stopped working altogether.
P.S. Everything I mentioned is created dynamically through the code, if that matters.
Code:
#Declaring the variables
var temp_text_key = ""
var temp_text_value = ""
#Function to show up a dialogue window with LineEdits and Confirm button
func _on_add_new_property(dict: Dictionary):
temporal_window_dialogue = WindowDialog.new()
temporal_window_dialogue.rect_min_size = Vector2(410,90)
temporal_window_dialogue.resizable = true
temporal_window_dialogue.popup_exclusive = true
temporal_window_dialogue.window_title = "Adding new property to %s" % get_dict_name_by_id(professions, dict["id"])
var le_key = LineEdit.new()
le_key.placeholder_text = "Name of the property"
le_key.hint_tooltip = "Name of the property"
le_key.connect("text_changed", self, "_on_add_new_prop_text_entered", ["key"])
var le_value = LineEdit.new()
le_value.expand_to_text_length = true
le_value.placeholder_text = "Value of the property"
le_value.set("custom_constants/minimum_spaces", 36)
le_value.hint_tooltip = "Value of the property"
le_value.connect("text_changed", self, "_on_add_new_prop_text_entered", ["value"])
var lab = Label.new()
lab.text = "Should the Value become a Dictionary?"
var check_bt = CheckBox.new()
var vbox = VBoxContainer.new()
var grid_container = GridContainer.new()
grid_container.columns = 2
var accept_bt = Button.new()
accept_bt.text = "Confirm"
temporal_window_dialogue.add_child(vbox)
vbox.add_child(grid_container)
grid_container.add_child(le_key)
grid_container.add_child(le_value)
grid_container.add_child(lab)
grid_container.add_child(check_bt)
vbox.add_child(accept_bt)
grid_container.set("custom_constants/vseparation", 5)
grid_container.set("custom_constants/hseparation", 5)
check_bt.connect("pressed", self, "_on_check_dict_pressed")
popup_window.add_child(temporal_window_dialogue)
temporal_window_dialogue.connect("popup_hide", self, "_on_close_specific_codegenerated_popup", [temporal_window_dialogue])
temporal_window_dialogue.popup_centered()
accept_bt.connect("pressed", self, "_on_add_new_property_confirmation", [dict, temp_text_key, temp_text_value])
#Function to create a new key/value pair in a dictionary
func _on_add_new_property_confirmation(dict: Dictionary, prop_name: String, prop_value: String):
if prop_name == "" or prop_value == "":
send_message_to_console("Neither of the two can be empty", 3)
return
if add_dictionary_flag:
dict[prop_name] = {
prop_value: {
"id": get_free_local_id_for_dict(dict)
}
}
elif !add_dictionary_flag:
if keywords_for_dictionaries.has(prop_name):
send_message_to_console("Only Dictionary items can become %s" % prop_name)
dict[prop_name] = prop_value
temp_text_key = ""
temp_text_value = ""
#Optional function to write the text from LineEdits to the variables
func _on_add_new_prop_text_entered(new_text, key_or_value):
if key_or_value == "key":
temp_text_key = new_text
elif key_or_value == "value":
temp_text_value = new_text
You mentioned using 'LineEdit.text', but have you tried the following?
var text = LineEdit.get_text()
If this doesn't help, please update your original post to include code examples.
Related
I have a recursive function to which i pass certain args. The function is as below:
def insert_category(a, b, c, d, content_to_write):
response_content = []
if content_to_write:
response_content.extend(content_to_write)
for x in b:
write_back_content = {}
write_back_content = {"category_path": "a", "name": "b" ,"status" : "Successful" ,"err_desc" : "-" }
form_category = {"pid": "0", "name": "Library" }
category_exists = db.collection.find_one({"_id":a})
if some_cond:
write_back_content["status"] = "Failed"
write_back_content["err_desc"] = "Duplicate Category"
response_content.append(write_back_content)
continue
elif some_other_cond:
write_back_content["status"] = "Failed"
write_back_content["err_desc"] = "Invalid pid i.e category path"
response_content.append(write_back_content)
continue
insert_status = db.collections.insert(form_category)
if not insert_status:
write_back_content["status"] = "Failed"
write_back_content["err_desc"] = "Unable to create category"
response_content.append(write_back_content)
continue
else:
c[map_some_id] = insert_status
response_content.append(write_back_content)
insert_category(a, b, c, d ,content_to_write=response_content)
logger.info("RESPONSE CONTENT {}".format(response_content))
return response_content
The current problem I am facing here is that the log line "RESPONSE CONTENT" somehow loses the last attached info, ex: if there are 4 insertions in response_content, when i call this function, the return response has only 3 insertions. The last one goes missing. Also, weirdly, the log prints 4 times instead of just once since it is outside the for loop.Any idea where I am going wrong?
Okay so after quite a long time of debugging, i realised the mistake was quite silly. The function returns some data. So i was not storing the return content. So the solution that worked was response_content = insert_category(args).
im trying to add variables to a list that i created. Got a result from a session.execute.
i´ve done this:
def machine_id(session, machine_serial):
stmt_raw = '''
SELECT
id
FROM
machine
WHERE
machine.serial = :machine_serial_arg
'''
utc_now = datetime.datetime.utcnow()
utc_now_iso = pytz.utc.localize(utc_now).isoformat()
utc_start = datetime.datetime.utcnow() - datetime.timedelta(days = 30)
utc_start_iso = pytz.utc.localize(utc_start).isoformat()
stmt_args = {
'machine_serial_arg': machine_serial,
}
stmt = text(stmt_raw).columns(
#ts_insert = ISODateTime
)
result = session.execute(stmt, stmt_args)
ts = utc_now_iso
ts_start = utc_start_iso
ID = []
for row in result:
ID.append({
'id': row[0],
'ts': ts,
'ts_start': ts_start,
})
return ID
In trying to get the result over api like this:
def form_response(response, session):
result_machine_id = machine_id(session, machine_serial)
if not result_machine_id:
response['Error'] = 'Seriennummer nicht vorhanden/gefunden'
return
response['id_timerange'] = result_machine_id
Output looks fine.
{
"id_timerange": [
{
"id": 1,
"ts": "2020-08-13T08:32:25.835055+00:00",
"ts_start": "2020-07-14T08:32:25.835089+00:00"
}
]
}
Now i only want the id from it as a parameter for another function. Problem is i think its not a list. I cant select the first element. result_machine_id[0] result is like the posted Output. I think in my first function i only add ts & ts_start to the first row? Is it possible to add emtpy rows and then add 'ts':ts as value?
Help would be nice
If I have understood your question correctly ...
Your output looks like dict. so access its id_timerange key which gives you a list. Access the first element which gives you another dict. On this dict you have an id key:
result_machine_id["id_timerange"][0]["id"]
I have the following form in my flask app. I'd like to ensure that the input value is actually an integer and also if the value entered in token > k here k can be some number it spits an error message to the screen. The IntegerField doesn't seem to enforce integer values, e.g., if the user enters 2.3 it passes that to my function which fails because it expects an integer.
Can this type of error message happen in the form or do I need to program that inside my flask app once the value is passed from the form to the server?
class Form(FlaskForm):
token = IntegerField('Token Size', [DataRequired()], default = 2)
submit = SubmitField('Submit')
EDIT
Per the comment below, updating this with my revised Form and the route
class Form(FlaskForm):
token = IntegerField('Token Size', validators=[DataRequired(), NumberRange(min=1, max=10, message='Something')], default = 2)
ngram_method = SelectField('Method', [DataRequired()],
choices=[('sliding', 'Sliding Window Method'),
('adjacent', 'Adjacent Text Method')])
rem_stop = BooleanField('Remove Stop Words', render_kw={'checked': True})
rem_punc = BooleanField('Remove Punctuation', default = True)
text2use = SelectField('Text To Use for Word Tree', [DataRequired()],
choices=[('clean', 'Clean/Processed Text'),
('original', 'Original Text String')])
pivot_word = TextField('Pivot Word for Word Tree', [DataRequired()])
submit = SubmitField('Submit')
And the route in which the form is used
#word_analyzer.route('/text', methods=('GET', 'POST'))
def text_analysis():
form = Form()
result = '<table></table>'
ngrams = '<table></table>'
orig_text = '<table></table>'
text = ""
if request.method == 'POST':
tmp_filename = tempfile.gettempdir()+'\\input.txt'
if request.files:
txt_upload = request.files.get('text_file')
if txt_upload:
f = request.files['text_file']
f.save(tmp_filename)
if os.path.exists(tmp_filename):
file = open(tmp_filename, 'r', encoding="utf8")
theText = [line.rstrip('\n') for line in file]
theText = str(theText)
token_size = form.token.data
stops = form.rem_stop.data
punc = form.rem_punc.data
ngram_method = form.ngram_method.data
text_result = text_analyzer(theText, token_size = token_size, remove_stop = stops, remove_punctuation = punc, method = ngram_method)
result = pd.DataFrame.from_dict(text_result, orient='index', columns = ['Results'])[:-3].to_html(classes='table table-striped table-hover', header = "true", justify = "center")
ngrams = pd.DataFrame.from_dict(text_result['ngrams'], orient='index', columns = ['Frequency']).to_html(classes='table table-striped table-hover', header = "true", justify = "center")
if form.pivot_word.data == None:
top_word = json.dumps(text_result['Top Word'])
else:
top_word = json.dumps(form.pivot_word.data)
if form.text2use.data == 'original':
text = json.dumps(text_result['original_text'])
else:
text = json.dumps(text_result['clean_text'])
if form.validate_on_submit():
return render_template('text.html', results = [result], ngrams = [ngrams], form = form, text=text, top_word = top_word)
return render_template('text.html', form = form, results = [result],ngrams = [ngrams], text=text, top_word='')
Use the NumberRange validator from wtforms.validators.NumberRange. You can pass an optional Min and Max value along with the error message. More info here
Update
# Form Class
class Form(FlaskForm):
token = FloatField('Token Size', validators=[DataRequired(), NumberRange(min=1, max=10, message='Something')])
# Route
if form.validate_on_submit():
print(form.name.data)
Here is an example that should work, make sure your form class field looks similar and also that in your route you use form.validate_on_submit():.
I want to got First line of the function goToSignUpActivit() if isAllInputValid == False
from CustomUtil import *
from Register import *
def goToSingUpActivity():
fName = input("Enter your First Name:")
lName = input("Enter your last name:")
mobileNum = input("input your mobile number")
role = input("Select your role s: for staff p: for patient:")
isFNameValid = validateInput(fName)
isLNameValid = validateInput(lName) // this function in CustomUtil package
isRoleValid = False
if (role in ["s","p","S","P"]):
isRoleValid = True
isMobileNumValid = validateMobilNum(mobileNum)// this function in CustomUtil package
isAllInputValid = False
if (isFNameValid and isLNameValid and isRoleValid and isMobileNumValid) :
isAllInputValid = True
if (isAllInputValid) :
isAllInputValid = True
if role in ["s","S"]:
registerAsStaff(fName,lName,mobileNum)// this function in Register package
return
elif role in ["p","P"]:
registerAsPatient(fName,lName,mobileNum)// this function in Register package
return
while(not isAllInputValid):
if(input("you want to exit y or n:") in ["y","Y"]):
return
goToSingUpActivity()
Above code put goToSingUpActivity() into the stack while isAllInputValid become true.
After I enter all input correctly stack pop goToSingUpActivity() one bye one.
What I need here is after isAllInputValid becomes true, clear all goToSingUpActivity() from stack.
If above solution not possible, is there any other way to modifie the code?
Edit: I got a solution by making isAllInputValid global and put the while loop outside the function after calling goToSingUpActivity().
You can use a while statement (WARNING to don't create a while(true), give to the user an opportunity to cancel his action !).
def goToSingUpActivity():
isAllValid = False
while(!isAllValid):
#your inputs stuff
if(isFNameValid and isLNameValid and isRoleValid and isMobileNumValid):
isAllValid = True
#rest of the function
Trying to get name of a spell as it seems like
local spellName = select(1, CombatLogGetCurrentEventInfo())
returns something like numbers instead plain text like 158989565.009
I was trying to get spell name by function GetSpellInfo(i) but no luck
Here is code sample that doesn't work:
local frame = CreateFrame("FRAME");
frame:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED");
frame:SetScript("OnEvent", function(self, event)
local type = select(1, CombatLogGetCurrentEventInfo())
if (type == "SPELL_DAMAGE") then
local spellId = select(1, CombatLogGetCurrentEventInfo())
local name = GetSpellInfo(spellId)
SendChatMessage(name, "SAY", "COMMON", GetUnitName("PLAYERTARGET"));
end
end)
Late answer but see https://wow.gamepedia.com/COMBAT_LOG_EVENT
local playerGUID = UnitGUID("player")
local MSG_SPELL_DAMAGE = "Damaged %s with %s"
local frame = CreateFrame("Frame");
frame:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
frame:SetScript("OnEvent", function(self, event)
local timestamp, subevent, _, sourceGUID, sourceName, sourceFlags, sourceRaidFlags, destGUID, destName, destFlags, destRaidFlags, spellId, spellName, spellSchool = CombatLogGetCurrentEventInfo()
if subevent == "SPELL_DAMAGE" and sourceGUID == playerGUID then
print(MSG_SPELL_DAMAGE:format(destName, spellName))
end
end)
Example message