Completed
Push — master ( 0b9edb...ab2b1a )
by Mathieu
10s
created

yes_no_prompt()   B

Complexity

Conditions 6

Size

Total Lines 13

Duplication

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