<commit_before>"""Provides the repository macro to import LLVM."""

load("//third_party:repo.bzl", "tf_http_archive")

def repo(name):
    """Imports LLVM."""
    LLVM_COMMIT = "f3a86a23c10db44cbcb432d56201475721c64bdc"
    LLVM_SHA256 = "9423c8bced64b69f5536c22e794a2b9635502f05bade81c022bb522fdfd9afce"

    tf_http_archive(
        name = name,
        sha256 = LLVM_SHA256,
        strip_prefix = "llvm-project-{commit}".format(commit = LLVM_COMMIT),
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
            "https://github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
        ],
        build_file = "//third_party/llvm:llvm.BUILD",
        patch_file = [
            "//third_party/llvm:build.patch",
            "//third_party/llvm:mathextras.patch",
            "//third_party/llvm:toolchains.patch",
            "//third_party/llvm:temporary.patch",  # Cherry-picks and temporary reverts. Do not remove even if temporary.patch is empty.
        ],
        link_files = {"//third_party/llvm:run_lit.sh": "mlir/run_lit.sh"},
    )
<commit_msg>Integrate LLVM at llvm/llvm-project@632a389f9635<commit_after>"""Provides the repository macro to import LLVM."""

load("//third_party:repo.bzl", "tf_http_archive")

def repo(name):
    """Imports LLVM."""
    LLVM_COMMIT = "632a389f96355cbe7ed8fa7b8d2ed6267c92457c"
    LLVM_SHA256 = "c6d753605975e4c11bce7befeec4b1f4a9d1e2d7ea0fcde1705d62f9bcb65179"

    tf_http_archive(
        name = name,
        sha256 = LLVM_SHA256,
        strip_prefix = "llvm-project-{commit}".format(commit = LLVM_COMMIT),
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
            "https://github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
        ],
        build_file = "//third_party/llvm:llvm.BUILD",
        patch_file = [
            "//third_party/llvm:build.patch",
            "//third_party/llvm:mathextras.patch",
            "//third_party/llvm:toolchains.patch",
            "//third_party/llvm:temporary.patch",  # Cherry-picks and temporary reverts. Do not remove even if temporary.patch is empty.
        ],
        link_files = {"//third_party/llvm:run_lit.sh": "mlir/run_lit.sh"},
    )
<|endoftext|>


<commit_before>"""Provides the repository macro to import LLVM."""

load("//third_party:repo.bzl", "tf_http_archive")

def repo(name):
    """Imports LLVM."""
    LLVM_COMMIT = "0a715c114686806193878e876ed3d50144138263"
    LLVM_SHA256 = "b7c468b570cf079b22cc05bd248008cdf732936598efbc5893b583a7c508e9dc"

    tf_http_archive(
        name = name,
        sha256 = LLVM_SHA256,
        strip_prefix = "llvm-project-{commit}".format(commit = LLVM_COMMIT),
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
            "https://github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
        ],
        build_file = "//third_party/llvm:llvm.BUILD",
        patch_file = [
            "//third_party/llvm:infer_type.patch",  # TODO(b/231285230): remove once resolved
            "//third_party/llvm:build.patch",
            "//third_party/llvm:macos_build_fix.patch",
        ],
        link_files = {"//third_party/llvm:run_lit.sh": "mlir/run_lit.sh"},
    )
<commit_msg>Integrate LLVM at llvm/llvm-project@b6fef0885333<commit_after>"""Provides the repository macro to import LLVM."""

load("//third_party:repo.bzl", "tf_http_archive")

def repo(name):
    """Imports LLVM."""
    LLVM_COMMIT = "b6fef088533376e16ca6b47f87c6c50f6f6cd014"
    LLVM_SHA256 = "f2a269f4c54f9c0aaad23126564680cdd729e365c36d290ac4dc213b555a0e9a"

    tf_http_archive(
        name = name,
        sha256 = LLVM_SHA256,
        strip_prefix = "llvm-project-{commit}".format(commit = LLVM_COMMIT),
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
            "https://github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
        ],
        build_file = "//third_party/llvm:llvm.BUILD",
        patch_file = [
            "//third_party/llvm:infer_type.patch",  # TODO(b/231285230): remove once resolved
            "//third_party/llvm:build.patch",
            "//third_party/llvm:macos_build_fix.patch",
        ],
        link_files = {"//third_party/llvm:run_lit.sh": "mlir/run_lit.sh"},
    )
<|endoftext|>


<commit_before>"""Provides the repository macro to import LLVM."""

load("//third_party:repo.bzl", "tf_http_archive")

def repo(name):
    """Imports LLVM."""
    LLVM_COMMIT = "7dde2a59e61ad669b52a93b0259ce2ad20d642fa"
    LLVM_SHA256 = "9710cf0d5a3076036c86a452b5f4e71812e4d9e0d8cd72f7bcb73db6b723216f"

    tf_http_archive(
        name = name,
        sha256 = LLVM_SHA256,
        strip_prefix = "llvm-project-{commit}".format(commit = LLVM_COMMIT),
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
            "https://github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
        ],
        build_file = "//third_party/llvm:llvm.BUILD",
        patch_file = [
            "//third_party/llvm:build.patch",
            "//third_party/llvm:mathextras.patch",
            "//third_party/llvm:toolchains.patch",
            "//third_party/llvm:temporary.patch",  # Cherry-picks and temporary reverts. Do not remove even if temporary.patch is empty.
        ],
        link_files = {"//third_party/llvm:run_lit.sh": "mlir/run_lit.sh"},
    )
<commit_msg>Integrate LLVM at llvm/llvm-project@e8a83c8dbf33<commit_after>"""Provides the repository macro to import LLVM."""

load("//third_party:repo.bzl", "tf_http_archive")

def repo(name):
    """Imports LLVM."""
    LLVM_COMMIT = "e8a83c8dbf3398ab9517d595432944bee21b02df"
    LLVM_SHA256 = "14c388f32731911a99bdb066baa33a3d34b916d025ed2c3ab135e022e87aae7a"

    tf_http_archive(
        name = name,
        sha256 = LLVM_SHA256,
        strip_prefix = "llvm-project-{commit}".format(commit = LLVM_COMMIT),
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
            "https://github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
        ],
        build_file = "//third_party/llvm:llvm.BUILD",
        patch_file = [
            "//third_party/llvm:build.patch",
            "//third_party/llvm:mathextras.patch",
            "//third_party/llvm:toolchains.patch",
            "//third_party/llvm:temporary.patch",  # Cherry-picks and temporary reverts. Do not remove even if temporary.patch is empty.
        ],
        link_files = {"//third_party/llvm:run_lit.sh": "mlir/run_lit.sh"},
    )
<|endoftext|>


<commit_before>"""Provides the repository macro to import LLVM."""

load("//third_party:repo.bzl", "tfrt_http_archive")

def repo(name):
    """Imports LLVM."""
    LLVM_COMMIT = "04a5ca862bb989acdd2729d0991b4e5a104bf244"
    LLVM_SHA256 = "10a0c150c477a36eff25d49f0f50379fddf626a7d87a2b1846fb101173c742c9"

    tfrt_http_archive(
        name = name,
        build_file = "//third_party/llvm:BUILD",
        sha256 = LLVM_SHA256,
        strip_prefix = "llvm-project-" + LLVM_COMMIT,
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
            "https://github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
        ],
    )
<commit_msg>Integrate LLVM at llvm/llvm-project@fa79dff8bc8b<commit_after>"""Provides the repository macro to import LLVM."""

load("//third_party:repo.bzl", "tfrt_http_archive")

def repo(name):
    """Imports LLVM."""
    LLVM_COMMIT = "fa79dff8bc8b2da923d4935f4b2035f7e1e11e0a"
    LLVM_SHA256 = "cf940b7e6f047fdbae94c8f01197400e81782685ff39736023bd07c249c6cf83"

    tfrt_http_archive(
        name = name,
        build_file = "//third_party/llvm:BUILD",
        sha256 = LLVM_SHA256,
        strip_prefix = "llvm-project-" + LLVM_COMMIT,
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
            "https://github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
        ],
    )
<|endoftext|>


<commit_before>"""Provides the repository macro to import LLVM."""

load("//third_party:repo.bzl", "tf_http_archive")

def repo(name):
    """Imports LLVM."""
    LLVM_COMMIT = "85f08c4197aea68b2444e6874524b5f8b4067cfd"
    LLVM_SHA256 = "c8cc9c8eeaf32a350b23315e8e2804ee51a64d63fae429ba3acc84831f6b778f"

    tf_http_archive(
        name = name,
        sha256 = LLVM_SHA256,
        strip_prefix = "llvm-project-{commit}".format(commit = LLVM_COMMIT),
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
            "https://github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
        ],
        build_file = "//third_party/llvm:llvm.BUILD",
        patch_file = [
            "//third_party/llvm:build.patch",
            "//third_party/llvm:mathextras.patch",
            "//third_party/llvm:toolchains.patch",
            "//third_party/llvm:temporary.patch",  # Cherry-picks and temporary reverts. Do not remove even if temporary.patch is empty.
        ],
        link_files = {"//third_party/llvm:run_lit.sh": "mlir/run_lit.sh"},
    )
<commit_msg>Integrate LLVM at llvm/llvm-project@e1b88c8a09be<commit_after>"""Provides the repository macro to import LLVM."""

load("//third_party:repo.bzl", "tf_http_archive")

def repo(name):
    """Imports LLVM."""
    LLVM_COMMIT = "e1b88c8a09be25b86b13f98755a9bd744b4dbf14"
    LLVM_SHA256 = "99c76ba24dcf26bee589f7446f2108e264e1a3148118edb1ce64795708359672"

    tf_http_archive(
        name = name,
        sha256 = LLVM_SHA256,
        strip_prefix = "llvm-project-{commit}".format(commit = LLVM_COMMIT),
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
            "https://github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
        ],
        build_file = "//third_party/llvm:llvm.BUILD",
        patch_file = [
            "//third_party/llvm:build.patch",
            "//third_party/llvm:mathextras.patch",
            "//third_party/llvm:toolchains.patch",
            "//third_party/llvm:temporary.patch",  # Cherry-picks and temporary reverts. Do not remove even if temporary.patch is empty.
        ],
        link_files = {"//third_party/llvm:run_lit.sh": "mlir/run_lit.sh"},
    )
<|endoftext|>


<commit_before>"""Provides the repository macro to import LLVM."""

load("//third_party:repo.bzl", "tfrt_http_archive")

def repo(name):
    """Imports LLVM."""
    LLVM_COMMIT = "c531171d995728f55e5775d354a21dceed03edce"
    LLVM_SHA256 = "4c33d5335f56687834ef43a8b1bf3f14cc5b1afbd0654bc5e376e928fd6d20e0"

    tfrt_http_archive(
        name = name,
        build_file = "//third_party/llvm:BUILD",
        sha256 = LLVM_SHA256,
        strip_prefix = "llvm-project-" + LLVM_COMMIT,
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
            "https://github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
        ],
    )
