File: misc.py

package info (click to toggle)
python-astropy 1.3-8~bpo8%2B2
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 44,292 kB
  • sloc: ansic: 160,360; python: 137,322; sh: 11,493; lex: 7,638; yacc: 4,956; xml: 1,796; makefile: 474; cpp: 364
file content (1104 lines) | stat: -rw-r--r-- 38,454 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
A "grab bag" of relatively small general-purpose utilities that don't have
a clear module/package to live in.
"""

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)


import abc
import contextlib
import difflib
import inspect
import json
import os
import signal
import sys
import traceback
import unicodedata
import locale
import threading

from contextlib import contextmanager
from collections import defaultdict, OrderedDict

from ..extern import six
from ..extern.six.moves import urllib, range, zip_longest


__all__ = ['isiterable', 'silence', 'format_exception', 'NumpyRNGContext',
           'find_api_page', 'is_path_hidden', 'walk_skip_hidden',
           'JsonCustomEncoder', 'indent', 'InheritDocstrings',
           'OrderedDescriptor', 'OrderedDescriptorContainer', 'set_locale',
           'ShapedLikeNDArray', 'check_broadcast', 'IncompatibleShapeError']


def isiterable(obj):
    """Returns `True` if the given object is iterable."""

    try:
        iter(obj)
        return True
    except TypeError:
        return False


def indent(s, shift=1, width=4):
    """Indent a block of text.  The indentation is applied to each line."""

    indented = '\n'.join(' ' * (width * shift) + l if l else ''
                         for l in s.splitlines())
    if s[-1] == '\n':
        indented += '\n'

    return indented


class _DummyFile(object):
    """A noop writeable object."""

    def write(self, s):
        pass


@contextlib.contextmanager
def silence():
    """A context manager that silences sys.stdout and sys.stderr."""

    old_stdout = sys.stdout
    old_stderr = sys.stderr
    sys.stdout = _DummyFile()
    sys.stderr = _DummyFile()
    yield
    sys.stdout = old_stdout
    sys.stderr = old_stderr


def format_exception(msg, *args, **kwargs):
    """
    Given an exception message string, uses new-style formatting arguments
    ``{filename}``, ``{lineno}``, ``{func}`` and/or ``{text}`` to fill in
    information about the exception that occurred.  For example:

        try:
            1/0
        except:
            raise ZeroDivisionError(
                format_except('A divide by zero occurred in {filename} at '
                              'line {lineno} of function {func}.'))

    Any additional positional or keyword arguments passed to this function are
    also used to format the message.

    .. note::
        This uses `sys.exc_info` to gather up the information needed to fill
        in the formatting arguments. Python 2.x and 3.x have slightly
        different behavior regarding `sys.exc_info` (the latter will not
        carry it outside a handled exception), so it's not wise to use this
        outside of an ``except`` clause - if it is, this will substitute
        '<unkown>' for the 4 formatting arguments.
    """

    tb = traceback.extract_tb(sys.exc_info()[2], limit=1)
    if len(tb) > 0:
        filename, lineno, func, text = tb[0]
    else:
        filename = lineno = func = text = '<unknown>'

    return msg.format(*args, filename=filename, lineno=lineno, func=func,
                      text=text, **kwargs)


class NumpyRNGContext(object):
    """
    A context manager (for use with the ``with`` statement) that will seed the
    numpy random number generator (RNG) to a specific value, and then restore
    the RNG state back to whatever it was before.

    This is primarily intended for use in the astropy testing suit, but it
    may be useful in ensuring reproducibility of Monte Carlo simulations in a
    science context.

    Parameters
    ----------
    seed : int
        The value to use to seed the numpy RNG

    Examples
    --------
    A typical use case might be::

        with NumpyRNGContext(<some seed value you pick>):
            from numpy import random

            randarr = random.randn(100)
            ... run your test using `randarr` ...

        #Any code using numpy.random at this indent level will act just as it
        #would have if it had been before the with statement - e.g. whatever
        #the default seed is.


    """
    def __init__(self, seed):
        self.seed = seed

    def __enter__(self):
        from numpy import random

        self.startstate = random.get_state()
        random.seed(self.seed)

    def __exit__(self, exc_type, exc_value, traceback):
        from numpy import random

        random.set_state(self.startstate)


def find_api_page(obj, version=None, openinbrowser=True, timeout=None):
    """
    Determines the URL of the API page for the specified object, and
    optionally open that page in a web browser.

    .. note::
        You must be connected to the internet for this to function even if
        ``openinbrowser`` is `False`, unless you provide a local version of
        the documentation to ``version`` (e.g., ``file:///path/to/docs``).

    Parameters
    ----------
    obj
        The object to open the docs for or its fully-qualified name
        (as a str).
    version : str
        The doc version - either a version number like '0.1', 'dev' for
        the development/latest docs, or a URL to point to a specific
        location that should be the *base* of the documentation. Defaults to
        latest if you are on aren't on a release, otherwise, the version you
        are on.
    openinbrowser : bool
        If `True`, the `webbrowser` package will be used to open the doc
        page in a new web browser window.
    timeout : number, optional
        The number of seconds to wait before timing-out the query to
        the astropy documentation.  If not given, the default python
        stdlib timeout will be used.

    Returns
    -------
    url : str
        The loaded URL

    Raises
    ------
    ValueError
        If the documentation can't be found

    """
    import webbrowser

    from zlib import decompress

    if (not isinstance(obj, six.string_types) and
            hasattr(obj, '__module__') and
            hasattr(obj, '__name__')):
        obj = obj.__module__ + '.' + obj.__name__
    elif inspect.ismodule(obj):
        obj = obj.__name__

    if version is None:
        from .. import version

        if version.release:
            version = 'v' + version.version
        else:
            version = 'dev'

    if '://' in version:
        if version.endswith('index.html'):
            baseurl = version[:-10]
        elif version.endswith('/'):
            baseurl = version
        else:
            baseurl = version + '/'
    elif version == 'dev' or version == 'latest':
        baseurl = 'http://devdocs.astropy.org/'
    else:
        baseurl = 'http://docs.astropy.org/en/{vers}/'.format(vers=version)

    if timeout is None:
        uf = urllib.request.urlopen(baseurl + 'objects.inv')
    else:
        uf = urllib.request.urlopen(baseurl + 'objects.inv', timeout=timeout)

    try:
        oiread = uf.read()

        # need to first read/remove the first four lines, which have info before
        # the compressed section with the actual object inventory
        idx = -1
        headerlines = []
        for _ in range(4):
            oldidx = idx
            idx = oiread.index(b'\n', oldidx + 1)
            headerlines.append(oiread[(oldidx+1):idx].decode('utf-8'))

        # intersphinx version line, project name, and project version
        ivers, proj, vers, compr  = headerlines
        if 'The remainder of this file is compressed using zlib' not in compr:
            raise ValueError('The file downloaded from {0} does not seem to be'
                             'the usual Sphinx objects.inv format.  Maybe it '
                             'has changed?'.format(baseurl + 'objects.inv'))

        compressed = oiread[(idx+1):]
    finally:
        uf.close()

    decompressed = decompress(compressed).decode('utf-8')

    resurl = None

    for l in decompressed.strip().splitlines():
        ls = l.split()
        name = ls[0]
        loc = ls[3]
        if loc.endswith('$'):
            loc = loc[:-1] + name

        if name == obj:
            resurl = baseurl + loc
            break

    if resurl is None:
        raise ValueError('Could not find the docs for the object {obj}'.format(obj=obj))
    elif openinbrowser:
        webbrowser.open(resurl)

    return resurl


def signal_number_to_name(signum):
    """
    Given an OS signal number, returns a signal name.  If the signal
    number is unknown, returns ``'UNKNOWN'``.
    """
    # Since these numbers and names are platform specific, we use the
    # builtin signal module and build a reverse mapping.

    signal_to_name_map = dict((k, v) for v, k in six.iteritems(signal.__dict__)
                              if v.startswith('SIG'))

    return signal_to_name_map.get(signum, 'UNKNOWN')


if sys.platform == 'win32':
    import ctypes

    def _has_hidden_attribute(filepath):
        """
        Returns True if the given filepath has the hidden attribute on
        MS-Windows.  Based on a post here:
        http://stackoverflow.com/questions/284115/cross-platform-hidden-file-detection
        """
        if isinstance(filepath, bytes):
            filepath = filepath.decode(sys.getfilesystemencoding())
        try:
            attrs = ctypes.windll.kernel32.GetFileAttributesW(filepath)
            assert attrs != -1
            result = bool(attrs & 2)
        except (AttributeError, AssertionError):
            result = False
        return result
else:
    def _has_hidden_attribute(filepath):
        return False


def is_path_hidden(filepath):
    """
    Determines if a given file or directory is hidden.

    Parameters
    ----------
    filepath : str
        The path to a file or directory

    Returns
    -------
    hidden : bool
        Returns `True` if the file is hidden
    """
    name = os.path.basename(os.path.abspath(filepath))
    if isinstance(name, bytes):
        is_dotted = name.startswith(b'.')
    else:
        is_dotted = name.startswith('.')
    return is_dotted or _has_hidden_attribute(filepath)


def walk_skip_hidden(top, onerror=None, followlinks=False):
    """
    A wrapper for `os.walk` that skips hidden files and directories.

    This function does not have the parameter ``topdown`` from
    `os.walk`: the directories must always be recursed top-down when
    using this function.

    See also
    --------
    os.walk : For a description of the parameters
    """
    for root, dirs, files in os.walk(
            top, topdown=True, onerror=onerror,
            followlinks=followlinks):
        # These lists must be updated in-place so os.walk will skip
        # hidden directories
        dirs[:] = [d for d in dirs if not is_path_hidden(d)]
        files[:] = [f for f in files if not is_path_hidden(f)]
        yield root, dirs, files


class JsonCustomEncoder(json.JSONEncoder):
    """Support for data types that JSON default encoder
    does not do.

    This includes:

        * Numpy array or number
        * Complex number
        * Set
        * Bytes (Python 3)

    Examples
    --------
    >>> import json
    >>> import numpy as np
    >>> from astropy.utils.misc import JsonCustomEncoder
    >>> json.dumps(np.arange(3), cls=JsonCustomEncoder)
    '[0, 1, 2]'

    """
    def default(self, obj):
        import numpy as np
        if isinstance(obj, (np.ndarray, np.number)):
            return obj.tolist()
        elif isinstance(obj, (complex, np.complex)):
            return [obj.real, obj.imag]
        elif isinstance(obj, set):
            return list(obj)
        elif isinstance(obj, bytes):  # pragma: py3
            return obj.decode()
        return json.JSONEncoder.default(self, obj)


def strip_accents(s):
    """
    Remove accents from a Unicode string.

    This helps with matching "ångström" to "angstrom", for example.
    """
    return ''.join(
        c for c in unicodedata.normalize('NFD', s)
        if unicodedata.category(c) != 'Mn')


def did_you_mean(s, candidates, n=3, cutoff=0.8, fix=None):
    """
    When a string isn't found in a set of candidates, we can be nice
    to provide a list of alternatives in the exception.  This
    convenience function helps to format that part of the exception.

    Parameters
    ----------
    s : str

    candidates : sequence of str or dict of str keys

    n : int
        The maximum number of results to include.  See
        `difflib.get_close_matches`.

    cutoff : float
        In the range [0, 1]. Possibilities that don't score at least
        that similar to word are ignored.  See
        `difflib.get_close_matches`.

    fix : callable
        A callable to modify the results after matching.  It should
        take a single string and return a sequence of strings
        containing the fixed matches.

    Returns
    -------
    message : str
        Returns the string "Did you mean X, Y, or Z?", or the empty
        string if no alternatives were found.
    """
    if isinstance(s, six.text_type):
        s = strip_accents(s)
    s_lower = s.lower()

    # Create a mapping from the lower case name to all capitalization
    # variants of that name.
    candidates_lower = {}
    for candidate in candidates:
        candidate_lower = candidate.lower()
        candidates_lower.setdefault(candidate_lower, [])
        candidates_lower[candidate_lower].append(candidate)

    # The heuristic here is to first try "singularizing" the word.  If
    # that doesn't match anything use difflib to find close matches in
    # original, lower and upper case.
    if s_lower.endswith('s') and s_lower[:-1] in candidates_lower:
        matches = [s_lower[:-1]]
    else:
        matches = difflib.get_close_matches(
            s_lower, candidates_lower, n=n, cutoff=cutoff)

    if len(matches):
        capitalized_matches = set()
        for match in matches:
            capitalized_matches.update(candidates_lower[match])
        matches = capitalized_matches

        if fix is not None:
            mapped_matches = []
            for match in matches:
                mapped_matches.extend(fix(match))
            matches = mapped_matches

        matches = list(set(matches))
        matches = sorted(matches)

        if len(matches) == 1:
            matches = matches[0]
        else:
            matches = (', '.join(matches[:-1]) + ' or ' +
                       matches[-1])
        return 'Did you mean {0}?'.format(matches)

    return ''


class InheritDocstrings(type):
    """
    This metaclass makes methods of a class automatically have their
    docstrings filled in from the methods they override in the base
    class.

    If the class uses multiple inheritance, the docstring will be
    chosen from the first class in the bases list, in the same way as
    methods are normally resolved in Python.  If this results in
    selecting the wrong docstring, the docstring will need to be
    explicitly included on the method.

    For example::

        >>> from astropy.utils.misc import InheritDocstrings
        >>> from astropy.extern import six
        >>> @six.add_metaclass(InheritDocstrings)
        ... class A(object):
        ...     def wiggle(self):
        ...         "Wiggle the thingamajig"
        ...         pass
        >>> class B(A):
        ...     def wiggle(self):
        ...         pass
        >>> B.wiggle.__doc__
        u'Wiggle the thingamajig'
    """

    def __init__(cls, name, bases, dct):
        def is_public_member(key):
            return (
                (key.startswith('__') and key.endswith('__')
                 and len(key) > 4) or
                not key.startswith('_'))

        for key, val in six.iteritems(dct):
            if (inspect.isfunction(val) and
                is_public_member(key) and
                val.__doc__ is None):
                for base in cls.__mro__[1:]:
                    super_method = getattr(base, key, None)
                    if super_method is not None:
                        val.__doc__ = super_method.__doc__
                        break

        super(InheritDocstrings, cls).__init__(name, bases, dct)


@six.add_metaclass(abc.ABCMeta)
class OrderedDescriptor(object):
    """
    Base class for descriptors whose order in the class body should be
    preserved.  Intended for use in concert with the
    `OrderedDescriptorContainer` metaclass.

    Subclasses of `OrderedDescriptor` must define a value for a class attribute
    called ``_class_attribute_``.  This is the name of a class attribute on the
    *container* class for these descriptors, which will be set to an
    `~collections.OrderedDict` at class creation time.  This
    `~collections.OrderedDict` will contain a mapping of all class attributes
    that were assigned instances of the `OrderedDescriptor` subclass, to the
    instances themselves.  See the documentation for
    `OrderedDescriptorContainer` for a concrete example.

    Optionally, subclasses of `OrderedDescriptor` may define a value for a
    class attribute called ``_name_attribute_``.  This should be the name of
    an attribute on instances of the subclass.  When specified, during
    creation of a class containing these descriptors, the name attribute on
    each instance will be set to the name of the class attribute it was
    assigned to on the class.

    .. note::

        Although this class is intended for use with *descriptors* (i.e.
        classes that define any of the ``__get__``, ``__set__``, or
        ``__delete__`` magic methods), this base class is not itself a
        descriptor, and technically this could be used for classes that are
        not descriptors too.  However, use with descriptors is the original
        intended purpose.
    """

    # This id increments for each OrderedDescriptor instance created, so they
    # are always ordered in the order they were created.  Class bodies are
    # guaranteed to be executed from top to bottom.  Not sure if this is
    # thread-safe though.
    _nextid = 1

    _class_attribute_ = abc.abstractproperty()
    """
    Subclasses should define this attribute to the name of an attribute on
    classes containing this subclass.  That attribute will contain the mapping
    of all instances of that `OrderedDescriptor` subclass defined in the class
    body.  If the same descriptor needs to be used with different classes,
    each with different names of this attribute, multiple subclasses will be
    needed.
    """

    _name_attribute_ = None
    """
    Subclasses may optionally define this attribute to specify the name of an
    attribute on instances of the class that should be filled with the
    instance's attribute name at class creation time.
    """

    def __init__(self, *args, **kwargs):
        # The _nextid attribute is shared across all subclasses so that
        # different subclasses of OrderedDescriptors can be sorted correctly
        # between themselves
        self.__order = OrderedDescriptor._nextid
        OrderedDescriptor._nextid += 1
        super(OrderedDescriptor, self).__init__()

    def __lt__(self, other):
        """
        Defined for convenient sorting of `OrderedDescriptor` instances, which
        are defined to sort in their creation order.
        """

        if (isinstance(self, OrderedDescriptor) and
                isinstance(other, OrderedDescriptor)):
            try:
                return self.__order < other.__order
            except AttributeError:
                raise RuntimeError(
                    'Could not determine ordering for {0} and {1}; at least '
                    'one of them is not calling super().__init__ in its '
                    '__init__.'.format(self, other))
        else:
            return NotImplemented


class OrderedDescriptorContainer(type):
    """
    Classes should use this metaclass if they wish to use `OrderedDescriptor`
    attributes, which are class attributes that "remember" the order in which
    they were defined in the class body.

    Every subclass of `OrderedDescriptor` has an attribute called
    ``_class_attribute_``.  For example, if we have

    .. code:: python

        class ExampleDecorator(OrderedDescriptor):
            _class_attribute_ = '_examples_'

    Then when a class with the `OrderedDescriptorContainer` metaclass is
    created, it will automatically be assigned a class attribute ``_examples_``
    referencing an `~collections.OrderedDict` containing all instances of
    ``ExampleDecorator`` defined in the class body, mapped to by the names of
    the attributes they were assigned to.

    When subclassing a class with this metaclass, the descriptor dict (i.e.
    ``_examples_`` in the above example) will *not* contain descriptors
    inherited from the base class.  That is, this only works by default with
    decorators explicitly defined in the class body.  However, the subclass
    *may* define an attribute ``_inherit_decorators_`` which lists
    `OrderedDescriptor` classes that *should* be added from base classes.
    See the examples section below for an example of this.

    Examples
    --------

    >>> from astropy.extern import six
    >>> from astropy.utils import OrderedDescriptor, OrderedDescriptorContainer
    >>> class TypedAttribute(OrderedDescriptor):
    ...     \"\"\"
    ...     Attributes that may only be assigned objects of a specific type,
    ...     or subclasses thereof.  For some reason we care about their order.
    ...     \"\"\"
    ...
    ...     _class_attribute_ = 'typed_attributes'
    ...     _name_attribute_ = 'name'
    ...     # A default name so that instances not attached to a class can
    ...     # still be repr'd; useful for debugging
    ...     name = '<unbound>'
    ...
    ...     def __init__(self, type):
    ...         # Make sure not to forget to call the super __init__
    ...         super(TypedAttribute, self).__init__()
    ...         self.type = type
    ...
    ...     def __get__(self, obj, objtype=None):
    ...         if obj is None:
    ...             return self
    ...         if self.name in obj.__dict__:
    ...             return obj.__dict__[self.name]
    ...         else:
    ...             raise AttributeError(self.name)
    ...
    ...     def __set__(self, obj, value):
    ...         if not isinstance(value, self.type):
    ...             raise ValueError('{0}.{1} must be of type {2!r}'.format(
    ...                 obj.__class__.__name__, self.name, self.type))
    ...         obj.__dict__[self.name] = value
    ...
    ...     def __delete__(self, obj):
    ...         if self.name in obj.__dict__:
    ...             del obj.__dict__[self.name]
    ...         else:
    ...             raise AttributeError(self.name)
    ...
    ...     def __repr__(self):
    ...         if isinstance(self.type, tuple) and len(self.type) > 1:
    ...             typestr = '({0})'.format(
    ...                 ', '.join(t.__name__ for t in self.type))
    ...         else:
    ...             typestr = self.type.__name__
    ...         return '<{0}(name={1}, type={2})>'.format(
    ...                 self.__class__.__name__, self.name, typestr)
    ...

    Now let's create an example class that uses this ``TypedAttribute``::

        >>> @six.add_metaclass(OrderedDescriptorContainer)
        ... class Point2D(object):
        ...     x = TypedAttribute((float, int))
        ...     y = TypedAttribute((float, int))
        ...
        ...     def __init__(self, x, y):
        ...         self.x, self.y = x, y
        ...
        >>> p1 = Point2D(1.0, 2.0)
        >>> p1.x
        1.0
        >>> p1.y
        2.0
        >>> p2 = Point2D('a', 'b')  # doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
            ...
        ValueError: Point2D.x must be of type (float, int>)

    We see that ``TypedAttribute`` works more or less as advertised, but
    there's nothing special about that.  Let's see what
    `OrderedDescriptorContainer` did for us::

        >>> Point2D.typed_attributes
        OrderedDict([('x', <TypedAttribute(name=x, type=(float, int))>),
        ('y', <TypedAttribute(name=y, type=(float, int))>)])

    If we create a subclass, it does *not* by default add inherited descriptors
    to ``typed_attributes``::

        >>> class Point3D(Point2D):
        ...     z = TypedAttribute((float, int))
        ...
        >>> Point3D.typed_attributes
        OrderedDict([('z', <TypedAttribute(name=z, type=(float, int))>)])

    However, if we specify ``_inherit_descriptors_`` from ``Point2D`` then
    it will do so::

        >>> class Point3D(Point2D):
        ...     _inherit_descriptors_ = (TypedAttribute,)
        ...     z = TypedAttribute((float, int))
        ...
        >>> Point3D.typed_attributes
        OrderedDict([('x', <TypedAttribute(name=x, type=(float, int))>),
        ('y', <TypedAttribute(name=y, type=(float, int))>),
        ('z', <TypedAttribute(name=z, type=(float, int))>)])

    .. note::

        Hopefully it is clear from these examples that this construction
        also allows a class of type `OrderedDescriptorContainer` to use
        multiple different `OrderedDescriptor` classes simultaneously.
    """

    _inherit_descriptors_ = ()

    def __init__(cls, cls_name, bases, members):
        descriptors = defaultdict(list)
        seen = set()
        inherit_descriptors = ()
        descr_bases = {}

        for mro_cls in cls.__mro__:
            for name, obj in mro_cls.__dict__.items():
                if name in seen:
                    # Checks if we've already seen an attribute of the given
                    # name (if so it will override anything of the same name in
                    # any base class)
                    continue

                seen.add(name)

                if (not isinstance(obj, OrderedDescriptor) or
                        (inherit_descriptors and
                            not isinstance(obj, inherit_descriptors))):
                    # The second condition applies when checking any
                    # subclasses, to see if we can inherit any descriptors of
                    # the given type from subclasses (by default inheritance is
                    # disabled unless the class has _inherit_descriptors_
                    # defined)
                    continue

                if obj._name_attribute_ is not None:
                    setattr(obj, obj._name_attribute_, name)

                # Don't just use the descriptor's class directly; instead go
                # through its MRO and find the class on which _class_attribute_
                # is defined directly.  This way subclasses of some
                # OrderedDescriptor *may* override _class_attribute_ and have
                # its own _class_attribute_, but by default all subclasses of
                # some OrderedDescriptor are still grouped together
                # TODO: It might be worth clarifying this in the docs
                if obj.__class__ not in descr_bases:
                    for obj_cls_base in obj.__class__.__mro__:
                        if '_class_attribute_' in obj_cls_base.__dict__:
                            descr_bases[obj.__class__] = obj_cls_base
                            descriptors[obj_cls_base].append((obj, name))
                            break
                else:
                    # Make sure to put obj first for sorting purposes
                    obj_cls_base = descr_bases[obj.__class__]
                    descriptors[obj_cls_base].append((obj, name))

            if not getattr(mro_cls, '_inherit_descriptors_', False):
                # If _inherit_descriptors_ is undefined then we don't inherit
                # any OrderedDescriptors from any of the base classes, and
                # there's no reason to continue through the MRO
                break
            else:
                inherit_descriptors = mro_cls._inherit_descriptors_

        for descriptor_cls, instances in descriptors.items():
            instances.sort()
            instances = OrderedDict((key, value) for value, key in instances)
            setattr(cls, descriptor_cls._class_attribute_, instances)

        super(OrderedDescriptorContainer, cls).__init__(cls_name, bases,
                                                        members)


LOCALE_LOCK = threading.Lock()

@contextmanager
def set_locale(name):
    """
    Context manager to temporarily set the locale to ``name``.

    An example is setting locale to "C" so that the C strtod()
    function will use "." as the decimal point to enable consistent
    numerical string parsing.

    Note that one cannot nest multiple set_locale() context manager
    statements as this causes a threading lock.

    This code taken from http://stackoverflow.com/questions/18593661/.

    Parameters
    ==========
    name : str
        Locale name, e.g. "C" or "fr_FR".
    """
    name = str(name)

    with LOCALE_LOCK:
        saved = locale.setlocale(locale.LC_ALL)
        if saved == name:
            # Don't do anything if locale is already the requested locale
            yield
        else:
            try:
                locale.setlocale(locale.LC_ALL, name)
                yield
            finally:
                locale.setlocale(locale.LC_ALL, saved)


@six.add_metaclass(abc.ABCMeta)
class ShapedLikeNDArray(object):
    """Mixin class to provide shape-changing methods.

    The class proper is assumed to have some underlying data, which are arrays
    or array-like structures. It must define a ``shape`` property, which gives
    the shape of those data, as well as an ``_apply`` method that creates a new
    instance in which a `~numpy.ndarray` method has been applied to those.

    Furthermore, for consistency with `~numpy.ndarray`, it is recommended to
    define a setter for the ``shape`` property, which, like the
    `~numpy.ndarray.shape` property allows in-place reshaping the internal data
    (and, unlike the ``reshape`` method raises an exception if this is not
    possible).

    This class also defines default implementations for ``ndim`` and ``size``
    properties, calculating those from the ``shape``.  These can be overridden
    by subclasses if there are faster ways to obtain those numbers.

    """

    # Note to developers: if new methods are added here, be sure to check that
    # they work properly with the classes that use this, such as Time and
    # BaseRepresentation, i.e., look at their ``_apply`` methods and add
    # relevant tests.  This is particularly important for methods that imply
    # copies rather than views of data (see the special-case treatment of
    # 'flatten' in Time).

    @abc.abstractproperty
    def shape(self):
        """The shape of the instance and underlying arrays."""

    @abc.abstractmethod
    def _apply(method, *args, **kwargs):
        """Create a new instance, with ``method`` applied to underlying data.

        The method is any of the shape-changing methods for `~numpy.ndarray`
        (``reshape``, ``swapaxes``, etc.), as well as those picking particular
        elements (``__getitem__``, ``take``, etc.). It will be applied to the
        underlying arrays (e.g., ``jd1`` and ``jd2`` in `~astropy.time.Time`),
        with the results used to create a new instance.

        Parameters
        ----------
        method : str
            Method to be applied to the instance's internal data arrays.
        args : tuple
            Any positional arguments for ``method``.
        kwargs : dict
            Any keyword arguments for ``method``.

        """

    @property
    def ndim(self):
        """The number of dimensions of the instance and underlying arrays."""
        return len(self.shape)

    @property
    def size(self):
        """The size of the object, as calculated from its shape."""
        size = 1
        for sh in self.shape:
            size *= sh
        return size

    @property
    def isscalar(self):
        return self.shape == ()

    def __len__(self):
        if self.isscalar:
            raise TypeError("Scalar {0!r} object has no len()"
                            .format(self.__class__.__name__))
        return self.shape[0]

    def __bool__(self):  # Python 3
        """Any instance should evaluate to True, except when it is empty."""
        return self.size > 0

    def __nonzero__(self):  # Python 2
        """Any instance should evaluate to True, except when it is empty."""
        return self.size > 0

    def __getitem__(self, item):
        try:
            return self._apply('__getitem__', item)
        except IndexError:
            if self.isscalar:
                raise TypeError('scalar {0!r} object is not subscriptable.'
                                .format(self.__class__.__name__))
            else:
                raise

    def __iter__(self):
        if self.isscalar:
            raise TypeError('scalar {0!r} object is not iterable.'
                            .format(self.__class__.__name__))

        # We cannot just write a generator here, since then the above error
        # would only be raised once we try to use the iterator, rather than
        # upon its definition using iter(self).
        def self_iter():
            for idx in range(len(self)):
                yield self[idx]

        return self_iter()

    def copy(self, *args, **kwargs):
        """Return an instance containing copies of the internal data.

        Parameters are as for :meth:`~numpy.ndarray.copy`.
        """
        return self._apply('copy', *args, **kwargs)

    def reshape(self, *args, **kwargs):
        """Returns an instance containing the same data with a new shape.

        Parameters are as for :meth:`~numpy.ndarray.reshape`.  Note that it is
        not always possible to change the shape of an array without copying the
        data (see :func:`~numpy.reshape` documentation). If you want an error
        to be raise if the data is copied, you should assign the new shape to
        the shape attribute (note: this may not be implemented for all classes
        using ``ShapedLikeNDArray``).
        """
        return self._apply('reshape', *args, **kwargs)

    def ravel(self, *args, **kwargs):
        """Return an instance with the array collapsed into one dimension.

        Parameters are as for :meth:`~numpy.ndarray.ravel`. Note that it is
        not always possible to unravel an array without copying the data.
        If you want an error to be raise if the data is copied, you should
        should assign shape ``(-1,)`` to the shape attribute.
        """
        return self._apply('ravel', *args, **kwargs)

    def flatten(self, *args, **kwargs):
        """Return a copy with the array collapsed into one dimension.

        Parameters are as for :meth:`~numpy.ndarray.flatten`.
        """
        return self._apply('flatten', *args, **kwargs)

    def transpose(self, *args, **kwargs):
        """Return an instance with the data transposed.

        Parameters are as for :meth:`~numpy.ndarray.transpose`.  All internal
        data are views of the data of the original.
        """
        return self._apply('transpose', *args, **kwargs)

    @property
    def T(self):
        """Return an instance with the data transposed.

        Parameters are as for :attr:`~numpy.ndarray.T`.  All internal
        data are views of the data of the original.
        """
        if self.ndim < 2:
            return self
        else:
            return self.transpose()

    def swapaxes(self, *args, **kwargs):
        """Return an instance with the given axes interchanged.

        Parameters are as for :meth:`~numpy.ndarray.swapaxes`:
        ``axis1, axis2``.  All internal data are views of the data of the
        original.
        """
        return self._apply('swapaxes', *args, **kwargs)

    def diagonal(self, *args, **kwargs):
        """Return an instance with the specified diagonals.

        Parameters are as for :meth:`~numpy.ndarray.diagonal`.  All internal
        data are views of the data of the original.
        """
        return self._apply('diagonal', *args, **kwargs)

    def squeeze(self, *args, **kwargs):
        """Return an instance with single-dimensional shape entries removed

        Parameters are as for :meth:`~numpy.ndarray.squeeze`.  All internal
        data are views of the data of the original.
        """
        return self._apply('squeeze', *args, **kwargs)

    def take(self, indices, axis=None, mode='raise'):
        """Return a new instance formed from the elements at the given indices.

        Parameters are as for :meth:`~numpy.ndarray.take`, except that,
        obviously, no output array can be given.
        """
        return self._apply('take', indices, axis=axis, mode=mode)


class IncompatibleShapeError(ValueError):
    def __init__(self, shape_a, shape_a_idx, shape_b, shape_b_idx):
        super(IncompatibleShapeError, self).__init__(
                shape_a, shape_a_idx, shape_b, shape_b_idx)


def check_broadcast(*shapes):
    """
    Determines whether two or more Numpy arrays can be broadcast with each
    other based on their shape tuple alone.

    Parameters
    ----------
    *shapes : tuple
        All shapes to include in the comparison.  If only one shape is given it
        is passed through unmodified.  If no shapes are given returns an empty
        `tuple`.

    Returns
    -------
    broadcast : `tuple`
        If all shapes are mutually broadcastable, returns a tuple of the full
        broadcast shape.
    """

    if len(shapes) == 0:
        return ()
    elif len(shapes) == 1:
        return shapes[0]

    reversed_shapes = (reversed(shape) for shape in shapes)

    full_shape = []

    for dims in zip_longest(*reversed_shapes, fillvalue=1):
        max_dim = 1
        max_dim_idx = None
        for idx, dim in enumerate(dims):
            if dim == 1:
                continue

            if max_dim == 1:
                # The first dimension of size greater than 1
                max_dim = dim
                max_dim_idx = idx
            elif dim != max_dim:
                raise IncompatibleShapeError(
                    shapes[max_dim_idx], max_dim_idx, shapes[idx], idx)

        full_shape.append(max_dim)

    return tuple(full_shape[::-1])