<commit_before># -*- coding: utf-8 -*-

# Copyright (c) 2013 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import subprocess
import sys

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath('../../stackalytics'))
sys.path.append(os.path.abspath('..'))
sys.path.append(os.path.abspath('../bin'))

# -- General configuration -----------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo', 'sphinx.ext.coverage',
              'sphinx.ext.pngmath', 'sphinx.ext.viewcode', 'sphinxcontrib.httpdomain']

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
#source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'Stackalytics'
copyright = u'2013, Mirantis Inc.'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# Version info
from stackalytics.version import version_info as stackalytics_version
release = stackalytics_version.release_string()
# The short X.Y version.
version = stackalytics_version.version_string()

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []

# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []

# -- Options for HTML output ---------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme_path = ['.']
html_theme = '_theme'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
html_title = 'Stackalytics'

# A shorter title for the navigation bar.  Default is the same as html_title.
#html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
git_cmd = ["git", "log", "--pretty=format:'%ad, commit %h'", "--date=local",
    "-n1"]
html_last_updated_fmt = subprocess.Popen(git_cmd,
                                     stdout=subprocess.PIPE).communicate()[0]

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
html_sidebars = {
    'index':    ['sidebarlinks.html', 'localtoc.html', 'searchbox.html', 'sourcelink.html'],
    '**':       ['localtoc.html', 'relations.html',
                 'searchbox.html', 'sourcelink.html']
}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}

# If false, no module index is generated.
#html_domain_indices = True

# If false, no index is generated.
#html_use_index = True

# If true, the index is split into individual pages for each letter.
#html_split_index = False

# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None

# Output file base name for HTML help builder.
htmlhelp_basename = 'StackalyticsDoc'

# -- Options for LaTeX output --------------------------------------------------

latex_elements = {
    # The paper size ('letterpaper' or 'a4paper').
    #'papersize': 'letterpaper',

    # The font size ('10pt', '11pt' or '12pt').
    #'pointsize': '10pt',

    # Additional stuff for the LaTeX preamble.
    #'preamble': '',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
    ('index', 'stackalyticsdoc.tex', u'Stackalytics',
     u'Mirantis Inc.', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False

# If true, show page references after internal links.
#latex_show_pagerefs = False

# If true, show URL addresses after external links.
#latex_show_urls = False

# Documents to append as an appendix to all manuals.
#latex_appendices = []

# If false, no module index is generated.
#latex_domain_indices = True

# -- Options for manual page output --------------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'stackalytics', u'Stackalytics',
     [u'Mirantis Inc.'], 1)
]

# If true, show URL addresses after external links.
#man_show_urls = False

# -- Options for Texinfo output ------------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    ('index', 'Stackalytics', u'Stackalytics',
     u'Mirantis Inc.', 'Stackalytics', 'Stackalytics',
     'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
#texinfo_appendices = []

# If false, no module index is generated.
#texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
<commit_msg>Remove unused pngmath Sphinx extension<commit_after># -*- coding: utf-8 -*-

# Copyright (c) 2013 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import subprocess
import sys

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath('../../stackalytics'))
sys.path.append(os.path.abspath('..'))
sys.path.append(os.path.abspath('../bin'))

# -- General configuration -----------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo', 'sphinx.ext.coverage',
              'sphinx.ext.viewcode', 'sphinxcontrib.httpdomain']

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
#source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'Stackalytics'
copyright = u'2013, Mirantis Inc.'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# Version info
from stackalytics.version import version_info as stackalytics_version
release = stackalytics_version.release_string()
# The short X.Y version.
version = stackalytics_version.version_string()

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []

# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []

# -- Options for HTML output ---------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme_path = ['.']
html_theme = '_theme'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
html_title = 'Stackalytics'

# A shorter title for the navigation bar.  Default is the same as html_title.
#html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
git_cmd = ["git", "log", "--pretty=format:'%ad, commit %h'", "--date=local",
    "-n1"]
html_last_updated_fmt = subprocess.Popen(git_cmd,
                                     stdout=subprocess.PIPE).communicate()[0]

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
html_sidebars = {
    'index':    ['sidebarlinks.html', 'localtoc.html', 'searchbox.html', 'sourcelink.html'],
    '**':       ['localtoc.html', 'relations.html',
                 'searchbox.html', 'sourcelink.html']
}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}

# If false, no module index is generated.
#html_domain_indices = True

# If false, no index is generated.
#html_use_index = True

# If true, the index is split into individual pages for each letter.
#html_split_index = False

# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None

# Output file base name for HTML help builder.
htmlhelp_basename = 'StackalyticsDoc'

# -- Options for LaTeX output --------------------------------------------------

latex_elements = {
    # The paper size ('letterpaper' or 'a4paper').
    #'papersize': 'letterpaper',

    # The font size ('10pt', '11pt' or '12pt').
    #'pointsize': '10pt',

    # Additional stuff for the LaTeX preamble.
    #'preamble': '',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
    ('index', 'stackalyticsdoc.tex', u'Stackalytics',
     u'Mirantis Inc.', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False

# If true, show page references after internal links.
#latex_show_pagerefs = False

# If true, show URL addresses after external links.
#latex_show_urls = False

# Documents to append as an appendix to all manuals.
#latex_appendices = []

# If false, no module index is generated.
#latex_domain_indices = True

# -- Options for manual page output --------------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'stackalytics', u'Stackalytics',
     [u'Mirantis Inc.'], 1)
]

# If true, show URL addresses after external links.
#man_show_urls = False

# -- Options for Texinfo output ------------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    ('index', 'Stackalytics', u'Stackalytics',
     u'Mirantis Inc.', 'Stackalytics', 'Stackalytics',
     'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
#texinfo_appendices = []

# If false, no module index is generated.
#texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
<|endoftext|>


<commit_before># Copyright (c) 2006, 2007, 2008, 2009, 2010, 2011, 2012  Andrey Golovizin
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import pybtex.io
from pybtex.bibtex.exceptions import BibTeXError
from pybtex.bibtex.utils import scan_bibtex_string
from pybtex.database.output import BaseWriter

