<commit_before># -*- coding: utf-8 -*-
from array import array
from struct import Struct

try:
    import numpy
except ImportError, e:
    numpy = None
    numpy_reason = e
else:
    numpy_reason = None

BAUD_RATE = 115200

CMD_RESET = b'v'
CMD_STREAM_START = b'b'
CMD_STREAM_STOP = b's'

# this is a Parsley (OMeta) grammar describing the protocol we receive
# from the OpenBCI device.
grammar = """
idle = <(~EOT anything)+>:x EOT -> receiver.handleResponse(x)
EOT = '$$$'

sampleStream = sample+
sample = SAMPLE_START
    uint8:counter
    <anything{30}>:x
    SAMPLE_END -> receiver.handleSample(counter, x)
SAMPLE_START = '\xA0'
SAMPLE_END = '\xC0'

debug = anything:x -> receiver.logIncoming(x)
uint8 = anything:x -> ord(x)
"""
# The ADS1299 outputs 24 bits of data per channel in binary twos complement
# format, MSB first [data sheet SBAS499A]. OpenBCI passes it through in that
# format to us, but most platforms do not have a 24-bit integer type, and
# we're probably not using that big-endian byte order.

# 24-bit integer is unusual enough that struct and numpy don't have tools
# to unpack them, but we can treat it as a signed 8-bit part followed by
# unsigned 16 bits and then reassemble.

_i3Struct = [Struct('>' + ('bH' * (n + 1))) for n in range(8)]

def python_int32From3Bytes(buf, count=-1, offset=0):
    """
    Turn a byte buffer containing 24-bit big-endian data into
    an array of python integers.
    """
    if count == -1:
        count = len(buf) / 3
    sizedStruct = _i3Struct[count - 1]
    # this unpacks to an alternating sequence of high bytes and lower 16-bits
    parts = sizedStruct.unpack_from(buf, offset=offset)
    high = parts[::2]  # start by grabbing the high bytes
    output = array('l', high)  # put them into an array of 32-bit ints
    for i, low in enumerate(parts[1::2]):
        output[i] <<= 16  # push them up by 16 bits
        output[i] |= low  # fill in the lower 16 bits
    return output

_accelerometerStruct = Struct('>hhh')

def python_accelerometerFromBytes(buf, offset=0):
    parts = _accelerometerStruct.unpack_from(buf, offset=offset)
    return array('h', parts)

if numpy:
    _i1u2 = numpy.dtype([('high', 'i1'), ('low', '>u2')])

def numpy_int32From3Bytes(buf, count=-1, offset=0):
    """
    Turn a byte buffer containing 24-bit big-endian data into
    a numpy array of 32-bit integers.
    """
    in_array = numpy.frombuffer(buf, _i1u2, count=count, offset=offset)
    output = in_array['high'].astype('i4')
    output <<= 16
    output |= in_array['low']
    return output

def numpy_accelerometerFromBytes(buf, offset=0):
    in_array = numpy.frombuffer(buf, '>i2', count=3, offset=offset)
    # that was much easier than 24-bit ints, but we'll still copy it to native byte order.
    return in_array.astype('i2')

if numpy:
    int32From3Bytes = numpy_int32From3Bytes
    accelerometerFromBytes = numpy_accelerometerFromBytes
else:
    int32From3Bytes = python_int32From3Bytes
    accelerometerFromBytes = python_accelerometerFromBytes

<commit_msg>protocol: put a max length on the general response<commit_after># -*- coding: utf-8 -*-
from array import array
from struct import Struct

try:
    import numpy
except ImportError, e:
    numpy = None
    numpy_reason = e
else:
    numpy_reason = None

BAUD_RATE = 115200

CMD_RESET = b'v'
CMD_STREAM_START = b'b'
CMD_STREAM_STOP = b's'

# this is a Parsley (OMeta) grammar describing the protocol we receive
# from the OpenBCI device.
grammar = """
idle = <(~EOT anything){0,2048}>:x EOT -> receiver.handleResponse(x)
EOT = '$$$'

sampleStream = sample+
sample = SAMPLE_START
    uint8:counter
    <anything{30}>:x
    SAMPLE_END -> receiver.handleSample(counter, x)
SAMPLE_START = '\xA0'
SAMPLE_END = '\xC0'

debug = anything:x -> receiver.logIncoming(x)
uint8 = anything:x -> ord(x)
"""
# The ADS1299 outputs 24 bits of data per channel in binary twos complement
# format, MSB first [data sheet SBAS499A]. OpenBCI passes it through in that
# format to us, but most platforms do not have a 24-bit integer type, and
# we're probably not using that big-endian byte order.

# 24-bit integer is unusual enough that struct and numpy don't have tools
# to unpack them, but we can treat it as a signed 8-bit part followed by
# unsigned 16 bits and then reassemble.

_i3Struct = [Struct('>' + ('bH' * (n + 1))) for n in range(8)]

def python_int32From3Bytes(buf, count=-1, offset=0):
    """
    Turn a byte buffer containing 24-bit big-endian data into
    an array of python integers.
    """
    if count == -1:
        count = len(buf) / 3
    sizedStruct = _i3Struct[count - 1]
    # this unpacks to an alternating sequence of high bytes and lower 16-bits
    parts = sizedStruct.unpack_from(buf, offset=offset)
    high = parts[::2]  # start by grabbing the high bytes
    output = array('l', high)  # put them into an array of 32-bit ints
    for i, low in enumerate(parts[1::2]):
        output[i] <<= 16  # push them up by 16 bits
        output[i] |= low  # fill in the lower 16 bits
    return output

_accelerometerStruct = Struct('>hhh')

def python_accelerometerFromBytes(buf, offset=0):
    parts = _accelerometerStruct.unpack_from(buf, offset=offset)
    return array('h', parts)

if numpy:
    _i1u2 = numpy.dtype([('high', 'i1'), ('low', '>u2')])

def numpy_int32From3Bytes(buf, count=-1, offset=0):
    """
    Turn a byte buffer containing 24-bit big-endian data into
    a numpy array of 32-bit integers.
    """
    in_array = numpy.frombuffer(buf, _i1u2, count=count, offset=offset)
    output = in_array['high'].astype('i4')
    output <<= 16
    output |= in_array['low']
    return output

def numpy_accelerometerFromBytes(buf, offset=0):
    in_array = numpy.frombuffer(buf, '>i2', count=3, offset=offset)
    # that was much easier than 24-bit ints, but we'll still copy it to native byte order.
    return in_array.astype('i2')

if numpy:
    int32From3Bytes = numpy_int32From3Bytes
    accelerometerFromBytes = numpy_accelerometerFromBytes
else:
    int32From3Bytes = python_int32From3Bytes
    accelerometerFromBytes = python_accelerometerFromBytes

<|endoftext|>


<commit_before>import types

from django.db import models
from django.db.models.base import ModelBase
from django.db.models.fields import Field

class TypedModelManager(models.Manager):
    def get_query_set(self):
        qs = super(TypedModelManager, self).get_query_set()
        if hasattr(self.model, '_typedmodels_type'):
            if len(self.model._typedmodels_subtypes) > 1:
                qs = qs.filter(type__in=self.model._typedmodels_subtypes)
            else:
                qs = qs.filter(type=self.model._typedmodels_type)
        return qs

