Decryption function: 'int' object is not callable - python

I've written code for a function that executes decryption of individual characters. I received this error message: 'int' object is not callable, but I don't know which object this is referring to and how exactly I'm illegally calling something. What did I do wrong? Thanks.
def affine_cipher_decryption(ch,N,alphabet):
M = len(alphabet)
A = get_smallest_co_prime(M)
A_inverse = multiplicative_inverse(A,M)
counter = -1
for element in alphabet:
if element == ch:
counter += 1
index = counter
break
else:
counter += 1
cipher_index = A_inverse(index-N) % M
cipher_ch = alphabet[cipher_index]
return cipher_ch
Here is the error traceback message:
Traceback (most recent call last):
File "", line 1, in
runfile('/Users/brandononeil/Documents/SS18proj04.py', wdir='/Users/brandononeil/Documents')
File
"/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py",
line 880, in runfile
execfile(filename, namespace)
File
"/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py",
line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/Users/brandononeil/Documents/SS18proj04.py", line 161, in
main()
File "/Users/brandononeil/Documents/SS18proj04.py", line 148, in
main
decr_ch1 = affine_cipher_decryption(ch, rotation, ALPHA_NUM)
File "/Users/brandononeil/Documents/SS18proj04.py", line 101, in
affine_cipher_decryption
cipher_index = multiplicative_inverse(A,M)(index-N) % M
TypeError: 'int' object is not callable
Also, here are the contents of multiplicative_inverse:
def multiplicative_inverse(A,M):
for x in range(M):
if (A*x)%M == 1:
return x
I've already tried renaming A_inverse, and I've tried writing the contents of the multiplicative_inverse function inside of affine_cipher_decryption (so I wouldn't have to call multiplicative_inverse) to no avail.
Any ideas of what else could be wrong?

Your problem is these two lines:
A_inverse = multiplicative_inverse(A,M)
cipher_index = A_inverse(index-N) % M
A_inverse is set to the result of multiplicative_inverse which I'm assuming returns an int. The second line tries to call a function named A_inverse but the local variable shadows the function in the scope.
You can fix it by renaming either the local variable or the function.

Related

AttributeError: 'Vocab' object has no attribute 'stoi'

Trying to run a training script, after resolving a few error messages I've come accross this one, Anyone know what is happening here?
Batch size > 1 not implemented! Falling back to batch_size = 1 ...
Building multi-modal model...
Loading model parameters.
Traceback (most recent call last):
File "translate_mm.py", line 166, in <module>
main()
File "translate_mm.py", line 98, in main
use_filter_pred=False)
File "/content/drive/My Drive/Thesis/thesis_code/onmt/io/IO.py", line 198, in build_dataset
use_filter_pred=use_filter_pred)
File "/content/drive/My Drive/Thesis/thesis_code/onmt/io/TextDataset.py", line 75, in __init__
out_examples = list(out_examples)
File "/content/drive/My Drive/Thesis/thesis_code/onmt/io/TextDataset.py", line 69, in <genexpr>
out_examples = (self._construct_example_fromlist(
File "/content/drive/My Drive/Thesis/thesis_code/onmt/io/TextDataset.py", line 68, in <genexpr>
example_values = ([ex[k] for k in keys] for ex in examples_iter)
File "/content/drive/My Drive/Thesis/thesis_code/onmt/io/TextDataset.py", line 265, in _dynamic_dict
src_map = torch.LongTensor([src_vocab.stoi[w] for w in src])
File "/content/drive/My Drive/Thesis/thesis_code/onmt/io/TextDataset.py", line 265, in <listcomp>
src_map = torch.LongTensor([src_vocab.stoi[w] for w in src])
File "/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py", line 1178, in __getattr__
type(self).__name__, name))
AttributeError: 'Vocab' object has no attribute 'stoi'
which refers to
def _dynamic_dict(self, examples_iter):
for example in examples_iter:
src = example["src"]
src_vocab = torchtext.vocab.Vocab(Counter(src))
self.src_vocabs.append(src_vocab)
# Mapping source tokens to indices in the dynamic dict.
src_map = torch.LongTensor([src_vocab.stoi[w] for w in src])
example["src_map"] = src_map
if "tgt" in example:
tgt = example["tgt"]
mask = torch.LongTensor(
[0] + [src_vocab.stoi[w] for w in tgt] + [0])
example["alignment"] = mask
yield example
Note: the original model was made with a much older version of torchtext, I am guessing the error is related to that, but I am simply too inexperienced to know for sure.
Anyone has an idea? Googling this provided no significant results.
regards,
U.
You must use get_stoi()[w].This is for the newer version after removing the legacy. You also can use get_itos() which returns a list of elements.

