how to raise an excpetion and return none value when the conditions are not satisfied - exception

I am new to python and have just to learn python. I have a written a code to find the common characters in two string and I am getting the desired output. I want to modify the code if the following cases arise and it should return None for the following conditions
1) For two string, if there is no match
2) any of string1 or string2 is nil/empty
3) any of string1 or string2 is hash/array/set/Fixnum [i.e anything other than string]
I am supposed to raise an exception for the above cases. I have gone through the forums and links but could not figure it out correctly. Could anyone please help me on how do raise exception for the above condition
This is the code
class CharactersInString:
def __init__(self, value1, value2):
self.value1 = value1
self.value2 = value2
def find_chars_order_n(self):
new_string = [ ]
new_value1 = list(self.value1)
new_value2 = list(self.value2)
print( "new_value1: ", new_value1)
print( "new_value2: ", new_value2)
for i in new_value1:
if i in new_value2 and i not in new_string:
new_string.append(i)
final_list = list(new_string)
return ''.join(final_list)
if __name__ == "__main__":
obj = CharactersInString("ho", "killmse")
print(obj.find_chars_order_n())

Related

How to compare two JSON responses in groovy and get the differences (similar to what json editor does)?

Can someone please tell me why the error happens and possible alternatives in solving this
My code:
def actual = " [{"inputs":[{"__typename":"ElementalField"}],"constraint":"FILE-STATUS:REPORT-STATUS:REPORT-STATUS-1='0'","source":{"sourceCodeFiles":[{"fileName":"/usr/src/workspace/PC/source/cobol/PCCTRE.cob","sourceLines":[{"nodes":[{"id":"8326"}],"lineNumber":620}]}],"__typename":"Source"},"branchExecuted":false},{"inputs":[{"__typename":"ElementalField"}],"constraint":"FILE-STATUS:TRAND-STATUS:TRAND-STATUS-1='0'","source":{"sourceCodeFiles":[{"fileName":"/usr/src/workspace/PC/source/cobol/PCCTRE.cob","sourceLines":[{"nodes":[{"id":"8369"}],"lineNumber":634}]}],"__typename":"Source"},"branchExecuted":false}]"
def expected = "[{"inputs":[{"__typename":"ElementalField"}],"constraint":"FILE-STATUS:REPORT-STATUS:REPORT-STATUS-1='0'","source":{"sourceCodeFiles":[{"fileName":"/usr/src/workspace/PC/source/cobol/PCCTRE.cob","sourceLines":[{"nodes":[{"id":"8326"}],"lineNumber":620}]}],"__typename":"Source"},"branchExecuted":false},{"inputs":[{"__typename":"ElementalField"}],"constraint":"FILE-STATUS:TRAND-STATUS:TRAND-STATUS-1='0'","source":{"sourceCodeFiles":[{"fileName":"/usr/src/workspace/PC/source/cobol/PCCTRE.cob","sourceLines":[{"nodes":[{"id":"8366"}],"lineNumber":634}]}],"__typename":"Source"},"branchExecuted":false}]"
def removedA = actual.replaceAll("[_]","").trim();
def removedE = expected.replaceAll("[_]","").trim();
def json = new groovy.json.JsonSlurper().parseText(removedA)
//Checks all elements of resource one by one and compare with expectedData
json.each{k, v -> assert v == removedE."$k" }
Here is the error:
groovy.lang.MissingMethodException: No signature of method: Script23$_run_closure1.doCall() is applicable for argument types: (org.apache.groovy.json.internal.LazyMap) values: [[inputs:[[typename:ElementalField]], constraint:FILE-STATUS:REPORT-STATUS:REPORT-STATUS-1='0', ...]] Possible solutions: doCall(java.lang.Object, java.lang.Object), findAll(), findAll(), isCase(java.lang.Object), isCase(java.lang.Object) error at line: 37

python 3 : deserialize nested dictionaries from sqlite

I have this sqlite3.register_converter function :
def str_to_dict(s: ByteString) -> Dict:
if s and isinstance(s, ByteString):
s = s.decode('UTF-8').replace("'", '"')
return json.loads(s)
raise TypeError(f'value : "{s}" should be a byte string')
which returns this exception text :
File "/usr/lib64/python3.7/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 30 (char 29)
when encounter with this string :
s = b"{'foo': {'bar': [('for', 'grid')]}}"
It seems that the issue comes from the nested list/tuple/dictionary but what I don't understand is that in the sqlite shell, the value is correctly returned with a select command :
select * from table;
whereas the same command issued from a python script returned the exception above :
class SqliteDb:
def __init__(self, file_path: str = '/tmp/database.db'):
self.file_path = file_path
self._db = sqlite3.connect(self.file_path, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
if self._db:
self._cursor = self._db.cursor()
else:
raise ValueError
# register data types converters and adapters
sqlite3.register_adapter(Dict, dict_to_str)
sqlite3.register_converter('Dict', str_to_dict)
sqlite3.register_adapter(List, list_to_str)
sqlite3.register_converter('List', str_to_list)
def __del__(self):
self._cursor.close()
self._db.close()
def select_from(self, table_name: str):
with self._db:
query = f'SELECT * FROM {table_name}'
self._cursor.execute(query)
if __name__ == '__main__':
try:
sq = SqliteDb()
selection_item = sq.select_from("table")[0]
print(f'selection_item : {selection_item}')
except KeyboardInterrupt:
print('\n')
sys.exit(0)
s, the value is already saved in database with no issue. Only the selection causes this issue.
So, anybody has a clue why ?
Your input is really a Python dict literal, and contains structures such as the tuple ('for', 'grid') that cannot be directly parsed as JSON even after you replace single quotes with double quotes.
You can use ast.literal_eval instead to parse the input:
from ast import literal_eval
def str_to_dict(s: ByteString) -> Dict:
return literal_eval(s.decode())

How to skip one condition if that is not needed in Python 3.7?

I have written a code using if, try/except clause. I want to use "try" to check whether the parameters are correct and if those are correct the "print" function will run.
If the parameters are not right then the error message will be printed and the print section will not run.
The problem is when I am correct input it is running but when I am giving wrong input, after printing the error message I am getting NameError, saying "room1" is not defined. I understood why it is happening but I am confused how to get the correct output without getting an error.
My code is:
class Hotel:
def __init__(self,room,catagory):
if type(room) != int:
raise TypeError()
if type(catagory) != str:
raise TypeError()
self.room = room
self.catagory = catagory
self.catagories = {"A":"Elite","B":"Economy","C":"Regular"}
self.rooms = ["0","1","2","3","4","5"]
def getRoom(self):
return self.room
def getCatagory(self):
return self.catagories.get(self.catagory)
def __str__(self):
return "%s and %s"%(self.rooms[self.room],self.catagories.get(self.catagory))
try:
room1 = Hotel(a,"A")
except:
print("there's an error")
print (room1)
Your print should be in the try segment of your code as it will always execute whether there is an error or not.
class Hotel:
def __init__(self,room,catagory):
if type(room) != int:
raise TypeError()
if type(catagory) != str:
raise TypeError()
self.room = room
self.catagory = catagory
self.catagories = {"A":"Elite","B":"Economy","C":"Regular"}
self.rooms = ["0","1","2","3","4","5"]
def getRoom(self):
return self.room
def getCatagory(self):
return self.catagories.get(self.catagory)
def __str__(self):
return "%s and %s"%(self.rooms[self.room],self.catagories.get(self.catagory))
Initialization
try:
room1 = Hotel(a,"A")
print (room1)
except:
print("there's an error")

Django rounds left 3 digits while displaying bigint in mysql

I am using Django to display rows in mysql.
The table in mysql has a primary key which it bigint, and one of them is 871195445245063168, 18 digits.
But on my page, I see 871195445245063200 displayed, the least 3 digits are rounded. I am wondering where I make it wrong.
1, I define a class with a function named data_query to query mysql.
class MyQuery:
self.conn = MySQLdb.connect(host = self.DBHOST, user = self.DBUSER,
passwd = self.DBPWD,port = self.DBPORT,charset = self.CHARSET,connect_timeout=3)
def data_query(self,sql):
cursor = self.conn.cursor(MySQLdb.cursors.DictCursor)
start = time.time()
cursor.execute(sql)
end = time.time()
sql_time = end - start
column_description = cursor.description
column_name = [ column[0] for column in column_description ]
res = cursor.fetchall()
cursor.close()
self.conn.close()
return res,column_name,sql_time
2, I defined a json encoder as follows
class CJsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
try:
return obj.strftime('%Y-%m-%d %H:%M:%S')
except ValueError:
return str(obj)
elif isinstance(obj, datetime.date):
try:
return obj.strftime('%Y-%m-%d')
except ValueError:
return str(obj)
elif isinstance(obj,datetime.timedelta):
return str(obj)
elif isinstance(obj, decimal.Decimal):
return float(obj)
elif isinstance(obj,ObjectId):
return str(obj)
else:
return json.JSONEncoder.default(self, obj)
3, I get my display like this, with sensitive info replaced.
db = MyQuery(host, user, pwd, port)
sql_statement = 'select * from mytable where Findex=871195445245063168 limit 10'
sql_result, table_column_name, sql_time = db.data_query(sql_statement)
query_result = {}
column_name = column_format(table_column_name)
query_result['column'] = column_name
query_result['data'] = list(sql_result)
return HttpResponse(json.dumps(query_result, cls=CJsonEncoder), content_type='application/json')
So, what I go wrong here? Thanks.
This is a JavaScript issue. Your number is bigger than the largest safe integer in JavaScript (Number.MAX_SAFE_INTEGER), so it is rounded.
You can verify this in your browser console or in node.js
$ node
> x = 871195445245063168
871195445245063200
I assume you are either using your response in some kind of JavaScript frontend or you have some Browser extension to render the JSON, which is written in JavaScript.
If you request that URL with a client like curl, you will see that it is returned correctly from the server.

Using integers with dictionary to create text menu (Switch/Case alternative)

I am working my way through the book Core Python Programming. Exercise 2_11 instructed to build a menu system that had allowed users to select and option which would run an earlier simple program. the menu system would stay open until the user selected the option to quit. Here is my first working program.
programList = {1:"menu system",
2:"for loop count 0 to 10",
3:"positive or negative",
4:"print a string, one character at a time",
5:"sum of a fixed tuple",
"x":"quit()",
"menu":"refresh the menu"}
import os
for x in programList:
print(x,":",programList[x])
while True:
selection = input("select a program: ")
if selection == "1":
os.startfile("cpp2_11.py")
elif selection == "2":
os.startfile("cpp2_5b.py")
elif selection == "3":
os.startfile("cpp2_6.py")
elif selection == "4":
os.startfile("cpp2_7.py")
elif selection == "5":
os.startfile("cpp2_8.py")
elif selection == "menu":
for x in range(8): print(" ")
for x in programList:print(x,":",programList[x])
elif selection == "X":
break
elif selection == "x":
break
else:
print("not sure what you want")
input()
quit()
This version worked fine, but I wanted to use the a dictionary as a case/switch statement to clean up the ugly if/elif/else lines.
Now I'm stuck. I'm using Eclipse with PyDev and my new code is throwing an error:
Duplicated signature:!!
Here's a copy of my current code:
import os
def '1'():
os.startfile("cpp2_11.py")
def '2'():
os.startfile("cpp2_5b.py")
def '3'():
os.startfile("cpp2_6.py")
def '4'():
os.startfile("cpp2_7.py")
def '5'():
os.startfile("cpp2_8.py")
def 'm'():
for x in range(8): print(" ")
for x in actions:print(x,":",actions[x])
def 'x'():
quit()
def errhandler():
else:
print("not sure what you want")
actions = {1:"menu system",
2:"for loop count 0 to 10",
3:"positive or negative",
4:"print a string, one character at a time",
5:"sum of a fixed tuple",
"X":"quit()",
"menu":"refresh the menu"}
for x in actions:
print(x,":",actions[x])
selectedaction = input("please select an option from the list")
while True:
actions.get(selectedaction,errhandler)()
input()
quit()
I'm pretty sure that my current problem (the error codes) are related to the way I'm trying to use the os.startfile() in the functions. Maybe I'm way off. Any help is appreciated.
EDIT: I am changing the title to make it more useful for future reference. After a helpful comment from Ryan pointing out the simple error in function naming, I was able to piece together a script that works. sort of...Here it is:
import os
def menu_system():
os.startfile("cpp2_11alt.py")
def loopCount_zero_to_ten():
os.startfile("cpp2_5b.py")
def positive_or_negative():
os.startfile("cpp2_6.py")
def print_a_string_one_character_at_a_time():
os.startfile("cpp2_7.py")
def sum_of_a_tuples_values():
os.startfile("cpp2_8.py")
def refresh_the_menu():
for x in range(4): print(" ")
for y in actions:print(y,":",actions[y])
for z in range(2): print(" ")
def exit_the_program():
quit()
def errhandler():
print("not sure what you want")
actions = {'1':menu_system,
'2':loopCount_zero_to_ten,
'3':positive_or_negative,
'4':print_a_string_one_character_at_a_time,
'5':sum_of_a_tuples_values,
'x':exit_the_program,
'm':refresh_the_menu}
for item in actions:
print(item,":",actions[item])
for z in range(2): print(" ")
selectedaction = input("please select an option from the list: ")
while True:
actions.get(selectedaction,errhandler)()
selectedaction = input("please select an option from the list: ")
quit()
There were many problems with the second attempt. I was referencing the dictionary key instead of the value when calling functions. I also had some bugs in the way the menu printed and handled input values. Now all I need to do is figure out how to get the dictionary values to print without all of the extra information:
This is the output when I print the menu:
2 : <function loopCount_zero_to_ten at 0x027FDA08>
3 : <function positive_or_negative at 0x027FD810>
1 : <function menu_system at 0x027FD978>
4 : <function print_a_string_one_character_at_a_time at 0x027FD930>
5 : <function sum_of_a_tuples_values at 0x027FD780>
x : <function exit_the_program at 0x027FD858>
m : <function refresh_the_menu at 0x027FD7C8>
AND how to get the menu to print in numeric order.
Once again, any help is appreciated.
I finally found a solution to the problem of sorting a dictionary and printing the function names as a string. In the last part of the edited question (3rd code section), I had the fixed code for the question that started this post: how to use integers in a dictionary to create a menu - with the intention of creating a switch/case style alternative and avoiding the ugly if/elif/else problems in the first code section.
Here's the final version of the working code:
import os
def menu_system():
os.startfile("cpp2_11alt.py")
def loopCount_zero_to_ten():
os.startfile("cpp2_5b.py")
def positive_or_negative():
os.startfile("cpp2_6.py")
def print_a_string_one_character_at_a_time():
os.startfile("cpp2_7.py")
def sum_of_a_tuples_values():
os.startfile("cpp2_8.py")
def refresh_the_menu():
for x in range(4): print(" ")
for key in sorted(actions):
print (key, '=>', actions[key].__name__)
for z in range(2): print(" ")
def exit_the_program():
quit()
def errhandler():
print("not sure what you want")
actions = {'1':menu_system,
'2':loopCount_zero_to_ten,
'3':positive_or_negative,
'4':print_a_string_one_character_at_a_time,
'5':sum_of_a_tuples_values,
'x':exit_the_program,
'm':refresh_the_menu}
for key in sorted(actions):
print (key, '=>', actions[key].__name__)
selectedaction = input("please select an option from the list: ")
while True:
actions.get(selectedaction,errhandler)()
selectedaction = input("please select an option from the list: ")
quit()
adding the .__name__ method allowed me to print the function names as a string.
Using the for loop:
for key in sorted(actions):
print (key, '=>', actions[key].__name__)
created the ability to sort the dictionary.