I am getting an error 'string object is not callable' - python-2.7

I am a beginner in python..I am learning decorators and all that stuff..
This is my code
def addone(myfunc):
def addsand():
return (str(myfunc())+'sand')
return addsand()
#addone
def oldfunc():
return 'ham'
print oldfunc()

The decorator should return a function, not a function's result. Replace return addsand() with return addsand.

Related

Write my own keras layer

I want to write my own keras layer with taking as input a tensor with shape (nb_batch, input_dim) and producing a tensor with shape (nb_batch, context_size, output_dim) . I have write a demo below:
class MyLayer(Layer):
def __init__(self, output_dim, context_size, init="uniform", **kwargs):
self.output_dim = output_dim
self.context_size = context_size
self.init = initializations.get(init)
super(MyLayer, self).__init__(**kwargs)
def build(self, input_shape):
input_dim = input_shape[1]
self.W_vec = self.init(
(self.context_size, input_dim, self.output_dim),
name="W_vec")
self.trainable_weights = [self.W_vec]
super(MyLayer, self).build() # be sure you call this somewhere!
def call(self, x, mask=None):
return K.dot(x, self.W_vec)
# return K.dot(x, self.W)
def get_output_shape_for(self, input_shape):
return (input_shape[0], self.context_size, self.output_dim)
when I ran it , got a error "TypeError: build() takes exactly 2 arguments (1 given)"enter code here
Looks like build needs input shape argument
super(MyLayer, self).build(input_shape) # be sure you call this somewhere!

Union Find algorithm in Python

I am trying to implement Union Find algorithm in python and I don't understand what's wrong with my code as everything seems to be in the right place.
Please help in this regard. Below is my code
class UnionFind:
def __init__(self,v):
self.parent = [-1 for i in range(v)]
self.lis=[]
def addEdge(self,i,j):
self.lis.append([i,j])
def findParent(self,i):
if self.parent[i] == -1:
return i
else :
self.findParent(self.parent[i])
def union(self,i,j):
self.parent[i]=j
def printResult(self):
print self.lis
def isBool(self):
for lisIter in self.lis:
x=self.findParent(lisIter[0])
y=self.findParent(lisIter[1])
if(x==y):
return True
self.union(x,y)
return False
uf = UnionFind(3)
uf.addEdge(0,1)
uf.addEdge(1,2)
uf.addEdge(2,0)
if uf.isBool():
print "The graph is cyclic"
else:
print "The graph is not cyclic"
Finally I got that little logic which I missed in the my code. I need to add the return statement in the else block of findParent method or else the returned value will be discarded and a none value will get returned. Uff!
def findParent(self,i):
if self.parent[i] == -1:
return i
else :
return self.findParent(self.parent[i])

Using dict like C switch

class checkevent:
def __init__(self,fromuser):
self.fromuser = fromuser
def openid_check(self):# use sqlalchemy
exist_user = User.query.filter_by(openid = self.fromuser).first()
if exist_user is None:
text = u'请绑定后在使用'
return text
def grade(self):
openid_check()
exist_user = User.query.filter_by(openid = self.fromuser).first()
geturp = urp(exist_user.username, exist_user.password_urp) #the function
return geturp #return the grades as text
def key_check(self,x): # use dict like switch
{'grade': self.grade
}
contents = checkevent('ozvT4jlLObJWzz2JQ9EFsWSkdM9U').key_check('grade')
print contents
It's always return None,I want to get a value
and it's the right way to use dict?
There's no return statement in key_check, so naturally it doesn't return anything. You're basically missing the last bit of the implementation: once you look up the appropriate function by name, you need to call that function and return the result.
def key_check(self, key): # "x" is a meaningless name; use something meaningful
lookup = {
'grade': self.grade
}
func = lookup[key] # Look up the correct method
return func() # Call that method and return its result
Technically you could in-line all that into one statement if you really wanted to, but unless performance is at a premium I wouldn't recommend it as the readability suffers.

Django 'int' object has no attribute 'status_code'