class TypedModelMetaclass(ModelBase):
    """
    This metaclass enables a model for auto-downcasting using a ``type`` attribute.
    """
    def __new__(meta, classname, bases, classdict):
        try:
            TypedModel
        except NameError:
            # don't do anything for TypedModel class itself
            #
            # ...except updating Meta class to instantiate fields_from_subclasses attribute
            typed_model = super(TypedModelMetaclass, meta).__new__(meta, classname, bases, classdict)
            # We have to set this attribute after _meta has been created, otherwise an
            # exception would be thrown by Options class constructor.
            typed_model._meta.fields_from_subclasses = {}
            return typed_model

        # look for a non-proxy base class that is a subclass of TypedModel
        mro = list(bases)
        while mro:
            base_class = mro.pop(-1)
            if issubclass(base_class, TypedModel) and base_class is not TypedModel:
                if base_class._meta.proxy:
                    # continue up the mro looking for non-proxy base classes
                    mro.extend(base_class.__bases__)
                else:
                    break
        else:
            base_class = None

        if base_class:
            if not hasattr(base_class, 'original'):
                class original_meta:
                    proxy = True
                Original = super(TypedModelMetaclass, meta).__new__(meta, base_class.__name__+'Original', (base_class,), {'Meta': original_meta, '__module__': base_class.__module__})
                base_class._meta.original = Original

            # Enforce that subclasses are proxy models.
            # Update an existing metaclass, or define an empty one
            # then set proxy=True
            class Meta:
                pass
            Meta = classdict.get('Meta', Meta)
            Meta.proxy = True

            declared_fields = dict((name, element) for name, element in classdict.items() if isinstance(element, Field))

            for field_name, field in declared_fields.items():
                field.null = True
                if isinstance(field, models.fields.related.RelatedField) and isinstance(field.rel.to, TypedModel) and field.rel.to.base_class:
                        field.rel.limit_choices_to['type__in'] = field.rel.to._typedmodels_subtypes
                        field.rel.to = field.rel.to.base_class
                field.contribute_to_class(base_class, field_name)
                classdict.pop(field_name)
            base_class._meta.fields_from_subclasses.update(declared_fields)

            # set app_label to the same as the base class, unless explicitly defined otherwise
            if not hasattr(Meta, 'app_label'):
                if hasattr(getattr(base_class, '_meta', None), 'app_label'):
                    Meta.app_label = base_class._meta.app_label

            classdict.update({
                'Meta': Meta,
            })

        classdict['base_class'] = base_class

        cls = super(TypedModelMetaclass, meta).__new__(meta, classname, bases, classdict)

        cls._meta.fields_from_subclasses = {}

        if base_class:
            opts = cls._meta
            typ = "%s.%s" % (opts.app_label, opts.object_name.lower())
            cls._typedmodels_type = typ
            cls._typedmodels_subtypes = [typ]
            if typ in base_class._typedmodels_registry:
                raise ValueError("Can't register %s type %r to %r (already registered to %r )" % (typ, classname, base_class._typedmodels_registry))
            base_class._typedmodels_registry[typ] = cls
            type_name = getattr(cls._meta, 'verbose_name', cls.__name__)
            type_field = base_class._meta.get_field('type')
            type_field._choices = tuple(list(type_field.choices) + [(typ, type_name)])

            cls._meta.declared_fields = declared_fields

            # look for any other proxy superclasses, they'll need to know
            # about this subclass
            for superclass in cls.mro():
                if (issubclass(superclass, base_class)
                        and superclass not in (cls, base_class)
                        and hasattr(superclass, '_typedmodels_type')):
                    superclass._typedmodels_subtypes.append(typ)

            # Overriding _fill_fields_cache function in Meta.
            # This is done by overriding method for specific instance of
            # django.db.models.options.Options class, which generally should
            # be avoided, but in this case it may be better than monkey patching
            # Options or copy-pasting large parts of Django code.
            def _fill_fields_cache(self):
                cache = []
                for parent in self.parents:
                    for field, model in parent._meta.get_fields_with_model():
                        if field in base_class._meta.original._meta.fields or any(field in ancestor._meta.declared_fields.values() for ancestor in cls.mro() if issubclass(ancestor, base_class) and not ancestor==base_class):
                            if model:
                                cache.append((field, model))
                            else:
                                cache.append((field, parent))
                self._field_cache = tuple(cache)
                self._field_name_cache = [x for x, _ in cache]
            cls._meta._fill_fields_cache = types.MethodType(_fill_fields_cache, cls._meta, cls._meta.__class__)
            if hasattr(cls._meta, '_field_name_cache'):
                del cls._meta._field_name_cache
            if hasattr(cls._meta, '_field_cache'):
                del cls._meta._field_cache
            cls._meta._fill_fields_cache()

            # No, no, no. This is wrong as it duplicates fields in _meta.fields:
            # # need to populate local_fields, otherwise no fields get serialized in fixtures
            # cls._meta.local_fields = base_class._meta.local_fields[:]
        else:
            # this is the base class
            cls._typedmodels_registry = {}

            # Since fields may be added by subclasses, save original fields.
            cls._meta.original_fields = cls._meta.fields

            # set default manager. this will be inherited by subclasses, since they are proxy models
            manager = None
            if not cls._default_manager:
                manager = TypedModelManager()
            elif not isinstance(cls._default_manager, TypedModelManager):
                class Manager(TypedModelManager, cls._default_manager.__class__):
                    pass
                cls._default_manager.__class__ = Manager
                manager = cls._default_manager
            if manager is not None:
                cls.add_to_class('objects', manager)
                cls._default_manager = cls.objects

            # add a get_type_classes classmethod to allow fetching of all the subclasses (useful for admin)

            def get_type_classes(subcls):
                # This is a bit inconsistent since there is _typedmodels_subtypes
                # attribute on subclasses. Perhaps it should be unified to achieve
                # similar behavior on both root class and it's subclasses.
                if subcls is not cls:
                    raise ValueError("get_type_classes() is not accessible from subclasses of %s (was called from %s)" % (cls.__name__, subcls.__name__))
                return cls._typedmodels_registry.values()[:]
            cls.get_type_classes = classmethod(get_type_classes)
        return cls

class TypedModel(models.Model):
    '''
    This class contains the functionality required to auto-downcast a model based
    on its ``type`` attribute.

    To use, simply subclass TypedModel for your base type, and then subclass
    that for your concrete types.

    Example usage::

        from django.db import models
        from typedmodels import TypedModel

        class Animal(TypedModel):
            """
            Abstract model
            """
            name = models.CharField(max_length=255)

            def say_something(self):
                raise NotImplemented

            def __repr__(self):
                return u'<%s: %s>' % (self.__class__.__name__, self.name)

        class Canine(Animal):
            def say_something(self):
                return "woof"

        class Feline(Animal):
            def say_something(self):
                return "meoww"
    '''

    __metaclass__ = TypedModelMetaclass

    type = models.CharField(choices=(), max_length=255, null=False, blank=False, db_index=True)

    # Class variable indicating if model should be automatically recasted after initialization
    _auto_recast = True

    class Meta:
        abstract = True

    def __init__(self, *args, **kwargs):
        # Calling __init__ on base class because some functions (e.g. save()) need access to field values from base
        # class.
        if self.base_class:
            before_class = self.__class__
            self.__class__ = self.base_class
        else:
            before_class = None
        super(TypedModel, self).__init__(*args, **kwargs)
        if before_class:
            self.__class__ = before_class
        if self._auto_recast:
            self.recast()

    def recast(self):
        if not self.type:
            if not hasattr(self, '_typedmodels_type'):
                # Ideally we'd raise an error here, but the django admin likes to call
                # model() and doesn't expect an error.
                # Instead, we raise an error when the object is saved.
                return
            self.type = self._typedmodels_type

        for base in self.__class__.mro():
            if issubclass(base, TypedModel) and hasattr(base, '_typedmodels_registry'):
                break
        else:
            raise ValueError("No suitable base class found to recast!")

        try:
            correct_cls = base._typedmodels_registry[self.type]
        except KeyError:
            raise ValueError("Invalid %s identifier : %r" % (base.__name__, self.type))

        if self.__class__ != correct_cls:
            self.__class__ = correct_cls

    def save(self, *args, **kwargs):
        if not getattr(self, '_typedmodels_type', None):
            raise RuntimeError("Untyped %s cannot be saved." % self.__class__.__name__)
        return super(TypedModel, self).save(*args, **kwargs)
<commit_msg>Fixed problem with field ordering in model constructor.<commit_after>import types

from django.db import models
from django.db.models.base import ModelBase
from django.db.models.fields import Field

class TypedModelManager(models.Manager):
    def get_query_set(self):
        qs = super(TypedModelManager, self).get_query_set()
        if hasattr(self.model, '_typedmodels_type'):
            if len(self.model._typedmodels_subtypes) > 1:
                qs = qs.filter(type__in=self.model._typedmodels_subtypes)
            else:
                qs = qs.filter(type=self.model._typedmodels_type)
        return qs

