<commit_before>from functools import partial

import sublime
from sublime_plugin import WindowCommand

from ..git_command import GitCommand
from ...common import util
from ..ui_mixins.quick_panel import show_remote_panel, show_branch_panel
from ..ui_mixins.input_panel import show_single_line_input_panel
from GitSavvy.core.runtime import enqueue_on_worker
from GitSavvy.core.utils import show_actions_panel, noop

__all__ = (
    "gs_push",
    "gs_push_to_branch",
    "gs_push_to_branch_name",
)

START_PUSH_MESSAGE = "Starting push..."
END_PUSH_MESSAGE = "Push complete."
CONFIRM_FORCE_PUSH = ("You are about to `git push {}`. Would you  "
                      "like to proceed?")

class PushBase(WindowCommand, GitCommand):
    set_upstream = False

    def do_push(self, remote, branch, force=False, force_with_lease=False, remote_branch=None):
        """
        Perform `git push remote branch`.
        """
        if self.savvy_settings.get("confirm_force_push", True):
            if force:
                if not sublime.ok_cancel_dialog(CONFIRM_FORCE_PUSH.format("--force")):
                    return
            elif force_with_lease:
                if not sublime.ok_cancel_dialog(CONFIRM_FORCE_PUSH.format("--force-with-lease")):
                    return

        self.window.status_message(START_PUSH_MESSAGE)
        self.push(
            remote,
            branch,
            set_upstream=self.set_upstream,
            force=force,
            force_with_lease=force_with_lease,
            remote_branch=remote_branch
        )
        self.window.status_message(END_PUSH_MESSAGE)
        util.view.refresh_gitsavvy(self.window.active_view())

class gs_push(PushBase):
    """
    Push current branch.
    """

    def run(self, local_branch_name=None, force=False, force_with_lease=False):
        # type: (str, bool, bool) -> None
        if local_branch_name:
            local_branch = self.get_local_branch(local_branch_name)
            if not local_branch:
                sublime.message_dialog("'{}' is not a local branch name.")
                return
        else:
            local_branch = self.get_current_branch()
            if not local_branch:
                sublime.message_dialog("Can't push a detached HEAD.")
                return

        upstream = local_branch.tracking
        if upstream:
            remote, remote_branch = upstream.split("/", 1)
            kont = partial(
                enqueue_on_worker,
                self.do_push,
                remote,
                local_branch.name,
                remote_branch=remote_branch,
                force=force,
                force_with_lease=force_with_lease
            )
            if not force and not force_with_lease and "behind" in local_branch.tracking_status:
                show_actions_panel(self.window, [
                    noop(
                        "Abort, '{}' is behind '{}/{}'."
                        .format(local_branch.name, remote, remote_branch)
                    ),
                    (
                        "Forcefully push.",
                        partial(kont, force_with_lease=True)
                    )
                ])
                return
            else:
                kont()

        else:
            self.window.run_command("gs_push_to_branch_name", {
                "local_branch_name": local_branch.name,
                "set_upstream": True,
                "force": force,
                "force_with_lease": force_with_lease
            })

class gs_push_to_branch(PushBase):
    """
    Through a series of panels, allow the user to push to a specific remote branch.
    """

    def run(self):
        enqueue_on_worker(self.run_async)

    def run_async(self):
        show_branch_panel(self.on_branch_selection, ask_remote_first=True)

    def on_branch_selection(self, branch):
        current_local_branch = self.get_current_branch_name()
        selected_remote, selected_branch = branch.split("/", 1)
        enqueue_on_worker(
            self.do_push,
            selected_remote,
            current_local_branch,
            remote_branch=selected_branch
        )

class gs_push_to_branch_name(PushBase):
    """
    Prompt for remote and remote branch name, then push.
    """

    def run(
        self,
        local_branch_name=None,
        branch_name=None,
        set_upstream=False,
        force=False,
        force_with_lease=False
    ):
        if local_branch_name:
            self.local_branch_name = local_branch_name
        else:
            self.local_branch_name = self.get_current_branch_name()

        self.branch_name = branch_name
        self.set_upstream = set_upstream
        self.force = force
        self.force_with_lease = force_with_lease
        enqueue_on_worker(self.run_async)

    def run_async(self):
        show_remote_panel(self.on_remote_selection, allow_direct=True)

    def on_remote_selection(self, remote):
        """
        After the user selects a remote, maybe prompt the user for a branch name.
        """
        self.selected_remote = remote

        if self.branch_name:
            self.on_entered_branch_name(self.branch_name)
        else:
            show_single_line_input_panel(
                "Push to {}/".format(remote),
                self.local_branch_name,
                self.on_entered_branch_name
            )

    def on_entered_branch_name(self, branch):
        """
        Push to the remote that was previously selected and provided branch
        name.
        """
        enqueue_on_worker(
            self.do_push,
            self.selected_remote,
            self.local_branch_name,
            remote_branch=branch,
            force=self.force,
            force_with_lease=self.force_with_lease
        )
<commit_msg>Move `gs_push_to_branch` class down in the source<commit_after>from functools import partial

import sublime
from sublime_plugin import WindowCommand

from ..git_command import GitCommand
from ...common import util
from ..ui_mixins.quick_panel import show_remote_panel, show_branch_panel
from ..ui_mixins.input_panel import show_single_line_input_panel
from GitSavvy.core.runtime import enqueue_on_worker
from GitSavvy.core.utils import show_actions_panel, noop

__all__ = (
    "gs_push",
    "gs_push_to_branch",
    "gs_push_to_branch_name",
)

START_PUSH_MESSAGE = "Starting push..."
END_PUSH_MESSAGE = "Push complete."
CONFIRM_FORCE_PUSH = ("You are about to `git push {}`. Would you  "
                      "like to proceed?")

class PushBase(WindowCommand, GitCommand):
    set_upstream = False

    def do_push(self, remote, branch, force=False, force_with_lease=False, remote_branch=None):
        """
        Perform `git push remote branch`.
        """
        if self.savvy_settings.get("confirm_force_push", True):
            if force:
                if not sublime.ok_cancel_dialog(CONFIRM_FORCE_PUSH.format("--force")):
                    return
            elif force_with_lease:
                if not sublime.ok_cancel_dialog(CONFIRM_FORCE_PUSH.format("--force-with-lease")):
                    return

        self.window.status_message(START_PUSH_MESSAGE)
        self.push(
            remote,
            branch,
            set_upstream=self.set_upstream,
            force=force,
            force_with_lease=force_with_lease,
            remote_branch=remote_branch
        )
        self.window.status_message(END_PUSH_MESSAGE)
        util.view.refresh_gitsavvy(self.window.active_view())

class gs_push(PushBase):
    """
    Push current branch.
    """

    def run(self, local_branch_name=None, force=False, force_with_lease=False):
        # type: (str, bool, bool) -> None
        if local_branch_name:
            local_branch = self.get_local_branch(local_branch_name)
            if not local_branch:
                sublime.message_dialog("'{}' is not a local branch name.")
                return
        else:
            local_branch = self.get_current_branch()
            if not local_branch:
                sublime.message_dialog("Can't push a detached HEAD.")
                return

        upstream = local_branch.tracking
        if upstream:
            remote, remote_branch = upstream.split("/", 1)
            kont = partial(
                enqueue_on_worker,
                self.do_push,
                remote,
                local_branch.name,
                remote_branch=remote_branch,
                force=force,
                force_with_lease=force_with_lease
            )
            if not force and not force_with_lease and "behind" in local_branch.tracking_status:
                show_actions_panel(self.window, [
                    noop(
                        "Abort, '{}' is behind '{}/{}'."
                        .format(local_branch.name, remote, remote_branch)
                    ),
                    (
                        "Forcefully push.",
                        partial(kont, force_with_lease=True)
                    )
                ])
                return
            else:
                kont()

        else:
            self.window.run_command("gs_push_to_branch_name", {
                "local_branch_name": local_branch.name,
                "set_upstream": True,
                "force": force,
                "force_with_lease": force_with_lease
            })

class gs_push_to_branch_name(PushBase):
    """
    Prompt for remote and remote branch name, then push.
    """

    def run(
        self,
        local_branch_name=None,
        branch_name=None,
        set_upstream=False,
        force=False,
        force_with_lease=False
    ):
        if local_branch_name:
            self.local_branch_name = local_branch_name
        else:
            self.local_branch_name = self.get_current_branch_name()

        self.branch_name = branch_name
        self.set_upstream = set_upstream
        self.force = force
        self.force_with_lease = force_with_lease
        enqueue_on_worker(self.run_async)

    def run_async(self):
        show_remote_panel(self.on_remote_selection, allow_direct=True)

    def on_remote_selection(self, remote):
        """
        After the user selects a remote, maybe prompt the user for a branch name.
        """
        self.selected_remote = remote

        if self.branch_name:
            self.on_entered_branch_name(self.branch_name)
        else:
            show_single_line_input_panel(
                "Push to {}/".format(remote),
                self.local_branch_name,
                self.on_entered_branch_name
            )

    def on_entered_branch_name(self, branch):
        """
        Push to the remote that was previously selected and provided branch
        name.
        """
        enqueue_on_worker(
            self.do_push,
            self.selected_remote,
            self.local_branch_name,
            remote_branch=branch,
            force=self.force,
            force_with_lease=self.force_with_lease
        )