I start with def start method, it calls go_adder to add the num value 5 times in the adder.html until num equals 5. After that, the adder method should return ready=1
In views.py
def start(request):
num=0
ready_or_not=go_adder(num)
return HttpResponse("Ready: %s "%str(ready_or_not))
def go_adder(num):
ready=0
if num<5:
return render_to_response('adder.html',{'num':num})
elif num==5:
ready=1
return ready
def check_post(request,num):
if request.method == 'POST':
num+=1
return adder(num)
When I try to run this snippet code, it works until my "num=5", Then I get that error :
'int' object has no attribute 'status_code'
Exception Location: C:\Python27\lib\site-packages\django\middleware\common.py in process_response, line 94
and Traceback says:
C:\Python27\lib\site-packages\django\core\handlers\base.py in get_response
response = middleware_method(request, response) ...
▶ Local vars
C:\Python27\lib\site-packages\django\middleware\common.py in process_response
if response.status_code == 404: ...
▶ Local vars
How can I fix that error ? Could you please help me ?
The django views need to return an HttpResponse object. You are doing that while num < 5, but then you return an int when num == 5:
def adder(num):
ready=0
if num<5:
num+=1
# This renders the template and returns and HttpResponse; good
return render_to_response('adder.html',{'num':num})
elif num==5:
ready=1
# DONT RETURN AN INT HERE. RETURN AN HttpResponse
return ready
If all you want for when num==5 is to return a plain text response of the number 1, then you can return an HttpResponse and set the content type:
elif num==5:
ready=1
return HttpResponse(str(ready), content_type="text/plain")
Update 1
Based on our conversation, you have suggested that you want the view to constantly pass along the count value no matter what, and that you are POST-ing the num value in the actual form. If the number is less than 5 it should return one kind of template, otherwise it should return another kind of template.
You can combine your two different views into one that will handle both the original GET request when the page is first loaded, and the POST request submitted by your form. Just make sure to point your form at that same page.
def check(request):
num = 0
if request.method == 'POST':
num = int(request.POST.get('num'))
return adder(num)
def adder(num):
if num < 5:
num += 1
tpl_name = 'adder.html'
else:
tpl_name = 'print.html'
return render_to_response(tpl_name, {'num':num})
check() is your single view.
adder() is the helper function that will add the value, check it, and return an HttpResponse object based on that value. You must always return this from your view to the client.
Both templates will be passed the context containing the value of num
Update 2
You said that you are actually passing in your num through the url and not through the POST form. Small adjustment to the last example. You don't even need an adder() anymore. You only need a single view.
Set your url to have an optional num pattern:
urls.py
(r'^checker/(?P<num>\d+)$', 'myapp.views.check')
views.py
def check(request, num=0):
num = int(num)
if num < 5:
num += 1
tpl_name = 'adder.html'
else:
tpl_name = 'print.html'
return render_to_response(tpl_name, {'num':num})
Your "checker" url now has an optional number. If it is not passed in the url, it will be a value of 0 in the view. If you send it as a POST request, it will add and return a different template.

Overload get_FIELD_display() function

Is there a way to overload Django's get_FIELD_display() function properly? When I call the function from inside itself, the result is a recursion. But I can't call it using super() either, as it's not a parent class' method but a method created by the metaclass...
The goal is to have a common interface for getting a displayable version of a CHOICE field (which is given by get_FIELD_display), but with the possibility to customize it in some specific cases.
Example:
# This does not work because it results in recursion
def get_opposition_state_display(self):
"""Overloading of default function."""
value = self.get_opposition_state_display()
if self.opposition_state == 4:
return '%s %s' % (value, self.opposition_date.strftime('%d.%m.%Y'))
return value
updated
field = self._meta.get_field('opposition_state')
value = self._get_FIELD_display(field)
To override get_FOO_display you need something like this:
field_name = models.PositiveSmallIntegerField('Field', choices=some_choices)
def _get_FIELD_display(self, field):
f_name = field.name
if f_name == 'field_name':
return 'what_you_need'
return super(YourModelName, self)._get_FIELD_display(field=field)