<commit_msg>Integrate LLVM at llvm/llvm-project@73244e8f8568<commit_after>"""Provides the repository macro to import LLVM."""

load("//third_party:repo.bzl", "tfrt_http_archive")

def repo(name):
    """Imports LLVM."""
    LLVM_COMMIT = "73244e8f8568fb0ebf0be5943c5d290f5b91d0c1"
    LLVM_SHA256 = "5417444887bf4776cad189d22168fe5e21e60e58a31bf277f0856ed629ef7ab1"

    tfrt_http_archive(
        name = name,
        build_file = "//third_party/llvm:BUILD",
        sha256 = LLVM_SHA256,
        strip_prefix = "llvm-project-" + LLVM_COMMIT,
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
            "https://github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
        ],
    )
<|endoftext|>


<commit_before>"""Provides the repository macro to import LLVM."""

load("//third_party:repo.bzl", "tfrt_http_archive")

def repo(name):
    """Imports LLVM."""
    LLVM_COMMIT = "3189dd205a581272b9a0cfc614e8f341495fc716"
    LLVM_SHA256 = "7318c3e797bd4143c15540117cefe908621ba83f74f10d28876ba16a1962e7c5"

    tfrt_http_archive(
        name = name,
        sha256 = LLVM_SHA256,
        strip_prefix = "llvm-project-" + LLVM_COMMIT,
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
            "https://github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
        ],
        link_files = {
            "//third_party/llvm:llvm.autogenerated.BUILD": "llvm/BUILD",
            "//third_party/mlir:BUILD": "mlir/BUILD",
            "//third_party/mlir:build_defs.bzl": "mlir/build_defs.bzl",
            "//third_party/mlir:linalggen.bzl": "mlir/linalggen.bzl",
            "//third_party/mlir:tblgen.bzl": "mlir/tblgen.bzl",
            "//third_party/mlir:test.BUILD": "mlir/test/BUILD",
        },
    )
<commit_msg>Integrate LLVM at llvm/llvm-project@c120edc7b3e1<commit_after>"""Provides the repository macro to import LLVM."""

load("//third_party:repo.bzl", "tfrt_http_archive")

def repo(name):
    """Imports LLVM."""
    LLVM_COMMIT = "c120edc7b3e1907127c3107b30e2667f1fde1ee2"
    LLVM_SHA256 = "c663a1b0f5d09d75d512240cb6345baff5ee0f9bffb84944cae6a2231d3e20e1"

    tfrt_http_archive(
        name = name,
        sha256 = LLVM_SHA256,
        strip_prefix = "llvm-project-" + LLVM_COMMIT,
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
            "https://github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
        ],
        link_files = {
            "//third_party/llvm:llvm.autogenerated.BUILD": "llvm/BUILD",
            "//third_party/mlir:BUILD": "mlir/BUILD",
            "//third_party/mlir:build_defs.bzl": "mlir/build_defs.bzl",
            "//third_party/mlir:linalggen.bzl": "mlir/linalggen.bzl",
            "//third_party/mlir:tblgen.bzl": "mlir/tblgen.bzl",
            "//third_party/mlir:test.BUILD": "mlir/test/BUILD",
        },
    )
<|endoftext|>


<commit_before>"""Provides the repository macro to import LLVM."""

load("//third_party:repo.bzl", "tfrt_http_archive")

def repo(name):
    """Imports LLVM."""
    LLVM_COMMIT = "d0a4450ecdaf124f9d422dbcba8cbdbeb50c836a"
    LLVM_SHA256 = "ea21b08d17045df1d25a3f296c8d9629b84943cdbbe419bafd74459e57bed921"

    tfrt_http_archive(
        name = name,
        build_file = "//third_party/llvm:BUILD",
        sha256 = LLVM_SHA256,
        strip_prefix = "llvm-project-" + LLVM_COMMIT,
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
            "https://github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
        ],
    )
<commit_msg>Integrate LLVM at llvm/llvm-project@6f258c0fd34c<commit_after>"""Provides the repository macro to import LLVM."""

load("//third_party:repo.bzl", "tfrt_http_archive")

def repo(name):
    """Imports LLVM."""
    LLVM_COMMIT = "6f258c0fd34cf4001ffa08c61f6e4e0f1254c50f"
    LLVM_SHA256 = "9464c454c66b0c33f0e431fd24c5e35cd5db02c4983377b88d386cd0ad94130e"

    tfrt_http_archive(
        name = name,
        build_file = "//third_party/llvm:BUILD",
        sha256 = LLVM_SHA256,
        strip_prefix = "llvm-project-" + LLVM_COMMIT,
        urls = [
            "https://storage.googleapis.com/mirror.tensorflow.org/github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
            "https://github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
        ],
    )
<|endoftext|>


<commit_before>__author__ = 'giacomov'

import numpy as np

import ROOT
import root_numpy

from threeML.io.cern_root_utils.io_utils import get_list_of_keys, open_ROOT_file
from threeML.io.cern_root_utils.tobject_to_numpy import tgraph_to_arrays, th2_to_arrays, tree_to_ndarray
from threeML.plugins.OGIPLike import OGIPLike
from threeML.plugins.OGIP.pha import PHAContainer
from threeML.plugins.OGIP.response import RMF
import astropy.io.fits as pyfits

__instrument_name = "VERITAS"

# This is the data format v 1.0 agreed with Udara:
# * each run is in a different folder within the ROOT file, called run_XXXXXX
# * each run contains the following trees:

_trees_in_run = ['data_on',  # Event list in the source region
                 'data_off',  # Event list of the background region
                 'tRunSummary',  # Summary info on the run (exposure, and so on, see below)
                 'gMeanEffectiveArea',  # Effective area
                 'fAccZe_0',  # relative acceptance with respect to the on-axis area
                 'hMigration'  # Redistribution matrix (energy dispersion)
                 ]

# In the data_* trees we have:

_columns_in_data_tree = ['Time',  # it is the MJD of individual events
                         'Erec'  # reconstructed energy. *****Note that there are some events with negative
                                      # energy. Those are the events that we were unable to reconstruct energy.
                                      # In VERITAS when we calculate significance some times we use these events,
                                      # if we are not quoting the energy. Because failing the energy reconstruction
                                      # does not mean that the event is a bad event. However, if we quote an energy
                                      # band we do not use them.
                         'Xoff',  # this is the X offset from the detector centre in degrees.
                         'Yoff',  # this is the Y offset from the detector centre in degrees.
                         'theta2'  # X^2 + Y^2 (i.e., off-axis radius squared)
                         ]

class VERITASRun(object):

    def __init__(self, root_file, run_name):

        # Read the data from the ROOT file

        with open_ROOT_file(root_file) as f:

            # Read first the TTrees as pandas DataFrame

            self._data_on = tree_to_ndarray(f.Get(run_name+'/data_on'))  # type: np.ndarray
            self._data_off = tree_to_ndarray(f.Get(run_name+'/data_off'))  # type: np.ndarray
            self._tRunSummary = np.squeeze(tree_to_ndarray(f.Get(run_name+'/tRunSummary')))  # type: np.ndarray

            # Now read the histogram
            self._mc_energies, self._recon_energies, self._hMigration = th2_to_arrays(f.Get(run_name + "/hMigration"))

            # Read the TGraph
            tgraph = f.Get(run_name + "/gMeanEffectiveArea")
            self._gMeanEffectiveArea_energies, self._gMeanEffectiveArea_area = tgraph_to_arrays(tgraph)

        # Static members for genereting OGIP equivalents

        self._mission = "VERITAS"
        self._instrument = "VERITAS"

    def get_response(self, filename):

        rmf = RMF()

    def get_pha(self):

        # Get the exposure
        exposure = float(self._tRunSummary['DeadTimeFracOn'])

        # Bin the counts in energy
        counts, _ = np.histogram(self._data_on['Erec'], self._recon_energies)

        # Now get the rates
        rates = counts / exposure

        # Assume Poisson statistic
        rate_err = np.sqrt(counts) / exposure

        # Number of "channels"
        n_channels = self._recon_energies.shape[0]

        pha = PHAContainer(rates = rates,
                           rate_errors = rate_err,
                           n_channels = n_channels,
                           exposure = exposure,
                           is_poisson = True,
                           response_file=self._rsp_file,
                           mission = self._mission,
                           instrument = self._instrument,
                           quality = np.zeros_like(rates, dtype=int))  # default quality to all good

        return pha

class VERITASData(object):

    def __init__(self, veritas_root_data):

        # Open file

        f = ROOT.TFile(veritas_root_data)

        try:

            # Loop over the runs
            keys = get_list_of_keys(f)

            run_numbers = filter(lambda x:x.find("run") == 0, keys)

            for run in run_numbers:

                pass

        finally:

            f.close()

# This function get a list of

class VERITASLike(OGIPLike):

    def __init__(self, name, udara_style_root_file):

        super(VERITASLike, self).__init__(name, {})<commit_msg>updated VERITAS plugin to use POISSON_PHAII<commit_after>__author__ = 'giacomov'

import numpy as np

import ROOT
import root_numpy

from threeML.io.cern_root_utils.io_utils import get_list_of_keys, open_ROOT_file
from threeML.io.cern_root_utils.tobject_to_numpy import tgraph_to_arrays, th2_to_arrays, tree_to_ndarray
from threeML.plugins.OGIPLike import OGIPLike
from threeML.plugins.OGIP.pha import POISSON_PHAII
from threeML.plugins.OGIP.response import RMF
import astropy.io.fits as pyfits

__instrument_name = "VERITAS"

# This is the data format v 1.0 agreed with Udara:
# * each run is in a different folder within the ROOT file, called run_XXXXXX
# * each run contains the following trees:

_trees_in_run = ['data_on',  # Event list in the source region
                 'data_off',  # Event list of the background region
                 'tRunSummary',  # Summary info on the run (exposure, and so on, see below)
                 'gMeanEffectiveArea',  # Effective area
                 'fAccZe_0',  # relative acceptance with respect to the on-axis area
                 'hMigration'  # Redistribution matrix (energy dispersion)
                 ]

# In the data_* trees we have:

_columns_in_data_tree = ['Time',  # it is the MJD of individual events
                         'Erec'  # reconstructed energy. *****Note that there are some events with negative
                                      # energy. Those are the events that we were unable to reconstruct energy.
                                      # In VERITAS when we calculate significance some times we use these events,
                                      # if we are not quoting the energy. Because failing the energy reconstruction
                                      # does not mean that the event is a bad event. However, if we quote an energy
                                      # band we do not use them.
                         'Xoff',  # this is the X offset from the detector centre in degrees.
                         'Yoff',  # this is the Y offset from the detector centre in degrees.
                         'theta2'  # X^2 + Y^2 (i.e., off-axis radius squared)
                         ]

