Exemple #1
0
 def handle_input(self, inpt):
     if inpt == 'enter':
         return self.accept_input()
     elif inpt == 'ctrl d':
         raise urwid.ExitMainLoop()
     elif inpt == 'ctrl p':
         self.screen.page(pydoc.render_doc('pydoc'))
         return True
     elif inpt == 'ctrl o':
         txt = self.widget.inputbox.text.strip()
         try:
             fulltxt = pydoc.render_doc(str(txt))
         except ImportError:
             fulltxt = 'No documentation found for ' + repr(txt)
         self.screen.page(fulltxt)
         return True
     if inpt == 'ctrl w': # widget switch
         if self.widget.upperbox.widget == self.widget.completionbox:
             self.widget.upperbox.widget = urwid.Text(self.usagetext)
         else:
             self.widget.upperbox.widget = self.widget.completionbox
             #self.widget.upperbox.widget = urwid.Text('Another widget!')
         return True
     else:
         self.widget.upperbox.widget = urwid.Text(inpt)
         return True
Exemple #2
0
Fichier : U.py Projet : QGB/QPSU
def helphtml(obj,*aos):
	txt=''
	import pydoc,re
	if aos:
		aos=flat(obj,aos,noNone=True)
		for i in aos:
			#TODO
			txt+=re.sub('.\b', '', pydoc.render_doc(i,'%s'))
			txt+='\n==============%s=======================\n'%ct(aos)
	else:txt=re.sub('.\b', '', pydoc.render_doc(obj,'%s'))
	# txt=txt.replace(txthtml[1],txthtml[1][:1]+'!!!qgb-padding!!!'+txthtml[1][1:])
	# txt=txthtml[0]+txt+txthtml[1]
	# msgbox(txt[txt.find(b'\x08'):])
	# repl()
	# exit()
	file='Uhelp_obj.txt'
	try:
		import T
		if obj:file=T.filename(getObjName(obj))+'.txt'
		elif aos:file=T.filename(getObjName(aos[0]))+'..%s.txt'%len(aos)
	except:pass
	

	with open(file,'w') as f:
		f.write(txt)
	# write(file,txt)
	globals()['browser'](file)
Exemple #3
0
def main():
    try:
        action = getattr(sys.modules[__name__], sys.argv[1])
        action(*sys.argv[2:])
    except IndexError as error:
        print "Usage {0} function [args]".format(sys.argv[0])
        print pydoc.render_doc(sys.modules[__name__], "Help on %s")
Exemple #4
0
def help(which=None):
    ''' help about all functions or one specific function '''
    m = sys.modules[__name__]
    if which:
        print (pydoc.render_doc(getattr(m, which)))
    else:
        print (pydoc.render_doc(m))
    sys.exit(1)
 def test_non_str_name(self):
     # issue14638
     # Treat illegal (non-str) name like no name
     class A:
         __name__ = 42
     class B:
         pass
     adoc = pydoc.render_doc(A())
     bdoc = pydoc.render_doc(B())
     self.assertEqual(adoc.replace("A", "B"), bdoc)
Exemple #6
0
 def test_typing_pydoc(self):
     def foo(data: typing.List[typing.Any],
             x: int) -> typing.Iterator[typing.Tuple[int, typing.Any]]:
         ...
     T = typing.TypeVar('T')
     class C(typing.Generic[T], typing.Mapping[int, str]): ...
     self.assertEqual(pydoc.render_doc(foo).splitlines()[-1],
                      'f\x08fo\x08oo\x08o(data:List[Any], x:int)'
                      ' -> Iterator[Tuple[int, Any]]')
     self.assertEqual(pydoc.render_doc(C).splitlines()[2],
                      'class C\x08C(typing.Mapping)')
def connected_all_devices():
    print(pydoc.plain(pydoc.render_doc(topology.mount)))
    unmounted_list = topology.unmounted_nodes()
    if unmounted_list:
        for device_name in unmounted_list:
            mount_device(device_name)
#            time.sleep(15)
    else:
        print('There are no (configured) devices unmounted.')
    print(pydoc.plain(pydoc.render_doc(topology.connected)))
    print('connected:  ', topology.connected_nodes())
Exemple #8
0
def print_desc(prefix, pkg_path):
    for pkg in pu.iter_modules(pkg_path):
        name = prefix+"."+pkg[1]

        if (pkg[2] == True):
            try:
                print(pd.plain(pd.render_doc(name)))
                docstr = pd.plain(pd.render_doc(name))
                docstr = clean(docstr)
                start = docstr.find("DESCRIPTION")
                docstr = docstr[start: start + 140]
                print(name, docstr)
            except:
                print("UnexpectedError", sys.exc_info()[0])
                continue
    def test_field_order_for_named_tuples(self):
        Person = namedtuple('Person', ['nickname', 'firstname', 'agegroup'])
        s = pydoc.render_doc(Person)
        self.assertLess(s.index('nickname'), s.index('firstname'))
        self.assertLess(s.index('firstname'), s.index('agegroup'))

        class NonIterableFields:
            _fields = None

        class NonHashableFields:
            _fields = [[]]

        # Make sure these doesn't fail
        pydoc.render_doc(NonIterableFields)
        pydoc.render_doc(NonHashableFields)