class TypedModelMetaclass(ModelBase):
    """
    This metaclass enables a model for auto-downcasting using a ``type`` attribute.
    """
    def __new__(meta, classname, bases, classdict):
        try:
            TypedModel
        except NameError:
            # don't do anything for TypedModel class itself
            #
            # ...except updating Meta class to instantiate fields_from_subclasses attribute
            typed_model = super(TypedModelMetaclass, meta).__new__(meta, classname, bases, classdict)
            # We have to set this attribute after _meta has been created, otherwise an
            # exception would be thrown by Options class constructor.
            typed_model._meta.fields_from_subclasses = {}
            return typed_model

        # look for a non-proxy base class that is a subclass of TypedModel
        mro = list(bases)
        while mro:
            base_class = mro.pop(-1)
            if issubclass(base_class, TypedModel) and base_class is not TypedModel:
                if base_class._meta.proxy:
                    # continue up the mro looking for non-proxy base classes
                    mro.extend(base_class.__bases__)
                else:
                    break
        else:
            base_class = None

        if base_class:
            if not hasattr(base_class, 'original'):
                class original_meta:
                    proxy = True
                Original = super(TypedModelMetaclass, meta).__new__(meta, base_class.__name__+'Original', (base_class,), {'Meta': original_meta, '__module__': base_class.__module__})
                base_class._meta.original = Original

            # Enforce that subclasses are proxy models.
            # Update an existing metaclass, or define an empty one
            # then set proxy=True
            class Meta:
                pass
            Meta = classdict.get('Meta', Meta)
            Meta.proxy = True

            declared_fields = dict((name, element) for name, element in classdict.items() if isinstance(element, Field))

            for field_name, field in declared_fields.items():
                field.null = True
                if isinstance(field, models.fields.related.RelatedField) and isinstance(field.rel.to, TypedModel) and field.rel.to.base_class:
                        field.rel.limit_choices_to['type__in'] = field.rel.to._typedmodels_subtypes
                        field.rel.to = field.rel.to.base_class
                field.contribute_to_class(base_class, field_name)
                classdict.pop(field_name)
            base_class._meta.fields_from_subclasses.update(declared_fields)

            # set app_label to the same as the base class, unless explicitly defined otherwise
            if not hasattr(Meta, 'app_label'):
                if hasattr(getattr(base_class, '_meta', None), 'app_label'):
                    Meta.app_label = base_class._meta.app_label

            classdict.update({
                'Meta': Meta,
            })

        classdict['base_class'] = base_class

        cls = super(TypedModelMetaclass, meta).__new__(meta, classname, bases, classdict)

        cls._meta.fields_from_subclasses = {}

        if base_class:
            opts = cls._meta
            typ = "%s.%s" % (opts.app_label, opts.object_name.lower())
            cls._typedmodels_type = typ
            cls._typedmodels_subtypes = [typ]
            if typ in base_class._typedmodels_registry:
                raise ValueError("Can't register %s type %r to %r (already registered to %r )" % (typ, classname, base_class._typedmodels_registry))
            base_class._typedmodels_registry[typ] = cls
            type_name = getattr(cls._meta, 'verbose_name', cls.__name__)
            type_field = base_class._meta.get_field('type')
            type_field._choices = tuple(list(type_field.choices) + [(typ, type_name)])

            cls._meta.declared_fields = declared_fields

            # look for any other proxy superclasses, they'll need to know
            # about this subclass
            for superclass in cls.mro():
                if (issubclass(superclass, base_class)
                        and superclass not in (cls, base_class)
                        and hasattr(superclass, '_typedmodels_type')):
                    superclass._typedmodels_subtypes.append(typ)

            # Overriding _fill_fields_cache function in Meta.
            # This is done by overriding method for specific instance of
            # django.db.models.options.Options class, which generally should
            # be avoided, but in this case it may be better than monkey patching
            # Options or copy-pasting large parts of Django code.
            def _fill_fields_cache(self):
                cache = []
                for parent in self.parents:
                    for field, model in parent._meta.get_fields_with_model():
                        if field in base_class._meta.original._meta.fields or any(field in ancestor._meta.declared_fields.values() for ancestor in cls.mro() if issubclass(ancestor, base_class) and not ancestor==base_class):
                            if model:
                                cache.append((field, model))
                            else:
                                cache.append((field, parent))
                self._field_cache = tuple(cache)
                self._field_name_cache = [x for x, _ in cache]
            cls._meta._fill_fields_cache = types.MethodType(_fill_fields_cache, cls._meta, cls._meta.__class__)
            if hasattr(cls._meta, '_field_name_cache'):
                del cls._meta._field_name_cache
            if hasattr(cls._meta, '_field_cache'):
                del cls._meta._field_cache
            cls._meta._fill_fields_cache()

            # No, no, no. This is wrong as it duplicates fields in _meta.fields:
            # # need to populate local_fields, otherwise no fields get serialized in fixtures
            # cls._meta.local_fields = base_class._meta.local_fields[:]
        else:
            # this is the base class
            cls._typedmodels_registry = {}

            # Since fields may be added by subclasses, save original fields.
            cls._meta.original_fields = cls._meta.fields

            # set default manager. this will be inherited by subclasses, since they are proxy models
            manager = None
            if not cls._default_manager:
                manager = TypedModelManager()
            elif not isinstance(cls._default_manager, TypedModelManager):
                class Manager(TypedModelManager, cls._default_manager.__class__):
                    pass
                cls._default_manager.__class__ = Manager
                manager = cls._default_manager
            if manager is not None:
                cls.add_to_class('objects', manager)
                cls._default_manager = cls.objects

            # add a get_type_classes classmethod to allow fetching of all the subclasses (useful for admin)

            def get_type_classes(subcls):
                # This is a bit inconsistent since there is _typedmodels_subtypes
                # attribute on subclasses. Perhaps it should be unified to achieve
                # similar behavior on both root class and it's subclasses.
                if subcls is not cls:
                    raise ValueError("get_type_classes() is not accessible from subclasses of %s (was called from %s)" % (cls.__name__, subcls.__name__))
                return cls._typedmodels_registry.values()[:]
            cls.get_type_classes = classmethod(get_type_classes)
        return cls

class TypedModel(models.Model):
    '''
    This class contains the functionality required to auto-downcast a model based
    on its ``type`` attribute.

    To use, simply subclass TypedModel for your base type, and then subclass
    that for your concrete types.

    Example usage::

        from django.db import models
        from typedmodels import TypedModel

        class Animal(TypedModel):
            """
            Abstract model
            """
            name = models.CharField(max_length=255)

            def say_something(self):
                raise NotImplemented

            def __repr__(self):
                return u'<%s: %s>' % (self.__class__.__name__, self.name)

        class Canine(Animal):
            def say_something(self):
                return "woof"

        class Feline(Animal):
            def say_something(self):
                return "meoww"
    '''

    __metaclass__ = TypedModelMetaclass

    type = models.CharField(choices=(), max_length=255, null=False, blank=False, db_index=True)

    # Class variable indicating if model should be automatically recasted after initialization
    _auto_recast = True

    class Meta:
        abstract = True

    def __init__(self, *args, **kwargs):
        # Calling __init__ on base class because some functions (e.g. save()) need access to field values from base
        # class.

        # Move args to kwargs since base_class may have more fields defined with different ordering
        args = list(args)
        if len(args) > len(self._meta.fields):
            # Daft, but matches old exception sans the err msg.
            raise IndexError("Number of args exceeds number of fields")
        for field_value, field in zip(args, self._meta.fields):
            kwargs[field.attname] = field_value
            args.pop(0)

        if self.base_class:
            before_class = self.__class__
            self.__class__ = self.base_class
        else:
            before_class = None
        super(TypedModel, self).__init__(*args, **kwargs)
        if before_class:
            self.__class__ = before_class
        if self._auto_recast:
            self.recast()

    def recast(self):
        if not self.type:
            if not hasattr(self, '_typedmodels_type'):
                # Ideally we'd raise an error here, but the django admin likes to call
                # model() and doesn't expect an error.
                # Instead, we raise an error when the object is saved.
                return
            self.type = self._typedmodels_type

        for base in self.__class__.mro():
            if issubclass(base, TypedModel) and hasattr(base, '_typedmodels_registry'):
                break
        else:
            raise ValueError("No suitable base class found to recast!")

        try:
            correct_cls = base._typedmodels_registry[self.type]
        except KeyError:
            raise ValueError("Invalid %s identifier : %r" % (base.__name__, self.type))

        if self.__class__ != correct_cls:
            self.__class__ = correct_cls

    def save(self, *args, **kwargs):
        if not getattr(self, '_typedmodels_type', None):
            raise RuntimeError("Untyped %s cannot be saved." % self.__class__.__name__)
        return super(TypedModel, self).save(*args, **kwargs)
