poption()   C
last analyzed

Complexity

Conditions 10

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 8
nop 2
dl 0
loc 11
rs 5.9999
c 0
b 0
f 0

How to fix   Complexity   

Complexity

Complex classes like build.rna_tools.tools.mq.lib.shellgraphics.shellgraphics.poption() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
#!/usr/bin/python
2
"""ShellGraphics - a library of some simple graphics tricks in terminal
3
4
Run `ShellGraphics.py` or open `demo.txt` (the file was created with `python ShellGraphics.py > demo.txt`)
5
6
 ____  _          _ _  ____                 _     _          
7
/ ___|| |__   ___| | |/ ___|_ __ __ _ _ __ | |__ (_) ___ ___ 
8
\___ \| '_ \ / _ \ | | |  _| '__/ _` | '_ \| '_ \| |/ __/ __|
9
 ___) | | | |  __/ | | |_| | | | (_| | |_) | | | | | (__\__ \
10
|____/|_| |_|\___|_|_|\____|_|  \__,_| .__/|_| |_|_|\___|___/
11
                                     |_|                     
12
13
 mqaprna.py
14
15
####################################################################################################
16
# mqaprna.py                                                                                       #
17
####################################################################################################
18
****************************************************************************************************
19
* mqaprna.py                                                                                       *
20
****************************************************************************************************
21
22
 mqaprna.py
23
24
 Ignore pdb fn        off
25
 Seq ss fn            off
26
 Native pdb           off
27
 Output csv           test_m0.csv
28
 Directory            test_data/2/
29
 Multiprocessing      off
30
 AnalyzeGeometry      off
31
 SSAgreement          off
32
 to ignore []
33
 files to analyze: 3
34
----------------------------------------------------------------------------------------------------
35
 methods: ['RASP', 'SimRNA', 'ClashScore', 'FARNA', 'NAST_pyro']
36
----------------------------------------------------------------------------------------------------
37
38
etc.
39
"""
40
import sys
41
import time
42
import subprocess
43
44
terminal_length = 80
45
color_mode = True
46
47
class Title(object):
48
    def __init__(self):
49
        print("#" * terminal_length)
50
        title = "mqaprna.py v0.1"
51
        print("#", title, " " * (terminal_length  - 5 - len(title)), '#')
52
        print("#" * terminal_length)
53
54
class Table(object):
55
    column_length = 30
56
    def __init__(self, headers):
57
        self.headers = headers
58
59
    def show_header(self):
60
        print(self.headers[0].ljust(self.column_length), end=' ')
61
        for h in self.headers[1:]:
62
            print(h.rjust(self.column_length), end=' ')
63
        print()
64
        print('-' * terminal_length)
65
66
    def show_row(self, values):
67
        print(values[0].ljust(self.column_length), end=' ')
68
        for h in values[1:]:
69
            print(h.rjust(self.column_length), end=' ')
70
        print()
71
72
    def save_csv(self):
73
        pass
74
75
76
def table_demo():
77
    t = Table(['fn','SimRNA', 'FARNA', 'X'])
78
    t.show_header()
79
    t.show_row(['1xjrA_output3-000142_AA.pdb', '-35.861', '44.043', '111'])
80
    t.show_row(['1xjrA_output3-000142_AA.pdb', '-34.861', '322.12', '443'])
81
    phr()
82
83
84
def phr(char='-'):
85
    """Print ------- where '-' is set by char"""
86
    print(char * terminal_length)
87
88
89
def phr_text(text, verbose=True):
90
    """Print hr if CHAR is '*' you will get:
91
    ************************************************************** <text> *"""
92
    len_of_hr = terminal_length
93
    CHAR =  '-'
94
    if verbose: 
95
        text=str(text)
96
        st=CHAR * (len_of_hr - 3 - len(text)) + ' ' + text + ' ' + CHAR # 3 = ' 'test' '* = 2x' ' + 1x*
97
        print(st)
98
        return True
99
    else:
100
        return False
101
102
103
def pbanner_simply(text):
104
    """
105
    """
106
    pbr()
107
    if color_mode:
108
        print('\033[1;34m' + text + '\033[1;m')
109
    else:
110
        print(text)
111
    pbr()
