• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

cokelaer / easydev / 8869842052

28 Apr 2024 07:15PM UTC coverage: 82.609% (-0.1%) from 82.71%
8869842052

push

github

cokelaer
roll back the try/except on httplib (regression)

4 of 4 new or added lines in 1 file covered. (100.0%)

14 existing lines in 2 files now uncovered.

703 of 851 relevant lines covered (82.61%)

4.94 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

88.06
/easydev/progressbar.py
1
# -*- python -*-
2
# -*- coding: utf-8 -*-
3
#
4
#  This file is part of the easydev software
5
#
6
#  Copyright (c) 2011-2024
7
#
8
#  File author(s): Thomas Cokelaer <cokelaer@gmail.com>
9
#
10
#  Distributed under the BSD3 License.
11
#
12
#  Website: https://github.com/cokelaer/easydev
13
#  Documentation: http://easydev-python.readthedocs.io
14
#
15
##############################################################################
16
"""A progress bar copied and adapted from pyMC code (dec 2014)"""
6✔
17

18
import sys
6✔
19
import time
6✔
20
import uuid
6✔
21

22
try:
6✔
23
    from IPython import display
6✔
UNCOV
24
    from IPython.core.display import HTML, Javascript
×
25

26
except ImportError:  # pragma: no cover
27
    pass
28

29

30
__all__ = ["progress_bar", "TextProgressBar", "Progress"]
6✔
31

32

33
class ProgressBar(object):
6✔
34
    def __init__(self, iterations, interval=None):
6✔
35
        self.iterations = iterations
6✔
36
        # if no interval provided, set it to 1%
37
        if interval is None:
6✔
UNCOV
38
            if iterations <= 100:
×
39
                interval = 1  # everything % of the data
×
40
            else:
UNCOV
41
                interval = int(iterations / 100)
×
42
        self.interval = interval
6✔
43
        self.start = time.time()
6✔
44
        self.last = 0
6✔
45

46
    def _percentage(self, i):
6✔
47
        if self.iterations != 0:
6✔
48
            return 100 * i / float(self.iterations)
6✔
49
        else:  # pragma: no cover
50
            # could be 100 ?
51
            return 100
52

53
    def _get_elapsed(self):
6✔
54
        return time.time() - self.start
6✔
55

56
    elapsed = property(_get_elapsed)
6✔
57

58

59
class TextProgressBar(ProgressBar):
6✔
60
    """Use :class:`Progress`"""
61

62
    def __init__(self, iterations, printer, width=40, interval=None):
6✔
63
        self.fill_char = "-"
6✔
64
        self.width = width
6✔
65
        self.printer = printer
6✔
66
        ProgressBar.__init__(self, iterations, interval=interval)
6✔
67

68
    def animate(self, i, dummy=None):
6✔
69
        # dummy=None is for back-compatibility
70
        if dummy is not None:  # pragma: no cover
71
            print("second argument in easydev.progress_bar.animate is deprecated. Update your code")
72
        # +1 if i starts at 0 and finishes at N-1
73
        if divmod(i, self.interval)[1] != 0 and i != self.iterations:
6✔
UNCOV
74
            pass
×
75
        else:
76
            self.printer(self.progbar(i))
6✔
77

78
    def progbar(self, i):
6✔
79
        # +1 if i starts at 0 and finishes at N-1
80
        bar = self.bar(self._percentage(i))
6✔
81
        return "[%s] %i of %i complete in %.1f sec" % (
6✔
82
            bar,
83
            (i),
84
            self.iterations,
85
            round(self.elapsed, 1),
86
        )
87

88
    def bar(self, percent):
6✔
89
        all_full = self.width - 2
6✔
90
        num_hashes = int(percent / 100 * all_full)
6✔
91

92
        bar = self.fill_char * num_hashes + " " * (all_full - num_hashes)
6✔
93

94
        info = "%d%%" % percent
