Calling a custom function in Rasa Actions - chatbot

I am facing a problem in developing a chatbot using rasa .
I am trying to call a custom function in rasa action file. But i am getting an error saying "name 'areThereAnyErrors' is not defined"
here is my action class. I want to call areThereAnyErrors function from run method. Could someone please help how to resolve this?
class ActionDayStatus(Action):
def areThereAnyErrors(procid):
errormessagecursor = connection.cursor()
errormessagecursor.execute(u"select count(*) from MT_PROSS_MEAGE where pro_id = :procid and msg_T = :messageT",{"procid": procid, "messageT": 'E'})
counts = errormessagecursor.fetchone()
errorCount = counts[0]
print("error count is {}".format(errorCount))
if errorCount == 0:
return False
else:
return True
def name(self):
return 'action_day_status'
def run(self, dispatcher, tracker, domain):
import cx_Oracle
import datetime
# Connect as user "hr" with password "welcome" to the "oraclepdb" service running on this computer.
conn_str = dbconnection
connection = cx_Oracle.connect(conn_str)
cursor = connection.cursor()
dateIndicator = tracker.get_slot('requiredDate')
delta = datetime.timedelta(days = 1)
now = datetime.datetime.now()
currentDate = (now - delta).strftime('%Y-%m-%d')
print(currentDate)
cursor = connection.cursor()
cursor.execute(u"select * from M_POCESS_FILE where CREATE_DATE >= TO_DATE(:createDate,'YYYY/MM/DD') fetch first 50 rows only",{"createDate":currentDate})
all_files = cursor.fetchall()
total_number_of_files = len(all_files)
print("total_number_of_files are {}".format(total_number_of_files))

Answer given by one of the intellectuals :
https://realpython.com/instance-class-and-static-methods-demystified/ Decide whether you want a static method or class method or instance method and call it appropriately . Also when you are using connection within the function it should be a member variable or passed to the method You dont have self as a parameter so you may be intending it as a static method - but you dont have it created as such

Related

How to use timer.performWithDelay with a method call

I'm using a Lua class to create two objects, each of which must check where the other is to determine their movement. I'm attempting to use timer.performWithDelay to have them check every second, but for some reason when I try to do this, the line
o.moveCheckTimer = timer.performWithDelay(1000, o:moveCheck, 0)
in the class constructor throws an error stating that "Function arguments are expected near ','".
I have attempted to use an anonymous function like this:
o.moveCheckTimer = timer.performWithDelay(1000, function() o:moveCheck() end, 0)
but that causes the timer of both objects to only call the function for the most recent object that was created and not for itself (also very confusing behavior, and if anyone knows why this happens I would love to learn why).
I have dug through the API and info on method calls thoroughly, but I can't seem to find anything that uses them both together, and I feel like I'm missing something.
How can I use the method call as the listener for this timer?
Here is the full constructor:
Melee = {}
Melee.__index = Melee
function Melee:new(id, name, lane, side)
local o = {}
setmetatable(o, Melee)
o.id = id
o.name = name
o.lane = lane
o.side = side
if name == "spearman" then
o.maxhp = 100
o.range = 1
o.damage = {10, 20}
o.imageName = "images/rebels/spearman.png"
else
error("Attempted to create melee unit with undefined name")
end
o.hp = o.maxhp
--Display self
o.image = display.newImageRect(mainGroup, "images/rebels/spearman.png", 80, 80)
o.image.x = 0
o.image.y = lanes[lane]
o.image.anchorY = 1
if side == 2 then
o.image.xScale = -1
o.image:setFillColor(0.8)
o.image.x = display.contentWidth - 100
end
--Move and attack
local destination = display.contentWidth
if side == 2 then
destination = 0
end
o.moving = 1
o.movement = transition.to(o.image, {x = destination, time = 30000+math.random(-200,200)})
o.moveCheckTimer = timer.performWithDelay(1000, o:moveCheck, 0)
--o.attackTimer = timer.performWithDelay(1000, self:attack, 0)
return o
end

Kivy getting values from Popup Window and use it at a Screen