<|endoftext|>


<commit_before>import sublime
from sublime_plugin import WindowCommand

from ..git_command import GitCommand
from ...common import util

NEW_BRANCH_PROMPT = "Branch name:"

class GsCheckoutBranchCommand(WindowCommand, GitCommand):

    """
    Display a panel of all local branches.  Change to the branch the
    user selected.
    """

    def run(self):
        sublime.set_timeout_async(self.run_async, 0)

    def run_async(self):
        stdout = self.git("branch", "--no-color")
        branch_entries = (branch.strip() for branch in stdout.split("\n") if branch)

        # The line with the active branch will begin with an asterisk.
        self.local_inactive_branches = [branch for branch in branch_entries if not branch[0] == "*"]

        if not self.local_inactive_branches:
            self.window.show_quick_panel(["There are no branches available."], None)
        else:
            self.window.show_quick_panel(
                self.local_inactive_branches,
                self.on_selection,
                flags=sublime.MONOSPACE_FONT
                )

    def on_selection(self, branch_name_index):
        if branch_name_index == -1:
            return

        branch_name = self.local_inactive_branches[branch_name_index]
        self.git("checkout", branch_name)
        sublime.status_message("Checked out `{}` branch.".format(branch_name))
        util.view.refresh_gitsavvy(self.window.active_view())

class GsCheckoutNewBranchCommand(WindowCommand, GitCommand):

    """
    Prompt the user for a new branch name, create it, and check it out.
    """

    def run(self):
        sublime.set_timeout_async(self.run_async)

    def run_async(self):
        self.window.show_input_panel(NEW_BRANCH_PROMPT, "", self.on_done, None, None)

    def on_done(self, branch_name):
        self.git("checkout", "-b", branch_name)
        sublime.status_message("Created and checked out `{}` branch.".format(branch_name))
        util.view.refresh_gitsavvy(self.window.active_view())

class GsCheckoutRemoteBranchCommand(WindowCommand, GitCommand):

    """
    Display a panel of all remote branches.  When the user makes a selection,
    create a corresponding local branch, and set it to the HEAD of the
    selected branch.
    """

    def run(self):
        sublime.set_timeout_async(self.run_async)

    def run_async(self):
        self.remote_branches = self.get_remote_branches()
        self.window.show_quick_panel(
            self.remote_branches,
            self.on_selection,
            flags=sublime.MONOSPACE_FONT
            )

    def on_selection(self, remote_branch_index):
        if remote_branch_index == -1:
            return

        remote_branch = self.remote_branches[remote_branch_index]
        local_name = remote_branch.split("/", 1)[1]
        self.git("checkout", "-b", local_name, "--track", remote_branch)
        sublime.status_message("Checked out `{}` as local branch `{}`.".format(remote_branch, local_name))
        util.view.refresh_gitsavvy(self.window.active_view())

class GsCheckoutCurrentFileCommand(WindowCommand, GitCommand):

    """
    Reset the current active file to HEAD.
    """

    def run(self):
        if self.file_path:
            self.checkout_file(self.file_path)
            sublime.status_message("Successfully checked out {} from head.".format(self.file_path))
<commit_msg>Validation on creating new branch<commit_after>import re
import sublime
from sublime_plugin import WindowCommand

from ..git_command import GitCommand
from ...common import util

NEW_BRANCH_PROMPT = "Branch name:"

class GsCheckoutBranchCommand(WindowCommand, GitCommand):

    """
    Display a panel of all local branches.  Change to the branch the
    user selected.
    """

    def run(self):
        sublime.set_timeout_async(self.run_async, 0)

    def run_async(self):
        stdout = self.git("branch", "--no-color")
        branch_entries = (branch.strip() for branch in stdout.split("\n") if branch)

        # The line with the active branch will begin with an asterisk.
        self.local_inactive_branches = [branch for branch in branch_entries if not branch[0] == "*"]

        if not self.local_inactive_branches:
            self.window.show_quick_panel(["There are no branches available."], None)
        else:
            self.window.show_quick_panel(
                self.local_inactive_branches,
                self.on_selection,
                flags=sublime.MONOSPACE_FONT
                )

    def on_selection(self, branch_name_index):
        if branch_name_index == -1:
            return

        branch_name = self.local_inactive_branches[branch_name_index]
        self.git("checkout", branch_name)
        sublime.status_message("Checked out `{}` branch.".format(branch_name))
        util.view.refresh_gitsavvy(self.window.active_view())

class GsCheckoutNewBranchCommand(WindowCommand, GitCommand):

    """
    Prompt the user for a new branch name, create it, and check it out.
    """

    def run(self):
        sublime.set_timeout_async(self.run_async)

    def run_async(self, name=""):
        self.window.show_input_panel(NEW_BRANCH_PROMPT, name, self.on_done, None, None)

    def on_done(self, branch_name):
        pattern = r"^(?!\.|.*\.\..*|.*@.*|\/)[a-zA-Z0-9\-\_\/\.]+(?<!\.lock)(?<!\/)(?<!\.)\b$"
        match = re.match(pattern, branch_name)
        if not match:
            sublime.status_message("`{}` is a invalid branch name.".format(branch_name))
            sublime.set_timeout_async(self.run_async(branch_name))
            return None

        self.git("checkout", "-b", branch_name)
        sublime.status_message("Created and checked out `{}` branch.".format(branch_name))
        util.view.refresh_gitsavvy(self.window.active_view())

class GsCheckoutRemoteBranchCommand(WindowCommand, GitCommand):

    """
    Display a panel of all remote branches.  When the user makes a selection,
    create a corresponding local branch, and set it to the HEAD of the
    selected branch.
    """

    def run(self):
        sublime.set_timeout_async(self.run_async)

    def run_async(self):
        self.remote_branches = self.get_remote_branches()
        self.window.show_quick_panel(
            self.remote_branches,
            self.on_selection,
            flags=sublime.MONOSPACE_FONT
            )

    def on_selection(self, remote_branch_index):
        if remote_branch_index == -1:
            return

        remote_branch = self.remote_branches[remote_branch_index]
        local_name = remote_branch.split("/", 1)[1]
        self.git("checkout", "-b", local_name, "--track", remote_branch)
        sublime.status_message("Checked out `{}` as local branch `{}`.".format(remote_branch, local_name))
        util.view.refresh_gitsavvy(self.window.active_view())

class GsCheckoutCurrentFileCommand(WindowCommand, GitCommand):

    """
    Reset the current active file to HEAD.
    """

    def run(self):
        if self.file_path:
            self.checkout_file(self.file_path)
            sublime.status_message("Successfully checked out {} from head.".format(self.file_path))
<|endoftext|>


<commit_before>"""
    filebrowser.views

"""
import logging
import re
from datetime import datetime
from django.http import HttpResponse
from django.shortcuts import render_to_response, render
from django.template import RequestContext, loader
from django.template.loader import get_template
from django.conf import settings
#from django.core.urlresolvers import reverse
#from django.views.decorators.csrf import ensure_csrf_cookie, csrf_exempt
from .utils import get_rucio_file, get_rucio_pfns_from_guids, fetch_file, get_filebrowser_vo, \
get_filebrowser_hostname

