signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def make_documentation_parser(**kwargs):
from vsgen import VSGSuite<EOL>return VSGSuite.make_parser(**kwargs)<EOL>
Generates the application's :class:`~argparse.ArgumentParser` instance for the documentation generator `sphinx-argparse <https://sphinx-argparse.readthedocs.io>`_
f15301:m0
def main(argv=None):
from vsgen import VSGSuite<EOL>from vsgen import VSGLogger<EOL>if argv is None:<EOL><INDENT>argv = sys.argv<EOL><DEDENT>pylogger = VSGLogger()<EOL>args = VSGSuite.make_parser(description='<STR_LIT>').parse_args(argv[<NUM_LIT:1>:])<EOL>for s in VSGSuite.from_args(**vars(args)):<EOL><INDENT>s.write(False)<EOL><DEDENT>return <NUM_LIT:0><EOL>
The entry point of the script.
f15301:m1
def __init__(self, *args, **kwargs):
kwargs.setdefault('<STR_LIT>', configparser.ExtendedInterpolation())<EOL>return super(VSGConfigParser, self).__init__(*args, **kwargs)<EOL>
Constructor :param args: List of arguments passed to the :class:`~configparser.ConfigParser` :param kwargs: List of arbitrary keyworded arguments passed to :class:`~configparser.ConfigParser`
f15302:c0:m0
def _convert_to_list(self, value, delimiters):
if not value:<EOL><INDENT>return []<EOL><DEDENT>if delimiters:<EOL><INDENT>return [l.strip() for l in value.split(delimiters)]<EOL><DEDENT>return [l.strip() for l in value.split()]<EOL>
Return a list value translating from other types if necessary. :param str value: The value to convert.
f15302:c0:m1
def _convert_to_path(self, value):
return os.path.normpath(value)<EOL>
Return a os path value translating from other types if necessary. :param str value: The value to convert.
f15302:c0:m2
def getlist(self, section, option, raw=False, vars=None, fallback=[], delimiters='<STR_LIT:U+002C>'):
v = self.get(section, option, raw=raw, vars=vars, fallback=fallback)<EOL>return self._convert_to_list(v, delimiters=delimiters)<EOL>
A convenience method which coerces the option in the specified section to a list of strings.
f15302:c0:m3
def getfile(self, section, option, raw=False, vars=None, fallback="<STR_LIT>", validate=False):
v = self.get(section, option, raw=raw, vars=vars, fallback=fallback)<EOL>v = self._convert_to_path(v)<EOL>return v if not validate or os.path.isfile(v) else fallback<EOL>
A convenience method which coerces the option in the specified section to a file.
f15302:c0:m4
def getdir(self, section, option, raw=False, vars=None, fallback="<STR_LIT>", validate=False):
v = self.get(section, option, raw=raw, vars=vars, fallback=fallback)<EOL>v = self._convert_to_path(v)<EOL>return v if not validate or os.path.isdir(v) else fallback<EOL>
A convenience method which coerces the option in the specified section to a directory.
f15302:c0:m5
def getdirs(self, section, option, raw=False, vars=None, fallback=[]):
globs = self.getlist(section, option, fallback=[])<EOL>return [f for g in globs for f in glob.glob(g) if os.path.isdir(f)]<EOL>
A convenience method which coerces the option in the specified section to a list of directories.
f15302:c0:m6
def set(self, section, option, value=None):
if isinstance(section, bytes):<EOL><INDENT>section = section.decode('<STR_LIT:utf8>')<EOL><DEDENT>if isinstance(option, bytes):<EOL><INDENT>option = option.decode('<STR_LIT:utf8>')<EOL><DEDENT>if isinstance(value, bytes):<EOL><INDENT>value = value.decode('<STR_LIT:utf8>')<EOL><DEDENT>return super(VSGConfigParser, self).set(section, option, value)<EOL>
Extends :meth:`~configparser.ConfigParser.set` by auto formatting byte strings into unicode strings.
f15302:c0:m7
def update(self, **kwargs):
<EOL>for s in config.sections():<EOL><INDENT>for o in config.options(s):<EOL><INDENT>override = kwargs.pop(o, None)<EOL>if override:<EOL><INDENT>config.set(s, o, override)<EOL><DEDENT><DEDENT><DEDENT>
Extends :meth:`~configparser.ConfigParser.set` by auto formatting byte strings into unicode strings.
f15302:c0:m8
def __init__(self, message=None):
self._message = message<EOL>self._start = <NUM_LIT:0><EOL>self._stop = <NUM_LIT:0><EOL>
Initializes the instance with an default values. :param message: The display message when using the time in a context manager (e.g the __enter__/__exit__ methods).
f15303:c0:m0
def __enter__(self):
self.start(self._message)<EOL>return self<EOL>
Convenience method to be used with Python's 'with' function. Starts the timer. Example: with VSGTimer("message") as simple_timer: ...
f15303:c0:m1
def __exit__(self, type, value, tb):
self.stop(self._message)<EOL>
Convenience method to be used with Python's 'with' function. Stops the timer initiated with the __enter__ method.
f15303:c0:m2
def start(self, message):
self._start = time.clock()<EOL>VSGLogger.info("<STR_LIT>".format(message))<EOL>
Manually starts timer with the message. :param message: The display message.
f15303:c0:m3
def stop(self, message):
self._stop = time.clock()<EOL>VSGLogger.info("<STR_LIT>".format(message, self.pprint(self._stop - self._start)))<EOL>
Manually stops timer with the message. :param message: The display message.
f15303:c0:m4
def pprint(self, seconds):
return ("<STR_LIT>", reduce(lambda ll, b: divmod(ll[<NUM_LIT:0>], b) + ll[<NUM_LIT:1>:], [(seconds * <NUM_LIT:1000>,), <NUM_LIT:1000>, <NUM_LIT>, <NUM_LIT>]))<EOL>
Pretty Prints seconds as Hours:Minutes:Seconds.MilliSeconds :param seconds: The time in seconds.
f15303:c0:m5
def entrypoints(section):
return {ep.name: ep.load() for ep in pkg_resources.iter_entry_points(section)}<EOL>
Returns the Entry Point for a given Entry Point section. :param str section: The section name in the entry point collection :returns: A dictionary of (Name, Class) pairs stored in the entry point collection.
f15304:m0
def entrypoint(section, option):
try:<EOL><INDENT>return entrypoints(section)[option]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise KeyError('<STR_LIT>'.format(option, section))<EOL><DEDENT>
Returns the the entry point object given a section, option pair. :param str section: The section name in the entry point collection :param str option: The option name in the entry point collection :return: The entry point object if available.
f15304:m1
def __init__(self, filepath=None, threshold=logging.INFO):
<EOL>self._logger = self.getLogger(None)<EOL>self._logger.setLevel(threshold)<EOL>self._fileHandlers = []<EOL>self._handlers = []<EOL>stdoutHandler = logging.StreamHandler(sys.stdout)<EOL>stdoutHandler.setFormatter(logging.Formatter("<STR_LIT>"))<EOL>stdoutHandler.addFilter(VSGLogger.LevelFilter([logging.DEBUG, logging.INFO, logging.WARNING]))<EOL>self._registerHandler(stdoutHandler)<EOL>stderrHandler = logging.StreamHandler(sys.stderr)<EOL>stderrHandler.setFormatter(logging.Formatter("<STR_LIT>"))<EOL>stderrHandler.addFilter(VSGLogger.LevelFilter([logging.ERROR, logging.CRITICAL]))<EOL>self._registerHandler(stderrHandler)<EOL>if filepath:<EOL><INDENT>fileHandler = logging.FileHandler(filepath, '<STR_LIT:a>')<EOL>fileHandler.setFormatter(logging.Formatter("<STR_LIT>", "<STR_LIT>"))<EOL>self._registerHandler(fileHandler)<EOL><DEDENT>
Creates a logger with the given name (the name prefixes each log line). :param filepath: The optional output path for the logger messages. :param threshold: The threshold for messages; logging messages which are less severe than 'threshold' will be ignored.
f15306:c0:m0
def __del__(self):
self.close()<EOL>
Destructor.
f15306:c0:m1
def _registerHandler(self, handler):
self._logger.addHandler(handler)<EOL>self._handlers.append(handler)<EOL>
Registers a handler. :param handler: A handler object.
f15306:c0:m2
def _unregisterHandler(self, handler, shutdown=True):
if handler in self._handlers:<EOL><INDENT>self._handlers.remove(handler)<EOL>self._logger.removeHandler(handler)<EOL>if shutdown:<EOL><INDENT>try:<EOL><INDENT>handler.close()<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>
Unregisters the logging handler. :param handler: A handler previously registered with this loggger. :param shutdown: Flag to shutdown the handler.
f15306:c0:m3
@classmethod<EOL><INDENT>def getLogger(cls, name=None):<DEDENT>
return logging.getLogger("<STR_LIT>".format(cls.BASENAME, name) if name else cls.BASENAME)<EOL>
Retrieves the Python native logger :param name: The name of the logger instance in the VSG namespace (VSG.<name>); a None value will use the VSG root. :return: The instacne of the Python logger object.
f15306:c0:m4
@classmethod<EOL><INDENT>def debug(cls, name, message, *args):<DEDENT>
cls.getLogger(name).debug(message, *args)<EOL>
Convenience function to log a message at the DEBUG level. :param name: The name of the logger instance in the VSG namespace (VSG.<name>) :param message: A message format string. :param args: The arguments that are are merged into msg using the string formatting operator. :..note: The native logger's `kwargs` are not used in this function.
f15306:c0:m5
@classmethod<EOL><INDENT>def info(cls, name, message, *args):<DEDENT>
cls.getLogger(name).info(message, *args)<EOL>
Convenience function to log a message at the INFO level. :param name: The name of the logger instance in the VSG namespace (VSG.<name>) :param message: A message format string. :param args: The arguments that are are merged into msg using the string formatting operator. :..note: The native logger's `kwargs` are not used in this function.
f15306:c0:m6
@classmethod<EOL><INDENT>def warning(cls, name, message, *args):<DEDENT>
cls.getLogger(name).warning(message, *args)<EOL>
Convenience function to log a message at the WARNING level. :param name: The name of the logger instance in the VSG namespace (VSG.<name>) :param message: A message format string. :param args: The arguments that are are merged into msg using the string formatting operator. :..note: The native logger's `kwargs` are not used in this function.
f15306:c0:m7
@classmethod<EOL><INDENT>def error(cls, name, message, *args):<DEDENT>
cls.getLogger(name).error(message, *args)<EOL>
Convenience function to log a message at the ERROR level. :param name: The name of the logger instance in the VSG namespace (VSG.<name>) :param message: A message format string. :param args: The arguments that are are merged into msg using the string formatting operator. :..note: The native logger's `kwargs` are not used in this function.
f15306:c0:m8
@classmethod<EOL><INDENT>def critical(cls, name, message, *args):<DEDENT>
cls.getLogger(name).critical(message, *args)<EOL>
Convenience function to log a message at the CRITICAL level. :param name: The name of the logger instance in the VSG namespace (VSG.<name>) :param message: A message format string. :param args: The arguments that are are merged into msg using the string formatting operator. :..note: The native logger's `kwargs` are not used in this function.
f15306:c0:m9
@classmethod<EOL><INDENT>def exception(cls, name, message, *args):<DEDENT>
cls.getLogger(name).exception(message, *args)<EOL>
Convenience function to log a message at the ERROR level with additonal exception information. :param name: The name of the logger instance in the VSG namespace (VSG.<name>) :param message: A message format string. :param args: The arguments that are are merged into msg using the string formatting operator. :..note: This method should only be called from an exception handler.
f15306:c0:m10
def close(self):
while self._handlers:<EOL><INDENT>self._unregisterHandler(self._handlers[<NUM_LIT:0>])<EOL><DEDENT>
Closes and unregisters all logging handlers.
f15306:c0:m11
def register(self):
raise NotImplementedError("<STR_LIT>")<EOL>
Interface method to 'register' the object.
f15308:c0:m0
def text(self, value):
return unicode(value) if sys.version_info < (<NUM_LIT:3>,) else str(value)<EOL>
Converts a value to text in a way compatible with Python2 and Python 3. :param object value: The value to convert. :return: The value as text.
f15308:c0:m1
def upper(self, value):
return self.text(value).upper()<EOL>
Converts a value to upper case text in a way compatible with Python2 and Python 3. :param object value: The value to convert. :return: The value as upper case text.
f15308:c0:m2
def lower(self, value):
return self.text(value).lower()<EOL>
Converts a value to lower case in a way compatible with Python2 and Python 3. :param object value: The value to convert. :return: The value as lower case text.
f15308:c0:m3
def __init__(self, logname, registerables):
self._logname = logname<EOL>self._registerables = registerables<EOL>registerables_names = set([r.__registerable_name__ for r in registerables])<EOL>if not registerables_names:<EOL><INDENT>self._message = "<STR_LIT>"<EOL><DEDENT>elif len(registerables_names) == <NUM_LIT:1>:<EOL><INDENT>self._message = "<STR_LIT>".format(next(iter(registerables_names)), '<STR_LIT:s>' if len(registerables) > <NUM_LIT:1> else '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>self._message = "<STR_LIT>"<EOL><DEDENT>
Initializes the instance with an collection of registerables. :param str logname: The python logger log name. :param list registerables: The list of VSGRegisterable class instances.
f15308:c1:m0
def __enter__(self):
return self<EOL>
Enter the runtime context related to this object.
f15308:c1:m1
def __exit__(self, exc_type, exc_value, exc_traceback):
<EOL>return False<EOL>
Exit the runtime context related to this object.
f15308:c1:m2
def execute(self):
from vsgen.util.logger import VSGLogger<EOL>VSGLogger.info(self._logname, self._message)<EOL>start = time.clock()<EOL>for i in self._registerables:<EOL><INDENT>i.register()<EOL><DEDENT>end = time.clock()<EOL>VSGLogger.info(self._logname, "<STR_LIT>", len(self._registerables), end - start)<EOL>self._start = time.clock()<EOL>
Executes the command.
f15308:c1:m3
def __init__(self, config):
<EOL>root = config.get('<STR_LIT>', '<STR_LIT:root>', fallback=None)<EOL>if not root:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if not os.path.isdir(root):<EOL><INDENT>raise ValueError('<STR_LIT>' % root)<EOL><DEDENT>self._solutions = [self._getsolution(config, s) for s in config.sections() if '<STR_LIT>' in s]<EOL>return super(VSGSuite, self).__init__()<EOL>
Constructor. :param object config: The instance of the VSGConfigParser class
f15309:c0:m0
def _getsolution(self, config, section, **kwargs):
if section not in config:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(section, '<STR_LIT:U+002CU+0020>'.join(config.sections())))<EOL><DEDENT>s = VSGSolution(**kwargs)<EOL>s.Name = config.get(section, '<STR_LIT:name>', fallback=s.Name)<EOL>s.FileName = os.path.normpath(config.get(section, '<STR_LIT:filename>', fallback=s.FileName))<EOL>s.VSVersion = config.getfloat(section, '<STR_LIT>', fallback=s.VSVersion)<EOL>if not s.VSVersion:<EOL><INDENT>raise ValueError('<STR_LIT>' % section)<EOL><DEDENT>project_sections = config.getlist(section, '<STR_LIT>', fallback=[])<EOL>for project_section in project_sections:<EOL><INDENT>project = self._getproject(config, project_section, VSVersion=s.VSVersion)<EOL>s.Projects.append(project)<EOL><DEDENT>return s<EOL>
Creates a VSG solution from a configparser instance. :param object config: The instance of the configparser class :param str section: The section name to read. :param kwargs: List of additional keyworded arguments to be passed into the VSGSolution. :return: A valid VSGSolution instance if succesful; None otherwise.
f15309:c0:m1
def _getproject(self, config, section, **kwargs):
if section not in config:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(section, '<STR_LIT:U+002CU+0020>'.join(config.sections())))<EOL><DEDENT>type = config.get(section, '<STR_LIT:type>', fallback=None)<EOL>if not type:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(section, "<STR_LIT:type>"))<EOL><DEDENT>project_class = entrypoint('<STR_LIT>', type)<EOL>return project_class.from_section(config, section, **kwargs)<EOL>
Creates a VSG project from a configparser instance. :param object config: The instance of the configparser class :param str section: The section name to read. :param kwargs: List of additional keyworded arguments to be passed into the VSGProject. :return: A valid VSGProject instance if succesful; None otherwise.
f15309:c0:m2
@classmethod<EOL><INDENT>def from_file(cls, filename):<DEDENT>
<EOL>config = VSGConfigParser()<EOL>if filename not in config.read([filename]):<EOL><INDENT>raise ValueError('<STR_LIT>' % filename)<EOL><DEDENT>root = config.get('<STR_LIT>', '<STR_LIT:root>')<EOL>root = os.path.normpath(os.path.join(os.path.dirname(filename), root))<EOL>config.set('<STR_LIT>', '<STR_LIT:root>', root)<EOL>return VSGSuite(config)<EOL>
Creates an VSGSuite instance from a filename. :param str filename: The fully qualified path to the VSG configuration file.
f15309:c0:m3
@classmethod<EOL><INDENT>def make_parser(cls, **kwargs):<DEDENT>
<EOL>parser = argparse.ArgumentParser(**kwargs)<EOL>subparsers = parser.add_subparsers(help='<STR_LIT>', dest='<STR_LIT>')<EOL>file_parser = subparsers.add_parser('<STR_LIT>', help='<STR_LIT>')<EOL>file_parser.add_argument('<STR_LIT>', metavar='<STR_LIT:file>', nargs='<STR_LIT:+>', help='<STR_LIT>')<EOL>auto_parser = subparsers.add_parser('<STR_LIT>', help='<STR_LIT>')<EOL>suite_parsers = auto_parser.add_subparsers(help='<STR_LIT>', dest='<STR_LIT>')<EOL>for ek, ev in entrypoints('<STR_LIT>').items():<EOL><INDENT>suite_parser = ev.make_parser(add_help=False)<EOL>suite_parsers.add_parser(ek, help='<STR_LIT>'.format(ek), parents=[suite_parser])<EOL><DEDENT>return parser<EOL>
Creates a :class:`~argparse.ArgumentParser` instances to work with VSGSuite classes. :param kwargs: List of additional keyworded arguments to be passed into the :class:`~argparse.ArgumentParser`. :return: A :class:`~argparse.ArgumentParser` instance.
f15309:c0:m4
@classmethod<EOL><INDENT>def from_args(cls, **kwargs):<DEDENT>
<EOL>if kwargs.get('<STR_LIT>', None) == '<STR_LIT>':<EOL><INDENT>filenames = kwargs.pop('<STR_LIT>', [])<EOL>return [cls.from_file(f) for f in filenames]<EOL><DEDENT>if kwargs.get('<STR_LIT>', None) == '<STR_LIT>':<EOL><INDENT>type = kwargs.get('<STR_LIT>', None)<EOL>return [cls.from_directory('<STR_LIT>', type, **kwargs)]<EOL><DEDENT>return []<EOL>
Generates one or more VSGSuite instances from command line arguments. :param kwargs: List of additional keyworded arguments to be passed into the VSGSuite defined in the :meth:`~VSGSuite.make_parser` method.
f15309:c0:m5
@classmethod<EOL><INDENT>def from_directory(cls, directory, type, **kwargs):<DEDENT>
<EOL>suite_class = entrypoint('<STR_LIT>', type)<EOL>params = {<EOL>'<STR_LIT:root>': os.path.abspath(directory),<EOL>'<STR_LIT:name>': os.path.basename(os.path.abspath(directory))<EOL>}<EOL>params.update({k: v for k, v in kwargs.items() if v is not None})<EOL>return suite_class(**params)<EOL>
Creates an VSGSuite instance from a filename. :param str filename: The fully qualified path to the VSG configuration file. :param str type: The configuration type to generate. :param kwargs: List of additional keyworded arguments to be passed into the VSGSuite.
f15309:c0:m6
def write(self, parallel=True):
<EOL>solutions = sorted(self._solutions, key=lambda x: x.Name)<EOL>with VSGWriteCommand('<STR_LIT>', solutions, parallel) as command:<EOL><INDENT>command.execute()<EOL><DEDENT>projects = set(sorted((p for s in solutions for p in s.Projects), key=lambda x: x.Name))<EOL>with VSGWriteCommand('<STR_LIT>', projects, parallel) as command:<EOL><INDENT>command.execute()<EOL><DEDENT>registerables = set(sorted((p for s in solutions for p in s.Projects), key=lambda x: x.Name))<EOL>with VSGRegisterCommand('<STR_LIT>', registerables) as command:<EOL><INDENT>command.execute()<EOL><DEDENT>
Writes the configuration to disk.
f15309:c0:m7
def render(self, template, filename, context={}, filters={}):
filename = os.path.normpath(filename)<EOL>path, file = os.path.split(filename)<EOL>try:<EOL><INDENT>os.makedirs(path)<EOL><DEDENT>except OSError as exception:<EOL><INDENT>if exception.errno != errno.EEXIST:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>path, file = os.path.split(template)<EOL>loader = jinja2.FileSystemLoader(path)<EOL>env = jinja2.Environment(loader=loader, trim_blocks=True, lstrip_blocks=True)<EOL>env.filters.update(filters)<EOL>template = env.get_template(file)<EOL>text = template.render(context)<EOL>with open(filename, '<STR_LIT>') as f:<EOL><INDENT>f.write(text)<EOL><DEDENT>
Renders a Jinja2 template to text.
f15310:c0:m0
def write(self):
raise NotImplementedError("<STR_LIT>")<EOL>
Interface method to 'write' the object.
f15310:c1:m0
def text(self, value):
return unicode(value) if sys.version_info < (<NUM_LIT:3>,) else str(value)<EOL>
Converts a value to text in a way compatible with Python2 and Python 3. :param object value: The value to convert. :return: The value as text.
f15310:c1:m1
def upper(self, value):
return self.text(value).upper()<EOL>
Converts a value to upper case text in a way compatible with Python2 and Python 3. :param object value: The value to convert. :return: The value as upper case text.
f15310:c1:m2
def lower(self, value):
return self.text(value).lower()<EOL>
Converts a value to lower case in a way compatible with Python2 and Python 3. :param object value: The value to convert. :return: The value as lower case text.
f15310:c1:m3
def __init__(self, logname, writables, parallel=True):
self._logname = logname<EOL>self._writables = writables<EOL>self._parallel = parallel<EOL>writables_names = set([w.__writable_name__ for w in writables])<EOL>if not writables_names:<EOL><INDENT>self._message = "<STR_LIT>"<EOL><DEDENT>elif len(writables_names) == <NUM_LIT:1>:<EOL><INDENT>self._message = "<STR_LIT>".format(next(iter(writables_names)), '<STR_LIT:s>' if len(writables) > <NUM_LIT:1> else '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>self._message = "<STR_LIT>"<EOL><DEDENT>
Initializes the instance with an default values. :param str logname: The python logger log name. :param list writables: The list of VSGWritable class instances. :param bool parallel: Flag to enable asynchronous writing.
f15310:c2:m0
def __enter__(self):
return self<EOL>
Enter the runtime context related to this object.
f15310:c2:m1
def __exit__(self, exc_type, exc_value, exc_traceback):
<EOL>return False<EOL>
Exit the runtime context related to this object.
f15310:c2:m2
def execute(self):
from vsgen.util.logger import VSGLogger<EOL>VSGLogger.info(self._logname, self._message)<EOL>start = time.clock()<EOL>VSGWriter.write(self._writables, self._parallel)<EOL>end = time.clock()<EOL>VSGLogger.info(self._logname, "<STR_LIT>", len(self._writables), end - start)<EOL>
Executes the command.
f15310:c2:m3
def __init__(self, pylist):
threading.Thread.__init__(self)<EOL>if not hasattr(pylist, '<STR_LIT>'):<EOL><INDENT>self._pylist = [pylist]<EOL><DEDENT>else:<EOL><INDENT>self._pylist = pylist<EOL><DEDENT>
VSGProject encapsulates the logic needed to create a *.pyproject file. :param list pylist: A list of VSG objects[PrProjects, VSGSolutions, etc]
f15310:c3:m0
def run(self):
for pyitem in self._pylist:<EOL><INDENT>pyitem.write()<EOL><DEDENT>
The Thread's execution function.
f15310:c3:m1
@staticmethod<EOL><INDENT>def write(pylist, parallel=True):<DEDENT>
threads = [VSGWriter(o) for o in pylist]<EOL>if parallel:<EOL><INDENT>for t in threads:<EOL><INDENT>t.start()<EOL><DEDENT>for t in threads:<EOL><INDENT>t.join()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for t in threads:<EOL><INDENT>t.run()<EOL><DEDENT><DEDENT>
Utility method to spawn a VSGWriter for each element in a collection. :param list pylist: A list of VSG objects (PrProjects, VSGSolutions, etc) :param bool parallel: Flag to enable asynchronous writing.
f15310:c3:m2
def __init__(self, **kwargs):
super(VSGProject, self).__init__()<EOL>self._import(kwargs)<EOL>
Constructor. :param kwargs: List of arbitrary keyworded arguments to be processed as instance variable data
f15311:c0:m0
def _import(self, datadict):
self.GUID = datadict.get("<STR_LIT>", uuid.uuid1())<EOL>self.FileName = datadict.get("<STR_LIT>", "<STR_LIT>")<EOL>self.Name = datadict.get("<STR_LIT:Name>", "<STR_LIT>")<EOL>self.WorkingDirectory = datadict.get("<STR_LIT>", "<STR_LIT>")<EOL>self.OutputPath = datadict.get("<STR_LIT>", "<STR_LIT>")<EOL>self.RootNamespace = datadict.get("<STR_LIT>", "<STR_LIT>")<EOL>self.ProjectHome = datadict.get("<STR_LIT>", "<STR_LIT>")<EOL>self.StartupFile = datadict.get("<STR_LIT>", "<STR_LIT>")<EOL>self.CompileFiles = datadict.get("<STR_LIT>", [])<EOL>self.ContentFiles = datadict.get("<STR_LIT>", [])<EOL>self.Directories = datadict.get("<STR_LIT>", [])<EOL>self.DirectoryInFilter = datadict.get("<STR_LIT>", [])<EOL>self.DirectoryExFilter = datadict.get("<STR_LIT>", [])<EOL>self.CompileInFilter = datadict.get("<STR_LIT>", [])<EOL>self.CompileExFilter = datadict.get("<STR_LIT>", [])<EOL>self.ContentInFilter = datadict.get("<STR_LIT>", [])<EOL>self.ContentExFilter = datadict.get("<STR_LIT>", [])<EOL>self.VSVersion = datadict.get("<STR_LIT>", None)<EOL>
Internal method to import instance variables data from a dictionary :param dict datadict: The dictionary containing variables values.
f15311:c0:m1
@classmethod<EOL><INDENT>def from_section(cls, config, section, **kwargs):<DEDENT>
p = cls(**kwargs)<EOL>p.Name = config.get(section, '<STR_LIT:name>', fallback=p.Name)<EOL>p.FileName = config.getfile(section, '<STR_LIT:filename>', fallback=p.FileName)<EOL>p.SearchPath = config.getdirs(section, '<STR_LIT>', fallback=p.SearchPath)<EOL>p.OutputPath = config.getdir(section, '<STR_LIT>', fallback=p.OutputPath)<EOL>p.WorkingDirectory = config.getdir(section, '<STR_LIT>', fallback=p.WorkingDirectory)<EOL>p.RootNamespace = config.get(section, '<STR_LIT>', fallback=p.RootNamespace)<EOL>p.ProjectHome = config.getdir(section, '<STR_LIT>', fallback=p.ProjectHome)<EOL>p.StartupFile = config.getfile(section, '<STR_LIT>', fallback=p.StartupFile)<EOL>p.CompileFiles = config.getlist(section, '<STR_LIT>', fallback=p.CompileFiles)<EOL>p.ContentFiles = config.getlist(section, '<STR_LIT>', fallback=p.ContentFiles)<EOL>p.CompileInFilter = config.getlist(section, '<STR_LIT>', fallback=p.CompileInFilter)<EOL>p.CompileExFilter = config.getlist(section, '<STR_LIT>', fallback=p.CompileExFilter)<EOL>p.ContentInFilter = config.getlist(section, '<STR_LIT>', fallback=p.ContentInFilter)<EOL>p.ContentExFilter = config.getlist(section, '<STR_LIT>', fallback=p.ContentExFilter)<EOL>p.DirectoryInFilter = config.getlist(section, '<STR_LIT>', fallback=p.DirectoryInFilter)<EOL>p.DirectoryExFilter = config.getlist(section, '<STR_LIT>', fallback=p.DirectoryExFilter)<EOL>root_path = config.get(section, '<STR_LIT>', fallback="<STR_LIT>")<EOL>p.insert_files(root_path)<EOL>return p<EOL>
Creates a :class:`~vsgen.project.VSGProject` from a :class:`~configparser.ConfigParser` section. :param ConfigParser config: A :class:`~configparser.ConfigParser` instance. :param str section: A :class:`~configparser.ConfigParser` section key. :param kwargs: List of additional keyworded arguments to be passed into the :class:`~vsgen.project.VSGProject`. :return: A valid :class:`~vsgen.project.VSGProject` instance if succesful; None otherwise.
f15311:c0:m2
@property<EOL><INDENT>def ProjectHomeRelative(self):<DEDENT>
return os.path.relpath(self.ProjectHome, os.path.dirname(self.FileName))<EOL>
Returns the :attr:`ProjectHome` relative to :attr:`FileName` directory.
f15311:c0:m3
@property<EOL><INDENT>def StartupFileRelative(self):<DEDENT>
return os.path.relpath(self.StartupFile, self.ProjectHome) if self.StartupFile else self.StartupFile<EOL>
Returns the :attr:`StartupFile` relative to :attr:`ProjectHome` directory.
f15311:c0:m4
@property<EOL><INDENT>def WorkingDirectoryRelative(self):<DEDENT>
return os.path.relpath(self.WorkingDirectory, self.ProjectHome)<EOL>
Returns the :attr:`WorkingDirectory` relative to :attr:`ProjectHome` directory.
f15311:c0:m5
@property<EOL><INDENT>def OutputPathRelative(self):<DEDENT>
return os.path.relpath(self.OutputPath, self.ProjectHome)<EOL>
Returns the :attr:`OutputPath` relative to :attr:`ProjectHome` directory.
f15311:c0:m6
@property<EOL><INDENT>def ContentFilesRelative(self):<DEDENT>
return (os.path.relpath(path, self.ProjectHome) for path in sorted(self.ContentFiles, key=self.lower))<EOL>
Returns a generator iterating over the each file in :attr:`ContentFiles` relative to :attr:`ProjectHome` directory.
f15311:c0:m7
@property<EOL><INDENT>def CompileFilesRelative(self):<DEDENT>
return (os.path.relpath(path, self.ProjectHome) for path in sorted(self.CompileFiles, key=self.lower))<EOL>
Returns a generator iterating over the each file in :attr:`ContentFiles` relative to :attr:`ProjectHome` directory.
f15311:c0:m8
@property<EOL><INDENT>def DirectoriesRelative(self):<DEDENT>
<EOL>directories = itertools.chain(self.Directories, (os.path.dirname(f) for f in itertools.chain(self.ContentFiles, self.CompileFiles)))<EOL>directories = set(os.path.relpath(d, self.ProjectHome) for d in directories)<EOL>for path in set(directories):<EOL><INDENT>subpath = os.path.dirname(path)<EOL>while subpath:<EOL><INDENT>directories.add(subpath)<EOL>subpath = os.path.dirname(subpath)<EOL><DEDENT><DEDENT>return sorted(directories)<EOL>
Returns a generator iterating over the each directory referenced by the project, relative to :attr:`ProjectHome` directory.
f15311:c0:m9
def insert_files(self, rootpath, directoryInFilter=None, directoryExFilter=None, compileInFilter=None, compileExFilter=None, contentInFilter=None, contentExFilter=None):
<EOL>directoryInFilter = self.DirectoryInFilter if directoryInFilter is None else directoryInFilter<EOL>directoryExFilter = self.DirectoryExFilter if directoryExFilter is None else directoryExFilter<EOL>compileInFilter = self.CompileInFilter if compileInFilter is None else compileInFilter<EOL>compileExFilter = self.CompileExFilter if compileExFilter is None else compileExFilter<EOL>contentInFilter = self.ContentInFilter if contentInFilter is None else contentInFilter<EOL>contentExFilter = self.ContentExFilter if contentExFilter is None else contentExFilter<EOL>def filter(text, filters, explicit):<EOL><INDENT>"""<STR_LIT>"""<EOL>if explicit:<EOL><INDENT>return any(fnmatch.fnmatch(text, f) for f in filters)<EOL><DEDENT>return not filters or any(fnmatch.fnmatch(text, f) for f in filters)<EOL><DEDENT>for root, dirnames, filenames in os.walk(rootpath):<EOL><INDENT>searchdir = os.path.normpath(os.path.normcase(root))<EOL>if filter(searchdir, directoryExFilter, True):<EOL><INDENT>dirnames[:] = []<EOL><DEDENT>elif filter(searchdir, directoryInFilter, False):<EOL><INDENT>for filepath in [os.path.join(root, filename) for filename in filenames]:<EOL><INDENT>if filter(filepath, compileInFilter, False) and not filter(filepath, compileExFilter, True):<EOL><INDENT>self.CompileFiles.append(filepath)<EOL><DEDENT>elif filter(filepath, contentInFilter, False) and not filter(filepath, contentExFilter, True):<EOL><INDENT>self.ContentFiles.append(filepath)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>
Inserts files by recursive traversing the rootpath and inserting files according the addition filter parameters. :param str rootpath: The absolute path to the root directory. :param list directoryInFilter: A list of fnmatch expressions to match directories to be included. A `None` value will default to :attr:`DirectoryInFilter`. :param list directoryExFilter: A list of fnmatch expressions to match directories to be excluded. A `None` value will default to :attr:`DirectoryExFilter`. :param list compileInFilter: A list of fnmatch expressions to match compile files to be included. A `None` value will default to :attr:`CompileInFilter`. :param list compileExFilter: A list of fnmatch expressions to match compile files to be excludes. A `None` value will default to :attr:`CompileExFilter`. :param list contentInFilter: A list of fnmatch expressions to match content files to be includes. A `None` value will default to :attr:`ContentInFilter`. :param list contentExFilter: A list of fnmatch expressions to match content files to be excludes. A `None` value will default to :attr:`ContentExFilter`.
f15311:c0:m10
def __init__(self, **kwargs):
super(VSGSolution, self).__init__()<EOL>self._import(kwargs)<EOL>
Constructor. :param kwargs: List of arbitrary keyworded arguments to be processed as instance variable data
f15312:c0:m0
def _import(self, datadict):
self.GUID = datadict.get("<STR_LIT>", uuid.uuid1())<EOL>self.FileName = datadict.get("<STR_LIT>", "<STR_LIT>")<EOL>self.Name = datadict.get("<STR_LIT:Name>", "<STR_LIT>")<EOL>self.Projects = datadict.get("<STR_LIT>", [])<EOL>self.VSVersion = datadict.get("<STR_LIT>", None)<EOL>
Internal method to import instance variables data from a dictionary :param dict datadict: The dictionary containing variables values.
f15312:c0:m1
def write(self):
filters = {<EOL>'<STR_LIT>': lambda x: ('<STR_LIT>' % x).upper(),<EOL>'<STR_LIT>': lambda x: os.path.relpath(x, os.path.dirname(self.FileName))<EOL>}<EOL>context = {<EOL>'<STR_LIT>': self<EOL>}<EOL>return self.render(self.__jinja_template__, self.FileName, context, filters)<EOL>
Writes the ``.sln`` file to disk.
f15312:c0:m2
@register.filter<EOL>def themeble(value):
return (value.replace('<STR_LIT>', config.CURRENT_THEME or '<STR_LIT>')<EOL>.replace('<STR_LIT>', config.DEFAULT_THEME or '<STR_LIT>'))<EOL>
Replace the keyword in the `value` on the name of active theme. Example: {% static 'img/THEME/logo.png'|themeble %} == {% static 'img/cool_theme/logo.png' %} # if CURRENT_THEME == 'cool_theme'
f15315:m0
@property<EOL><INDENT>def CURRENT_THEME(self):<DEDENT>
return getattr(self.source, '<STR_LIT>', None)<EOL>
Trying to getting `CURRENT_THEME` parameter from settings or os env.
f15318:c0:m1
@property<EOL><INDENT>def CURRENT_THEME(self):<DEDENT>
return os.environ.get('<STR_LIT>', None)<EOL>
Trying to getting `CURRENT_THEME` parameter from settings or os env.
f15318:c1:m0
def load_object(s):
try:<EOL><INDENT>m_path, o_name = s.rsplit('<STR_LIT:.>', <NUM_LIT:1>)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ImportError('<STR_LIT>'.format(s))<EOL><DEDENT>module = import_module(m_path)<EOL>return getattr(module, o_name)<EOL>
Load backend by dotted path.
f15323:m0
def get_available_themes():
for d in settings.TEMPLATE_DIRS:<EOL><INDENT>for _d in os.listdir(d):<EOL><INDENT>if os.path.isdir(os.path.join(d, _d)) and is_theme_dir(_d):<EOL><INDENT>yield _d<EOL><DEDENT><DEDENT><DEDENT>
Iterator on available themes
f15323:m1
def themeble(name, themes=None, global_context=None):
def wrap(obj):<EOL><INDENT>context = global_context or inspect.stack()[<NUM_LIT:1>][<NUM_LIT:0>].f_globals<EOL>if name in context and not getattr(context[name], '<STR_LIT>', False):<EOL><INDENT>raise RuntimeError(<EOL>'<STR_LIT>'.format(name))<EOL><DEDENT>if ((themes and settings.CURRENT_THEME in themes) or<EOL>(themes is None and name not in context)):<EOL><INDENT>context[name] = obj<EOL>obj.__themeble = True<EOL><DEDENT>return obj<EOL><DEDENT>return wrap<EOL>
Decorator for registering objects (i.e. functions, classes) for different themes. Params: * name - type of string. New global name for object * themes - for this themes ``obj`` will be have alias with given name * global_context - current decorator's global context Example: .. code:: python # my_app.forms.py @themeble(name='Form', themes=('dark_theme',)) class DarkThemeForm(object): ''' Some kind of logic for dark_theme ''' name = 'DarkThemeForm' @themeble(name='Form') class DefaultForm(object): ''' Default logic for all themes ''' name = 'Default form' Now if settings.CURRENT_THEME == 'dark_theme': .. code:: python # my_app.views.py from my_app.forms import Form assert Form.name == 'DarkThemeForm'
f15324:m0
def only_for(theme, redirect_to='<STR_LIT:/>', raise_error=None):
def check_theme(*args, **kwargs):<EOL><INDENT>if isinstance(theme, six.string_types):<EOL><INDENT>themes = (theme,)<EOL><DEDENT>else:<EOL><INDENT>themes = theme<EOL><DEDENT>if settings.CURRENT_THEME is None:<EOL><INDENT>return True<EOL><DEDENT>result = settings.CURRENT_THEME in themes<EOL>if not result and raise_error is not None:<EOL><INDENT>raise raise_error<EOL><DEDENT>return result<EOL><DEDENT>return user_passes_test(check_theme, login_url=redirect_to)<EOL>
Decorator for restrict access to views according by list of themes. Params: * ``theme`` - string or list of themes where decorated view must be * ``redirect_to`` - url or name of url pattern for redirect if CURRENT_THEME not in themes * ``raise_error`` - error class for raising Example: .. code:: python # views.py from django_vest import only_for @only_for('black_theme') def my_view(request): ...
f15324:m1
def _check_is_dark_theme(self):
response = self.client.get('<STR_LIT:/>')<EOL>self.assertEqual(response.status_code, <NUM_LIT:200>)<EOL>templates = get_templates_used(response)<EOL>self.assertEqual(len(templates), <NUM_LIT:2>)<EOL>self.assertIn('<STR_LIT>', templates)<EOL>self.assertIn('<STR_LIT>', templates)<EOL>
Common checks for `dark_theme`
f15326:c0:m6
def setUpModule():
assert not os.path.exists(TEST_CACHE_DIR), (<EOL>'<STR_LIT>' + TEST_CACHE_DIR + '<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' + TEST_CACHE_DIR<EOL>+ '<STR_LIT>')<EOL>
Before running the test suite, check that TEST_CACHE_DIR does not already exist - as the tests will delete it.
f15342:m0
def setUp(self):
try:<EOL><INDENT>os.makedirs(TEST_CACHE_DIR)<EOL><DEDENT>except FileExistsError:<EOL><INDENT>pass<EOL><DEDENT>
Make a temporary directory for saving test results.
f15342:c0:m0
def tearDown(self):
try:<EOL><INDENT>shutil.rmtree(TEST_CACHE_DIR)<EOL><DEDENT>except OSError:<EOL><INDENT>pass<EOL><DEDENT>
Remove any caches saved by the tests.
f15342:c0:m1
def setUp(self):
try:<EOL><INDENT>os.makedirs(TEST_CACHE_DIR)<EOL><DEDENT>except FileExistsError:<EOL><INDENT>pass<EOL><DEDENT>
Make a temporary directory for saving test results.
f15342:c1:m0
def tearDown(self):
try:<EOL><INDENT>shutil.rmtree(TEST_CACHE_DIR)<EOL><DEDENT>except OSError:<EOL><INDENT>pass<EOL><DEDENT>
Remove any caches saved by the tests.
f15342:c1:m1
def setUp(self):
self.test_data = np.random.random(<NUM_LIT:10>)<EOL>@nestcheck.io_utils.save_load_result<EOL>def io_func(data):<EOL><INDENT>"""<STR_LIT>"""<EOL>return data<EOL><DEDENT>self.io_func = io_func<EOL>
Get some data data for io testing. Note that the saving function in io_utils makes the specified directory if it does not already exist, so there is no need to make it in setUp.
f15342:c3:m0
def tearDown(self):
try:<EOL><INDENT>shutil.rmtree(TEST_CACHE_DIR)<EOL><DEDENT>except OSError:<EOL><INDENT>pass<EOL><DEDENT>
Remove any caches saved by the tests.
f15342:c3:m1
def setUp(self):
self.ns_run = nestcheck.dummy_data.get_dummy_run(<NUM_LIT:3>, <NUM_LIT:10>)<EOL>nestcheck.ns_run_utils.check_ns_run(self.ns_run)<EOL>
Get some dummy data to plot.
f15343:c0:m0
def setUpModule():
assert not os.path.exists(TEST_CACHE_DIR), (<EOL>'<STR_LIT>' + TEST_CACHE_DIR + '<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' + TEST_CACHE_DIR<EOL>+ '<STR_LIT>')<EOL>
Before running the test suite, check that TEST_CACHE_DIR does not already exist - as the tests will delete it.
f15344:m0
def parallel_apply_func(x, arg, kwarg=-<NUM_LIT:1>):
return np.asarray([x, arg, kwarg])<EOL>
A test function for checking parallel_apply. Must be defined at module level to make it picklable.
f15344:m1
def setUp(self):
self.nrows = <NUM_LIT:100><EOL>self.ncols = <NUM_LIT:3><EOL>self.data = np.random.random((self.nrows, self.ncols))<EOL>self.col_names = ['<STR_LIT>']<EOL>self.col_names += ['<STR_LIT>' + str(i) for i in range(self.ncols - <NUM_LIT:1>)]<EOL>self.df = pd.DataFrame(self.data, columns=self.col_names)<EOL>self.sum_df = nestcheck.pandas_functions.summary_df(<EOL>self.df, true_values=np.zeros(self.ncols),<EOL>include_true_values=True, include_rmse=True)<EOL>
Set up dummy data in a pandas DataFrame and make a summary data frame for testing.
f15344:c0:m0
def setUp(self):
self.nsamples = <NUM_LIT:10><EOL>self.ns_run = nestcheck.dummy_data.get_dummy_run(<NUM_LIT:1>, self.nsamples)<EOL>self.logw = nestcheck.ns_run_utils.get_logw(self.ns_run)<EOL>self.w_rel = np.exp(self.logw - self.logw.max())<EOL>self.w_rel /= np.sum(self.w_rel)<EOL>
Set up a dummy run to test estimators on.
f15344:c3:m0
def setUp(self):
self.x = list(range(<NUM_LIT:5>))<EOL>self.func = parallel_apply_func<EOL>self.func_args = (<NUM_LIT:1>,)<EOL>self.func_kwargs = {'<STR_LIT>': <NUM_LIT:2>}<EOL>
Define some variables.
f15344:c4:m0
def get_package_dir():
return os.path.abspath(os.path.dirname(__file__))<EOL>
Get the file path for nestcheck's directory.
f15345:m0
def get_long_description():
pkg_dir = get_package_dir()<EOL>with open(os.path.join(pkg_dir, '<STR_LIT>')) as readme_file:<EOL><INDENT>long_description = readme_file.read()<EOL><DEDENT>return long_description<EOL>
Get PyPI long description from the .rst file.
f15345:m1
def get_version():
pkg_dir = get_package_dir()<EOL>with open(os.path.join(pkg_dir, '<STR_LIT>')) as ver_file:<EOL><INDENT>string = ver_file.read()<EOL><DEDENT>return string.strip().replace('<STR_LIT>', '<STR_LIT>').replace('<STR_LIT>', '<STR_LIT>')<EOL>
Get single-source __version__.
f15345:m2
def summary_df_from_array(results_array, names, axis=<NUM_LIT:0>, **kwargs):
assert axis == <NUM_LIT:0> or axis == <NUM_LIT:1><EOL>df = pd.DataFrame(results_array)<EOL>if axis == <NUM_LIT:1>:<EOL><INDENT>df = df.T<EOL><DEDENT>df.columns = names<EOL>return summary_df(df, **kwargs)<EOL>
Make a panda data frame of the mean and std devs of an array of results, including the uncertainties on the values. This function converts the array to a DataFrame and calls summary_df on it. Parameters ---------- results_array: 2d numpy array names: list of str Names for the output df's columns. axis: int, optional Axis on which to calculate summary statistics. Returns ------- df: MultiIndex DataFrame See summary_df docstring for more details.
f15346:m0
def summary_df_from_list(results_list, names, **kwargs):
for arr in results_list:<EOL><INDENT>assert arr.shape == (len(names),)<EOL><DEDENT>df = pd.DataFrame(np.stack(results_list, axis=<NUM_LIT:0>))<EOL>df.columns = names<EOL>return summary_df(df, **kwargs)<EOL>
Make a panda data frame of the mean and std devs of each element of a list of 1d arrays, including the uncertainties on the values. This just converts the array to a DataFrame and calls summary_df on it. Parameters ---------- results_list: list of 1d numpy arrays Must have same length as names. names: list of strs Names for the output df's columns. kwargs: dict, optional Keyword arguments to pass to summary_df. Returns ------- df: MultiIndex DataFrame See summary_df docstring for more details.
f15346:m1
def summary_df_from_multi(multi_in, inds_to_keep=None, **kwargs):
<EOL>include_true_values = kwargs.pop('<STR_LIT>', False)<EOL>true_values = kwargs.get('<STR_LIT>', None)<EOL>if inds_to_keep is None:<EOL><INDENT>inds_to_keep = list(multi_in.index.names)[:-<NUM_LIT:1>]<EOL><DEDENT>if '<STR_LIT>' not in inds_to_keep:<EOL><INDENT>df = multi_in.groupby(inds_to_keep).apply(<EOL>summary_df, include_true_values=False, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>inds_to_keep = [lev if lev != '<STR_LIT>' else<EOL>'<STR_LIT>' for lev in inds_to_keep]<EOL>multi_temp = copy.deepcopy(multi_in)<EOL>multi_temp.index.set_names(<EOL>[lev if lev != '<STR_LIT>' else '<STR_LIT>' for<EOL>lev in list(multi_temp.index.names)], inplace=True)<EOL>df = multi_temp.groupby(inds_to_keep).apply(<EOL>summary_df, include_true_values=False, **kwargs)<EOL>ind = (df.index.get_level_values('<STR_LIT>') + '<STR_LIT:U+0020>' +<EOL>df.index.get_level_values('<STR_LIT>'))<EOL>order = list(df.index.names)<EOL>order.remove('<STR_LIT>')<EOL>df.index = df.index.droplevel(<EOL>['<STR_LIT>', '<STR_LIT>'])<EOL>df['<STR_LIT>'] = list(ind)<EOL>df.set_index('<STR_LIT>', append=True, inplace=True)<EOL>df = df.reorder_levels(order)<EOL><DEDENT>if include_true_values:<EOL><INDENT>assert true_values is not None<EOL>tv_ind = ['<STR_LIT>' if name == '<STR_LIT>' else '<STR_LIT>' for<EOL>name in df.index.names[:-<NUM_LIT:1>]] + ['<STR_LIT:value>']<EOL>df.loc[tuple(tv_ind), :] = true_values<EOL><DEDENT>return df<EOL>
Apply summary_df to a multiindex while preserving some levels. Parameters ---------- multi_in: multiindex pandas DataFrame inds_to_keep: None or list of strs, optional Index levels to preserve. kwargs: dict, optional Keyword arguments to pass to summary_df. Returns ------- df: MultiIndex DataFrame See summary_df docstring for more details.
f15346:m2