class gs_push_to_branch(PushBase):
    """
    Through a series of panels, allow the user to push to a specific remote branch.
    """

    def run(self):
        enqueue_on_worker(self.run_async)

    def run_async(self):
        show_branch_panel(self.on_branch_selection, ask_remote_first=True)

    def on_branch_selection(self, branch):
        current_local_branch = self.get_current_branch_name()
        selected_remote, selected_branch = branch.split("/", 1)
        enqueue_on_worker(
            self.do_push,
            selected_remote,
            current_local_branch,
            remote_branch=selected_branch
        )
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# 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.

# swift documentation build configuration file, created by
# sphinx-quickstart on Mon Oct  3 17:01:55 2016.
#
# 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.

# 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('.'))

import datetime

# -- 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 = [
    'reno.sphinxext',
    'openstackdocstheme',
]

# 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 encoding of source files.
#
# source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'Swift Release Notes'
copyright = u'%d, OpenStack Foundation' % datetime.datetime.now().year

# Release notes do not need a version number in the title, they
# cover multiple releases.
# The short X.Y version.
version = ''
# The full version, including alpha/beta/rc tags.
release = ''

# 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

# 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.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']

# 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 = 'native'

# 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

# 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 = 'openstackdocs'

# 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.
# "<project> v<release> documentation" by default.
#
# html_title = u'swift v2.10.0'

# 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 (relative to this directory) to use as a 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 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 = {}

# 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

# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
#   'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
#   'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh'
#
# html_search_language = 'en'

# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
#
# html_search_options = {'type': 'default'}

# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#
# html_search_scorer = 'scorer.js'

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

# -- 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, 'swift.tex', u'swift Documentation',
#      u'swift', '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 = []

# It false, will not define \strong, \code, 	itleref, \crossref ... but only
# \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added
# packages.
#
# latex_keep_old_macro_names = True

# 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 = [
#     (master_doc, 'swift', u'swift Documentation',
#      [author], 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 = [
#     (master_doc, 'swift', u'swift Documentation',
#      author, 'swift', '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

locale_dirs = ['locale/']

# -- Options for openstackdocstheme -------------------------------------------
openstackdocs_repo_name = 'openstack/swift'
openstackdocs_auto_name = False
openstackdocs_bug_project = 'swift'
openstackdocs_bug_tag = ''
<commit_msg>doc: Comment out language option<commit_after># -*- coding: utf-8 -*-
# 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.

# swift documentation build configuration file, created by
# sphinx-quickstart on Mon Oct  3 17:01:55 2016.
#
# 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.

# 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('.'))

import datetime

# -- 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 = [
    'reno.sphinxext',
    'openstackdocstheme',
]

# 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 encoding of source files.
#
# source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'Swift Release Notes'
copyright = u'%d, OpenStack Foundation' % datetime.datetime.now().year

# Release notes do not need a version number in the title, they
# cover multiple releases.
# The short X.Y version.
version = ''
# The full version, including alpha/beta/rc tags.
release = ''

# 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

# 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.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']

# 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 = 'native'

# 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

# 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 = 'openstackdocs'

# 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.
# "<project> v<release> documentation" by default.
#
# html_title = u'swift v2.10.0'

# 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 (relative to this directory) to use as a 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 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 = {}

# 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

# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
#   'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
#   'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh'
#
# html_search_language = 'en'

# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
#
# html_search_options = {'type': 'default'}

# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#
# html_search_scorer = 'scorer.js'

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

# -- 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, 'swift.tex', u'swift Documentation',
#      u'swift', '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 = []

# It false, will not define \strong, \code, 	itleref, \crossref ... but only
# \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added
# packages.
#
# latex_keep_old_macro_names = True

# 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 = [
#     (master_doc, 'swift', u'swift Documentation',
#      [author], 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 = [
#     (master_doc, 'swift', u'swift Documentation',
#      author, 'swift', '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

locale_dirs = ['locale/']

# -- Options for openstackdocstheme -------------------------------------------
openstackdocs_repo_name = 'openstack/swift'
openstackdocs_auto_name = False
openstackdocs_bug_project = 'swift'
openstackdocs_bug_tag = ''
<|endoftext|>


<commit_before>"""From the project root directory (containing data files), this can be run with:

Boolean logic evaluation:
python -m rembed.models.classifier --training_data_path bl-data/pbl_train.tsv \
       --eval_data_path bl-data/pbl_dev.tsv

SST sentiment:
python -m rembed.models.classifier --data_type sst --embedding_dim 25 --training_data_path sst-data/train.txt \
       --eval_data_path sst-data/dev.txt
"""

from functools import partial
import pprint
import sys

import gflags
from theano import tensor as T
import theano

from rembed import afs_safe_logger
from rembed import util
from rembed.data.boolean import load_boolean_data
from rembed.data.sst import load_sst_data
import rembed.stack

FLAGS = gflags.FLAGS

def build_hard_stack(cls, vocab_size, seq_length, tokens, transitions,
                     num_classes, vs):
    """
    Construct a classifier which makes use of some hard-stack model.

    Args:
      cls: Hard stack class to use (from e.g. `rembed.stack`)
      vocab_size:
      seq_length: Length of each sequence provided to the stack model
      tokens: Theano batch (integer matrix), `batch_size * seq_length`
      transitions: Theano batch (integer matrix), `batch_size * seq_length`
      num_classes: Number of output classes
      vs: Variable store.
    """

    # Prepare layer which performs stack element composition.
    compose_network = partial(util.ReLULayer,
                              initializer=util.DoubleIdentityInitializer(FLAGS.init_range))

    # Build hard stack which scans over input sequence.
    stack = cls(
        FLAGS.embedding_dim, vocab_size, seq_length,
        compose_network, vs, X=tokens, transitions=transitions)

    # Extract top element of final stack timestep.
    final_stack = stack.final_stack
    stack_top = final_stack[:, 0]
    embeddings = stack_top.reshape((-1, FLAGS.embedding_dim))

    # Feed forward through a single output layer
    logits = util.Linear(
        embeddings, FLAGS.embedding_dim, num_classes, vs, use_bias=True)

    return stack.transitions_pred, logits

def build_cost(logits, targets):
    """
    Build a classification cost function.
    """
    # Clip gradients coming from the cost function.
    logits = theano.gradient.grad_clip(
        logits, -1 * FLAGS.clipping_max_norm, FLAGS.clipping_max_norm)

    predicted_dist = T.nnet.softmax(logits)
    costs = T.nnet.categorical_crossentropy(predicted_dist, targets)
    cost = costs.mean()

    pred = T.argmax(logits, axis=1)
    acc = 1 - T.mean(T.neq(pred, targets))

    return cost, acc

def build_action_cost(logits, targets):
    """
    Build a parse action prediction cost function.
    """

    # swap seq_length dimension to front so that we can scan per timestep
    logits = T.swapaxes(logits, 0, 1)
    targets = targets.T

    def cost_t(logits, tgt):
        # TODO(jongauthier): Taper down xent cost as we proceed through
        # sequence?
        predicted_dist = T.nnet.softmax(logits)
        cost = T.nnet.categorical_crossentropy(predicted_dist, tgt)

        pred = T.argmax(logits, axis=1)
        error = T.neq(pred, tgt)
        return cost, error

    results, _ = theano.scan(cost_t, [logits, targets])
    costs, errors = results

    # Take mean over both example- and timestep-dimensions
    cost = T.mean(costs)
    acc = 1 - T.mean(errors)
    return cost, acc