from core.common.models import Filestable4

_logger = logging.getLogger('bigpandamon-filebrowser')

def index(request):
    """
        index -- filebrowser's default page

        :param request: Django's HTTP request
        :type request: django.http.HttpRequest

    """
    errors = {}

    ### check that all expected parameters are in URL
    expectedFields = ['guid', 'site', 'scope', 'lfn']
    for expectedField in expectedFields:
        try:
            request.GET[expectedField]
        except:
            msg = 'Missing expected GET parameter %s. ' % expectedField
            _logger.error(msg)
            if 'missingparameter' not in errors.keys():
                errors['missingparameter'] = ''
            errors['missingparameter'] += msg

    ### if all expected GET parameters are present, execute file lookup
    pfns = []
    scope = ''
    lfn = ''
    guid = ''
    site = ''
    pattern_string='^[a-zA-Z0-9.\-_]+$'
    pattern_site = '^[a-zA-Z0-9.,\-_]+$'
    pattern_guid='^(\{){0,1}[0-9a-zA-Z]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12}(\}){0,1}$'
    try:
        guid = request.GET['guid']
        if re.match(pattern_guid, guid) is None:
            guid = None
            if 'improperformat' not in errors.keys():
                errors['improperformat'] = ''
            errors['improperformat'] += 'guid: %s ' % (request.GET['guid'])
    except:
        pass
    try:
        site = request.GET['site']
        if re.match(pattern_site, site) is None:
            site = None
            if 'improperformat' not in errors.keys():
                errors['improperformat'] = ''
            errors['improperformat'] += 'site: %s ' % (request.GET['site'])
    except:
        pass
    try:
        lfn = request.GET['lfn']
        if re.match(pattern_string, lfn) is None:
            lfn = None
            if 'improperformat' not in errors.keys():
                errors['improperformat'] = ''
            errors['improperformat'] += 'lfn: %s ' % (request.GET['lfn'])
    except:
        pass
    try:
        scope = request.GET['scope']
        if re.match(pattern_string, scope) is None:
            scope = None
            if 'improperformat' not in errors.keys():
                errors['improperformat'] = ''
            errors['improperformat'] += 'scope: %s ' % (request.GET['scope'])
    except:
        pass

    ### download the file
    files = []
    dirprefix = ''
    tardir = ''
    files, errtxt, dirprefix, tardir = get_rucio_file(scope,lfn, guid)
    if not len(files):
        msg = 'File download failed. [guid=%s, site=%s, scope=%s, lfn=%s]' % \
            (guid, site, scope, lfn)
        _logger.warning(msg)
        errors['download'] = msg
    if len(errtxt):
        if 'download' not in errors:
            errors['download'] = ''
        errors['download'] += errtxt

    ### return the file page

    ### set request response data
    data = { \
        'errors': errors, \
        'pfns': pfns, \
        'files': files, \
        'dirprefix': dirprefix, \
        'tardir': tardir, \
        'scope': scope, \
        'lfn': lfn, \
        'site': site, \
        'guid': guid, \
        'viewParams' : {'MON_VO': str(get_filebrowser_vo()).upper()}, \
        'HOSTNAME': get_filebrowser_hostname() \
#        , 'new_contents': new_contents
    }
    return render_to_response('filebrowser/filebrowser_index.html', data, RequestContext(request))

def api_single_pandaid(request):
    """
        api_single_pandaid -- return log file URL for a single PanDA job

        :param request: Django's HTTP request
        :type request: django.http.HttpRequest

    """
    errors = {}

    ### check that all expected parameters are in URL
#    expectedFields = ['guid', 'site', 'scope', 'lfn']
    expectedFields = ['pandaid']
    for expectedField in expectedFields:
        try:
            if len(request.GET[expectedField]) < 1:
                msg = 'Missing expected GET parameter %s. ' % expectedField
                if 'missingparameter' not in errors.keys():
                    errors['missingparameter'] = ''
                errors['missingparameter'] += msg
        except:
            msg = 'Missing expected GET parameter %s. ' % expectedField
            _logger.error(msg)
            if 'missingparameter' not in errors.keys():
                errors['missingparameter'] = ''
            errors['missingparameter'] += msg

    ### if all expected GET parameters are present, execute file lookup
    pfns = []
    scope = ''
    lfn = ''
    guid = ''
    site = ''
    pandaid = None
    status = ''
    query = {}
    query['type'] = 'log'
    try:
        pandaid = int(request.GET['pandaid'])
    except:
        pass
    query['pandaid'] = pandaid
    file_properties = []
    try:
        file_properties = Filestable4.objects.filter(**query).values('pandaid', 'guid', \
                                'scope', 'lfn', 'destinationse', 'status')
    except:
        pass

    if len(file_properties):
        file_properties = file_properties[0]
        try:
            guid = file_properties['guid']
        except:
            pass
        try:
            site = file_properties['destinationse']
        except:
            pass
        try:
            lfn = file_properties['lfn']
        except:
            pass
        try:
            scope = file_properties['scope']
        except:
            pass
        try:
            status = file_properties['status']
        except:
            pass

        if 'missingparameter' not in errors.keys():
            pfns, errtxt = get_rucio_pfns_from_guids(guids=[guid], site=[site], \
                        lfns=[lfn], scopes=[scope])
            if len(errtxt):
                if 'lookup' not in errors:
                    errors['lookup'] = ''
                errors['lookup'] += errtxt

        ### download the file
        files = []
        dirprefix = ''
        tardir = ''
        if len(pfns):
            pfn = pfns[0]
            files, errtxt, dirprefix, tardir = fetch_file(pfn, guid, unpack=False, listfiles=False)
            if not len(pfns):
                msg = 'File download failed. [pfn=%s guid=%s, site=%s, scope=%s, lfn=%s]' % \
                    (pfn, guid, site, scope, lfn)
                _logger.warning(msg)
                errors['download'] = msg
            if len(errtxt):
                if 'download' in errors:
                    errors['download'] += errtxt
    else: # file not found in DB
        if 'lookup' not in errors:
            errors['lookup'] = ''
        errors['lookup'] += 'Log file for this job has not been found. '
    ### return the file page

    url = None
    data = { \
        'pandaid': pandaid, \
        'url': url, \
        'errors': errors, \
        'pfns': pfns, \
        'scope': scope, \
        'lfn': lfn, \
        'site': site, \
        'guid': guid, \
        'status': status, \
        'timestamp': datetime.utcnow().isoformat() \
    }
    if not len(errors):
        url = 'http://' + get_filebrowser_hostname() + \
                    settings.MEDIA_URL + dirprefix + '/' + lfn
        data['url'] = url
        ### set request response data
        return render_to_response('filebrowser/filebrowser_api_single_pandaid.html', {'data': data}, RequestContext(request))
    elif 'pandaid' not in request.GET.keys() or pandaid == None:
        t = get_template('filebrowser/filebrowser_api_single_pandaid.html')
        context = RequestContext(request, {'data':data})
        return HttpResponse(t.render(context), status=400)
    elif not len(file_properties):
        t = get_template('filebrowser/filebrowser_api_single_pandaid.html')
        context = RequestContext(request, {'data':data})
        return HttpResponse(t.render(context), status=404)
    else:
        t = get_template('filebrowser/filebrowser_api_single_pandaid.html')
        context = RequestContext(request, {'data':data})
        return HttpResponse(t.render(context), status=400)

<commit_msg>fix panda log<commit_after>"""
    filebrowser.views

"""
import logging
import re
from datetime import datetime
from django.http import HttpResponse
from django.shortcuts import render_to_response, render
from django.template import RequestContext, loader
from django.template.loader import get_template
from django.conf import settings
#from django.core.urlresolvers import reverse
#from django.views.decorators.csrf import ensure_csrf_cookie, csrf_exempt
from .utils import get_rucio_file, get_rucio_pfns_from_guids, fetch_file, get_filebrowser_vo, \
get_filebrowser_hostname

from core.common.models import Filestable4

_logger = logging.getLogger('bigpandamon-filebrowser')

