I have to make a code taking a name and turning it into a last name, first initial and middle initial format - python-3.x

I have to make a code taking a name and turning it into a last name, first initial, middle initial format. My code works assuming there is a middle name but breaks if not provided a middle name. Is there a way to ignore not having a middle name and to just default to last name and first initial? I'm super new to python3 so I'm sorry if my code is uber bad.
Heres my code :
your_name = input()
broken_name = your_name.split()
first_name = broken_name[0]
middle_name = broken_name[1]
last_name = broken_name[2]
middle_in = middle_name[0]
first_in = first_name[0]
print(last_name+',',first_in+'.'+middle_in+'.' )

You can use an if else statement to check how long broken_name is.
Try:
your_name = input()
broken_name = your_name.split()
if len(broken_name) > 2:
first_name = broken_name[0]
middle_name = broken_name[1]
last_name = broken_name[2]
middle_in = middle_name[0]
first_in = first_name[0]
print(last_name+', ',first_in+'. '+middle_in+'.'
else:
first_name = broken_name[0]
last_name = broken_name[1]
first_in = first_name[0]
print(last_name+', ',first_in+'.')

Another option:
def get_pretty_name_str(names):
splited_names = names.split()
last_name = splited_names.pop(-1)
result = f'{last_name},'
while splited_names:
n = splited_names.pop(0)
result += f'{n}.'
return result
print(get_pretty_name_str('First Middle Last')) # Last,First.Middle.
print(get_pretty_name_str('First Last')) # Last,First.

Related

What is the problem in the following code?

I want to generate auto generate book fine of 10% of book cost. I have written the following code but nothing happens. No error comes and not working. book_cost field is in book module.
Please check code.
issue_date = fields.Date('Issue Date', required=True, tracking=True)
due_date = fields.Date('Due Date', required=True, tracking=True)
book_ids = fields.Many2many('odooschool.library.books','tch_book_rel','book_name','teacher_id','Issued Books')
sequence = fields.Integer('sequence')
fine_amount = fields.Char('Fine Amount', compute='_get_cost_details')
submission_date = fields.Date.today()
price = fields.Char('Price')
#api.depends('due_date','book_ids.book_cost')
def _get_cost_details(self):
market_multiplier = 0
date_return = fields.Date()
for rec in self:
fine_amount = 0
if rec.due_date and rec.submission_date and rec.due_date > rec.submission_date:
date_return = (rec.due_date - rec.submission_date)
market_multiplier = int(decimal.Decimal('0.10'))
fine_amount = rec.book_ids.book_cost * market_multiplier
rec.fine_amount += rec.fine_amount
I think if you replace
submission_date = fields.Date.today()
by
submission_date = fields.Date(default= fields.Date.today)
That will be work. Cause the submission_date in your code is always the starting date of Odoo server.
Regards

write attribute_line_ids in product.tempate in odoo 12

i am getting fields data from xls file and creating product
everything work fine except one2many field of variant in product.template
how can i achieve this.
here is my code.
main_product = self.env["product.template"].create(product_data)
attribute_ids = self.env["product.attribute"].search([])
attrib_id_set = set(ids.name for ids in attribute_ids)
product_attrib_ids = sheet.cell(suits, 13).value.split(",")
attrib_id_list = []; exist_attribute_list = []
for name in product_attrib_ids:
if name not in attrib_id_set:
attrib_id = self.env["product.attribute"].create({'name':name})
attrib_id_list.append(attrib_id)
else:
exist_attribute = self.env["product.attribute"].search([('name','=',name)])
exist_attribute_list.append(exist_attribute)
union_list = list(set(attrib_id_list).union(exist_attribute_list))
exist_attribute_values = self.env["product.attribute.value"].search([])
exist_attrib_val_list = [attrib_name.name for attrib_name in exist_attribute_values]
product_attrib_id_values = sheet.cell(suits, 14).value.split(",")
for value in product_attrib_id_values:
if value not in exist_attrib_val_list:
for ids in union_list:
attrib_value_id = self.env["product.attribute.value"].create({
'attribute_id':ids.id,
'name':value
})
main_product.write({
'attribute_line_ids':[(0,0,{
'attribute_id':ids.id, 'value_ids':(4,attrib_value_id.id)
})]
})
product_data is my dictionary for fields like name,sale_ok,type,catag_id etc.
this works, product is created, attribute_id and attribute values even works
but i can not write one2many of variant in product.template.
--EDIT--
values_lst=[]
for value in product_attrib_id_values:
if value not in exist_attrib_val_list:
for ids in union_list:
attrib_value_id = self.env["product.attribute.value"].create({
'attribute_id':ids.id,
'name':value
})
else:
for ids in exist_attribute_values:
if value == ids.name:
attrib_value_id =self.env["product.attribute.value"].browse(ids.id)
if attrib_value_id not in values_lst:
values_lst.append(attrib_value_id)

Validate WTF Flask Form Input Values

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

Error inserting an email string in sqlite3 and python Tkinter

I am writing a simple program to update a basic db based on data entered on a simple GUI. I'm using string formatting but keep getting an error trying to enter an email address , which I know should be surrounded with double-quotes. I'm sure the solution is simple- I just don't know what it is!
def update_rec():
# Connect to the db
conn = sqlite3.connect("address_book.db")
# create a cursor
c = conn.cursor()
fields = ["f_name", "s_name", "mob", "email"]
# Check which textboxes have data
update_txt = ""
update_field = ""
rec_no = str(id_no.get())
if len(f_name.get()) > 0:
update_txt = f_name.get()
update_field = fields[0]
elif len(s_name.get()) > 0:
update_txt = s_name.get()
update_field = fields[1]
elif len(mob.get()) > 0:
update_txt = mob.get()
update_field = fields[2]
elif len(email.get()) > 0:
update_txt = email.get()
update_field = fields[3]
else:
update_txt = ""
update_field = ""
c.execute("""UPDATE address_book SET {0} = ? WHERE {1} = ?""".format(update_field, update_txt), rec_no)
conn.commit()
conn.close()
I keep getting this error:
c.execute("""UPDATE address_book SET {0} = ? WHERE {1} = ?""".format(update_field, update_txt), rec_no)
sqlite3.OperationalError: near "#gmail": syntax error
What needs to be supplied to .format() is getting confused with what needs to be passed to c.execute().
Do it in two steps so it's easier to understand.
You need to tell us what rec_field should be. It's probably something like id or address_book_id or ?
rec_field = 'id' # you know what this should be...
qry = """UPDATE address_book
SET {0} = ?
WHERE {1} = ?;""".format(update_field, rec_field)
c.execute(qry, (update_txt,rec_no))

Get id of a record with the lowest sequence

I have this class
name = fields.Char("Name")
sequence = fields.Integer("Sequence")
description = fields.Text("Description")
I need a search method to find the id with lower sequence
res = self.env['your.model'].search([], limit=1, order='sequence desc')
should to the trick
I think this search function would do the trick.
def _find_register(self, operator, value):
lowest_sequence_id = False
lowest_sequence = False
for state in self.env['ags.traffic.operation.state'].search([('id','>',0)]):
if not lowest_sequence:
lowest_sequence_id = state.id
lowest_sequence = state.sequence
elif state.sequence < lowest_sequence:
lowest_sequence = state.sequence
return [('id', '=', lowest_sequence_id)]

Resources