112
113
114
def pbanner(text, char="#", verbose=True):
115
    """Print
116
117
    - text, like: SUPER PROGRAM ver.01
118
    - len, by default it equals to LENGTH_OF_THE_SCREEN
119
    - verbose
120
    ---------
121
122
    DO:
123
    - print banner, like:
124
    ##################################################
125
    # SUPER PROGRAM ver.01                           #
126
    ##################################################
127
128
    or use '*'
129
    ---------
130
    RETURN:
131
    - True if ok
132
    """
133
    len = terminal_length
134
    if verbose:
135
        print(char * len + '\n' + char +' '+ text.ljust(len-3)+ char  +'\n'+ char * len)
136
    return True
137
138
139
def pprogress_line(step, amount,text,length_the_bar=terminal_length, verbose=True):
140
    """Generate a progress bar::
141
142
      [===================================================X----] # 36412 ; 94.0878552972 % ; 36500
143
144
    :params:
145
146
     - step, c(ounter) in loop,
147
     - amount, to count a percent,
148
     - length_the_bar of whole progress bar (use to scale)
149
150
    how to use it::
151
152
        c=0
153
        len_of_iter=len(list)
154
        for i in list:
155
            c+=1
156
            toolboX.progress_line(c,len_of_iter,verbose=True)
157
    
158
    :return: string
159
    """
160
    percent=float(step)/amount * 100
161
    #
162
    #  length_the_bar 
163
    #
164
    #length_the_bar=length_the_bar#-15
165
    #
166
    done=int((float(percent)*length_the_bar)/100) # 1.4 % -> 1
167
    #
168
    #  2% calosci - 100%
169
    #  x (ile kresek) - 50 (gdy dlugosc bara wynosi jeno 50); czyli wyjdzie o polowe mnieij
170
    #  dla procent 2% tylko jeden step done '[=X ...'
171
    #
172
    #for done in range(1,100): to test
173
    #print '#',step,';',percent, '%'            
174
    if verbose: print('['+'-'*done+''+' '*(length_the_bar-done)+']',' ',str(step).rjust(4), str(round(percent,2)).ljust(4), '%',amount, text)
175
    # return True
176
177
178
def pformat_line(name, value='',char="#", verbose=True, wide=terminal_length):
179
    """
180
    GET:
181
    - name,
182
    - value,
183
    - verbose,
184
    - wide, length of field with name, len from the beginning of name to ':'
185
186
187
    DO:
188
    print # STEP              : 20
189
190
    pformat_line('magnus','ok')
191
    # Magnus                                                            o
192
    """
193
194
    value=str(value)
195
196
    if verbose: 
197
        if value:
198
            #print "# "+name.capitalize().ljust(wide)+' : ',value # #EXISTS               : Yes
199
            if type(value)==type([1]):
200
                print(char + ' ' + name.capitalize() +' ', value)
201
            else:
202
                print(char + ' ' + name.capitalize()+' '* (LENGTH_OF_THE_SCREEN - len(value) - len(name)-2) +value) #EXISTS               : Yes
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable LENGTH_OF_THE_SCREEN does not seem to be defined.
Loading history...
203
        else:
204
            print(char + ' ' + name.capitalize().ljust(wide))               #EXISTS              
205
206
207
def pin_red(text, newline = True):
208
    """
209
    http://www.siafoo.net/snippet/88
210
    """
211
    if color_mode:
212
        if newline:
213
            print('\033[1;31m' + text + '\033[1;m')
214
        else:
215
            print('\033[1;31m' + text + '\033[1;m', end=' ')        
216
    else:
217
        print(text)
218
    
219
def pin_green(text, newline = True):
220
    """
221
    http://www.siafoo.net/snippet/88
222
    """
223
    if color_mode:
224
        if newline:
225
            print('\033[1;32m' + text + '\033[1;m')
226
        else:
227
            print('\033[1;32m' + text + '\033[1;m', end=' ')
228
    else:
229
        print(text)
230
231
def pin_blue(text, newline = True):
232
    """
233
    http://www.siafoo.net/snippet/88
234
    """
235
    if color_mode:
236
        if newline:
237
            print('\033[1;34m' + text + '\033[1;m')
238
        else:
239
            print('\033[1;34m' + text + '\033[1;m', end=' ')