def index(request):
    """
        index -- filebrowser's default page

        :param request: Django's HTTP request
        :type request: django.http.HttpRequest

    """
    errors = {}

    ### check that all expected parameters are in URL
    expectedFields = ['guid', 'site', 'scope', 'lfn']
    for expectedField in expectedFields:
        try:
            request.GET[expectedField]
        except:
            msg = 'Missing expected GET parameter %s. ' % expectedField
            _logger.error(msg)
            if 'missingparameter' not in errors.keys():
                errors['missingparameter'] = ''
            errors['missingparameter'] += msg

    ### if all expected GET parameters are present, execute file lookup
    pfns = []
    scope = ''
    lfn = ''
    guid = ''
    site = ''
    pattern_string='^[a-zA-Z0-9.\-_]+$'
    pattern_site = '^[a-zA-Z0-9.,\-_]+$'
    pattern_guid='^(\{){0,1}[0-9a-zA-Z]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12}(\}){0,1}$'
    try:
        guid = request.GET['guid']
        if re.match(pattern_guid, guid) is None:
            guid = None
            if 'improperformat' not in errors.keys():
                errors['improperformat'] = ''
            errors['improperformat'] += 'guid: %s ' % (request.GET['guid'])
    except:
        pass
    try:
        site = request.GET['site']
        if re.match(pattern_site, site) is None:
            site = None
            if 'improperformat' not in errors.keys():
                errors['improperformat'] = ''
            errors['improperformat'] += 'site: %s ' % (request.GET['site'])
    except:
        pass
    try:
        lfn = request.GET['lfn']
        if re.match(pattern_string, lfn) is None:
            lfn = None
            if 'improperformat' not in errors.keys():
                errors['improperformat'] = ''
            errors['improperformat'] += 'lfn: %s ' % (request.GET['lfn'])
    except:
        pass
    try:
        scope = request.GET['scope']
        if re.match(pattern_string, scope) is None:
            scope = None
            if 'improperformat' not in errors.keys():
                errors['improperformat'] = ''
            errors['improperformat'] += 'scope: %s ' % (request.GET['scope'])
    except:
        pass

    ### download the file
    files = []
    dirprefix = ''
    tardir = ''
    files, errtxt, dirprefix, tardir = get_rucio_file(scope,lfn, guid)
    if not len(files):
        msg = 'File download failed. [guid=%s, site=%s, scope=%s, lfn=%s]' % \
            (guid, site, scope, lfn)
        _logger.warning(msg)
        errors['download'] = msg
    if len(errtxt):
        if 'download' not in errors:
            errors['download'] = ''
        errors['download'] += errtxt

    ### return the file page

    ### set request response data
    data = { \
        'errors': errors, \
        'pfns': pfns, \
        'files': files, \
        'dirprefix': dirprefix, \
        'tardir': tardir, \
        'scope': scope, \
        'lfn': lfn, \
        'site': site, \
        'guid': guid, \
        'MEDIA_URL': settings.MEDIA_URL, \
        'viewParams' : {'MON_VO': str(get_filebrowser_vo()).upper()}, \
        'HOSTNAME': get_filebrowser_hostname() \
#        , 'new_contents': new_contents
    }
    return render_to_response('filebrowser/filebrowser_index.html', data, RequestContext(request))

def api_single_pandaid(request):
    """
        api_single_pandaid -- return log file URL for a single PanDA job

        :param request: Django's HTTP request
        :type request: django.http.HttpRequest

    """
    errors = {}

    ### check that all expected parameters are in URL
#    expectedFields = ['guid', 'site', 'scope', 'lfn']
    expectedFields = ['pandaid']
    for expectedField in expectedFields:
        try:
            if len(request.GET[expectedField]) < 1:
                msg = 'Missing expected GET parameter %s. ' % expectedField
                if 'missingparameter' not in errors.keys():
                    errors['missingparameter'] = ''
                errors['missingparameter'] += msg
        except:
            msg = 'Missing expected GET parameter %s. ' % expectedField
            _logger.error(msg)
            if 'missingparameter' not in errors.keys():
                errors['missingparameter'] = ''
            errors['missingparameter'] += msg

    ### if all expected GET parameters are present, execute file lookup
    pfns = []
    scope = ''
    lfn = ''
    guid = ''
    site = ''
    pandaid = None
    status = ''
    query = {}
    query['type'] = 'log'
    try:
        pandaid = int(request.GET['pandaid'])
    except:
        pass
    query['pandaid'] = pandaid
    file_properties = []
    try:
        file_properties = Filestable4.objects.filter(**query).values('pandaid', 'guid', \
                                'scope', 'lfn', 'destinationse', 'status')
    except:
        pass

    if len(file_properties):
        file_properties = file_properties[0]
        try:
            guid = file_properties['guid']
        except:
            pass
        try:
            site = file_properties['destinationse']
        except:
            pass
        try:
            lfn = file_properties['lfn']
        except:
            pass
        try:
            scope = file_properties['scope']
        except:
            pass
        try:
            status = file_properties['status']
        except:
            pass

        if 'missingparameter' not in errors.keys():
            pfns, errtxt = get_rucio_pfns_from_guids(guids=[guid], site=[site], \
                        lfns=[lfn], scopes=[scope])
            if len(errtxt):
                if 'lookup' not in errors:
                    errors['lookup'] = ''
                errors['lookup'] += errtxt

        ### download the file
        files = []
        dirprefix = ''
        tardir = ''
        if len(pfns):
            pfn = pfns[0]
            files, errtxt, dirprefix, tardir = fetch_file(pfn, guid, unpack=False, listfiles=False)
            if not len(pfns):
                msg = 'File download failed. [pfn=%s guid=%s, site=%s, scope=%s, lfn=%s]' % \
                    (pfn, guid, site, scope, lfn)
                _logger.warning(msg)
                errors['download'] = msg
            if len(errtxt):
                if 'download' in errors:
                    errors['download'] += errtxt
    else: # file not found in DB
        if 'lookup' not in errors:
            errors['lookup'] = ''
        errors['lookup'] += 'Log file for this job has not been found. '
    ### return the file page

    url = None
    data = { \
        'pandaid': pandaid, \
        'url': url, \
        'errors': errors, \
        'pfns': pfns, \
        'scope': scope, \
        'lfn': lfn, \
        'site': site, \
        'guid': guid, \
        'status': status, \
        'timestamp': datetime.utcnow().isoformat() \
    }
    if not len(errors):
        url = 'http://' + get_filebrowser_hostname() + \
                    settings.MEDIA_URL + dirprefix + '/' + lfn
        data['url'] = url
        ### set request response data
        return render_to_response('filebrowser/filebrowser_api_single_pandaid.html', {'data': data}, RequestContext(request))
    elif 'pandaid' not in request.GET.keys() or pandaid == None:
        t = get_template('filebrowser/filebrowser_api_single_pandaid.html')
        context = RequestContext(request, {'data':data})
        return HttpResponse(t.render(context), status=400)
    elif not len(file_properties):
        t = get_template('filebrowser/filebrowser_api_single_pandaid.html')
        context = RequestContext(request, {'data':data})
        return HttpResponse(t.render(context), status=404)
    else:
        t = get_template('filebrowser/filebrowser_api_single_pandaid.html')
        context = RequestContext(request, {'data':data})
        return HttpResponse(t.render(context), status=400)

<|endoftext|>


<commit_before>import pdb
import inspect

def add(x, y):
    return x + y

def cached(func):
    def cachedfunc(*pargs, **kwargs):
        # pdb.set_trace()
        if (pargs, tuple(kwargs.items())) in func.__dict__:
            return func.__dict__[(pargs, tuple(kwargs.items()))]
        result = func(*pargs, **kwargs)
        func.__dict__[(pargs, tuple(kwargs.items()))] = result
        return result
    cachedfunc.__name__ = func.__name__
    cachedfunc.__doc__ = func.__doc__
    return cachedfunc

@cached
def add2(x, y):
    """
    Computes the sum and returns the value

    :param x:
    :param y:
    :return: The sum of x and y
    """
    return x + y

