How to resolve TypeError? - python

from __future__ import division
import urllib,urllib2
import urllib
import json
from math import log
def hits(word1,word2=""):
query = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%s"
if word2 == "":
results = urllib.urlopen(query % word1)
else:
results = urllib.urlopen(query % word1+" "+"AROUND(10)"+" "+word2)
json_res = json.loads(results.read())
google_hits=int(json_res['responseData']['cursor']['estimatedResultCount'])
return google_hits
def so(phrase):
num = hits(phrase,"excellent") * hits("poor")
den = hits(phrase,"poor") * hits("excellent")
ratio = num / den
sop = log(ratio,2)
return sop
print so("beautiful product")
I require the above code to calculate the semantic orientation of a given phrase(or string).
When I execute the code, I get the following error:
Traceback (most recent call last):
File "C:\Python27\nltkexp\ddddd.py", line 32, in <module>
print so("beautiful product")
File "C:\Python27\nltkexp\ddddd.py", line 24, in so
den = hits(phrase,"poor") * hits("excellent")
File "C:\Python27\nltkexp\ddddd.py", line 16, in hits
google_hits=int(json_res['responseData']['cursor']['estimatedResultCount'])
TypeError: 'NoneType' object has no attribute '__getitem__'
How to resolve this error? Can someone point out where I am going wrong with the code?

You are accessing json_res['responseData']['cursor']['estimatedResultCount'], the problem is
json_res or json_res['responseData'] or json_res['responseData']['cursor'] might be None and its can't access key of the NoneType object.
Please print json_resp and check which keys are available in that.

Related

How to fix '' 'Mul' object has no attribute 'sp' " error in Python (using Sympy & Math)

I'm making a program that uses derivates to calculate an error.
I keep getting this error : 'Mul' object has no attribute 'sp'.
The solutions to this error that i've found so far are when people import everything from sympy and math (from sympy/math import *) because both sympy and math have a sin() function.
But as you can see from my code bellow i don't have it like that and the error still shows up, why?
import sympy as sp
from math import factorial
def F(x):
return 4*(x**2)+sp.sin(9*x)
sp.init_printing()
x=sp.symbols('x')
def D1(x1):
return(sp.diff(F(x),x,1).sp.subs(x,x1))
def D2(x1):
return(sp.diff(F(x),x,2).sp.subs(x,x1))
def D3(x1):
return(sp.diff(F(x),x,3).sp.subs(x,x1))
def maxD3(x1,x2):
if(D3(x1)>D3(x2)):
return D3(x1)
else:
return D3(x2)
erro1 = (1/factorial(3))*maxD3(-1,1)*abs((0.3-(-1))*(0.3-1))
erro1 = (1/factorial(3))*maxD3(-1,1)*abs((0.83-(-1))*(0.83-1))
print("Erro f(0.3): ", erro1)
print("Erro f(0.83): ", erro2)
Also have changed "from math import factorial" to "import math as math" and the error also keeps showing up.
I'm using Python 3.6.1.
EDIT: Full Traceback
Traceback (most recent call last):
File "main.py", line 24, in <module>
erro1 = (1/math.factorial(3))*maxD3(-1,1)*abs((0.3-(-1))*(0.3-1))
File "main.py", line 19, in maxD3
if(D3(x1)>D3(x2)):
File "main.py", line 16, in D3
return(sp.diff(F(x),x,3).sp.subs(x,x1))
AttributeError: 'Mul' object has no attribute 'sp'
This is the corrected version of your code
import sympy as sp
from math import factorial
def F(x):
return 4*(x**2)+sp.sin(9*x)
sp.init_printing()
x=sp.symbols('x')
def D1(x1):
return(sp.diff(F(x),x,1).subs(x,x1)) # subs instead of sp.subs
def D2(x1):
return(sp.diff(F(x),x,2).subs(x,x1)) # subs instead of sp.subs
def D3(x1):
return(sp.diff(F(x),x,3).sp.subs(x,x1))
def maxD3(x1,x2):
if(D3(x1)>D3(x2)):
return D3(x1)
else:
return D3(x2)
erro1 = (1/factorial(3))*maxD3(-1,1)*abs((0.3-(-1))*(0.3-1))
erro2 = (1/factorial(3))*maxD3(-1,1)*abs((0.83-(-1))*(0.83-1)) # erro2 instead of erro1
print("Erro f(0.3): ", erro1)
print("Erro f(0.83): ", erro2)
Output on my system:
('Erro f(0.83): ', 0)
('Erro f(0.83): ', 0)
Is this the expected output?
Also, you don't need to import everything from sympy. You can just import what you need.
Example:
>>> from sympy import sin, symbols, diff
>>> x = symbols('x')
>>> f = x**3 + sin(x)
>>> print(diff(f, x))
3*x**2 + cos(x)
>>> print(diff(f, x).subs(x, 1))
cos(1) + 3