Hi i am new to kivy and just started programming. So what i want to do is,once a user key in a valid date/time in the popup window, popup will close and will goes to a screen and create buttons. May i know how to pass the values get from getDay() which is dayoutput,timeoutput from popupwindow and transfer use it in another other class? and be able to use in the VariesTimeScreen?
Thank your for taking your time to help :)
class SetDateTime(Popup):
def getDay(self):
set_day = (self.ids.dayofmonth).text
set_month = (self.ids.month).text
set_year = (self.ids.year).text
set_hour = (self.ids.houroftime).text
set_minutes = (self.ids.minuteoftime).text
wrongtime = self.ids.wronginput_time
#Calculate Date and Time only when user input a valid number
if set_day.isdigit() and set_month.isdigit() and
set_year.isdigit()andset_hour.isdigit()
and set_minutes.isdigit():
try:
set_date = datetime.date(int(set_year),
int(set_month),int(set_day))
set_time = datetime.time(int(set_hour), int(set_minutes))
if not (set_date >= counttime.todaydate()):
wrongtime.text = "[color=#FF0000]Date is out of
range[/color]"
if not (set_time >= counttime.todaytime()):
wrongtime.text = "[color=#FF0000]Time is out of
range[/color]"
dayoutput = counttime.calculatedate(set_date)
timeoutput = set_hour + set_minutes
self.dismiss()
return dayoutput,timeoutput
except ValueError:
wrongtime.text = "[color=#FF0000]Please enter a valid
datetime.[/color]"
else:
wrongtime.text = "[color=#FF0000]Please enter a valid
date[/color]"
class VariesTimeScreen(Screen):
def __init__(self, **kwargs):
super(VariesTimeScreen, self).__init__(**kwargs)
a = '_icons_/mcdonald.png'
b = '_icons_/kfc.png'
c = '_icons_/subway.png'
Outlet_Store = [a,b,c]
layout = GridLayout(rows=1, spacing=100, size_hint_y=None,
pos_hint ={"top":.6,"x":0.2})
layout.bind(minimum_height=layout.setter('height'))
#Before the for loop there will be an if statement which is
the Day and Time i get from getDay() values. This part i'm
unsure how to retrieve the values from the SetDateTime Class
for image in Outlet_Store:
food_image = ImageButton(size_hint=(None, None),size=
(100,100),source=image)
layout.add_widget(food_image)
self.add_widget(layout)
One problem with your design is that the VariesTimeScreen is created very early in the App run, like when the GUI is created. So, the day and time from the SetDateTime Popup is not yet available. One way to handle this is to add an on_enter() method to the VariesTimeScreen to make any adjustments to the Screen at that time. To do that, I added Properties to the VariesTimeScreen:
class VariesTimeScreen(Screen):
day = StringProperty('None')
time = NumericProperty(0)
And add the on_enter() method to the VariesTimeScreen class:
def on_enter(self, *args):
print('day:', self.day, ', time:', self.time)
# make changes to the Screen
And then change the SetDateTime class slightly:
class SetDateTime(Popup):
def getDay(self):
set_day = (self.ids.dayofmonth).text
set_month = (self.ids.month).text
set_year = (self.ids.year).text
set_hour = (self.ids.houroftime).text
set_minutes = (self.ids.minuteoftime).text
wrongtime = self.ids.wronginput_time
# Calculate Date and Time only when user input a valid number
if set_day.isdigit() and set_month.isdigit() and set_year.isdigit() and set_hour.isdigit() and set_minutes.isdigit():
try:
set_date = datetime.date(int(set_year),
int(set_month), int(set_day))
set_time = datetime.time(int(set_hour), int(set_minutes))
if not (set_date >= counttime.todaydate()):
wrongtime.text = "[color=#FF0000]Date is out of range[ / color]"
if not (set_time >= counttime.todaytime()):
wrongtime.text = "[color=#FF0000]Time is out of range[ / color]"
dayoutput = counttime.calculatedate(set_date)
timeoutput = set_hour + set_minutes
# get the VariesTimeScreen
varies_time = App.get_running_app().root.ids.screen_manager.get_screen('variestime_screen')
# set the day and time for the VariesTimeScreen
varies_time.day = dayoutput
varies_time.time = timeoutput
# switch to the VariesTimeScreen
App.get_running_app().change_screen('variestime_screen')
# dismiss Popup
self.dismiss()
except ValueError:
wrongtime.text = "[color=#FF0000]Please enter a valid datetime.[ / color]"
else:
wrongtime.text = "[color=#FF0000]Please enter a valid date[ / color]"
The only changes are to set the day and time in the VariesTimeScreen, and to actually switch to the VariesTimeScreen. The switch to the VariesTimeScreen doesn't have to happen there, once the day and time are set, the on_enter() method will get called whenever it becomes the current Screen.

grails Objects query when hasMany relationship is NULL

Not able to get the list of Objects when a hasMany attribute is null.
Class User {
...
List<EMail> emails
static hasMany = [emails: EMail,... ]
static mappedBy = [emails: 'customer',...]
...
}
Where Email is another Class with some String Attributes
Now i am trying to make a simple query as:
Method 1:
def users = User.findAllByEmailsIsEmpty()
This is giving Error as:
Queries of type IsEmpty are not supported by this implementation
Method 2:
def users = User.findAllByEmailsIsNull()
This is giving all the users even those have Email object associated with it.
Then I thought of trying Criteria Query (https://grails.github.io/grails-doc/latest/ref/Domain%20Classes/createCriteria.html )
Method 3:
def userCriteria = User.createCriteria()
def users = userCriteria.list(){
sizeEq('emails', 0)
}
This gives No result ( users.size() is 0 )
Method 4:
def userCriteria = User.createCriteria()
def users = userCriteria.list(){
isNull('emails')
}
This again gives all the Users even those who don't have emails.
Method 5:
def userCriteria = User.createCriteria()
def users = userCriteria.list(){
isEmpty('emails')
}
This gives the Error :
Queries of type IsEmpty are not supported by this implementation
Method 6:
def userCriteria = User.createCriteria()
def users = userCriteria.list(){
eq('emails', null)
}
This again lists down all the users.
PS: Grails is configured with Database as MongoDB.
I would use the grep method. Something like this:
nullEmailUsers = User.list().grep {
!it.emails
}
User.findAll { emails.id != null } do the job!

How to get e-mail address of current Jenkins user to use in groovy script

I've created a groovy script for the new Jenkins Workflow Plugin, https://github.com/jenkinsci/workflow-plugin. I want it to send a mail to the user who started the job when it needs input for the next step. I've tried to search the API but I can't find anything about getting the users email address.
I would think of something like this.
import hudson.model.User
def user = User.current()
def mailAddress = user.getMailAddress()
Is there a way to get the current Jenkins user' address in groovy?
I found a way:
import hudson.model.AbstractProject
import hudson.tasks.Mailer
import hudson.model.User
def item = hudson.model.Hudson.instance.getItem(env.JOB_NAME)
def build = item.getLastBuild()
def cause = build.getCause(hudson.model.Cause.UserIdCause.class)
def id = cause.getUserId()
User u = User.get(id)
def umail = u.getProperty(Mailer.UserProperty.class)
print umail.getAddress()
You can access the object of the current user with the method current()
def user = hudson.model.User.current();
The email address can be retrieved in the same way as to what you have done in your answer.
print user.getProperty(hudson.tasks.Mailer.UserProperty.class).getAddress();
import hudson.tasks.Mailer;
import hudson.model.User;
import hudson.model.Cause;
import hudson.model.Cause.UserIdCause;
def cause = build.getCause(hudson.model.Cause$UserIdCause)
def id = cause.getUserId()
User u = User.get(id)
def umail = u.getProperty(Mailer.UserProperty.class)
print umail.getAddress()
If you have access to the build variable in the Java code of your plugin (for instance in the setUp() method of the class that extends BuildWrapper), you can get the currently logged user this way :
#Override
public MyJenkinsPlugin setUp(AbstractBuild build, Launcher launcher, BuildListener listener)
String connectedUser = build.getCause(Cause.UserIdCause.class).getUserId();
String mail = User.get(connectedUser.getProperty(hudson.tasks.Mailer.UserProperty.class).getEmailAddress()
...
}
I have not been able to get the logged user using User.current().getId(), it always returned me 'SYSTEM'.
Hope it helps!
You can get the author name and then use it for an example on a mailing registry or something like that:
def author = ""
def changeSet = currentBuild.rawBuild.changeSets
for (int i = 0; i < changeSet.size(); i++)
{
def entries = changeSet[i].items;
for (int i = 0; i < changeSet.size(); i++)
{
def entries = changeSet[i].items;
def entry = entries[0]
author += "${entry.author}"
}
}
print author;
You can use the following routine:
import hudson.tasks.Mailer;
import hudson.model.User;
/**#
* Get user's email
*
* #param id null for a user who triggered the current build or name otherwise
* #return user's email
*/
def getUserEmail(String id=null) {
User user = User.getById(id ?: currentBuild.rawBuild.getCause(Cause.UserIdCause).getUserId(), false)
user?.getProperty(Mailer.UserProperty.class).getAddress()
}

MongoAlchemy query embedded documents

I want to know how to use MongoAlchemy about embeded docment operation.
But I havn't find any documents about these.
Can anyone give me some helps?
Here is demo code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
from flask import Flask
from flaskext.mongoalchemy import MongoAlchemy
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['MONGOALCHEMY_DATABASE'] = 'book'
db = MongoAlchemy(app)
class Comment(db.Document):
user_id = db.StringField(db_field='uid')
posted = db.StringField(db_field='posted')
class Book(db.Document):
title = db.StringField()
author = db.StringField()
comments = db.ListField(db.DocumentField(Comment), db_field='Comments')
from mongoalchemy.session import Session
def test():
with Session.connect('book') as s:
s.clear_collection(Book)
save()
test_Book()
def save():
title = "Hello World"
author = 'me'
comment_a = Comment(user_id='user_a', posted='post_a')
comment_b = Comment(user_id='user_b', posted='post_b')
comments = [comment_a, comment_b]
book = Book(title=title, author=author, comments=comments)
book.save()
def test_Book():
book = Book.query.filter({'author':'me'}).first()
comment = book.comments[0]
comment.posted = str(book.comments[0].posted)+'_new'
book.save()
print 'change posted: Book.comments[0].posted:', book.comments[0].posted
comment_c = Comment(user_id='user_c', posted='post_c')
book.comments.append(comment_c)
book.save()
print 'append: Book.comments[2].posted:', book.comments[2].posted
query = Book.query.filter({Book.comments:{'$elemMatch':{Comment.user_id:'user_c'}}}).limit(1).first()
print 'query type:', type(query)
if __name__ == '__main__':
test()
I want to query data which user_id is "user_c", and just return back one Comment, How can I do that?
Does these methods below are MongoAlchemy remommended? BTW, these methods will return the whole document.
#query = Book.query.filter({Book.comments:{'uid':'user_c'}}).limit(1).first()
#query = Book.query_class(Comment).filter(Comment.user_id == 'user_c').limit(1).first()
#query = Book.query.filter({'comments':{'$elemMatch':{'uid':'user_c'}}}).limit(1).first()
#query = Book.query.filter({Book.comments:{'$elemMatch':{Comment.user_id:'user_c'}}}).limit(1).first()
How can I change "user_c" to "user_c_new" which find by query ?
How can I remove one comment which user_id is "user_b"?
Mongo doesn't support returning subdocuments. You can use $elemMatch to filter so that only documents with matching attributes are returned, but you'll have to grab the comments yourself. You could slightly optimize by only returning the comments field as follows:
query = Book.query.filter({Book.comments:{'$elemMatch':{Comment.user_id:'user_c'}}})
query = query.fields(Book.comments.elem_match({Comment.user_id:'user_c'}))
result = query.limit(1).first()
print 'query result:', result.comments
Note that there was a bug with this up until 0.14.3 (which I just released a few minutes ago) which would have caused results.comments not to work.
Another very important note is that the elem_match I'm doing there only returns the first matching element. If you want all matching elements you have to filter them yourself:
query = Book.query.filter({Book.comments:{'$elemMatch':{Comment.user_id:'user_c'}}})
result = query.limit(1).first()
print 'query result:', [c for c in result.comments if c.user_id == 'user_c']