def train():
    logger = afs_safe_logger.Logger(FLAGS.experiment_name + ".log")

    if FLAGS.data_type == "bl":
        data_manager = load_boolean_data
    elif FLAGS.data_type == "sst":
        data_manager = load_sst_data
    else:
        logging.error("Bad data type.")
        return

    pp = pprint.PrettyPrinter(indent=4)
    logger.Log("Flag values:\n" + pp.pformat(FLAGS.FlagValuesDict()))

    # Load the data
    training_data_iter, vocabulary = data_manager.load_data(
        FLAGS.training_data_path, seq_length=FLAGS.seq_length, batch_size=FLAGS.batch_size, logger=logger)

    eval_sets = []
    for eval_filename in FLAGS.eval_data_path.split(","):
        eval_data_iter, _ = data_manager.load_data(
            eval_filename, vocabulary=vocabulary, seq_length=FLAGS.seq_length, batch_size=FLAGS.batch_size, eval_mode=True)
        eval_sets.append((eval_filename, eval_data_iter))

    # Set up the placeholders.
    X = T.imatrix("X")
    transitions = T.imatrix("transitions")
    y = T.ivector("y")
    lr = T.scalar("lr")

    logger.Log("Building model.")
    vs = util.VariableStore(
        default_initializer=util.UniformInitializer(FLAGS.init_range), logger=logger)
    model_cls = getattr(rembed.stack, FLAGS.model_type)
    actions, logits = build_hard_stack(
        model_cls, len(vocabulary), FLAGS.seq_length,
        X, transitions, data_manager.NUM_CLASSES, vs)

    xent_cost, acc = build_cost(logits, y)

    # Set up L2 regularization.
    # TODO(SB): Don't naively L2ify the embedding matrix. It'll break on NL.
    l2_cost = 0.0
    for var in vs.vars:
        if "embedding" not in var:
            l2_cost += FLAGS.l2_lambda * T.sum(T.sqr(vs.vars[var]))

    if actions is not None:
        # Compute cross-entropy cost on action predictions.
        action_cost, action_acc = build_action_cost(actions, transitions)
    else:
        action_cost = T.constant(0.0)
        action_acc = T.constant(0.0)

    # TODO(jongauthier): Add hyperparameter for trading off action cost vs xent
    # cost
    total_cost = xent_cost + l2_cost + action_cost

    # Set up optimization.
    new_values = util.RMSprop(total_cost, vs.vars.values(), lr)
    update_fn = theano.function(
        [X, transitions, y, lr],
        [total_cost, xent_cost, action_cost, action_acc, l2_cost, acc],
        updates=new_values)
    eval_fn = theano.function([X, transitions, y], [acc, action_acc])

    # Main training loop.
    for step in range(FLAGS.training_steps):
        X_batch, transitions_batch, y_batch = training_data_iter.next()
        ret = update_fn(X_batch, transitions_batch, y_batch,
                        FLAGS.learning_rate)
        total_cost_val, xent_cost_val, action_cost_val, action_acc_val, l2_cost_val, acc_val = ret

        if step % FLAGS.statistics_interval_steps == 0:
            logger.Log(
                "Step: %i\tAcc: %f\t%f\tCost: %5f %5f %5f %5f"
                % (step, acc_val, action_acc_val, total_cost_val, xent_cost_val, action_cost_val,
                   l2_cost_val))

        if step % FLAGS.eval_interval_steps == 0:
            for eval_set in eval_sets:
                # Evaluate
                acc_accum = 0.0
                action_acc_accum = 0.0
                eval_batches = 0.0
                for (eval_X_batch, eval_transitions_batch, eval_y_batch) in eval_set[1]:
                    acc_value, action_acc_value = eval_fn(
                        eval_X_batch, eval_transitions_batch,
                        eval_y_batch)
                    acc_accum += acc_value
                    action_acc_accum += action_acc_value
                    eval_batches += 1.0
                logger.Log("Step: %i\tEval acc: %f\t %f\t%s" %
                          (step, acc_accum / eval_batches, action_acc_accum / eval_batches, eval_set[0]))

if __name__ == '__main__':
    # Experiment naming.
    gflags.DEFINE_string("experiment_name", "experiment", "")

    # Data types.
    gflags.DEFINE_string("data_type", "bl", "Values: bl, sst")

    # Data settings.
    gflags.DEFINE_string("training_data_path", None, "")
    gflags.DEFINE_string("eval_data_path", None, "")
    gflags.DEFINE_integer("seq_length", 29, "")

    # Model architecture settings.
    # TODO(JG): What is the significance of leaving in both HardStack and the
    # models identifiers? Should HardStack just trigger Model0?
    gflags.DEFINE_enum("model_type", "HardStack",
                       ["HardStack", "Model0", "Model1", "Model2"],
                       "")
    gflags.DEFINE_integer("embedding_dim", 5, "")
    # gflags.DEFINE_integer("num_composition_layers", 1, "")

    # Optimization settings.
    gflags.DEFINE_integer("training_steps", 100000, "")
    gflags.DEFINE_integer("batch_size", 32, "")
    gflags.DEFINE_float("learning_rate", 0.005, "")
    # gflags.DEFINE_float("momentum", 0.9, "")
    gflags.DEFINE_float("clipping_max_norm", 1.0, "")
    gflags.DEFINE_float("l2_lambda", 1e-5, "")
    gflags.DEFINE_float("init_range", 0.01, "")

    # Display settings.
    gflags.DEFINE_integer("statistics_interval_steps", 50, "")
    gflags.DEFINE_integer("eval_interval_steps", 50, "")

    # Parse command line flags.
    FLAGS(sys.argv)

    # Run.
    train()
<commit_msg>Explicit Model0 default.<commit_after>"""From the project root directory (containing data files), this can be run with:

Boolean logic evaluation:
python -m rembed.models.classifier --training_data_path bl-data/pbl_train.tsv \
       --eval_data_path bl-data/pbl_dev.tsv

SST sentiment:
python -m rembed.models.classifier --data_type sst --embedding_dim 25 --training_data_path sst-data/train.txt \
       --eval_data_path sst-data/dev.txt
"""

from functools import partial
import pprint
import sys

import gflags
from theano import tensor as T
import theano

from rembed import afs_safe_logger
from rembed import util
from rembed.data.boolean import load_boolean_data
from rembed.data.sst import load_sst_data
import rembed.stack

FLAGS = gflags.FLAGS

def build_hard_stack(cls, vocab_size, seq_length, tokens, transitions,
                     num_classes, vs):
    """
    Construct a classifier which makes use of some hard-stack model.

    Args:
      cls: Hard stack class to use (from e.g. `rembed.stack`)
      vocab_size:
      seq_length: Length of each sequence provided to the stack model
      tokens: Theano batch (integer matrix), `batch_size * seq_length`
      transitions: Theano batch (integer matrix), `batch_size * seq_length`
      num_classes: Number of output classes
      vs: Variable store.
    """

    # Prepare layer which performs stack element composition.
    compose_network = partial(util.ReLULayer,
                              initializer=util.DoubleIdentityInitializer(FLAGS.init_range))

    # Build hard stack which scans over input sequence.
    stack = cls(
        FLAGS.embedding_dim, vocab_size, seq_length,
        compose_network, vs, X=tokens, transitions=transitions)

    # Extract top element of final stack timestep.
    final_stack = stack.final_stack
    stack_top = final_stack[:, 0]
    embeddings = stack_top.reshape((-1, FLAGS.embedding_dim))

    # Feed forward through a single output layer
    logits = util.Linear(
        embeddings, FLAGS.embedding_dim, num_classes, vs, use_bias=True)

    return stack.transitions_pred, logits

def build_cost(logits, targets):
    """
    Build a classification cost function.
    """
    # Clip gradients coming from the cost function.
    logits = theano.gradient.grad_clip(
        logits, -1 * FLAGS.clipping_max_norm, FLAGS.clipping_max_norm)

    predicted_dist = T.nnet.softmax(logits)
    costs = T.nnet.categorical_crossentropy(predicted_dist, targets)
    cost = costs.mean()

    pred = T.argmax(logits, axis=1)
    acc = 1 - T.mean(T.neq(pred, targets))

    return cost, acc

def build_action_cost(logits, targets):
    """
    Build a parse action prediction cost function.
    """

    # swap seq_length dimension to front so that we can scan per timestep
    logits = T.swapaxes(logits, 0, 1)
    targets = targets.T

    def cost_t(logits, tgt):
        # TODO(jongauthier): Taper down xent cost as we proceed through
        # sequence?
        predicted_dist = T.nnet.softmax(logits)
        cost = T.nnet.categorical_crossentropy(predicted_dist, tgt)

        pred = T.argmax(logits, axis=1)
        error = T.neq(pred, tgt)
        return cost, error

    results, _ = theano.scan(cost_t, [logits, targets])
    costs, errors = results

    # Take mean over both example- and timestep-dimensions
    cost = T.mean(costs)
    acc = 1 - T.mean(errors)
    return cost, acc

def train():
    logger = afs_safe_logger.Logger(FLAGS.experiment_name + ".log")

    if FLAGS.data_type == "bl":
        data_manager = load_boolean_data
    elif FLAGS.data_type == "sst":
        data_manager = load_sst_data
    else:
        logging.error("Bad data type.")
        return

    pp = pprint.PrettyPrinter(indent=4)
    logger.Log("Flag values:\n" + pp.pformat(FLAGS.FlagValuesDict()))

    # Load the data
    training_data_iter, vocabulary = data_manager.load_data(
        FLAGS.training_data_path, seq_length=FLAGS.seq_length, batch_size=FLAGS.batch_size, logger=logger)

    eval_sets = []
    for eval_filename in FLAGS.eval_data_path.split(","):
        eval_data_iter, _ = data_manager.load_data(
            eval_filename, vocabulary=vocabulary, seq_length=FLAGS.seq_length, batch_size=FLAGS.batch_size, eval_mode=True)
        eval_sets.append((eval_filename, eval_data_iter))

    # Set up the placeholders.
    X = T.imatrix("X")
    transitions = T.imatrix("transitions")
    y = T.ivector("y")
    lr = T.scalar("lr")

    logger.Log("Building model.")
    vs = util.VariableStore(
        default_initializer=util.UniformInitializer(FLAGS.init_range), logger=logger)
    model_cls = getattr(rembed.stack, FLAGS.model_type)
    actions, logits = build_hard_stack(
        model_cls, len(vocabulary), FLAGS.seq_length,
        X, transitions, data_manager.NUM_CLASSES, vs)

    xent_cost, acc = build_cost(logits, y)

    # Set up L2 regularization.
    # TODO(SB): Don't naively L2ify the embedding matrix. It'll break on NL.
    l2_cost = 0.0
    for var in vs.vars:
        if "embedding" not in var:
            l2_cost += FLAGS.l2_lambda * T.sum(T.sqr(vs.vars[var]))

    if actions is not None:
        # Compute cross-entropy cost on action predictions.
        action_cost, action_acc = build_action_cost(actions, transitions)
    else:
        action_cost = T.constant(0.0)
        action_acc = T.constant(0.0)

    # TODO(jongauthier): Add hyperparameter for trading off action cost vs xent
    # cost
    total_cost = xent_cost + l2_cost + action_cost

    # Set up optimization.
    new_values = util.RMSprop(total_cost, vs.vars.values(), lr)
    update_fn = theano.function(
        [X, transitions, y, lr],
        [total_cost, xent_cost, action_cost, action_acc, l2_cost, acc],
        updates=new_values)
    eval_fn = theano.function([X, transitions, y], [acc, action_acc])

    # Main training loop.
    for step in range(FLAGS.training_steps):
        X_batch, transitions_batch, y_batch = training_data_iter.next()
        ret = update_fn(X_batch, transitions_batch, y_batch,
                        FLAGS.learning_rate)
        total_cost_val, xent_cost_val, action_cost_val, action_acc_val, l2_cost_val, acc_val = ret

        if step % FLAGS.statistics_interval_steps == 0:
            logger.Log(
                "Step: %i\tAcc: %f\t%f\tCost: %5f %5f %5f %5f"
                % (step, acc_val, action_acc_val, total_cost_val, xent_cost_val, action_cost_val,
                   l2_cost_val))

        if step % FLAGS.eval_interval_steps == 0:
            for eval_set in eval_sets:
                # Evaluate
                acc_accum = 0.0
                action_acc_accum = 0.0
                eval_batches = 0.0
                for (eval_X_batch, eval_transitions_batch, eval_y_batch) in eval_set[1]:
                    acc_value, action_acc_value = eval_fn(
                        eval_X_batch, eval_transitions_batch,
                        eval_y_batch)
                    acc_accum += acc_value
                    action_acc_accum += action_acc_value
                    eval_batches += 1.0
                logger.Log("Step: %i\tEval acc: %f\t %f\t%s" %
                          (step, acc_accum / eval_batches, action_acc_accum / eval_batches, eval_set[0]))

