ValueError: invalid literal for int() with base 10: '5df1170a921ee283d8529aa3' - python

I am trying to retrieve one book from a json of books. When retrieving a single book i get this Value Error message on the line that is in bold.
Error -
show_all_books
page_num = int(request.args.get('pn'))
ValueError: invalid literal for int() with base 10: '5df1170a921ee283d8529aa3'
#app.route("/api/v1.0/books", methods=["GET"])
def show_all_books():
page_num, page_size = 1, 10
if request.args.get('pn'):
***page_num = int(request.args.get('pn'))***
if request.args.get('ps'):
page_size = int(request.args.get('ps'))
page_start = (page_size * (page_num - 1))

You are getting this error because you can't convert the string to integer because it have characters that doesn't allow it:
int('5df1170a921ee283d8529aa3')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5df1170a921ee283d8529aa3'
If you try with a number:
int('1231')
1231
So I think that the problem is with the data you receive in get('pn'). The default base of the int() function is 10 but you can do this with hexadecimal base:
int('5df1170a921ee283d8529aa3', 16)
29073565845337865796180941475L

You are getting this error because the string passed to the function can not be represented as an integer.
For instance if you were to do:
int('abc')
you'd get the same error, because the string abc can not be represented as an integer.

Related

Django scientific notation input validation

I have the following fields on my model:
class Range(models.Model):
optimal_low = models.DecimalField(max_digits=30, decimal_places=8)
optimal_high = models.DecimalField(max_digits=30, decimal_places=8)
And here's how I bring them into the form (because the form's primary object is not this model, I just need the fields, and don't want to duplicate the max_digits and decimal_places.
class ReadingMappingForm(forms.ModelForm):
optimal_low = Range._meta.get_field('optimal_low').formfield()
optimal_high = Range._meta.get_field('optimal_high').formfield()
It seems django allows entering of decimals in scientific notation out of the box, but there's a glitch above a certain threshold.
In the form, if I input 1.5E9 it works fine, and the value gets saved as 1500000000.00000000 (Here's an online scientific notation calculator).
However if I input 1.5E10 it says:
Ensure that there are no more than 8 decimal places.
Which is wrong, because I'm not adding any decimal places. In fact, if I enter 1.5E10 in normal notation, even with the 8 decimal places added, i.e. 15000000000.00000000 it works fine.
So I think something is not working correctly under the hood...
EDIT
I tested the field in the console, and it errors there:
from django.forms import DecimalField
>>> f = DecimalField(max_digits=30, decimal_places=8)
>>> f.clean('1.5E9')
Decimal('1.5E+9')
>>> f.clean('1.5E10')
Traceback (most recent call last):
File "myproject/env/lib/python3.5/site-packages/django/core/management/commands/shell.py", line 69, in handle
self.run_shell(shell=options['interface'])
File "myproject/env/lib/python3.5/site-packages/django/core/management/commands/shell.py", line 61, in run_shell
raise ImportError
ImportError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "myproject/env/lib/python3.5/site-packages/django/forms/fields.py", line 168, in clean
self.run_validators(value)
File "myproject/env/lib/python3.5/site-packages/django/forms/fields.py", line 157, in run_validators
raise ValidationError(errors)
django.core.exceptions.ValidationError: ['Ensure that there are no more than 8 decimal places.']
It does seem to be bug in DecimalValidator with the following explanation
Number that you stated 1.5E10 is parsed as object with properties _int '15' and _exp 9
In DecimalValidator __call__ method number of decimals is calculated as
decimals = abs(exponent)
which than furthermore triggers the following
if self.decimal_places is not None and decimals > self.decimal_places:
raise ValidationError(
self.messages['max_decimal_places'],
code='max_decimal_places',
params={'max': self.decimal_places},
)
Seems that fix for following would be something like
if exponent < 0:
decimal = abs(exponent)
else:
decimal = 0
Fix for version 2.0 looks like following
# If the absolute value of the negative exponent is larger than the
# number of digits, then it's the same as the number of digits,
# because it'll consume all of the digits in digit_tuple and then
# add abs(exponent) - len(digit_tuple) leading zeros after the
# decimal point.
if abs(exponent) > len(digit_tuple):
digits = decimals = abs(exponent)
else:
digits = len(digit_tuple)
decimals = abs(exponent)
This is a known bug which is fixed, but only in django 2.0 as far as I can tell.

Reading a single number from another file using python

I am reading a number from a file p2.txt. This file contrains only 1 number which is an integer lets say 10.
test_file = open('p2.txt', 'r')
test_lines = test_file.readlines()
test_file.close()
ferNum= test_lines[0]
print int(ferNum)
when however, I am getting an error
print int(ferNum)
ValueError: invalid literal for int() with base 10: '1.100000000000000000e+01\n'
I can see that it is considering it just as a line. How can I parse that number to a variable? any suggestions? regards
The problem is that even though the value of the number is an integer (11) it is represented in scientific notation so you'd have to read it as a float first.
>>> float('1.100000000000000000e+01\n')
11.0
>>> int('1.100000000000000000e+01\n')
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
int('1.100000000000000000e+01\n')
ValueError: invalid literal for int() with base 10: '1.100000000000000000e+01\n'
You can of course convert first to a float then to an int after that.
>>> int(float('1.100000000000000000e+01\n'))
11

How to read the string and long features in tensorflow

The tensorflow, I can't read string,long, only short float allowed? Why?
import tensorflow as tf
import numpy as np
# Data sets
IRIS_TRAINING = "seRelFeatures.csv"
IRIS_TEST = "seRelFeatures.csv"
# Load datasets.
training_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TRAINING, target_dtype=np.int)
test_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TEST, target_dtype=np.int)
here is the error
/home/xuejiao/anaconda2/bin/python /home/xuejiao/Desktop/HDSO_DirectAnswer/training_testing/dnn_semiSuper.py
Traceback (most recent call last):
File "/home/xuejiao/Desktop/HDSO_DirectAnswer/training_testing/dnn_semiSuper.py", line 9, in <module>
training_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TRAINING, target_dtype=np.int)
File "/home/xuejiao/anaconda2/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/datasets/base.py", line 47, in load_csv
target[i] = np.asarray(ir.pop(target_column), dtype=target_dtype)
File "/home/xuejiao/anaconda2/lib/python2.7/site-packages/numpy/core/numeric.py", line 482, in asarray
return array(a, dtype, copy=False, order=order)
ValueError: invalid literal for long() with base 10: ''
Process finished with exit code 1
Your error is ValueError: invalid literal for long() with base 10: ''. It simply that you are entering empty string instead of an integer (or string presentation of an integer). I'd check data in CSV files.
Actually I solved this problem by myself, this mistake mean
ValueError: invalid literal for long() with base 10: ''
I have some empty cell, but actually I don't have on the view.
After I check it, it cased by I delete the last column but I just delete the content didn't delete the cells, so from view can't find any empty