class Writer(BaseWriter):
    """Outputs BibTeX markup"""

    unicode_io = True

    def quote(self, s):
        """
        >>> w = Writer()
        >>> print w.quote('The World')
        "The World"
        >>> print w.quote(r'The \emph{World}')
        "The \emph{World}"
        >>> print w.quote(r'The "World"')
        {The "World"}
        >>> try:
        ...     print w.quote(r'The {World')
        ... except BibTeXError, error:
        ...     print error
        String has unmatched braces: The {World
        """

        self.check_braces(s)
        if '"' not in s:
            return '"%s"' % s
        else:
            return '{%s}' % s

    def check_braces(self, s):
        """
        Raise an exception if the given string has unmatched braces.

        >>> w = Writer()
        >>> w.check_braces('Cat eats carrots.')
        >>> w.check_braces('Cat eats {carrots}.')
        >>> w.check_braces('Cat eats {carrots{}}.')
        >>> w.check_braces('')
        >>> w.check_braces('end}')
        >>> try:
        ...     w.check_braces('{')
        ... except BibTeXError, error:
        ...     print error
        String has unmatched braces: {
        >>> w.check_braces('{test}}')
        >>> try:
        ...     w.check_braces('{{test}')
        ... except BibTeXError, error:
        ...     print error
        String has unmatched braces: {{test}

        """

        tokens = list(scan_bibtex_string(s))
        if tokens:
            end_brace_level = tokens[-1][1]
            if end_brace_level != 0:
                raise BibTeXError('String has unmatched braces: %s' % s)

    def write_stream(self, bib_data, stream):
        def write_field(type, value):
            stream.write(u',\n    %s = %s' % (type, self.quote(value)))
        def format_name(person):
            def join(l):
                return ' '.join([name for name in l if name])
            first = person.get_part_as_text('first')
            middle = person.get_part_as_text('middle')
            prelast = person.get_part_as_text('prelast')
            last = person.get_part_as_text('last')
            lineage = person.get_part_as_text('lineage')
            s = ''
            if last:
                s += join([prelast, last])
            if lineage:
                s += ', %s' % lineage
            if first or middle:
                s += ', '
                s += join([first, middle])
            return s
        def write_persons(persons, role):
#            persons = getattr(entry, role + 's')
            if persons:
                write_field(role, u' and '.join([format_name(person) for person in persons]))
        def write_preamble(preamble):
            if preamble:
                stream.write(u'@preamble{%s}\n\n' % self.quote(preamble))

        write_preamble(bib_data.preamble)
        for key, entry in bib_data.entries.iteritems():
            stream.write(u'@%s' % entry.original_type)
            stream.write(u'{%s' % key)
#            for role in ('author', 'editor'):
            for role, persons in entry.persons.iteritems():
                write_persons(persons, role)
            for type, value in entry.fields.iteritems():
                write_field(type, value)
            stream.write(u'\n}\n\n')
<commit_msg>Remove excessive trailing newline from .bib output<commit_after># Copyright (c) 2006, 2007, 2008, 2009, 2010, 2011, 2012  Andrey Golovizin
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import pybtex.io
from pybtex.bibtex.exceptions import BibTeXError
from pybtex.bibtex.utils import scan_bibtex_string
from pybtex.database.output import BaseWriter

class Writer(BaseWriter):
    """Outputs BibTeX markup"""

    unicode_io = True

    def quote(self, s):
        """
        >>> w = Writer()
        >>> print w.quote('The World')
        "The World"
        >>> print w.quote(r'The \emph{World}')
        "The \emph{World}"
        >>> print w.quote(r'The "World"')
        {The "World"}
        >>> try:
        ...     print w.quote(r'The {World')
        ... except BibTeXError, error:
        ...     print error
        String has unmatched braces: The {World
        """

        self.check_braces(s)
        if '"' not in s:
            return '"%s"' % s
        else:
            return '{%s}' % s

    def check_braces(self, s):
        """
        Raise an exception if the given string has unmatched braces.

        >>> w = Writer()
        >>> w.check_braces('Cat eats carrots.')
        >>> w.check_braces('Cat eats {carrots}.')
        >>> w.check_braces('Cat eats {carrots{}}.')
        >>> w.check_braces('')
        >>> w.check_braces('end}')
        >>> try:
        ...     w.check_braces('{')
        ... except BibTeXError, error:
        ...     print error
        String has unmatched braces: {
        >>> w.check_braces('{test}}')
        >>> try:
        ...     w.check_braces('{{test}')
        ... except BibTeXError, error:
        ...     print error
        String has unmatched braces: {{test}

        """

        tokens = list(scan_bibtex_string(s))
        if tokens:
            end_brace_level = tokens[-1][1]
            if end_brace_level != 0:
                raise BibTeXError('String has unmatched braces: %s' % s)

    def write_stream(self, bib_data, stream):
        def write_field(type, value):
            stream.write(u',\n    %s = %s' % (type, self.quote(value)))
        def format_name(person):
            def join(l):
                return ' '.join([name for name in l if name])
            first = person.get_part_as_text('first')
            middle = person.get_part_as_text('middle')
            prelast = person.get_part_as_text('prelast')
            last = person.get_part_as_text('last')
            lineage = person.get_part_as_text('lineage')
            s = ''
            if last:
                s += join([prelast, last])
            if lineage:
                s += ', %s' % lineage
            if first or middle:
                s += ', '
                s += join([first, middle])
            return s
        def write_persons(persons, role):
#            persons = getattr(entry, role + 's')
            if persons:
                write_field(role, u' and '.join([format_name(person) for person in persons]))
        def write_preamble(preamble):
            if preamble:
                stream.write(u'@preamble{%s}\n\n' % self.quote(preamble))

        write_preamble(bib_data.preamble)

        first = True
        for key, entry in bib_data.entries.iteritems():
            if not first:
                stream.write(u'\n')
            first = False

            stream.write(u'@%s' % entry.original_type)
            stream.write(u'{%s' % key)
#            for role in ('author', 'editor'):
            for role, persons in entry.persons.iteritems():
                write_persons(persons, role)
            for type, value in entry.fields.iteritems():
                write_field(type, value)
            stream.write(u'\n}\n')
<|endoftext|>


<commit_before>#!/usr/bin/env python
# name IsOpen.py
import os, subprocess
import socket
import psutil
import logging
logging.basicConfig(level=logging.DEBUG,\
    format='%(asctime)s|%(filename)s|%(funcName)s|line:%(lineno)d|%(levelname)s|%(message)s',
    datefmt='%Y-%m-%d %X',
    filename=os.path.dirname(os.path.abspath(__file__)) +'/checkService.log'
    )

def IsOpen(ip,port):
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    try:
        s.connect((ip,int(port)))
        s.shutdown(2)
        print '%d is open' % port
        return True
    except:
        print '%d is down' % port
        return False

def runPyService(pyname):
    INTERPRETER = "/usr/bin/python"
    if not os.path.exists(INTERPRETER):
        print "Cannot find INTERPRETER at path \"%s\"." % INTERPRETER
    processor = pyname

    pargs = [INTERPRETER, processor]
    pargs.extend(["--input=inputMd5s"])
    subprocess.Popen(pargs)

def isRunning(cmd):
    pids = psutil.pids()
    for pid in pids:
        if cmd in str(psutil.Process(pid).cmdline()):
            return pid
    return False

def checkService(arg2):
    if isRunning(arg2) == False:
        INTERPRETER = "/usr/bin/python"
        if not os.path.exists(INTERPRETER):
            print "Cannot find INTERPRETER at path \"%s\"." % INTERPRETER
        processor = os.path.dirname(os.path.abspath(__file__)) \
            + '/manage.py'
        pargs = [INTERPRETER, processor, arg2]
        subprocess.Popen(pargs)
        logging.info('%s', str(pargs))

