Pytorch visdom: can`t start visdom - pytorch

When I run python -m visdom.server, then it shows:
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -3] Temporary failure in name resolution
logging.error('Error {} while downloading {}'.format(exc.code, key))
AttributeError: 'URLError' object has no attribute 'code'
What does it mean? How can I deal with it?

Related

how to set up a mail server and send emails using python SMTP

I would like to send an email with Python smtplib from a custom email address that is linked to a gmail account. The address ends with '.org'. I set up the App Password on the gmail account that the address is linked to. This is my code:
def send_email_from_gmail(**kwargs):
'''
kwparams:
receivers: list
event_datetime: str
event_name: str
parent_name: str
event_date: str
event_time: str
student_name: str
location: str,
location_link: str
'''
email_data = json.load(open('email_info.json'))
receivers = kwargs['receivers']
sender = email_data['email_address']
msg = EmailMessage()
msg['Subject'] = email_data['subject'].format(kwargs['event_datetime'], kwargs['event_name'])
msg['From'] = sender
msg['To'] = receivers
msg.set_content(email_data['email'].format(kwargs['parent_name'], kwargs['event_date'], kwargs['event_time'], kwargs['student_name'], kwargs['location'], kwargs['location_link']))
app_pass = email_data['email_pass']
with smtplib.SMTP_SSL(host='smtp.gmail.com', port=465) as smtp:
try:
smtp.login(sender, app_pass)
smtp.send_message(msg)
return {'success': True}
except:
return {'success': False}
This is the error:
Traceback (most recent call last):
File "/Users/ayushpal/MatrixLearning/websitebackend/email_testing.py", line 55, in <module>
print(send_email_from_gmail(**sample_args))
File "/Users/ayushpal/MatrixLearning/websitebackend/email_testing.py", line 33, in send_email_from_gmail
with smtplib.SMTP_SSL(host='smtp.matrixlearning.org', port=587) as smtp:
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/smtplib.py", line 1050, in __init__
SMTP.__init__(self, host, port, local_hostname, timeout,
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/smtplib.py", line 255, in __init__
(code, msg) = self.connect(host, port)
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/smtplib.py", line 341, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/smtplib.py", line 1056, in _get_socket
new_socket = super()._get_socket(host, port, timeout)
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/smtplib.py", line 312, in _get_socket
return socket.create_connection((host, port), timeout,
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/socket.py", line 824, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/socket.py", line 955, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
If I set the host to 'smtp.{my-domain}.com' instead of '.org', the program runs for about 5 minutes without doing anything before timing out and losing connection.
How can I solve this?
According to DNS queries from my comp smtp.matrixlearning.org has no DMS records so it can not be mapped to IP address.
Traceback (most recent call last):
…
File "/Users/ayushpal/MatrixLearning/websitebackend/email_testing.py", line 33, in send_email_from_gmail
with smtplib.SMTP_SSL(host='smtp.matrixlearning.org', port=587) as smtp:
…
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
I had to attach the mailbox of my custom domain server to gmail before using gmail as the server to send emails. Thank you to everyone who answered!
I think gmail isn't allowing to use third-party apps anymore. I've just seen this on the security settings of gmail:
"To help keep your account secure, from May 30, 2022, ​​Google no longer supports the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password."

Reverse Geocoding: Error using python Geopy for Reverse Geocoding

I tried using reverse geocoding for some coordinates (longitude and latitude) with python, which is a column of my dataset. I tried using a row of the coordinate system as an example, kept on having an error.
This is my code:
import geopandas as gpd
import geopy
from functools import partial
from geopy.geocoders import Nominatim
from geopy.extra.rate_limiter import RateLimiter
import tqdm
from tqdm._tqdm_notebook import tqdm_notebook
# specifying the geocoding service
locator = Nominatim(user_agent="myGeocoder", timeout=30)
cordinates = "-29.4277,26.8160"
location = RateLimiter(locator.reverse(cordinates), min_delay_seconds=1)
location.address
And i got this error message:
---------------------------------------------------------------------------
gaierror Traceback (most recent call last)
/opt/conda/lib/python3.7/site-packages/urllib3/connection.py in _new_conn(self)
158 conn = connection.create_connection(
--> 159 (self._dns_host, self.port), self.timeout, **extra_kw)
160
/opt/conda/lib/python3.7/site-packages/urllib3/util/connection.py in create_connection(address, timeout, source_address, socket_options)
56
---> 57 for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
58 af, socktype, proto, canonname, sa = res
/opt/conda/lib/python3.7/socket.py in getaddrinfo(host, port, family, type, proto, flags)
751 addrlist = []
--> 752 for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
753 af, socktype, proto, canonname, sa = res
gaierror: [Errno -3] Temporary failure in name resolution
During handling of the above exception, another exception occurred:
NewConnectionError Traceback (most recent call last)
/opt/conda/lib/python3.7/site-packages/urllib3/connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
599 body=body, headers=headers,
--> 600 chunked=chunked)
601
/opt/conda/lib/python3.7/site-packages/urllib3/connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
342 try:
--> 343 self._validate_conn(conn)
344 except (SocketTimeout, BaseSSLError) as e:
/opt/conda/lib/python3.7/site-packages/urllib3/connectionpool.py in _validate_conn(self, conn)
838 if not getattr(conn, 'sock', None): # AppEngine might not have `.sock`
--> 839 conn.connect()
840
/opt/conda/lib/python3.7/site-packages/urllib3/connection.py in connect(self)
300 # Add certificate verification
--> 301 conn = self._new_conn()
302 hostname = self.host
/opt/conda/lib/python3.7/site-packages/urllib3/connection.py in _new_conn(self)
167 raise NewConnectionError(
--> 168 self, "Failed to establish a new connection: %s" % e)
169
NewConnectionError: <urllib3.connection.VerifiedHTTPSConnection object at 0x7fb7d6f15490>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution
During handling of the above exception, another exception occurred:
GeocoderUnavailable: HTTPSConnectionPool(host='nominatim.openstreetmap.org', port=443): Max retries exceeded with url: /reverse?lat=-29.4277&lon=26.816&format=json&accept-language=es&addressdetails=1 (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7fb7d6f15490>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution'))
please, what could be the problem??
I think the problem goes with me using an online server for it. Tried it with my system installed jupyter notebook, and i didn't encounter any problem.

Python: Automatically Raise a Custom Exception Without Using The Command raise CustomException("Something Happened")

I've been looking and couldn't find an answer. Basically, Is there a way to automatically raise a custom exception without using the command raise CustomException("Something Happened")? For Example: program calls 'FaultyFunction()' which then
causes a custom exception to occur without having a raise CustomException("Something Bad Happened") inside of the 'FaultyFunction()'.
You could write a decorator that checks for faulty result and then raise an exception for you.
For example
class CustomException(Exception):
pass
def raise_custom_exception(on_returning=None, on_not_returning=None, message="Something happened"):
def wrapper(fn):
def wrapper2(*args, **kwargs):
try:
returned = fn(*args, **kwargs)
except Exception as exc:
raise CustomException(message + f", caused by: {exc}")
if on_returning is not None:
if returned == on_returning or \
isinstance(on_returning, tuple) and returned in on_returning:
raise CustomException(message)
if on_not_returning is not None:
if isinstance(on_not_returning, tuple) and returned not in on_not_returning \
or not isinstance(on_not_returning, tuple) and returned != on_not_returning:
raise CustomException(message)
return returned
return wrapper2
return wrapper
# Usage
#raise_custom_exception(on_returning=42, message="Something is wrong")
def my_faulty_function(x):
return x
#raise_custom_exception(on_not_returning=(200, 201), message="Server replied not okay")
def my_faulty_api_call(url):
import requests
print(f'calling ... {url}')
return requests.get(url).status_code
# Use my_faulty_function and my_faulty_api_call
print(my_faulty_function(41))
try:
my_faulty_function(42)
except Exception:
import traceback
traceback.print_exc()
print(my_faulty_api_call("http://google.com"))
print(my_faulty_api_call("http://goooooooogle.com.does.not.exist"))
The output of this program is
41
Traceback (most recent call last):
File "faulty-raise.py", line 39, in <module>
my_faulty_function(42)
File "faulty-raise.py", line 14, in wrapper2
raise CustomException(message)
CustomException: Something is wrong
calling ... http://google.com
200
calling ... http://goooooooogle.com.does.not.exist
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/urllib3/connection.py", line 157, in _new_conn
(self._dns_host, self.port), self.timeout, **extra_kw
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/urllib3/util/connection.py", line 61, in create_connection
for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socket.py", line 743, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
...
As you can see, you can really craft the way how you would want this decorator to check for fault and raise the CustomException for you.
If you don't even want to decorate the function or the function is in some library you can just monkey patch it like this and use it.
# In file some_faulty_library.py
def some_faulty_function_which_i_dont_even_want_to_decorate(*args, **kwargs):
return None
# In file my_file_which_uses_faulty_library.py
import some_faulty_library
some_faulty_function_which_i_dont_even_want_to_decorate = raise_custom_exception(
on_returning=(None,), message="This function always returns None. Stop using it.")(
some_faulty_library.some_faulty_function_which_i_dont_even_want_to_decorate)
some_faulty_function_which_i_dont_even_want_to_decorate()

How to fix "no such file found error" in python

I'm trying to perform feature extraction from bytefiles.
While opening the file through
with open('byteFiles/'+file,"r") as fp:
...
I am getting an error "Nosuchfilefound". I have checked that the file exists and even tried putting r before bytefiles
with open(r'byteFiles/'+file,"r") as fp:
...
but still I am unable to fix it.
with open('byteFiles/'+file,"r") as fp:
lines=""
for line in fp:
a=line.rstrip().split(" ")[1:]
b=' '.join(a)
b=b+"\n"
text_file.write(b)
fp.close()
os.remove('byteFiles/'+file)
text_file.close()
I am getting the error:
FileNotFoundError: [Errno 2] No such file or directory: 'byteFiles/01azqd4InC7m9JpocGv5'

Python3.6: OSError: [Errno 22] Invalid argument for _io.BufferedReader.read(8)

I have a Python line where I try to define a variable: ts_parts = unpack('>8B', self.file.read(8)), where self.file is an _io.BufferedReader object. Unfortunately, this returns the error: OSError: [Errno 22] Invalid argument, unless the # inside the read method is 0, in which case the complaint is of course: struct.error: unpack requires a bytes object of length 8. Why is this happening? How can I fix it?

Resources