CMS 3D CMS Logo

helperFunctions.py
Go to the documentation of this file.
1 from __future__ import print_function
2 from __future__ import absolute_import
3 from builtins import range
4 import os
5 import re
6 import ROOT
7 import sys
8 from .TkAlExceptions import AllInOneError
9 import six
10 
11 ####################--- Helpers ---############################
12 def replaceByMap(target, the_map):
13  """This function replaces `.oO[key]Oo.` by `the_map[key]` in target.
14 
15  Arguments:
16  - `target`: String which contains symbolic tags of the form `.oO[key]Oo.`
17  - `the_map`: Dictionary which has to contain the `key`s in `target` as keys
18  """
19 
20  result = target
21  for key in the_map:
22  lifeSaver = 10e3
23  iteration = 0
24  while ".oO[" in result and "]Oo." in result:
25  for key in the_map:
26  try:
27  result = result.replace(".oO["+key+"]Oo.",the_map[key])
28  except TypeError: #try a dict
29  try:
30  for keykey, value in six.iteritems(the_map[key]):
31  result = result.replace(".oO[" + key + "['" + keykey + "']]Oo.", value)
32  result = result.replace(".oO[" + key + '["' + keykey + '"]]Oo.', value)
33  except AttributeError: #try a list
34  try:
35  for index, value in enumerate(the_map[key]):
36  result = result.replace(".oO[" + key + "[" + str(index) + "]]Oo.", value)
37  except TypeError:
38  raise TypeError("Something is wrong in replaceByMap! Need a string, dict, or list, but the_map(%s)=%s!"%(repr(key), repr(the_map[key])))
39  iteration += 1
40  if iteration > lifeSaver:
41  problematicLines = ""
42  for line in result.splitlines():
43  if ".oO[" in result and "]Oo." in line:
44  problematicLines += "%s\n"%line
45  msg = ("Oh Dear, there seems to be an endless loop in "
46  "replaceByMap!!\n%s\n%s"%(problematicLines, the_map))
47  raise AllInOneError(msg)
48  return result
49 
50 
51 def getCommandOutput2(command):
52  """This function executes `command` and returns it output.
53 
54  Arguments:
55  - `command`: Shell command to be invoked by this function.
56  """
57 
58  child = os.popen(command)
59  data = child.read()
60  err = child.close()
61  if err:
62  raise RuntimeError('%s failed w/ exit code %d' % (command, err))
63  return data
64 
65 
66 def castorDirExists(path):
67  """This function checks if the directory given by `path` exists.
68 
69  Arguments:
70  - `path`: Path to castor directory
71  """
72 
73  if path[-1] == "/":
74  path = path[:-1]
75  containingPath = os.path.join( *path.split("/")[:-1] )
76  dirInQuestion = path.split("/")[-1]
77  try:
78  rawLines = getCommandOutput2("rfdir /"+containingPath).splitlines()
79  except RuntimeError:
80  return False
81  for line in rawLines:
82  if line.split()[0][0] == "d":
83  if line.split()[8] == dirInQuestion:
84  return True
85  return False
86 
87 def replacelast(string, old, new, count = 1):
88  """Replace the last occurances of a string"""
89  return new.join(string.rsplit(old,count))
90 
91 fileExtensions = ["_cfg.py", ".sh", ".root"]
92 
93 def addIndex(filename, njobs, index = None):
94  if index is None:
95  return [addIndex(filename, njobs, i) for i in range(njobs)]
96  if njobs == 1:
97  return filename
98 
99  fileExtension = None
100  for extension in fileExtensions:
101  if filename.endswith(extension):
102  fileExtension = extension
103  if fileExtension is None:
104  raise AllInOneError(fileName + " does not end with any of the extensions "
105  + str(fileExtensions))
106  return replacelast(filename, fileExtension, "_" + str(index) + fileExtension)
107 
108 def parsecolor(color):
109  try: #simplest case: it's an int
110  return int(color)
111  except ValueError:
112  pass
113 
114  try: #kRed, kBlue, ...
115  color = str(getattr(ROOT, color))
116  return int(color)
117  except (AttributeError, ValueError):
118  pass
119 
120  if color.count("+") + color.count("-") == 1: #kRed+5, kGreen-2
121  if "+" in color: #don't want to deal with nonassociativity of -
122  split = color.split("+")
123  color1 = parsecolor(split[0])
124  color2 = parsecolor(split[1])
125  return color1 + color2
126 
127  if "-" in color:
128  split = color.split("-")
129  color1 = parsecolor(split[0])
130  color2 = parsecolor(split[1])
131  return color1 - color2
132 
133  raise AllInOneError("color has to be an integer, a ROOT constant (kRed, kBlue, ...), or a two-term sum or difference (kGreen-5)!")
134 
135 def parsestyle(style):
136  try: #simplest case: it's an int
137  return int(style)
138  except ValueError:
139  pass
140 
141  try: #kStar, kDot, ...
142  style = str(getattr(ROOT,style))
143  return int(style)
144  except (AttributeError, ValueError):
145  pass
146 
147  raise AllInOneError("style has to be an integer or a ROOT constant (kDashed, kStar, ...)!")
148 
150  result = [cls]
151  for subcls in cls.__subclasses__():
152  result += recursivesubclasses(subcls)
153  return result
154 
155 def cache(function):
156  cache = {}
157  def newfunction(*args, **kwargs):
158  try:
159  return cache[args, tuple(sorted(six.iteritems(kwargs)))]
160  except TypeError:
161  print(args, tuple(sorted(six.iteritems(kwargs))))
162  raise
163  except KeyError:
164  cache[args, tuple(sorted(six.iteritems(kwargs)))] = function(*args, **kwargs)
165  return newfunction(*args, **kwargs)
166  newfunction.__name__ = function.__name__
167  return newfunction
168 
169 def boolfromstring(string, name):
170  """
171  Takes a string from the configuration file
172  and makes it into a bool
173  """
174  #try as a string, not case sensitive
175  if string.lower() == "true": return True
176  if string.lower() == "false": return False
177  #try as a number
178  try:
179  return str(bool(int(string)))
180  except ValueError:
181  pass
182  #out of options
183  raise ValueError("{} has to be true or false!".format(name))
184 
185 
186 def pythonboolstring(string, name):
187  """
188  Takes a string from the configuration file
189  and makes it into a bool string for a python template
190  """
191  return str(boolfromstring(string, name))
192 
193 def cppboolstring(string, name):
194  """
195  Takes a string from the configuration file
196  and makes it into a bool string for a C++ template
197  """
198  return pythonboolstring(string, name).lower()
199 
200 conddbcode = None
201 def conddb(*args):
202  """
203  Wrapper for conddb, so that you can run
204  conddb("--db", "myfile.db", "listTags"),
205  like from the command line, without explicitly
206  dealing with all the functions in CondCore/Utilities.
207  getcommandoutput2(conddb ...) doesn't work, it imports
208  the wrong sqlalchemy in CondCore/Utilities/python/conddblib.py
209  """
210  global conddbcode
211  from tempfile import mkdtemp, NamedTemporaryFile
212 
213  if conddbcode is None:
214  conddbfile = getCommandOutput2("which conddb").strip()
215  tmpdir = mkdtemp()
216  getCommandOutput2("2to3 -f print -o " + tmpdir + " -n -w " + conddbfile)
217 
218  with open(os.path.join(tmpdir, "conddb")) as f:
219  conddb = f.read()
220 
221  conddbcode = conddb.replace("sys.exit", "sysexit")
222 
223  def sysexit(number):
224  if number != 0:
225  raise AllInOneError("conddb exited with status {}".format(number))
226  namespace = {"sysexit": sysexit, "conddboutput": ""}
227 
228  bkpargv = sys.argv
229  sys.argv[1:] = args
230  bkpstdout = sys.stdout
231  try:
232  with NamedTemporaryFile(bufsize=0) as sys.stdout:
233  exec(conddbcode, namespace)
234  namespace["main"]()
235  with open(sys.stdout.name) as f:
236  result = f.read()
237  finally:
238  sys.argv[:] = bkpargv
239  sys.stdout = bkpstdout
240 
241  return result
242 
243 
244 def clean_name(s):
245  """Transforms a string into a valid variable or method name.
246 
247  Arguments:
248  - `s`: input string
249  """
250 
251  # Remove invalid characters
252  s = re.sub(r"[^0-9a-zA-Z_]", "", s)
253 
254  # Remove leading characters until we find a letter or underscore
255  s = re.sub(r"^[^a-zA-Z_]+", "", s)
256 
257  return s
Definition: vlib.h:256
def parsestyle(style)
def pythonboolstring(string, name)
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:66
def getCommandOutput2(command)
def cppboolstring(string, name)
def addIndex(filename, njobs, index=None)
def replacelast(string, old, new, count=1)
def cache(function)
def replaceByMap(target, the_map)
— Helpers —############################
def boolfromstring(string, name)
def parsecolor(color)
def castorDirExists(path)
def recursivesubclasses(cls)
#define str(s)