I get this error when i try to use Wolfram Alpha in VS code python ValueError: dictionary update sequence element #0 has length 1; 2 is required - wolframalpha

This is my code
import wolframalpha
app_id = '876P8Q-R2PY95YEXY'
client = wolframalpha.Client(app_id)
res = client.query(input('Question: '))
print(next(res.results).text)
the question I tried was 1 + 1
and i run it and then i get this error
Traceback (most recent call last):
File "c:/Users/akshi/Desktop/Xander/Untitled.py", line 9, in <module>
print(next(res.results).text)
File "C:\Users\akshi\AppData\Local\Programs\Python\Python38\lib\site-packages\wolframalpha\__init__.py", line 166, in text
return next(iter(self.subpod)).plaintext
ValueError: dictionary update sequence element #0 has length 1; 2 is required
Please help me

I was getting the same error when I tried to run the same code.
You can refer to "Implementing Wolfram Alpha Search" section of this website for better understanding of how the result was extracted from the dictionary returned.
https://medium.com/#salisuwy/build-an-ai-assistant-with-wolfram-alpha-and-wikipedia-in-python-d9bc8ac838fe
Also, I tried the following code by referring to the above website....hope it might help you :)
import wolframalpha
client = wolframalpha.Client('<your app_id>')
query = str(input('Question: '))
res = client.query(query)
if res['#success']=='true':
pod0=res['pod'][0]['subpod']['plaintext']
print(pod0)
pod1=res['pod'][1]
if (('definition' in pod1['#title'].lower()) or ('result' in pod1['#title'].lower()) or (pod1.get('#primary','false') == 'true')):
result = pod1['subpod']['plaintext']
print(result)
else:
print("No answer returned")

Related

PDF to txt python3

