This file is indexed.

/usr/lib/python2.7/dist-packages/sagenb/misc/support.py is in python-sagenb 1.0.1+ds1-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
# -*- coding: utf-8 -*
"""
Support for Notebook Introspection and Setup

AUTHORS:

- William Stein (much of this code is from IPython).

- Nick Alexander
"""

import inspect
import os
import base64
import string
import sys
import pydoc

from six import iteritems
import __builtin__

try:
    from cPickle import PicklingError
except ImportError:
    from pickle import PicklingError

from .misc import loads, dumps, cython, session_init

from . import sageinspect

try:
    from sage.misc.sagedoc import format_src
except ImportError:
    # Fallback
    def format_src(s, *args, **kwds):
        return s

try:
    from sagenb.misc.sphinxify import sphinxify, is_sphinx_markup
except ImportError as msg:
    print(msg)
    print("Sphinx docstrings not available.")
    # Don't do any Sphinxifying if sphinx's dependencies aren't around
    def sphinxify(s):
        return s
    def is_sphinx_markup(s):
        return False

try:
    from sage.misc.displayhook import DisplayHook
    sys.displayhook = DisplayHook()
except ImportError as msg:
    print(msg)
    print('Graphics will not be shown automatically')


######################################################################
# Initialization
######################################################################
EMBEDDED_MODE = False
sage_globals = None
globals_at_init = None
global_names_at_init = None

def init(object_directory=None, globs={}):
    r"""
    Initialize Sage for use with the web notebook interface.
    """
    global sage_globals, globals_at_init, global_names_at_init
    global EMBEDDED_MODE

    os.environ['PAGER'] = 'cat'
    
    sage_globals = globs
    #globals_at_init = set(globs.keys())
    globals_at_init = globs.values()
    global_names_at_init = set(globs.keys())
    EMBEDDED_MODE = True
    
    setup_systems(globs)
    session_init(globs)

    # Ugly cruft.  Initialize the embedded mode of the old Sage
    # notebook, which is going to be included in old copies of Sage
    # forever.
    try:
        import sage.server.support
        sage.server.support.EMBEDDED_MODE = True
    except ImportError:
        pass
    # Also initialize EMBEDDED_MODE in Sage's misc.sageinspect module,
    # which is used to format docstrings in the notebook.
    try:
        import sage.misc.sageinspect
        sage.misc.sageinspect.EMBEDDED_MODE = True
    except ImportError:
        pass


def setup_systems(globs):
    from .misc import InlineFortran
    fortran = InlineFortran(globs)
    globs['fortran'] = fortran


######################################################################
# Introspection
######################################################################
def help(obj):
    """
    Display HTML help for ``obj``, a Python object, module, etc.  This
    help is often more extensive than that given by 'obj?'.  This
    function does not return a value --- it prints HTML as a side
    effect.
    
    .. note::

       This a wrapper around the built-in help. If formats the output
       as HTML without word wrap, which looks better in the notebook.

    INPUT:
    
    -  ``obj`` - a Python object, module, etc.
    
    TESTS::
    
        sage: import numpy.linalg
        sage: current_dir = os.getcwd()
        sage: os.chdir(tmp_dir('server_doctest'))
        sage: sagenb.misc.support.help(numpy.linalg.norm)
        <html><table notracebacks bgcolor="#386074" cellpadding=10 cellspacing=10><tr><td bgcolor="#f5f5f5"><font color="#37546d">
        &nbsp;&nbsp;&nbsp;<a target='_new' href='cell://docs-....html'>Click to open help window</a>&nbsp;&nbsp;&nbsp;
        <br></font></tr></td></table></html>
        sage: os.chdir(current_dir)
    """
    from pydoc import resolve, html, describe
    import sagenb.notebook.interact as interact

    print('<html><table notracebacks bgcolor="#386074" cellpadding=10 cellspacing=10><tr><td bgcolor="#f5f5f5"><font color="#37546d">')
    object, name = resolve(obj)
    page = html.page(describe(object), html.document(object, name))
    page = page.replace('<a href','<a ')
    n = 0
    while True:
        filename = 'docs-%s.html'%n
        if not os.path.exists(filename): break
        n += 1
    open(filename, 'w').write(page)
    print("&nbsp;&nbsp;&nbsp;<a target='_new' href='cell://%s'>Click to open help window</a>&nbsp;&nbsp;&nbsp;" % filename)
    print('<br></font></tr></td></table></html>')
    
def get_rightmost_identifier(s):
    X = string.ascii_letters + string.digits + '._'
    i = len(s)-1
    while i >= 0 and s[i] in X:
        i -= 1
    return s[i+1:]
    
def completions(s, globs, format=False, width=90, system="None"):
    """
    Return a list of completions in the given context.

    INPUT:

    - ``globs`` - a string:object dictionary; context in which to
      search for completions, e.g., :func:`globals()`

    - ``format`` - a bool (default: False); whether to tabulate the
      list
    
    - ``width`` - an int; character width of the table
    
    - ``system`` - a string (default: 'None'); system prefix for the
      completions

    OUTPUT:

    - a list of strings, if ``format`` is False, or a string
    """
    if system not in ['sage', 'python']:
        prepend = system + '.'
        s = prepend + s
    else:
        prepend = ''
    n = len(s)
    if n == 0:
        return '(empty string)'
    try:
        if not '.' in s and not '(' in s:
            v = [x for x in globs.keys() if x[:n] == s] + \
                [x for x in __builtins__.keys() if x[:n] == s] 
        else:
            if not ')' in s:
                i = s.rfind('.')
                method = s[i+1:]
                obj = s[:i]
                n = len(method)
            else:
                obj = preparse(s)
                method = ''
            try:
                O = eval(obj, globs)
                D = dir(O)
                try:
                    D += O.trait_names()
                except (AttributeError, TypeError):
                    pass
                if method == '':
                    v = [obj + '.'+x for x in D if x and x[0] != '_']
                else:
                    v = [obj + '.'+x for x in D if x[:n] == method]
            except Exception:
                v = []
        v = list(set(v))   # make unique
        v.sort()
    except Exception:
        v = []

    if prepend:
        i = len(prepend)
        v = [x[i:] for x in v]
        
    if format:
        if len(v) == 0:
            return "No completions of '%s' currently defined"%s
        else:
            return tabulate(v, width)
    return v    

def docstring(obj_name, globs, system='sage'):
    r"""
    Format an object's docstring to process and display in the Sage
    notebook.
    
    INPUT:

    - ``obj_name`` - a string; a name of an object

    - ``globs`` - a string:object dictionary; a context in which to
      evaluate ``obj_name``

    - ``system`` - a string (default: 'sage'); the system to which to
      confine the search

    OUTPUT:

    - a string containing the object's file, type, definition, and
      docstring or a message stating the object is not defined

    AUTHORS:

    - William Stein: partly taken from IPython for use in Sage

    - Nick Alexander: extensions

    TESTS:

    Check that Trac 10860 is fixed and we can handle Unicode help
    strings in the notebook::

        sage: from sagenb.misc.support import docstring
        sage: D = docstring("r.lm", globs=globals())
    """
    if system not in ['sage', 'python']:
        obj_name = system + '.' + obj_name
    try:
        obj = eval(obj_name, globs)
    except (AttributeError, NameError, SyntaxError):
        return "No object '%s' currently defined."%obj_name
    s  = ''
    newline = "\n\n"  # blank line to start new paragraph
    try:
        filename = sageinspect.sage_getfile(obj)
        #i = filename.find('site-packages/sage/')
        #if i == -1:
        s += '**File:** %s'%filename
        s += newline
        #else:
        #    file = filename[i+len('site-packages/sage/'):]
        #    s += 'File:        <html><a href="src_browser?%s">%s</a></html>\n'%(file,file)
    except TypeError:
        pass
    s += '**Type:** %s'%type(obj)
    s += newline
    s += '**Definition:** %s'%sageinspect.sage_getdef(obj, obj_name)
    s += newline
    s += '**Docstring:**'
    s += newline
    s += sageinspect.sage_getdoc(obj, obj_name)
    s = s.rstrip()
    return html_markup(s.decode('utf-8'))

def html_markup(s):
    try:
        from sagenb.misc.sphinxify import sphinxify, is_sphinx_markup
    except ImportError:
        # sphinx not available
        def is_sphinx_markup(s): return False

    if is_sphinx_markup(s):
        try:
            return sphinxify(s)
        except:
            pass
    # Not in ReST format, so use docutils
    # to process the preamble ("**File:**" etc.)  and put
    # everything else in a <pre> block.
    i = s.find("**Docstring:**")
    if i != -1:
        preamble = s[:i+14]
        from docutils.core import publish_parts
        preamble = publish_parts(s[:i+14], writer_name='html')['body']
        s = s[i+14:]
    else:
        preamble = ""
    return '<div class="docstring">' + preamble + '<pre>' + s + '</pre></div>'

def source_code(s, globs, system='sage'):
    r"""
    Format an object's source code to process and display in the
    Sage notebook.
    
    INPUT:

    - ``s`` - a string; a name of an object

    - ``globs`` - a string:object dictionary; a context in which to
      evaluate ``s``

    - ``system`` - a string (default: 'sage'); the system to which to
      confine the search

    OUTPUT:

    - a string containing the object's file, starting line number, and
      source code

    AUTHORS:

    - William Stein: partly taken from IPython for use in Sage

    - Nick Alexander: extensions
    """
    if system not in ['sage', 'python']:
        s = system + '.' + s

    try:
        obj = eval(s, globs)
    except NameError:
        return html_markup("No object %s"%s)
    
    try:
        try:
            return html_markup(obj._sage_src_())
        except:
            pass
        newline = "\n\n"  # blank line to start new paragraph
        indent = "    "   # indent source code to mark it as a code block

        filename = sageinspect.sage_getfile(obj)
        try:
            lines, lineno = sageinspect.sage_getsourcelines(obj)
        except IOError as msg:
            return html_markup(str(msg))
        src = indent.join(lines)
        src = indent + format_src(src)
        if not lineno is None:
            output = "**File:** %s"%filename
            output += newline
            output += "**Source Code** (starting at line %s)::"%lineno
            output += newline
            output += src
        return html_markup(output)
    
    except (TypeError, IndexError):
        return html_markup("Source code for {} is not available.".format(s) +
                           "\nUse {}? to see the documentation.".format(s))
    
def tabulate(v, width=90, ncols=3):
    e = len(v)
    if e == 0:
        return ''
    while True:
        col_widths = []
        nrows = e//ncols + 1
        for c in range(ncols):
            m = max([0] + [len(v[r+c*nrows]) for r in range(nrows) if r+c*nrows < e])
            col_widths.append(m+3)
        if ncols > 1 and max(col_widths + [0]) > width//ncols:
            ncols -= 1
        else:
            break
    n = max(len(x) for x in v)
    s = ''
    for r in range(nrows):
        for c in range(ncols):
            i = r + c*nrows
            if i < e:
                w = v[i]
                s += w + ' '*(col_widths[c] - len(w))
        s += '\n'
    return s

def syseval(system, cmd, dir=None):
    """
    Evaluate an input with a "system" object that can evaluate inputs
    (e.g., python, gap).

    INPUT:
        
    - ``system`` - an object with an eval method that takes an input

    - ``cmd`` - a string input

    - ``sage_globals`` - a string:object dictionary

    - dir - a string (default: None); an optional directory to change
      to before calling :func:`system.eval`

    OUTPUT:

    - :func:`system.eval`'s output
                  
    EXAMPLES::

        sage: from sage.misc.python import python
        sage: sagenb.misc.support.syseval(python, '2+4//3')
        3
        ''
        sage: sagenb.misc.support.syseval(python, 'import os; os.chdir(".")')
        ''
        sage: sagenb.misc.support.syseval(python, 'import os; os.chdir(1,2,3)')
        Traceback (most recent call last):
        ...
        TypeError: chdir() takes exactly 1 argument (3 given)
        sage: sagenb.misc.support.syseval(gap, "2+3")
        '5'
    """
    if dir:
        if hasattr(system.__class__, 'chdir'):
            system.chdir(dir)
    if isinstance(cmd, unicode):
        cmd = cmd.encode('utf-8', 'ignore')
    return system.eval(cmd, sage_globals, locals = sage_globals)

