Category Archives: Python

The solution of typeerror: expected string or buffer

Error type: TypeError: expected string or buffer

Specific error explanation: This is because the returned variable is not a character type, which causes this error

The specific solution: add an if statement before the specific program segment to determine whether the program returns in a legal format, and if it is, continue to run the program.

 

How to Solve TypeError: object() takes no parameters

The following errors were found when running the test case

Ran 1 test in 22.505s

FAILED (errors=1)

Error
Traceback (most recent call last):
  File "D:\Program\python34\lib\unittest\case.py", line 58, in testPartExecutor
    yield
  File "D:\Program\python34\lib\unittest\case.py", line 580, in run
    testMethod()
  File "D:\python_workshop\appium_framework\TestCases\test_login.py", line 37, in test_login_success
    LoginPage(self.driver).input_phoneNumber("1868XXXX553")
TypeError: object() takes no parameters

Really drunk: def__ init__ Wrong function

Just change it

python 3.6 socket tcp Connect TypeError: a bytes-like object is required, not ‘str’

About socket TCP communication code in Python core programming:

Client:

# !/usr/bin/env python

from socket import *

HOST = '*******'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)

tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)

while True:
    data = input('> ')
    if not data:
        break
    tcpCliSock.send(data)
    data = tcpCliSock.recv(BUFSIZE)
    if not data:
        break
    print(data.decode('utf-8'))

tcpCliSock.close()

Server:

# !/usr/bin/env python

from socket import *
from time import ctime

HOST = ''
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)

tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)

while True:
    print("waiting for connection...")
    tcpCliSock, addr = tcpSerSock.accept()
    print("...connected from: ", addr)

    while True:
        data = tcpCliSock.recv(BUFSIZE)
        if not data:
            break
        print(type(data))
        tcpCliSock.send("[%s] %s" %(ctime(), data))

    tcpCliSock.close()

tcpSerSock.close()

Running in python 3.6 environment reports an error.

Traceback (most recent call last):
File “.\tsTclnt3.py”, line 17, in <module>
tcpCliSock.send(data)
TypeError: a bytes-like object is required, not ‘str’

So change the client code as follows.

—>tcpCliSock.send(data.encode())

Running error reported.

Printed data data type is <class ‘bytes’>, so was curious why this error was reported. Looking up the information online I saw this passage.

In python 3, bytes strings and unicodestrings are now two different types. Since sockets are not aware of string encodings, they are using raw bytes strings, that have a slightly differentinterface from unicode strings.

So, now, whenever you have a unicode stringthat you need to use as a byte string, you need toencode() it. And whenyou have a byte string, you need to decode it to use it as a regular(python 2.x) string.

Unicode strings are quotes enclosedstrings. Bytes strings are b”” enclosed strings

When you use client_socket.send(data),replace it by client_socket.send(data.encode()). When you get datausing data = client_socket.recv(512), replace it by data =client_socket.recv(512).decode()

The code was then modified as follows.

—>

That’s how you get through.

Finally, the ultimate code.

Server side.

# !/usr/bin/env python

from socket import *
from time import ctime

HOST = ''
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)

tcpSerSock = socket(AF_INET, SOCK_STREAM) #Create a socket
tcpSerSock.bind(ADDR) #Bind the socket to the address
tcpSerSock.listen(5) #Listen (set maximum number of listeners)

while True:
    print("waiting for connection...")
    tcpCliSock, addr = tcpSerSock.accept()
    print("...connected from: ", addr)

    while True:
        data = tcpCliSock.recv(BUFSIZE).decode()
        if not data:
            break
        tcpCliSock.send(("[%s] %s" %(ctime(), data)).encode())

    tcpCliSock.close()

tcpSerSock.close()

Client:

# !/usr/bin/env python

from socket import *

HOST = '*********'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)

tcpCliSock = socket(AF_INET, SOCK_STREAM) #Create a socket
tcpCliSock.connect(ADDR) # Request to establish a connection

while True:
    data = input('> ')
    if not data:
        break
    tcpCliSock.send(data.encode())
    data = tcpCliSock.recv(BUFSIZE)
    if not data:
        break
    print(data.decode())