TypeError: cannot concatenate 'str' and 'Response' objects

(Ignoring that g.text and p.content return "You're not authorised to view this content" from plug.dj) I get the error
Traceback (most recent call last):
File "plugling.py", line 20, in <module>
r.send('{"a":"auth","p":"'+g+'","t":'+t+'}')
TypeError: cannot concatenate 'str' and 'Response' objects
When running this code:
import time
from websocket import create_connection
import requests
import calendar
slug = 'sfoc'
r = create_connection("wss://godj.plug.dj/socket")
t = calendar.timegm(time.gmtime())
token = 'https://plug.dj/_/auth/token'
join = 'https://plug.dj/_/rooms/join'
pl = {'slug': 'sfoc'}
g = requests.get(token)
print g.text
p = requests.post(join, data=pl)
print p.content
r.send('{"a":"auth","p":"'+g+'","t":'+t+'}')
result = r.recv()
print result
r.close()
It didn't like me using %s for the variables either. I don't know what I'm doing wrong. Thanks in advance and let me know if I haven't explained something clearly.
You are trying to concatenate a Response object:
g = requests.get(token)
# ...
r.send('{"a":"auth","p":"'+g+'","t":'+t+'}')
g is the response object. You wanted to get the text value:
r.send('{"a": "auth", "p": "' + g.text + '", "t":' + t + '}')
You may want to look at the json module if you are trying to send JSON data there:
r.send(json.dumps({'a': 'auth', 'p': g.text, 't': t}))

Is there a bug in this python module or am I using it the wrong way?

lambda from getattr getting called with "connection" as a keyword argument? Am I misusing the code or is there a bug?
Code and traceback: https://github.com/bigcommerce/bigcommerce-api-python/issues/32
#!/usr/bin/env python2
import bigcommerce
import bigcommerce.api
BIG_URL = 'store-45eg5.mybigcommerce.com'
BIG_USER = 'henry'
BIG_KEY = '10f0f4f371f7953c4d7d7809b62463281f15c829'
api = bigcommerce.api.BigcommerceApi(host=BIG_URL, basic_auth=(BIG_USER, BIG_KEY))
def get_category_id(name):
get_request = api.Categories.get(name)
try:
cat_list = api.Categories.all(name=name)
if cat_list:
return cat_list[0]['id']
else:
return None
except:
return None
def create_category(name):
rp = api.Categories.create(name)
if rp.status == 201:
return rp.json()['id']
else:
return get_category_id(name)
create_category('anothertestingcat')
Gives this traceback:
Traceback (most recent call last):
File "./bigcommerceimporter.py", line 50, in
create_category('anothertestingcat')
File "./bigcommerceimporter.py", line 44, in create_category
rp = api.Categories.create(name)
File "/home/henry/big_test_zone/local/lib/python2.7/site-packages/bigcommerce/api.py", line 57, in
return lambda args, *kwargs: (getattr(self.resource_class, item))(args, connection=self.connection, *kwargs)
TypeError: create() got multiple values for keyword argument 'connection'
Line in api.py that the traceback refers to: https://github.com/bigcommerce/bigcommerce-api-python/blob/master/bigcommerce/api.py#L57
According to the examples, create should be used like this:
api.Categories.create(name = 'anothertestingcat')
Note: You should generate a new API KEY, since you published the current one in this question.

Error always on line 102 of my code