Sentence Generation: TypeError: 'NoneType' object is not subscriptable

i have a code for generating sentences given a word after sentence_start
the code that encountered an error:
def generate_sentences(model, n, index_to_word, word_to_index):
for i in range(n):
sent = None
while not sent:
for i in range(len(arr)):
sent = generate_sentence(arr[i], model, index_to_word, word_to_index)
# print (arr[i])
print_sentence(sent, index_to_word)
print("\n")
here is the called function:
def generate_sentence(anot, model, index_to_word, word_to_index, min_length=5):
# We start the sentence with the start token
new_sentence = [word_to_index[SENTENCE_START_TOKEN], word_to_index[anot]]
# Repeat until we get an end token
while not new_sentence[-1] == word_to_index[SENTENCE_END_TOKEN]:
next_word_probs = model.predict(new_sentence)[-1]
samples = np.random.multinomial(1, next_word_probs)
sampled_word = np.argmax(samples)
new_sentence.append(sampled_word)
# Seomtimes we get stuck if the sentence becomes too long, e.g. "........" :(
# And: We don't want sentences with UNKNOWN_TOKEN's
if len(new_sentence) > 100 or sampled_word == word_to_index[UNKNOWN_TOKEN]:
return None
if len(new_sentence) < min_length:
return None
return new_sentence
def print_sentence(s, index_to_word):
sentence_str = [index_to_word[x] for x in s[1:-1]]
print(" ".join(sentence_str))
sys.stdout.flush()
and here is the traceback:
Traceback (most recent call last):
File "<ipython-input-10-b9a0a1f5bd04>", line 1, in <module>
runfile('C:/Users/cerdas/Documents/bil/Code_Latihan/rnn-tutorial-gru-lstm-master/train.py', wdir='C:/Users/cerdas/Documents/bil/Code_Latihan/rnn-tutorial-gru-lstm-master')
File "C:\Users\cerdas\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
execfile(filename, namespace)
File "C:\Users\cerdas\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/cerdas/Documents/bil/Code_Latihan/rnn-tutorial-gru-lstm-master/train.py", line 53, in <module>
generate_sentences(model, 20, index_to_word, word_to_index)
File "C:\Users\cerdas\Documents\bil\Code_Latihan\rnn-tutorial-gru-lstm-master\utils.py", line 190, in generate_sentences
print_sentence(sent, index_to_word)
File "C:\Users\cerdas\Documents\bil\Code_Latihan\rnn-tutorial-gru-lstm-master\utils.py", line 179, in print_sentence
sentence_str = [index_to_word[x] for x in s[1:-1]]
TypeError: 'NoneType' object is not subscriptable
i suspect the error caused by the function print_sentence(sent, index_to_word)
i was trying to edit the indentation for exclude the print_sentence function from looping.
but the output only read the last element of array arr
What the error message
TypeError: 'NoneType' object is not subscriptable
means, is that your line
sentence_str = [index_to_word[x] for x in s[1:-1]]
is trying to access index_to_word[x] and s[1:-1] though one of them appear to be None
Seeing that you didn't provide the information what generate_sentences is being called with, we can only speculate what causes this.
I would recommend you add an if clause, to make sure you don't try to print a sentence, which is None:
print_sentence(sent, index_to_word)
should be replaced with
if sent is not None:
print_sentence(sent, index_to_word)

Having a difficult time resolving "TypeError: 'list' object is not callable" issue

