Grails strange properties exception - exception

Hope i'm not putting too much code in here .. I have what i consider a strange problem .. I have 2 classes ..
class Card {
String customerNumber
String memberId
String cardNumber
String issueNumber
Boolean active = true
// Audit info ..
Date dateCreated
String createdBy
Integer uniqId
}
class CardHistory extends Card {
static constraints = {
note(nullable: true, size:1..500)
}
// History note
String note
// Audit info ..
Date originalDateCreated
String originalCreatedBy
Integer originalUniqId
}
and another ..
class Seat {
...
Card activeCard
}
I have some code which generates a history record from the current one by doing
cardHistoryInstance.properties = seat.card.properties
but it's throwing a NullPointerException ..
So I wrote this to test it ..
def seat = Seat.get(1)
try{
def cardHistoryEntry = new CardHistory();
println cardHistoryEntry.properties
println "properties okay .."
assert seat
println "Seat okay ..."
assert seat.card
println "Card okay ..."
println seat.card.dateCreated
println "Date okay ..."
.... and each of the other properties
println seat.card.customerNumber
println "customer number okay .. "
println "Seems okay .."
println seat.card.properties <---- Blows up with NPE here ..
println "Don't get to here"
}
catch(e)
{
println "OOps .. An error occurred ${e} .."
}
So basically I can get at each property individually but accessing via properties keyword is giving me a npe .. Can anyone shed any light on this ??
Grails 1.3.6 ..
Thanks

No, you should refer to the property of Seat as activeCard, not card:
try{
def cardHistoryEntry = new CardHistory();
println cardHistoryEntry.properties
println "properties okay .."
assert seat
println "Seat okay ..."
assert seat.activeCard
println "Card okay ..."
println seat.activeCard.dateCreated
println "Date okay ..."
println seat.activeCard.customerNumber
println "customer number okay .. "
println "Seems okay .."
println seat.activeCard.properties
println "Don't get to here"
}
catch(e)
{
println "OOps .. An error occurred ${e} .."
}

Related

KeyError: 'data' in python3

I am using graphql in order to show the number of pull requests made by a user. The query works fine when I ran it on the graphql explorer by GitHub. However when I run the script, it shows KeyError and that the expected value is string. Even though the username entered is converted to a string.
Here's the code:
accessToken = "###################################"
headers = {"Authorization": "bearer "+ accessToken }
def getpullRequests(username):
topic_query = """
query {
repositoryOwner(login:""" + str(username) + """) {
login
... on User {
name
avatarUrl
pullRequests(last: 100){
nodes{
id
createdAt
additions
deletions
}
}
}
}
}
"""
request = requests.post('https://api.github.com/graphql', json={'query': topic_query}, headers=headers)
if request.status_code == 200:
result = request.json()
prsdata = {}
for pr in result['data']['repositoryOwner']['pullRequests']['nodes']:
prdata = {}
if re.match(r'^2019-10', pr['createdAt']):
prdata['createdAt'] = pr['createdAt']
prdata['additions'] = pr['additions']
prdata['deletions'] = pr['deletions']
prsdata[pr['id']] = prdata
if prsdata:
print(prsdata)
else:
print("No PRs made in Hacktoberfest")
if __name__ == "__main__":
username = input("Enter the GitHub username: ")
getpullRequests(username)
However on debugging after some tries I found out that the problem is with this line:
for pr in result['data']['repositoryOwner']['pullRequests']['nodes']:
On running the code, the error I face is :
Enter the GitHub username: adiaux
Traceback (most recent call last):
File "script.py", line 47, in <module>
getpullRequests(username)
File "script.py", line 33, in getpullRequests
for pr in result['data']['repositoryOwner']['pullRequests']['nodes']:
KeyError: 'data'
Someone please help :)
I found a solution.
Basically I used the graphQL variables and made the variable into a dict, like this:
variables=dict({
"name":str(username)
})
However accordingly I modified the the query by including:
query ($name:String!){
repositoryOwner(login:$name){
login
... on User {
name
avatarUrl
pullRequests(last: 100){
nodes{
id
createdAt
additions
deletions
}
}
}
}
}
Thanks to whoever tried to solve this :)

