Completed
Push — master ( f07933...a88d3a )
by Marc-Alexandre
9s
created

jobname_generator()   A

Complexity

Conditions 2

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

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