I'm trying to convert pdf file to txt.
`
import re
import PyPDF2
with open('123.pdf', 'rb') as pdfFileObj:
pdfreader = PyPDF2.PdfFileReader(pdfFileObj)
x = pdfreader.numPages
pageObj = pdfreader.getPage(x + 1)
text = pageObj.extractText()
file1 = open(f"C:\\Users\\honorr\\Desktop\\ssssssss\{re.sub('pdf$','txt',pdfFileObj)}", "a")
file1.writelines(text)
file1.close()
Errors:
Traceback (most recent call last):
File "C:\Users\honorr\Desktop\ssssssss\main.py", line 5, in <module>
pageobj = pdfreader.getPage(x + 1)
File "C:\Users\honorr\Desktop\ssssssss\venv\lib\site-packages\PyPDF2\_reader.py", line 477, in getPage
return self._get_page(pageNumber)
File "C:\Users\honorr\Desktop\ssssssss\venv\lib\site-packages\PyPDF2\_reader.py", line 492, in _get_page
return self.flattened_pages[page_number]
IndexError: list index out of range
`
How to fix it?
So i don't know why i have this errors. Maybe somebody tell me another way to convert from PDF to TXT?
You're setting x to the number of pages, but then trying to get page x + 1, which doesn't exist. Depending on how the library is implemented (I'm not familiar with PyPDF2), you may need to try pdfreader.getPage(x) or pdfreader.getPage(x - 1) to get it to work. This will only get the last page in the document though.

ValueError: could not broadcast input array from shape (16,18,3) into shape (16)

I was trying to instance segment my RGB images using pixellib library. However, I encountered the problem from segmentImage function. From stacktrace, I found the issue within init.py, and I have no idea why it needs to broadcast from 3D arrays to 1D. 20 Images from another folder I tried earlier didn't counter any of these.
P.S. This was my first question on StackOverflow. if I miss any necessary details, please let me know.
for file in os.listdir(test_path):
abs_test_path = os.path.join(test_path, file)
if file.endswith('.jpg'):
filename = os.path.splitext(file)[0]
if (os.path.isfile(abs_test_path)):
out_path = out_seg_path + filename
segment_image.segmentImage(abs_test_path, show_bboxes=True,
save_extracted_objects=True,
extract_segmented_objects=True)
im_0 = cv2.imread('segmented_object_1.jpg')
cv2.imwrite(out_path + '_1.jpg', im_0)
im_1 = cv2.imread('segmented_object_2.jpg')
cv2.imwrite(out_path + '_2.jpg', im_1)
This is my error
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-4-835299843033> in <module>
15
16 segment_image.segmentImage(abs_test_path, show_bboxes=True,
---> 17 save_extracted_objects=True, extract_segmented_objects=True)
18
19 # segment_image.segmentImage('segmented_object_1.jpg', show_bboxes=True, output_image_name=out_path + '_1.jpg',
~\anaconda3\envs\mask_rcnn\lib\site-packages\pixellib\instance\__init__.py in segmentImage(self, image_path, show_bboxes, extract_segmented_objects, save_extracted_objects, mask_points_values, output_image_name, text_thickness, text_size, box_thickness, verbose)
762 cv2.imwrite(save_path, extracted_objects)
763
--> 764 extracted_objects = np.array(ex, dtype=object)
765
766 if mask_points_values == True:
ValueError: could not broadcast input array from shape (16,18,3) into shape (16)
There isn't enough information to help you.
I don't know what segment_image.segmentImage is, or what it expects. And I don't have your jpg file to test.
I have an idea of why the problem line raises this error, but since it occurs in an unknown function I can't suggest any fixes.
extracted_objects = np.array(ex, dtype=object)
ex probably is a list of arrays, arrays that match in some some dimensions but not others. It's trying to make an object dtype array of those arrays, but due to the mix of shapes it raises an error.
An simple example that raises the same error:
In [151]: ex = [np.ones((3, 4, 3)), np.ones((3, 5, 3))]
In [152]: np.array(ex, object)
Traceback (most recent call last):
Input In [152] in <module>
np.array(ex, object)
ValueError: could not broadcast input array from shape (3,4,3) into shape (3,)

Pandas function with 2 arguments to find threshold

I need to find people with greater or equal to threshold gain =>
dataframe contains column 'capitalGain' with different values 10,20,30,50,1000,5000,10000 ...etc
I try :
Function:
def get_num_people_with_higher_gain(dataframe, threshold_gain)
threshold_gain = dataframe["capitalGain"][dataframe["capitalGain"] >= threshold_gain].count()
return threshold_gain
Call function
df = get_num_people_with_higher_gain(dataframe, threshold_gain)
But I get the following error message:
NameError Traceback (most recent call last)
<ipython-input-50-5485c90412c8> in <module>
----> 1 df = get_num_people_with_higher_gain(dataframe, threshold_gain)
2 threshold = get_num_people_with_higher_gain(dataframe, threshold_gain)
NameError: name 'dataframe' is not defined
Since there are 2 arguments in the function (dataframe, threshold_gain), does it mean that both should be somehow defined within the function ?
Thanks
Finally,
Here is the solution
def get_num_people_with_higher_gain(dataframe, threshold_gain):
result = len(dataframe[dataframe["capitalGain"] >= threshold_gain])
return result
result = get_num_people_with_higher_gain(dataframe,60000)
result

ValueError: invalid literal for int() with base 10: 'O'

I am relatively new to python, and as such I don't always understand why I get errors. I keep getting this error:
Traceback (most recent call last):
File "python", line 43, in <module>
ValueError: invalid literal for int() with base 10: 'O'
This is the line it's referring to:
np.insert(arr, [i,num], "O")
I'm trying to change a value in a numpy array.
Some code around this line for context:
hOne = [one,two,three]
hTwo = [four,five,six]
hThree = [seven, eight, nine]
arr = np.array([hOne, hTwo, hThree])
test = "O"
while a != Answer :
Answer = input("Please Enter Ready to Start")
if a == Answer:
while win == 0:
for lists in arr:
print(lists)
place = int(input("Choose a number(Use arabic numerals 1,5 etc.)"))
for i in range(0,len(arr)):
for num in range(0, len(arr[i])):
print(arr[i,num], "test")
print(arr)
if place == arr[i,num]:
if arr[i,num]:
np.delete(arr, [i,num])
np.insert(arr, [i,num], "O")
aiTurn = 1
else:
print(space_taken)
The number variables in the lists just hold the int version of themselves, so one = 1, two = 2 three = 3, etc
I've also tried holding "O" as a variable and changing it that way as well.
Can anyone tell me why I'm getting this error?

PyOmo/Ipopt fails with "can't evaluate pow"

I am using PyOmo to generate a nonlinear model which will ultimately be solved with Ipopt. The model is as follows:
from pyomo.environ import *
from pyomo.dae import *
m = ConcreteModel()
m.t = ContinuousSet(bounds=(0,100))
m.T = Param(default=100,mutable=True)
m.a = Param(default=0.1)
m.kP = Param(default=20)
m.P = Var(m.t, bounds=(0,None))
m.S = Var(m.t, bounds=(0,None))
m.u = Var(m.t, bounds=(0,1), initialize=0.5)
m.Pdot = DerivativeVar(m.P)
m.Sdot = DerivativeVar(m.S)
m.obj = Objective(expr=m.S[100],sense=maximize)
def _Pdot(M,i):
if i == 0:
return Constraint.Skip
return M.Pdot[i] == (1-M.u[i])*(M.P[i]**0.75)
def _Sdot(M,i):
if i == 0:
return Constraint.Skip
return M.Sdot[i] == M.u[i]*0.2*(M.P[i]**0.75)
def _init(M):
yield M.P[0] == 2
yield M.S[0] == 0
yield ConstraintList.End
m.Pdotcon = Constraint(m.t, rule=_Pdot)
m.Sdotcon = Constraint(m.t, rule=_Sdot)
m.init_conditions = ConstraintList(rule=_init)
discretizer = TransformationFactory('dae.collocation')
discretizer.apply_to(m,nfe=100,ncp=3,scheme='LAGRANGE-RADAU')
discretizer.reduce_collocation_points(m,var=m.u,ncp=1,contset=m.t)
solver = SolverFactory('ipopt')
results = solver.solve(m,tee=False)
Running the model results in the following error:
Error evaluating constraint 1: can't evaluate pow'(0,0.75).
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/dist-packages/pyomo/opt/base/solvers.py", line 577, in solve
"Solver (%s) did not exit normally" % self.name)
pyutilib.common._exceptions.ApplicationError: Solver (asl) did not exit normally
The first part of the error comes from Ipopt whereas the second part comes from PyOmo. Evidently the issue has something ot do with the term M.P[i]**0.75 in the constraints, but changing the power does not resolve the issue (though 2.0 did work).
How can I resolve this?
The error message states that pow'(0,0.75) cannot be evaluated. The ' character in this function indicates the first derivative ('' would indiate the second derivative). The message is effectively saying that the first derivative does not exist or results in an infinity at zero.
Resolving the issue is easy: bound your variables to a non-zero value as follows:
m.P = Var(m.t, bounds=(1e-20,None))
m.S = Var(m.t, bounds=(1e-20,None))
I would add to Richard's answer:
you might also need to update the initial value of your variable as ipopt assumes 0 if not specified, so it will evaluate the variable at 0 for the first iteration.
hence:
m.P = Var(m.t, bounds=(1e-20,None), initialize=1e-20)
m.S = Var(m.t, bounds=(1e-20,None), initialize=1e-20)
instead of 1e-20 as initialize you might use a value more relevant to your problem