6✔
95
        loc = (len(bar) - len(info)) // 2
6✔
96
        return replace_at(bar, info, loc, loc + len(info))
6✔
97

98

99
def replace_at(str, new, start, stop):
6✔
100
    return str[:start] + new + str[stop:]
6✔
101

102

103
def consoleprint(s):
6✔
104
    if sys.platform.lower().startswith("win"):
6✔
UNCOV
105
        print(s, "\r", end="")
×
106
    else:
107
        print("\r", s, end="")
6✔
108
        sys.stdout.flush()
6✔
109

110

111
def ipythonprint(s):  # pragma no cover
112
    print("\r", s, end="")
113
    sys.stdout.flush()
114

115

116
class IPythonNotebookPB(ProgressBar):  # pragma: no cover
117
    """Use :class:`Progress`"""
118

119
    def __init__(self, iterations, interval=None):
120
        self.divid = str(uuid.uuid4())
121
        self.sec_id = str(uuid.uuid4())
122

123
        pb = HTML(
124
            """
125
            <div style="float: left; border: 1px solid black; width:500px">
126
              <div id="%s" style="background-color:blue; width:0%%">&nbsp;</div>
127
            </div>
128
            <label id="%s" style="padding-left: 10px;" text = ""/>
129
            """
130
            % (self.divid, self.sec_id)
131
        )
132
        display(pb)
133

134
        ProgressBar.__init__(self, iterations, interval=interval)
135

136
    def animate(self, i, dummy=None):
137
        if dummy is not None:
138
            print("second argument in easydev.progress_bar.animate is deprecated. Update your code")
139

140
        # +1 if i starts at 0 and finishes at N-1
141
        if divmod(i, self.interval)[1] != 0 and i != self.iterations:
142
            pass
143
        else:
144
            percentage = self._percentage(i)
145
            fraction = percentage
146
            display(Javascript("$('div#%s').width('%i%%')" % (self.divid, percentage)))
147
            display(
148
                Javascript("$('label#%s').text('%i%% in %.1f sec')" % (self.sec_id, fraction, round(self.elapsed, 1)))
149
            )
150

151

152
def _run_from_ipython():
6✔
153
    try:
6✔
154
        __IPYTHON__
6✔
UNCOV
155
        return True
×
156
    except NameError:
6✔
157
        return False
6✔
158

159

160
def progress_bar(iters, interval=None):
6✔
161
    """A progress bar for Python/IPython/IPython notebook
162

163
    :param int iters: number of iterations (steps in the loop)
164
    :param interval: number of intervals to use to update the progress bar (20
165
        by default)
166

167

168
    ::
169

170
        from easydev import progress_bar
171
        pb = progress_bar(10)
172
        for i in range(1,10):
173
            import time
174
            time.sleep(0.1)
175
            pb.animate(i)
176

177
    """
178
    if _run_from_ipython():  # pragma: no cover
179
        from easydev.misc import in_ipynb
180

181
        if in_ipynb() is True:
182
            return IPythonNotebookPB(iters, interval=interval)
183
        else:
184
            return TextProgressBar(iters, printer=ipythonprint, interval=interval)
185
    else:
186
        return TextProgressBar(iters, printer=consoleprint, interval=interval)
6✔
187

188

189
class Progress(object):
6✔
190
    """Generic progress bar for python, IPython, IPython notebook
191

192
    ::
193

194
        from easydev import Progress
195
        pb = Progress(100, interval=1)
196
        pb.animate(10)
197
    """
198

199
    def __init__(self, iters, interval=None):
6✔
200
        self.pb = progress_bar(iters, interval=interval)
6✔
201

202
    def animate(self, i):
6✔
203
        self.pb.animate(i)
6✔
204

205
    def _get_elapsed(self):
6✔
UNCOV
206
        return self.pb.elapsed
×
207

208
    elapsed = property(_get_elapsed)
6✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc