From 88340abec242151002a0cb415706221d89225853 Mon Sep 17 00:00:00 2001
From: Igor Chubin <igor@chub.in>
Date: Fri, 3 Apr 2020 21:49:51 +0200
Subject: [PATCH] switched to python3

---
 lib/spark.py     | 32 +++++++++++++++++---------------
 lib/wttr.py      | 33 +++++++++++++++++++++------------
 lib/wttr_line.py |  2 +-
 lib/wttr_srv.py  | 11 ++++++-----
 4 files changed, 45 insertions(+), 33 deletions(-)

diff --git a/lib/spark.py b/lib/spark.py
index 511ebf6..edd943b 100644
--- a/lib/spark.py
+++ b/lib/spark.py
@@ -70,9 +70,11 @@ def interpolate_data(input_data, max_width):
     Resample `input_data` to number of `max_width` counts
     """
 
-    x = list(range(len(input_data)))
+    input_data = list(input_data)
+    input_data_len = len(input_data)
+    x = list(range(input_data_len))
     y = input_data
-    xvals = np.linspace(0, len(input_data)-1, max_width)
+    xvals = np.linspace(0, input_data_len-1, max_width)
     yinterp = interp1d(x, y, kind='cubic')
     return yinterp(xvals)
 
@@ -82,7 +84,7 @@ def jq_query(query, data_parsed):
     """
 
     pyjq_data = pyjq.all(query, data_parsed)
-    data = map(float, pyjq_data)
+    data = list(map(float, pyjq_data))
     return data
 
 # }}}
@@ -136,11 +138,11 @@ def draw_spark(data, height, width, color_data):
                 orig_max_line = max_line
 
                 # aligning it
-                if len(max_line)/2 < j and len(max_line)/2 + j < width:
-                    spaces = " "*(j - len(max_line)/2)
+                if len(max_line)//2 < j and len(max_line)//2 + j < width:
+                    spaces = " "*(j - len(max_line)//2)
                     max_line = spaces + max_line # + spaces
                     max_line = max_line + " "*(width - len(max_line))
-                elif len(max_line)/2 + j >= width:
+                elif len(max_line)//2 + j >= width:
                     max_line = " "*(width - len(max_line)) + max_line
 
                 max_line = max_line.replace(orig_max_line, colorize(orig_max_line, "38;5;33"))
@@ -160,13 +162,13 @@ def draw_diagram(data, height, width):
     option.size = diagram.Point([width, height])
     option.mode = 'g'
 
-    stream = StringIO.StringIO()
+    stream = io.BytesIO()
     gram = diagram.DGWrapper(
         data=[list(data), range(len(data))],
         dg_option=option,
         ostream=stream)
     gram.show()
-    return stream.getvalue()
+    return stream.getvalue().decode("utf-8")
 # }}}
 # draw_date {{{
 
@@ -185,7 +187,7 @@ def draw_date(config, geo_data):
         datetime_ = datetime_day_start + datetime.timedelta(hours=24*day)
         date = format_datetime(datetime_, "EEE dd MMM", locale=locale, tzinfo=tzinfo)
 
-        spaces = ((24-len(date))/2)*" "
+        spaces = ((24-len(date))//2)*" "
         date = spaces + date + spaces
         date = " "*(24-len(date)) + date
         answer += date
@@ -326,7 +328,7 @@ def draw_wind(data, color_data):
 
         degree = int(degree)
         if degree:
-            wind_direction = constants.WIND_DIRECTION[((degree+22)%360)/45]
+            wind_direction = constants.WIND_DIRECTION[((degree+22)%360)//45]
         else:
             wind_direction = ""
 
@@ -470,15 +472,15 @@ def textual_information(data_parsed, geo_data, config):
     tmp_output = []
     tmp_output.append('  Now:    %%{{NOW(%s)}}' % timezone)
     tmp_output.append('Dawn:    %s'
-                      % str(sun['dawn'].strftime("%H:%M:%S")))
+                      % str(current_sun['dawn'].strftime("%H:%M:%S")))
     tmp_output.append('Sunrise: %s'
-                      % str(sun['sunrise'].strftime("%H:%M:%S")))
+                      % str(current_sun['sunrise'].strftime("%H:%M:%S")))
     tmp_output.append('  Zenith: %s'
-                      % str(sun['noon'].strftime("%H:%M:%S     ")))
+                      % str(current_sun['noon'].strftime("%H:%M:%S     ")))
     tmp_output.append('Sunset:  %s'
-                      % str(sun['sunset'].strftime("%H:%M:%S")))
+                      % str(current_sun['sunset'].strftime("%H:%M:%S")))
     tmp_output.append('Dusk:    %s'
-                      % str(sun['dusk'].strftime("%H:%M:%S")))
+                      % str(current_sun['dusk'].strftime("%H:%M:%S")))
     tmp_output = [
         re.sub("^([A-Za-z]*:)", lambda m: colorize(m.group(1), "2"), x)
         for x in tmp_output]