if __name__ == '__main__':
    #if IsOpen('127.0.0.1',8000) != True:
    #    runPyService(\
    #    os.path.dirname(os.path.abspath(__file__)) + '/yourpyfile.py')
    #logging.info('start check')
    checkService('crawler')
    checkService('notify')

<commit_msg>checkService.py add, run this every minite in crontab<commit_after>#!/usr/bin/env python
# name IsOpen.py
import os, subprocess
import socket
import psutil
import logging
logging.basicConfig(level=logging.DEBUG,\
    format='%(asctime)s|%(filename)s|%(funcName)s|line:%(lineno)d|%(levelname)s|%(message)s',
    datefmt='%Y-%m-%d %X',
    filename=os.path.dirname(os.path.abspath(__file__)) +'/checkService.log'
    )

def IsOpen(ip,port):
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    try:
        s.connect((ip,int(port)))
        s.shutdown(2)
        print '%d is open' % port
        return True
    except:
        print '%d is down' % port
        return False

def runPyService(pyname):
    INTERPRETER = "/usr/bin/python"
    if not os.path.exists(INTERPRETER):
        print "Cannot find INTERPRETER at path \"%s\"." % INTERPRETER
    processor = pyname

    pargs = [INTERPRETER, processor]
    pargs.extend(["--input=inputMd5s"])
    subprocess.Popen(pargs)

def isRunning(cmd):
    pids = psutil.pids()
    for pid in pids:
        if cmd in str(psutil.Process(pid).cmdline()):
            return pid
    return False

def checkService(arg2):
    if isRunning(arg2) == False:
        INTERPRETER = "/usr/bin/python"
        if not os.path.exists(INTERPRETER):
            print "Cannot find INTERPRETER at path \"%s\"." % INTERPRETER
        processor = os.path.dirname(os.path.abspath(__file__)) \
            + '/manage.py'
        pargs = [INTERPRETER, processor, arg2]
        subprocess.Popen(pargs)
        logging.info('%s', str(pargs))

if __name__ == '__main__':
    #if IsOpen('127.0.0.1',8000) != True:
    #    runPyService(\
    #    os.path.dirname(os.path.abspath(__file__)) + '/yourpyfile.py')
    logging.info('start check')
    checkService('crawler')
    checkService('notify')

<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
# FlowCytometryTools documentation build configuration file, created by
# sphinx-quickstart on Sat Oct 12 16:30:49 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys
import os
import sphinx_bootstrap_theme

import sys, os
sys.path.insert(0, os.path.abspath('../../../'))
sys.path.insert(0, os.path.abspath('../sphinxext'))

sys.path.extend([

    # numpy standard doc extensions
    os.path.join(os.path.dirname(__file__),
                 '..', '../..',
                 'sphinxext')

])

# Takes documentation both from class doc and from __init__
autoclass_content = 'both'

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
#extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest']
extensions = ['sphinx.ext.autodoc',
              'sphinx.ext.doctest',
              'sphinx.ext.extlinks',
              'sphinx.ext.todo',
              'numpydoc',
              'ipython_directive',
              'ipython_console_highlighting',
              #'sphinx.ext.intersphinx',
              'sphinx.ext.todo',
              'sphinx.ext.coverage',
              'sphinx.ext.pngmath',
              'sphinx.ext.ifconfig',
              'sphinx.ext.autosummary',
              'matplotlib.sphinxext.only_directives',
              'matplotlib.sphinxext.plot_directive',
              ]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates', '_templates/autosummary']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
#source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'FlowCytometryTools'
copyright = u'2013, Jonathan Friedman & Eugene Yurtsev'

import FlowCytometryTools

# The short X.Y version.
version = '%s' % (FlowCytometryTools.__version__)
# The full version, including alpha/beta/rc tags.
release = version

autosummary_generate = True

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []

# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#html_theme = 'default'

html_theme = 'bootstrap'
html_theme_path = sphinx_bootstrap_theme.get_html_theme_path()

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}

# Theme options are theme-specific and customize the look and feel of a
# theme further.
html_theme_options = {
    # Navigation bar title. (Default: ``project`` value)
    #'navbar_title': "Demo",

    # Tab name for entire site. (Default: "Site")
    #'navbar_site_name': "Site",

    # A list of tuples containing pages or urls to link to.
    # Valid tuples should be in the following forms:
    #    (name, page)                 # a link to a page
    #    (name, "/aa/bb", 1)          # a link to an arbitrary relative url
    #    (name, "http://example.com", True) # arbitrary absolute url
    # Note the "1" or "True" value above as the third argument to indicate
    # an arbitrary url.
    'navbar_links': [
        ("Gallery", 'gallery'),
        ("Install", 'install'),
        ("Tutorial", 'tutorial'),
        ("API", "api"),
    ],

    # Render the next and previous page links in navbar. (Default: true)
    'navbar_sidebarrel': False,

    # Render the current pages TOC in the navbar. (Default: true)
    'navbar_pagenav': True,

    # Global TOC depth for "site" navbar tab. (Default: 1)
    # Switching to -1 shows all levels.
    'globaltoc_depth': -1,

    # Include hidden TOCs in Site navbar?
    #
    # Note: If this is "false", you cannot have mixed ``:hidden:`` and
    # non-hidden ``toctree`` directives in the same page, or else the build
    # will break.
    #
    # Values: "true" (default) or "false"
    'globaltoc_includehidden': "true",

    # HTML navbar class (Default: "navbar") to attach to <div> element.
    # For black navbar, do "navbar navbar-inverse"
    #'navbar_class': "navbar navbar-inverse",
    'navbar_class': "navbar",

    # Fix navigation bar to top of page?
    # Values: "true" (default) or "false"
    'navbar_fixed_top': "true",

    # Location of link to source.
    # Options are "nav" (default), "footer" or anything else to exclude.
    'source_link_position': "nowhere",

    # Bootswatch (http://bootswatch.com/) theme.
    #
    # Options are nothing with "" (default) or the name of a valid theme
    # such as "amelia" or "cosmo".
    #
    # Note that this is served off CDN, so won't be available offline.
    'bootswatch_theme': "flatly",
    #'bootswatch_theme': "united",
    #'bootswatch_theme': "spacelab",

    # Choose Bootstrap version.
    # Values: "3" (default) or "2" (in quotes)
    'bootstrap_version': "3",
}

# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
#html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
#html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}

EY_doc_names = ['localtoc.html']
html_sidebars = {'tutorial': EY_doc_names, 'install': EY_doc_names, 'api' : EY_doc_names}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}

# If false, no module index is generated.
html_use_modindex = True

# If false, no index is generated.
#html_use_index = True

# If true, the index is split into individual pages for each letter.
#html_split_index = False

# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None

# Output file base name for HTML help builder.
htmlhelp_basename = 'FlowCytometryToolsdoc'

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',

# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',