if __name__ == '__main__':
    # Experiment naming.
    gflags.DEFINE_string("experiment_name", "experiment", "")

    # Data types.
    gflags.DEFINE_string("data_type", "bl", "Values: bl, sst")

    # Data settings.
    gflags.DEFINE_string("training_data_path", None, "")
    gflags.DEFINE_string("eval_data_path", None, "")
    gflags.DEFINE_integer("seq_length", 29, "")

    # Model architecture settings.
    # TODO(JG): What is the significance of leaving in both HardStack and the
    # models identifiers? Should HardStack just trigger Model0?
    gflags.DEFINE_enum("model_type", "Model0",
                       ["HardStack", "Model0", "Model1", "Model2"],
                       "")
    gflags.DEFINE_integer("embedding_dim", 5, "")
    # gflags.DEFINE_integer("num_composition_layers", 1, "")

    # Optimization settings.
    gflags.DEFINE_integer("training_steps", 100000, "")
    gflags.DEFINE_integer("batch_size", 32, "")
    gflags.DEFINE_float("learning_rate", 0.005, "")
    # gflags.DEFINE_float("momentum", 0.9, "")
    gflags.DEFINE_float("clipping_max_norm", 1.0, "")
    gflags.DEFINE_float("l2_lambda", 1e-5, "")
    gflags.DEFINE_float("init_range", 0.01, "")

    # Display settings.
    gflags.DEFINE_integer("statistics_interval_steps", 50, "")
    gflags.DEFINE_integer("eval_interval_steps", 50, "")

    # Parse command line flags.
    FLAGS(sys.argv)

    # Run.
    train()
<|endoftext|>


<commit_before>from django.http import Http404
from rest_framework.generics import CreateAPIView, RetrieveUpdateAPIView, get_object_or_404
from rest_framework.response import Response
from rest_framework.views import APIView

from agency.permissions import AgencyPermission
from common.permissions import current_user_has_permission, HasUNPPPermission
from externals.models import PartnerVendorNumber
from externals.serializers import PartnerVendorNumberSerializer
from externals.sources.unhcr import UNHCRInfoClient

class PartnerVendorNumberAPIView(CreateAPIView, RetrieveUpdateAPIView):

    serializer_class = PartnerVendorNumberSerializer
    queryset = PartnerVendorNumber.objects.all()
    permission_classes = (
        HasUNPPPermission(
            agency_permissions=[]
        ),
    )

    def get_queryset(self):
        queryset = super(PartnerVendorNumberAPIView, self).get_queryset()
        if not self.request.method == 'GET':
            current_user_has_permission(self.request, agency_permissions=[
                AgencyPermission.ERP_ENTER_VENDOR_NUMBER,
            ], raise_exception=True)
            queryset = queryset.filter(agency=self.request.user.agency)

        return queryset

class PartnerExternalDetailsAPIView(APIView):

    permission_classes = (
        HasUNPPPermission(
            agency_permissions=[],
            partner_permissions=[],
        ),
    )
    provider_for_agency = {
        'UNHCR': UNHCRInfoClient,
    }

    def get_queryset(self):
        queryset = PartnerVendorNumber.objects.all()
        if not self.request.agency_member:
            queryset = queryset.filter(partner=self.request.active_partner)

        return queryset

    def get(self, request, *args, **kwargs):
        vendor_number = get_object_or_404(
            self.get_queryset(), partner_id=kwargs['partner_id'], agency_id=kwargs['agency_id']
        )
        provider = self.provider_for_agency.get(vendor_number.agency.name)
        if not provider:
            raise Http404
        return Response({
            'tables': provider().get_tables(vendor_number.number)
        })
<commit_msg>added delete viewa<commit_after>from django.http import Http404
from rest_framework.generics import CreateAPIView, RetrieveUpdateAPIView, get_object_or_404, DestroyAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from agency.permissions import AgencyPermission
from common.permissions import current_user_has_permission, HasUNPPPermission
from externals.models import PartnerVendorNumber
from externals.serializers import PartnerVendorNumberSerializer
from externals.sources.unhcr import UNHCRInfoClient

class PartnerVendorNumberAPIView(CreateAPIView, RetrieveUpdateAPIView, DestroyAPIView):

    serializer_class = PartnerVendorNumberSerializer
    queryset = PartnerVendorNumber.objects.all()
    permission_classes = (
        HasUNPPPermission(
            agency_permissions=[]
        ),
    )

    def get_queryset(self):
        queryset = super(PartnerVendorNumberAPIView, self).get_queryset()
        if not self.request.method == 'GET':
            current_user_has_permission(self.request, agency_permissions=[
                AgencyPermission.ERP_ENTER_VENDOR_NUMBER,
            ], raise_exception=True)
            queryset = queryset.filter(agency=self.request.user.agency)

        return queryset

class PartnerExternalDetailsAPIView(APIView):

    permission_classes = (
        HasUNPPPermission(
            agency_permissions=[],
            partner_permissions=[],
        ),
    )
    provider_for_agency = {
        'UNHCR': UNHCRInfoClient,
    }

    def get_queryset(self):
        queryset = PartnerVendorNumber.objects.all()
        if not self.request.agency_member:
            queryset = queryset.filter(partner=self.request.active_partner)

        return queryset

    def get(self, request, *args, **kwargs):
        vendor_number = get_object_or_404(
            self.get_queryset(), partner_id=kwargs['partner_id'], agency_id=kwargs['agency_id']
        )
        provider = self.provider_for_agency.get(vendor_number.agency.name)
        if not provider:
            raise Http404
        return Response({
            'tables': provider().get_tables(vendor_number.number)
        })
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals

from django import forms

from core.models import Investigation, Project, ProjectTracking

class TrackProjectForm(forms.ModelForm):
    project = forms.ModelChoiceField(queryset=Project.active_objects.all())

    def save(self, **kwargs):
        commit = kwargs.pop('commit', True)
        user = kwargs.pop('user', None)

        instance = super(TrackProjectForm, self).save(commit=False)
        instance.user = user

        if commit:
            instance.save()

        return instance

    class Meta:
        model = ProjectTracking
        fields = ('project', 'is_owner',)

class CreateProjectForm(forms.ModelForm):

    class Meta:
        model = Project
        fields = ('name', 'description',)

    def clean_name(self):
        name = self.cleaned_data['name']
        reserved_names = [
            'create',
            'track',
            'all'
        ]
        if name in reserved_names:
            self.add_error('name',
                'Project name "{}" is reserved, please choose another'.format(name))
        return name

class CreateInvestigationForm(forms.ModelForm):

    class Meta:
        model = Investigation
        fields = ('name', 'description',)

    def clean_name(self):
        name = self.cleaned_data['name']
        reserved_names = [
            'activate',
            'deactivate',
            'add-investigation'
        ]
        if name in reserved_names:
            self.add_error('name',
                'Investigation name "{}" is reserved, please choose another'.format(name))
        return name
<commit_msg>Added 'all' to reserved names for investigation<commit_after># -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals

from django import forms

from core.models import Investigation, Project, ProjectTracking

class TrackProjectForm(forms.ModelForm):
    project = forms.ModelChoiceField(queryset=Project.active_objects.all())

    def save(self, **kwargs):
        commit = kwargs.pop('commit', True)
        user = kwargs.pop('user', None)

        instance = super(TrackProjectForm, self).save(commit=False)
        instance.user = user

        if commit:
            instance.save()

        return instance

    class Meta:
        model = ProjectTracking
        fields = ('project', 'is_owner',)

class CreateProjectForm(forms.ModelForm):

    class Meta:
        model = Project
        fields = ('name', 'description',)

    def clean_name(self):
        name = self.cleaned_data['name']
        reserved_names = [
            'create',
            'track',
            'all',
        ]
        if name in reserved_names:
            self.add_error('name',
                'Project name "{}" is reserved, please choose another'.format(name))
        return name

class CreateInvestigationForm(forms.ModelForm):

    class Meta:
        model = Investigation
        fields = ('name', 'description',)

    def clean_name(self):
        name = self.cleaned_data['name']
        reserved_names = [
            'activate',
            'deactivate',
            'add-investigation',
            'all',
        ]
        if name in reserved_names:
            self.add_error('name',
                'Investigation name "{}" is reserved, please choose another'.format(name))
        return name
<|endoftext|>


<commit_before>#!/usr/bin/env python
# coding: utf-8
# References:
# man curl
# https://curl.haxx.se/libcurl/c/curl_easy_getinfo.html
# https://curl.haxx.se/libcurl/c/easy_getinfo_options.html
# http://blog.kenweiner.com/2014/11/http-request-timings-with-curl.html

from __future__ import print_function

import os
import json
import sys
import logging
import tempfile
import subprocess

__version__ = '1.1.3'

PY3 = sys.version_info >= (3,)

if PY3:
    xrange = range

class Env(object):
    prefix = 'HTTPSTAT'

    def __init__(self, key):
        self.key = key.format(prefix=self.prefix)

    def get(self, default=None):
        return os.environ.get(self.key, default)

ENV_SHOW_BODY = Env('{prefix}_SHOW_BODY')
ENV_SHOW_SPEED = Env('{prefix}_SHOW_SPEED')
ENV_CURL_BIN = Env('{prefix}_CURL_BIN')
ENV_DEBUG = Env('{prefix}_DEBUG')

curl_format = """{
"time_namelookup": %{time_namelookup},
"time_connect": %{time_connect},
"time_appconnect": %{time_appconnect},
"time_pretransfer": %{time_pretransfer},
"time_redirect": %{time_redirect},
"time_starttransfer": %{time_starttransfer},
"time_total": %{time_total},
"speed_download": %{speed_download},
"speed_upload": %{speed_upload}
}"""

https_template = """
  DNS Lookup   TCP Connection   SSL Handshake   Server Processing   Content Transfer
[   {a0000}  |     {a0001}    |    {a0002}    |      {a0003}      |      {a0004}     ]
             |                |               |                   |                  |
    namelookup:{b0000}        |               |                   |                  |
                        connect:{b0001}       |                   |                  |
                                    pretransfer:{b0002}           |                  |
                                                      starttransfer:{b0003}          |
                                                                                total:{b0004}
"""[1:]

http_template = """
  DNS Lookup   TCP Connection   Server Processing   Content Transfer
[   {a0000}  |     {a0001}    |      {a0003}      |      {a0004}     ]
             |                |                   |                  |
    namelookup:{b0000}        |                   |                  |
                        connect:{b0001}           |                  |
                                      starttransfer:{b0003}          |
                                                                 total:{b0004}
"""[1:]

ISATTY = sys.stdout.isatty()

def make_color(code):
    def color_func(s):
        if not ISATTY:
            return s
        tpl = '\x1b[{}m{}\x1b[0m'
        return tpl.format(code, s)
    return color_func

red = make_color(31)
green = make_color(32)
yellow = make_color(33)
blue = make_color(34)
magenta = make_color(35)
cyan = make_color(36)

bold = make_color(1)
underline = make_color(4)

grayscale = {(i - 232): make_color('38;5;' + str(i)) for i in xrange(232, 256)}

def quit(s, code=0):
    if s is not None:
        print(s)
    sys.exit(code)

def print_help():
    help = """
Usage: httpstat URL [CURL_OPTIONS]
       httpstat -h | --help
       httpstat --version

Arguments:
  URL     url to request, could be with or without `http(s)://` prefix

Options:
  CURL_OPTIONS  any curl supported options, except for -w -D -o -S -s,
                which are already used internally.
  -h --help     show this screen.
  --version     show version.

Environments:
  HTTPSTAT_SHOW_BODY    By default httpstat will write response body
                        in a tempfile, but you can let it print out by setting
                        this variable to `true`.
  HTTPSTAT_SHOW_SPEED   set to `true` to show download and upload speed.
"""[1:-1]
    print(help)

def main():
    args = sys.argv[1:]
    if not args:
        print_help()
        quit(None, 0)

    # get envs
    show_body = 'true' in ENV_SHOW_BODY.get('false').lower()
    show_speed = 'true'in ENV_SHOW_SPEED.get('false').lower()
    curl_bin = ENV_CURL_BIN.get('curl')
    is_debug = 'true' in ENV_DEBUG.get('false').lower()

    # configure logging
    if is_debug:
        log_level = logging.DEBUG
    else:
        log_level = logging.INFO
    logging.basicConfig(level=log_level)
    lg = logging.getLogger('httpstat')

    # log envs
    lg.debug(
        'ENVs:\n'
        '  {show_body_key}: {show_body}\n'
        '  {show_speed_key}: {show_speed}\n'
        '  {curl_bin_key}: {curl_bin}\n'
        '  {is_debug_key}: {is_debug}\n'.format(
            show_body_key=ENV_SHOW_BODY.key,
            show_body=show_body,
            show_speed_key=ENV_SHOW_SPEED.key,
            show_speed=show_speed,
            curl_bin_key=ENV_CURL_BIN.key,
            curl_bin=curl_bin,
            is_debug_key=ENV_DEBUG.key,
            is_debug=is_debug,
        )
    )

    # get url
    url = args[0]
    if url in ['-h', '--help']:
        print_help()
        quit(None, 0)
    elif url == '--version':
        print('httpstat {}'.format(__version__))
        quit(None, 0)

    curl_args = args[1:]

    # check curl args
    exclude_options = [
        '-w', '--write-out',
        '-D', '--dump-header',
        '-o', '--output',
        '-s', '--silent',
    ]
    for i in exclude_options:
        if i in curl_args:
            quit(yellow('Error: {} is not allowed in extra curl args'.format(i)), 1)

    # tempfile for output
    bodyf = tempfile.NamedTemporaryFile(delete=False)
    bodyf.close()

    headerf = tempfile.NamedTemporaryFile(delete=False)
    headerf.close()

    # run cmd
    cmd_env = os.environ.copy()
    cmd_env.update(
        LC_ALL='C',
    )
    cmd_core = [curl_bin, '-w', curl_format, '-D', headerf.name, '-o', bodyf.name, '-s', '-S']
    cmd = cmd_core + curl_args + [url]
    lg.debug('cmd: %s', cmd)
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=cmd_env)
    out, err = p.communicate()
    if PY3:
        out, err = out.decode(), err.decode()

    # print stderr
    if p.returncode == 0:
        print(grayscale[16](err))
    else:
        _cmd = list(cmd)
        _cmd[2] = '<output-format>'
        _cmd[4] = '<tempfile>'
        _cmd[6] = '<tempfile>'
        print('> {}'.format(' '.join(_cmd)))
        quit(yellow('curl error: {}'.format(err)), p.returncode)

    # parse output
    try:
        d = json.loads(out)
    except ValueError as e:
        print(yellow('Could not decode json: {}'.format(e)))
        print('curl result:', p.returncode, grayscale[16](out), grayscale[16](err))
        quit(None, 1)
    for k in d:
        if k.startswith('time_'):
            d[k] = int(d[k] * 1000)

    # calculate ranges
    d.update(
        range_dns=d['time_namelookup'],
        range_connection=d['time_connect'] - d['time_namelookup'],
        range_ssl=d['time_pretransfer'] - d['time_connect'],
        range_server=d['time_starttransfer'] - d['time_pretransfer'],
        range_transfer=d['time_total'] - d['time_starttransfer'],
    )

    # print header & body summary
    with open(headerf.name, 'r') as f:
        headers = f.read().strip()
    # remove header file
    os.remove(headerf.name)

    for loop, line in enumerate(headers.split('\n')):
        if loop == 0:
            p1, p2 = tuple(line.split('/'))
            print(green(p1) + grayscale[14]('/') + cyan(p2))
        else:
            pos = line.find(':')
            print(grayscale[14](line[:pos + 1]) + cyan(line[pos + 1:]))

    print()

    # body
    if show_body:
        body_limit = 1024
        with open(bodyf.name, 'r') as f:
            body = f.read().strip()
        if len(body) > body_limit:
            print(body[:body_limit] + '... (more in {})'.format(bodyf.name))
        else:
            print(body)
    else:
        print('{} stored in: {}'.format(green('Body'), bodyf.name))

    # print stat
    if url.startswith('https://'):
        template = https_template
    else:
        template = http_template

    # colorize template first line
    tpl_parts = template.split('\n')
    tpl_parts[0] = grayscale[16](tpl_parts[0])
    template = '\n'.join(tpl_parts)

    def fmta(s):
        return cyan('{:^7}'.format(str(s) + 'ms'))

    def fmtb(s):
        return cyan('{:<7}'.format(str(s) + 'ms'))

    stat = template.format(
        # a
        a0000=fmta(d['range_dns']),
        a0001=fmta(d['range_connection']),
        a0002=fmta(d['range_ssl']),
        a0003=fmta(d['range_server']),
        a0004=fmta(d['range_transfer']),
        # b
        b0000=fmtb(d['time_namelookup']),
        b0001=fmtb(d['time_connect']),
        b0002=fmtb(d['time_pretransfer']),
        b0003=fmtb(d['time_starttransfer']),
        b0004=fmtb(d['time_total']),
    )
    print()
    print(stat)

    # speed, originally bytes per second
    if show_speed:
        print('speed_download: {:.1f} KiB, speed_upload: {:.1f} KiB'.format(
            d['speed_download'] / 1024, d['speed_upload'] / 1024))