class VERITASRun(object):

    def __init__(self, root_file, run_name):

        # Read the data from the ROOT file

        with open_ROOT_file(root_file) as f:

            # Read first the TTrees as pandas DataFrame

            self._data_on = tree_to_ndarray(f.Get(run_name+'/data_on'))  # type: np.ndarray
            self._data_off = tree_to_ndarray(f.Get(run_name+'/data_off'))  # type: np.ndarray
            self._tRunSummary = np.squeeze(tree_to_ndarray(f.Get(run_name+'/tRunSummary')))  # type: np.ndarray

            # Now read the histogram
            self._mc_energies, self._recon_energies, self._hMigration = th2_to_arrays(f.Get(run_name + "/hMigration"))

            # Read the TGraph
            tgraph = f.Get(run_name + "/gMeanEffectiveArea")
            self._gMeanEffectiveArea_energies, self._gMeanEffectiveArea_area = tgraph_to_arrays(tgraph)

        # Static members for genereting OGIP equivalents

        self._mission = "VERITAS"
        self._instrument = "VERITAS"

    def get_response(self, filename):

        rmf = RMF()

    def get_pha(self):

        # Get the exposure
        exposure = float(self._tRunSummary['DeadTimeFracOn'])

        # Bin the counts in energy
        counts, _ = np.histogram(self._data_on['Erec'], self._recon_energies)

        # Now get the rates
        rates = counts / exposure

        # Assume Poisson statistic
        rate_err = np.sqrt(counts) / exposure

        # Number of "channels"
        n_channels = self._recon_energies.shape[0]

        pha = POISSON_PHAII(instrument_name=self._instrument,
                    telescope_name=self._mission,
                    channel=,
                    rate=rates,
                    quality=np.zeros_like(rates, dtype=int),
                    grouping=np.ones(n_channels),
                    exposure=exposure,
                    backscale=None,
                    respfile=self._rsp_file,
                    ancrfile=None)

        return pha

class VERITASData(object):

    def __init__(self, veritas_root_data):

        # Open file

        f = ROOT.TFile(veritas_root_data)

        try:

            # Loop over the runs
            keys = get_list_of_keys(f)

            run_numbers = filter(lambda x:x.find("run") == 0, keys)

            for run in run_numbers:

                pass

        finally:

            f.close()

# This function get a list of

class VERITASLike(OGIPLike):

    def __init__(self, name, udara_style_root_file):

        super(VERITASLike, self).__init__(name, {})<|endoftext|>


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

import copy
import math
import unittest

from testing.types import (
    Color,
    File,
    Integers,
    Kind,
    NonCopyable,
    Optionals,
    Reserved,
    Runtime,
    SlowCompare,
    UnusedError,
    easy,
    hard,
    mixed,
    numerical,
)
from thrift.py3.common import Protocol
from thrift.py3.serializer import deserialize
from thrift.py3.types import Struct

class StructTests(unittest.TestCase):
    def test_isset_Struct(self) -> None:
        serialized = b'{"name":"/dev/null","type":8}'
        file = deserialize(File, serialized, protocol=Protocol.JSON)
        self.assertTrue(Struct.isset(file).type)
        self.assertFalse(Struct.isset(file).permissions)
        # required fields are always set
        self.assertTrue(Struct.isset(file).name)

        serialized = b'{"name":"/dev/null"}'
        file = deserialize(File, serialized, protocol=Protocol.JSON)
        self.assertEqual(file.type, Kind.REGULAR)
        self.assertFalse(Struct.isset(file).type)

    def test_isset_repr(self) -> None:
        serialized = b'{"name":"/dev/null","type":8}'
        file = deserialize(File, serialized, protocol=Protocol.JSON)
        self.assertEqual(
            "Struct.isset(<File>, name=True, permissions=False, type=True)",
            repr(Struct.isset(file)),
        )
        self.assertEqual(
            "Struct.isset(<File>, name=True, permissions=False, type=True)",
            str(Struct.isset(file)),
        )

    def test_isset_Union(self) -> None:
        i = Integers(large=2)
        with self.assertRaises(TypeError):
            Struct.isset(i).large

    def test_isset_Error(self) -> None:
        e = UnusedError()
        self.assertFalse(Struct.isset(e).message)

        e = UnusedError(message="ACK")
        self.assertTrue(Struct.isset(e).message)

    def test_copy(self) -> None:
        x = easy(val=1, an_int=Integers(small=300), name="foo", val_list=[1, 2, 3, 4])
        dif_list = copy.copy(x.val_list)
        self.assertEqual(x.val_list, dif_list)
        dif_int = copy.copy(x.an_int)
        self.assertEqual(x.an_int, dif_int)

    def test_hashability(self) -> None:
        hash(easy())

    def test_optional_struct_creation(self) -> None:
        with self.assertRaises(TypeError):
            easy(1, [1, 1], "test", Integers(tiny=1))  # type: ignore
        easy(val=1, an_int=Integers(small=500))
        with self.assertRaises(TypeError):
            easy(name=b"binary")  # type: ignore
        # Only Required Fields don't accept None
        easy(val=5, an_int=None)

    def test_required_fields_not_enforced(self) -> None:
        # None is not acceptable as a string
        hard(  # type: ignore
            val=1, val_list=[1, 2], name=None, an_int=Integers(small=1)
        )

        hard(val=1, val_list=[1, 2])  # type: ignore

    def test_call_replace(self) -> None:
        x = easy(val=1, an_int=Integers(small=300), name="foo")
        y = x(name="bar")
        self.assertNotEqual(x.name, y.name)
        z = y(an_int=None, val=4)
        self.assertNotEqual(x.an_int, z.an_int)
        self.assertNotEqual(x.val, z.val)
        self.assertIsNone(z.an_int.value)
        self.assertEqual(y.val, x.val)
        self.assertEqual(y.an_int, x.an_int)
        x = easy()
        self.assertIsNotNone(x.val)
        self.assertIsNotNone(x.val_list)
        self.assertIsNone(x.name)
        self.assertIsNotNone(x.an_int)

    def test_call_replace_container(self) -> None:
        x = Optionals(values=["a", "b", "c"])
        z = x(values=["b", "c"])
        self.assertEqual(z.values, ["b", "c"])
        y = z(values=None)
        self.assertIsNone(y.values)

    def test_runtime_checks(self) -> None:
        x = Runtime()
        with self.assertRaises(TypeError):
            x(bool_val=5)  # type: ignore

        with self.assertRaises(TypeError):
            Runtime(bool_val=5)  # type: ignore

        with self.assertRaises(TypeError):
            x(enum_val=2)  # type: ignore

        with self.assertRaises(TypeError):
            Runtime(enum_val=2)  # type: ignore

        with self.assertRaises(TypeError):
            x(int_list_val=["foo", "bar", "baz"])  # type: ignore

        with self.assertRaises(TypeError):
            Runtime(int_list_val=["foo", "bar", "baz"])  # type: ignore

    def test_reserved(self) -> None:
        x = Reserved(
            from_="hello",
            nonlocal_=3,
            ok="bye",
            is_cpdef=True,
            move="Qh4xe1",
            inst="foo",
            changes="bar",
        )
        self.assertEqual(x.from_, "hello")
        self.assertEqual(x.nonlocal_, 3)
        self.assertEqual(x.ok, "bye")
        self.assertEqual(x.is_cpdef, True)
        self.assertEqual(x.move, "Qh4xe1")
        self.assertEqual(x.inst, "foo")
        self.assertEqual(x.changes, "bar")

    def test_ordering(self) -> None:
        x = Runtime(bool_val=False, enum_val=Color.red, int_list_val=[64, 128])
        y = x(bool_val=True)
        self.assertLess(x, y)
        self.assertLessEqual(x, y)
        self.assertGreater(y, x)
        self.assertGreaterEqual(y, x)
        self.assertEquals([x, y], sorted([y, x]))

    def test_noncomparable(self) -> None:
        x = SlowCompare(field1="text", field2=10, field3=Color.red)
        y = x(field3=Color.blue)
        x2 = SlowCompare(field1="text", field2=10, field3=Color.red)

        self.assertEqual(x, x2)
        self.assertNotEqual(x, y)

    def test_noncopyable(self) -> None:
        x = NonCopyable(num=123)
        with self.assertRaises(TypeError):
            x(num=1234)
        with self.assertRaises(TypeError):
            copy.copy(x)
        with self.assertRaises(TypeError):
            copy.deepcopy(x)

class NumericalConversionsTests(unittest.TestCase):
    def test_overflow(self) -> None:
        with self.assertRaises(OverflowError):
            numerical(req_float_val=5, req_int_val=2 ** 63 - 1)

        with self.assertRaises(OverflowError):
            numerical(req_float_val=5, req_int_val=2, int_list=[5, 2 ** 32])

    def test_int_to_float(self) -> None:
        x = numerical(req_int_val=5, req_float_val=5, float_val=5, float_list=[1, 5, 6])
        x(req_float_val=10)
        x(float_val=10)
        x(float_list=[6, 7, 8])

    def test_int_to_i64(self) -> None:
        large = 2 ** 63 - 1
        numerical(req_int_val=5, req_float_val=5, i64_val=int(large))
        too_large = 2 ** 65 - 1
        with self.assertRaises(OverflowError):
            numerical(req_int_val=5, req_float_val=5, i64_val=int(too_large))

    def test_float_to_int_required_field(self) -> None:
        with self.assertRaises(TypeError):
            numerical(req_int_val=math.pi, req_float_val=math.pi)  # type: ignore

    def test_float_to_int_unqualified_field(self) -> None:
        with self.assertRaises(TypeError):
            numerical(  # type: ignore
                req_int_val=5,
                req_float_val=math.pi,
                int_val=math.pi,  # pyre-ignore[6]: intentionally for test
            )

    def test_float_to_int_list(self) -> None:
        with self.assertRaises(TypeError):
            numerical(
                req_int_val=5,
                req_float_val=math.pi,
                int_list=[math.pi, math.e],  # type: ignore
            )
<commit_msg>suppress errors in `thrift/lib/py3/test`<commit_after># Copyright (c) Facebook, Inc. and its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import copy
import math
import unittest

from testing.types import (
    Color,
    File,
    Integers,
    Kind,
    NonCopyable,
    Optionals,
    Reserved,
    Runtime,
    SlowCompare,
    UnusedError,
    easy,
    hard,
    mixed,
    numerical,
)
from thrift.py3.common import Protocol
from thrift.py3.serializer import deserialize
from thrift.py3.types import Struct

class StructTests(unittest.TestCase):
    def test_isset_Struct(self) -> None:
        serialized = b'{"name":"/dev/null","type":8}'
        file = deserialize(File, serialized, protocol=Protocol.JSON)
        self.assertTrue(Struct.isset(file).type)
        self.assertFalse(Struct.isset(file).permissions)
        # required fields are always set
        # pyre-fixme[16]: `__fbthrift_IsSet` has no attribute `name`.
        self.assertTrue(Struct.isset(file).name)

        serialized = b'{"name":"/dev/null"}'
        file = deserialize(File, serialized, protocol=Protocol.JSON)
        self.assertEqual(file.type, Kind.REGULAR)
        self.assertFalse(Struct.isset(file).type)

    def test_isset_repr(self) -> None:
        serialized = b'{"name":"/dev/null","type":8}'
        file = deserialize(File, serialized, protocol=Protocol.JSON)
        self.assertEqual(
            "Struct.isset(<File>, name=True, permissions=False, type=True)",
            repr(Struct.isset(file)),
        )
        self.assertEqual(
            "Struct.isset(<File>, name=True, permissions=False, type=True)",
            str(Struct.isset(file)),
        )

    def test_isset_Union(self) -> None:
        i = Integers(large=2)
        with self.assertRaises(TypeError):
            Struct.isset(i).large

    def test_isset_Error(self) -> None:
        e = UnusedError()
        self.assertFalse(Struct.isset(e).message)

        e = UnusedError(message="ACK")
        self.assertTrue(Struct.isset(e).message)

    def test_copy(self) -> None:
        x = easy(val=1, an_int=Integers(small=300), name="foo", val_list=[1, 2, 3, 4])
        dif_list = copy.copy(x.val_list)
        self.assertEqual(x.val_list, dif_list)
        dif_int = copy.copy(x.an_int)
        self.assertEqual(x.an_int, dif_int)

    def test_hashability(self) -> None:
        hash(easy())

    def test_optional_struct_creation(self) -> None:
        with self.assertRaises(TypeError):
            easy(1, [1, 1], "test", Integers(tiny=1))  # type: ignore
        easy(val=1, an_int=Integers(small=500))
        with self.assertRaises(TypeError):
            easy(name=b"binary")  # type: ignore
        # Only Required Fields don't accept None
        easy(val=5, an_int=None)

    def test_required_fields_not_enforced(self) -> None:
        # None is not acceptable as a string
        hard(  # type: ignore
            val=1, val_list=[1, 2], name=None, an_int=Integers(small=1)
        )

        hard(val=1, val_list=[1, 2])  # type: ignore

    def test_call_replace(self) -> None:
        x = easy(val=1, an_int=Integers(small=300), name="foo")
        y = x(name="bar")
        self.assertNotEqual(x.name, y.name)
        z = y(an_int=None, val=4)
        self.assertNotEqual(x.an_int, z.an_int)
        self.assertNotEqual(x.val, z.val)
        self.assertIsNone(z.an_int.value)
        self.assertEqual(y.val, x.val)
        self.assertEqual(y.an_int, x.an_int)
        x = easy()
        self.assertIsNotNone(x.val)
        self.assertIsNotNone(x.val_list)
        self.assertIsNone(x.name)
        self.assertIsNotNone(x.an_int)

    def test_call_replace_container(self) -> None:
        x = Optionals(values=["a", "b", "c"])
        z = x(values=["b", "c"])
        self.assertEqual(z.values, ["b", "c"])
        y = z(values=None)
        self.assertIsNone(y.values)

    def test_runtime_checks(self) -> None:
        x = Runtime()
        with self.assertRaises(TypeError):
            x(bool_val=5)  # type: ignore

        with self.assertRaises(TypeError):
            Runtime(bool_val=5)  # type: ignore

        with self.assertRaises(TypeError):
            x(enum_val=2)  # type: ignore

        with self.assertRaises(TypeError):
            Runtime(enum_val=2)  # type: ignore

        with self.assertRaises(TypeError):
            x(int_list_val=["foo", "bar", "baz"])  # type: ignore

        with self.assertRaises(TypeError):
            Runtime(int_list_val=["foo", "bar", "baz"])  # type: ignore

    def test_reserved(self) -> None:
        x = Reserved(
            from_="hello",
            nonlocal_=3,
            ok="bye",
            is_cpdef=True,
            move="Qh4xe1",
            inst="foo",
            changes="bar",
        )
        self.assertEqual(x.from_, "hello")
        self.assertEqual(x.nonlocal_, 3)
        self.assertEqual(x.ok, "bye")
        self.assertEqual(x.is_cpdef, True)
        self.assertEqual(x.move, "Qh4xe1")
        self.assertEqual(x.inst, "foo")
        self.assertEqual(x.changes, "bar")

    def test_ordering(self) -> None:
        x = Runtime(bool_val=False, enum_val=Color.red, int_list_val=[64, 128])
        y = x(bool_val=True)
        self.assertLess(x, y)
        self.assertLessEqual(x, y)
        self.assertGreater(y, x)
        self.assertGreaterEqual(y, x)
        self.assertEquals([x, y], sorted([y, x]))

    def test_noncomparable(self) -> None:
        x = SlowCompare(field1="text", field2=10, field3=Color.red)
        y = x(field3=Color.blue)
        x2 = SlowCompare(field1="text", field2=10, field3=Color.red)

        self.assertEqual(x, x2)
        self.assertNotEqual(x, y)

    def test_noncopyable(self) -> None:
        x = NonCopyable(num=123)
        with self.assertRaises(TypeError):
            x(num=1234)
        with self.assertRaises(TypeError):
            copy.copy(x)
        with self.assertRaises(TypeError):
            copy.deepcopy(x)

class NumericalConversionsTests(unittest.TestCase):
    def test_overflow(self) -> None:
        with self.assertRaises(OverflowError):
            numerical(req_float_val=5, req_int_val=2 ** 63 - 1)

        with self.assertRaises(OverflowError):
            numerical(req_float_val=5, req_int_val=2, int_list=[5, 2 ** 32])

    def test_int_to_float(self) -> None:
        x = numerical(req_int_val=5, req_float_val=5, float_val=5, float_list=[1, 5, 6])
        x(req_float_val=10)
        x(float_val=10)
        x(float_list=[6, 7, 8])

    def test_int_to_i64(self) -> None:
        large = 2 ** 63 - 1
        numerical(req_int_val=5, req_float_val=5, i64_val=int(large))
        too_large = 2 ** 65 - 1
        with self.assertRaises(OverflowError):
            numerical(req_int_val=5, req_float_val=5, i64_val=int(too_large))

    def test_float_to_int_required_field(self) -> None:
        with self.assertRaises(TypeError):
            numerical(req_int_val=math.pi, req_float_val=math.pi)  # type: ignore

    def test_float_to_int_unqualified_field(self) -> None:
        with self.assertRaises(TypeError):
            numerical(  # type: ignore
                req_int_val=5,
                req_float_val=math.pi,
                int_val=math.pi,  # pyre-ignore[6]: intentionally for test
            )

    def test_float_to_int_list(self) -> None:
        with self.assertRaises(TypeError):
            numerical(
                req_int_val=5,
                req_float_val=math.pi,
                int_list=[math.pi, math.e],  # type: ignore
            )
<|endoftext|>


<commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-

import logging, logging.handlers, json
from thumbor import __version__
import re, time

class ErrorHandler(object):
    def __init__(self, config):
        if not config.ERROR_FILE_LOGGER:
            raise RuntimeError(
                "If you set USE_CUSTOM_ERROR_HANDLING to True, and you are using thumbor_file_logger.logger, " +
                "then you must specify the file path to log to with the ERROR_FILE_LOGGER configuration."
            )
        if ( config.ERROR_FILE_NAME_USE_CONTEXT and not re.search('^(\w+\.)?\w+$', config.ERROR_FILE_NAME_USE_CONTEXT) ):
            raise RuntimeError(
                "ERROR_FILE_NAME_USE_CONTEXT config must reffer an attribute of context object and be form of ^(\w+.)?\w+$ : " + config.ERROR_FILE_NAME_USE_CONTEXT
            )
        self.file_name = config.ERROR_FILE_LOGGER
        if config.ERROR_FILE_NAME_USE_CONTEXT:
          self.use_context = config.ERROR_FILE_NAME_USE_CONTEXT
        else:
          self.use_context = None
        self.logger = None

    def handle_error(self, context, handler, exception):

        #create log file if not existing
        if not self.logger:
            if self.use_context:
                file = self.file_name % eval('context.' + self.use_context)
            else:
                file = self.file_name

            self.logger = logging.getLogger('error_handler')
            self.logger.setLevel(logging.ERROR)
            self.logger.addHandler(logging.handlers.WatchedFileHandler(file))

        req = handler.request
        extra = {
            'thumbor-version': __version__,
            'timestamp': time.time()
        }
        extra.update({
            'Headers': req.headers
        })
        cookies_header = extra.get('Headers', {}).get('Cookie', {})
        if isinstance(cookies_header, basestring):
            cookies = {}
            for cookie in cookies_header.split(';'):
                if not cookie:
                    continue
                values = cookie.strip().split('=')
                key, val = values[0], "".join(values[1:])
                cookies[key] = val
        else:
            cookies = cookies_header
        extra['Headers']['Cookie'] = cookies

        data = {
            'Http': {
                'url': req.full_url(),
                'method': req.method,
                'data': req.arguments,
                'body': req.body,
                'query_string': req.query
            },
            'interfaces.User': {
                'ip': req.remote_ip,
            },
            'exception': str(exception),
            'extra': extra
        }

        self.logger.error(json.dumps(data))
<commit_msg>file error handler with context<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-

import logging, logging.handlers, json
from thumbor import __version__
import re, time

class ErrorHandler(object):
    def __init__(self, config):
        if not config.ERROR_FILE_LOGGER:
            raise RuntimeError(
                "If you set USE_CUSTOM_ERROR_HANDLING to True, and you are using thumbor_file_logger.logger, " +
                "then you must specify the file path to log to with the ERROR_FILE_LOGGER configuration."
            )
        if ( config.ERROR_FILE_NAME_USE_CONTEXT and not re.search('^(\w+\.)?\w+$', config.ERROR_FILE_NAME_USE_CONTEXT) ):
            raise RuntimeError(
                "ERROR_FILE_NAME_USE_CONTEXT config must reffer an attribute of context object and be form of ^(\w+.)?\w+$ : " + config.ERROR_FILE_NAME_USE_CONTEXT
            )
        self.file_name = config.ERROR_FILE_LOGGER
        if config.ERROR_FILE_NAME_USE_CONTEXT:
          self.use_context = config.ERROR_FILE_NAME_USE_CONTEXT
        else:
          self.use_context = None
        self.logger = None

    def handle_error(self, context, handler, exception):

        #create log file if not existing
        if not self.logger:
            if self.use_context:
                if '.' in self.use_context:
                    parts = self.use_context.split('.')
                    obj = getattr(context, parts[0], None)
                    obj = reduce(getattr, parts[1:], obj)
                else:
                    obj = getattr(context, self.use_context, None)
                file = self.file_name % obj
            else:
                file = self.file_name

            self.logger = logging.getLogger('error_handler')
            self.logger.setLevel(logging.ERROR)
            self.logger.addHandler(logging.handlers.WatchedFileHandler(file))

        req = handler.request
        extra = {
            'thumbor-version': __version__,
            'timestamp': time.time()
        }
        extra.update({
            'Headers': req.headers
        })
        cookies_header = extra.get('Headers', {}).get('Cookie', {})
        if isinstance(cookies_header, basestring):
            cookies = {}
            for cookie in cookies_header.split(';'):
                if not cookie:
                    continue
                values = cookie.strip().split('=')
                key, val = values[0], "".join(values[1:])
                cookies[key] = val
        else:
            cookies = cookies_header
        extra['Headers']['Cookie'] = cookies

        data = {
            'Http': {
                'url': req.full_url(),
                'method': req.method,
                'data': req.arguments,
                'body': req.body,
                'query_string': req.query
            },
            'interfaces.User': {
                'ip': req.remote_ip,
            },
            'exception': str(exception),
            'extra': extra
        }

        self.logger.error(json.dumps(data))
<|endoftext|>


<commit_before># Copyright (C) 2015 VA Linux Systems Japan K.K.
# Copyright (C) 2015 YAMAMOTO Takashi <yamamoto at valinux co jp>
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import functools

from oslo_log import log as logging
import ryu.app.ofctl.api  # noqa
from ryu.base import app_manager
from ryu.lib import hub
from ryu.ofproto import ofproto_v1_3

from neutron._i18n import _LE
from neutron.plugins.ml2.drivers.openvswitch.agent.openflow.native \
    import br_int
from neutron.plugins.ml2.drivers.openvswitch.agent.openflow.native \
    import br_phys
from neutron.plugins.ml2.drivers.openvswitch.agent.openflow.native \
    import br_tun
from neutron.plugins.ml2.drivers.openvswitch.agent \
    import ovs_neutron_agent as ovs_agent

LOG = logging.getLogger(__name__)

def agent_main_wrapper(bridge_classes):
    try:
        ovs_agent.main(bridge_classes)
    except Exception:
        LOG.exception(_LE("Agent main thread died of an exception"))
    finally:
        # The following call terminates Ryu's AppManager.run_apps(),
        # which is needed for clean shutdown of an agent process.
        # The close() call must be called in another thread, otherwise
        # it suicides and ends prematurely.
        hub.spawn(app_manager.AppManager.get_instance().close)

class OVSNeutronAgentRyuApp(app_manager.RyuApp):
    OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]

    def start(self):
        # Start Ryu event loop thread
        super(OVSNeutronAgentRyuApp, self).start()

        def _make_br_cls(br_cls):
            return functools.partial(br_cls, ryu_app=self)

        # Start agent main loop thread
        bridge_classes = {
            'br_int': _make_br_cls(br_int.OVSIntegrationBridge),
            'br_phys': _make_br_cls(br_phys.OVSPhysicalBridge),
            'br_tun': _make_br_cls(br_tun.OVSTunnelBridge),
        }
        return hub.spawn(agent_main_wrapper, bridge_classes)
<commit_msg>ovs: bubble up failures into main thread in native ofctl mode<commit_after># Copyright (C) 2015 VA Linux Systems Japan K.K.
# Copyright (C) 2015 YAMAMOTO Takashi <yamamoto at valinux co jp>
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import functools

from oslo_log import log as logging
from oslo_utils import excutils
import ryu.app.ofctl.api  # noqa
from ryu.base import app_manager
from ryu.lib import hub
from ryu.ofproto import ofproto_v1_3

from neutron._i18n import _LE
from neutron.plugins.ml2.drivers.openvswitch.agent.openflow.native \
    import br_int
from neutron.plugins.ml2.drivers.openvswitch.agent.openflow.native \
    import br_phys
from neutron.plugins.ml2.drivers.openvswitch.agent.openflow.native \
    import br_tun
from neutron.plugins.ml2.drivers.openvswitch.agent \
    import ovs_neutron_agent as ovs_agent

LOG = logging.getLogger(__name__)

def agent_main_wrapper(bridge_classes):
    try:
        ovs_agent.main(bridge_classes)
    except Exception:
        with excutils.save_and_reraise_exception():
            LOG.exception(_LE("Agent main thread died of an exception"))
    finally:
        # The following call terminates Ryu's AppManager.run_apps(),
        # which is needed for clean shutdown of an agent process.
        # The close() call must be called in another thread, otherwise
        # it suicides and ends prematurely.
        hub.spawn(app_manager.AppManager.get_instance().close)

class OVSNeutronAgentRyuApp(app_manager.RyuApp):
    OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]

    def start(self):
        # Start Ryu event loop thread
        super(OVSNeutronAgentRyuApp, self).start()

        def _make_br_cls(br_cls):
            return functools.partial(br_cls, ryu_app=self)

        # Start agent main loop thread
        bridge_classes = {
            'br_int': _make_br_cls(br_int.OVSIntegrationBridge),
            'br_phys': _make_br_cls(br_phys.OVSPhysicalBridge),
            'br_tun': _make_br_cls(br_tun.OVSTunnelBridge),
        }
        return hub.spawn(agent_main_wrapper, bridge_classes, raise_error=True)
<|endoftext|>


<commit_before>"""Module for database operations on matches tables."""
from tof_server import mysql

MATCH_STATE_NEW = 0
MATCH_STATE_IN_PROGRESS = 1
MATCH_STATE_ENDED = 2
MATCH_STATE_FORFEIT = 3

MATCH_SIDE_BLUE = 0
MATCH_SIDE_RED = 1

MATCH_PLAYER_STATE_ACTIVE = 0
MATCH_PLAYER_STATE_INACTIVE = 1
MATCH_PLAYER_STATE_WIN = 2
MATCH_PLAYER_STATE_LOSS = 3
MATCH_PLAYER_STATE_DISMISSED = 4

MATCH_CODE_ERASED = 'nope'

def get_player_visible_matches(player_id):
    """Method for getting non-dismissed matches."""
    cursor = mysql.connection.cursor()
    sql = "SELECT match_id, side, status FROM match_players WHERE player_id = %s"

    cursor.execute(sql, (player_id,))
    matches = cursor.fetchall()
    cursor.close()

    return matches

def create_new_match(map_id, join_code):
    """Method for creating new match."""
    cursor = mysql.connection.cursor()
    sql = """INSERT INTO matches
            (join_code, map_id, status)
            VALUES (%s, %s, %s)"""

    cursor.execute(sql, (join_code, map_id, MATCH_STATE_NEW))

    last_id_sql = "SELECT LAST_INSERT_ID()"
    cursor.execute(last_id_sql)

    last_id = cursor.fetchone()

    mysql.connection.commit()
    cursor.close()

    return last_id[0]

def create_empty_match_state(match_id):
    """Method for creating empty match state."""
    cursor = mysql.connection.cursor()
    sql = """INSERT INTO match_states
            (match_id, json)
            VALUES (%s, %s)"""

    initial_json = "{}"

    cursor.execute(sql, (match_id, initial_json))

    mysql.connection.commit()
    cursor.close()

def join_player_to_match(match_id, player_id, side):
    """Method for joining a player to a match."""
    cursor = mysql.connection.cursor()
    sql = """INSERT INTO match_players
            (match_id, player_id, side, status)
            VALUES (%s, %s, %s, %s)"""
    cursor.execute(sql, (match_id, player_id, side, side))

    mysql.connection.commit()
    cursor.close()

def get_match_info(match_id):
    """Method for getting match details for listing."""
    cursor = mysql.connection.cursor()
    sql = "SELECT join_code, status, map_id FROM matches WHERE id = %s"

    cursor.execute(sql, (match_id,))
    match_data = cursor.fetchone()
    cursor.close()

    return match_data

def get_match_info_by_code(join_code):
    """Method for getting match details for join query."""
    cursor = mysql.connection.cursor()
    sql = "SELECT id, status, map_id FROM matches WHERE join_code = %s"

    cursor.execute(sql, (join_code,))
    match_data = cursor.fetchone()
    cursor.close()

    return match_data

def get_players_for_match(match_id):
    """Method for getting list of players in a match."""
    cursor = mysql.connection.cursor()
    sql = "SELECT player_id, side, status FROM match_players WHERE match_id = %s"

    cursor.execute(sql, (match_id,))
    players = cursor.fetchall()
    cursor.close()

    return players

def get_player_in_match(player_id, match_id):
    """Get information about player in a match."""
    cursor = mysql.connection.cursor()
    sql = "SELECT side, status FROM match_players WHERE match_id = %s AND player_id = %s"

    cursor.execute(sql, (match_id, player_id))
    player = cursor.fetchone()
    cursor.close()

    return player

def get_match_state(match_id):
    """Get state of a match."""
    cursor = mysql.connection.cursor()
    sql = "SELECT json FROM match_states WHERE match_id = %s"

    cursor.execute(sql, (match_id, ))
    state = cursor.fetchone()
    cursor.close()

    if not state:
        return "{}"

    return state[0]

def update_match_state(match_id, json_data):
    """Method for updating match state."""
    cursor = mysql.connection.cursor()
    sql = "UPDATE match_states SET json = %s WHERE match_id = %s"
    cursor.execute(sql, (json_data, match_id))
    mysql.connection.commit()
    cursor.close()

def update_match_status(match_id, status):
    """Method for updating match status."""
    cursor = mysql.connection.cursor()
    sql = "UPDATE matches SET status = %s WHERE id = %s"
    cursor.execute(sql, (status, match_id))
    mysql.connection.commit()
    cursor.close()

def update_player_status(match_id, player_id, status):
    """Method for updating player status."""
    cursor = mysql.connection.cursor()
    sql = "UPDATE match_players SET status = %s WHERE match_id = %s AND player_id = %s"
    cursor.execute(sql, (status, match_id, player_id))
    mysql.connection.commit()
    cursor.close()

def update_other_players_status(match_id, player_id, status):
    """Method for updating player status."""
    cursor = mysql.connection.cursor()
    sql = "UPDATE match_players SET status = %s WHERE match_id = %s AND player_id <> %s"
    cursor.execute(sql, (status, match_id, player_id))
    mysql.connection.commit()
    cursor.close()
<commit_msg>Fixed a bug showing abandoned matches on list<commit_after>"""Module for database operations on matches tables."""
from tof_server import mysql

MATCH_STATE_NEW = 0
MATCH_STATE_IN_PROGRESS = 1
MATCH_STATE_ENDED = 2
MATCH_STATE_FORFEIT = 3

MATCH_SIDE_BLUE = 0
MATCH_SIDE_RED = 1

MATCH_PLAYER_STATE_ACTIVE = 0
MATCH_PLAYER_STATE_INACTIVE = 1
MATCH_PLAYER_STATE_WIN = 2
MATCH_PLAYER_STATE_LOSS = 3
MATCH_PLAYER_STATE_DISMISSED = 4

MATCH_CODE_ERASED = 'nope'

def get_player_visible_matches(player_id):
    """Method for getting non-dismissed matches."""
    cursor = mysql.connection.cursor()
    sql = "SELECT match_id, side, status FROM match_players WHERE player_id = %s AND status <> %s"

    cursor.execute(sql, (player_id, MATCH_PLAYER_STATE_DISMISSED))
    matches = cursor.fetchall()
    cursor.close()

    return matches

def create_new_match(map_id, join_code):
    """Method for creating new match."""
    cursor = mysql.connection.cursor()
    sql = """INSERT INTO matches
            (join_code, map_id, status)
            VALUES (%s, %s, %s)"""

    cursor.execute(sql, (join_code, map_id, MATCH_STATE_NEW))

    last_id_sql = "SELECT LAST_INSERT_ID()"
    cursor.execute(last_id_sql)

    last_id = cursor.fetchone()

    mysql.connection.commit()
    cursor.close()

    return last_id[0]