tcpCliSock.close()

Python TypeError: can only concatenate str (not “int”) to str

 code

def gcd(x, y):
    (x, y) = (y, x) if x > y else (x, y)
    for factor in range(x, 0, -1):
        if x % factor == 0 and y % factor == 0:
            return factor


if __name__ == '__main__':
    num1 = int(input("Please enter a positive integer: "))
    num2 = int(input("Please enter a positive integer. "))
    print("i" + gcd(num1, num2))

code error

PS G:\vscode_worksapce\vscode_python_workspace> python -u "g:\vscode_worksapce\vscode_python_workspace\test1.py"      
Please enter a positive integer: 3
Please enter a positive integer: 9
Traceback (most recent call last):
  File "g:\vscode_worksapce\vscode_python_workspace\test1.py", line 11, in <module>
    print("i" + gcd(num1, num2))
TypeError: can only concatenate str (not "int") to str

causes and solutions

reference the blog https://blog.csdn.net/feng2147685/article/details/86494905, and https://www.cnblogs.com/Jimc/p/9606112.html

is a Python string concatenation problem;

if __name__ == '__main__':
    num1 = int(input("Please enter a positive integer: "))
    num2 = int(input("Please enter a positive integer. "))
    print("i%d" % (gcd(num1, num2)) + "hahahha")

HMM…

Python Error:Exception Value:can only concatenate str (not “bytes”) to str

error source code:

#Receive request data
def search(request):
    request.encoding = 'utf-8'
    if 'q' in request.GET:
        message = 'You searched for: ' +request.GET['q'].encode('utf-8')
    else:
        message = 'You submitted an empty form'
    return HttpResponse(message)

code marked red position, we can see that encode function is used to transcode, because encode transcode returns data of type Bytes, can not be directly added with data of type STR.

Since the request request has been transcoded in the first sentence of the function, we remove the following encode function here, and the error can be solved.

The updated code is:

#Receive request data
def search(request):
    request.encoding = 'utf-8'
    if 'q' in request.GET:
        message = 'You searched for: ' +request.GET['q']
    else:
        message = 'You submitted an empty form'
    return HttpResponse(message)

Solve the problem of “typeerror: ‘bool’ object is not callable” in flash and Django

> Welcome to Flask’s large tutorial project! When it comes time to refactor the user model, run the script and it says :

TypeError: ‘bool’ object is not callable

This is the user model:

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True) nickname = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(120), index=True, unique=True) posts = db.relationship('Post', backref='author', lazy='dynamic')  @property def is_authenticated(self): return True  @property def is_active(self): return True  @property def is_anonymous(self): return False def get_id(self): try: return unicode(self.id) # python 2 except NameError: return str(self.id) # python 3 def __repr__(self): return '<User %r>' % (self.nickname) 

This is the code at the time of the call:

from flask import render_template, flash, redirect, session, url_for, request, g
from flask.ext.login import login_user, logout_user, current_user, login_required
from app import app, db, lm, oid from .forms import LoginForm from .models import User @app.route('/login', methods=['GET', 'POST']) @oid.loginhandler def login(): if g.user is not None and g.user.is_authenticated(): # error return redirect(url_for('index')) form = LoginForm() if form.validate_on_submit(): session['remember_me'] = form.remember_me.data return oid.try_login(form.openid.data, ask_for=['nickname', 'email']) return render_template('login.html', title='Sign In', form=form, providers=app.config['OPENID_PROVIDERS']) 

is_authenticated is a property, not a method, as described in Resources, so just remove the parentheses. There are two typos in this section of the book. Please refer to the Git source code.

put the wrong place:
if g.user is not None and g.user.is_authenticated():
if g.user is not None and G.user. is_authenticated:
and then no error.

Python TypeError: softmax() got an unexpected keyword argument ‘axis’

There are several solutions to this problem. You can lower the version of keras, for example:

pip install keras==2.1

However, there is a more convenient way. From the error, we can see that softmax does not contain the axis parameter, so we can replace the axis parameter with dim. The source code is as follows:

def softmax(x, axis=-1):
    """Softmax of a tensor.

    # Arguments
        x: A tensor or variable.
        axis: The dimension softmax would be performed on.
            The default is -1 which indicates the last dimension.

    # Returns
        A tensor.
    """
    return tf.nn.softmax(x, axis=axis)

Change to this:

def softmax(x, axis=-1):
    """Softmax of a tensor.

    # Arguments
        x: A tensor or variable.
        axis: The dimension softmax would be performed on.
            The default is -1 which indicates the last dimension.

    # Returns
        A tensor.
    """
    return tf.nn.softmax(x, dim=axis)

That’s to change the last line

[Solved] Python TypeError: sequence item 0: expected str instance, int found

TypeError: sequence item 0: expected str instance, int found

code

list1=[1,'two','three',4]
print(' '.join(list1))

I thought I would print 1 two three 4

It turned out to be a mistake

Traceback (most recent call last):
 File "<pyshell#27>", line 1, in <module>
  print(" ".join(list1))
TypeError: sequence item 0: expected str instance, int found

I checked the information on the Internet and said that the list contains numbers and cannot be directly converted into a string

Solution:

print(" ".join('%s' %id for id in list1))

That is to traverse the elements of the list and convert it into a string. In this way, we can successfully output the result of 1 two three 4

from: https://blog.csdn.net/laochu250/article/details/67649210

Python TypeError: only size-1 arrays can be converted to Python scalars

Traceback (most recent call last):
File “/Users/mac126/111/mayplotlib/mayplotlib.py”, line 50, in <module>
plt.text(x,y ,’%.2f’%y ,ha=’center’,va=’bottom’)
TypeError: only size-1 arrays can be converted to Python scalars

code
import matplotlib.pyplot as plt
import numpy as np
k=10
x=np.arange(k)
y=np.random.rand(k)
plt.bar(x,y)

for x in zip(x,y):
    plt.text(x,y ,'%.2f'%y ,ha='center',va='bottom')
plt.show()

It’s found that one parameter Y is missing and it’s OK to add it

only size-1 arrays can be converted to Python scalars

Python version: 3.6.5

Opencv version: 3.2.0

Jupyter notebook used

The source code is as follows:

import cv2
import numpy as np
import matplotlib.pyplot as plt


%matplotlib inline

# Feature set containing (x,y) values of 25 known/training data
trainData = np.random.randint(0,100,(25,2)).astype(np.float32)

# Labels each one either Red or Blue with numbers 0 and 1
responses = np.random.randint(0,2,(25,1)).astype(np.float32)

# Take Red families and plot them
red = trainData[responses.ravel()==0]
plt.scatter(red[:,0],red[:,1],80,'r','^')

# Take Blue families and plot them
blue = trainData[responses.ravel()==1]
plt.scatter(blue[:,0],blue[:,1],80,'b','s')

# plt.show()

newcomer = np.random.randint(0,100,(1,2)).astype(np.float32)
plt.scatter(newcomer[:,0],newcomer[:,1],80,'g','o')

knn = cv2.ml.KNearest_create()

knn.train(trainData,responses)
ret, results, neighbours ,dist = knn.findNearest(newcomer, 3)


print ("result: ", results,"\n")
print ("neighbours: ", neighbours,"\n")
print ("distance: ", dist)

plt.show()

The error is as follows:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-21-b1c5cdca5e57> in <module>()
     20 knn = cv2.ml.KNearest_create()
     21 
---> 22 knn.train(trainData,responses)
     23 ret, results, neighbours ,dist = knn.findNearest(newcomer, 3)
     24 

TypeError: only size-1 arrays can be converted to Python scalars

Error reason:

Wrong parameter passed

The second parameter in the train function should be the layout of the array

Cv2.ml.row should be filled in according to the form of the passed in array_ Sample or cv2.ml.col_ SAMPLE

For example, mine is

knn.train(trainData,cv2.ml.ROW_SAMPLE,responses)

https://stackoverflow.com/questions/33975695/type-error-only-length-1-arrays-can-be-converted-to-python-scalars