# Additional stuff for the LaTeX preamble.
#'preamble': '',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
  ('index', 'FlowCytometryTools.tex', u'FlowCytometryTools Documentation',
   u'Jonathan Friedman & Eugene Yurtsev', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False

# If true, show page references after internal links.
#latex_show_pagerefs = False

# If true, show URL addresses after external links.
#latex_show_urls = False

# Documents to append as an appendix to all manuals.
#latex_appendices = []

# If false, no module index is generated.
#latex_domain_indices = True

# Example configuration for intersphinx: refer to the Python standard library.
# intersphinx_mapping = {'http://docs.scipy.org/': None}
import glob
autosummary_generate = glob.glob("*.rst")

# -- Options for manual page output --------------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'FlowCytometryTools', u'FlowCytometryTools Documentation',
     [u'Jonathan Friedman & Eugene Yurtsev'], 1)
]

# If true, show URL addresses after external links.
#man_show_urls = False

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
  ('index', 'FlowCytometryTools', u'FlowCytometryTools Documentation',
   u'Jonathan Friedman and Eugene Yurtsev', 'FlowCytometryTools', 'One line description of project.',
   'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
#texinfo_appendices = []

# If false, no module index is generated.
#texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False

# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'http://docs.python.org/': None}
<commit_msg>Updated conf to link documentation to bitbucket, napoleon for doc parsing, google analytics, and other more minor changes<commit_after># -*- coding: utf-8 -*-
#
# FlowCytometryTools documentation build configuration file, created by
# sphinx-quickstart on Sat Oct 12 16:30:49 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys
import os
import sphinx_bootstrap_theme

import sys, os
sys.path.insert(0, os.path.abspath('../../../'))
sys.path.insert(0, os.path.abspath('../sphinxext'))

sys.path.extend([

    # numpy standard doc extensions
    os.path.join(os.path.dirname(__file__),
                 '..', '../..',
                 'sphinxext')

])

# Takes documentation both from class doc and from __init__
autoclass_content = 'both'

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
#extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest']
extensions = ['sphinx.ext.autodoc',
              'sphinx.ext.doctest',
              'sphinx.ext.extlinks',
              'sphinx.ext.todo',
              #'numpydoc',
              'sphinxcontrib.napoleon',
              'sphinxcontrib.googleanalytics',
              #'sphinx.ext.intersphinx',
              'sphinx.ext.todo',
              'sphinx.ext.linkcode',
              'sphinx.ext.coverage',
              'sphinx.ext.pngmath',
              'sphinx.ext.ifconfig',
              'sphinx.ext.autosummary',
              'matplotlib.sphinxext.only_directives',
              'matplotlib.sphinxext.plot_directive',
              ##
              # On newer versions
              'IPython.sphinxext.ipython_directive',
              'IPython.sphinxext.ipython_console_highlighting'

              ##
              # On older sphinx versions
              #'ipython_directive',
              #'ipython_console_highlighting',
              ]

## Google analytics
googleanalytics_id = 'UA-45363835-3'
googleanalytics_enabled = True

## Napoleon settings
napoleon_google_docstring = False
napoleon_numpy_docstring = True
napoleon_include_private_with_doc = False
napoleon_include_special_with_doc = True
napoleon_use_admonition_for_examples = True
napoleon_use_admonition_for_notes = True
napoleon_use_admonition_for_references = False
napoleon_use_ivar = False
napoleon_use_param = True
napoleon_use_rtype = True

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates', '_templates/autosummary']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
#source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'FlowCytometryTools'
copyright = u'2013-2014, Jonathan Friedman & Eugene Yurtsev'

import FlowCytometryTools

# The short X.Y version.
version = '%s' % (FlowCytometryTools.__version__)
# The full version, including alpha/beta/rc tags.
release = version

autosummary_generate = True

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []

# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#html_theme = 'default'

html_theme = 'bootstrap'
html_theme_path = sphinx_bootstrap_theme.get_html_theme_path()

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}

# Theme options are theme-specific and customize the look and feel of a
# theme further.
html_theme_options = {
    # Navigation bar title. (Default: ``project`` value)
    #'navbar_title': "Demo",

    # Tab name for entire site. (Default: "Site")
    #'navbar_site_name': "Site",

    # A list of tuples containing pages or urls to link to.
    # Valid tuples should be in the following forms:
    #    (name, page)                 # a link to a page
    #    (name, "/aa/bb", 1)          # a link to an arbitrary relative url
    #    (name, "http://example.com", True) # arbitrary absolute url
    # Note the "1" or "True" value above as the third argument to indicate
    # an arbitrary url.
    'navbar_links': [
        ("Gallery", 'gallery'),
        ("Install", 'install'),
        ("Tutorial", 'tutorial'),
        ("API", "api"),
    ],

    # Render the next and previous page links in navbar. (Default: true)
    'navbar_sidebarrel': False,

    # Render the current pages TOC in the navbar. (Default: true)
    'navbar_pagenav': True,

    # Global TOC depth for "site" navbar tab. (Default: 1)
    # Switching to -1 shows all levels.
    'globaltoc_depth': -1,

    # Include hidden TOCs in Site navbar?
    #
    # Note: If this is "false", you cannot have mixed ``:hidden:`` and
    # non-hidden ``toctree`` directives in the same page, or else the build
    # will break.
    #
    # Values: "true" (default) or "false"
    'globaltoc_includehidden': "true",

    # HTML navbar class (Default: "navbar") to attach to <div> element.
    # For black navbar, do "navbar navbar-inverse"
    #'navbar_class': "navbar navbar-inverse",
    'navbar_class': "navbar",

    # Fix navigation bar to top of page?
    # Values: "true" (default) or "false"
    'navbar_fixed_top': "true",

    # Location of link to source.
    # Options are "nav" (default), "footer" or anything else to exclude.
    'source_link_position': "nowhere",

    # Bootswatch (http://bootswatch.com/) theme.
    #
    # Options are nothing with "" (default) or the name of a valid theme
    # such as "amelia" or "cosmo".
    #
    # Note that this is served off CDN, so won't be available offline.
    'bootswatch_theme': "yeti",
    #'bootswatch_theme': "flatly",
    #'bootswatch_theme': "united",
    #'bootswatch_theme': "spacelab",

    # Choose Bootstrap version.
    # Values: "3" (default) or "2" (in quotes)
    'bootstrap_version': "3",
}

# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
#html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
#html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}

EY_doc_names = ['localtoc.html']
html_sidebars = {'tutorial': EY_doc_names, 'install': EY_doc_names, 'api' : EY_doc_names, 'gallery' : EY_doc_names}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}

# If false, no module index is generated.
html_use_modindex = True

# If false, no index is generated.
#html_use_index = True

# If true, the index is split into individual pages for each letter.
#html_split_index = False

# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None

# Output file base name for HTML help builder.
htmlhelp_basename = 'FlowCytometryToolsdoc'

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',

# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',