def create_empty_match_state(match_id):
    """Method for creating empty match state."""
    cursor = mysql.connection.cursor()
    sql = """INSERT INTO match_states
            (match_id, json)
            VALUES (%s, %s)"""

    initial_json = "{}"

    cursor.execute(sql, (match_id, initial_json))

    mysql.connection.commit()
    cursor.close()

def join_player_to_match(match_id, player_id, side):
    """Method for joining a player to a match."""
    cursor = mysql.connection.cursor()
    sql = """INSERT INTO match_players
            (match_id, player_id, side, status)
            VALUES (%s, %s, %s, %s)"""
    cursor.execute(sql, (match_id, player_id, side, side))

    mysql.connection.commit()
    cursor.close()

def get_match_info(match_id):
    """Method for getting match details for listing."""
    cursor = mysql.connection.cursor()
    sql = "SELECT join_code, status, map_id FROM matches WHERE id = %s"

    cursor.execute(sql, (match_id,))
    match_data = cursor.fetchone()
    cursor.close()

    return match_data

def get_match_info_by_code(join_code):
    """Method for getting match details for join query."""
    cursor = mysql.connection.cursor()
    sql = "SELECT id, status, map_id FROM matches WHERE join_code = %s"

    cursor.execute(sql, (join_code,))
    match_data = cursor.fetchone()
    cursor.close()

    return match_data

def get_players_for_match(match_id):
    """Method for getting list of players in a match."""
    cursor = mysql.connection.cursor()
    sql = "SELECT player_id, side, status FROM match_players WHERE match_id = %s"

    cursor.execute(sql, (match_id,))
    players = cursor.fetchall()
    cursor.close()

    return players

def get_player_in_match(player_id, match_id):
    """Get information about player in a match."""
    cursor = mysql.connection.cursor()
    sql = "SELECT side, status FROM match_players WHERE match_id = %s AND player_id = %s"

    cursor.execute(sql, (match_id, player_id))
    player = cursor.fetchone()
    cursor.close()

    return player

def get_match_state(match_id):
    """Get state of a match."""
    cursor = mysql.connection.cursor()
    sql = "SELECT json FROM match_states WHERE match_id = %s"

    cursor.execute(sql, (match_id, ))
    state = cursor.fetchone()
    cursor.close()

    if not state:
        return "{}"

    return state[0]

def update_match_state(match_id, json_data):
    """Method for updating match state."""
    cursor = mysql.connection.cursor()
    sql = "UPDATE match_states SET json = %s WHERE match_id = %s"
    cursor.execute(sql, (json_data, match_id))
    mysql.connection.commit()
    cursor.close()

def update_match_status(match_id, status):
    """Method for updating match status."""
    cursor = mysql.connection.cursor()
    sql = "UPDATE matches SET status = %s WHERE id = %s"
    cursor.execute(sql, (status, match_id))
    mysql.connection.commit()
    cursor.close()

def update_player_status(match_id, player_id, status):
    """Method for updating player status."""
    cursor = mysql.connection.cursor()
    sql = "UPDATE match_players SET status = %s WHERE match_id = %s AND player_id = %s"
    cursor.execute(sql, (status, match_id, player_id))
    mysql.connection.commit()
    cursor.close()

def update_other_players_status(match_id, player_id, status):
    """Method for updating player status."""
    cursor = mysql.connection.cursor()
    sql = "UPDATE match_players SET status = %s WHERE match_id = %s AND player_id <> %s"
    cursor.execute(sql, (status, match_id, player_id))
    mysql.connection.commit()
    cursor.close()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
# Copyright (c) 2008-2012 the MansOS team. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#  * Redistributions of source code must retain the above copyright notice,
#    this list of  conditions and the following disclaimer.
#  * Redistributions in binary form must reproduce the above copyright
#   notice, this list of conditions and the following disclaimer in the
#   documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

import wx

class UploadModule(wx.Panel):
    def __init__(self, parent, API):
        super(UploadModule, self).__init__(parent = parent)

        self.API = API
        self.editorManager = self.API.tabManager.GetCurrentPage()
        self.filename = self.editorManager.fileName
        self.API.motelistCallbacks.append(self.updateMotelist)
        # Just a shorter name
        self.tr = self.API.translater.translate
        self.tmpDir = self.API.path + '/temp/'
        self.haveMote = False
        self.platform = "telosb"
        self.moteOrder = list()
        # this is path from /mansos/tools/IDE
        self.pathToMansos = self.API.path + "/../.."
        self.motes = []

        self.main = wx.BoxSizer(wx.VERTICAL)
        self.controls = wx.GridBagSizer(10, 10)

        self.source = wx.ComboBox(self, choices = ["USB", "Shell"])
        self.source.SetValue("USB")
        self.platforms = wx.ComboBox(self, choices = self.API.getPlatforms())
        self.platforms.SetValue(self.API.getActivePlatform())
        if self.API.platformOnly != None:
            self.platforms.Enable(False)
        self.compile = wx.Button(self, label = self.tr("Compile"))
        self.upload = wx.Button(self, label = self.tr("Upload"))
        self.refresh = wx.Button(self, label = self.tr("Refresh"))

        self.controls.Add(self.compile, (0, 0), flag = wx.EXPAND | wx.ALL)
        self.controls.Add(self.platforms, (0, 1), flag = wx.EXPAND | wx.ALL)
        self.controls.Add(self.upload, (0, 2), span = (2, 2),
                          flag = wx.EXPAND | wx.ALL)

        self.controls.Add(self.source, (1, 1), flag = wx.EXPAND | wx.ALL)
        self.controls.Add(self.refresh, (1, 0), flag = wx.EXPAND | wx.ALL)

        self.list = wx.CheckListBox(self, wx.ID_ANY, style = wx.MULTIPLE)

        self.main.Add(self.controls, 0, wx.EXPAND | wx.ALL, 3);
        self.main.Add(self.list, 0, wx.EXPAND | wx.ALL, 3);

        self.Bind(wx.EVT_BUTTON, self.API.doCompile, self.compile)
        self.Bind(wx.EVT_BUTTON, self.API.doUpload, self.upload)
        self.Bind(wx.EVT_BUTTON, self.populateMotelist, self.refresh)
        self.Bind(wx.EVT_COMBOBOX, self.populateMotelist, self.source)
        self.Bind(wx.EVT_COMBOBOX, self.API.changePlatform, self.platforms)
        self.Bind(wx.EVT_CHECKLISTBOX, self.modifyTargets, self.list)

        self.SetSizerAndFit(self.main)
        self.SetAutoLayout(1)
        self.Show()

        self.updateMotelist()

    def __del__(self):
        self.API.motelistCallbacks.remove(self.updateMotelist)

    def populateMotelist(self, event = None):
        self.list.Clear()
        self.list.Insert(self.tr("Searching devices") + "...", 0)
        self.list.Disable()
        self.API.populateMotelist()

    def updateMotelist(self):
        motelist = self.API.motelist
        self.list.Clear()

        if len(motelist) == 0:
            self.list.Insert(self.tr("No devices found!"), 0)
        else:
            for i in range(len(motelist)):
                if len(motelist[i] > 2):
                    self.list.Insert(motelist[i][0] + "(" + motelist[i][2] +
                                 ") @ " + motelist[i][1], i)
                else:
                    self.API.printInfo("Wrong motelist format:", str(motelist[0]))
            self.list.Enable()

    def modifyTargets(self, event):
        self.API.targets = list(self.list.GetChecked())

<commit_msg>MansOS IDE, fix syntax error from last commit.<commit_after># -*- coding: utf-8 -*-
#
# Copyright (c) 2008-2012 the MansOS team. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#  * Redistributions of source code must retain the above copyright notice,
#    this list of  conditions and the following disclaimer.
#  * Redistributions in binary form must reproduce the above copyright
#   notice, this list of conditions and the following disclaimer in the
#   documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

import wx

class UploadModule(wx.Panel):
    def __init__(self, parent, API):
        super(UploadModule, self).__init__(parent = parent)

        self.API = API
        self.editorManager = self.API.tabManager.GetCurrentPage()
        self.filename = self.editorManager.fileName
        self.API.motelistCallbacks.append(self.updateMotelist)
        # Just a shorter name
        self.tr = self.API.translater.translate
        self.tmpDir = self.API.path + '/temp/'
        self.haveMote = False
        self.platform = "telosb"
        self.moteOrder = list()
        # this is path from /mansos/tools/IDE
        self.pathToMansos = self.API.path + "/../.."
        self.motes = []

        self.main = wx.BoxSizer(wx.VERTICAL)
        self.controls = wx.GridBagSizer(10, 10)

        self.source = wx.ComboBox(self, choices = ["USB", "Shell"])
        self.source.SetValue("USB")
        self.platforms = wx.ComboBox(self, choices = self.API.getPlatforms())
        self.platforms.SetValue(self.API.getActivePlatform())
        if self.API.platformOnly != None:
            self.platforms.Enable(False)
        self.compile = wx.Button(self, label = self.tr("Compile"))
        self.upload = wx.Button(self, label = self.tr("Upload"))
        self.refresh = wx.Button(self, label = self.tr("Refresh"))

        self.controls.Add(self.compile, (0, 0), flag = wx.EXPAND | wx.ALL)
        self.controls.Add(self.platforms, (0, 1), flag = wx.EXPAND | wx.ALL)
        self.controls.Add(self.upload, (0, 2), span = (2, 2),
                          flag = wx.EXPAND | wx.ALL)

        self.controls.Add(self.source, (1, 1), flag = wx.EXPAND | wx.ALL)
        self.controls.Add(self.refresh, (1, 0), flag = wx.EXPAND | wx.ALL)

        self.list = wx.CheckListBox(self, wx.ID_ANY, style = wx.MULTIPLE)

        self.main.Add(self.controls, 0, wx.EXPAND | wx.ALL, 3);
        self.main.Add(self.list, 0, wx.EXPAND | wx.ALL, 3);

        self.Bind(wx.EVT_BUTTON, self.API.doCompile, self.compile)
        self.Bind(wx.EVT_BUTTON, self.API.doUpload, self.upload)
        self.Bind(wx.EVT_BUTTON, self.populateMotelist, self.refresh)
        self.Bind(wx.EVT_COMBOBOX, self.populateMotelist, self.source)
        self.Bind(wx.EVT_COMBOBOX, self.API.changePlatform, self.platforms)
        self.Bind(wx.EVT_CHECKLISTBOX, self.modifyTargets, self.list)

        self.SetSizerAndFit(self.main)
        self.SetAutoLayout(1)
        self.Show()

        self.updateMotelist()

    def __del__(self):
        self.API.motelistCallbacks.remove(self.updateMotelist)

    def populateMotelist(self, event = None):
        self.list.Clear()
        self.list.Insert(self.tr("Searching devices") + "...", 0)
        self.list.Disable()
        self.API.populateMotelist()

    def updateMotelist(self):
        motelist = self.API.motelist
        self.list.Clear()

        if len(motelist) == 0:
            self.list.Insert(self.tr("No devices found!"), 0)
        else:
            for i in range(len(motelist)):
                if len(motelist[i]) > 2:
                    self.list.Insert(motelist[i][0] + "(" + motelist[i][2] +
                                 ") @ " + motelist[i][1], i)
                else:
                    self.API.printInfo("Wrong motelist format:", str(motelist[0]))
            self.list.Enable()

    def modifyTargets(self, event):
        self.API.targets = list(self.list.GetChecked())