######################################################################
# Cython
######################################################################
def cython_import(filename, verbose=False, compile_message=False,
                 use_cache=False, create_local_c_file=True):
    """
    Compile a file containing Cython code, then import and return the
    module.  Raises an ``ImportError`` if anything goes wrong.

    INPUT:
    
    - ``filename`` - a string; name of a file that contains Cython
      code
    
    OUTPUT:
    
    - the module that contains the compiled Cython code.
    """
    name, build_dir = cython(filename, verbose=verbose,
                             compile_message=compile_message,
                                            use_cache=use_cache,
                                            create_local_c_file=create_local_c_file)
    sys.path.append(build_dir)
    return __builtin__.__import__(name)


def cython_import_all(filename, globals, verbose=False, compile_message=False,
                     use_cache=False, create_local_c_file=True):
    """
    Imports all non-private (i.e., not beginning with an underscore)
    attributes of the specified Cython module into the given context.
    This is similar to::

        from module import *

    Raises an ``ImportError`` exception if anything goes wrong.

    INPUT:
    
    - ``filename`` - a string; name of a file that contains Cython
      code
    """
    m = cython_import(filename, verbose=verbose, compile_message=compile_message,
                     use_cache=use_cache,
                     create_local_c_file=create_local_c_file)
    for k, x in iteritems(m.__dict__):
        if k[0] != '_':
            globals[k] = x
            


###################################################
# Preparser
###################################################
try:
    from sage.repl.preparse import preparse, preparse_file
    def do_preparse():
        """
        Return True if the preparser is set to on, and False otherwise.
        """
        import sage.repl.interpreter
        return sage.repl.interpreter._do_preparse
except ImportError:
    def preparse(line, *args, **kwds):
        return line
    def preparse_file(contents, *args, **kwds):
        return contents
    def do_preparse():
        """
        Return True if the preparser is set to on, and False otherwise.
        """
        return False


########################################################################
#
# Automatic Creation of Variable Names
#
# See the docstring for automatic_names below for an explanation of how
# this works. 
#
########################################################################