diff --git a/lib/wttr.py b/lib/wttr.py
index b1724cd..a1982dc 100644
--- a/lib/wttr.py
+++ b/lib/wttr.py
@@ -8,6 +8,7 @@ from gevent.monkey import patch_all
 from gevent.subprocess import Popen, PIPE, STDOUT
 patch_all()
 
+import sys
 import os
 import re
 import time
@@ -36,12 +37,12 @@ def get_wetter(location, ip, html=False, lang=None, query=None, location_name=No
         if local_url is None:
             url = ""
         else:
-            url = local_url.encode('utf-8')
+            url = local_url
 
         if local_location is None:
             location = ""
         else:
-            location = local_location.encode('utf-8')
+            location = local_location
 
         pic_url = url.replace('?', '_')
 
@@ -120,9 +121,12 @@ def get_wetter(location, ip, html=False, lang=None, query=None, location_name=No
 
             p = Popen(cmd, stdout=PIPE, stderr=PIPE)
             stdout, stderr = p.communicate()
+            stdout = stdout.decode("utf-8")
+            stderr = stderr.decode("utf-8")
+
             if p.returncode != 0:
                 print("ERROR: location not found: %s" % location)
-                if 'Unable to find any matching weather location to the query submitted' in stderr:
+                if u'Unable to find any matching weather location to the query submitted' in stderr:
                     if location != NOT_FOUND_LOCATION:
                         NOT_FOUND_MESSAGE_HEADER = u"ERROR: %s: %s\n---\n\n" % (get_message('UNKNOWN_LOCATION', lang), location)
                         location = NOT_FOUND_LOCATION
@@ -133,10 +137,10 @@ def get_wetter(location, ip, html=False, lang=None, query=None, location_name=No
         dirname = os.path.dirname(filename)
         if not os.path.exists(dirname):
             os.makedirs(dirname)
-        
+
         if location_not_found:
-            stdout += get_message('NOT_FOUND_MESSAGE', lang).encode('utf-8')
-            stdout = NOT_FOUND_MESSAGE_HEADER.encode('utf-8') + stdout
+            stdout += get_message('NOT_FOUND_MESSAGE', lang)
+            stdout = NOT_FOUND_MESSAGE_HEADER + stdout
 
         if 'days' in query:
             if query['days'] == '0':
@@ -146,7 +150,7 @@ def get_wetter(location, ip, html=False, lang=None, query=None, location_name=No
             if query['days'] == '2':
                 stdout = "\n".join(stdout.splitlines()[:27]) + "\n"
 
-        first = stdout.splitlines()[0].decode('utf-8')
+        first = stdout.splitlines()[0]
         rest = stdout.splitlines()[1:]
         if query.get('no-caption', False):
 
@@ -158,7 +162,7 @@ def get_wetter(location, ip, html=False, lang=None, query=None, location_name=No
 
             if separator:
                 first = first.split(separator,1)[1]
-                stdout = "\n".join([first.strip().encode('utf-8')] + rest) + "\n"
+                stdout = "\n".join([first.strip()] + rest) + "\n"
 
         if query.get('no-terminal', False):
             stdout = remove_ansi(stdout)
@@ -172,9 +176,9 @@ def get_wetter(location, ip, html=False, lang=None, query=None, location_name=No
                  and not query.get('no-caption')
                  and not query.get('days') == '0'):
             line = "%s: %s [%s]\n" % (
-                get_message('LOCATION', lang).encode('utf-8'),
-                full_address.encode('utf-8'),
-                location.encode('utf-8'))
+                get_message('LOCATION', lang),
+                full_address,
+                location)
             stdout += line
 
         if query.get('padding', False):
@@ -191,13 +195,15 @@ def get_wetter(location, ip, html=False, lang=None, query=None, location_name=No
 
         p = Popen(cmd,  stdin=PIPE, stdout=PIPE, stderr=PIPE )
         stdout, stderr = p.communicate(stdout)
+        stdout = stdout.decode("utf-8")
+        stderr = stderr.decode("utf-8")
         if p.returncode != 0:
             error(stdout + stderr)
 
         if query.get('inverted_colors'):
             stdout = stdout.replace('<body class="">', '<body class="" style="background:white;color:#777777">')
         
-        title = "<title>%s</title>" % first.encode('utf-8')
+        title = "<title>%s</title>" % first
         opengraph = get_opengraph()
         stdout = re.sub("<head>", "<head>" + title + opengraph, stdout)
         open(filename+'.html', 'w').write(stdout)
@@ -232,6 +238,7 @@ def get_moon(location, html=False, lang=None, query=None):
     if lang:
         env['LANG'] = lang
     p = Popen(cmd, stdout=PIPE, stderr=PIPE, env=env)
+    stdout = stdout.decode("utf-8")
     stdout = p.communicate()[0]
 
     if query.get('no-terminal', False):
@@ -240,6 +247,8 @@ def get_moon(location, html=False, lang=None, query=None):
     if html:
         p = Popen(["bash", ANSI2HTML, "--palette=solarized", "--bg=dark"],  stdin=PIPE, stdout=PIPE, stderr=PIPE)
         stdout, stderr = p.communicate(stdout)
+        stdout = stdout.decode("utf-8")
+        stderr = stderr.decode("utf-8")
         if p.returncode != 0:
             error(stdout + stderr)
 
diff --git a/lib/wttr_line.py b/lib/wttr_line.py
index f632936..6029f4a 100644
--- a/lib/wttr_line.py
+++ b/lib/wttr_line.py
@@ -140,7 +140,7 @@ def render_wind(data, query):
         degree = ""
 
     if degree:
-        wind_direction = WIND_DIRECTION[((degree+22)%360)/45]
+        wind_direction = WIND_DIRECTION[((degree+22)%360)//45]
     else:
         wind_direction = ""
 
diff --git a/lib/wttr_srv.py b/lib/wttr_srv.py
index a55c934..802dafe 100644
--- a/lib/wttr_srv.py
+++ b/lib/wttr_srv.py
@@ -49,7 +49,7 @@ def show_text_file(name, lang):
         text = text\
                 .replace('NUMBER_OF_LANGUAGES', str(len(SUPPORTED_LANGS)))\
                 .replace('SUPPORTED_LANGUAGES', ' '.join(SUPPORTED_LANGS))
-    return text.decode('utf-8')
+    return text
 
 def client_ip_address(request):
     """
@@ -238,8 +238,8 @@ def wttr(location, request):
         query = parse_query.metric_or_imperial(query, lang, us_ip=us_ip)
 
         # logging query
-        orig_location_utf8 = (orig_location or "").encode('utf-8')
-        location_utf8 = location.encode('utf-8')
+        orig_location_utf8 = (orig_location or "")
+        location_utf8 = location
         use_imperial = query.get('use_imperial', False)
         log(" ".join(map(str,
                          [ip_addr, user_agent, orig_location_utf8, location_utf8, use_imperial, lang])))
@@ -297,16 +297,17 @@ def wttr(location, request):
                 output = add_buttons(output)
             else:
                 #output += '\n' + get_message('NEW_FEATURE', lang).encode('utf-8')
-                output += '\n' + get_message('FOLLOW_ME', lang).encode('utf-8') + '\n'
+                output += '\n' + get_message('FOLLOW_ME', lang) + '\n'
 
         return _wrap_response(output, html_output)
 
     except Exception as exception:
         # if 'Malformed response' in str(exception) \
         #         or 'API key has reached calls per day allowed limit' in str(exception):
+            logging.error("Exception has occured", exc_info=1)
             if html_output:
                 return _wrap_response(MALFORMED_RESPONSE_HTML_PAGE, html_output)
-            return _wrap_response(get_message('CAPACITY_LIMIT_REACHED', lang).encode('utf-8'), html_output)
+            return _wrap_response(get_message('CAPACITY_LIMIT_REACHED', lang), html_output)
         # logging.error("Exception has occured", exc_info=1)
         # return "ERROR"