yes_no_prompt()   B
last analyzed

Complexity

Conditions 6

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 6
dl 0
loc 13
rs 8
c 2
b 0
f 0
1
import re
2
import hashlib
3
import unicodedata
4
import json
5
6
from distutils.util import strtobool
7
from subprocess import Popen, PIPE
8
9
def jobname_generator(jobname, job_id):
10
    '''Crop the jobname to a maximum of 64 characters.
11
    Parameters
12
    ----------
13
    jobname : str
14
    Initial jobname.
15
    job_id: str
16
    ID of the job in the current batch.
17
    Returns
18
    -------
19
    str
20
    The cropped version of the string.  
21
    '''
22
    # 64 - 1 since the total length including -1 should be less than 64
23
    job_id = str(job_id)
24
    if len(jobname) + len(job_id) > 63:
25
        croped_string = '{}_{}'.format(jobname[:63 - len(job_id)], job_id)
26
    else:
27
        croped_string = '{}_{}'.format(jobname, job_id)
28
    return croped_string
29
30
31
def print_boxed(string):
32
    splitted_string = string.split('\n')
33
    max_len = max(map(len, splitted_string))
34
    box_line = u"\u2500" * (max_len + 2)
35
36
    out = u"\u250c" + box_line + u"\u2510\n"
37
    out += '\n'.join([u"\u2502 {} \u2502".format(line.ljust(max_len)) for line in splitted_string])
38
    out += u"\n\u2514" + box_line + u"\u2518"
39
    print out
40
41
42
def yes_no_prompt(query, default=None):
43
    available_prompts = {None: " [y/n] ", 'y': " [Y/n] ", 'n': " [y/N] "}
44
45
    if default not in available_prompts:
46
        raise ValueError("Invalid default: '{}'".format(default))
47
48
    while True:
49
        try:
50
            answer = raw_input("{0}{1}".format(query, available_prompts[default]))
51
            return strtobool(answer)
52
        except ValueError:
53
            if answer == '' and default is not None:
54
                return strtobool(default)
55
56
57
def chunks(sequence, n):
58
    """ Yield successive n-sized chunks from sequence. """
59
    for i in xrange(0, len(sequence), n):
60
        yield sequence[i:i + n]
61
62
63
def generate_uid_from_string(value):
64
    """ Create unique identifier from a string. """
65
    return hashlib.sha256(value).hexdigest()
66
67
68
def slugify(value):
69
    """
70
    Converts to lowercase, removes non-word characters (alphanumerics and
71
    underscores) and converts spaces to underscores. Also strips leading and
72
    trailing whitespace.
73
74
    Reference
75
    ---------
76
    https://github.com/django/django/blob/1.7c3/django/utils/text.py#L436
77
    """
78
    value = unicodedata.normalize('NFKD', unicode(value, "UTF-8")).encode('ascii', 'ignore').decode('ascii')
79
    value = re.sub('[^\w\s-]', '', value).strip().lower()
80
    return str(re.sub('[-\s]+', '_', value))
81
82
83
def encode_escaped_characters(text, escaping_character="\\"):
84
    """ Escape the escaped character using its hex representation """
85
    def hexify(match):
86
        return "\\x{0}".format(match.group()[-1].encode("hex"))
87
88
    return re.sub(r"\\.", hexify, text)
89
90
91
def decode_escaped_characters(text):
92
    """ Convert hex representation to the character it represents """
93
    if len(text) == 0:
94
        return ''
95
96
    def unhexify(match):
97
        return match.group()[2:].decode("hex")
98
99
    return re.sub(r"\\x..", unhexify, text)
100
101
102
def save_dict_to_json_file(path, dictionary):
103
    with open(path, "w") as json_file:
104
        json_file.write(json.dumps(dictionary, indent=4, separators=(',', ': ')))
105
106
107
def load_dict_from_json_file(path):
108
    with open(path, "r") as json_file:
109
        return json.loads(json_file.read())
110
111
112
def detect_cluster():
113
    # Get server status
114
    try:
115
        output = Popen(["qstat", "-B"], stdout=PIPE).communicate()[0]
116
    except OSError:
117
        # If qstat is not available we assume that the cluster is unknown.
118
        return None
119
    # Get server name from status
120
    server_name = output.split('\n')[2].split(' ')[0]
121
    # Cleanup the name and return it
122
    cluster_name = None
123
    if server_name.split('.')[-1] == 'm':
124
        cluster_name = "mammouth"
125
    elif server_name.split('.')[-1] == 'guil':
126
        cluster_name = "guillimin"
127
    elif server_name.split('.')[-1] == 'helios':
128
        cluster_name = "helios"
129
    elif server_name.split('.')[-1] == 'hades':
130
        cluster_name = "hades"
131
    return cluster_name
132
133
134
def get_launcher(cluster_name):
135
    if cluster_name == "helios":
136
        return "msub"
137
    else:
138
        return "qsub"
139