First, this is my code:
import re
clientaddress = ('192.168.10.111', 43567)
x = re.search("\d+.\d+.\d+.\d+\$", clientaddress)
print (x)
if x:
print("YES! We have a match!")
else:
print("No match")
Here is the problem. the 'ClientAddress' is imported from another server and its format is like this:
('IP', port)
So we have an (str, int).
the error is :
Traceback (most recent call last):
File "./prog.py", line 6, in <module>
File "/usr/lib/python3.7/re.py", line 183, in search
return _compile(pattern, flags).search(string)
TypeError: expected string or bytes-like object
After that, if I use this code:
import re
clientaddress = str('192.168.31.111', 43567)
clientaddress = ('192.168.31.111', 43567)
x = re.search("\d+.\d+.\d+.\d+\$", clientaddress)
print (x)
if x:
print("YES! We have a match!")
else:
print("No match")
The error that appeared is :
Traceback (most recent call last):
File "./prog.py", line 4, in <module>
TypeError: str() argument 2 must be str, not int
clientAddress is a tuple containing a string as the first element.
so index the tuple first and do the checking then. (clientaddress[0])
clientaddress = ('192.168.10.111', 43567)
x = re.search("\d+.\d+.\d+.\d+$", clientaddress[0])
print(x)
Related
def get_playlist_tracks(username, playlist_id):
results = sp.user_playlist_tracks(username,playlist_id)
playlist_items = results['items']
uris = []
while results['next']:
results = sp.next(results)
playlist_items.append(results['items'])
for item in playlist_items:
track_uri = item["track"]["uri"]
uris.append(track_uri)
return uris
get_playlist_tracks('iKetu', '7h10RuUjKqfqwWibESmwy1')
print(uris)
The Output I get is
PS C:\Users\iketu\Music\Elite\Album Artworks> & C:/Users/iketu/AppData/Local/Programs/Python/Python38/python.exe "c:/Users/iketu/Music/Elite/Album Artworks/getAlbumArt.py"
Traceback (most recent call last):
File "c:/Users/iketu/Music/Elite/Album Artworks/getAlbumArt.py", line 27, in <module>
get_playlist_tracks('iKetu', '7h10RuUjKqfqwWibESmwy1')
File "c:/Users/iketu/Music/Elite/Album Artworks/getAlbumArt.py", line 23, in get_playlist_tracks
track_uri = item["track"]["uri"]
TypeError: list indices must be integers or slices, not str
I have
import nltk
from nltk.stem.snowball import GermanStemmer
def my_tokenizer(doc):
stemmer= GermanStemmer()
return([stemmer.stem(t.lower()) for t in nltk.word_tokenize(doc) if
t.lower() not in my_stop_words])
text="hallo df sdfd"
singleTFIDF = TfidfVectorizer(analyzer='char_wb', ngram_range=
(4,6),preprocessor=my_tokenizer, max_features=50).fit([str(text)])
From docs it is clear that a custom toenizer only applies for analyzer=word.
I get
Traceback (most recent call last):
File "TfidF.py", line 95, in <module>
singleTFIDF = TfidfVectorizer(analyzer='char_wb', ngram_range=(4,6),preprocessor=my_tokenizer, max_features=50).fit([str(text)])
File "C:\Users\chris1\Anaconda3\envs\master\lib\site-packages\sklearn\feature_extraction\text.py", line 185, in _char_wb_ngrams
text_document = self._white_spaces.sub(" ", text_document)
TypeError: expected string or bytes-like object
you have to join the words and then return a single string.
Try this!
return(' '.join ([stemmer.stem(t.lower()) for t in nltk.word_tokenize(doc) if
t.lower() not in my_stop_words]))
I am trying to calculate IRR and its giving me result in command line but whenever I am trying to pass the values as a parameter its failing with below error
Code
import numpy
import sys
def irrYearly(array):
array = [array]
irr = round(numpy.irr(array), 2)*100
return irr
def irrCal(tenure, array):
if tenure == "Yearly":
# return irrYearly(array)
# array = [-30000, -30000, -30000, -30000, -30000, 107180] -- if I uncomment this line its works fine
print(irrYearly(array))
elif tenure == "Monthly":
# return irrMonthly(array)
print(irrMonthly(array))
def main():
if len(sys.argv) == 3:
tenure = sys.argv[1]
array = sys.argv[2]
irrCal(tenure, array)
main()
Error
Please find the error
C:\Python27\python.exe C:/Users/abhis/PycharmProjects/IRR/irr.py Yearly -30000.00,-30000.00,-30000.00,-30000.00,-30000.00,107180.00
Traceback (most recent call last):
File "C:/Users/abhis/PycharmProjects/IRR/irr.py", line 74, in <module>
['-30000.00,-30000.00,-30000.00,-30000.00,-30000.00,107180.00']
main()
File "C:/Users/abhis/PycharmProjects/IRR/irr.py", line 64, in main
irrCal(tenure, array)
File "C:/Users/abhis/PycharmProjects/IRR/irr.py", line 49, in irrCal
print(irrYearly(array))
File "C:/Users/abhis/PycharmProjects/IRR/irr.py"", line 19, in irrYearly
irr = round(numpy.irr(array), 2)*100
File "C:\Python27\lib\site-packages\numpy\lib\financial.py", line 669, in irr
res = np.roots(values[::-1])
File "C:\Python27\lib\site-packages\numpy\lib\polynomial.py", line 222, in roots
p = p.astype(float)
ValueError: invalid literal for float(): -30000.00,-30000.00,-30000.00,-30000.00,-30000.00,107180.00
argv[2] is a string with comma separated values, but to numpy it's a string not a list of floats. You first need to convert it like so:
float_vals = [float(x) for x in argv[2].split(",")].
Using the wifi package, here is what I did:
>>> cell = Cell.all('wlan0')[0]
>>> print cell
>>> scheme = Scheme.for_cell('wlan0', 'home', cell)
When I print cell it prints the ssid. When I run scheme = Scheme.for_cell('wlan0', 'home', cell). It gives the error
>>> scheme = Scheme.for_cell('wlan0', 'home', cell)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/aaeronn/virt_proj/wifi_hack/local/lib/python2.7/site-packages/wifi/scheme.py", line 110, in for_cell
return cls(interface, name, configuration(cell, passkey))
File "/home/aaeronn/virt_proj/wifi_hack/local/lib/python2.7/site-packages/wifi/scheme.py", line 23, in configuration
if len(passkey) != 64:
TypeError: object of type 'NoneType' has no len()
Whats wrong ? Where should I enter the password for that ssid?
The documentation for wifi.Scheme.for_cell says it takes a passkey argument:
classmethod for_cell(interface, name, cell, passkey=None)
So with some passkey, you would call
scheme = Scheme.for_cell('wlan0', 'home', cell, passkey)
Looking at the source code for that package, the TypeError raised there is a bug, or at least a sign of hasty design.
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.