<|endoftext|>


<commit_before># Copyright 2016 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Rules for downloading files and archives over HTTP.

### Setup

To use these rules, load them in your `WORKSPACE` file as follows:

```python
load(
    "@bazel_tools//tools/build_defs/repo:http.bzl",
    "http_archive",
    "http_file",
    "http_jar",
)
```

These rules are improved versions of the native http rules and will eventually
replace the native rules.
"""

load("@bazel_tools//tools/build_defs/repo:utils.bzl", "patch", "workspace_and_buildfile")

def _http_archive_impl(ctx):
    """Implementation of the http_archive rule."""
    if not ctx.attr.url and not ctx.attr.urls:
        ctx.fail("At least one of url and urls must be provided")
    if ctx.attr.build_file and ctx.attr.build_file_content:
        ctx.fail("Only one of build_file and build_file_content can be provided.")

    all_urls = []
    if ctx.attr.urls:
        all_urls = ctx.attr.urls
    if ctx.attr.url:
        all_urls = [ctx.attr.url] + all_urls

    ctx.download_and_extract(
        all_urls,
        "",
        ctx.attr.sha256,
        ctx.attr.type,
        ctx.attr.strip_prefix,
    )
    patch(ctx)
    workspace_and_buildfile(ctx)

_HTTP_FILE_BUILD = """
package(default_visibility = ["//visibility:public"])

filegroup(
    name = "file",
    srcs = ["downloaded"],
)
"""

def _http_file_impl(ctx):
    """Implementation of the http_file rule."""
    ctx.download(
        ctx.attr.urls,
        "file/downloaded",
        ctx.attr.sha256,
        ctx.attr.executable,
    )
    ctx.file("WORKSPACE", "workspace(name = \"{name}\")".format(name = ctx.name))
    ctx.file("file/BUILD", _HTTP_FILE_BUILD)

_HTTP_JAR_BUILD = """
package(default_visibility = ["//visibility:public"])

java_import(
  name = 'jar',
  jars = ['downloaded.jar'],
  visibility = ['//visibility:public'],
)

filegroup(
  name = 'file',
  srcs = ['downloaded.jar'],
  visibility = ['//visibility:public'],
)

"""

def _http_jar_impl(ctx):
    """Implementation of the http_jar rule."""
    all_urls = []
    if ctx.attr.urls:
        all_urls = ctx.attr.urls
    if ctx.attr.url:
        all_urls = [ctx.attr.url] + all_urls
    ctx.download(all_urls, "jar/downloaded.jar", ctx.attr.sha256)
    ctx.file("WORKSPACE", "workspace(name = \"{name}\")".format(name = ctx.name))
    ctx.file("jar/BUILD", _HTTP_JAR_BUILD)

_http_archive_attrs = {
    "url": attr.string(),
    "urls": attr.string_list(),
    "sha256": attr.string(),
    "strip_prefix": attr.string(),
    "type": attr.string(),
    "build_file": attr.label(allow_single_file = True),
    "build_file_content": attr.string(),
    "patches": attr.label_list(default = []),
    "patch_tool": attr.string(default = "patch"),
    "patch_args": attr.string_list(default = ["-p0"]),
    "patch_cmds": attr.string_list(default = []),
    "workspace_file": attr.label(allow_single_file = True),
    "workspace_file_content": attr.string(),
}

http_archive = repository_rule(
    implementation = _http_archive_impl,
    attrs = _http_archive_attrs,
)
"""Downloads a Bazel repository as a compressed archive file, decompresses it,
and makes its targets available for binding.

It supports the following file extensions: `"zip"`, `"jar"`, `"war"`, `"tar"`,
`"tar.gz"`, `"tgz"`, `"tar.xz"`, and `tar.bz2`.

Examples:
  Suppose the current repository contains the source code for a chat program,
  rooted at the directory `~/chat-app`. It needs to depend on an SSL library
  which is available from http://example.com/openssl.zip. This `.zip` file
  contains the following directory structure:

  ```
  WORKSPACE
  src/
    openssl.cc
    openssl.h
  ```

  In the local repository, the user creates a `openssl.BUILD` file which
  contains the following target definition:

  ```python
  cc_library(
      name = "openssl-lib",
      srcs = ["src/openssl.cc"],
      hdrs = ["src/openssl.h"],
  )
  ```

  Targets in the `~/chat-app` repository can depend on this target if the
  following lines are added to `~/chat-app/WORKSPACE`:

  ```python
  http_archive(
      name = "my_ssl",
      urls = ["http://example.com/openssl.zip"],
      sha256 = "03a58ac630e59778f328af4bcc4acb4f80208ed4",
      build_file = "//:openssl.BUILD",
  )
  ```

  Then targets would specify `@my_ssl//:openssl-lib` as a dependency.