Exemple #10
0
def print_doc (symbol):
  import pydoc;
  # if symbol is "module.symbol", try auto-import
  match_module = _re_mod_command.match(symbol);
  if match_module:
    _autoimport(match_module.group(1));
  # try to evaluate the symbol to 'what'
  what = None
  try:
    what = eval(symbol,Pyxis.Context);
  except:
    # if symbol does not contain a dot, try to treat it as a module name
    if '.' not in symbol:
      try:
        _autoimport(symbol)
        what = eval(symbol,Pyxis.Context)
      except:
        pass
  if what is None:
    print("Pyxis doesn't know anything about '%s'"%symbol);
    return;
  docs = pydoc.render_doc(what).split("\n");
  if docs[0].startswith("Python Library"):
    docs[0] = "Pyxis documentation for %s (%s):"%(symbol, type(what).__name__);
  print("\n".join(docs));
Exemple #11
0
    def get_help_on(self, info, level=0, none_on_fail=False):
        """Implement basic help for functions"""
        if not info['code']:
            return None if none_on_fail else ''

        last = info['obj']

        default = None if none_on_fail else ('No help available for "%s"' % last)

        parts = last.split('.')

        obj = self.env.get(parts[0], None)

        if not obj:
            return default

        for p in parts[1:]:

            obj = getattr(obj, p, None)

            if not obj:
                return default

        strhelp = pydoc.render_doc(obj, "Help on %s")
        if level == 0:
            return getattr(obj, '__doc__', strhelp)
        else:
            return strhelp
 def test_classic_class(self):
     class C: "Classic class"
     c = C()
     self.assertEqual(pydoc.describe(C), 'class C')
     self.assertEqual(pydoc.describe(c), 'C')
     expected = 'C in module %s' % __name__
     self.assertTrue(expected in pydoc.render_doc(c))
Exemple #13
0
def print_function(functions, function):
    func = get_function(functions, function)
    if func:
        print pydoc.plain(pydoc.render_doc(
            func,
            "Displaying docstring for %s")
        )
Exemple #14
0
 def __init__(self, name):
     self['data'] = MyDocFileDataDict('')
     self['func'] = MyDocFileFunctionDict('')
     self['class'] = MyDocFileClassDict('')
     self['desc'] = MyDocFileDataDesc('')
     self['tree'] = ''
     self['name'] = name
     self['raw'] = re.sub('.\b', '', pydoc.render_doc(name))
     self['synmols'] = __import__(name,fromlist=[name.split('.')[-1]])
     d = split_sections(self['raw'].split('\n'))
     if 'DATA' in d.keys():
         self['data'] = MyDocFileDataDict('\n'.join(d['DATA']))
     if 'FUNCTIONS' in d.keys():
         self['func'] = MyDocFileFunctionDict('\n'.join(d['FUNCTIONS']))
     if 'CLASSES' in d.keys():
         for x in do_undent(d['CLASSES']):
             if re.match(r'[ ]*class ', x):
                 break
             self['tree'] += x + '\n'
         self['tree'] = self['tree'].rstrip()
         self['class'] = MyDocFileClassDict('\n'.join(d['CLASSES']))
     if 'DESCRIPTION' in d.keys():
         self['desc'] = MyDocFileDataDesc('\n'.join(d['DESCRIPTION']))
         self['name1'] = d['NAME'][0].strip()
     else:
         x = d['NAME'][0].split('-', 1)
         self['name1'] = x[0].strip()
         self['desc'] = MyDocFileDataDesc(x[1].strip())
     self['desc'] = MyDocFileDataDesc(self['synmols'].__doc__)
     ## print name, repr(self['synmols'].__doc__)
     self['file'] = d['FILE'][0].strip()
 def test_classic_class(self):
     class C: "Classic class"
     c = C()
     self.assertEqual(pydoc.describe(C), 'class C')
     self.assertEqual(pydoc.describe(c), 'instance of C')
     expected = 'instance of C in module %s' % __name__
     self.assertIn(expected, pydoc.render_doc(c))
    def test_builtin(self):
        for name in ('str', 'str.translate', '__builtin__.str',
                     '__builtin__.str.translate'):
            # test low-level function
            self.assertIsNotNone(pydoc.locate(name))
            # test high-level function
            try:
                pydoc.render_doc(name)
            except ImportError:
                self.fail('finding the doc of {!r} failed'.format(o))

        for name in ('not__builtin__', 'strrr', 'strr.translate',
                     'str.trrrranslate', '__builtin__.strrr',
                     '__builtin__.str.trrranslate'):
            self.assertIsNone(pydoc.locate(name))
            self.assertRaises(ImportError, pydoc.render_doc, name)
Exemple #17
0
def main():
    print(pydoc.plain(pydoc.render_doc(topology.mount)))
    try:
        device_name = topology.unmounted_nodes()[0]
        mount_device(device_name)
    except IndexError:
        print('All configured devices are mounted. Demonstration cancelled.')
def usage():
    usage_text = '''
    This script is a barebones version of query_cqadupstack.py which can be downloaded from https://github.com/D1Doris/CQADupStack/.

    It is called from insertrecords.cgi (see https://github.com/D1Doris/AnnotateCQADupStack), to fill a database with
    posts from CQADupStack, the StackExchange data which can be downloaded from http://nlp.cis.unimelb.edu.au/resources/cqadupstack/,
    so they can be annotated.

    The script contains a main function called load_subforum(). It has one argument: a StackExchange (CQADupStack) subforum.zip file.
    load_subforum() uses this file to create a 'Subforum' object and returns this.

    Subforum objects can be queried using the following methods:

'''

    strhelp = pydoc.render_doc(Subforum, "Help on %s")
    i = strhelp.find('below')
    strhelp = strhelp[i+9:]
    usage_text += strhelp
    usage_text += '\n\n    -----------------------------'
    usage_text += '\n\n    Here are some examples of how to use the script:'
    usage_text += '''\n\n    >>> import query_cqadupstack_barebones as qcqa
    >>> o = qcqa.load_subforum('/home/hoogeveen/datasets/CQADupStack/webmasters.zip')
    >>> o.get_posttitle('18957')
    u'What do you consider a "mobile" device?'
    >>> o.get_postbody('18957')'''
    usage_text += u'<p>I\'m implementing a mobile-friendly version of our corporate web site and will be using <a href="http://wurfl.sourceforge.net/" rel="nofollow" title="WURFL">WURFL</a> to detect mobile browsers and redirect them to our mobile site.  Having recently purchased an Android tablet, I\'ve found that many sites consider it to be a mobile device even though it has a large 10" screen and it\'s perfectly capable of handling sites designed using standard desktop resolutions.</p>\n\n<p>My plan is to use WURFL, examine the device capabilities and treat anything with a resolution width of less than 700px as a mobile device, but I\'d like some input as to that sweet spot for determining mobile vs desktop.</p>\n'
    usage_text += '\n\n    -----------------------------'
    usage_text += '\n\n    Please see the README file that came with this script for more information on the data.\n'
    print usage_text 
    sys.exit(' ')
    def test_class(self):
        class C(object): "New-style class"
        c = C()

        self.assertEqual(pydoc.describe(C), 'class C')
        self.assertEqual(pydoc.describe(c), 'C')
        expected = 'C in module %s object' % __name__
        self.assertTrue(expected in pydoc.render_doc(c))
def main():
    print(pydoc.plain(pydoc.render_doc(topology.mounted)))
    device_names = settings.config['network_device'].keys()
    if not device_names:
        print('There are no devices configured in the settings.')
    else:
        device_name = device_names[0]
        print('is_mounted(%s):' % device_name, topology.mounted(device_name))
Exemple #21
0
def main():
    print(pydoc.plain(pydoc.render_doc(topology.mount)))
    unmounted_list = topology.unmounted_nodes()
    if unmounted_list:
        for device_name in unmounted_list:
            mount_device(device_name)
    else:
        print('There are no (configured) devices unmounted.')
Exemple #22
0
def main():
    print(pydoc.plain(pydoc.render_doc(topology.mount)))
    mounted_list = topology.mounted_nodes()
    if mounted_list:
        for device_name in mounted_list:
            dismount_device(device_name)
    else:
        print('There are no mounted devices to dismount.')
Exemple #23
0
def info(r):
    """ Provides interface help """
    import rob_interface
    import pydoc
    print("===================\n")
    print(pydoc.render_doc(rob_interface))
    #help(rob_interface)
    print("===================\n")
Exemple #24
0
def main():
    print(pydoc.plain(pydoc.render_doc(topology.dismount)))
    try:
        # Select a mounted device that is in our settings.config
        device_name = next(name for name in topology.mounted_nodes() if name in settings.config['network_device'])
        dismount_device(device_name)
    except(TypeError, StopIteration):
        print('There are no mounted devices to dismount. Demonstration cancelled.')