240
    else:
241
        print(text)
242
243
244
def pin_red_and_blue(text, text2, newline = True):
245
    """
246
247
    inspired: http://www.siafoo.net/snippet/88
248
    """
249
    if color_mode:
250
        if newline:
251
            print('\033[1;31m' + text + '\033[1;m' + '\033[1;34m' + text2 + '\033[1;m')
252
        else:
253
            print('\033[1;31m' + text + '\033[1;m' + '\033[1;34m' + text2 + '\033[1;m')
254
    else:
255
        print(text + ' ' + text)
256
257
258
def ph_center(text, char='-'):
259
    if len(text) % 2:
260
        half = (terminal_length - len(text) - 1) / 2
261
        print(char * (half - 1), text, char * half)
262
    else:
263
        half = (terminal_length - len(text) - 2) / 2
264
        print(char * half, text, char * half)
265
266
267
def ph_center2(text):
268
    """
269
    ================================================================
270
                            Output                              
271
    ----------------------------------------------------------------
272
    """
273
    phr('=')
274
    ph_center(text, char=' ')
275
    phr('-')
276
277
278
def ptitle(text):
279
        """Show a huge title using `figlet`.
280
281
        .. warning :: `figlet` has to be installed in system
282
        """
283
        subprocess.check_call(['figlet', text])
284
285
286
def poption(name, value):
287
    """Print option: name and value. If value is True or 'on' or any string/number then print 'on' in green otherwise print 'off' in red.
288
    """
289
    if (value == 'off' or value == False or not value) and color_mode:
290
        print('', name.ljust(20), '\033[1;31moff\033[1;m')  # red
291
    elif (value == 'on' or value == True) and color_mode:
292
        print('', name.ljust(20), '\033[1;32mon\033[1;m')  # green
293
    elif value and color_mode:
294
        print('', name.ljust(20), '\033[1;32m' + value + '\033[1;m')  # green
295
    else:
296
        print('', name.ljust(20), value)
297
298
299
def poptions(dictionary):
300
    """Get dict and print as options
301
    """
302
    print('--------------------------  ----------------------------------------------------')
303
    for d in list(dictionary.keys()):
304
        print(d.ljust(27), end=' ') 
305
        value = dictionary[d]        
306
        if (value == 'off' or value == False or not value) and color_mode:
307
            print('\033[1;31moff\033[1;m')  # red
308
        elif (value == 'on' or value == True) and color_mode:
309
            print('\033[1;32mon\033[1;m')  # green
310
        elif value and color_mode:
311
            print('\033[1;32m' + value + '\033[1;m')  # green
312
        else:
313
            if value == None:
314
                print('off')
315
            elif value == False:
316
                print('off')
317
            elif value == True:
318
                print('on')
319
            else:
320
                print(value)
321
322
323
def pbr():
324
        print()
325
326
327
def psub(text):
328
    """Print ' <text>'
329
    """
330
    print('', str(text))
331
332
def p(text):
333
    """Just print '<text>'
334
    """
335
    print(str(text))
336
337
338
def start(): pass
339
340
if __name__ == '__main__':
341
        ptitle('ShellGraphics')
342
        pbanner_simply('mqaprna.py')
343
        pbanner('mqaprna.py')
344
        pbanner('mqaprna.py', '*')
345
        phr_text('SimRNA')
346
347
        for i in range(1,6):
348
                pprogress_line(i,5, 'text')
349
                sys.stdout.write("\033[F") # Cursor up one line - works in oneline!
350
                time.sleep(1)
351
352
        Title()
353
        table_demo()
354
        pformat_line('foo foo')
355
        pin_red('foo')
356
        pin_blue('foo')
357
        pin_red_and_blue('foo','foo2')
358
        ph_center('Options')
359
        p('help')
360
        psub('logout - to log out')
361
        ph_center('Options:')
362
        ph_center2('Option')
363
        pbr()
364
        poption('native pdb', 'on') 
365
        poption('native pdb', 'off') 
366
        pbr()
367
        poption('native pdb', True) 
368
        poption('native pdb', False) 
369
        pbr()
370
        poption('native pdb', 'any text')
371
        poption('native pdb', bool('any text'))
372
        poption('native pdb', '') 
373