Groovy - CSVParsing - How to split a string by comma outside double quotes without using any external libraries

I have a CSV file like below
COL1,COL2,COL3,COL4
3920,10163,"ST. PAUL, MN",TWIN CITIES
I want to read the file and split them outside double quotes WITHOUT using any external libraries. For example in the above CSV, we need to split them into 4 parts as
1. 3920
2. 10163
3. ST. PAUL, MN
4. TWIN CITIES
i tried using regex with folliwing code but never worked. I want to make this work using Groovy code. I tried different solutions given in Java. But couldnt achieve the solution.
NOTE : I dont want to use any external grails/Jars to make this work.
def staticCSV = new File(staticMapping.csv")
staticCSV.eachLine {line->
def parts = line.split(",(?=(?:[^\"]\"[^\"]\")[^\"]\${1})")
parts.each {
println "${it}"
}
}
Got the solution :
def getcsvListofListFromFile( String fileName ) {
def lol = []
def r1 = r1 = ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*\$)"
try {
def csvf = new File(fileName) ;
csvf.eachLine { line ->
def c1 = line.split(r1)
def c2 = []
c1.each { e1 ->
def s = e1.toString() ;
s = s.replaceAll('^"', "").replaceAll('"\$', "")
c2.add(s)
}
lol.add(c2) ;
}
return (lol)
} catch (Exception e) {
def eMsg = "Error Reading file [" + fileName + "] --- " + e.getMessage();
throw new RuntimeException(eMsg)
}
}
Using a ready-made library is a better idea. But you certainly have your reasons.
Here is an alternative solution to yours. It splits the lines with commas and reassembles the parts that originally belonged together (see multipart).
def content =
"""COL1,COL2,COL3,COL4
3920,10163, "ST. PAUL, MN" ,TWIN CITIES
3920,10163, " ST. PAUL, MN " ,TWIN CITIES, ,"Bla,Bla, Bla" """
content.eachLine {line ->
def multiPart
for (part in line.split(/,/)) {
if (!part.trim()) continue // for empty parts
if (part =~ /^\s*\"/) { // beginning of a multipart
multiPart = part
continue
} else if (part =~ /"\s*$/) { // end of the multipart
multiPart += "," + part
println multiPart.replaceAll(/"/, "").trim()
multiPart = null
continue
}
if (multiPart) {
multiPart += "," + part
} else {
println part.trim()
}
}
}
Output (You can copy the code directly into the GroovyConsole to run.
COL1
COL2
COL3
COL4
3920
10163
ST. PAUL, MN
TWIN CITIES
3920
10163
ST. PAUL, MN
TWIN CITIES
Bla,Bla, Bla

Print a value of a key from json

I am trying to parse a json file and extract the value of a key from it, and pass it to another post request. However, I am not able to extract they value, when I try, it prints the key itself instead of value
PFB the json file
{
"data":{
"isActivated":true,
"userDetails":{
"userId":"52321713-add8-4455-9e0c-426eab923338",
"oktaId":"00ub24c5bs6awQyBD0h7",
"contactId":"7234294092390",
"oktaSessionToken":"20111UqAZ9-E1YPlNcXBLRCu_ZHHzBCH2q_j01yiIkPyRp5-0E7HAQQ",
"oktaSessionId":"102a9q79TrqRWek9vHEPkP3yQ",
"apiToken":"f5c95fd8-efc4-497e-8128-51a014de3a9a",
"firstName":"Judy",
"lastName":"Test1",
"middleName":null,
"email":"abc#mailinator.com",
"isEmployee":true,
"pushNotificationStatus":true
},
"companyDetails":{
"profileScreenBackgroundColor":"13253D",
"companyColor":"7ED321",
"companyName":"Mobile App Demo",
"companyLogo":"http://",
"isSSO":false
}
}
}
PFB the hash file:
{"data"=>{"isActivated"=>true, "userDetails"=>
{"userId"=>"52321713-add8-4455-9e0c-426eab923338",
"oktaId"=>"00ub24c5bs6awQyBD0h7", "contactId"=>"0033300001tZ8k5AAC",
"oktaSessionToken"=>"201112Ncbw364pHojkD4UlzGb1knz9UTZPIy2LFDn9Tgy_FmgEpZmmU",
"oktaSessionId"=>"102Kd-c2yEeSnmwr3YKX8qeyg",
"apiToken"=>"f8f070e2-e51b-4d69-8b1a-b7b63d25e781",
"firstName"=>"Judy", "lastName"=>"Test1",
"middleName"=>nil,
"email"=>"judy.test1#mailinator.com",
"isEmployee"=>true,
"pushNotificationStatus"=>true},
"companyDetails"=>{"profileScreenBackgroundColor"=>"13253D", "companyColor"=>"7ED321",
"companyName"=>"Mobile App Demo", "companyLogo"=>"https:",
"isSSO"=>false}}}
The code below:
I had tried almost all means, not sure what am i missing.
apitoken = RestClient.post("https://", {'email'=>arg,'password'=>'abcs','deviceUUId'=>'udid', 'deviceTypeId'=>1}.to_json, { "Content-Type" => 'application/json','buildNumber' => '000','deviceTypeId'=>'9'})
puts apitoken
puts "**************"
puts apitoken["apiToken"]
logindetails = JSON.parse(apitoken)
tada = JSON.parse(logindetails)['data']['apitoken']
puts tada
puts logindetails
result = logindetails["data"]["apiToken"]
puts result
puts "**************"
logindetails.each do |logindetail|
puts logindetail
puts logindetail["apiToken]
puts "**************"
end
result = logindetails['apiToken']
puts result
end
The output I get is apiToken instead of the value of it. Any help is greatly appreciated.
The token is under data userDetails apiToken:
json['data']['userDetails']['apiToken'] #=> f5c95fd8-efc4-497e-8128-51a014de3a9a

Creating a Caesar Cipher Program in Python 3.4, but function doesn't work

Currently, I am creating a Caesar Cipher but it is not working correctly, can anyone help at all? The code will be below. At the moment, if the program is run first time (as in, no functions have to be re run) it works perfectly, but when the getKey() function is re run, it returns an error. After the code, the error is shown:
def runProgram():
def choice():
userChoice = input("Do you wish to Encrypt of Decrypt? Enter E or D: ").lower()
if userChoice == "e":
return userChoice
elif userChoice == "d":
return userChoice
else:
print("Invalid Response. Please try again.")
choice()
def getMessage():
userMessage = input("Enter your message: ")
return userMessage
def getKey():
try:
userKey = int(input("Enter a key number (1-26): "))
except:
print("Invalid Option. Please try again.")
getKey()
else:
if userKey < 1 or userKey > 26:
print("Invalid Option. Please try again.")
getKey()
else:
return userKey
def getTranslated(userChoice, message, key):
translated = ""
if userChoice == "e":
for character in message:
num = ord(character)
num += key
translated += chr(num)
savedFile = open('Encrypted.txt', 'w')
savedFile.write(translated)
savedFile.close()
return translated
else:
for character in message:
num = ord(character)
num -= key
translated += chr(num)
return translated
userChoice = choice() #Runs function for encrypt/decrypt selection. Saves choice made.
message = getMessage() #Run function for user to enter message. Saves message.
key = getKey() #Runs function for user to select key. Saves key choice.
translatedMessage = getTranslated(userChoice, message, key) #Runs function to translate message, using the choice, message and key variables)
print("\nTranslation complete: " + translatedMessage)
runProgram()
I have tried to create it error proof during the getKey() function with the try, except and else commands. It will 'Try' to see that the input is an int or not, if it is, it goes to else, but if it isn't an int, then it will rerun the function. If the function is rerun, and an int is entered, this error is given:
This is an example of it working:
Do you wish to Encrypt of Decrypt? Enter E or D: E
Enter your message: Hello
Enter a key number (1-26): 5
Translation complete: Mjqqt
This is an example when the getKey() function must be re run due to an int not being entered:
Do you wish to Encrypt of Decrypt? Enter E or D: E
Enter your message: Hello
Enter a key number (1-26): H
Invalid Option. Please try again.
Enter a key number (1-26): 5
Traceback (most recent call last):
File "C:\Python34\Encryptor2.py", line 54, in
runProgram()
File "C:\Python34\Encryptor2.py", line 52, in runProgram
translatedMessage = getTranslated(userChoice, message, key) #Runs function to translate message, using the choice, message and key variables)
File "C:\Python34\Encryptor2.py", line 35, in getTranslated
num += key
TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType'
As you can see, it re runs the function as I want it too, but the error occurs when adding the key to the ord of character.
The first call to getKey(), with your comment:
key = getKey() #Runs function for user to select key. Saves key choice.
Another place you call it:
if userKey < 1 or userKey > 26:
print("Invalid Option. Please try again.")
getKey()
If you were to write that with the same kind of comment, it would be:
getKey() #Runs function for user to select key. Doesn't save key choice.
What the user types in, comes out of getKey() ... and you aren't keeping track of it, so it vanishes. You then do.
return userKey
userKey is still the H you tried to convert to int, the one that failed. You didn't get rid of it, so it's still there.
The better solution is to rework the shape of your code, so getKey() never calls getKey() inside itself. Do the error checking outside, perhaps, like this kind of shape:
def getKey():
prompt user for key
try to convert to int and return the int
if it fails, return None as an indication that getting the key went wrong.
key = None #set some wrong placeholder
while (key is None) or (key < 1) or (key > 26):
key = getKey()
change your input to raw_input
just use the maketrans and translate functions that basically encrypt or decrypt the message for you.they make for a very short and efficient solution to the problem
message = input('enter message').lower()
offset = int(input('enter offset (enter a negative number to decrypt)'))
alphabet = 'abcdefghijklmnopqrstuvwxyz'
enc_alphabet = (alphabet[alphabet.index(alphabet[offset]):len(alphabet)])+ alphabet[0:offset]
data = str.maketrans(alphabet,enc_alphabet)
final_message = str.translate(message, data)
print(final_message)
This code really doesn't need to be this complicated at all, if you just use regex the code will be much shorter but (in my opinion) way better.
Here's a code I created for Caesar cipher encrypting, decrypting and using a shift of the user's choice using regex.
import re
def caesar(plain_text, shift):
cipherText = ''
for ch in plain_text:
stayInAlphabet = ord(ch) + shift
if ch.islower():
if stayInAlphabet > ord('z'):
stayInAlphabet -= 26
elif stayInAlphabet < ord('a'):
stayInAlphabet += 26
elif ch.isupper():
if stayInAlphabet > ord('Z'):
stayInAlphabet -= 26
elif stayInAlphabet < ord('A'):
stayInAlphabet += 26
finalLetter = chr(stayInAlphabet)
cipherText += finalLetter
print(cipherText)
return cipherText
selection = input ("encrypt/decrypt ")
if selection == 'encrypt':
plainText = input("What is your plaintext? ")
shift = (int(input("What is your shift? ")))%26
caesar(plainText, shift)
else:
plainText = input("What is your plaintext? ")
shift = ((int(input("What is your shift? ")))%26)*-1
caesar(plainText, shift)

Groovy: how to use Exceptions or <If> <else> construction with MySQL queries?

I have a query from table of MySQL database, and i want check: have i got this number in table and if not - println that this number not in database, if this number exist - println that this number exist. How i can do that, using Exceptions or (If) (else) construction?
Assuming you're using an in memory hsql db:
def sql = Sql.newInstance( 'jdbc:hsqldb:mem:testDB', // JDBC Url
'sa', // Username
'', // Password
'org.hsqldb.jdbc.JDBCDriver') // Driver classname
def tim = 'tim'
def name = sql.firstRow( "SELECT name FROM users WHERE userid=$tim" )?.name
if( name ) {
println "Name was $name"
}
else {
println "Name not found"
}