_automatic_names = False
# We wrap everything in a try/catch, in case this is being imported
# without the sage library present, e.g., in FEMhub.
try:
    from sage.symbolic.all import Expression, SR
    class AutomaticVariable(Expression):
        """
        An automatically created symbolic variable with an additional
        :meth:`__call__` method designed so that doing self(foo,...)
        results in foo.self(...).
        """
        def __call__(self, *args, **kwds):
            """
            Call method such that self(foo, ...) is transformed into
            foo.self(...).  Note that self(foo=...,...) is not
            transformed, it is treated as a normal symbolic
            substitution.
            """
            if len(args) == 0:
                return Expression.__call__(self, **kwds)
            return args[0].__getattribute__(str(self))(*args[1:], **kwds)

    def automatic_name_eval(s, globals, max_names=10000):
        """
        Exec the string ``s`` in the scope of the ``globals``
        dictionary, and if any :exc:`NameError`\ s are raised, try to
        fix them by defining the variable that caused the error to be
        raised, then eval again.  Try up to ``max_names`` times.
        
        INPUT:

           - ``s`` -- a string
           - ``globals`` -- a dictionary
           - ``max_names`` -- a positive integer (default: 10000)
        """
        # This entire automatic naming system really boils down to
        # this bit of code below.  We simply try to exec the string s
        # in the globals namespace, defining undefined variables and
        # functions until everything is defined.
        for _ in range(max_names):
            try:
                exec(s , globals)
                return
            except NameError as msg:
                # Determine if we hit a NameError that is probably
                # caused by a variable or function not being defined:
                if len(msg.args) == 0: raise  # not NameError with
                                              # specific variable name
                v = msg.args[0].split("'")
                if len(v) < 2: raise  # also not NameError with
                                      # specific variable name We did
                                      # find an undefined variable: we
                                      # simply define it and try
                                      # again.
                nm = v[1]
                globals[nm] = AutomaticVariable(SR, SR.var(nm))
        raise NameError("Too many automatic variable names and functions created (limit=%s)" % max_names)

    def automatic_name_filter(s):
        """
        Wrap the string ``s`` in a call that will cause evaluation of
        ``s`` to automatically create undefined variable names.

        INPUT:

           - ``s`` -- a string

        OUTPUT:

           - a string
        """
        return '_support_.automatic_name_eval(_support_.base64.b64decode("%s"),globals())'%base64.b64encode(s)

    def automatic_names(state=None):
        """
        Turn automatic creation of variables and functional calling of
        methods on or off.  Returns the current ``state`` if no
        argument is given.

        This ONLY works in the Sage notebook.  It is not supported on
        the command line.

        INPUT:

        - ``state`` -- a boolean (default: None); whether to turn
          automatic variable creation and functional calling on or off

        OUTPUT:

        - a boolean, if ``state`` is None; otherwise, None

        EXAMPLES::

            sage: automatic_names(True)      # not tested
            sage: x + y + z                  # not tested
            x + y + z

        Here, ``trig_expand``, ``y``, and ``theta`` are all
        automatically created::
        
            sage: trig_expand((2*x + 4*y + sin(2*theta))^2)   # not tested
            4*(sin(theta)*cos(theta) + x + 2*y)^2
           
        IMPLEMENTATION: Here's how this works, internally.  We define
        an :class:`AutomaticVariable` class derived from
        :class:`~sage.symbolic.all.Expression`.  An instance of
        :class:`AutomaticVariable` is a specific symbolic variable,
        but with a special :meth:`~AutomaticVariable.__call__` method.
        We overload the call method so that ``foo(bar, ...)`` gets
        transformed to ``bar.foo(...)``.  At the same time, we still
        want expressions like ``f^2 - b`` to work, i.e., we don't want
        to have to figure out whether a name appearing in a
        :exc:`NameError` is meant to be a symbolic variable or a
        function name. Instead, we just make an object that is both!

        This entire approach is very simple---we do absolutely no
        parsing of the actual input.  The actual real work amounts to
        only a few lines of code.  The primary catch to this approach
        is that if you evaluate a big block of code in the notebook,
        and the first few lines take a long time, and the next few
        lines define 10 new variables, the slow first few lines will
        be evaluated 10 times.  Of course, the advantage of this
        approach is that even very subtle code that might inject
        surprisingly named variables into the namespace will just work
        correctly, which would be impossible to guarantee with static
        parsing, no matter how sophisticated it is.  Finally, given
        the target audience: people wanting to simplify use of Sage
        for Calculus for undergrads, I think this is an acceptable
        tradeoff, especially given that this implementation is so
        simple.
        """
        global _automatic_names
        if state is None:
            return _automatic_names
        _automatic_names = bool(state)
        
except ImportError:
    pass

from sagenb.misc.format import displayhook_hack

def preparse_worksheet_cell(s, globals):
    """
    Preparse the contents of a worksheet cell in the notebook,
    respecting the user using ``preparser(False)`` to turn off the
    preparser.  This function calls
    :func:`~sage.repl.preparse.preparse_file` which also reloads
    attached files.  It also does displayhook formatting by calling
    the :func:`~sagenb.notebook.interfaces.format.displayhook_hack`
    function.

    INPUT:

    - ``s`` - a string containing code

    - ``globals`` - a string:object dictionary; passed directly to
      :func:`~sage.repl.preparse.preparse_file`

    OUTPUT:

        - a string
    """
    if do_preparse(): 
        s = preparse_file(s, globals=globals)
    s = displayhook_hack(s)
    if _automatic_names:
        s = automatic_name_filter(s)
    return s