Error with "unsupported operand type" when converting feet to inches

I am working on a homework problem, and got the following error:
Traceback (most recent call last):
File "/Users//Dropbox/Homework 3 - 2.py", line 15, in <module>
conversion = convert_feet_to_inches(get_feet)
File "/Users//Dropbox/Homework 3 - 2.py", line 4, in convert_feet_to_inches
calculate_conversion = feet*12 TypeError:
unsupported operand type(s) for *: 'function' and 'int'
Here is my code. I'm trying to convert feet to inches:
def convert_feet_to_inches(feet):
calculate_conversion = feet*12
return calculate_conversion
def get_feet():
ask_for_feet = float(input("Please enter number of feet for conversion "))
return ask_for_feet
def printing_answer():
print (convert_feet_to_inches)
asking_for_feet = get_feet()
conversion = convert_feet_to_inches(get_feet)
print_answer(printing_answer)
What am I doing wrong?
I think you meant to pass asking_for_feet to convert_feet_to_inches instead of the function get_feet in this line:
conversion = convert_feet_to_inches(get_feet)
So that should be:
conversion = convert_feet_to_inches(asking_for_feet)
The error was because get_feet() is a function and you passed it to convert_feet_to_inches() which is taking the argument you pass it and multiplying it by 12. You can't multiply a function by an int so that is what the error was saying. I think what you meant to do was to pass asking_for_feet. So change
conversion = convert_feet_to_inches(get_feet)
to
conversion = convert_feet_to_inches(asking_for_feet)
After that, you have
print_answer(printing_answer)
The function print_answer was not defined yet so change:
def printing_answer():
print (convert_feet_to_inches)
to
def print_answer(answer):
print (answer)
Then you final line of code would be:
print_answer(conversion)

Trouble with for loops

We just learned for loops in class for about five minutes and we were already given a lab. I am trying but still not getting what I need to get. What I am trying to do is take a list of integers, and then only take the odd integers and add them up and then return them so if the list of integers was [3,2,4,7,2,4,1,3,2] the returned value would be 14
def f(ls):
ct=0
for x in (f(ls)):
if x%2==1:
ct+=x
return(ct)
print(f[2,5,4,6,7,8,2])
the error code reads
Traceback (most recent call last):
File "C:/Users/Ian/Documents/Python/Labs/lab8.py", line 10, in <module>
print(f[2,5,4,6,7,8,2])
TypeError: 'function' object is not subscriptable
Just a couple of minor mistakes:
def f(ls):
ct = 0
for x in ls:
# ^ Do not call the method, but just parse through the list
if x % 2 == 1:
ct += x
return(ct)
# ^ ^ parenthesis are not necessary
print(f([2,5,4,6,7,8,2]))
# ^ ^ Missing paranthesis
You're missing the parenthesis in the function call
print(f([2,5,4,6,7,8,2]))
rather than
print(f[2,5,4,6,7,8,2])

Categories

Resources