# Additional stuff for the LaTeX preamble.
#'preamble': '',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
  ('index', 'FlowCytometryTools.tex', u'FlowCytometryTools Documentation',
   u'Jonathan Friedman & Eugene Yurtsev', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False

# If true, show page references after internal links.
#latex_show_pagerefs = False

# If true, show URL addresses after external links.
#latex_show_urls = False

# Documents to append as an appendix to all manuals.
#latex_appendices = []

# If false, no module index is generated.
#latex_domain_indices = True

# Example configuration for intersphinx: refer to the Python standard library.
# intersphinx_mapping = {'http://docs.scipy.org/': None}
import glob
autosummary_generate = glob.glob("*.rst")

# -- Options for manual page output --------------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'FlowCytometryTools', u'FlowCytometryTools Documentation',
     [u'Jonathan Friedman & Eugene Yurtsev'], 1)
]

# If true, show URL addresses after external links.
#man_show_urls = False

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
  ('index', 'FlowCytometryTools', u'FlowCytometryTools Documentation',
   u'Jonathan Friedman and Eugene Yurtsev', 'FlowCytometryTools', 'One line description of project.',
   'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
#texinfo_appendices = []

# If false, no module index is generated.
#texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False

# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'http://docs.python.org/': None}

# -----------------------------------------------------------------------------
# Source code links
# -----------------------------------------------------------------------------

import inspect
from os.path import relpath, dirname
import FlowCytometryTools

from git import *
import FlowCytometryTools
repo = Repo(FlowCytometryTools.__path__[0])
current_commit = repo.commit()
current_branch = repo.active_branch

def linkcode_resolve(domain, info):
    """
    Determine the URL corresponding to Python object

    Code from scipy:
        http://nullege.com/codes/show/src@s@c@scipy-HEAD@doc@source@conf.py
    """
    if domain != 'py':
        return None

    modname = info['module']
    fullname = info['fullname']

    submod = sys.modules.get(modname)
    if submod is None:
        return None

    obj = submod
    for part in fullname.split('.'):
        try:
            obj = getattr(obj, part)
        except:
            return None

    try:
        fn = inspect.getsourcefile(obj)
    except:
        fn = None
    if not fn:
        try:
            fn = inspect.getsourcefile(sys.modules[obj.__module__])
        except:
            fn = None
    if not fn:
        return None

    try:
        source, lineno = inspect.findsource(obj)
    except:
        lineno = None

    if lineno:
        linespec = "#cl-%d" % (lineno + 1)
    else:
        linespec = ""

    fn = relpath(fn, start=dirname(FlowCytometryTools.__file__))

    return "//bitbucket.org/gorelab/flowcytometrytools/src/{}/FlowCytometryTools/{}?at={}{}".format(current_commit, fn, current_branch, linespec)
<|endoftext|>


<commit_before>from __future__ import division
import shutil
import os.path
op = os.path
import sys
libtbx_path = os.path.join(
  os.path.abspath(os.path.dirname(os.path.dirname(__file__))), "lib")
if (not libtbx_path in sys.path) :
  sys.path.append(libtbx_path)
from libtbx.auto_build import install_distribution
from libtbx.auto_build.installer_utils import *

class installer(install_distribution.installer):
  product_name = "DIALS"
  dest_dir_prefix = "dials"
  make_apps = []
  configure_modules = ["dials"]
  include_gui_packages = True
  base_package_options = ["--dials"]
  installer_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  base_modules = ['docutils']
  modules = [
    # hot
    'annlib',
    'boost',
    'scons',
    'ccp4io',
    'docutils',
    # base
    'cbflib',
    'cctbx_project',
    'gui_resources',
    'ccp4io_adaptbx',
    'annlib_adaptbx',
    'tntbx',
    'clipper',
    # dials
    'dials'
  ]

if (__name__ == "__main__") :
  installer(sys.argv[1:]).install()<commit_msg>Moved docutils to regular python dependency.<commit_after>from __future__ import division
import shutil
import os.path
op = os.path
import sys
libtbx_path = os.path.join(
  os.path.abspath(os.path.dirname(os.path.dirname(__file__))), "lib")
if (not libtbx_path in sys.path) :
  sys.path.append(libtbx_path)
from libtbx.auto_build import install_distribution
from libtbx.auto_build.installer_utils import *

class installer(install_distribution.installer):
  product_name = "DIALS"
  dest_dir_prefix = "dials"
  make_apps = []
  configure_modules = ["dials"]
  include_gui_packages = True
  base_package_options = ["--dials"]
  installer_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  modules = [
    # hot
    'annlib',
    'boost',
    'scons',
    'ccp4io',
    # base
    'cbflib',
    'cctbx_project',
    'gui_resources',
    'ccp4io_adaptbx',
    'annlib_adaptbx',
    'tntbx',
    'clipper',
    # dials
    'dials'
  ]

if (__name__ == "__main__") :
  installer(sys.argv[1:]).install()<|endoftext|>


<commit_before># Copyright (c) 2013 John Maguire <john@leftforliving.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.

import os
import sys
import sqlite3
import json
import urllib2

class LastfmPlugin(object):
    # This will hold the connection to the sqlite database
    conn = None

    def __init__(self, cardinal):
        # Connect to or create the database
        self._connect_or_create_db(cardinal)

    def _connect_or_create_db(self, cardinal):
        try:
            self.conn = sqlite3.connect(os.path.join(cardinal.path, 'db', 'lastfm-%s.db' % cardinal.network))
        except Exception, e:
            self.conn = None
            print >> sys.stderr, "ERROR: Unable to access local Last.fm database (%s)" % e
            return

        c = self.conn.cursor()
        c.execute("CREATE TABLE IF NOT EXISTS users (nick text collate nocase, vhost text, username text)")
        self.conn.commit()

    def set_user(self, cardinal, user, channel, msg):
        if not self.conn:
            cardinal.sendMsg(channel, "Unable to access local Last.fm database.")

        message = msg.split()
        if len(message) < 2:
            cardinal.sendMsg(channel, "Syntax: .setlastfm <username>")
            return

        c = self.conn.cursor()
        c.execute("SELECT username FROM users WHERE nick=? OR vhost=?", (user.group(1), user.group(3)))
        result = c.fetchone()
        if result:
            c.execute("UPDATE users SET username=? WHERE nick=? OR vhost=?", (message[1], user.group(1), user.group(3)))
        else:
            c.execute("INSERT INTO users (nick, vhost, username) VALUES(?, ?, ?)", (user.group(1), user.group(3), message[1]))
        self.conn.commit()

        cardinal.sendMsg(channel, "Your Last.fm username is now set to %s." % (message[1],))

    set_user.commands = ['setlastfm']
    set_user.help = ["Sets the default Last.fm username for your nick.",
                     "Syntax: .setlastfm <username>"]

    def now_playing(self, cardinal, user, channel, msg):
        # Before we do anything, let's make sure we'll be able to query Last.fm
        if not hasattr(cardinal.config['lastfm'], 'API_KEY') or cardinal.config['lastfm'].API_KEY == "API_KEY":
            cardinal.sendMsg(channel, "Last.fm plugin is not configured correctly. Please set API key.")
            return

        if not self.conn:
            cardinal.sendMsg(channel, "Unable to access local Last.fm database.")
            return

        # Open the cursor for the query to find a saved Last.fm username
        c = self.conn.cursor()

        # If they supplied user parameter, use that for the query instead
        message = msg.split()
        if len(message) >= 2:
            nick = message[1]
            c.execute("SELECT username FROM users WHERE nick=?", (nick,))
        else:
            nick = user.group(1)
            c.execute("SELECT username FROM users WHERE nick=? OR vhost=?", (nick, user.group(3)))
        result = c.fetchone()

        # Use the returned username, or the entered/user's nick otherwise
        if not result:
            try:
                username = message[1]
            except IndexError:
                username = user.group(1)
        else:
            username = result[0]

        try:
            uh = urllib2.urlopen("http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=%s&api_key=%s&limit=1&format=json" % (username, cardinal.config['lastfm'].API_KEY))
            content = json.load(uh)
        except urllib2.URLError, e:
            cardinal.sendMsg(channel, "Unable to reach Last.fm.")
            print >> sys.stderr, "ERROR: Failed to reach the server: %s" % e.reason
            return
        except urllib2.HTTPError, e:
            cardinal.sendMsg(channel, "Unable to access Last.fm API.")
            print >> sys.stderr, "ERROR: The server did not fulfill the request. (%s Error)" % e.code
            return

        if 'error' in content and content['error'] == 10:
            cardinal.sendMsg(channel, "Last.fm plugin is not configured correctly. Please set API key.")
            return
        elif 'error' in content and content['error'] == 6:
            cardinal.sendMsg(channel, "Your Last.fm username is incorrect. No user exists by the username %s." % str(username))
            return

        try:
            song = content['recenttracks']['track'][0]['name']
            artist = content['recenttracks']['track'][0]['artist']['#text']

            cardinal.sendMsg(channel, "%s is now listening to: %s by %s" % (str(username), str(song), str(artist)))
        except KeyError:
            try:
                song = content['recenttracks']['track']['name']
                artist = content['recenttracks']['track']['artist']['#text']

                cardinal.sendMsg(channel, "%s last listened to: %s by %s" % (str(username), str(song), str(artist)))
            except KeyError:
                cardinal.sendMsg(channel, "Unable to find any tracks played. (Is your Last.fm username correct?)")

    now_playing.commands = ['np', 'nowplaying']
    now_playing.help = ["Get the Last.fm track currently played by a user (attempts to default to username set with .setlastfm)",
                        "Syntax: .np [username]"]

    def compare(self, cardinal, user, channel, msg):
        # Before we do anything, let's make sure we'll be able to query Last.fm
        if not hasattr(cardinal.config['lastfm'], 'API_KEY') or cardinal.config['lastfm'].API_KEY == "API_KEY":
            cardinal.sendMsg(channel, "Last.fm plugin is not configured correctly. Please set API key.")

        if not self.conn:
            cardinal.sendMsg(channel, "Unable to access local Last.fm database.")
            return

        # Open the cursor for the query to find a saved Last.fm username
        c = self.conn.cursor()

        # If they supplied user parameter, use that for the query instead
        message = msg.split()
        if len(message) < 2:
            cardinal.sendMsg(channel, "Syntax: .compare <username> [username]")

        nick = message[1]
        c.execute("SELECT username FROM users WHERE nick=?", (nick,))
        result = c.fetchone()

        if not result:
            username1 = nick
        else:
            username1 = result[0]

        if len(message) >= 3:
            nick = message[2]
            c.execute("SELECT username FROM users WHERE nick=?", (nick,))
        else:
            nick = user.group(1)
            c.execute("SELECT username FROM users WHERE nick=? OR vhost=?", (nick, user.group(3)))
        result = c.fetchone()

        # Use the returned username, or the entered/user's nick otherwise
        if not result:
            username2 = nick
        else:
            username2 = result[0]

        try:
            uh = urllib2.urlopen("http://ws.audioscrobbler.com/2.0/?method=tasteometer.compare&type1=user&type2=user&value1=%s&value2=%s&api_key=%s&format=json" % (username1, username2, cardinal.config['lastfm'].API_KEY))
            content = json.load(uh)
        except urllib2.URLError, e:
            cardinal.sendMsg(channel, "Unable to reach Last.fm.")
            print >> sys.stderr, "ERROR: Failed to reach the server: %s" % e.reason
            return
        except urllib2.HTTPError, e:
            cardinal.sendMsg(channel, "Unable to access Last.fm API.")
            print >> sys.stderr, "ERROR: The server did not fulfill the request. (%s Error)" % e.code
            return

        if 'error' in content and content['error'] == 10:
            cardinal.sendMsg(channel, "Last.fm plugin is not configured correctly. Please set API key.")
            return
        elif 'error' in content and content['error'] == 7:
            print content
            cardinal.sendMsg(channel, "One of the Last.fm usernames entered was invalid. Please try again.")
            return

        try:
            score = int(float(content['comparison']['result']['score']) * 100)
            artists = []
            if not 'artist' in content['comparison']['result']['artists']:
                # Return early to avoid error on looping through artists
                cardinal.sendMsg(channel, "According to Last.fm's Tasteometer, %s and %s share none of the same music." % (str(username1), str(username2)))
                return

            # Account for Last.fm giving a string instead of a list if only one artist is shared
            if not isinstance(content['comparison']['result']['artists']['artist'], list):
                artists.append(str(content['comparison']['result']['artists']['artist']['name']))
            else:
                # Loop through all artists to grab artist names
                for i in range(len(content['comparison']['result']['artists']['artist'])):
                    artists.append(str(content['comparison']['result']['artists']['artist'][i]['name']))

            cardinal.sendMsg(channel, "According to Last.fm's Tasteometer, %s and %s's music preferences are %d%% compatible! Some artists they have in common include: %s" % (str(username1), str(username2), score, ', '.join(artists)))
        except KeyError:
            cardinal.sendMsg(channel, "An unknown error has occurred.")

    compare.commands = ['compare']
    compare.help = ["Uses Last.fm to compare the compatibility of music between two users.",
                    "Syntax: .compare <username> [username]"]

    def close(self):
        self.conn.close()

def setup(cardinal):
    return LastfmPlugin(cardinal)
<commit_msg>making last.fm plugin a little easier to follow with variables<commit_after># Copyright (c) 2013 John Maguire <john@leftforliving.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.

import os
import sys
import sqlite3
import json
import urllib2

class LastfmPlugin(object):
    # This will hold the connection to the sqlite database
    conn = None

    def __init__(self, cardinal):
        # Connect to or create the database
        self._connect_or_create_db(cardinal)

    def _connect_or_create_db(self, cardinal):
        try:
            self.conn = sqlite3.connect(os.path.join(cardinal.path, 'db', 'lastfm-%s.db' % cardinal.network))
        except Exception, e:
            self.conn = None
            print >> sys.stderr, "ERROR: Unable to access local Last.fm database (%s)" % e
            return

        c = self.conn.cursor()
        c.execute("CREATE TABLE IF NOT EXISTS users (nick text collate nocase, vhost text, username text)")
        self.conn.commit()

    def set_user(self, cardinal, user, channel, msg):
        if not self.conn:
            cardinal.sendMsg(channel, "Unable to access local Last.fm database.")

        message = msg.split()
        if len(message) < 2:
            cardinal.sendMsg(channel, "Syntax: .setlastfm <username>")
            return

        nick = user.group(1)
        vhost = user.group(3)
        username = message[1]

        c = self.conn.cursor()
        c.execute("SELECT username FROM users WHERE nick=? OR vhost=?", (nick, vhost))
        result = c.fetchone()
        if result:
            c.execute("UPDATE users SET username=? WHERE nick=? OR vhost=?", (username, nick, vhost))
        else:
            c.execute("INSERT INTO users (nick, vhost, username) VALUES(?, ?, ?)", (nick, vhost, username))
        self.conn.commit()

        cardinal.sendMsg(channel, "Your Last.fm username is now set to %s." % (username,))

    set_user.commands = ['setlastfm']
    set_user.help = ["Sets the default Last.fm username for your nick.",
                     "Syntax: .setlastfm <username>"]

    def now_playing(self, cardinal, user, channel, msg):
        # Before we do anything, let's make sure we'll be able to query Last.fm
        if not hasattr(cardinal.config['lastfm'], 'API_KEY') or cardinal.config['lastfm'].API_KEY == "API_KEY":
            cardinal.sendMsg(channel, "Last.fm plugin is not configured correctly. Please set API key.")
            return

        if not self.conn:
            cardinal.sendMsg(channel, "Unable to access local Last.fm database.")
            return

        # Open the cursor for the query to find a saved Last.fm username
        c = self.conn.cursor()

        # If they supplied user parameter, use that for the query instead
        message = msg.split()

        if len(message) >= 2:
            nick = message[1]
            c.execute("SELECT username FROM users WHERE nick=?", (nick,))
        else:
            nick = user.group(1)
            vhost = user.group(3)
            c.execute("SELECT username FROM users WHERE nick=? OR vhost=?", (nick, vhost))
        result = c.fetchone()

        # Use the returned username, or the entered/user's nick otherwise
        if not result:
            try:
                username = message[1]
            except IndexError:
                username = user.group(1)
        else:
            username = result[0]

        try:
            uh = urllib2.urlopen("http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=%s&api_key=%s&limit=1&format=json" % (username, cardinal.config['lastfm'].API_KEY))
            content = json.load(uh)
        except urllib2.URLError, e:
            cardinal.sendMsg(channel, "Unable to reach Last.fm.")
            print >> sys.stderr, "ERROR: Failed to reach the server: %s" % e.reason
            return
        except urllib2.HTTPError, e:
            cardinal.sendMsg(channel, "Unable to access Last.fm API.")
            print >> sys.stderr, "ERROR: The server did not fulfill the request. (%s Error)" % e.code
            return

        if 'error' in content and content['error'] == 10:
            cardinal.sendMsg(channel, "Last.fm plugin is not configured correctly. Please set API key.")
            return
        elif 'error' in content and content['error'] == 6:
            cardinal.sendMsg(channel, "Your Last.fm username is incorrect. No user exists by the username %s." % str(username))
            return

        try:
            song = content['recenttracks']['track'][0]['name']
            artist = content['recenttracks']['track'][0]['artist']['#text']

            cardinal.sendMsg(channel, "%s is now listening to: %s by %s" % (str(username), str(song), str(artist)))
        except KeyError:
            try:
                song = content['recenttracks']['track']['name']
                artist = content['recenttracks']['track']['artist']['#text']

                cardinal.sendMsg(channel, "%s last listened to: %s by %s" % (str(username), str(song), str(artist)))
            except KeyError:
                cardinal.sendMsg(channel, "Unable to find any tracks played. (Is your Last.fm username correct?)")

    now_playing.commands = ['np', 'nowplaying']
    now_playing.help = ["Get the Last.fm track currently played by a user (attempts to default to username set with .setlastfm)",
                        "Syntax: .np [username]"]

    def compare(self, cardinal, user, channel, msg):
        # Before we do anything, let's make sure we'll be able to query Last.fm
        if not hasattr(cardinal.config['lastfm'], 'API_KEY') or cardinal.config['lastfm'].API_KEY == "API_KEY":
            cardinal.sendMsg(channel, "Last.fm plugin is not configured correctly. Please set API key.")

        if not self.conn:
            cardinal.sendMsg(channel, "Unable to access local Last.fm database.")
            return

        # Open the cursor for the query to find a saved Last.fm username
        c = self.conn.cursor()

        # If they supplied user parameter, use that for the query instead
        message = msg.split()
        if len(message) < 2:
            cardinal.sendMsg(channel, "Syntax: .compare <username> [username]")

        nick = message[1]
        c.execute("SELECT username FROM users WHERE nick=?", (nick,))
        result = c.fetchone()

        if not result:
            username1 = nick
        else:
            username1 = result[0]

        if len(message) >= 3:
            nick = message[2]
            c.execute("SELECT username FROM users WHERE nick=?", (nick,))
        else:
            nick = user.group(1)
            vhost = user.group(3)
            c.execute("SELECT username FROM users WHERE nick=? OR vhost=?", (nick, vhost))
        result = c.fetchone()

        # Use the returned username, or the entered/user's nick otherwise
        if not result:
            username2 = nick
        else:
            username2 = result[0]

        try:
            uh = urllib2.urlopen("http://ws.audioscrobbler.com/2.0/?method=tasteometer.compare&type1=user&type2=user&value1=%s&value2=%s&api_key=%s&format=json" % (username1, username2, cardinal.config['lastfm'].API_KEY))
            content = json.load(uh)
        except urllib2.URLError, e:
            cardinal.sendMsg(channel, "Unable to reach Last.fm.")
            print >> sys.stderr, "ERROR: Failed to reach the server: %s" % e.reason
            return
        except urllib2.HTTPError, e:
            cardinal.sendMsg(channel, "Unable to access Last.fm API.")
            print >> sys.stderr, "ERROR: The server did not fulfill the request. (%s Error)" % e.code
            return

        if 'error' in content and content['error'] == 10:
            cardinal.sendMsg(channel, "Last.fm plugin is not configured correctly. Please set API key.")
            return
        elif 'error' in content and content['error'] == 7:
            print content
            cardinal.sendMsg(channel, "One of the Last.fm usernames entered was invalid. Please try again.")
            return

        try:
            score = int(float(content['comparison']['result']['score']) * 100)
            artists = []
            if not 'artist' in content['comparison']['result']['artists']:
                # Return early to avoid error on looping through artists
                cardinal.sendMsg(channel, "According to Last.fm's Tasteometer, %s and %s share none of the same music." % (str(username1), str(username2)))
                return

            # Account for Last.fm giving a string instead of a list if only one artist is shared
            if not isinstance(content['comparison']['result']['artists']['artist'], list):
                artists.append(str(content['comparison']['result']['artists']['artist']['name']))
            else:
                # Loop through all artists to grab artist names
                for i in range(len(content['comparison']['result']['artists']['artist'])):
                    artists.append(str(content['comparison']['result']['artists']['artist'][i]['name']))

            cardinal.sendMsg(channel, "According to Last.fm's Tasteometer, %s and %s's music preferences are %d%% compatible! Some artists they have in common include: %s" % (str(username1), str(username2), score, ', '.join(artists)))
        except KeyError:
            cardinal.sendMsg(channel, "An unknown error has occurred.")

    compare.commands = ['compare']
    compare.help = ["Uses Last.fm to compare the compatibility of music between two users.",
                    "Syntax: .compare <username> [username]"]

    def close(self):
        self.conn.close()

def setup(cardinal):
    return LastfmPlugin(cardinal)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
# NiftyNet documentation build configuration file, created by
# sphinx-quickstart on Wed Aug 30 14:13:50 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import subprocess
import os
import sys
import pip

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))

