shutil error: "Module 'shutil' has no 'copy' member" - visual-studio

I am still learning python but got stuck here:
from pathlib import Path
import os
import shutil
p = Path.home()
shutil.copy(p / 'G:\souce.txt', p / 'G:\dest.text')
The error is:
shutil: shutil
Anomalous backslash in string: '\s'. String constant might be missing an r prefix.pylint(anomalous-
backslash-in-string)
Anomalous backslash in string: '\d'. String constant might be missing an r prefix.pylint(anomalous-
backslash-in-string)
Module 'shutil' has no 'copy' memberpylint(no-member)
Not able to go for the next step. So any suggestions please.

You can just do:
import shutil
shutil.copy('G:\souce.txt', 'G:\dest.text')

Related

python-telegram-bot for (v20.x) TypeError: bad operand type for unary ~: 'type'

I am trying to build a telegram bot, I have just reproduce the code:
from telegram.ext import MessageHandler
from telegram.ext import filters
from telegram.ext import Application
from telegram import Update
from telegram.ext import ContextTypes
from decouple import config
def testFunc (update: Update, context: ContextTypes.DEFAULT_TYPE):
print('Hi')
def main():
BOT_TOKEN = config('TELE_BOT_API_KEY_2')
application = Application.builder().token(BOT_TOKEN).build()
application.add_handler(MessageHandler(filters.Text & ~filters.Command, testFunc))
application.run_polling()
if __name__ == '__main__':
main()
The error this code shows is:
Bot\AsyncAdvanceBot\test3.py", line 16, in main
application.add_handler(MessageHandler(filters.Text & ~filters.Command, testFunc))
TypeError: bad operand type for unary ~: 'type'
I am using python-telegram-bot api v20.x
I know this might be a naive problem that I might be missing.
Thanks!
I tried changing the code to different format but it doesn't work.
I got it! It was as I said naive error. I was not thinking straight😅
I have seen the document even earlier and was only focusing on making filters.Command to filters.COMMAND, but forgot to change filters.Text to filters.TEXT.
just replaced
filters.Text & ~filters.Command
with
filters.TEXT & ~filters.COMMAND

pylint not generating messages for C0326 whitepace violations

pylint is not producing the expected convention warning messages for whitespace non-conformances.
python 3.6.8
pylint 2.13.5
using this test script :
from __future__ import print_function
import os, sys
import logging
from .. import views
class DoSomething(SomeCommand) : # space before colon !
def __init__(self):
for i in range(1,11): # no space after comma !!
if self.number == i:
print("matched")
else:
print ('not matched') # space before paren !!!
def check_user(self):
if self.user: return True
else : return False # spaces before colon !
results from pylint check :
PS C:\Users\PycharmProjects\coding_standard\src> pylint test_script.py
************* Module test_script
test_script.py:18:0: C0304: Final newline missing (missing-final-newline)
test_script.py:1:0: C0114: Missing module docstring (missing-module-docstring)
test_script.py:3:0: C0410: Multiple imports on one line (os, sys) (multiple-imports)
test_script.py:5:0: E0402: Attempted relative import beyond top-level package (relative-beyond-top-level)
test_script.py:7:0: C0115: Missing class docstring (missing-class-docstring)
test_script.py:7:18: E0602: Undefined variable 'SomeCommand' (undefined-variable)
test_script.py:16:4: C0116: Missing function or method docstring (missing-function-docstring)
test_script.py:17:8: R1703: The if statement can be replaced with 'return bool(test)' (simplifiable-if-statement)
test_script.py:17:8: R1705: Unnecessary "else" after "return", remove the "else" and de-indent the code inside it (no-else-return)
test_script.py:17:22: C0321: More than one statement on a single line (multiple-statements)
test_script.py:7:0: R0903: Too few public methods (1/2) (too-few-public-methods)
test_script.py:3:0: W0611: Unused import os (unused-import)
test_script.py:3:0: W0611: Unused import sys (unused-import)
test_script.py:4:0: W0611: Unused import logging (unused-import)
test_script.py:5:0: W0611: Unused import views (unused-import)
Based on the docs I would expect to see C0326 messages for the commented lines.
I am using this as the reference for the conditions to be identified by C0326:
http://pylint-messages.wikidot.com/messages:c0326
Any suggestions to T/S this ?
Based on comment from #DylanLee ...
If I did it is truly by accident. I am not (knowingly) using any kind of config file to disable messages. Based on your comment, I ued the command line option:
$pylint --list-msgs-enabled
, which produces a list ...
Enabled messages:
...
multiple-statements (C0321)
superfluous-parens (C0325)
mixed-line-endings (C0327)
unexpected-line-ending-format (C0328)
wrong-spelling-in-comment (C0401)
...
Disabled messages:
raw-checker-failed (I0001)
bad-inline-option (I0010)
locally-disabled (I0011)
file-ignored (I0013)
suppressed-message (I0020)
useless-suppression (I0021)
deprecated-pragma (I0022)
use-symbolic-message-instead (I0023)
So, it is not obviously being disable, but is not included in the enabled list !
Maybe some updates to pylint that is suppressing that specific message ?
bad-whitespace has been removed from pylint in 2.6. You should use an autoformatter like black and pre-commit to handle this automatically.
See : https://pylint.pycqa.org/en/latest/whatsnew/2.6.html?highlight=bad-whitespace#other-changes
bad-continuation and bad-whitespace have been removed. black or another formatter can help you with this better than Pylint

Fiona Driver Error when downloading files via URL