print add2(2, 3) # value is computed and cached
print add2(3, 2) # value is computed and cached
print add2(2, 3) # value is returned from the cache

>>> add2.func_closure
(<cell at 0x24994b0: function object at 0x23ef398>,)

>>> add2.func_closure[0].cell_contents
<function add2 at 0x23ef398>

>>> add2.func_closure[0].cell_contents.__dict__
{((3, 2), ()): 5, ((2, 3), ()): 5}

>>> inspect.isfunction(add2.func_closure[0].cell_contents)
True
<commit_msg>Update cached_func.py<commit_after>import pdb
import inspect
import os

def add(x, y):
    return x + y

def cached(func):
    def cachedfunc(*pargs, **kwargs):
        if os.environ.get('DEBUG_CACHED'):
            pdb.set_trace()
        if (pargs, tuple(kwargs.items())) in func.__dict__:
            return func.__dict__[(pargs, tuple(kwargs.items()))]
        result = func(*pargs, **kwargs)
        func.__dict__[(pargs, tuple(kwargs.items()))] = result
        return result
    cachedfunc.__name__ = func.__name__
    cachedfunc.__doc__ = func.__doc__
    return cachedfunc

@cached
def add2(x, y):
    """
    Computes the sum and returns the value

    :param x:
    :param y:
    :return: The sum of x and y
    """
    return x + y

os.environ['DEBUG_CACHED'] = "1"

print add2(2, 3) # value is computed and cached
5

print add2.func_closure[0].cell_contents.__dict__
{((2, 3), ()): 5}

del os.environ['DEBUG_CACHED']

print add2(3, 2) # value is computed and cached
5

print add2.func_closure[0].cell_contents.__dict__
{((3, 2), ()): 5, ((2, 3), ()): 5}

os.environ['DEBUG_CACHED'] = "1"

print add2(2, 3) # value is returned from the cache
5

print add2.func_closure[0].cell_contents.__dict__
{((3, 2), ()): 5, ((2, 3), ()): 5}

"""
>>> add2.func_closure
(<cell at 0x24994b0: function object at 0x23ef398>,)

>>> add2.func_closure[0].cell_contents
<function add2 at 0x23ef398>

>>> add2.func_closure[0].cell_contents.__dict__
{((3, 2), ()): 5, ((2, 3), ()): 5}

>>> inspect.isfunction(add2.func_closure[0].cell_contents)
True
"""
<|endoftext|>


<commit_before># !usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under a 3-clause BSD license.
#
# @Author: Brian Cherinka
# @Date:   2017-09-20 10:31:11
# @Last modified by:   Brian Cherinka
# @Last Modified time: 2017-09-20 16:57:51

from __future__ import print_function, division, absolute_import
from collections import OrderedDict
from six import with_metaclass

class MetaDataModel(type):
    ''' MetaClass to construct a new DataModelList class '''
    def __new__(cls, name, parents, dict):
        if 'base' in dict:
            item = dict['base'].items()[0]
            dict['base_name'] = item[0].strip()
            dict['base_model'] = item[1]
        return super(MetaDataModel, cls).__new__(cls, name, parents, dict)

class DataModelList(with_metaclass(MetaDataModel, OrderedDict)):
    ''' Base Class for a list of DataModels '''

    def __init__(self, models=None):

        if models is not None:
            assert all([isinstance(model, self.base_model) for model in models]), \
                'values must be {0} instances.'.format(self.base_name)
            OrderedDict.__init__(self, ((model.release, model) for model in models))
        else:
            OrderedDict.__init__(self, {})

    def __setitem__(self, key, value):
        """Sets a new datamodel."""

        assert isinstance(value, self.base_model), 'value must be a {0}'.format(self.base_name)

        super(DataModelList, self).__setitem__(key, value)

    def __getitem__(self, release):
        """Returns model based on release and aliases."""

        if release in self.keys():
            return super(DataModelList, self).__getitem__(release)

        for model in self.values():
            if release in model.aliases:
                return model

        raise KeyError('cannot find release or alias {0!r}'.format(release))

    def __repr__(self):

        return repr([xx for xx in self.values()])

    def add_datamodel(self, dm):
        """Adds a new datamodel. Uses its release as key."""

        assert isinstance(dm, self.base_model), 'value must be a {0}'.format(self.base_name)

        self[dm.release] = dm
<commit_msg>fixed dict problem in PY3<commit_after># !usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under a 3-clause BSD license.
#
# @Author: Brian Cherinka
# @Date:   2017-09-20 10:31:11
# @Last modified by:   Brian Cherinka
# @Last Modified time: 2017-09-20 16:57:51

from __future__ import print_function, division, absolute_import
from collections import OrderedDict
from six import with_metaclass

class MetaDataModel(type):
    ''' MetaClass to construct a new DataModelList class '''
    def __new__(cls, name, parents, dict):
        if 'base' in dict:
            item = list(dict['base'].items())[0]
            dict['base_name'] = item[0].strip()
            dict['base_model'] = item[1]
        return super(MetaDataModel, cls).__new__(cls, name, parents, dict)

class DataModelList(with_metaclass(MetaDataModel, OrderedDict)):
    ''' Base Class for a list of DataModels '''

    def __init__(self, models=None):

        if models is not None:
            assert all([isinstance(model, self.base_model) for model in models]), \
                'values must be {0} instances.'.format(self.base_name)
            OrderedDict.__init__(self, ((model.release, model) for model in models))
        else:
            OrderedDict.__init__(self, {})

    def __setitem__(self, key, value):
        """Sets a new datamodel."""

        assert isinstance(value, self.base_model), 'value must be a {0}'.format(self.base_name)

        super(DataModelList, self).__setitem__(key, value)

    def __getitem__(self, release):
        """Returns model based on release and aliases."""

        if release in self.keys():
            return super(DataModelList, self).__getitem__(release)

        for model in self.values():
            if release in model.aliases:
                return model

        raise KeyError('cannot find release or alias {0!r}'.format(release))

    def __repr__(self):

        return repr([xx for xx in self.values()])

    def add_datamodel(self, dm):
        """Adds a new datamodel. Uses its release as key."""

        assert isinstance(dm, self.base_model), 'value must be a {0}'.format(self.base_name)

        self[dm.release] = dm
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from django.forms.util import flatatt
from django.forms.widgets import DateTimeInput
from django.utils import translation
from django.utils.safestring import mark_safe
from django.utils.html import conditional_escape

try:
    import json
except ImportError:
    from django.utils import simplejson as json
try:
    from django.utils.encoding import force_unicode as force_text
except ImportError:  # python3
    from django.utils.encoding import force_text