if __name__ == '__main__':
    main()
<commit_msg>add `/s` for speed info<commit_after>#!/usr/bin/env python
# coding: utf-8
# References:
# man curl
# https://curl.haxx.se/libcurl/c/curl_easy_getinfo.html
# https://curl.haxx.se/libcurl/c/easy_getinfo_options.html
# http://blog.kenweiner.com/2014/11/http-request-timings-with-curl.html

from __future__ import print_function

import os
import json
import sys
import logging
import tempfile
import subprocess

__version__ = '1.1.3'

PY3 = sys.version_info >= (3,)

if PY3:
    xrange = range

class Env(object):
    prefix = 'HTTPSTAT'

    def __init__(self, key):
        self.key = key.format(prefix=self.prefix)

    def get(self, default=None):
        return os.environ.get(self.key, default)

ENV_SHOW_BODY = Env('{prefix}_SHOW_BODY')
ENV_SHOW_SPEED = Env('{prefix}_SHOW_SPEED')
ENV_CURL_BIN = Env('{prefix}_CURL_BIN')
ENV_DEBUG = Env('{prefix}_DEBUG')

curl_format = """{
"time_namelookup": %{time_namelookup},
"time_connect": %{time_connect},
"time_appconnect": %{time_appconnect},
"time_pretransfer": %{time_pretransfer},
"time_redirect": %{time_redirect},
"time_starttransfer": %{time_starttransfer},
"time_total": %{time_total},
"speed_download": %{speed_download},
"speed_upload": %{speed_upload}
}"""

https_template = """
  DNS Lookup   TCP Connection   SSL Handshake   Server Processing   Content Transfer
[   {a0000}  |     {a0001}    |    {a0002}    |      {a0003}      |      {a0004}     ]
             |                |               |                   |                  |
    namelookup:{b0000}        |               |                   |                  |
                        connect:{b0001}       |                   |                  |
                                    pretransfer:{b0002}           |                  |
                                                      starttransfer:{b0003}          |
                                                                                total:{b0004}
"""[1:]

http_template = """
  DNS Lookup   TCP Connection   Server Processing   Content Transfer
[   {a0000}  |     {a0001}    |      {a0003}      |      {a0004}     ]
             |                |                   |                  |
    namelookup:{b0000}        |                   |                  |
                        connect:{b0001}           |                  |
                                      starttransfer:{b0003}          |
                                                                 total:{b0004}
"""[1:]

ISATTY = sys.stdout.isatty()

def make_color(code):
    def color_func(s):
        if not ISATTY:
            return s
        tpl = '\x1b[{}m{}\x1b[0m'
        return tpl.format(code, s)
    return color_func

red = make_color(31)
green = make_color(32)
yellow = make_color(33)
blue = make_color(34)
magenta = make_color(35)
cyan = make_color(36)

bold = make_color(1)
underline = make_color(4)

grayscale = {(i - 232): make_color('38;5;' + str(i)) for i in xrange(232, 256)}

def quit(s, code=0):
    if s is not None:
        print(s)
    sys.exit(code)

def print_help():
    help = """
Usage: httpstat URL [CURL_OPTIONS]
       httpstat -h | --help
       httpstat --version

Arguments:
  URL     url to request, could be with or without `http(s)://` prefix

Options:
  CURL_OPTIONS  any curl supported options, except for -w -D -o -S -s,
                which are already used internally.
  -h --help     show this screen.
  --version     show version.

Environments:
  HTTPSTAT_SHOW_BODY    By default httpstat will write response body
                        in a tempfile, but you can let it print out by setting
                        this variable to `true`.
  HTTPSTAT_SHOW_SPEED   set to `true` to show download and upload speed.
"""[1:-1]
    print(help)

def main():
    args = sys.argv[1:]
    if not args:
        print_help()
        quit(None, 0)

    # get envs
    show_body = 'true' in ENV_SHOW_BODY.get('false').lower()
    show_speed = 'true'in ENV_SHOW_SPEED.get('false').lower()
    curl_bin = ENV_CURL_BIN.get('curl')
    is_debug = 'true' in ENV_DEBUG.get('false').lower()

    # configure logging
    if is_debug:
        log_level = logging.DEBUG
    else:
        log_level = logging.INFO
    logging.basicConfig(level=log_level)
    lg = logging.getLogger('httpstat')

    # log envs
    lg.debug(
        'ENVs:\n'
        '  {show_body_key}: {show_body}\n'
        '  {show_speed_key}: {show_speed}\n'
        '  {curl_bin_key}: {curl_bin}\n'
        '  {is_debug_key}: {is_debug}\n'.format(
            show_body_key=ENV_SHOW_BODY.key,
            show_body=show_body,
            show_speed_key=ENV_SHOW_SPEED.key,
            show_speed=show_speed,
            curl_bin_key=ENV_CURL_BIN.key,
            curl_bin=curl_bin,
            is_debug_key=ENV_DEBUG.key,
            is_debug=is_debug,
        )
    )

    # get url
    url = args[0]
    if url in ['-h', '--help']:
        print_help()
        quit(None, 0)
    elif url == '--version':
        print('httpstat {}'.format(__version__))
        quit(None, 0)

    curl_args = args[1:]

    # check curl args
    exclude_options = [
        '-w', '--write-out',
        '-D', '--dump-header',
        '-o', '--output',
        '-s', '--silent',
    ]
    for i in exclude_options:
        if i in curl_args:
            quit(yellow('Error: {} is not allowed in extra curl args'.format(i)), 1)

    # tempfile for output
    bodyf = tempfile.NamedTemporaryFile(delete=False)
    bodyf.close()

    headerf = tempfile.NamedTemporaryFile(delete=False)
    headerf.close()

    # run cmd
    cmd_env = os.environ.copy()
    cmd_env.update(
        LC_ALL='C',
    )
    cmd_core = [curl_bin, '-w', curl_format, '-D', headerf.name, '-o', bodyf.name, '-s', '-S']
    cmd = cmd_core + curl_args + [url]
    lg.debug('cmd: %s', cmd)
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=cmd_env)
    out, err = p.communicate()
    if PY3:
        out, err = out.decode(), err.decode()

    # print stderr
    if p.returncode == 0:
        print(grayscale[16](err))
    else:
        _cmd = list(cmd)
        _cmd[2] = '<output-format>'
        _cmd[4] = '<tempfile>'
        _cmd[6] = '<tempfile>'
        print('> {}'.format(' '.join(_cmd)))
        quit(yellow('curl error: {}'.format(err)), p.returncode)

    # parse output
    try:
        d = json.loads(out)
    except ValueError as e:
        print(yellow('Could not decode json: {}'.format(e)))
        print('curl result:', p.returncode, grayscale[16](out), grayscale[16](err))
        quit(None, 1)
    for k in d:
        if k.startswith('time_'):
            d[k] = int(d[k] * 1000)

    # calculate ranges
    d.update(
        range_dns=d['time_namelookup'],
        range_connection=d['time_connect'] - d['time_namelookup'],
        range_ssl=d['time_pretransfer'] - d['time_connect'],
        range_server=d['time_starttransfer'] - d['time_pretransfer'],
        range_transfer=d['time_total'] - d['time_starttransfer'],
    )

    # print header & body summary
    with open(headerf.name, 'r') as f:
        headers = f.read().strip()
    # remove header file
    os.remove(headerf.name)

    for loop, line in enumerate(headers.split('\n')):
        if loop == 0:
            p1, p2 = tuple(line.split('/'))
            print(green(p1) + grayscale[14]('/') + cyan(p2))
        else:
            pos = line.find(':')
            print(grayscale[14](line[:pos + 1]) + cyan(line[pos + 1:]))

    print()

    # body
    if show_body:
        body_limit = 1024
        with open(bodyf.name, 'r') as f:
            body = f.read().strip()
        if len(body) > body_limit:
            print(body[:body_limit] + '... (more in {})'.format(bodyf.name))
        else:
            print(body)
    else:
        print('{} stored in: {}'.format(green('Body'), bodyf.name))

    # print stat
    if url.startswith('https://'):
        template = https_template
    else:
        template = http_template

    # colorize template first line
    tpl_parts = template.split('\n')
    tpl_parts[0] = grayscale[16](tpl_parts[0])
    template = '\n'.join(tpl_parts)

    def fmta(s):
        return cyan('{:^7}'.format(str(s) + 'ms'))

    def fmtb(s):
        return cyan('{:<7}'.format(str(s) + 'ms'))

    stat = template.format(
        # a
        a0000=fmta(d['range_dns']),
        a0001=fmta(d['range_connection']),
        a0002=fmta(d['range_ssl']),
        a0003=fmta(d['range_server']),
        a0004=fmta(d['range_transfer']),
        # b
        b0000=fmtb(d['time_namelookup']),
        b0001=fmtb(d['time_connect']),
        b0002=fmtb(d['time_pretransfer']),
        b0003=fmtb(d['time_starttransfer']),
        b0004=fmtb(d['time_total']),
    )
    print()
    print(stat)

    # speed, originally bytes per second
    if show_speed:
        print('speed_download: {:.1f} KiB/s, speed_upload: {:.1f} KiB/s'.format(
            d['speed_download'] / 1024, d['speed_upload'] / 1024))

