<commit_before># Copyright (C) 2010-2011 Mathijs de Bruin <mathijs@mathijsfietst.nl>
#
# This file is part of django-webshop.
#
# django-webshop is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

# -*- coding: utf-8 -*-
#
# django-webshop documentation build configuration file, created by
# sphinx-quickstart on Sat Nov  6 13:12:00 2010.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys, os

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

# Default flags for autodoc
autodoc_default_flags = ['members', 'show-inheritance', ]
autodoc_member_order = 'bysource'

# This is needed to be able to import the Django shizzle
from django.conf import global_settings

setattr(global_settings, 'WEBSHOP_PRODUCT_MODEL', '')
setattr(global_settings, 'WEBSHOP_CART_MODEL', '')
setattr(global_settings, 'WEBSHOP_ORDER_MODEL', '')
setattr(global_settings, 'WEBSHOP_TAX_PERCENTAGE', '')

from django.core.management import setup_environ
setup_environ(global_settings)

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

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

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

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

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

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'django-webshop'
copyright = u'2010, Mathijs de Bruin'

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

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

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

# List of documents that shouldn't be included in the build.
#unused_docs = []

# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = ['_build']

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

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

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

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

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

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

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

# The theme to use for HTML and HTML Help pages.  Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
html_theme = 'default'

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

# If true, 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 = ''

# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''

# Output file base name for HTML help builder.
htmlhelp_basename = 'django-webshopdoc'

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

# The paper size ('letter' or 'a4').
latex_paper_size = 'a4'

# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
  ('index', 'django-webshop.tex', u'django-webshop Documentation',
   u'Mathijs de Bruin', '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

# Additional stuff for the LaTeX preamble.
#latex_preamble = ''

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

# If false, no module index is generated.
#latex_use_modindex = True
<commit_msg>Fixed module index in docs.<commit_after># Copyright (C) 2010-2011 Mathijs de Bruin <mathijs@mathijsfietst.nl>
#
# This file is part of django-webshop.
#
# django-webshop is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

# -*- coding: utf-8 -*-
#
# django-webshop documentation build configuration file, created by
# sphinx-quickstart on Sat Nov  6 13:12:00 2010.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys, os

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

# Default flags for autodoc
autodoc_default_flags = ['members', 'show-inheritance', ]
autodoc_member_order = 'bysource'

# This is needed to be able to import the Django shizzle
from django.conf import global_settings

setattr(global_settings, 'WEBSHOP_PRODUCT_MODEL', '')
setattr(global_settings, 'WEBSHOP_CART_MODEL', '')
setattr(global_settings, 'WEBSHOP_ORDER_MODEL', '')
setattr(global_settings, 'WEBSHOP_TAX_PERCENTAGE', '')

from django.core.management import setup_environ
setup_environ(global_settings)

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

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

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

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

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

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'django-webshop'
copyright = u'2010, Mathijs de Bruin'

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

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

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

# List of documents that shouldn't be included in the build.
#unused_docs = []

# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = ['_build']

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

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

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

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

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

# A list of ignored prefixes for module index sorting.
modindex_common_prefix = ['webshop.', 'webshop.extensions.', ]

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

# The theme to use for HTML and HTML Help pages.  Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
html_theme = 'default'

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

# If true, 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 = ''

# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''

# Output file base name for HTML help builder.
htmlhelp_basename = 'django-webshopdoc'

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

# The paper size ('letter' or 'a4').
latex_paper_size = 'a4'

# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
  ('index', 'django-webshop.tex', u'django-webshop Documentation',
   u'Mathijs de Bruin', '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

# Additional stuff for the LaTeX preamble.
#latex_preamble = ''

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

# If false, no module index is generated.
#latex_use_modindex = True
<|endoftext|>


<commit_before>#-*- coding: utf-8 -*-
# version string following pep-0396 and pep-0386
__version__ = '0.9pbs.32'  # pragma: nocover
<commit_msg>master_pbs Bumped version as instructed by bamboo.<commit_after>#-*- coding: utf-8 -*-
# version string following pep-0396 and pep-0386
__version__ = '0.9pbs.33'  # pragma: nocover
<|endoftext|>


<commit_before>from __future__ import division

__author__ = 'jacob'
import ROOT
import numpy as np
import os
import math
from root_numpy import root2array
import luminosity_plotting_routines as luminosity_plotting
import glob

data_files = glob.iglob(os.path.join("data", "*.root"))
for file_name in data_files:
    detector_array = root2array(file_name)

    # Get LUCID and BCM EventOR data to graph
    luminosity_block = detector_array['LBDATA_LB'].tolist()
    luminosity_block_stable = detector_array['LBDATA_stable'].tolist()
    luminosity_block_run = detector_array['LBDATA_Run'].tolist()

    start_time = detector_array['LBDATA_StartTime'].tolist()
    end_time = detector_array['LBDATA_EndTime'].tolist()

    lucid_event_or_bi = detector_array['LUCID_EVENTOR_BI'].tolist()

    bcm_h_event_or = detector_array['BCM_H_EVENTOR'].tolist()
    bcm_v_event_or = detector_array['BCM_V_EVENTOR'].tolist()

    # Timing is named Status in the root file
    status = detector_array['Status'].tolist()

    print("Length of LUCID: " + str(len(lucid_event_or_bi)))
    print(" Length of BCM H: " + str(len(bcm_h_event_or)))
    print(" Length of BCM V: " + str(len(bcm_v_event_or)))
    print(" Length of Start: " + str(len(start_time)))
    print(" Length of End: " + str(len(end_time)))
    print(" Length of Status: " + str(len(status)))
    print(" Length of Luminosity Block Data: " + str(len(luminosity_block)))
    print(" Length of LB Stable: " + str(len(luminosity_block_stable)))
    print(" Length of LB Run: " + str(len(luminosity_block_stable)))

    # Each luminosity block is an array in the
    # Slice the data to ignore certain datasets because of physical reasons
    temp_lucid = []
    temp_bcm_h = []
    temp_bcm_v = []

    # Go through each BCID number
    lucid_sum = 0.0
    bcm_h_sum = 0.0
    bcm_v_sum = 0.0

    # Save each event to a list to plot later
    lucid_event_or_bi1 = [[] for _ in xrange(len(luminosity_block))]
    bcm_v_event_or1 = [[] for _ in xrange(len(luminosity_block))]
    bcm_h_event_or1 = [[] for _ in xrange(len(luminosity_block))]
    luminosity_ratio_lucid_h_sum = [[] for _ in xrange(len(luminosity_block))]
    luminosity_ratio_h_v_sum = [[] for _ in xrange(len(luminosity_block))]
    luminosity_ratio_lucid_v_sum = [[] for _ in xrange(len(luminosity_block))]
    new_luminosity_block = []

    for block in range(len(luminosity_block)):
        for bcid in range(3564):
            if luminosity_block_stable[block] > 0.0 and status[block] > 0.0:
                if lucid_event_or_bi[block][bcid] > 0.0 and bcm_h_event_or[block][bcid] > 0.0 and bcm_v_event_or[block][bcid] > 0.0:
                    lucid = lucid_event_or_bi[block][bcid]
                    bcm_h = bcm_h_event_or[block][bcid]
                    bcm_v = bcm_v_event_or[block][bcid]
                    # Save the event to the list
                    lucid_event_or_bi1[block].append(lucid)
                    bcm_h_event_or1[block].append(bcm_h)
                    bcm_v_event_or1[block].append(bcm_v)
                    # Add as the negative log of 1 - rate, as that should be linear to luminosity
                    lucid_sum += -math.log(1 - lucid)
                    bcm_h_sum += -math.log(1 - bcm_h)
                    bcm_v_sum += -math.log(1 - bcm_v)
        # Print out if the blocks are zero
        if lucid_sum != 0.0 or bcm_h_sum != 0.0 or bcm_v_sum != 0.0:
            luminosity_ratio_lucid_h = lucid_sum / bcm_h_sum
            luminosity_ratio_lucid_v = lucid_sum / bcm_v_sum
            luminosity_ratio_h_v = bcm_h_sum / bcm_v_sum
            luminosity_ratio_lucid_h_sum[block].append(luminosity_ratio_lucid_h)
            luminosity_ratio_lucid_v_sum[block].append(luminosity_ratio_lucid_v)
            luminosity_ratio_h_v_sum[block].append(luminosity_ratio_h_v)
            new_luminosity_block.append(block)

    # Actually plot the luminosity ratios
    luminosity_plotting.plot_percent_luminosity_ratio(lucid_event_or_bi1, bcm_v_event_or1, new_luminosity_block,
                                                      'ATLAS', os.path.splitext(file_name)[0])

    luminosity_plotting.plot_percent_luminosity_ratio(lucid_event_or_bi1, bcm_h_event_or1, new_luminosity_block,
                                                      'ATLAS', os.path.splitext(file_name)[0])

    luminosity_plotting.plot_percent_luminosity_ratio(bcm_h_event_or1, bcm_v_event_or1, new_luminosity_block,
                                                      'ATLAS', os.path.splitext(file_name)[0])<commit_msg>Add making each type of graph for each run<commit_after>from __future__ import division

__author__ = 'jacob'
import ROOT
import numpy as np
import os
import math
from root_numpy import root2array
import luminosity_plotting_routines as luminosity_plotting
import glob

data_files = glob.iglob(os.path.join("data", "*.root"))
for file_name in data_files:
    detector_array = root2array(file_name)

    # Get LUCID and BCM EventOR data to graph
    luminosity_block = detector_array['LBDATA_LB'].tolist()
    luminosity_block_stable = detector_array['LBDATA_stable'].tolist()
    luminosity_block_run = detector_array['LBDATA_Run'].tolist()

    start_time = detector_array['LBDATA_StartTime'].tolist()
    end_time = detector_array['LBDATA_EndTime'].tolist()

    lucid_event_or_bi = detector_array['LUCID_EVENTOR_BI'].tolist()

    bcm_h_event_or = detector_array['BCM_H_EVENTOR'].tolist()
    bcm_v_event_or = detector_array['BCM_V_EVENTOR'].tolist()

    # Timing is named Status in the root file
    status = detector_array['Status'].tolist()

    print("Length of LUCID: " + str(len(lucid_event_or_bi)))
    print(" Length of BCM H: " + str(len(bcm_h_event_or)))
    print(" Length of BCM V: " + str(len(bcm_v_event_or)))
    print(" Length of Start: " + str(len(start_time)))
    print(" Length of End: " + str(len(end_time)))
    print(" Length of Status: " + str(len(status)))
    print(" Length of Luminosity Block Data: " + str(len(luminosity_block)))
    print(" Length of LB Stable: " + str(len(luminosity_block_stable)))
    print(" Length of LB Run: " + str(len(luminosity_block_stable)))

    # Each luminosity block is an array in the
    # Slice the data to ignore certain datasets because of physical reasons
    temp_lucid = []
    temp_bcm_h = []
    temp_bcm_v = []

    # Go through each BCID number
    lucid_sum = 0.0
    bcm_h_sum = 0.0
    bcm_v_sum = 0.0

    # Save each event to a list to plot later
    lucid_event_or_bi1 = [[] for _ in xrange(len(luminosity_block))]
    bcm_v_event_or1 = [[] for _ in xrange(len(luminosity_block))]
    bcm_h_event_or1 = [[] for _ in xrange(len(luminosity_block))]
    luminosity_ratio_lucid_h_sum = [[] for _ in xrange(len(luminosity_block))]
    luminosity_ratio_h_v_sum = [[] for _ in xrange(len(luminosity_block))]
    luminosity_ratio_lucid_v_sum = [[] for _ in xrange(len(luminosity_block))]
    new_luminosity_block = []

    for block in range(len(luminosity_block)):
        for bcid in range(3564):
            if luminosity_block_stable[block] > 0.0 and status[block] > 0.0:
                if lucid_event_or_bi[block][bcid] > 0.0 and bcm_h_event_or[block][bcid] > 0.0 and bcm_v_event_or[block][bcid] > 0.0:
                    lucid = lucid_event_or_bi[block][bcid]
                    bcm_h = bcm_h_event_or[block][bcid]
                    bcm_v = bcm_v_event_or[block][bcid]
                    # Save the event to the list
                    lucid_event_or_bi1[block].append(lucid)
                    bcm_h_event_or1[block].append(bcm_h)
                    bcm_v_event_or1[block].append(bcm_v)
                    # Add as the negative log of 1 - rate, as that should be linear to luminosity
                    lucid_sum += -math.log(1 - lucid)
                    bcm_h_sum += -math.log(1 - bcm_h)
                    bcm_v_sum += -math.log(1 - bcm_v)
        # Print out if the blocks are zero
        if lucid_sum != 0.0 or bcm_h_sum != 0.0 or bcm_v_sum != 0.0:
            luminosity_ratio_lucid_h = lucid_sum / bcm_h_sum
            luminosity_ratio_lucid_v = lucid_sum / bcm_v_sum
            luminosity_ratio_h_v = bcm_h_sum / bcm_v_sum
            luminosity_ratio_lucid_h_sum[block].append(luminosity_ratio_lucid_h)
            luminosity_ratio_lucid_v_sum[block].append(luminosity_ratio_lucid_v)
            luminosity_ratio_h_v_sum[block].append(luminosity_ratio_h_v)
            new_luminosity_block.append(block)

    # Actually plot the luminosity ratios
    luminosity_plotting.plot_percent_luminosity_ratio(lucid_event_or_bi1, bcm_v_event_or1, new_luminosity_block,
                                                      'ATLAS', os.path.splitext(file_name)[0])
    luminosity_plotting.plot_normalized_luminosity_ratio(lucid_event_or_bi1, bcm_v_event_or1, new_luminosity_block,
                                                      'ATLAS', os.path.splitext(file_name)[0])
    luminosity_plotting.plot_luminosity_ratio(lucid_event_or_bi1, bcm_v_event_or1, new_luminosity_block,
                                                      'ATLAS', os.path.splitext(file_name)[0])

    luminosity_plotting.plot_percent_luminosity_ratio(lucid_event_or_bi1, bcm_h_event_or1, new_luminosity_block,
                                                      'ATLAS', os.path.splitext(file_name)[0])
    luminosity_plotting.plot_normalized_luminosity_ratio(lucid_event_or_bi1, bcm_h_event_or1, new_luminosity_block,
                                                         'ATLAS', os.path.splitext(file_name)[0])
    luminosity_plotting.plot_luminosity_ratio(lucid_event_or_bi1, bcm_h_event_or1, new_luminosity_block,
                                              'ATLAS', os.path.splitext(file_name)[0])

    luminosity_plotting.plot_percent_luminosity_ratio(bcm_h_event_or1, bcm_v_event_or1, new_luminosity_block,
                                                      'ATLAS', os.path.splitext(file_name)[0])
    luminosity_plotting.plot_normalized_luminosity_ratio(bcm_h_event_or1, bcm_v_event_or1, new_luminosity_block,
                                                         'ATLAS', os.path.splitext(file_name)[0])
    luminosity_plotting.plot_luminosity_ratio(bcm_h_event_or1, bcm_v_event_or1, new_luminosity_block,
                                              'ATLAS', os.path.splitext(file_name)[0])
<|endoftext|>


<commit_before># Licensed under a 3-clause BSD style license - see LICENSE.rst

from __future__ import print_function, division, absolute_import

import numpy as np
from matplotlib.patches import Polygon

from astropy import units as u
from astropy.coordinates.representation import UnitSphericalRepresentation, CartesianRepresentation
from astropy.coordinates.angles import rotation_matrix

__all__ = ['SphericalCircle']

def _transform_cartesian(representation, matrix):

    # Get xyz once since it's an expensive operation
    xyz = representation.xyz

    # Since the underlying data can be n-dimensional, reshape to a
    # 2-dimensional (3, N) array.
    vec = xyz.reshape((3, xyz.size // 3))

    # Do the transformation
    vec_new = np.dot(np.asarray(matrix), vec)

    # Reshape to preserve the original shape
    subshape = xyz.shape[1:]
    x = vec_new[0].reshape(subshape)
    y = vec_new[1].reshape(subshape)
    z = vec_new[2].reshape(subshape)

    # Make a new representation and return
    return CartesianRepresentation(x, y, z)

def _rotate_polygon(lon, lat, lon0, lat0):
    """
    Given a polygon with vertices defined by (lon, lat), rotate the polygon
    such that the North pole of the spherical coordinates is now at (lon0,
    lat0). Therefore, to end up with a polygon centered on (lon0, lat0), the
    polygon should initially be drawn around the North pole.
    """

    # Create a representation object
    polygon = UnitSphericalRepresentation(lon=lon, lat=lat)

    # Determine rotation matrix to make it so that the circle is centered
    # on the correct longitude/latitude.
    m1 = rotation_matrix(-(0.5 * np.pi * u.radian - lat0), axis='y')
    m2 = rotation_matrix(-lon0, axis='z')
    transform_matrix = m2 * m1

    # Apply 3D rotation
    polygon = polygon.to_cartesian()

    try:
        polygon = polygon.transform(transform_matrix)
    except:  # TODO: remove once Astropy 1.1 is no longer supported
        polygon = _transform_cartesian(polygon, transform_matrix)

    polygon = UnitSphericalRepresentation.from_cartesian(polygon)

    return polygon.lon, polygon.lat

class SphericalCircle(Polygon):
    """
    Create a patch representing a spherical circle - that is, a circle that is
    formed of all the points that are within a certain angle of the central
    coordinates on a sphere. Here we assume that latitude goes from -90 to +90

    This class is needed in cases where the user wants to add a circular patch
    to a celestial image, since otherwise the circle will be distorted, because
    a fixed interval in longitude corresponds to a different angle on the sky
    depending on the latitude.

    Parameters
    ----------
    center : tuple or `~astropy.units.Quantity`
        This can be either a tuple of two `~astropy.units.Quantity` objects, or
        a single `~astropy.units.Quantity` array with two elements.
    radius : `~astropy.units.Quantity`
        The radius of the circle
    resolution : int, optional
        The number of points that make up the circle - increase this to get a
        smoother circle.
    vertex_unit : `~astropy.units.Unit`
        The units in which the resulting polygon should be defined - this
        should match the unit that the transformation (e.g. the WCS
        transformation) expects as input.

    Notes
    -----
    Additional keyword arguments are passed to `~matplotlib.patches.Polygon`
    """

    def __init__(self, center, radius, resolution=100, vertex_unit=u.degree, **kwargs):

        # Extract longitude/latitude, either from a tuple of two quantities, or
        # a single 2-element Quantity.
        longitude, latitude = center

        # Start off by generating the circle around the North pole
        lon = np.linspace(0., 2 * np.pi, resolution + 1)[:-1] * u.radian
        lat = np.repeat(0.5 * np.pi - radius.to(u.radian).value, resolution) * u.radian

        lon, lat = _rotate_polygon(lon, lat, longitude, latitude)

        # Extract new longitude/latitude in the requested units
        lon = lon.to(vertex_unit).value
        lat = lat.to(vertex_unit).value

        # Create polygon vertices
        vertices = np.array([lon, lat]).transpose()

        super(SphericalCircle, self).__init__(vertices, **kwargs)
<commit_msg>Fix deprecation warning<commit_after># Licensed under a 3-clause BSD style license - see LICENSE.rst

from __future__ import print_function, division, absolute_import

import numpy as np
from matplotlib.patches import Polygon

from astropy import units as u
from astropy.coordinates.representation import UnitSphericalRepresentation, CartesianRepresentation

try:
    from astropy.coordinates.matrix_utilities import rotation_matrix as rotation_array
    def rotation_matrix(*args, **kwargs):
        return np.matrix(rotation_array(*args, **kwargs))
except ImportError:
    from astropy.coordinates.angles import rotation_matrix

__all__ = ['SphericalCircle']

def _transform_cartesian(representation, matrix):

    # Get xyz once since it's an expensive operation
    xyz = representation.xyz

    # Since the underlying data can be n-dimensional, reshape to a
    # 2-dimensional (3, N) array.
    vec = xyz.reshape((3, xyz.size // 3))

    # Do the transformation
    vec_new = np.dot(np.asarray(matrix), vec)

    # Reshape to preserve the original shape
    subshape = xyz.shape[1:]
    x = vec_new[0].reshape(subshape)
    y = vec_new[1].reshape(subshape)
    z = vec_new[2].reshape(subshape)

    # Make a new representation and return
    return CartesianRepresentation(x, y, z)

def _rotate_polygon(lon, lat, lon0, lat0):
    """
    Given a polygon with vertices defined by (lon, lat), rotate the polygon
    such that the North pole of the spherical coordinates is now at (lon0,
    lat0). Therefore, to end up with a polygon centered on (lon0, lat0), the
    polygon should initially be drawn around the North pole.
    """

    # Create a representation object
    polygon = UnitSphericalRepresentation(lon=lon, lat=lat)

    # Determine rotation matrix to make it so that the circle is centered
    # on the correct longitude/latitude.
    m1 = rotation_matrix(-(0.5 * np.pi * u.radian - lat0), axis='y')
    m2 = rotation_matrix(-lon0, axis='z')
    transform_matrix = m2 * m1

    # Apply 3D rotation
    polygon = polygon.to_cartesian()

    try:
        polygon = polygon.transform(transform_matrix)
    except:  # TODO: remove once Astropy 1.1 is no longer supported
        polygon = _transform_cartesian(polygon, transform_matrix)

    polygon = UnitSphericalRepresentation.from_cartesian(polygon)

    return polygon.lon, polygon.lat

class SphericalCircle(Polygon):
    """
    Create a patch representing a spherical circle - that is, a circle that is
    formed of all the points that are within a certain angle of the central
    coordinates on a sphere. Here we assume that latitude goes from -90 to +90

    This class is needed in cases where the user wants to add a circular patch
    to a celestial image, since otherwise the circle will be distorted, because
    a fixed interval in longitude corresponds to a different angle on the sky
    depending on the latitude.

    Parameters
    ----------
    center : tuple or `~astropy.units.Quantity`
        This can be either a tuple of two `~astropy.units.Quantity` objects, or
        a single `~astropy.units.Quantity` array with two elements.
    radius : `~astropy.units.Quantity`
        The radius of the circle
    resolution : int, optional
        The number of points that make up the circle - increase this to get a
        smoother circle.
    vertex_unit : `~astropy.units.Unit`
        The units in which the resulting polygon should be defined - this
        should match the unit that the transformation (e.g. the WCS
        transformation) expects as input.

    Notes
    -----
    Additional keyword arguments are passed to `~matplotlib.patches.Polygon`
    """

    def __init__(self, center, radius, resolution=100, vertex_unit=u.degree, **kwargs):

        # Extract longitude/latitude, either from a tuple of two quantities, or
        # a single 2-element Quantity.
        longitude, latitude = center

        # Start off by generating the circle around the North pole
        lon = np.linspace(0., 2 * np.pi, resolution + 1)[:-1] * u.radian
        lat = np.repeat(0.5 * np.pi - radius.to(u.radian).value, resolution) * u.radian

        lon, lat = _rotate_polygon(lon, lat, longitude, latitude)

        # Extract new longitude/latitude in the requested units
        lon = lon.to(vertex_unit).value
        lat = lat.to(vertex_unit).value

        # Create polygon vertices
        vertices = np.array([lon, lat]).transpose()

        super(SphericalCircle, self).__init__(vertices, **kwargs)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
# PDF Analytics Client API documentation build configuration file, created by
# sphinx-quickstart on Sat Oct 14 22:18:36 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys
import os

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

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

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

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

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

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

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

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'PDF Analytics Client API'
copyright = u'2017, PDF Analytics'

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'pdfanalyticsclientapi', u'PDF Analytics Client API Documentation',
     [u'PDF Analytics'], 1)
]

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

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

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
  ('index', 'PDFAnalyticsClientAPI', u'PDF Analytics Client API Documentation',
   u'PDF Analytics', 'PDFAnalyticsClientAPI', '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
<commit_msg>Add to the conf.py the right version<commit_after># -*- coding: utf-8 -*-
#
# PDF Analytics Client API documentation build configuration file, created by
# sphinx-quickstart on Sat Oct 14 22:18:36 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys
import os

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

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

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

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

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

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

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

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'PDF Analytics Client API'
copyright = u'2017, PDF Analytics'

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'pdfanalyticsclientapi', u'PDF Analytics Client API Documentation',
     [u'PDF Analytics'], 1)
]

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

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

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
  ('index', 'PDFAnalyticsClientAPI', u'PDF Analytics Client API Documentation',
   u'PDF Analytics', 'PDFAnalyticsClientAPI', '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
<|endoftext|>


<commit_before>''' Guess the number

Have the computer select an integer between 1 and 100 (inclusive)
and ask the user to guess that number.

Keep track of the user's number of guesses required to guess the correct value.

Make sure that incorrect input by the user (for exemple: entering a word
instead of number) are taken care of with appropriate feedback
given to the user.

Allow the user to leave the game at any time by entering a value of -1.

End the program by giving the user appropriate feedback; for example, if the
user guesses correctly, indicate how many guesses were needed.
'''

import random

# use a variable to avoid having to change the maximum value at
# two different places - if we decide to make the game more difficult.
max_nb = 100
number = random.randint(1, max_nb)
prompt = "Guess a number, between 1 and {}, or enter -1 to quit.".format(max_nb)

def safe_input():
    '''Prompts the user for an integer and return only when a valid value
       is entered
    '''
    while True:
        try:
            guess = int(input(prompt))
            return guess
        except ValueError:
            print("You must enter a valid value.")

nb_attempts = 0
while True:
    guess = safe_input()
    nb_attempts += 1
    if guess == number:
        print("Congratulations, you guessed correctly.")
        print("You only needed {} attempts.".format(nb_attempts))
    elif guess == -1:
        print("Sorry to see you leave; the number was {}.".format(number))
<commit_msg>adding feedback about guess: too low or too high<commit_after>''' Guess the number

Have the computer select an integer between 1 and 100 (inclusive)
and ask the user to guess that number.

Keep track of the user's number of guesses required to guess the correct value.

Provide feedback to the user indicating if their guess is too low or too high.

Make sure that incorrect input by the user (for exemple: entering a word
instead of number) are taken care of with appropriate feedback
given to the user.

Allow the user to leave the game at any time by entering a value of -1.

End the program by giving the user appropriate feedback; for example, if the
user guesses correctly, indicate how many guesses were needed.
'''

import random

# use a variable to avoid having to change the maximum value at
# two different places - if we decide to make the game more difficult.
max_nb = 100
number = random.randint(1, max_nb)
prompt = "Guess a number, between 1 and {}, or enter -1 to quit.".format(max_nb)

def safe_input():
    '''Prompts the user for an integer and return only when a valid value
       is entered
    '''
    while True:
        try:
            guess = int(input(prompt))
            return guess
        except ValueError:
            print("You must enter a valid value.")

nb_attempts = 0
while True:
    guess = safe_input()
    nb_attempts += 1
    if guess == number:
        print("Congratulations, you guessed correctly.")
        print("You only needed {} attempts.".format(nb_attempts))
    elif guess == -1:
        print("Sorry to see you leave; the number was {}.".format(number))
    elif guess < number:
        print("Your guess is too low.")
    elif guess > number:
        print("Your guess is too high.")
<|endoftext|>


<commit_before>from collections import Counter

from marisa_trie import Trie

from detie.utils import logger
from detie.data import DictData, NLPIRXMLData
from detie.extract import extract_new_string

def build_trie():
    logger.info("Building trie tree")
    dict_data = DictData('COAE_Known_dict.txt')
    trie = Trie(dict_data)
    logger.info("Trie tree build success")
    return trie

def load_corpus():
    logger.info("Loading corpus data")
    corpus_data = NLPIRXMLData("NLPIR_weibo_content_corpus.xml")
    logger.info("Corpus data loaded")
    return corpus_data

def count_new_strings():
    trie = build_trie()
    corpus = load_corpus()
    counter = Counter()
    i=0
    sum_ = float(23E4)
    for text in corpus.texts:
        if not text: continue
        new_strings = extract_new_string(trie, text)
        for str_ in new_strings:
            counter[str_] += 1
        i+=1
        if i%1000==0:
            logger.info("Computing: %.2f%% - [%d]" % (i/sum_*100, len(counter)))
    logger.info("Computing finished")
    return counter

def run():
    counter = count_new_strings()
    for word, count in counter.most_common(50):
        l = u"%s (%d)" % (word, count)
        print l.encode('utf8')
<commit_msg>scale output to 1000<commit_after>from collections import Counter

from marisa_trie import Trie

from detie.utils import logger
from detie.data import DictData, NLPIRXMLData
from detie.extract import extract_new_string

def build_trie():
    logger.info("Building trie tree")
    dict_data = DictData('COAE_Known_dict.txt')
    trie = Trie(dict_data)
    logger.info("Trie tree build success")
    return trie

def load_corpus():
    logger.info("Loading corpus data")
    corpus_data = NLPIRXMLData("NLPIR_weibo_content_corpus.xml")
    logger.info("Corpus data loaded")
    return corpus_data

def count_new_strings():
    trie = build_trie()
    corpus = load_corpus()
    counter = Counter()
    i=0
    sum_ = float(23E4)
    for text in corpus.texts:
        if not text: continue
        new_strings = extract_new_string(trie, text)
        for str_ in new_strings:
            counter[str_] += 1
        i+=1
        if i%1000==0:
            logger.info("Computing: %.2f%% - [%d]" % (i/sum_*100, len(counter)))
    logger.info("Computing finished")
    return counter

def run():
    counter = count_new_strings()
    for word, count in counter.most_common(1000):
        l = u"%s (%d)" % (word, count)
        print l.encode('utf8')
<|endoftext|>


<commit_before><commit_msg>Fixed an issue where the server wouldn't return the right message if you weren't in the permissions.txt file<commit_after><|endoftext|>


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

import os

extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.autosummary',
    'sphinx.ext.viewcode',
    'sphinx.ext.napoleon',
    'sphinx.ext.extlinks'
]
if os.getenv('SPELLCHECK'):
    extensions += 'sphinxcontrib.spelling',
    spelling_show_suggestions = True
    spelling_lang = 'en_US'

source_suffix = '.rst'
master_doc = 'index'
project = u'Apex Python library'
year = u'2015'
author = u'Christer van der Meeren, Angeline G. Burrell'
copyright = '{0}, {1}'.format(year, author)
version = release = u'1.0.3'
# on_rtd is whether we are on readthedocs.org
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'

if not on_rtd:  # only import and set the theme if we're building docs locally
    import sphinx_rtd_theme
    html_theme = 'sphinx_rtd_theme'
    html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

pygments_style = 'trac'
templates_path = ['.']
html_use_smartypants = True
html_last_updated_fmt = '%b %d, %Y'
html_split_index = True
html_sidebars = {
   '**': ['searchbox.html', 'globaltoc.html', 'sourcelink.html'],
}
html_short_title = '%s-%s' % (project, version)
autodoc_member_order='bysource'
napoleon_use_ivar=True
napoleon_use_rtype=False
napoleon_use_param=False

extlinks = {'doi': ('http://dx.doi.org/%s', 'doi:')}
<commit_msg>TST: removed spelling test support<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals

import os

extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.autosummary',
    'sphinx.ext.viewcode',
    'sphinx.ext.napoleon',
    'sphinx.ext.extlinks'
]

source_suffix = '.rst'
master_doc = 'index'
project = u'Apex Python library'
year = u'2015'
author = u'Christer van der Meeren, Angeline G. Burrell'
copyright = '{0}, {1}'.format(year, author)
version = release = u'1.0.3'
# on_rtd is whether we are on readthedocs.org
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'

if not on_rtd:  # only import and set the theme if we're building docs locally
    import sphinx_rtd_theme
    html_theme = 'sphinx_rtd_theme'
    html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

pygments_style = 'trac'
templates_path = ['.']
html_use_smartypants = True
html_last_updated_fmt = '%b %d, %Y'
html_split_index = True
html_sidebars = {
   '**': ['searchbox.html', 'globaltoc.html', 'sourcelink.html'],
}
html_short_title = '%s-%s' % (project, version)
autodoc_member_order='bysource'
napoleon_use_ivar=True
napoleon_use_rtype=False
napoleon_use_param=False

extlinks = {'doi': ('http://dx.doi.org/%s', 'doi:')}
<|endoftext|>


<commit_before>from nala.features import FeatureGenerator
from nltk.stem import PorterStemmer
import abc

class EdgeFeatureGenerator(FeatureGenerator):
    """
    Abstract class for generating features for each edge in the dataset.
    Subclasses that inherit this class should:
    * Be named [Name]FeatureGenerator
    * Implement the abstract method generate
    * Append new items to the dictionary field "features" of each Edge in the dataset
    """

    @abc.abstractmethod
    def generate(self, dataset):
        """
        :type dataset: nala.structures.data.Dataset
        """
        return

    def add_to_feature_set(self, edge, feature_name, value=1):
        if self.training_mode:
            if feature_name not in self.feature_set.keys():
                self.feature_set[feature_name] = len(self.feature_set.keys()) + 1
            edge.features[self.feature_set[feature_name]] = value
        else:
            if feature_name in self.feature_set.keys():
                edge.features[self.feature_set[feature_name]] = value

class TokenFeatureGenerator:
    """
    Token based features for each entity belonging to an edge
    """
    def __init__(self, feature_set, training_mode=True):
        self.feature_set = feature_set
        """the feature set for the dataset"""
        self.training_mode = training_mode
        """whether the mode is training or testing"""
        self.stemmer = PorterStemmer()
        """an instance of the PorterStemmer()"""

    def token_features(self, token, prefix, edge):
        feature_name_1 = '73_'+prefix+'txt_'+token.word+'_[0]'
        self.add_to_feature_set(edge, feature_name_1)
        feature_name_2 = '74_'+prefix+'pos_'+token.features['pos']+'_[0]'
        self.add_to_feature_set(edge, feature_name_2)
        feature_name_3 = '75_'+prefix+'txt_'+token.masked_text(edge.part)+'_[0]'
        self.add_to_feature_set(edge, feature_name_3)
        feature_name_4 = '76_'+prefix+'stem_'+self.stemmer.stem(token.masked_text(edge.part))+'_[0]'
        self.add_to_feature_set(edge, feature_name_4)
        ann_types = self.annotated_types(token, edge)
        for ann in ann_types:
            feature_name_5 = '77_'+prefix+'ann_type_'+ann+'_[0]'
            self.add_to_feature_set(edge, feature_name_5)

    def annotated_types(self, token, edge):
        head1 = edge.entity1.head_token
        head2 = edge.entity2.head_token
        if not token.is_entity_part(edge.part):
            feature_name = 'no_ann_type'
            return [feature_name]
        else:
            ann_types = []
            if token.is_entity_part(edge.part):
                entity = token.get_entity(edge.part)
                feature_name_1 = entity.class_id
                ann_types.append(feature_name_1)
                if entity==edge.entity1:
                    feature_name_2 = 'entity1_'+edge.entity1.class_id
                    ann_types.append(feature_name_2)
                    return ann_types
                elif entity==edge.entity2:
                    feature_name_2 = 'entity2_'+edge.entity2.class_id
                    ann_types.append(feature_name_2)
                    return ann_types
                return ann_types

    def add_to_feature_set(self, edge, feature_name, value=1):
        if self.training_mode:
            if feature_name not in self.feature_set.keys():
                self.feature_set[feature_name] = len(self.feature_set.keys()) + 1
            edge.features[self.feature_set[feature_name]] = value
        else:
            if feature_name in self.feature_set.keys():
                edge.features[self.feature_set[feature_name]] = value

def calculateInformationGain(feature_set, dataset, output_file):
    number_pos_instances = 0
    number_neg_instances = 0

    for edge in dataset.edges():
        if edge.target == 1:
            number_pos_instances += 1
        else:
            number_neg_instances += 1

    number_total_instances = number_pos_instances + number_neg_instances
    percentage_pos_instances = number_pos_instances / number_total_instances
    percentage_neg_instances = number_neg_instances / number_total_instances

    first_ent_component = -1 * (percentage_pos_instances * log2(percentage_pos_instances) + percentage_neg_instances * log2(percentage_neg_instances))
    feature_list = []
    for key, value in feature_set.items():
        feature_present_in_pos = 0
        feature_present_in_neg = 0
        feature_absent_in_pos = 0
        feature_absent_in_neg = 0
        total_feature_present = 0
        total_feature_absent = 0

        for edge in dataset.edges():
            if edge.target == 1:
                if value in edge.features.keys():
                    feature_present_in_pos += 1
                    total_feature_present += 1
                else:
                    feature_absent_in_pos += 1
                    total_feature_absent +=1
            if edge.target == -1:
                if value in edge.features.keys():
                    feature_present_in_neg += 1
                    total_feature_present += 1
                else:
                    feature_absent_in_neg += 1
                    total_feature_absent += 1

        percentage_pos_given_feature = 0
        percentage_neg_given_feature = 0
        if (total_feature_present > 0):
            percentage_pos_given_feature = feature_present_in_pos / total_feature_present
            percentage_neg_given_feature = feature_present_in_neg / total_feature_present

        percentage_pos_given_feature_log = 0
        percentage_neg_given_feature_log = 0
        if percentage_pos_given_feature > 0:
            percentage_pos_given_feature_log = log2(percentage_pos_given_feature)
        if percentage_neg_given_feature > 0:
            percentage_neg_given_feature_log = log2(percentage_neg_given_feature)

        second_emp_component_factor = percentage_pos_given_feature * percentage_pos_given_feature_log + \
                            percentage_neg_given_feature * percentage_neg_given_feature_log

        percentage_feature_given_pos = feature_present_in_pos / number_pos_instances
        percentage_feature_given_neg = feature_present_in_pos / number_neg_instances
        percentage_feature = percentage_feature_given_pos * percentage_pos_instances + \
                    percentage_feature_given_neg * percentage_neg_instances

        second_ent_component = percentage_feature * second_emp_component_factor
        percentage_pos_given_feature_component = 0
        percentage_neg_given_feature_component = 0
        if total_feature_absent>0:
            percentage_pos_given_feature_component = feature_absent_in_pos / total_feature_absent
            percentage_neg_given_feature_component = feature_absent_in_neg / total_feature_absent

        percentage_pos_given_feature_component_log = 0
        percentage_neg_given_feature_component_log = 0
        if percentage_pos_given_feature_component>0:
            percentage_pos_given_feature_component_log = log2(percentage_pos_given_feature_component)
        if percentage_neg_given_feature_component>0:
            percentage_neg_given_feature_component_log = log2(percentage_neg_given_feature_component)

        third_component_multi_factor = percentage_pos_given_feature_component * percentage_pos_given_feature_component_log + \
                percentage_neg_given_feature_component * percentage_neg_given_feature_component_log

        percentage_feature_comp_given_pos = feature_absent_in_pos / number_pos_instances
        percentage_feature_comp_given_neg = feature_absent_in_neg / number_neg_instances
        percentage_feature_comp = percentage_feature_comp_given_pos * percentage_pos_instances + \
                    percentage_feature_comp_given_neg * percentage_neg_instances

        third_ent_component = percentage_feature_comp * third_component_multi_factor
        entropy = first_ent_component + second_ent_component + third_ent_component

        feature_list.append([key, value, entropy])

    feature_list = sorted(feature_list, key=itemgetter(2), reverse=True)

    return feature_list
<commit_msg>rename nala to nalaf<commit_after>from nalaf.features import FeatureGenerator
from nltk.stem import PorterStemmer
import abc

class EdgeFeatureGenerator(FeatureGenerator):
    """
    Abstract class for generating features for each edge in the dataset.
    Subclasses that inherit this class should:
    * Be named [Name]FeatureGenerator
    * Implement the abstract method generate
    * Append new items to the dictionary field "features" of each Edge in the dataset
    """

    @abc.abstractmethod
    def generate(self, dataset):
        """
        :type dataset: nalaf.structures.data.Dataset
        """
        return

    def add_to_feature_set(self, edge, feature_name, value=1):
        if self.training_mode:
            if feature_name not in self.feature_set.keys():
                self.feature_set[feature_name] = len(self.feature_set.keys()) + 1
            edge.features[self.feature_set[feature_name]] = value
        else:
            if feature_name in self.feature_set.keys():
                edge.features[self.feature_set[feature_name]] = value

class TokenFeatureGenerator:
    """
    Token based features for each entity belonging to an edge
    """
    def __init__(self, feature_set, training_mode=True):
        self.feature_set = feature_set
        """the feature set for the dataset"""
        self.training_mode = training_mode
        """whether the mode is training or testing"""
        self.stemmer = PorterStemmer()
        """an instance of the PorterStemmer()"""

    def token_features(self, token, prefix, edge):
        feature_name_1 = '73_'+prefix+'txt_'+token.word+'_[0]'
        self.add_to_feature_set(edge, feature_name_1)
        feature_name_2 = '74_'+prefix+'pos_'+token.features['pos']+'_[0]'
        self.add_to_feature_set(edge, feature_name_2)
        feature_name_3 = '75_'+prefix+'txt_'+token.masked_text(edge.part)+'_[0]'
        self.add_to_feature_set(edge, feature_name_3)
        feature_name_4 = '76_'+prefix+'stem_'+self.stemmer.stem(token.masked_text(edge.part))+'_[0]'
        self.add_to_feature_set(edge, feature_name_4)
        ann_types = self.annotated_types(token, edge)
        for ann in ann_types:
            feature_name_5 = '77_'+prefix+'ann_type_'+ann+'_[0]'
            self.add_to_feature_set(edge, feature_name_5)

    def annotated_types(self, token, edge):
        head1 = edge.entity1.head_token
        head2 = edge.entity2.head_token
        if not token.is_entity_part(edge.part):
            feature_name = 'no_ann_type'
            return [feature_name]
        else:
            ann_types = []
            if token.is_entity_part(edge.part):
                entity = token.get_entity(edge.part)
                feature_name_1 = entity.class_id
                ann_types.append(feature_name_1)
                if entity==edge.entity1:
                    feature_name_2 = 'entity1_'+edge.entity1.class_id
                    ann_types.append(feature_name_2)
                    return ann_types
                elif entity==edge.entity2:
                    feature_name_2 = 'entity2_'+edge.entity2.class_id
                    ann_types.append(feature_name_2)
                    return ann_types
                return ann_types

    def add_to_feature_set(self, edge, feature_name, value=1):
        if self.training_mode:
            if feature_name not in self.feature_set.keys():
                self.feature_set[feature_name] = len(self.feature_set.keys()) + 1
            edge.features[self.feature_set[feature_name]] = value
        else:
            if feature_name in self.feature_set.keys():
                edge.features[self.feature_set[feature_name]] = value

def calculateInformationGain(feature_set, dataset, output_file):
    number_pos_instances = 0
    number_neg_instances = 0

    for edge in dataset.edges():
        if edge.target == 1:
            number_pos_instances += 1
        else:
            number_neg_instances += 1

    number_total_instances = number_pos_instances + number_neg_instances
    percentage_pos_instances = number_pos_instances / number_total_instances
    percentage_neg_instances = number_neg_instances / number_total_instances

    first_ent_component = -1 * (percentage_pos_instances * log2(percentage_pos_instances) + percentage_neg_instances * log2(percentage_neg_instances))
    feature_list = []
    for key, value in feature_set.items():
        feature_present_in_pos = 0
        feature_present_in_neg = 0
        feature_absent_in_pos = 0
        feature_absent_in_neg = 0
        total_feature_present = 0
        total_feature_absent = 0

        for edge in dataset.edges():
            if edge.target == 1:
                if value in edge.features.keys():
                    feature_present_in_pos += 1
                    total_feature_present += 1
                else:
                    feature_absent_in_pos += 1
                    total_feature_absent +=1
            if edge.target == -1:
                if value in edge.features.keys():
                    feature_present_in_neg += 1
                    total_feature_present += 1
                else:
                    feature_absent_in_neg += 1
                    total_feature_absent += 1

        percentage_pos_given_feature = 0
        percentage_neg_given_feature = 0
        if (total_feature_present > 0):
            percentage_pos_given_feature = feature_present_in_pos / total_feature_present
            percentage_neg_given_feature = feature_present_in_neg / total_feature_present

        percentage_pos_given_feature_log = 0
        percentage_neg_given_feature_log = 0
        if percentage_pos_given_feature > 0:
            percentage_pos_given_feature_log = log2(percentage_pos_given_feature)
        if percentage_neg_given_feature > 0:
            percentage_neg_given_feature_log = log2(percentage_neg_given_feature)

        second_emp_component_factor = percentage_pos_given_feature * percentage_pos_given_feature_log + \
                            percentage_neg_given_feature * percentage_neg_given_feature_log

        percentage_feature_given_pos = feature_present_in_pos / number_pos_instances
        percentage_feature_given_neg = feature_present_in_pos / number_neg_instances
        percentage_feature = percentage_feature_given_pos * percentage_pos_instances + \
                    percentage_feature_given_neg * percentage_neg_instances

        second_ent_component = percentage_feature * second_emp_component_factor
        percentage_pos_given_feature_component = 0
        percentage_neg_given_feature_component = 0
        if total_feature_absent>0:
            percentage_pos_given_feature_component = feature_absent_in_pos / total_feature_absent
            percentage_neg_given_feature_component = feature_absent_in_neg / total_feature_absent

        percentage_pos_given_feature_component_log = 0
        percentage_neg_given_feature_component_log = 0
        if percentage_pos_given_feature_component>0:
            percentage_pos_given_feature_component_log = log2(percentage_pos_given_feature_component)
        if percentage_neg_given_feature_component>0:
            percentage_neg_given_feature_component_log = log2(percentage_neg_given_feature_component)

        third_component_multi_factor = percentage_pos_given_feature_component * percentage_pos_given_feature_component_log + \
                percentage_neg_given_feature_component * percentage_neg_given_feature_component_log

        percentage_feature_comp_given_pos = feature_absent_in_pos / number_pos_instances
        percentage_feature_comp_given_neg = feature_absent_in_neg / number_neg_instances
        percentage_feature_comp = percentage_feature_comp_given_pos * percentage_pos_instances + \
                    percentage_feature_comp_given_neg * percentage_neg_instances

        third_ent_component = percentage_feature_comp * third_component_multi_factor
        entropy = first_ent_component + second_ent_component + third_ent_component

        feature_list.append([key, value, entropy])

    feature_list = sorted(feature_list, key=itemgetter(2), reverse=True)

    return feature_list
<|endoftext|>


<commit_before>from PyQt4.QtGui import *
from PyQt4.QtCore import *
import PyQt4.QtCore as QtCore

from electrum.i18n import _
from electrum import Wallet, mnemonic

from seed_dialog import SeedDialog
from network_dialog import NetworkDialog
from util import *
from amountedit import AmountEdit

import sys
import threading

class InstallWizard(QDialog):

    def __init__(self, config, network, storage):
        QDialog.__init__(self)
        self.config = config
        self.network = network
        self.storage = storage
        self.setMinimumSize(575, 400)
        self.setWindowTitle('Electrum')
        self.connect(self, QtCore.SIGNAL('accept'), self.accept)

    def restore_or_create(self):

        grid = QGridLayout()
        grid.setSpacing(5)

        msg = _("Electrum could not find an existing wallet.")+"\n\n"+_("Did you use Electrum before and want to restore a previous wallet or is this your first time and do you want to create a new wallet?")+"\n"
        label = QLabel(msg)
        label.setWordWrap(True)
        grid.addWidget(label, 0, 0)

        gb = QGroupBox()

        b1 = QRadioButton(gb)
        b1.setText(_("Create new wallet"))
        b1.setChecked(True)

        b2 = QRadioButton(gb)
        b2.setText(_("Restore wallet from seed"))

        b3 = QRadioButton(gb)
        b3.setText(_("Restore wallet from master public key"))

        grid.addWidget(b1,1,0)
        grid.addWidget(b2,2,0)
        grid.addWidget(b3,3,0)

        vbox = QVBoxLayout(self)
        vbox.addLayout(grid)

        vbox.addStretch(1)
        vbox.addLayout(ok_cancel_buttons(self, _('Next')))

        if not self.exec_():
            return

        if b1.isChecked():
            answer = 'create'
        elif b2.isChecked():
            answer = 'restore'
        else:
            answer = 'watching'

        return answer

    def verify_seed(self, wallet):
        r = self.seed_dialog(False)
        if not r:
            return

        if r != wallet.seed:
            QMessageBox.warning(None, _('Error'), _('Incorrect seed'), _('OK'))
            return False
        else:
            return True

    def seed_dialog(self, is_restore=True):

        if self.layout(): QWidget().setLayout(self.layout())

        vbox = QVBoxLayout(self)
        if is_restore:
            msg = _("Please enter your wallet seed.") + "\n"
            msg += _("Your seed can be entered as a sequence of words, or as a hexadecimal string.")+ ' \n'
        else:
            msg = _("Your seed is important!") \
                  + "\n" + _("To make sure that you have properly saved your seed, please retype it here.") + ' '

        logo = QLabel()
        logo.setPixmap(QPixmap(":icons/seed.png").scaledToWidth(56))
        logo.setMaximumWidth(60)

        label = QLabel(msg)
        label.setWordWrap(True)

        seed_e = QTextEdit()
        seed_e.setMaximumHeight(100)

        vbox.addWidget(label)

        grid = QGridLayout()
        grid.addWidget(logo, 0, 0)
        grid.addWidget(seed_e, 0, 1)

        vbox.addLayout(grid)

        vbox.addStretch(1)
        vbox.addLayout(ok_cancel_buttons(self, _('Next')))

        if not self.exec_():
            return

        try:
            seed = str(seed_e.toPlainText())
            seed.decode('hex')
        except:
            try:
                seed = mnemonic.mn_decode( seed.split() )
            except:
                QMessageBox.warning(None, _('Error'), _('I cannot decode this'), _('OK'))
                return

        if not seed:
            QMessageBox.warning(None, _('Error'), _('No seed'), _('OK'))
            return

        return seed

    def waiting_dialog(self, task, msg= _("Electrum is generating your addresses, please wait.")):
        def target():
            task()
            self.emit(QtCore.SIGNAL('accept'))

        if self.layout(): QWidget().setLayout(self.layout())
        vbox = QVBoxLayout(self)
        self.waiting_label = QLabel(msg)
        vbox.addWidget(self.waiting_label)
        t = threading.Thread(target = target)
        t.start()
        self.exec_()

    def mpk_dialog(self):

        if self.layout(): QWidget().setLayout(self.layout())

        vbox = QVBoxLayout(self)

        vbox.addWidget(QLabel(_("Please enter your master public key.")))

        grid = QGridLayout()
        grid.setSpacing(8)

        label = QLabel(_("Key"))
        grid.addWidget(label, 0, 0)
        mpk_e = QTextEdit()
        mpk_e.setMaximumHeight(100)
        grid.addWidget(mpk_e, 0, 1)

        label = QLabel(_("Chain"))
        grid.addWidget(label, 1, 0)
        chain_e = QTextEdit()
        chain_e.setMaximumHeight(100)
        grid.addWidget(chain_e, 1, 1)

        vbox.addLayout(grid)

        vbox.addStretch(1)
        vbox.addLayout(ok_cancel_buttons(self, _('Next')))

        if not self.exec_(): return None, None

        mpk = str(mpk_e.toPlainText()).strip()
        chain = str(chain_e.toPlainText()).strip()
        return mpk, chain

    def network_dialog(self):

        if self.layout(): QWidget().setLayout(self.layout())

        grid = QGridLayout()
        grid.setSpacing(5)

        label = QLabel(_("Electrum communicates with remote servers to get information about your transactions and addresses. The servers all fulfil the same purpose only differing in hardware. In most cases you simply want to let Electrum pick one at random if you have a preference though feel free to select a server manually.") + "\n\n" \
                      + _("How do you want to connect to a server:")+" ")
        label.setWordWrap(True)
        grid.addWidget(label, 0, 0)

        gb = QGroupBox()

        b1 = QRadioButton(gb)
        b1.setText(_("Auto connect"))
        b1.setChecked(True)

        b2 = QRadioButton(gb)
        b2.setText(_("Select server manually"))

        #b3 = QRadioButton(gb)
        #b3.setText(_("Stay offline"))

        grid.addWidget(b1,1,0)
        grid.addWidget(b2,2,0)
        #grid.addWidget(b3,3,0)

        vbox = QVBoxLayout(self)
        vbox.addLayout(grid)

        vbox.addStretch(1)
        vbox.addLayout(ok_cancel_buttons(self, _('Next')))

        if not self.exec_():
            return

        if b2.isChecked():
            return NetworkDialog(self.network, self.config, None).do_exec()

        elif b1.isChecked():
            self.config.set_key('auto_cycle', True, True)
            return

        else:
            self.config.set_key("server", None, True)
            self.config.set_key('auto_cycle', False, True)
            return

    def show_seed(self, wallet):
        from seed_dialog import make_seed_dialog

        vbox = make_seed_dialog(wallet.seed, wallet.imported_keys)
        vbox.addLayout(ok_cancel_buttons(self, _("Next")))

        if self.layout(): QWidget().setLayout(self.layout())
        self.setLayout(vbox)

        if not self.exec_():
            exit()

    def password_dialog(self, wallet):
        msg = _("Please choose a password to encrypt your wallet keys.")+'\n'\
              +_("Leave these fields empty if you want to disable encryption.")
        from password_dialog import make_password_dialog, run_password_dialog
        if self.layout(): QWidget().setLayout(self.layout())
        make_password_dialog(self, wallet, msg)
        run_password_dialog(self, wallet, self)

    def run(self):

        action = self.restore_or_create()
        if not action: exit()

        wallet = Wallet(self.storage)
        gap = self.config.get('gap_limit', 5)
        if gap != 5:
            wallet.gap_limit = gap
            wallet.storage.put('gap_limit', gap, True)

        if action == 'create':
            wallet.init_seed(None)
            self.show_seed(wallet)
            if self.verify_seed(wallet):
                def create():
                    wallet.save_seed()
                    wallet.create_accounts()
                    wallet.synchronize()  # generate first addresses offline
                self.waiting_dialog(create)
            else:
                return

        elif action == 'restore':
            # ask for seed and gap.
            seed = self.seed_dialog()
            if not seed:
                return
            wallet.init_seed(str(seed))
            wallet.save_seed()

        elif action == 'watching':
            # ask for seed and gap.
            K, chain = self.mpk_dialog()
            if not K:
                return
            wallet.seed = ''
            wallet.create_watching_only_wallet(chain,K)

        else: raise

        #if not self.config.get('server'):
        self.network_dialog()

        # start wallet threads
        wallet.start_threads(self.network)

        if action == 'restore':

            self.waiting_dialog(lambda: wallet.restore(self.waiting_label.setText))

            if wallet.is_found():
                QMessageBox.information(None, _('Information'), _("Recovery successful"), _('OK'))
            else:
                QMessageBox.information(None, _('Information'), _("No transactions found for this seed"), _('OK'))

            wallet.fill_addressbook()

        self.password_dialog(wallet)

        return wallet
<commit_msg>enforce 'chain' parameter in wizard<commit_after>from PyQt4.QtGui import *
from PyQt4.QtCore import *
import PyQt4.QtCore as QtCore

from electrum.i18n import _
from electrum import Wallet, mnemonic

from seed_dialog import SeedDialog
from network_dialog import NetworkDialog
from util import *
from amountedit import AmountEdit

import sys
import threading

class InstallWizard(QDialog):

    def __init__(self, config, network, storage):
        QDialog.__init__(self)
        self.config = config
        self.network = network
        self.storage = storage
        self.setMinimumSize(575, 400)
        self.setWindowTitle('Electrum')
        self.connect(self, QtCore.SIGNAL('accept'), self.accept)

    def restore_or_create(self):

        grid = QGridLayout()
        grid.setSpacing(5)

        msg = _("Electrum could not find an existing wallet.")+"\n\n"+_("Did you use Electrum before and want to restore a previous wallet or is this your first time and do you want to create a new wallet?")+"\n"
        label = QLabel(msg)
        label.setWordWrap(True)
        grid.addWidget(label, 0, 0)

        gb = QGroupBox()

        b1 = QRadioButton(gb)
        b1.setText(_("Create new wallet"))
        b1.setChecked(True)

        b2 = QRadioButton(gb)
        b2.setText(_("Restore wallet from seed"))

        b3 = QRadioButton(gb)
        b3.setText(_("Restore wallet from master public key"))

        grid.addWidget(b1,1,0)
        grid.addWidget(b2,2,0)
        grid.addWidget(b3,3,0)

        vbox = QVBoxLayout(self)
        vbox.addLayout(grid)

        vbox.addStretch(1)
        vbox.addLayout(ok_cancel_buttons(self, _('Next')))

        if not self.exec_():
            return

        if b1.isChecked():
            answer = 'create'
        elif b2.isChecked():
            answer = 'restore'
        else:
            answer = 'watching'

        return answer

    def verify_seed(self, wallet):
        r = self.seed_dialog(False)
        if not r:
            return

        if r != wallet.seed:
            QMessageBox.warning(None, _('Error'), _('Incorrect seed'), _('OK'))
            return False
        else:
            return True

    def seed_dialog(self, is_restore=True):

        if self.layout(): QWidget().setLayout(self.layout())

        vbox = QVBoxLayout(self)
        if is_restore:
            msg = _("Please enter your wallet seed.") + "\n"
            msg += _("Your seed can be entered as a sequence of words, or as a hexadecimal string.")+ ' \n'
        else:
            msg = _("Your seed is important!") \
                  + "\n" + _("To make sure that you have properly saved your seed, please retype it here.") + ' '

        logo = QLabel()
        logo.setPixmap(QPixmap(":icons/seed.png").scaledToWidth(56))
        logo.setMaximumWidth(60)

        label = QLabel(msg)
        label.setWordWrap(True)

        seed_e = QTextEdit()
        seed_e.setMaximumHeight(100)

        vbox.addWidget(label)

        grid = QGridLayout()
        grid.addWidget(logo, 0, 0)
        grid.addWidget(seed_e, 0, 1)

        vbox.addLayout(grid)

        vbox.addStretch(1)
        vbox.addLayout(ok_cancel_buttons(self, _('Next')))

        if not self.exec_():
            return

        try:
            seed = str(seed_e.toPlainText())
            seed.decode('hex')
        except:
            try:
                seed = mnemonic.mn_decode( seed.split() )
            except:
                QMessageBox.warning(None, _('Error'), _('I cannot decode this'), _('OK'))
                return

        if not seed:
            QMessageBox.warning(None, _('Error'), _('No seed'), _('OK'))
            return

        return seed

    def waiting_dialog(self, task, msg= _("Electrum is generating your addresses, please wait.")):
        def target():
            task()
            self.emit(QtCore.SIGNAL('accept'))

        if self.layout(): QWidget().setLayout(self.layout())
        vbox = QVBoxLayout(self)
        self.waiting_label = QLabel(msg)
        vbox.addWidget(self.waiting_label)
        t = threading.Thread(target = target)
        t.start()
        self.exec_()

    def mpk_dialog(self):

        if self.layout(): QWidget().setLayout(self.layout())

        vbox = QVBoxLayout(self)

        vbox.addWidget(QLabel(_("Please enter your master public key.")))

        grid = QGridLayout()
        grid.setSpacing(8)

        label = QLabel(_("Key"))
        grid.addWidget(label, 0, 0)
        mpk_e = QTextEdit()
        mpk_e.setMaximumHeight(100)
        grid.addWidget(mpk_e, 0, 1)

        label = QLabel(_("Chain"))
        grid.addWidget(label, 1, 0)
        chain_e = QTextEdit()
        chain_e.setMaximumHeight(100)
        grid.addWidget(chain_e, 1, 1)

        vbox.addLayout(grid)

        vbox.addStretch(1)
        vbox.addLayout(ok_cancel_buttons(self, _('Next')))

        if not self.exec_(): return None, None

        mpk = str(mpk_e.toPlainText()).strip()
        chain = str(chain_e.toPlainText()).strip()
        return mpk, chain

    def network_dialog(self):

        if self.layout(): QWidget().setLayout(self.layout())

        grid = QGridLayout()
        grid.setSpacing(5)

        label = QLabel(_("Electrum communicates with remote servers to get information about your transactions and addresses. The servers all fulfil the same purpose only differing in hardware. In most cases you simply want to let Electrum pick one at random if you have a preference though feel free to select a server manually.") + "\n\n" \
                      + _("How do you want to connect to a server:")+" ")
        label.setWordWrap(True)
        grid.addWidget(label, 0, 0)

        gb = QGroupBox()

        b1 = QRadioButton(gb)
        b1.setText(_("Auto connect"))
        b1.setChecked(True)

        b2 = QRadioButton(gb)
        b2.setText(_("Select server manually"))

        #b3 = QRadioButton(gb)
        #b3.setText(_("Stay offline"))

        grid.addWidget(b1,1,0)
        grid.addWidget(b2,2,0)
        #grid.addWidget(b3,3,0)

        vbox = QVBoxLayout(self)
        vbox.addLayout(grid)

        vbox.addStretch(1)
        vbox.addLayout(ok_cancel_buttons(self, _('Next')))

        if not self.exec_():
            return

        if b2.isChecked():
            return NetworkDialog(self.network, self.config, None).do_exec()

        elif b1.isChecked():
            self.config.set_key('auto_cycle', True, True)
            return

        else:
            self.config.set_key("server", None, True)
            self.config.set_key('auto_cycle', False, True)
            return

    def show_seed(self, wallet):
        from seed_dialog import make_seed_dialog

        vbox = make_seed_dialog(wallet.seed, wallet.imported_keys)
        vbox.addLayout(ok_cancel_buttons(self, _("Next")))

        if self.layout(): QWidget().setLayout(self.layout())
        self.setLayout(vbox)

        if not self.exec_():
            exit()

    def password_dialog(self, wallet):
        msg = _("Please choose a password to encrypt your wallet keys.")+'\n'\
              +_("Leave these fields empty if you want to disable encryption.")
        from password_dialog import make_password_dialog, run_password_dialog
        if self.layout(): QWidget().setLayout(self.layout())
        make_password_dialog(self, wallet, msg)
        run_password_dialog(self, wallet, self)

    def run(self):

        action = self.restore_or_create()
        if not action: exit()

        wallet = Wallet(self.storage)
        gap = self.config.get('gap_limit', 5)
        if gap != 5:
            wallet.gap_limit = gap
            wallet.storage.put('gap_limit', gap, True)

        if action == 'create':
            wallet.init_seed(None)
            self.show_seed(wallet)
            if self.verify_seed(wallet):
                def create():
                    wallet.save_seed()
                    wallet.create_accounts()
                    wallet.synchronize()  # generate first addresses offline
                self.waiting_dialog(create)
            else:
                return

        elif action == 'restore':
            # ask for seed and gap.
            seed = self.seed_dialog()
            if not seed:
                return
            wallet.init_seed(str(seed))
            wallet.save_seed()

        elif action == 'watching':
            # ask for seed and gap.
            K, chain = self.mpk_dialog()
            if not K or not chain:
                return
            wallet.seed = ''
            wallet.create_watching_only_wallet(chain,K)

        else: raise

        #if not self.config.get('server'):
        self.network_dialog()

        # start wallet threads
        wallet.start_threads(self.network)

        if action == 'restore':

            self.waiting_dialog(lambda: wallet.restore(self.waiting_label.setText))

            if wallet.is_found():
                QMessageBox.information(None, _('Information'), _("Recovery successful"), _('OK'))
            else:
                QMessageBox.information(None, _('Information'), _("No transactions found for this seed"), _('OK'))

            wallet.fill_addressbook()

        self.password_dialog(wallet)

        return wallet
<|endoftext|>