working_dir = os.path.abspath(os.path.dirname(__file__))
root_dir_rel = os.path.join(working_dir, '..', '..')
root_dir_abs = os.path.abspath(root_dir_rel)
module_path = root_dir_abs
sys.path.insert(0, module_path)
logo_path = os.path.join(root_dir_abs, 'niftynet-logo.png')

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = [
    'tests',
    'run_*',
    'net_*',
    'setup.py',
]

def generate_apidocs(*args):
    """Generate API docs automatically by trawling the available modules"""
    # SimpleITK is an optional dependency, which is why it doesn't get
    # installed automatically via the requirements file installation hook
    # on ReadTheDocs.
    pip.main(['install', 'simpleitk'])

    global working_dir, module_path
    output_path = working_dir
    apidoc_command_path = 'sphinx-apidoc'
    if hasattr(sys, 'real_prefix'):  # called from a virtualenv
        apidoc_command_path = os.path.join(sys.prefix, 'bin', 'sphinx-apidoc')
        apidoc_command_path = os.path.abspath(apidoc_command_path)
    subprocess.check_call(
        [apidoc_command_path, '-o', output_path, module_path] +
        [os.path.join(root_dir_abs, pattern) for pattern in exclude_patterns])

def setup(app):
    # Hook to allow for automatic generation of API docs
    # before doc deployment begins.
    app.connect('builder-inited', generate_apidocs)

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.autodoc',
    'sphinx.ext.imgmath']

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'NiftyNet'
copyright = u'2017, NiftyNet Consortium'
author = u'NiftyNet Consortium'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = u''
# The full version, including alpha/beta/rc tags.
release = u''

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#
html_theme_options = {
    'logo': logo_path,
    'logo_name': 'true',
    'description': 'An open-source CNN platform for medical image analysis'
                   ' and image-guided therapy',
    'touch_icon': logo_path,
}

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# -- Options for HTMLHelp output ------------------------------------------