if __name__ == '__main__':
    main()
<|endoftext|>


<commit_before>import sys, platform, os, traceback, datetime, codecs
from twisted.words.protocols import irc
from twisted.internet import protocol, reactor

from IRCResponse import IRCResponse, ResponseType
from IRCMessage import IRCMessage
from FunctionHandler import AutoLoadFunctions
import GlobalVars

class HubbeBot(irc.IRCClient):

    nickname = GlobalVars.CurrentNick

    realname = GlobalVars.CurrentNick
    username = GlobalVars.CurrentNick

    fingerReply = GlobalVars.finger

    versionName = GlobalVars.CurrentNick
    versionNum = GlobalVars.version
    versionEnv = platform.platform()

    sourceURL = GlobalVars.source

    responses = []

    def signedOn(self):
        for channel in sys.argv[2:]:
            self.join(channel)

    def privmsg(self, user, channel, msg):
        message = IRCMessage('PRIVMSG', user, channel, msg)
        if msg.startswith(GlobalVars.CommandChar):
            self.log(u'<{0}> {1}'.format(message.User.Name, message.MessageString), message.ReplyTo)
        self.handleMessage(message)

    def action(self, user, channel, msg):
        message = IRCMessage('ACTION', user, channel, msg)
        self.log(u'*{0} {1}*'.format(message.User.Name, message.MessageString), message.ReplyTo)
        self.handleMessage(message)

    def noticed(self, user, channel, msg):
        message = IRCMessage('NOTICE', user, channel, msg.upper())
        self.log(u'[{0}] {1}'.format(message.User.Name, message.MessageString), message.ReplyTo)
        self.handleMessage(message)

    def nickChanged(self, nick):
        self.nickname = nick
        GlobalVars.CurrentNick = nick

    def irc_JOIN(self, prefix, params):
        message = IRCMessage('JOIN', prefix, params[0], '')

    def irc_PART(self, prefix, params):
        partMessage = u''
        if len(params) > 1:
            partMessage = u', message: '+u' '.join(params[1:])
        message = IRCMessage('PART', prefix, params[0], partMessage)

    def sendResponse(self, response):
        if (response == None or response.Response == None):
            return False

        if (response.Type == ResponseType.Say):
            self.msg(response.Target, response.Response.encode('utf-8'))
            self.log(u'<{0}> {1}'.format(self.nickname, response.Response), response.Target)
        elif (response.Type == ResponseType.Do):
            self.describe(response.Target, response.Response.encode('utf-8'))
            self.log(u'*{0} {1}*'.format(self.nickname, response.Response), response.Target)
        elif (response.Type == ResponseType.Notice):
            self.notice(response.Target, response.Response.encode('utf-8'))
            self.log(u'[{0}] {1}'.format(self.nickname, response.Response), response.Target)
        elif (response.Type == ResponseType.Raw):
            self.sendLine(response.Response.encode('utf-8'))

    def handleMessage(self, message):
        for (name, func) in GlobalVars.functions.items():
            try:
                response = func.GetResponse(message)
                if response is None:
                    continue
                if hasattr(response, '__iter__'):
                    for r in response:
                        self.responses.append(r)
                else:
                    self.responses.append(response)
            except Exception:
                print "Python Execution Error in '%s': %s" % (name, str( sys.exc_info() ))
                traceback.print_tb(sys.exc_info()[2])

        for response in self.responses:
            self.sendResponse(response)
        self.responses = []

    def log(self, text, target):
        now = datetime.datetime.utcnow()
        time = now.strftime("[%H:%M]")
        data = u'{0} {1}'.format(time, text)
        print target, data

        fileName = "{0}{1}.txt".format(target, now.strftime("-%Y%m%d"))
        fileDirs = os.path.join(GlobalVars.logPath, sys.argv[1])
        if not os.path.exists(fileDirs):
            os.makedirs(fileDirs)
        filePath = os.path.join(fileDirs, fileName)

        with codecs.open(filePath, 'a+', 'utf-8') as f:
            f.write(data + '\n')

class HubbeBotFactory(protocol.ReconnectingClientFactory):

	protocol = HubbeBot

	def startedConnecting(self, connector):
            print "-#- Started to connect."

        def buildProtocol(self, addr):
            print "-#- Connected."
            print "-#- Resetting reconnectiong delay"
            self.resetDelay()
            return HubbeBot()

        def clientConnectionLost(self, connector, reason):
            print "-!- Connection lost. Reason:", reason
            protocol.ReconnectingClientFactory.clientConnectionLost(self, connector, reason)

        def clientConnectionFailed(self, connector, reason):
            print "-!- Connection failed. Reason:", reason
            protocol.ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)

if __name__ == "__main__":
    if len(sys.argv)< 3:
        print "Correct usage: hubbot.py <server> <channel> [channel]"
    else:
        AutoLoadFunctions()
        hubbot = HubbeBotFactory()
        reactor.connectTCP(sys.argv[1], GlobalVars.port, hubbot)
        reactor.run()
<commit_msg>Log even less things and some different things<commit_after>import sys, platform, os, traceback, datetime, codecs
from twisted.words.protocols import irc
from twisted.internet import protocol, reactor

from IRCResponse import IRCResponse, ResponseType
from IRCMessage import IRCMessage
from FunctionHandler import AutoLoadFunctions
import GlobalVars

class HubbeBot(irc.IRCClient):

    nickname = GlobalVars.CurrentNick

    realname = GlobalVars.CurrentNick
    username = GlobalVars.CurrentNick

    fingerReply = GlobalVars.finger

    versionName = GlobalVars.CurrentNick
    versionNum = GlobalVars.version
    versionEnv = platform.platform()

    sourceURL = GlobalVars.source

    responses = []

    def signedOn(self):
        for channel in sys.argv[2:]:
            self.join(channel)

    def privmsg(self, user, channel, msg):
        message = IRCMessage('PRIVMSG', user, channel, msg)
        if msg.startswith(GlobalVars.CommandChar):
            self.log(u'<{0}> {1}'.format(message.User.Name, message.MessageString), message.ReplyTo)
        self.handleMessage(message)

    def action(self, user, channel, msg):
        message = IRCMessage('ACTION', user, channel, msg)
        #self.log(u'*{0} {1}*'.format(message.User.Name, message.MessageString), message.ReplyTo)
        self.handleMessage(message)

    def noticed(self, user, channel, msg):
        message = IRCMessage('NOTICE', user, channel, msg.upper())
        self.log(u'[{0}] {1}'.format(message.User.Name, message.MessageString), message.ReplyTo)
        self.handleMessage(message)

    def nickChanged(self, nick):
        self.nickname = nick
        GlobalVars.CurrentNick = nick

    def irc_JOIN(self, prefix, params):
        message = IRCMessage('JOIN', prefix, params[0], '')

    def irc_PART(self, prefix, params):
        partMessage = u''
        if len(params) > 1:
            partMessage = u', message: '+u' '.join(params[1:])
        message = IRCMessage('PART', prefix, params[0], partMessage)

    def sendResponse(self, response):
        if (response == None or response.Response == None):
            return False

        if (response.Type == ResponseType.Say):
            self.msg(response.Target, response.Response.encode('utf-8'))
            self.log(u'<{0}> {1}'.format(self.nickname, response.Response), response.Target)
        elif (response.Type == ResponseType.Do):
            self.describe(response.Target, response.Response.encode('utf-8'))
            self.log(u'*{0} {1}*'.format(self.nickname, response.Response), response.Target)
        elif (response.Type == ResponseType.Notice):
            self.notice(response.Target, response.Response.encode('utf-8'))
            self.log(u'[{0}] {1}'.format(self.nickname, response.Response), response.Target)
        elif (response.Type == ResponseType.Raw):
            self.sendLine(response.Response.encode('utf-8'))

    def handleMessage(self, message):
        for (name, func) in GlobalVars.functions.items():
            try:
                response = func.GetResponse(message)
                if response is None:
                    continue
                if hasattr(response, '__iter__'):
                    for r in response:
                        self.responses.append(r)
                else:
                    self.responses.append(response)
            except Exception:
                print "Python Execution Error in '%s': %s" % (name, str( sys.exc_info() ))
                self.log("Python Execution Error in '%s': %s" % (name, str(sys.exc_info())))
                traceback.print_tb(sys.exc_info()[2])

        for response in self.responses:
            self.sendResponse(response)
        self.responses = []

    def log(self, text, target):
        now = datetime.datetime.utcnow()
        time = now.strftime("[%H:%M]")
        data = u'{0} {1}'.format(time, text)
        print target, data

        fileName = "{0}{1}.txt".format(target, now.strftime("-%Y%m%d"))
        fileDirs = os.path.join(GlobalVars.logPath, sys.argv[1])
        if not os.path.exists(fileDirs):
            os.makedirs(fileDirs)
        filePath = os.path.join(fileDirs, fileName)

        with codecs.open(filePath, 'a+', 'utf-8') as f:
            f.write(data + '\n')