Error:
Traceback (most recent call last): File
"/root/PycharmProjects/Capstone2/main", line 207, in
for paramIndex in range(0, 4): TypeError: 'list' object is not callable
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File
"/root/PycharmProjects/Capstone2/main", line 249, in
print('stream ending') File "/usr/lib/python3/dist-packages/picamera/camera.py", line 758, in
exit
self.close() File "/usr/lib/python3/dist-packages/picamera/camera.py", line 737, in
close
self.stop_recording(splitter_port=port) File "/usr/lib/python3/dist-packages/picamera/camera.py", line 1198, in
stop_recording
encoder.close() File "/usr/lib/python3/dist-packages/picamera/encoders.py", line 431, in
close
self.stop() File "/usr/lib/python3/dist-packages/picamera/encoders.py", line 815, in
stop
super(PiVideoEncoder, self).stop() File "/usr/lib/python3/dist-packages/picamera/encoders.py", line 419, in
stop
self._close_output() File "/usr/lib/python3/dist-packages/picamera/encoders.py", line 349, in
_close_output
mo.close_stream(output, opened) File "/usr/lib/python3/dist-packages/picamera/mmalobj.py", line 371, in
close_stream
stream.flush() ValueError: flush of closed file
Relevant Code:
angle = []
distance = []
speed = []
current = []
timestamp = []
parameterList = []
parameterList.extend((angle, distance, speed, current, timestamp))
for paramIndex in range(0, 4): # LINE 207
# Select Range
range = getRange(index, paramIndex + 5)
cell_list = sheet.range(range[0], range[1], range[2], range[3])
cellIndex = 0
for cell in cell_list:
try:
cell.value = parameterList[paramIndex][cellIndex]
except:
print("PI: " + str(paramIndex))
print("CI: " + str(cellIndex))
print("PL LEN: " + str(len(parameterList)))
print("P LEN: " + str(len(parameterList[paramIndex])))
My Thoughts:
The error makes me think that paramIndex is a list and not an integer but the code executes fine for the first four iterations. This makes me think that there is something wrong with my last list (timestamp). The only thing that I can imagine being wrong with my last list is some sort of index out of bounds issue but...
The except block is never hit
The largest value cellIndex reaches is 30 (expected)
The length of parameterList is 5 (expected)
The length of timestamp is 31 (expected)
I am stumped. If anyone can offer some help that would be greatly appreciated.
paramIndex is fine but you need to avoid calling variables the same name as your functions. In this case, range() is a standard python function but you create a variable called 'range'. Thereafter if you tried to use the range function you'd get an 'object is not callable' error because it's trying to use your range object as the standard range function.
If you insist on wanting to keep the range object name then use xrange() instead of range() where you define your for loop and you shouldn't get any conflicts.

Usage of python-readability

