Test Failed
Push — master ( 69b639...e7fa0a )
by Nicolas
04:05 queued 01:05
created

glances.compat.to_ascii()   A

Complexity

Conditions 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nop 1
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
# -*- coding: utf-8 -*-
2
#
3
# This file is part of Glances.
4
#
5
# Copyright (C) 2019 Nicolargo <[email protected]>
6
#
7
# Glances is free software; you can redistribute it and/or modify
8
# it under the terms of the GNU Lesser General Public License as published by
9
# the Free Software Foundation, either version 3 of the License, or
10
# (at your option) any later version.
11
#
12
# Glances is distributed in the hope that it will be useful,
13
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
# GNU Lesser General Public License for more details.
16
#
17
# You should have received a copy of the GNU Lesser General Public License
18
# along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20
# flake8: noqa
21
# pylint: skip-file
22
"""Python 2/3 compatibility shims."""
23
24
from __future__ import print_function, unicode_literals
25
26
import operator
27
import sys
28
import unicodedata
29
import types
30
import subprocess
31
import os
32
33
from glances.logger import logger
34
35
PY3 = sys.version_info[0] == 3
36
37
if PY3:
38
    import queue
39
    from configparser import ConfigParser, NoOptionError, NoSectionError
40
    from statistics import mean
41
    from xmlrpc.client import Fault, ProtocolError, ServerProxy, Transport, Server
42
    from xmlrpc.server import SimpleXMLRPCRequestHandler, SimpleXMLRPCServer
43
    from urllib.request import urlopen
44
    from urllib.error import HTTPError, URLError
45
    from urllib.parse import urlparse
46
47
    input = input
48
    range = range
49
    map = map
50
51
    text_type = str
52
    binary_type = bytes
53
    bool_type = bool
54
    long = int
55
56
    PermissionError = OSError
57
58
    viewkeys = operator.methodcaller('keys')
59
    viewvalues = operator.methodcaller('values')
60
    viewitems = operator.methodcaller('items')
61
62
    def printandflush(string):
63
        """Print and flush (used by stdout* outputs modules)"""
64
        print(string, flush=True)
65
66
    def to_ascii(s):
67
        """Convert the bytes string to a ASCII string
68
        Usefull to remove accent (diacritics)"""
69
        if isinstance(s, binary_type):
70
            return s.decode()
71
        return s.encode('ascii', 'ignore').decode()
72
73
    def listitems(d):
74
        return list(d.items())
75
76
    def listkeys(d):
77
        return list(d.keys())
78
79
    def listvalues(d):
80
        return list(d.values())
81
82
    def iteritems(d):
83
        return iter(d.items())
84
85
    def iterkeys(d):
86
        return iter(d.keys())
87
88
    def itervalues(d):
89
        return iter(d.values())
90
91
    def u(s, errors='replace'):
92
        if isinstance(s, text_type):
93
            return s
94
        return s.decode('utf-8', errors=errors)
95
96
    def b(s, errors='replace'):
97
        if isinstance(s, binary_type):
98
            return s
99
        return s.encode('utf-8', errors=errors)
100
101
    def n(s):
102
        '''Only in Python 2...
103
        from future.utils import bytes_to_native_str as n
104
        '''
105
        return s
106
107
    def nativestr(s, errors='replace'):
108
        if isinstance(s, text_type):
109
            return s
110
        elif isinstance(s, (int, float)):
111
            return s.__str__()
112
        else:
113
            return s.decode('utf-8', errors=errors)
114
115
    def system_exec(command):
116
        """Execute a system command and return the result as a str"""
117
        try:
118
            res = subprocess.run(command.split(' '),
119
                                 stdout=subprocess.PIPE).stdout.decode('utf-8')
120
        except Exception as e:
121
            logger.debug('Can not evaluate command {} ({})'.format(command, e))
122
            res = ''
123
        return res.rstrip()
124
125
else:
126
    from future.utils import bytes_to_native_str as n
127
    import Queue as queue
128
    from itertools import imap as map
129
    from ConfigParser import SafeConfigParser as ConfigParser, NoOptionError, NoSectionError
130
    from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler, SimpleXMLRPCServer
131
    from xmlrpclib import Fault, ProtocolError, ServerProxy, Transport, Server
132
    from urllib2 import urlopen, HTTPError, URLError
133
    from urlparse import urlparse
134
135
    input = raw_input
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable raw_input does not seem to be defined.
Loading history...
136
    range = xrange
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable xrange does not seem to be defined.
Loading history...
137
    ConfigParser.read_file = ConfigParser.readfp
138
139
    text_type = unicode
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable unicode does not seem to be defined.
Loading history...
140
    binary_type = str
141
    bool_type = types.BooleanType
142
    long = long
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable long does not seem to be defined.
Loading history...
143
144
    PermissionError = OSError
145
146
    viewkeys = operator.methodcaller('viewkeys')