class HubbeBotFactory(protocol.ReconnectingClientFactory):

	protocol = HubbeBot

	def startedConnecting(self, connector):
            print "-#- Started to connect."

        def buildProtocol(self, addr):
            print "-#- Connected."
            print "-#- Resetting reconnectiong delay"
            self.resetDelay()
            return HubbeBot()

        def clientConnectionLost(self, connector, reason):
            print "-!- Connection lost. Reason:", reason
            protocol.ReconnectingClientFactory.clientConnectionLost(self, connector, reason)

        def clientConnectionFailed(self, connector, reason):
            print "-!- Connection failed. Reason:", reason
            protocol.ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)

if __name__ == "__main__":
    if len(sys.argv)< 3:
        print "Correct usage: hubbot.py <server> <channel> [channel]"
    else:
        AutoLoadFunctions()
        hubbot = HubbeBotFactory()
        reactor.connectTCP(sys.argv[1], GlobalVars.port, hubbot)
        reactor.run()
<|endoftext|>


<commit_before>from __future__ import print_function

import json
import logging

from .stream import (
    MarketStream,
    OrderStream,
)

logger = logging.getLogger(__name__)

class BaseListener(object):

    def __init__(self, max_latency=0.5):
        self.max_latency = max_latency

        self.stream = None
        self.stream_type = None  # marketSubscription/orderSubscription
        self.stream_unique_id = None

    def register_stream(self, unique_id, operation):
        if self.stream is not None:
            logger.warning('[Listener: %s]: stream already registered, replacing data' % unique_id)
        self.stream = self._add_stream(unique_id, operation)
        self.stream_type = operation
        self.stream_unique_id = unique_id

    def on_data(self, raw_data):
        print(raw_data)

    def _add_stream(self, unique_id, operation):
        print('Register: %s %s' % (operation, unique_id))

    def __str__(self):
        return '<BaseListener>'

    def __repr__(self):
        return str(self)

class StreamListener(BaseListener):
    """Stream listener, processes results from socket,
    holds a market or order stream which hold
    market_book caches
    """

    def __init__(self, output_queue, max_latency=0.5, lightweight=False):
        super(StreamListener, self).__init__(max_latency)
        self.output_queue = output_queue
        self.lightweight = lightweight

    def on_data(self, raw_data):
        """Called when raw data is received from connection.
        Override this method if you wish to manually handle
        the stream data

        :param raw_data: Received raw data
        :return: Return False to stop stream and close connection
        """
        try:
            data = json.loads(raw_data)
        except ValueError:
            logger.error('value error: %s' % raw_data)
            return

        unique_id = data.get('id')

        if self._error_handler(data, unique_id):
            return False

        operation = data.get('op')
        if operation == 'connection':
            self._on_connection(data, unique_id)
        elif operation == 'status':
            self._on_status(data, unique_id)
        elif operation in ['mcm', 'ocm']:
            if unique_id != self.stream_unique_id and unique_id is not None:  # historic data does not contain unique_id
                logging.warning('Unwanted data received from uniqueId: %s, expecting: %s' %
                                (unique_id, self.stream_unique_id))
                return
            self._on_change_message(data, unique_id)

    def _on_connection(self, data, unique_id):
        """Called on collection operation

        :param data: Received data
        """
        self.connection_id = data.get('connectionId')
        logger.info('[Connect: %s]: connection_id: %s' % (unique_id, self.connection_id))

    @staticmethod
    def _on_status(data, unique_id):
        """Called on status operation

        :param data: Received data
        """
        status_code = data.get('statusCode')
        logger.info('[Subscription: %s]: %s' % (unique_id, status_code))

    def _on_change_message(self, data, unique_id):
        change_type = data.get('ct', 'UPDATE')

        logger.debug('[Subscription: %s]: %s: %s' % (unique_id, change_type, data))

        if change_type == 'SUB_IMAGE':
            self.stream.on_subscribe(data)
        elif change_type == 'RESUB_DELTA':
            self.stream.on_resubscribe(data)
        elif change_type == 'HEARTBEAT':
            self.stream.on_heartbeat(data)
        elif change_type == 'UPDATE':
            self.stream.on_update(data)

    def _add_stream(self, unique_id, stream_type):
        if stream_type == 'marketSubscription':
            return MarketStream(
                unique_id, self.output_queue, self.max_latency, self.lightweight
            )
        elif stream_type == 'orderSubscription':
            return OrderStream(
                unique_id, self.output_queue, self.max_latency, self.lightweight
            )

    @staticmethod
    def _error_handler(data, unique_id):
        """Called when data first received

        :param data: Received data
        :param unique_id: Unique id
        :return: True if error present
        """
        if data.get('statusCode') == 'FAILURE':
            logger.error('[Subscription: %s] %s: %s' % (unique_id, data.get('errorCode'), data.get('errorMessage')))
            if data.get('connectionClosed'):
                return True

    def __str__(self):
        return 'StreamListener'

    def __repr__(self):
        return '<StreamListener>'
<commit_msg>HISTORICAL unique id added<commit_after>from __future__ import print_function

import json
import logging

from .stream import (
    MarketStream,
    OrderStream,
)

logger = logging.getLogger(__name__)

class BaseListener(object):

    def __init__(self, max_latency=0.5):
        self.max_latency = max_latency

        self.stream = None
        self.stream_type = None  # marketSubscription/orderSubscription
        self.stream_unique_id = None

    def register_stream(self, unique_id, operation):
        if self.stream is not None:
            logger.warning('[Listener: %s]: stream already registered, replacing data' % unique_id)
        self.stream = self._add_stream(unique_id, operation)
        self.stream_type = operation
        self.stream_unique_id = unique_id

    def on_data(self, raw_data):
        print(raw_data)

    def _add_stream(self, unique_id, operation):
        print('Register: %s %s' % (operation, unique_id))

    def __str__(self):
        return '<BaseListener>'

    def __repr__(self):
        return str(self)

class StreamListener(BaseListener):
    """Stream listener, processes results from socket,
    holds a market or order stream which hold
    market_book caches
    """

    def __init__(self, output_queue, max_latency=0.5, lightweight=False):
        super(StreamListener, self).__init__(max_latency)
        self.output_queue = output_queue
        self.lightweight = lightweight

    def on_data(self, raw_data):
        """Called when raw data is received from connection.
        Override this method if you wish to manually handle
        the stream data

        :param raw_data: Received raw data
        :return: Return False to stop stream and close connection
        """
        try:
            data = json.loads(raw_data)
        except ValueError:
            logger.error('value error: %s' % raw_data)
            return

        unique_id = data.get('id')

        if self._error_handler(data, unique_id):
            return False

        operation = data.get('op')
        if operation == 'connection':
            self._on_connection(data, unique_id)
        elif operation == 'status':
            self._on_status(data, unique_id)
        elif operation in ['mcm', 'ocm']:
            # historic data does not contain unique_id
            if unique_id != self.stream_unique_id and self.stream_unique_id != 'HISTORICAL':
                logging.warning('Unwanted data received from uniqueId: %s, expecting: %s' %
                                (unique_id, self.stream_unique_id))
                return
            self._on_change_message(data, unique_id)

    def _on_connection(self, data, unique_id):
        """Called on collection operation

        :param data: Received data
        """
        self.connection_id = data.get('connectionId')
        logger.info('[Connect: %s]: connection_id: %s' % (unique_id, self.connection_id))

    @staticmethod
    def _on_status(data, unique_id):
        """Called on status operation

        :param data: Received data
        """
        status_code = data.get('statusCode')
        logger.info('[Subscription: %s]: %s' % (unique_id, status_code))

    def _on_change_message(self, data, unique_id):
        change_type = data.get('ct', 'UPDATE')

        logger.debug('[Subscription: %s]: %s: %s' % (unique_id, change_type, data))

        if change_type == 'SUB_IMAGE':
            self.stream.on_subscribe(data)
        elif change_type == 'RESUB_DELTA':
            self.stream.on_resubscribe(data)
        elif change_type == 'HEARTBEAT':
            self.stream.on_heartbeat(data)
        elif change_type == 'UPDATE':
            self.stream.on_update(data)

    def _add_stream(self, unique_id, stream_type):
        if stream_type == 'marketSubscription':
            return MarketStream(
                unique_id, self.output_queue, self.max_latency, self.lightweight
            )
        elif stream_type == 'orderSubscription':
            return OrderStream(
                unique_id, self.output_queue, self.max_latency, self.lightweight
            )

    @staticmethod
    def _error_handler(data, unique_id):
        """Called when data first received

        :param data: Received data
        :param unique_id: Unique id
        :return: True if error present
        """
        if data.get('statusCode') == 'FAILURE':
            logger.error('[Subscription: %s] %s: %s' % (unique_id, data.get('errorCode'), data.get('errorMessage')))
            if data.get('connectionClosed'):
                return True

    def __str__(self):
        return 'StreamListener'

    def __repr__(self):
        return '<StreamListener>'
<|endoftext|>