So I am creating a module, and I am importing it to a python shell and running some stuff to make sure all features work and such.
For some reason every time I run the code, it gives the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ryansaxe/Desktop/Code/python/modules/pymaps.py", line 102, in url_maker
#anything can be here
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
So where the #anything can be here is, is whatever is on line 102 of my code. Originally line 102 was:
if isinstance(startindex,datetime.datetime):
and I got the error above. I put a quick print statement on line 102 to check and it gave the same error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ryansaxe/Desktop/Code/python/modules/pymaps.py", line 102, in url_maker
print 'Hello'
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
Is this some sort of bug? Why is it telling me there is an error with datetime on the line print 'Hello'?
Because it may be helpful, I will give you the function I am having trouble with since I have no clue how this is possible. I am keeping the print 'Hello' line so you can see where line 102 is:
def url_maker(latitudes,longitudes,times=None,color='red',label=' ',zoom=12,center=None,start=None,end=None,by=None,size='600x300'):
urls = []
import datetime
if isinstance(times[0],str) or isinstance(times[0],datetime.datetime):
from dateutil import parser
if isinstance(times[0],str):
times = [parser.parse(x) for x in times]
if isinstance(start,str):
startindex = parser.parse(start)
else:
startindex = start
if isinstance(end,str):
endindex = parse.parse(end)
else:
endindex = end
print 'Hello'
if isinstance(startindex,datetime.datetime):
startpos = between_times(times,startindex,by='start')
elif isinstance(startindex,int):
if isinstance(endindex,datetime.datetime):
startpos = between_times(times,endindex,by='end') - start
else:
startpos = start
else:
pass
if isinstance(endindex,datetime.datetime):
endpos = between_times(times,endindex,by='end')
elif isinstance(endindex,int):
if isinstance(startindex,datetime.datetime):
endpos = between_times(times,startindex,by='start') + end
else:
endpos = end
else:
pass
else:
times = range(1,len(latitudes) + 1)
if isinstance(start,int):
startpos = start
else:
startpos = None
if isinstance(end,int):
endpos = end
else:
endpos = None
if isinstance(by,str):
lat,lon,t = latitudes[startpos:endpos],latitudes[startpos:endpos],times[startpos:endpos]
print lat
t,lats,lons = time_sample(t,by,lat,lon)
elif isinstance(by,int):
lats,lons,t = latitudes[startpos:endpos:by],latitudes[startpos:endpos:by],times[startpos:endpos:by]
else:
lats,lons,t= latitudes[startpos:endpos],latitudes[startpos:endpos],times[startpos:endpos]
print t
print len(t)
if center == None:
latit = [str(i) for i in lats]
longi = [str(i) for i in lons]
center = '&center=' + common_finder(latit,longi)
else:
center = '&center=' + '+'.join(center.split())
zoom = '&zoom=' + str(zoom)
for i in range(len(lats)):
#label = str(i)
x,y = str(lats[i]),str(lons[i])
marker = '&markers=color:' + color + '%7Clabel:' + label + '%7C' + x + ',' + y
url = 'http://maps.googleapis.com/maps/api/staticmap?maptype=roadmap&size=' + size + zoom + center + marker + '&sensor=true'
urls.append(url)
#print i
return urls,t
You are running with a stale bytecode cache or are re-running the code in an existing interpreter without restarting it.
The traceback code has only bytecode to work with, which contains filename and linenumber information. When an exception occurs, the source file is loaded to retrieve the original line of code, but if the source file has changed, that leads to the wrong line being shown.
Restart the interpreter and/or remove all *.pyc files; the latter will be recreated when the interpreter imports the code again.
As for your specific exception; you probably imported the datetime class from the datetime module somewhere:
from datetime import datetime
The datetime class does not have a datetime attribute, only the module does.

python ctypes and sysctl

I have following code
import sys
from ctypes import *
from ctypes.util import find_library
libc = cdll.LoadLibrary(find_library("c"))
CTL_KERN = 1
KERN_SHMMAX = 34
sysctl_names = {
'memory_shared_buffers' : (CTL_KERN, KERN_SHMMAX),
}
def posix_sysctl_long(name):
_mem = c_uint64(0)
_arr = c_int * 2
_name = _arr()
_name[0] = c_int(sysctl_names[name][0])
_name[1] = c_int(sysctl_names[name][1])
result = libc.sysctl(_name, byref(_mem), c_size_t(sizeof(_mem)), None, c_size_t(0))
if result != 0:
raise Exception('sysctl returned with error %s' % result)
return _mem.value
print posix_sysctl_long('memory_shared_buffers')
which produces following result:
Traceback (most recent call last):
File "test.py", line 23, in <module>
print posix_sysctl_long('memory_shared_buffers')
File "test.py", line 20, in posix_sysctl_long
raise Exception('sysctl returned with error %s' % result)
Exception: sysctl returned with error -1
I gues I did something wrong. What would be the correct calling convention? How would I find out what exactly went wrong?
You are not providing the correct values to the sysctl function. Detailed information on the arguments of sysctl() can be found here.
Here are your errors:
You have forgotten the nlen argument (second argument)
The oldlenp argument is a pointer to the size, not directly the size
Here is the correct function (with minor improvement):
def posix_sysctl_long(name):
_mem = c_uint64(0)
_def = sysctl_names[name]
_arr = c_int * len(_def)
_name = _arr()
for i, v in enumerate(_def):
_name[i] = c_int(v)
_sz = c_size_t(sizeof(_mem))
result = libc.sysctl(_name, len(_def), byref(_mem), byref(_sz), None, c_size_t(0))
if result != 0:
raise Exception('sysctl returned with error %s' % result)
return _mem.value

Categories

Resources