Exemple #25
0
def fmt(name, fn):
  [puts(x, False) for x in [
    colored.blue('action'),
    " ",
    colored.red(name)
  ]]
  puts("")
  with indent(4):
    puts(pydoc.render_doc(fn, "%s"))
Exemple #26
0
    def test_classic_class(self):
        class C:
            "Classic class"

        c = C()
        self.assertEqual(pydoc.describe(C), "class C")
        self.assertEqual(pydoc.describe(c), "C")
        expected = "C in module %s" % __name__
        self.assert_(expected in pydoc.render_doc(c))
    def test_should_get_docstring(self):
        filename = self.project_file("test.py", "")
        source, offset = source_and_offset("import threading\nthreading.Thread.join_|_(")
        docstring = self.backend.rpc_get_docstring(self.project_root, filename, source, offset)

        import pydoc

        wanted = pydoc.render_doc("threading.Thread.join", "Elpy Pydoc Documentation for %s", False)
        self.assertEqual(docstring, wanted)
Exemple #28
0
 def test_should_find_documentation(self):
     source = "foo(open("
     offset = 6  # foo(op_|_en(
     docstring = pydoc.render_doc("open",
                                  "Elpy Pydoc Documentation for %s",
                                  False)
     self.assertEqual(self.backend.rpc_get_docstring(None, None,
                                                     source, offset),
                      docstring)
def main():
    print(pydoc.plain(pydoc.render_doc(topology.connected)))
    # Create list of mounted devices that are in our settings.config
    mounted_devices = [ name for name in topology.mounted_nodes() if name in settings.config['network_device'] ]
    if not mounted_devices:
        print('There are no devices mounted on the Controller.')
    else:
        device_name = mounted_devices[0]
        print('is_connected(%s):' % device_name, topology.connected(device_name))
Exemple #30
0
 def test_text_enum_member_with_value_zero(self):
     # Test issue #20654 to ensure enum member with value 0 can be
     # displayed. It used to throw KeyError: 'zero'.
     import enum
     class BinaryInteger(enum.IntEnum):
         zero = 0
         one = 1
     doc = pydoc.render_doc(BinaryInteger)
     self.assertIn('<BinaryInteger.zero: 0>', doc)
Exemple #31
0
def print_function(functions, function):
    func = get_function(functions, function)
    if func:
        print(
            pydoc.plain(pydoc.render_doc(func, "Displaying docstring for %s")))
Exemple #32
0
    # the ground object made with the ground shape. As the mass is
    # not given, it is a static object only involved in contact
    # detection.
    io.addObject('ground', [Contactor('Ground')], translation=[0, 0, 0])