# Output file base name for HTML help builder.
htmlhelp_basename = 'NiftyNetdoc'

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
    # The paper size ('letterpaper' or 'a4paper').
    #
    # 'papersize': 'letterpaper',

    # The font size ('10pt', '11pt' or '12pt').
    #
    # 'pointsize': '10pt',

    # Additional stuff for the LaTeX preamble.
    #
    # 'preamble': '',

    # Latex figure (float) alignment
    #
    # 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    (master_doc, 'NiftyNet.tex', u'NiftyNet Documentation',
     u'NiftyNet Consortium', 'manual'),
]

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    (master_doc, 'niftynet', u'NiftyNet Documentation',
     [author], 1)
]

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    (master_doc, 'NiftyNet', u'NiftyNet Documentation',
     author, 'NiftyNet', 'One line description of project.',
     'Miscellaneous'),
]

<commit_msg>Issue #112: fixed relative root path<commit_after># -*- coding: utf-8 -*-
#
# NiftyNet documentation build configuration file, created by
# sphinx-quickstart on Wed Aug 30 14:13:50 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import subprocess
import os
import sys
import pip

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))

working_dir = os.path.abspath(os.path.dirname(__file__))
root_dir_rel = os.path.join('..', '..')
root_dir_abs = os.path.abspath(root_dir_rel)
module_path = root_dir_abs
sys.path.insert(0, module_path)
logo_path = os.path.join(root_dir_abs, 'niftynet-logo.png')

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = [
    'tests',
    'run_*',
    'net_*',
    'setup.py',
]

