Completed
Pull Request — master (#152)
by
unknown
01:03
created

default_name()   A

Complexity

Conditions 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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