147
    viewvalues = operator.methodcaller('viewvalues')
148
    viewitems = operator.methodcaller('viewitems')
149
150
    def printandflush(string):
151
        """Print and flush (used by stdout* outputs modules)"""
152
        print(string)
153
        sys.stdout.flush()
154
155
    def mean(numbers):
156
        return float(sum(numbers)) / max(len(numbers), 1)
157
158
    def to_ascii(s):
159
        """Convert the unicode 's' to a ASCII string
160
        Usefull to remove accent (diacritics)"""
161
        if isinstance(s, binary_type):
162
            return s
163
        return unicodedata.normalize('NFKD', s).encode('ascii', 'ignore')
164
165
    def listitems(d):
166
        return d.items()
167
168
    def listkeys(d):
169
        return d.keys()
170
171
    def listvalues(d):
172
        return d.values()
173
174
    def iteritems(d):
175
        return d.iteritems()
176
177
    def iterkeys(d):
178
        return d.iterkeys()
179
180
    def itervalues(d):
181
        return d.itervalues()
182
183
    def u(s, errors='replace'):
184
        if isinstance(s, text_type):
185
            return s.encode('utf-8', errors=errors)
186
        return s.decode('utf-8', errors=errors)
187
188
    def b(s, errors='replace'):
189
        if isinstance(s, binary_type):
190
            return s
191
        return s.encode('utf-8', errors=errors)
192
193
    def nativestr(s, errors='replace'):
194
        if isinstance(s, binary_type):
195
            return s
196
        elif isinstance(s, (int, float)):
197
            return s.__str__()
198
        else:
199
            return s.encode('utf-8', errors=errors)
200
201
    def system_exec(command):
202
        """Execute a system command and return the resul as a str"""
203
        try:
204
            res = subprocess.check_output(command.split(' '))
205
        except Exception as e:
206
            logger.debug('Can not execute command {} ({})'.format(command, e))
207
            res = ''
208
        return res.rstrip()
209
210
211
# Globals functions for both Python 2 and 3
212
213
214
def subsample(data, sampling):
215
    """Compute a simple mean subsampling.
216
217
    Data should be a list of numerical itervalues
218
219
    Return a subsampled list of sampling lenght
220
    """
221
    if len(data) <= sampling:
222
        return data
223
    sampling_length = int(round(len(data) / float(sampling)))
224
    return [mean(data[s * sampling_length:(s + 1) * sampling_length]) for s in range(0, sampling)]
225
226
227
def time_serie_subsample(data, sampling):
228
    """Compute a simple mean subsampling.
229
230
    Data should be a list of set (time, value)
231
232
    Return a subsampled list of sampling length
233
    """
234
    if len(data) <= sampling:
235
        return data
236
    t = [t[0] for t in data]
237
    v = [t[1] for t in data]
238
    sampling_length = int(round(len(data) / float(sampling)))
239
    t_subsampled = [t[s * sampling_length:(s + 1) * sampling_length][0] for s in range(0, sampling)]
240
    v_subsampled = [mean(v[s * sampling_length:(s + 1) * sampling_length]) for s in range(0, sampling)]
241
    return list(zip(t_subsampled, v_subsampled))
242
243
244
def to_fahrenheit(celsius):
245
    """Convert Celsius to Fahrenheit."""
246
    return celsius * 1.8 + 32
247
248
249
def is_admin():
250
    """
251
    https://stackoverflow.com/a/19719292
252
    @return: True if the current user is an 'Admin' whatever that
253
    means (root on Unix), otherwise False.
254
    Warning: The inner function fails unless you have Windows XP SP2 or
255
    higher. The failure causes a traceback to be printed and this
256
    function to return False.
257
    """
258
259
    if os.name == 'nt':
260
        import ctypes
261
        import traceback
262
        # WARNING: requires Windows XP SP2 or higher!
263
        try:
264
            return ctypes.windll.shell32.IsUserAnAdmin()
265
        except Exception as e:
266
            traceback.print_exc()
267
            return False
268
    else:
269
        # Check for root on Posix
270
        return os.getuid() == 0
271
272
273
def key_exist_value_not_none(k, d):
274
    # Return True if:
275
    # - key k exists
276
    # - d[k] is not None
277
    return k in d and d[k] is not None
278
279
280
def key_exist_value_not_none_not_v(k, d, v=''):
281
    # Return True if:
282
    # - key k exists
283
    # - d[k] is not None
284
    # - d[k] != v
285
    return k in d and d[k] is not None and d[k] != v
286
287
288
def disable(class_name, var):
289
    """Set disable_<var> to True in the class class_name."""
290
    setattr(class_name, 'enable_' + var, False)
291
    setattr(class_name, 'disable_' + var, True)
292
293
294
def enable(class_name, var):
295
    """Set disable_<var> to False in the class class_name."""
296
    setattr(class_name, 'enable_' + var, True)
297
    setattr(class_name, 'disable_' + var, False)
298