def generate_apidocs(*args):
    """Generate API docs automatically by trawling the available modules"""
    # SimpleITK is an optional dependency, which is why it doesn't get
    # installed automatically via the requirements file installation hook
    # on ReadTheDocs.
    pip.main(['install', 'simpleitk'])

    global working_dir, module_path
    output_path = working_dir
    apidoc_command_path = 'sphinx-apidoc'
    if hasattr(sys, 'real_prefix'):  # called from a virtualenv
        apidoc_command_path = os.path.join(sys.prefix, 'bin', 'sphinx-apidoc')
        apidoc_command_path = os.path.abspath(apidoc_command_path)
    subprocess.check_call(
        [apidoc_command_path, '-o', output_path, module_path] +
        [os.path.join(root_dir_abs, pattern) for pattern in exclude_patterns])

def setup(app):
    # Hook to allow for automatic generation of API docs
    # before doc deployment begins.
    app.connect('builder-inited', generate_apidocs)

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.autodoc',
    'sphinx.ext.imgmath']

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'NiftyNet'
copyright = u'2017, NiftyNet Consortium'
author = u'NiftyNet Consortium'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = u''
# The full version, including alpha/beta/rc tags.
release = u''

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#
html_theme_options = {
    'logo': logo_path,
    'logo_name': 'true',
    'description': 'An open-source CNN platform for medical image analysis'
                   ' and image-guided therapy',
    'touch_icon': logo_path,
}

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# -- Options for HTMLHelp output ------------------------------------------

# Output file base name for HTML help builder.
htmlhelp_basename = 'NiftyNetdoc'

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
    # The paper size ('letterpaper' or 'a4paper').
    #
    # 'papersize': 'letterpaper',

    # The font size ('10pt', '11pt' or '12pt').
    #
    # 'pointsize': '10pt',

    # Additional stuff for the LaTeX preamble.
    #
    # 'preamble': '',

    # Latex figure (float) alignment
    #
    # 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    (master_doc, 'NiftyNet.tex', u'NiftyNet Documentation',
     u'NiftyNet Consortium', 'manual'),
]

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    (master_doc, 'niftynet', u'NiftyNet Documentation',
     [author], 1)
]

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    (master_doc, 'NiftyNet', u'NiftyNet Documentation',
     author, 'NiftyNet', 'One line description of project.',
     'Miscellaneous'),
]

<|endoftext|>