# Run the simulation from the inputs previously defined and add
# results to the hdf5 file. The visualisation of the output may be done
# with the vview command.
with Hdf5(mode='r+') as io:

    # By default earth gravity is applied and the units are those
    # of the International System of Units.
    # Because of fixed collision margins used in the collision detection,
    # sizes of small objects may need to be expressed in cm or mm.
    print(pydoc.render_doc(io.run, "Help on %s"))
    io.run(with_timer=False,
           time_stepping=None,
           space_filter=None,
           body_class=None,
           shape_class=None,
           face_class=None,
           edge_class=None,
           length_scale=1,
           t0=0,
           T=10,
           h=0.0005,
           multipoints_iterations=True,
           theta=0.50001,
           Newton_max_iter=20,
           set_external_forces=None,
        def decorator(*args, **kwargs):
            exception = None
            has_error = False
            error_traceback = None

            if log_sql:
                # setup SQL logger
                output, _ = get_string_db_logger()

            # get timing
            start = time.time()
            try:
                if inspect.ismethod(func):
                    if len(args) <= 1:
                        res = func(**kwargs)
                    else:
                        res = func(args[1:], **kwargs)
                else:
                    res = func(*args, **kwargs)
            except Exception as e:
                res = None
                exception = e
                has_error = True
                error_traceback = format_exc()

            estimate = time.time() - start

            if log_sql:
                # NOTE: in case of querysets - they won't be logged if they are not evaluated yet!
                sql_log = output.getvalue()
            else:
                sql_log = None

            # try to find Request objects and get User
            try:
                user = kwargs['request'].user
            except (KeyError, AttributeError):
                user = None
            if user is None:
                request_objs = [i for i in args if isinstance(i, (HttpRequest, Request))
                                and hasattr(i, 'user') and isinstance(i.user, User)]
                for request_obj in request_objs:
                    if request_obj.user:
                        user = request_obj.user
                        break

            func_name = func.__name__
            fun_args = inspect.signature(func).parameters  # ['self'].__class__.__name__
            if fun_args and 'self' in fun_args:
                func_self = fun_args["self"]
                if func_self:
                    func_name = f'{func_self.__class__.__name__}.{func_name}'

            method_stats = MethodStats(
                user=user,
                time=estimate,
                name=name,
                comment=comment,
                method=func_name,
                path=get_func_path(func, *args, **kwargs),
                description=pydoc.render_doc(func, title='%s', renderer=pydoc.plaintext),
                sql_log=sql_log,
                args=str(args),
                kwargs=str(kwargs),
                # decorator adds extra depth, so set start to 3
                callers=callers(depth=callers_depth, start=3),
                has_error=has_error,
                error_traceback=error_traceback
            )
            cache_key = 'MethodStats_' + name
            cached_res, resume = redis.push_or_pop(cache_key, method_stats, batch_size, batch_time)
            if resume:
                MethodStats.objects.bulk_create(cached_res)

            if exception is not None:
                raise exception

            return res
Exemple #34
0
def render_doc(obj):
    return trim_whitespace(pydoc.render_doc(obj, renderer=pydoc.plaintext))
Exemple #35
0
 def help(cls):
     """
     The Lone's help.
     """
     return pydoc.render_doc(cls, title='Lone Documentation: %s')
Exemple #36
0
def show_help(object_to_help_with):
    help_contents = pydoc.render_doc(object_to_help_with)
    help_contents = re.sub(r'={.*}', '={...trimmed...}', help_contents)
    help_contents = re.sub(r'=\[.*\]', '=[...trimmed...]', help_contents)
    pydoc.pager(help_contents)
dict_result = instance.get_dict_2()
dict_result['key2'] = 'value2'
instance.print_dict_2(dict_result)

set_result = instance.get_set()
set_result.add(u'key3')
instance.print_set(set_result)

set_result = instance.get_set2()
set_result.add(u'key3')
instance.print_set_2(set_result)

list_result = instance.get_list()
list_result.append('value2')
instance.print_list(list_result)

list_result = instance.get_list_2()
list_result.append('value2')
instance.print_list_2(list_result)

try:
    instance.throw_exception()
except Exception as e:
    print(e)

print(instance.pair_passthrough((True, "test")))
print(instance.tuple_passthrough((True, "test", 5)))

print(pydoc.render_doc(Example2, "Help on %s"))
import pydoc
from view import viewImage
from GUI.mainWindow import Ui_MainWindow
from controller.controllerDate import ControllerDate
from view.viewImage import ViewImage

h = pydoc.render_doc(ViewImage)
print(h)
Exemple #39
0
 def _get_summary_line(o):
     text = pydoc.plain(pydoc.render_doc(o))
     lines = text.split('\n')
     assert len(lines) >= 2
     return lines[2]
Exemple #40
0
    def test_method_aliases(self):
        class A:
            def tkraise(self, aboveThis=None):
                """Raise this widget in the stacking order."""

            lift = tkraise

            def a_size(self):
                """Return size"""

        class B(A):
            def itemconfigure(self, tagOrId, cnf=None, **kw):
                """Configure resources of an item TAGORID."""

            itemconfig = itemconfigure
            b_size = A.a_size

        doc = pydoc.render_doc(B)
        # clean up the extra text formatting that pydoc performs
        doc = re.sub('\b.', '', doc)
        self.assertEqual(
            doc, '''\
Python Library Documentation: class B in module %s

class B(A)
 |  Method resolution order:
 |      B
 |      A
 |      builtins.object
 |\x20\x20
 |  Methods defined here:
 |\x20\x20
 |  b_size = a_size(self)
 |\x20\x20
 |  itemconfig = itemconfigure(self, tagOrId, cnf=None, **kw)
 |\x20\x20
 |  itemconfigure(self, tagOrId, cnf=None, **kw)
 |      Configure resources of an item TAGORID.
 |\x20\x20
 |  ----------------------------------------------------------------------
 |  Methods inherited from A:
 |\x20\x20
 |  a_size(self)
 |      Return size
 |\x20\x20
 |  lift = tkraise(self, aboveThis=None)
 |\x20\x20
 |  tkraise(self, aboveThis=None)
 |      Raise this widget in the stacking order.
 |\x20\x20
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from A:
 |\x20\x20
 |  __dict__
 |      dictionary for instance variables (if defined)
 |\x20\x20
 |  __weakref__
 |      list of weak references to the object (if defined)
''' % __name__)

        doc = pydoc.render_doc(B, renderer=pydoc.HTMLDoc())
        self.assertEqual(
            doc, '''\
Python Library Documentation: class B in module %s

<p>
<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#ffc8d8">
<td colspan=3 valign=bottom>&nbsp;<br>
<font color="#000000" face="helvetica, arial"><a name="B">class <strong>B</strong></a>(A)</font></td></tr>
\x20\x20\x20\x20
<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
<td width="100%%"><dl><dt>Method resolution order:</dt>
<dd>B</dd>
<dd>A</dd>
<dd><a href="builtins.html#object">builtins.object</a></dd>
</dl>
<hr>
Methods defined here:<br>
<dl><dt><a name="B-b_size"><strong>b_size</strong></a> = <a href="#B-a_size">a_size</a>(self)</dt></dl>

<dl><dt><a name="B-itemconfig"><strong>itemconfig</strong></a> = <a href="#B-itemconfigure">itemconfigure</a>(self, tagOrId, cnf=None, **kw)</dt></dl>

<dl><dt><a name="B-itemconfigure"><strong>itemconfigure</strong></a>(self, tagOrId, cnf=None, **kw)</dt><dd><tt>Configure&nbsp;resources&nbsp;of&nbsp;an&nbsp;item&nbsp;TAGORID.</tt></dd></dl>

<hr>
Methods inherited from A:<br>
<dl><dt><a name="B-a_size"><strong>a_size</strong></a>(self)</dt><dd><tt>Return&nbsp;size</tt></dd></dl>

<dl><dt><a name="B-lift"><strong>lift</strong></a> = <a href="#B-tkraise">tkraise</a>(self, aboveThis=None)</dt></dl>

<dl><dt><a name="B-tkraise"><strong>tkraise</strong></a>(self, aboveThis=None)</dt><dd><tt>Raise&nbsp;this&nbsp;widget&nbsp;in&nbsp;the&nbsp;stacking&nbsp;order.</tt></dd></dl>

<hr>
Data descriptors inherited from A:<br>
<dl><dt><strong>__dict__</strong></dt>
<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
</dl>
<dl><dt><strong>__weakref__</strong></dt>
<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
</dl>
</td></tr></table>\
''' % __name__)
Exemple #41
0
def shelp(thing):
    return HelpDoc(pydoc.render_doc(thing, renderer=SummaryDoc()))
Exemple #42
0
import pydoc
from view import viewDate
from GUI.mainWindow import Ui_MainWindow
from controller.controllerDate import ControllerDate
from view.viewDate import ViewDate

h = pydoc.render_doc(ViewDate)
print(h)
Exemple #43
0
# Simply run this module (no inputs or modifications needed) to update the help
# files for all of the gappack modules.
#

import sys, pydoc, os

#Where's the config module? Must be named gapconfig.py
sys.path.append("")
#Where's the gappack code located?
sys.path.append('')
import gapproduction as gp

helpDir = '/GAPProduction/documentation'
if not os.path.exists(helpDir):
    os.makedirs(helpDir)

for mod in gp.__all__:
    s = pydoc.plain(pydoc.render_doc('gapproduction.' + mod))
    gp.docs.Write(os.path.join(helpDir, 'Help_' + mod + '.txt'), s, 'o')
 def test_module(self):
     # Check that pydocfodder module can be described
     from test import pydocfodder
     doc = pydoc.render_doc(pydocfodder)
     self.assertIn("pydocfodder", doc)
Exemple #45
0
def strHelp(topic):
    return pydoc.plain(pydoc.render_doc(topic))
Exemple #46
0
 def help(self, obj):
     self.print(pydoc.render_doc(obj))
Exemple #47
0
 def test_should_find_documentation(self):
     docstring = pydoc.render_doc("open", "Elpy Pydoc Documentation for %s",
                                  False)
     self.assertEqual(self.backend.rpc_get_pydoc_documentation("open"),
                      docstring)
Exemple #48
0
        print(
            f"Here's every argument by name, with defaults: {arguments.arguments}"
        )
        # Let's make the surname uppercase
        arguments.arguments["surname"] = arguments.arguments["surname"].upper()
        # Call the function that we've wrapped
        func(*arguments.args, **arguments.kwargs)

    return wrapper


# Decorate the example


@my_decorator
def greet(forename: str, surname: str, *, greeting: str = "Hello"):
    """
    Greets a named person
    """
    print(f"{greeting} {forename} {surname}")


# Try the decorated function.

greet("Gabriel", "Utterson")
greet("Gabriel", "Utterson", greeting="Hi")

# All the docs have been preserved:

print(pydoc.render_doc(greet))
def spec(func):
    """return a string with Python function specification"""
    doc = pydoc.plain(pydoc.render_doc(func))
    return doc.splitlines()[2]
Exemple #50
0
    def represent(value_):

        value = value_

        if isinstance(value, Module):
            value = value.__dict__

        try:
            repr_value = repr(value)
            __inspected_times__[repr_value] = __inspected_times__.get(
                repr_value, 0) + 1
            if __inspected_times__[repr_value] > 5:
                return repr_value
        except Exception as e:
            pass

        if isinstance(value, list):
            dictionnary = {}
            for i, value_ in enumerate(value):
                if isinstance(value_, (rubicon.objc.api.ObjCClass,
                                       rubicon.objc.api.ObjCInstance)):
                    dictionnary[str(i)] = value
                elif isinstance(value_, (dict, list)):
                    dictionnary[str(i)] = represent(value_.copy())
                elif callable(value_):
                    dictionnary[str(i)] = pydoc.render_doc(
                        value_).splitlines()[2]
                else:
                    dictionnary[str(i)] = repr(value_)
            return dictionnary

        elif type(value) is dict:

            dictionnary = {}
            for key_, value_ in value.items():
                if isinstance(value_, (rubicon.objc.api.ObjCClass,
                                       rubicon.objc.api.ObjCInstance)):
                    dictionnary[repr(key_)] = value_
                elif isinstance(value_, (dict, list)):
                    dictionnary[repr(key_)] = represent(value_.copy())
                elif callable(value_):
                    dictionnary[repr(key)] = pydoc.render_doc(
                        value_).splitlines()[2]
                else:
                    dictionnary[repr(key_)] = repr(value_)
            return dictionnary
        elif isinstance(
                value,
            (rubicon.objc.api.ObjCClass, rubicon.objc.api.ObjCInstance)):
            return value
        elif isinstance(
                value,
                str) and not value.startswith("'") and not value.endswith("'"):
            return "'" + value + "'"
        else:
            try:
                if callable(value) or isinstance(value, int) or isinstance(
                        value, float):
                    raise AttributeError
                return get_variables_hierarchy(value)
            except AttributeError:
                return repr(value)
Exemple #51
0
        self.name = name
        self.sound = sound
        self.num_legs = num_legs

    def says(self, sound: Optional[str] = None):
        # NumPy/SciPy Docstrings Example
        """Print what the animals name is and what sound it makes.

        If the argument `sound` isn't passed in, the default Animal sound is used.

        Parameters
        ----------
        sound : Optional[str]
            The sound the animal makes (default is None)

        Raises
        ------
        NotImplementedError
            If no sound is set for the animal or passed in as a parameter.
        """

        if self.sound is None and sound is None:
            raise NotImplementedError("Silent Animals are not supported!")

        out_sound = self.sound if sound is None else sound
        print(self.says_str.format(name=self.name, sound=out_sound))


print(render_doc(Animal))
# print(Animal.__doc__)
Exemple #52
0
import pydoc
from controller.controllerImage import ControllerImage

h = pydoc.render_doc(ControllerImage)
print(h)
 def test_render_doc(self):
     # render_doc is robust against unicode in docstrings
     doc = pydoc.render_doc(self.Q)
     self.assertIsInstance(doc, str)
Exemple #54
0
#!/usr/bin/env python3
# Software License Agreement (BSD License)
#
# Copyright (c) 2017, UFactory, Inc.
# All rights reserved.
#
# Author: Duke Fong <*****@*****.**>

import sys, os
import pydoc

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

from uf.wrapper.swift_api import SwiftAPI
from doc.markdown_doc import MarkdownDoc

#open('swift_api.md', 'w').write(pydoc.render_doc(SwiftAPI, renderer = pydoc.HTMLDoc()))
open('swift_api.md',
     'w').write(pydoc.render_doc(SwiftAPI, renderer=MarkdownDoc()))
print('done ...')
Exemple #55
0
 def test_render(self):
     pydoc.render_doc(drgn)
#!/usr/bin/env python
from __future__ import print_function
import sys
import pydoc

sys.path.append('.')

from example import kw_func, kw_func2, kw_func3, kw_func4, call_kw_func
from example import args_function, args_kwargs_function, kw_func_udl

print(pydoc.render_doc(kw_func, "Help on %s"))
print(pydoc.render_doc(kw_func2, "Help on %s"))
print(pydoc.render_doc(kw_func3, "Help on %s"))
print(pydoc.render_doc(kw_func4, "Help on %s"))
print(pydoc.render_doc(kw_func_udl, "Help on %s"))

kw_func(5, 10)
kw_func(5, y=10)
kw_func(y=10, x=5)

kw_func2()

kw_func2(5)
kw_func2(x=5)

kw_func2(y=10)

kw_func2(5, 10)
kw_func2(x=5, y=10)

try:
Exemple #57
0
from my_package import calculator


def output_help_to_file(filepath, request):
    with open(filepath, "w") as f:
        sys.stdout = f
        pydoc.help(request)
        f.close()
    sys.stdout = sys.__stdout__
    return


if __name__ == "__main__":
    if not os.path.exists("docs"):
        os.mkdir("docs")

    output_help_to_file(r"docs/calculator.txt", calculator)
    output_help_to_file(r"docs/math.txt", "math")

    # print(dir(__name__))
    # print()
    # print(__name__.__doc__)

    print(pydoc.help(__name__))
    print()
    print(pydoc.render_doc(__name__))

    with open("docs/__name__.txt", "w") as a:
        a.write(pydoc.render_doc(__name__))
        a.close()

argvi = 1
mindist = 50
minscore = 2
mu = -4
sigma = 4
assignexplv = True

allfile = []

distype = "lognormal"

while argvi < (len(sys.argv)):
    if sys.argv[argvi] == "-h" or sys.argv[argvi] == "--help":
        print(pydoc.render_doc(sys.modules[__name__]), file=sys.stderr)
        sys.exit()
    elif sys.argv[argvi] == "-f" or sys.argv[argvi] == "--statonly":
        assignexplv = False
    elif sys.argv[argvi] == "-e" or sys.argv[argvi] == "--lognormal":
        distype = "lognormal"
        ms = sys.argv[argvi + 1].split(",")
        argvi = argvi + 1
        if len(ms) != 2:
            print('Error: incorrect parameter for -e.', file=sys.stderr)
            sys.exit()
        try:
            mu = float(ms[0])
            sigma = float(ms[1])
        except ValueError:
            print('Error: incorrect parameter for -e.', file=sys.stderr)
import random;
import bisect;
import math;
from getSegs import *;

import pdb;

# read length
readlen=32;
# number of reads to sample
readcnt=100000;

nfield=7;

if len(sys.argv)<2:
  print(pydoc.render_doc(sys.modules[__name__]));
  sys.exit();

allids={};
allidl=[];
allexp=[];

posweight=[];

#onbedfile=sys.argv[-1]+'.reads.bed';
onbedfile="-";

genpereads=False;
pemean=200;
pestd=20;
Exemple #60
0
    def _parse(self, package, module, function):
        """
        Get pydoc output on the module generated and parse that output to
        extract information about data members and methods

        package  - Package that the module belongs to (type: str)
        module   - Hierarchically sorted list of modules(type: list)
        function - Function/Class of interest (type: str)
        """
        pac = __import__('%s' % package)
        mod = pac
        for modul in module:
            mod = getattr(mod, '%s' % modul)
        func = None
        for prx_mod in self.proxy_modules:
            try:
                proxy_mod = getattr(mod, '%s' % prx_mod)
                func = getattr(proxy_mod, '%s' % function)
            except AttributeError:
                continue
            break
        if not func:
            raise Exception, 'Proxy not found: %s %s' % (function, modul)
        doc_to_parse = pydoc.render_doc(func)
        doc_to_parse = re.sub(r'\x08.', '', doc_to_parse)
        # Append a block completion line at the very end for easier regex matches
        doc_to_parse = doc_to_parse + " |"\
        "  ----------------------------------------------------------------------\n"

        desc = re.search(r'(?<=SourceProxy\)).+?(?=Method resolution order)',
                         doc_to_parse, re.DOTALL)
        if desc:
            desc = desc.group()
            common_desc = re.search(
                r'(Proxy for a server).+?(vtkSMProxy C\+\+ class.)', desc,
                re.DOTALL)
            if common_desc:
                desc = re.sub(common_desc.re, '', desc)
            self.desc = desc.replace('|', '').strip()

        data_mems = re.search(
            r'(?<=Data descriptors defined here:).+?(?=---------)',
            doc_to_parse, re.DOTALL)
        if data_mems:
            self.data_mems = data_mems.group().replace('|', '')

        inh_data_mems = re.findall(
            r'(?<=Data descriptors inherited from).+?(?=-------)',
            doc_to_parse, re.DOTALL)
        for mem in inh_data_mems:
            inh_data_mem_class = re.search(r'.+?(?=:)(:)', mem)
            self.inh_data_mems[inh_data_mem_class.group().replace(':','').strip()] =\
                re.sub(inh_data_mem_class.re, '', mem).replace('|','')

        method_mems = re.search(r'(?<=Methods defined here:).+?(?=--------)',
                                doc_to_parse, re.DOTALL)
        if method_mems:
            self.method_mems = method_mems.group().replace('|', '')

        inh_method_mems = re.findall(
            r'(?<=Methods inherited from).+?(?=--------)', doc_to_parse,
            re.DOTALL)
        for mem in inh_method_mems:
            inh_method_mem_class = re.search(r'.+?(?=:)(:)', mem)
            self.inh_method_mems[inh_method_mem_class.group().replace(':','').strip()] =\
                re.sub(inh_method_mem_class.re, '', mem).replace('|','')