class DateTimePicker(DateTimeInput):
    class Media:
        class JsFiles(object):
            def __iter__(self):
                yield 'bootstrap3_datetime/js/moment.min.js'
                yield 'bootstrap3_datetime/js/bootstrap-datetimepicker.min.js'
                lang = translation.get_language()
                if lang:
                    lang = lang.lower()
                    #There is language name that length>2 *or* contains uppercase.
                    lang_map = {
                        'ar-ma': 'ar-ma',
                        'en-au': 'en-au',
                        'en-ca': 'en-ca',
                        'en-gb': 'en-gb',
                        'en-us': 'en-us',
                        'fa-ir': 'fa-ir',
                        'fr-ca': 'fr-ca',
                        'ms-my': 'ms-my',
                        'pt-br': 'bt-BR',
                        'rs-latin': 'rs-latin',
                        'tzm-la': 'tzm-la',
                        'tzm': 'tzm',
                        'zh-cn': 'zh-CN',
                        'zh-tw': 'zh-TW',
                        'zh-hk': 'zh-TW',
                    }
                    if len(lang) > 2:
                        lang = lang_map.get(lang, 'en-us')
                    if lang not in ('en', 'en-us'):
                        yield 'bootstrap3_datetime/js/locales/bootstrap-datetimepicker.%s.js' % (lang)

        js = JsFiles()
        css = {'all': ('bootstrap3_datetime/css/bootstrap-datetimepicker.min.css',), }

    # http://momentjs.com/docs/#/parsing/string-format/
    # http://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
    format_map = (('DDD', r'%j'),
                  ('DD', r'%d'),
                  ('MMMM', r'%B'),
                  ('MMM', r'%b'),
                  ('MM', r'%m'),
                  ('YYYY', r'%Y'),
                  ('YY', r'%y'),
                  ('HH', r'%H'),
                  ('hh', r'%I'),
                  ('mm', r'%M'),
                  ('ss', r'%S'),
                  ('a', r'%p'),
                  ('ZZ', r'%z'),
    )

    @classmethod
    def conv_datetime_format_py2js(cls, format):
        for js, py in cls.format_map:
            format = format.replace(py, js)
        return format

    @classmethod
    def conv_datetime_format_js2py(cls, format):
        for js, py in cls.format_map:
            format = format.replace(js, py)
        return format

    html_template = '''

            <input%(input_attrs)s/>

'''

    js_template = '''
        '''

    def __init__(self, attrs=None, format=None, options=None, div_attrs=None, icon_attrs=None):
        if not icon_attrs:
            icon_attrs = {'class': 'glyphicon glyphicon-calendar'}
        if not div_attrs:
            div_attrs = {'class': 'input-group date'}
        if format is None and options and options.get('format'):
            format = self.conv_datetime_format_js2py(options.get('format'))
        super(DateTimePicker, self).__init__(attrs, format)
        if 'class' not in self.attrs:
            self.attrs['class'] = 'form-control'
        self.div_attrs = div_attrs and div_attrs.copy() or {}
        self.icon_attrs = icon_attrs and icon_attrs.copy() or {}
        self.picker_id = self.div_attrs.get('id') or None
        if options == False:  # datetimepicker will not be initalized only when options is False
            self.options = False
        else:
            self.options = options and options.copy() or {}
            self.options['language'] = translation.get_language()
            if format and not self.options.get('format') and not self.attrs.get('date-format'):
                self.options['format'] = self.conv_datetime_format_py2js(format)

    def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        input_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
        if value != '':
            # Only add the 'value' attribute if a value is non-empty.
            input_attrs['value'] = force_text(self._format_value(value))
        input_attrs = dict([(key, conditional_escape(val)) for key, val in input_attrs.items()])  # python2.6 compatible
        if not self.picker_id:
            self.picker_id = input_attrs.get('id', '') + '_picker'
        self.div_attrs['id'] = self.picker_id
        picker_id = conditional_escape(self.picker_id)
        div_attrs = dict(
            [(key, conditional_escape(val)) for key, val in self.div_attrs.items()])  # python2.6 compatible
        icon_attrs = dict([(key, conditional_escape(val)) for key, val in self.icon_attrs.items()])
        html = self.html_template % dict(div_attrs=flatatt(div_attrs),
                                         input_attrs=flatatt(input_attrs),
                                         icon_attrs=flatatt(icon_attrs))
        if not self.options:
            js = ''
        else:
            js = self.js_template % dict(picker_id=picker_id,
                                         options=json.dumps(self.options or {}))
        return mark_safe(force_text(html + js))

<commit_msg>Move option "language" in the render method because render called on every request<commit_after># -*- coding: utf-8 -*-
from django.forms.util import flatatt
from django.forms.widgets import DateTimeInput
from django.utils import translation
from django.utils.safestring import mark_safe
from django.utils.html import conditional_escape

try:
    import json
except ImportError:
    from django.utils import simplejson as json
try:
    from django.utils.encoding import force_unicode as force_text
except ImportError:  # python3
    from django.utils.encoding import force_text

class DateTimePicker(DateTimeInput):
    class Media:
        class JsFiles(object):
            def __iter__(self):
                yield 'bootstrap3_datetime/js/moment.min.js'
                yield 'bootstrap3_datetime/js/bootstrap-datetimepicker.min.js'
                lang = translation.get_language()
                if lang:
                    lang = lang.lower()
                    #There is language name that length>2 *or* contains uppercase.
                    lang_map = {
                        'ar-ma': 'ar-ma',
                        'en-au': 'en-au',
                        'en-ca': 'en-ca',
                        'en-gb': 'en-gb',
                        'en-us': 'en-us',
                        'fa-ir': 'fa-ir',
                        'fr-ca': 'fr-ca',
                        'ms-my': 'ms-my',
                        'pt-br': 'bt-BR',
                        'rs-latin': 'rs-latin',
                        'tzm-la': 'tzm-la',
                        'tzm': 'tzm',
                        'zh-cn': 'zh-CN',
                        'zh-tw': 'zh-TW',
                        'zh-hk': 'zh-TW',
                    }
                    if len(lang) > 2:
                        lang = lang_map.get(lang, 'en-us')
                    if lang not in ('en', 'en-us'):
                        yield 'bootstrap3_datetime/js/locales/bootstrap-datetimepicker.%s.js' % (lang)

        js = JsFiles()
        css = {'all': ('bootstrap3_datetime/css/bootstrap-datetimepicker.min.css',), }

    # http://momentjs.com/docs/#/parsing/string-format/
    # http://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
    format_map = (('DDD', r'%j'),
                  ('DD', r'%d'),
                  ('MMMM', r'%B'),
                  ('MMM', r'%b'),
                  ('MM', r'%m'),
                  ('YYYY', r'%Y'),
                  ('YY', r'%y'),
                  ('HH', r'%H'),
                  ('hh', r'%I'),
                  ('mm', r'%M'),
                  ('ss', r'%S'),
                  ('a', r'%p'),
                  ('ZZ', r'%z'),
    )

    @classmethod
    def conv_datetime_format_py2js(cls, format):
        for js, py in cls.format_map:
            format = format.replace(py, js)
        return format

    @classmethod
    def conv_datetime_format_js2py(cls, format):
        for js, py in cls.format_map:
            format = format.replace(js, py)
        return format

    html_template = '''

            <input%(input_attrs)s/>

'''

    js_template = '''
        '''

    def __init__(self, attrs=None, format=None, options=None, div_attrs=None, icon_attrs=None):
        if not icon_attrs:
            icon_attrs = {'class': 'glyphicon glyphicon-calendar'}
        if not div_attrs:
            div_attrs = {'class': 'input-group date'}
        if format is None and options and options.get('format'):
            format = self.conv_datetime_format_js2py(options.get('format'))
        super(DateTimePicker, self).__init__(attrs, format)
        if 'class' not in self.attrs:
            self.attrs['class'] = 'form-control'
        self.div_attrs = div_attrs and div_attrs.copy() or {}
        self.icon_attrs = icon_attrs and icon_attrs.copy() or {}
        self.picker_id = self.div_attrs.get('id') or None
        if options == False:  # datetimepicker will not be initalized only when options is False
            self.options = False
        else:
            self.options = options and options.copy() or {}
            if format and not self.options.get('format') and not self.attrs.get('date-format'):
                self.options['format'] = self.conv_datetime_format_py2js(format)

    def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        input_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
        if value != '':
            # Only add the 'value' attribute if a value is non-empty.
            input_attrs['value'] = force_text(self._format_value(value))
        input_attrs = dict([(key, conditional_escape(val)) for key, val in input_attrs.items()])  # python2.6 compatible
        if not self.picker_id:
            self.picker_id = input_attrs.get('id', '') + '_picker'
        self.div_attrs['id'] = self.picker_id
        picker_id = conditional_escape(self.picker_id)
        div_attrs = dict(
            [(key, conditional_escape(val)) for key, val in self.div_attrs.items()])  # python2.6 compatible
        icon_attrs = dict([(key, conditional_escape(val)) for key, val in self.icon_attrs.items()])
        html = self.html_template % dict(div_attrs=flatatt(div_attrs),
                                         input_attrs=flatatt(input_attrs),
                                         icon_attrs=flatatt(icon_attrs))
        if self.options:
            self.options['language'] = translation.get_language()
            js = self.js_template % dict(picker_id=picker_id,
                                         options=json.dumps(self.options or {}))
        else:
            js = ''
        return mark_safe(force_text(html + js))
<|endoftext|>