(https://github.com/buriy/python-readability)
I am struggling using this library and I can't find any documentation for it. (Is there any?)
There are some kind of useable pieces calling help(Document) but there is still something wrong.
My code so far:
from readability.readability import Document
import requests
url = 'http://www.somepage.com'
html = requests.get(url, verify=False).content
readable_article = Document(html, negative_keywords='test_keyword').summary()
with open('test.html', 'w', encoding='utf-8') as test_file:
test_file.write(readable_article)
According to the help(Document) output, it should be possible to use a list for the input of the negative_keywords.
readable_article = Document(html, negative_keywords=['test_keyword1', 'test-keyword2').summary()
Gives me a bunch of errors I don't understand:
Traceback (most recent call last): File
"/usr/lib/python3.4/site-packages/readability/readability.py", line
163, in summary
candidates = self.score_paragraphs() File "/usr/lib/python3.4/site-packages/readability/readability.py", line
300, in score_paragraphs
candidates[parent_node] = self.score_node(parent_node) File "/usr/lib/python3.4/site-packages/readability/readability.py", line
360, in score_node
content_score = self.class_weight(elem) File "/usr/lib/python3.4/site-packages/readability/readability.py", line
348, in class_weight
if self.negative_keywords and self.negative_keywords.search(feature): AttributeError: 'list' object
has no attribute 'search' Traceback (most recent call last): File
"/usr/lib/python3.4/site-packages/readability/readability.py", line
163, in summary
candidates = self.score_paragraphs() File "/usr/lib/python3.4/site-packages/readability/readability.py", line
300, in score_paragraphs
candidates[parent_node] = self.score_node(parent_node) File "/usr/lib/python3.4/site-packages/readability/readability.py", line
360, in score_node
content_score = self.class_weight(elem) File "/usr/lib/python3.4/site-packages/readability/readability.py", line
348, in class_weight
if self.negative_keywords and self.negative_keywords.search(feature): AttributeError: 'list' object
has no attribute 'search'
Could some one give me please a hint on the error or how to deal with it?
There's an error in the library code. If you look at compile_pattern:
def compile_pattern(elements):
if not elements:
return None
elif isinstance(elements, (list, tuple)):
return list(elements)
elif isinstance(elements, regexp_type):
return elements
else:
# assume string or string like object
elements = elements.split(',')
return re.compile(u'|'.join([re.escape(x.lower()) for x in elements]), re.U)
You can see that it only returns a regex if the elements is not None, not a list or tuple, and not a regular expression.
Later on, though, it assumes that self.negative_keywords is a regular expression. So, I suggest you input your list as a string in the form of "test_keyword1,test_keyword2". This will make sure that compile_pattern returns a regular expression which should fix the error.

Python TypeErrors: "' list' object is not callable" and "'function' object is unsubscriptable"

I have the following code:
from random import randint,choice
add=lambda x:lambda y:x+y
sub=lambda x:lambda y:x-y
mul=lambda x:lambda y:x*y
ops=[[add,'+'],[sub,'-'],[mul,'*']]
def gen_expression(length,left,right):
expr=[]
for i in range(length):
op=choice(ops)
expr.append([op[0](randint(left,right)),op[1]])
return expr
def eval_expression (expr,x):
for i in expr:
x=i[0](x)
return x
def eval_expression2 (expr,x):
for i in expr:
x=i(x)
return x
[snip , see end of post]
def genetic_arithmetic(get,start,length,left,right):
batch=[]
found = False
for i in range(30):
batch.append(gen_expression(length,left,right))
while not found:
batch=sorted(batch,key=lambda y:abs(eval_expression(y,start)-get))
print evald_expression_tostring(batch[0],start)+"\n\n"
#combine
for w in range(len(batch)):
rind=choice(range(length))
batch.append(batch[w][:rind]+choice(batch)[rind:])
#mutate
for w in range(len(batch)):
rind=choice(range(length))
op=choice(ops)
batch.append(batch[w][:rind]+[op[0](randint(left,right)),op[1]]+batch[w][rind+1:])
found=(eval_expression(batch[0],start)==get)
print "\n\n"+evald_expression_tostring(batch[0],start)
When I try to call to call genetic_artihmetic with eval_expression as the sorting key, I get this:
Traceback (most recent call last):
File "<pyshell#113>", line 1, in <module>
genetic_arithmetic(0,10,10,-10,10)
File "/home/benikis/graming/py/genetic_number.py", line 50, in genetic_arithmetic
batch=sorted(batch,key=lambda y:abs(eval_expression(y,start)-get))
File "/home/benikis/graming/py/genetic_number.py", line 50, in <lambda>
batch=sorted(batch,key=lambda y:abs(eval_expression(y,start)-get))
File "/home/benikis/graming/py/genetic_number.py", line 20, in eval_expression
x=i[0](x)
TypeError: 'function' object is unsubscriptable
And when I try the same with eval_expression2 as the sorting,the error is this:
Traceback (most recent call last):
File "<pyshell#114>", line 1, in <module>
genetic_arithmetic(0,10,10,-10,10)
File "/home/benikis/graming/py/genetic_number.py", line 50, in genetic_arithmetic
batch=sorted(batch,key=lambda y:abs(eval_expression2(y,start)-get))
File "/home/benikis/graming/py/genetic_number.py", line 50, in <lambda>
batch=sorted(batch,key=lambda y:abs(eval_expression2(y,start)-get))
File "/home/benikis/graming/py/genetic_number.py", line 25, in eval_expression2
x=i(x)
TypeError: 'list' object is not callable
As far as i can wrap my head around this, my guess is that sorted() is trying to recursively sort the sublists,maybe? What is really going on here?
Python version is 2.6 - the one in the debian stable repos.
[snip] here:
def expression_tostring(expr):
expr_str=len(expr)*'('+'x '
for i in expr :
if i[1]=='*':
n=i[0](1)
else:
n=i[0](0)
expr_str+=i[1]+' '+str(n)+') '
return expr_str
def evald_expression_tostring(expr,x):
exprstr=expression_tostring(expr).replace('x',str(x))
return exprstr+ ' = ' + str(eval_expression(expr,x))
x=i[0](x) #here i is a function so you can't perform indexing operation on it
x=i(x) #here i is a list so you can't call it as a function
in both cases the value of i is fetched from expr, may be expr contains different type of object than what you're assuming here.
Try this modification:
def gen_expression(length,left,right):
expr=[]
for i in range(length):
op=choice(ops)
expr.append([op[0], randint(left,right),op[1]])
return expr
def eval_expression (expr,x):
for i in expr:
x=i[0](i[1])
return x
You had expr.append([op[0](randint(left,right)),op[1]]) which will put the return value of the calling the function into the 0th index.

Categories

Resources