Args:
  name: A unique name for this rule.
  build_file: The file to use as the `BUILD` file for this repository.

    Either `build_file` or `build_file_content` can be specified.

    This attribute is a label relative to the main workspace. The file does not
    need to be named `BUILD`, but can be (something like `BUILD.new-repo-name`
    may work well for distinguishing it from the repository's actual `BUILD`
    files.

  build_file_content: The content for the BUILD file for this repository.

    Either `build_file` or `build_file_content` can be specified.
  workspace_file: The file to use as the `WORKSPACE` file for this repository.

    Either `workspace_file` or `workspace_file_content` can be specified, or
    neither, but not both.
  workspace_file_content: The content for the WORKSPACE file for this repository.

    Either `workspace_file` or `workspace_file_content` can be specified, or
    neither, but not both.
  sha256: The expected SHA-256 of the file downloaded.

    This must match the SHA-256 of the file downloaded. _It is a security risk
    to omit the SHA-256 as remote files can change._ At best omitting this
    field will make your build non-hermetic. It is optional to make development
    easier but should be set before shipping.
  strip_prefix: A directory prefix to strip from the extracted files.

    Many archives contain a top-level directory that contains all of the useful
    files in archive. Instead of needing to specify this prefix over and over
    in the `build_file`, this field can be used to strip it from all of the
    extracted files.

    For example, suppose you are using `foo-lib-latest.zip`, which contains the
    directory `foo-lib-1.2.3/` under which there is a `WORKSPACE` file and are
    `src/`, `lib/`, and `test/` directories that contain the actual code you
    wish to build. Specify `strip_prefix = "foo-lib-1.2.3"` to use the
    `foo-lib-1.2.3` directory as your top-level directory.

    Note that if there are files outside of this directory, they will be
    discarded and inaccessible (e.g., a top-level license file). This includes
    files/directories that start with the prefix but are not in the directory
    (e.g., `foo-lib-1.2.3.release-notes`). If the specified prefix does not
    match a directory in the archive, Bazel will return an error.
  type: The archive type of the downloaded file.

    By default, the archive type is determined from the file extension of the
    URL. If the file has no extension, you can explicitly specify one of the
    following: `"zip"`, `"jar"`, `"war"`, `"tar"`, `"tar.gz"`, `"tgz"`,
    `"tar.xz"`, or `tar.bz2`.
  url: A URL to a file that will be made available to Bazel.

    This must be an file, http or https URL. Redirections are followed.
    Authentication is not supported.

    This parameter is to simplify the transition from the native http_archive
    rule. More flexibility can be achieved by the urls parameter that allows
    to specify alternative URLs to fetch from.
  urls: A list of URLs to a file that will be made available to Bazel.

    Each entry must be an file, http or https URL. Redirections are followed.
    Authentication is not supported.
  patches: A list of files that are to be applied as patches after extracting
    the archive.
  patch_tool: the patch(1) utility to use.
  patch_args: arguments given to the patch tool, defaults to ["-p0"]
  patch_cmds: sequence of commands to be applied after patches are applied.
"""

http_file = repository_rule(
    implementation = _http_file_impl,
    attrs = {
        "executable": attr.bool(),
        "sha256": attr.string(),
        "urls": attr.string_list(mandatory = True),
    },
)
"""Downloads a file from a URL and makes it available to be used as a file
group.

Examples:
  Suppose you need to have a debian package for your custom rules. This package
  is available from http://example.com/package.deb. Then you can add to your
  WORKSPACE file:

  ```python
  http_file(
      name = "my_deb",
      urls = ["http://example.com/package.deb"],
      sha256 = "03a58ac630e59778f328af4bcc4acb4f80208ed4",
  )
  ```

  Targets would specify `@my_deb//file` as a dependency to depend on this file.

Args:
  name: A unique name for this rule.
  executable: If the downloaded file should be made executable. Defaults to
    False.
  sha256: The expected SHA-256 of the file downloaded.

    This must match the SHA-256 of the file downloaded. _It is a security risk
    to omit the SHA-256 as remote files can change._ At best omitting this
    field will make your build non-hermetic. It is optional to make development
    easier but should be set before shipping.
  urls: A list of URLs to a file that will be made available to Bazel.

    Each entry must be an file, http or https URL. Redirections are followed.
    Authentication is not supported.
"""

http_jar = repository_rule(
    implementation = _http_jar_impl,
    attrs = {
        "sha256": attr.string(),
        "url": attr.string(),
        "urls": attr.string_list(),
    },
)
"""Downloads a jar from a URL and makes it available as java_import

Downloaded files must have a .jar extension.

Examples:
  Suppose the current repository contains the source code for a chat program, rooted at the
  directory `~/chat-app`. It needs to depend on an SSL library which is available from
  `http://example.com/openssl-0.2.jar`.

  Targets in the `~/chat-app` repository can depend on this target if the following lines are
  added to `~/chat-app/WORKSPACE`:

  ```python
  http_jar(
      name = "my_ssl",
      url = "http://example.com/openssl-0.2.jar",
      sha256 = "03a58ac630e59778f328af4bcc4acb4f80208ed4",
  )
  ```

  Targets would specify <code>@my_ssl//jar</code> as a dependency to depend on this jar.

  You may also reference files on the current system (localhost) by using "file:///path/to/file"
  if you are on Unix-based systems. If you're on Windows, use "file:///c:/path/to/file". In both
  examples, note the three slashes (`/`) -- the first two slashes belong to `file://` and the third
  one belongs to the absolute path to the file.

Args:
  name: A unique name for this rule.
  sha256: The expected SHA-256 of the file downloaded.
  url: The URL to fetch the jar from. It must end in `.jar`.
  urls: A list of URLS the jar can be fetched from. They have to end in `.jar`.
"""
<commit_msg>Add option to specify name for downloaded file to http_file skylark rule<commit_after># Copyright 2016 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Rules for downloading files and archives over HTTP.

### Setup

To use these rules, load them in your `WORKSPACE` file as follows:

```python
load(
    "@bazel_tools//tools/build_defs/repo:http.bzl",
    "http_archive",
    "http_file",
    "http_jar",
)
```

These rules are improved versions of the native http rules and will eventually
replace the native rules.
"""

load("@bazel_tools//tools/build_defs/repo:utils.bzl", "patch", "workspace_and_buildfile")

def _http_archive_impl(ctx):
    """Implementation of the http_archive rule."""
    if not ctx.attr.url and not ctx.attr.urls:
        fail("At least one of url and urls must be provided")
    if ctx.attr.build_file and ctx.attr.build_file_content:
        fail("Only one of build_file and build_file_content can be provided.")

    all_urls = []
    if ctx.attr.urls:
        all_urls = ctx.attr.urls
    if ctx.attr.url:
        all_urls = [ctx.attr.url] + all_urls

    ctx.download_and_extract(
        all_urls,
        "",
        ctx.attr.sha256,
        ctx.attr.type,
        ctx.attr.strip_prefix,
    )
    patch(ctx)
    workspace_and_buildfile(ctx)

_HTTP_FILE_BUILD = """
package(default_visibility = ["//visibility:public"])

filegroup(
    name = "file",
    srcs = ["{}"],
)
"""

def _http_file_impl(ctx):
    """Implementation of the http_file rule."""
    repo_root = ctx.path(".")
    forbidden_files = [
        repo_root,
        ctx.path("WORKSPACE"),
        ctx.path("BUILD"),
        ctx.path("BUILD.bazel"),
        ctx.path("file/BUILD"),
        ctx.path("file/BUILD.bazel"),
    ]
    downloaded_file_path = ctx.attr.downloaded_file_path
    download_path = ctx.path("file/" + downloaded_file_path)
    if download_path in forbidden_files or not str(download_path).startswith(str(repo_root)):
        fail("'%s' cannot be used as downloaded_file_path in http_file" % ctx.attr.downloaded_file_path)
    ctx.download(
        ctx.attr.urls,
        "file/" + downloaded_file_path,
        ctx.attr.sha256,
        ctx.attr.executable,
    )
    ctx.file("WORKSPACE", "workspace(name = \"{name}\")".format(name = ctx.name))
    ctx.file("file/BUILD", _HTTP_FILE_BUILD.format(downloaded_file_path))

_HTTP_JAR_BUILD = """
package(default_visibility = ["//visibility:public"])

java_import(
  name = 'jar',
  jars = ['downloaded.jar'],
  visibility = ['//visibility:public'],
)

filegroup(
  name = 'file',
  srcs = ['downloaded.jar'],
  visibility = ['//visibility:public'],
)

"""

def _http_jar_impl(ctx):
    """Implementation of the http_jar rule."""
    all_urls = []
    if ctx.attr.urls:
        all_urls = ctx.attr.urls
    if ctx.attr.url:
        all_urls = [ctx.attr.url] + all_urls
    ctx.download(all_urls, "jar/downloaded.jar", ctx.attr.sha256)
    ctx.file("WORKSPACE", "workspace(name = \"{name}\")".format(name = ctx.name))
    ctx.file("jar/BUILD", _HTTP_JAR_BUILD)

_http_archive_attrs = {
    "url": attr.string(),
    "urls": attr.string_list(),
    "sha256": attr.string(),
    "strip_prefix": attr.string(),
    "type": attr.string(),
    "build_file": attr.label(allow_single_file = True),
    "build_file_content": attr.string(),
    "patches": attr.label_list(default = []),
    "patch_tool": attr.string(default = "patch"),
    "patch_args": attr.string_list(default = ["-p0"]),
    "patch_cmds": attr.string_list(default = []),
    "workspace_file": attr.label(allow_single_file = True),
    "workspace_file_content": attr.string(),
}

http_archive = repository_rule(
    implementation = _http_archive_impl,
    attrs = _http_archive_attrs,
)
"""Downloads a Bazel repository as a compressed archive file, decompresses it,
and makes its targets available for binding.

It supports the following file extensions: `"zip"`, `"jar"`, `"war"`, `"tar"`,
`"tar.gz"`, `"tgz"`, `"tar.xz"`, and `tar.bz2`.

Examples:
  Suppose the current repository contains the source code for a chat program,
  rooted at the directory `~/chat-app`. It needs to depend on an SSL library
  which is available from http://example.com/openssl.zip. This `.zip` file
  contains the following directory structure:

  ```
  WORKSPACE
  src/
    openssl.cc
    openssl.h
  ```

  In the local repository, the user creates a `openssl.BUILD` file which
  contains the following target definition:

  ```python
  cc_library(
      name = "openssl-lib",
      srcs = ["src/openssl.cc"],
      hdrs = ["src/openssl.h"],
  )
  ```

  Targets in the `~/chat-app` repository can depend on this target if the
  following lines are added to `~/chat-app/WORKSPACE`:

  ```python
  http_archive(
      name = "my_ssl",
      urls = ["http://example.com/openssl.zip"],
      sha256 = "03a58ac630e59778f328af4bcc4acb4f80208ed4",
      build_file = "//:openssl.BUILD",
  )
  ```

  Then targets would specify `@my_ssl//:openssl-lib` as a dependency.

Args:
  name: A unique name for this rule.
  build_file: The file to use as the `BUILD` file for this repository.

    Either `build_file` or `build_file_content` can be specified.

    This attribute is a label relative to the main workspace. The file does not
    need to be named `BUILD`, but can be (something like `BUILD.new-repo-name`
    may work well for distinguishing it from the repository's actual `BUILD`
    files.

  build_file_content: The content for the BUILD file for this repository.

    Either `build_file` or `build_file_content` can be specified.
  workspace_file: The file to use as the `WORKSPACE` file for this repository.

    Either `workspace_file` or `workspace_file_content` can be specified, or
    neither, but not both.
  workspace_file_content: The content for the WORKSPACE file for this repository.

    Either `workspace_file` or `workspace_file_content` can be specified, or
    neither, but not both.
  sha256: The expected SHA-256 of the file downloaded.

    This must match the SHA-256 of the file downloaded. _It is a security risk
    to omit the SHA-256 as remote files can change._ At best omitting this
    field will make your build non-hermetic. It is optional to make development
    easier but should be set before shipping.
  strip_prefix: A directory prefix to strip from the extracted files.

    Many archives contain a top-level directory that contains all of the useful
    files in archive. Instead of needing to specify this prefix over and over
    in the `build_file`, this field can be used to strip it from all of the
    extracted files.

    For example, suppose you are using `foo-lib-latest.zip`, which contains the
    directory `foo-lib-1.2.3/` under which there is a `WORKSPACE` file and are
    `src/`, `lib/`, and `test/` directories that contain the actual code you
    wish to build. Specify `strip_prefix = "foo-lib-1.2.3"` to use the
    `foo-lib-1.2.3` directory as your top-level directory.

    Note that if there are files outside of this directory, they will be
    discarded and inaccessible (e.g., a top-level license file). This includes
    files/directories that start with the prefix but are not in the directory
    (e.g., `foo-lib-1.2.3.release-notes`). If the specified prefix does not
    match a directory in the archive, Bazel will return an error.
  type: The archive type of the downloaded file.

    By default, the archive type is determined from the file extension of the
    URL. If the file has no extension, you can explicitly specify one of the
    following: `"zip"`, `"jar"`, `"war"`, `"tar"`, `"tar.gz"`, `"tgz"`,
    `"tar.xz"`, or `tar.bz2`.
  url: A URL to a file that will be made available to Bazel.

    This must be an file, http or https URL. Redirections are followed.
    Authentication is not supported.

    This parameter is to simplify the transition from the native http_archive
    rule. More flexibility can be achieved by the urls parameter that allows
    to specify alternative URLs to fetch from.
  urls: A list of URLs to a file that will be made available to Bazel.

    Each entry must be an file, http or https URL. Redirections are followed.
    Authentication is not supported.
  patches: A list of files that are to be applied as patches after extracting
    the archive.
  patch_tool: the patch(1) utility to use.
  patch_args: arguments given to the patch tool, defaults to ["-p0"]
  patch_cmds: sequence of commands to be applied after patches are applied.
"""

http_file = repository_rule(
    implementation = _http_file_impl,
    attrs = {
        "executable": attr.bool(),
        "downloaded_file_path": attr.string(default = "downloaded"),
        "sha256": attr.string(),
        "urls": attr.string_list(mandatory = True),
    },
)
"""Downloads a file from a URL and makes it available to be used as a file
group.

Examples:
  Suppose you need to have a debian package for your custom rules. This package
  is available from http://example.com/package.deb. Then you can add to your
  WORKSPACE file:

  ```python
  http_file(
      name = "my_deb",
      urls = ["http://example.com/package.deb"],
      sha256 = "03a58ac630e59778f328af4bcc4acb4f80208ed4",
  )
  ```

  Targets would specify `@my_deb//file` as a dependency to depend on this file.

Args:
  name: A unique name for this rule.
  executable: If the downloaded file should be made executable. Defaults to
    False.
  downloaded_file_path: Path assigned to the file downloaded.
  sha256: The expected SHA-256 of the file downloaded.

    This must match the SHA-256 of the file downloaded. _It is a security risk
    to omit the SHA-256 as remote files can change._ At best omitting this
    field will make your build non-hermetic. It is optional to make development
    easier but should be set before shipping.
  urls: A list of URLs to a file that will be made available to Bazel.

    Each entry must be an file, http or https URL. Redirections are followed.
    Authentication is not supported.
"""

http_jar = repository_rule(
    implementation = _http_jar_impl,
    attrs = {
        "sha256": attr.string(),
        "url": attr.string(),
        "urls": attr.string_list(),
    },
)
"""Downloads a jar from a URL and makes it available as java_import

Downloaded files must have a .jar extension.

Examples:
  Suppose the current repository contains the source code for a chat program, rooted at the
  directory `~/chat-app`. It needs to depend on an SSL library which is available from
  `http://example.com/openssl-0.2.jar`.

  Targets in the `~/chat-app` repository can depend on this target if the following lines are
  added to `~/chat-app/WORKSPACE`:

  ```python
  http_jar(
      name = "my_ssl",
      url = "http://example.com/openssl-0.2.jar",
      sha256 = "03a58ac630e59778f328af4bcc4acb4f80208ed4",
  )
  ```

  Targets would specify <code>@my_ssl//jar</code> as a dependency to depend on this jar.

  You may also reference files on the current system (localhost) by using "file:///path/to/file"
  if you are on Unix-based systems. If you're on Windows, use "file:///c:/path/to/file". In both
  examples, note the three slashes (`/`) -- the first two slashes belong to `file://` and the third
  one belongs to the absolute path to the file.

Args:
  name: A unique name for this rule.
  sha256: The expected SHA-256 of the file downloaded.
  url: The URL to fetch the jar from. It must end in `.jar`.
  urls: A list of URLS the jar can be fetched from. They have to end in `.jar`.
"""
<|endoftext|>