This is simple to test if you get the error on your side:
import geopandas as gpd
gdf = gpd.read_file('https://hepgis.fhwa.dot.gov/fhwagis/AltFuels_Rounds1-5_2021-05-25.zip')
File "fiona/ogrext.pyx", line 540, in fiona.ogrext.Session.start
File "fiona/_shim.pyx", line 90, in fiona._shim.gdal_open_vector
fiona.errors.DriverError: '/vsimem/6101ab5f23764c15b5fe47aa52a049d6' not recognized as a supported file format.
Interestingly, I have received this error for other URLs recently and thought there was something wrong with the URL. But, now I suspect that something else is going on since it is happening with more than one URL. On the other hand, some URLs don't have this issue. One other interesting thing, this error only occurs sometimes. For instance, if I rerun that command it will work maybe 1 out of 20 times.
My Fiona version:
fiona 1.8.20 py39hea8b339_1 conda-forge
Any help would be much appreciated.
Investigating, the URL does not return a zip file. See code below, it actually returns a HTML input page...
import geopandas as gpd
import requests, io
from pathlib import Path
from zipfile import ZipFile, BadZipFile
import urllib
import fiona
url = "https://hepgis.fhwa.dot.gov/fhwagis/AltFuels_Rounds1-5_2021-05-25.zip"
try:
gdf = gpd.read_file(url)
except Exception:
f = Path.cwd().joinpath(urllib.parse.urlparse(url).path.split("/")[-1])
r = requests.get(url, stream=True, headers={"User-Agent": "XY"})
with open(f, "wb") as fd:
for chunk in r.iter_content(chunk_size=128):
fd.write(chunk)
try:
zfile = ZipFile(f)
zfile.extractall(f.stem)
except BadZipFile:
with open(f) as fh:
print(fh.read())

Pydotplus, Graphviz error: Program terminated with status: 1. stderr follows: 'C:\Users\En' is not recognized as an internal or external command

from pydotplus import graph_from_dot_data
from sklearn.tree import export_graphviz
from IPython.display import Image
dot_data = export_graphviz(tree,filled=True,rounded=True,class_names=['Setosa','Versicolor','Virginica'],feature_names=['petal length','petal width'],out_file=None)
graph = graph_from_dot_data(dot_data)
Image(graph.create_png())
Program terminated with status:
1. stderr follows: 'C:\Users\En' is not recognized as an internal or external command,
operable program or batch file.
it seems that it split my username into half.How do i overcome this?
I have a very similar example that I'm trying out, it's based on a ML how-to book which is working with a Taiwan Credit Card dataset predicting default risk. My setup is as follows:
from six import StringIO
from sklearn.tree import export_graphviz
from IPython.display import Image
import pydotplus
Then creating the decision tree plot is done in this way:
dot_data = StringIO()
export_graphviz(decision_tree=class_tree,
out_file=dot_data,
filled=True,
rounded=True,
feature_names = X_train.columns,
class_names = ['pay','default'],
special_characters=True)
graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
Image(graph.create_png())
I think it's all coming from the out_file=dot_data argument but cannot figure out where the file path is created and stored as print(dot_data.getvalue()) did not show any pathname.
In my research I came across sklearn.plot_tree() which seems to do everything that the graphviz does. So I took the above exporet_graphviz arguments and were matching arguments were in the .plot_tree method I added them.
I ended up with the following which created the same image as was found in the text:
from sklearn import tree
plt.figure(figsize=(20, 10))
tree.plot_tree(class_tree,
filled=True, rounded=True,
feature_names = X_train.columns,
class_names = ['pay','default'],
fontsize=12)
plt.show()

Python error: one of the arguments is required

I'm trying to run a code from github that uses Python to classify images but I'm getting an error.
here is the code:
import argparse as ap
import cv2
import imutils
import numpy as np
import os
from sklearn.svm import LinearSVC
from sklearn.externals import joblib
from scipy.cluster.vq import *
# Get the path of the testing set
parser = ap.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("-t", "--testingSet", help="Path to testing Set")
group.add_argument("-i", "--image", help="Path to image")
parser.add_argument('-v',"--visualize", action='store_true')
args = vars(parser.parse_args())
# Get the path of the testing image(s) and store them in a list
image_paths = []
if args["testingSet"]:
test_path = args["testingSet"]
try:
testing_names = os.listdir(test_path)
except OSError:
print "No such directory {}\nCheck if the file exists".format(test_path)
exit()
for testing_name in testing_names:
dir = os.path.join(test_path, testing_name)
class_path = imutils.imlist(dir)
image_paths+=class_path
else:
image_paths = [args["image"]]
and this is the error message I'm getting
usage: getClass.py [-h]
(- C:/Users/Lenovo/Downloads/iris/bag-of-words-master/dataset/test TESTINGSET | - C:/Users/Lenovo/Downloads/iris/bag-of-words-master/dataset/test/test_1.jpg IMAGE)
[- C:/Users/Lenovo/Downloads/iris/bag-of-words-master/dataset]
getClass.py: error: one of the arguments - C:/Users/Lenovo/Downloads/iris/bag-of-words-master/dataset/test/--testingSet - C:/Users/Lenovo/Downloads/iris/bag-of-words-master/dataset/test/test_1.jpg/--image is required
can you please help me with this? where and how should I write the file path?
This is an error your own program is issuing. The message is not about the file path but about the number of arguments. This line
group = parser.add_mutually_exclusive_group(required=True)
says that only one of your command-line arguments (-t, -i) is permitted. But it appears from the error message that you are supplying both --testingSet and --image on your command line.
Since you only have 3 arguments, I have to wonder if you really need argument groups at all.
To get your command line to work, drop the mutually-exclusive group and add the arguments to the parser directly.
parser.add_argument("-t", "--testingSet", help="Path to testing Set")
parser.add_argument("-i", "--image", help="Path to image")
parser.add_argument('-v',"--visualize", action='store_true')

Resources