code
stringlengths
26
870k
docstring
stringlengths
1
65.6k
func_name
stringlengths
1
194
language
stringclasses
1 value
repo
stringlengths
8
68
path
stringlengths
5
194
url
stringlengths
46
254
license
stringclasses
4 values
def test_copy(self): """Test the copy event.""" # Testing with the actual clipboard proved problematic, so this # test replaces the clipboard manipulation functions with mocks # and checks that they are called appropriately. squeezer = self.make_mock_squeezer() expandingbutton = ExpandingButton('TEXT', 'TAGS', 50, squeezer) expandingbutton.clipboard_clear = Mock() expandingbutton.clipboard_append = Mock() # Trigger the copy event. retval = expandingbutton.copy(event=Mock()) self.assertEqual(retval, None) # Vheck that the expanding button called clipboard_clear() and # clipboard_append('TEXT') once each. self.assertEqual(expandingbutton.clipboard_clear.call_count, 1) self.assertEqual(expandingbutton.clipboard_append.call_count, 1) expandingbutton.clipboard_append.assert_called_with('TEXT')
Test the copy event.
test_copy
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_squeezer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_squeezer.py
MIT
def test_view(self): """Test the view event.""" squeezer = self.make_mock_squeezer() expandingbutton = ExpandingButton('TEXT', 'TAGS', 50, squeezer) expandingbutton.selection_own = Mock() with patch('idlelib.squeezer.view_text', autospec=view_text)\ as mock_view_text: # Trigger the view event. expandingbutton.view(event=Mock()) # Check that the expanding button called view_text. self.assertEqual(mock_view_text.call_count, 1) # Check that the proper text was passed. self.assertEqual(mock_view_text.call_args[0][2], 'TEXT')
Test the view event.
test_view
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_squeezer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_squeezer.py
MIT
def test_rmenu(self): """Test the context menu.""" squeezer = self.make_mock_squeezer() expandingbutton = ExpandingButton('TEXT', 'TAGS', 50, squeezer) with patch('tkinter.Menu') as mock_Menu: mock_menu = Mock() mock_Menu.return_value = mock_menu mock_event = Mock() mock_event.x = 10 mock_event.y = 10 expandingbutton.context_menu_event(event=mock_event) self.assertEqual(mock_menu.add_command.call_count, len(expandingbutton.rmenu_specs)) for label, *data in expandingbutton.rmenu_specs: mock_menu.add_command.assert_any_call(label=label, command=ANY)
Test the context menu.
test_rmenu
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_squeezer.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_squeezer.py
MIT
def __init__(self, master=None, cnf={}, **kw): '''Initialize mock, non-gui, text-only Text widget. At present, all args are ignored. Almost all affect visual behavior. There are just a few Text-only options that affect text behavior. ''' self.data = ['', '\n']
Initialize mock, non-gui, text-only Text widget. At present, all args are ignored. Almost all affect visual behavior. There are just a few Text-only options that affect text behavior.
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/mock_tk.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/mock_tk.py
MIT
def _decode(self, index, endflag=0): """Return a (line, char) tuple of int indexes into self.data. This implements .index without converting the result back to a string. The result is constrained by the number of lines and linelengths of self.data. For many indexes, the result is initially (1, 0). The input index may have any of several possible forms: * line.char float: converted to 'line.char' string; * 'line.char' string, where line and char are decimal integers; * 'line.char lineend', where lineend='lineend' (and char is ignored); * 'line.end', where end='end' (same as above); * 'insert', the positions before terminal \n; * 'end', whose meaning depends on the endflag passed to ._endex. * 'sel.first' or 'sel.last', where sel is a tag -- not implemented. """ if isinstance(index, (float, bytes)): index = str(index) try: index=index.lower() except AttributeError: raise TclError('bad text index "%s"' % index) from None lastline = len(self.data) - 1 # same as number of text lines if index == 'insert': return lastline, len(self.data[lastline]) - 1 elif index == 'end': return self._endex(endflag) line, char = index.split('.') line = int(line) # Out of bounds line becomes first or last ('end') index if line < 1: return 1, 0 elif line > lastline: return self._endex(endflag) linelength = len(self.data[line]) -1 # position before/at \n if char.endswith(' lineend') or char == 'end': return line, linelength # Tk requires that ignored chars before ' lineend' be valid int # Out of bounds char becomes first or last index of line char = int(char) if char < 0: char = 0 elif char > linelength: char = linelength return line, char
Return a (line, char) tuple of int indexes into self.data. This implements .index without converting the result back to a string. The result is constrained by the number of lines and linelengths of self.data. For many indexes, the result is initially (1, 0). The input index may have any of several possible forms: * line.char float: converted to 'line.char' string; * 'line.char' string, where line and char are decimal integers; * 'line.char lineend', where lineend='lineend' (and char is ignored); * 'line.end', where end='end' (same as above); * 'insert', the positions before terminal \n; * 'end', whose meaning depends on the endflag passed to ._endex. * 'sel.first' or 'sel.last', where sel is a tag -- not implemented.
_decode
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/mock_tk.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/mock_tk.py
MIT
def _endex(self, endflag): '''Return position for 'end' or line overflow corresponding to endflag. -1: position before terminal \n; for .insert(), .delete 0: position after terminal \n; for .get, .delete index 1 1: same viewed as beginning of non-existent next line (for .index) ''' n = len(self.data) if endflag == 1: return n, 0 else: n -= 1 return n, len(self.data[n]) + endflag
Return position for 'end' or line overflow corresponding to endflag. -1: position before terminal \n; for .insert(), .delete 0: position after terminal \n; for .get, .delete index 1 1: same viewed as beginning of non-existent next line (for .index)
_endex
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/mock_tk.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/mock_tk.py
MIT
def delete(self, index1, index2=None): '''Delete slice from index1 to index2 (default is 'index1+1'). Adjust default index2 ('index+1) for line ends. Do not delete the terminal \n at the very end of self.data ([-1][-1]). ''' startline, startchar = self._decode(index1, -1) if index2 is None: if startchar < len(self.data[startline])-1: # not deleting \n endline, endchar = startline, startchar+1 elif startline < len(self.data) - 1: # deleting non-terminal \n, convert 'index1+1 to start of next line endline, endchar = startline+1, 0 else: # do not delete terminal \n if index1 == 'insert' return else: endline, endchar = self._decode(index2, -1) # restricting end position to insert position excludes terminal \n if startline == endline and startchar < endchar: self.data[startline] = self.data[startline][:startchar] + \ self.data[startline][endchar:] elif startline < endline: self.data[startline] = self.data[startline][:startchar] + \ self.data[endline][endchar:] startline += 1 for i in range(startline, endline+1): del self.data[startline]
Delete slice from index1 to index2 (default is 'index1+1'). Adjust default index2 ('index+1) for line ends. Do not delete the terminal \n at the very end of self.data ([-1][-1]).
delete
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/mock_tk.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/mock_tk.py
MIT
def bar(s='a'*100): """Hello Guido""" pass
Hello Guido
test_properly_formated.bar
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_calltip.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_calltip.py
MIT
def test_properly_formated(self): def foo(s='a'*100): pass def bar(s='a'*100): """Hello Guido""" pass def baz(s='a'*100, z='b'*100): pass indent = calltip._INDENT sfoo = "(s='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"\ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + indent + "aaaaaaaaa"\ "aaaaaaaaaa')" sbar = "(s='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"\ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + indent + "aaaaaaaaa"\ "aaaaaaaaaa')\nHello Guido" sbaz = "(s='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"\ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + indent + "aaaaaaaaa"\ "aaaaaaaaaa', z='bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"\ "bbbbbbbbbbbbbbbbb\n" + indent + "bbbbbbbbbbbbbbbbbbbbbb"\ "bbbbbbbbbbbbbbbbbbbbbb')" for func,doc in [(foo, sfoo), (bar, sbar), (baz, sbaz)]: with self.subTest(func=func, doc=doc): self.assertEqual(get_spec(func), doc)
Hello Guido
test_properly_formated
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_calltip.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_calltip.py
MIT
def mock_config(self): """Return a mocked idleConf Both default and user config used the same config-*.def """ conf = config.IdleConf(_utest=True) for ctype in conf.config_types: conf.defaultCfg[ctype] = config.IdleConfParser('') conf.defaultCfg[ctype].read_string(self.config_string[ctype]) conf.userCfg[ctype] = config.IdleUserConfParser('') conf.userCfg[ctype].read_string(self.config_string[ctype]) return conf
Return a mocked idleConf Both default and user config used the same config-*.def
mock_config
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_config.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_config.py
MIT
def test_dialog_title(self): """Test about dialog title""" self.assertEqual(self.dialog.title(), 'About IDLE')
Test about dialog title
test_dialog_title
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_help_about.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_help_about.py
MIT
def test_dialog_logo(self): """Test about dialog logo.""" path, file = os.path.split(self.dialog.icon_image['file']) fn, ext = os.path.splitext(file) self.assertEqual(fn, 'idle_48')
Test about dialog logo.
test_dialog_logo
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_help_about.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_help_about.py
MIT
def test_printer_buttons(self): """Test buttons whose commands use printer function.""" dialog = self.dialog button_sources = [(dialog.py_license, license, 'license'), (dialog.py_copyright, copyright, 'copyright'), (dialog.py_credits, credits, 'credits')] for button, printer, name in button_sources: with self.subTest(name=name): printer._Printer__setup() button.invoke() get = dialog._current_textview.viewframe.textframe.text.get lines = printer._Printer__lines if len(lines) < 2: self.fail(name + ' full text was not found') self.assertEqual(lines[0], get('1.0', '1.end')) self.assertEqual(lines[1], get('2.0', '2.end')) dialog._current_textview.destroy()
Test buttons whose commands use printer function.
test_printer_buttons
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_help_about.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_help_about.py
MIT
def test_file_buttons(self): """Test buttons that display files.""" dialog = self.dialog button_sources = [(self.dialog.readme, 'README.txt', 'readme'), (self.dialog.idle_news, 'NEWS.txt', 'news'), (self.dialog.idle_credits, 'CREDITS.txt', 'credits')] for button, filename, name in button_sources: with self.subTest(name=name): button.invoke() fn = findfile(filename, subdir='idlelib') get = dialog._current_textview.viewframe.textframe.text.get with open(fn, encoding='utf-8') as f: self.assertEqual(f.readline().strip(), get('1.0', '1.end')) f.readline() self.assertEqual(f.readline().strip(), get('3.0', '3.end')) dialog._current_textview.destroy()
Test buttons that display files.
test_file_buttons
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_help_about.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_help_about.py
MIT
def test_dialog_title(self): """Test about dialog title""" self.assertEqual(self.dialog.title(), f'About IDLE {python_version()}' f' ({help_about.build_bits()} bit)')
Test about dialog title
test_dialog_title
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_help_about.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_help_about.py
MIT
def test_sidebar_text_width(self): """ Test that linenumber text widget is always at the minimum width """ def get_width(): return self.linenumber.sidebar_text.config()['width'][-1] self.assert_sidebar_n_lines(1) self.assertEqual(get_width(), 1) self.text.insert('insert', 'foo') self.assert_sidebar_n_lines(1) self.assertEqual(get_width(), 1) self.text.insert('insert', 'foo\n'*8) self.assert_sidebar_n_lines(9) self.assertEqual(get_width(), 1) self.text.insert('insert', 'foo\n') self.assert_sidebar_n_lines(10) self.assertEqual(get_width(), 2) self.text.insert('insert', 'foo\n') self.assert_sidebar_n_lines(11) self.assertEqual(get_width(), 2) self.text.delete('insert -1l linestart', 'insert linestart') self.assert_sidebar_n_lines(10) self.assertEqual(get_width(), 2) self.text.delete('insert -1l linestart', 'insert linestart') self.assert_sidebar_n_lines(9) self.assertEqual(get_width(), 1) self.text.insert('insert', 'foo\n'*90) self.assert_sidebar_n_lines(99) self.assertEqual(get_width(), 2) self.text.insert('insert', 'foo\n') self.assert_sidebar_n_lines(100) self.assertEqual(get_width(), 3) self.text.insert('insert', 'foo\n') self.assert_sidebar_n_lines(101) self.assertEqual(get_width(), 3) self.text.delete('insert -1l linestart', 'insert linestart') self.assert_sidebar_n_lines(100) self.assertEqual(get_width(), 3) self.text.delete('insert -1l linestart', 'insert linestart') self.assert_sidebar_n_lines(99) self.assertEqual(get_width(), 2) self.text.delete('50.0 -1c', 'end -1c') self.assert_sidebar_n_lines(49) self.assertEqual(get_width(), 2) self.text.delete('5.0 -1c', 'end -1c') self.assert_sidebar_n_lines(4) self.assertEqual(get_width(), 1) # Note: Text widgets always keep a single '\n' character at the end. self.text.delete('1.0', 'end -1c') self.assert_sidebar_n_lines(1) self.assertEqual(get_width(), 1)
Test that linenumber text widget is always at the minimum width
test_sidebar_text_width
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_sidebar.py
MIT
def lerp(a, b, steps): """linearly interpolate from a to b (inclusive) in equal steps""" last_step = steps - 1 for i in range(steps): yield ((last_step - i) / last_step) * a + (i / last_step) * b
linearly interpolate from a to b (inclusive) in equal steps
simulate_drag.lerp
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_sidebar.py
MIT
def simulate_drag(self, start_line, end_line): start_x, start_y = self.get_line_screen_position(start_line) end_x, end_y = self.get_line_screen_position(end_line) self.linenumber.sidebar_text.event_generate('<Button-1>', x=start_x, y=start_y) self.root.update() def lerp(a, b, steps): """linearly interpolate from a to b (inclusive) in equal steps""" last_step = steps - 1 for i in range(steps): yield ((last_step - i) / last_step) * a + (i / last_step) * b for x, y in zip( map(int, lerp(start_x, end_x, steps=11)), map(int, lerp(start_y, end_y, steps=11)), ): self.linenumber.sidebar_text.event_generate('<B1-Motion>', x=x, y=y) self.root.update() self.linenumber.sidebar_text.event_generate('<ButtonRelease-1>', x=end_x, y=end_y) self.root.update()
linearly interpolate from a to b (inclusive) in equal steps
simulate_drag
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_sidebar.py
MIT
def test_paren_styles(self): """ Test ParenMatch with each style. """ text = self.text pm = self.get_parenmatch() for style, range1, range2 in ( ('opener', ('1.10', '1.11'), ('1.10', '1.11')), ('default',('1.10', '1.11'),('1.10', '1.11')), ('parens', ('1.14', '1.15'), ('1.15', '1.16')), ('expression', ('1.10', '1.15'), ('1.10', '1.16'))): with self.subTest(style=style): text.delete('1.0', 'end') pm.STYLE = style text.insert('insert', 'def foobar(a, b') pm.flash_paren_event('event') self.assertIn('<<parenmatch-check-restore>>', text.event_info()) if style == 'parens': self.assertTupleEqual(text.tag_nextrange('paren', '1.0'), ('1.10', '1.11')) self.assertTupleEqual( text.tag_prevrange('paren', 'end'), range1) text.insert('insert', ')') pm.restore_event() self.assertNotIn('<<parenmatch-check-restore>>', text.event_info()) self.assertEqual(text.tag_prevrange('paren', 'end'), ()) pm.paren_closed_event('event') self.assertTupleEqual( text.tag_prevrange('paren', 'end'), range2)
Test ParenMatch with each style.
test_paren_styles
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_parenmatch.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_parenmatch.py
MIT
def test_paren_corner(self): """ Test corner cases in flash_paren_event and paren_closed_event. These cases force conditional expression and alternate paths. """ text = self.text pm = self.get_parenmatch() text.insert('insert', '# this is a commen)') pm.paren_closed_event('event') text.insert('insert', '\ndef') pm.flash_paren_event('event') pm.paren_closed_event('event') text.insert('insert', ' a, *arg)') pm.paren_closed_event('event')
Test corner cases in flash_paren_event and paren_closed_event. These cases force conditional expression and alternate paths.
test_paren_corner
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_parenmatch.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_parenmatch.py
MIT
def test_dump_event(self): """ Dump_event cannot be tested directly without changing environment variables. So, test statements in dump_event indirectly """ text = self.text d = self.delegator text.insert('insert', 'foo') text.insert('insert', 'bar') text.delete('1.2', '1.4') self.assertTupleEqual((d.pointer, d.can_merge), (3, True)) text.event_generate('<<undo>>') self.assertTupleEqual((d.pointer, d.can_merge), (2, False))
Dump_event cannot be tested directly without changing environment variables. So, test statements in dump_event indirectly
test_dump_event
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_undo.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/idle_test/test_undo.py
MIT
def wrapper(*args, **kwds): """Wrapper function that initializes curses and calls another function, restoring normal keyboard/screen behavior on error. The callable object 'func' is then passed the main window 'stdscr' as its first argument, followed by any other arguments passed to wrapper(). """ if args: func, *args = args elif 'func' in kwds: func = kwds.pop('func') else: raise TypeError('wrapper expected at least 1 positional argument, ' 'got %d' % len(args)) try: # Initialize curses stdscr = initscr() # Turn off echoing of keys, and enter cbreak mode, # where no buffering is performed on keyboard input noecho() cbreak() # In keypad mode, escape sequences for special keys # (like the cursor keys) will be interpreted and # a special value like curses.KEY_LEFT will be returned stdscr.keypad(1) # Start color, too. Harmless if the terminal doesn't have # color; user can test with has_color() later on. The try/catch # works around a minor bit of over-conscientiousness in the curses # module -- the error return from C start_color() is ignorable. try: start_color() except: pass return func(stdscr, *args, **kwds) finally: # Set everything back to normal if 'stdscr' in locals(): stdscr.keypad(0) echo() nocbreak() endwin()
Wrapper function that initializes curses and calls another function, restoring normal keyboard/screen behavior on error. The callable object 'func' is then passed the main window 'stdscr' as its first argument, followed by any other arguments passed to wrapper().
wrapper
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/curses/__init__.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/curses/__init__.py
MIT
def rectangle(win, uly, ulx, lry, lrx): """Draw a rectangle with corners at the provided upper-left and lower-right coordinates. """ win.vline(uly+1, ulx, curses.ACS_VLINE, lry - uly - 1) win.hline(uly, ulx+1, curses.ACS_HLINE, lrx - ulx - 1) win.hline(lry, ulx+1, curses.ACS_HLINE, lrx - ulx - 1) win.vline(uly+1, lrx, curses.ACS_VLINE, lry - uly - 1) win.addch(uly, ulx, curses.ACS_ULCORNER) win.addch(uly, lrx, curses.ACS_URCORNER) win.addch(lry, lrx, curses.ACS_LRCORNER) win.addch(lry, ulx, curses.ACS_LLCORNER)
Draw a rectangle with corners at the provided upper-left and lower-right coordinates.
rectangle
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/curses/textpad.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/curses/textpad.py
MIT
def _end_of_line(self, y): """Go to the location of the first blank on the given line, returning the index of the last non-blank character.""" self._update_max_yx() last = self.maxx while True: if curses.ascii.ascii(self.win.inch(y, last)) != curses.ascii.SP: last = min(self.maxx, last+1) break elif last == 0: break last = last - 1 return last
Go to the location of the first blank on the given line, returning the index of the last non-blank character.
_end_of_line
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/curses/textpad.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/curses/textpad.py
MIT
def resolve_dotted_attribute(obj, attr, allow_dotted_names=True): """resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d Resolves a dotted attribute name to an object. Raises an AttributeError if any attribute in the chain starts with a '_'. If the optional allow_dotted_names argument is false, dots are not supported and this function operates similar to getattr(obj, attr). """ if allow_dotted_names: attrs = attr.split('.') else: attrs = [attr] for i in attrs: if i.startswith('_'): raise AttributeError( 'attempt to access private attribute "%s"' % i ) else: obj = getattr(obj,i) return obj
resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d Resolves a dotted attribute name to an object. Raises an AttributeError if any attribute in the chain starts with a '_'. If the optional allow_dotted_names argument is false, dots are not supported and this function operates similar to getattr(obj, attr).
resolve_dotted_attribute
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def list_public_methods(obj): """Returns a list of attribute strings, found in the specified object, which represent callable attributes""" return [member for member in dir(obj) if not member.startswith('_') and callable(getattr(obj, member))]
Returns a list of attribute strings, found in the specified object, which represent callable attributes
list_public_methods
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def register_instance(self, instance, allow_dotted_names=False): """Registers an instance to respond to XML-RPC requests. Only one instance can be installed at a time. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and its parameters as a tuple e.g. instance._dispatch('add',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an '_' are considered private and will not be called by SimpleXMLRPCServer. If a registered function matches an XML-RPC request, then it will be called instead of the registered instance. If the optional allow_dotted_names argument is true and the instance does not have a _dispatch method, method names containing dots are supported and resolved, as long as none of the name segments start with an '_'. *** SECURITY WARNING: *** Enabling the allow_dotted_names options allows intruders to access your module's global variables and may allow intruders to execute arbitrary code on your machine. Only use this option on a secure, closed network. """ self.instance = instance self.allow_dotted_names = allow_dotted_names
Registers an instance to respond to XML-RPC requests. Only one instance can be installed at a time. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and its parameters as a tuple e.g. instance._dispatch('add',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an '_' are considered private and will not be called by SimpleXMLRPCServer. If a registered function matches an XML-RPC request, then it will be called instead of the registered instance. If the optional allow_dotted_names argument is true and the instance does not have a _dispatch method, method names containing dots are supported and resolved, as long as none of the name segments start with an '_'. *** SECURITY WARNING: *** Enabling the allow_dotted_names options allows intruders to access your module's global variables and may allow intruders to execute arbitrary code on your machine. Only use this option on a secure, closed network.
register_instance
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def register_function(self, function=None, name=None): """Registers a function to respond to XML-RPC requests. The optional name argument can be used to set a Unicode name for the function. """ # decorator factory if function is None: return partial(self.register_function, name=name) if name is None: name = function.__name__ self.funcs[name] = function return function
Registers a function to respond to XML-RPC requests. The optional name argument can be used to set a Unicode name for the function.
register_function
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def register_introspection_functions(self): """Registers the XML-RPC introspection methods in the system namespace. see http://xmlrpc.usefulinc.com/doc/reserved.html """ self.funcs.update({'system.listMethods' : self.system_listMethods, 'system.methodSignature' : self.system_methodSignature, 'system.methodHelp' : self.system_methodHelp})
Registers the XML-RPC introspection methods in the system namespace. see http://xmlrpc.usefulinc.com/doc/reserved.html
register_introspection_functions
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def register_multicall_functions(self): """Registers the XML-RPC multicall method in the system namespace. see http://www.xmlrpc.com/discuss/msgReader$1208""" self.funcs.update({'system.multicall' : self.system_multicall})
Registers the XML-RPC multicall method in the system namespace. see http://www.xmlrpc.com/discuss/msgReader$1208
register_multicall_functions
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def _marshaled_dispatch(self, data, dispatch_method = None, path = None): """Dispatches an XML-RPC method from marshalled (XML) data. XML-RPC methods are dispatched from the marshalled (XML) data using the _dispatch method and the result is returned as marshalled data. For backwards compatibility, a dispatch function can be provided as an argument (see comment in SimpleXMLRPCRequestHandler.do_POST) but overriding the existing method through subclassing is the preferred means of changing method dispatch behavior. """ try: params, method = loads(data, use_builtin_types=self.use_builtin_types) # generate response if dispatch_method is not None: response = dispatch_method(method, params) else: response = self._dispatch(method, params) # wrap response in a singleton tuple response = (response,) response = dumps(response, methodresponse=1, allow_none=self.allow_none, encoding=self.encoding) except Fault as fault: response = dumps(fault, allow_none=self.allow_none, encoding=self.encoding) except: # report exception back to server exc_type, exc_value, exc_tb = sys.exc_info() try: response = dumps( Fault(1, "%s:%s" % (exc_type, exc_value)), encoding=self.encoding, allow_none=self.allow_none, ) finally: # Break reference cycle exc_type = exc_value = exc_tb = None return response.encode(self.encoding, 'xmlcharrefreplace')
Dispatches an XML-RPC method from marshalled (XML) data. XML-RPC methods are dispatched from the marshalled (XML) data using the _dispatch method and the result is returned as marshalled data. For backwards compatibility, a dispatch function can be provided as an argument (see comment in SimpleXMLRPCRequestHandler.do_POST) but overriding the existing method through subclassing is the preferred means of changing method dispatch behavior.
_marshaled_dispatch
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def system_listMethods(self): """system.listMethods() => ['add', 'subtract', 'multiple'] Returns a list of the methods supported by the server.""" methods = set(self.funcs.keys()) if self.instance is not None: # Instance can implement _listMethod to return a list of # methods if hasattr(self.instance, '_listMethods'): methods |= set(self.instance._listMethods()) # if the instance has a _dispatch method then we # don't have enough information to provide a list # of methods elif not hasattr(self.instance, '_dispatch'): methods |= set(list_public_methods(self.instance)) return sorted(methods)
system.listMethods() => ['add', 'subtract', 'multiple'] Returns a list of the methods supported by the server.
system_listMethods
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def system_methodSignature(self, method_name): """system.methodSignature('add') => [double, int, int] Returns a list describing the signature of the method. In the above example, the add method takes two integers as arguments and returns a double result. This server does NOT support system.methodSignature.""" # See http://xmlrpc.usefulinc.com/doc/sysmethodsig.html return 'signatures not supported'
system.methodSignature('add') => [double, int, int] Returns a list describing the signature of the method. In the above example, the add method takes two integers as arguments and returns a double result. This server does NOT support system.methodSignature.
system_methodSignature
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def system_methodHelp(self, method_name): """system.methodHelp('add') => "Adds two integers together" Returns a string containing documentation for the specified method.""" method = None if method_name in self.funcs: method = self.funcs[method_name] elif self.instance is not None: # Instance can implement _methodHelp to return help for a method if hasattr(self.instance, '_methodHelp'): return self.instance._methodHelp(method_name) # if the instance has a _dispatch method then we # don't have enough information to provide help elif not hasattr(self.instance, '_dispatch'): try: method = resolve_dotted_attribute( self.instance, method_name, self.allow_dotted_names ) except AttributeError: pass # Note that we aren't checking that the method actually # be a callable object of some kind if method is None: return "" else: return pydoc.getdoc(method)
system.methodHelp('add') => "Adds two integers together" Returns a string containing documentation for the specified method.
system_methodHelp
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def system_multicall(self, call_list): """system.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => \ [[4], ...] Allows the caller to package multiple XML-RPC calls into a single request. See http://www.xmlrpc.com/discuss/msgReader$1208 """ results = [] for call in call_list: method_name = call['methodName'] params = call['params'] try: # XXX A marshalling error in any response will fail the entire # multicall. If someone cares they should fix this. results.append([self._dispatch(method_name, params)]) except Fault as fault: results.append( {'faultCode' : fault.faultCode, 'faultString' : fault.faultString} ) except: exc_type, exc_value, exc_tb = sys.exc_info() try: results.append( {'faultCode' : 1, 'faultString' : "%s:%s" % (exc_type, exc_value)} ) finally: # Break reference cycle exc_type = exc_value = exc_tb = None return results
system.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => \ [[4], ...] Allows the caller to package multiple XML-RPC calls into a single request. See http://www.xmlrpc.com/discuss/msgReader$1208
system_multicall
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def _dispatch(self, method, params): """Dispatches the XML-RPC method. XML-RPC calls are forwarded to a registered function that matches the called XML-RPC method name. If no such function exists then the call is forwarded to the registered instance, if available. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and its parameters as a tuple e.g. instance._dispatch('add',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an '_' are considered private and will not be called. """ try: # call the matching registered function func = self.funcs[method] except KeyError: pass else: if func is not None: return func(*params) raise Exception('method "%s" is not supported' % method) if self.instance is not None: if hasattr(self.instance, '_dispatch'): # call the `_dispatch` method on the instance return self.instance._dispatch(method, params) # call the instance's method directly try: func = resolve_dotted_attribute( self.instance, method, self.allow_dotted_names ) except AttributeError: pass else: if func is not None: return func(*params) raise Exception('method "%s" is not supported' % method)
Dispatches the XML-RPC method. XML-RPC calls are forwarded to a registered function that matches the called XML-RPC method name. If no such function exists then the call is forwarded to the registered instance, if available. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and its parameters as a tuple e.g. instance._dispatch('add',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an '_' are considered private and will not be called.
_dispatch
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def do_POST(self): """Handles the HTTP POST request. Attempts to interpret all HTTP POST requests as XML-RPC calls, which are forwarded to the server's _dispatch method for handling. """ # Check that the path is legal if not self.is_rpc_path_valid(): self.report_404() return try: # Get arguments by reading body of request. # We read this in chunks to avoid straining # socket.read(); around the 10 or 15Mb mark, some platforms # begin to have problems (bug #792570). max_chunk_size = 10*1024*1024 size_remaining = int(self.headers["content-length"]) L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) chunk = self.rfile.read(chunk_size) if not chunk: break L.append(chunk) size_remaining -= len(L[-1]) data = b''.join(L) data = self.decode_request_content(data) if data is None: return #response has been sent # In previous versions of SimpleXMLRPCServer, _dispatch # could be overridden in this class, instead of in # SimpleXMLRPCDispatcher. To maintain backwards compatibility, # check to see if a subclass implements _dispatch and dispatch # using that method if present. response = self.server._marshaled_dispatch( data, getattr(self, '_dispatch', None), self.path ) except Exception as e: # This should only happen if the module is buggy # internal error, report as HTTP server error self.send_response(500) # Send information about the exception if requested if hasattr(self.server, '_send_traceback_header') and \ self.server._send_traceback_header: self.send_header("X-exception", str(e)) trace = traceback.format_exc() trace = str(trace.encode('ASCII', 'backslashreplace'), 'ASCII') self.send_header("X-traceback", trace) self.send_header("Content-length", "0") self.end_headers() else: self.send_response(200) self.send_header("Content-type", "text/xml") if self.encode_threshold is not None: if len(response) > self.encode_threshold: q = self.accept_encodings().get("gzip", 0) if q: try: response = gzip_encode(response) self.send_header("Content-Encoding", "gzip") except NotImplementedError: pass self.send_header("Content-length", str(len(response))) self.end_headers() self.wfile.write(response)
Handles the HTTP POST request. Attempts to interpret all HTTP POST requests as XML-RPC calls, which are forwarded to the server's _dispatch method for handling.
do_POST
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def log_request(self, code='-', size='-'): """Selectively log an accepted request.""" if self.server.logRequests: BaseHTTPRequestHandler.log_request(self, code, size)
Selectively log an accepted request.
log_request
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def handle_xmlrpc(self, request_text): """Handle a single XML-RPC request""" response = self._marshaled_dispatch(request_text) print('Content-Type: text/xml') print('Content-Length: %d' % len(response)) print() sys.stdout.flush() sys.stdout.buffer.write(response) sys.stdout.buffer.flush()
Handle a single XML-RPC request
handle_xmlrpc
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def handle_get(self): """Handle a single HTTP GET request. Default implementation indicates an error because XML-RPC uses the POST method. """ code = 400 message, explain = BaseHTTPRequestHandler.responses[code] response = http.server.DEFAULT_ERROR_MESSAGE % \ { 'code' : code, 'message' : message, 'explain' : explain } response = response.encode('utf-8') print('Status: %d %s' % (code, message)) print('Content-Type: %s' % http.server.DEFAULT_ERROR_CONTENT_TYPE) print('Content-Length: %d' % len(response)) print() sys.stdout.flush() sys.stdout.buffer.write(response) sys.stdout.buffer.flush()
Handle a single HTTP GET request. Default implementation indicates an error because XML-RPC uses the POST method.
handle_get
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def handle_request(self, request_text=None): """Handle a single XML-RPC request passed through a CGI post method. If no XML data is given then it is read from stdin. The resulting XML-RPC response is printed to stdout along with the correct HTTP headers. """ if request_text is None and \ os.environ.get('REQUEST_METHOD', None) == 'GET': self.handle_get() else: # POST data is normally available through stdin try: length = int(os.environ.get('CONTENT_LENGTH', None)) except (ValueError, TypeError): length = -1 if request_text is None: request_text = sys.stdin.read(length) self.handle_xmlrpc(request_text)
Handle a single XML-RPC request passed through a CGI post method. If no XML data is given then it is read from stdin. The resulting XML-RPC response is printed to stdout along with the correct HTTP headers.
handle_request
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def markup(self, text, escape=None, funcs={}, classes={}, methods={}): """Mark up some plain text, given a context of symbols to look for. Each context dictionary maps object names to anchor names.""" escape = escape or self.escape results = [] here = 0 # XXX Note that this regular expression does not allow for the # hyperlinking of arbitrary strings being used as method # names. Only methods with names consisting of word characters # and '.'s are hyperlinked. pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|' r'RFC[- ]?(\d+)|' r'PEP[- ]?(\d+)|' r'(self\.)?((?:\w|\.)+))\b') while 1: match = pattern.search(text, here) if not match: break start, end = match.span() results.append(escape(text[here:start])) all, scheme, rfc, pep, selfdot, name = match.groups() if scheme: url = escape(all).replace('"', '&quot;') results.append('<a href="%s">%s</a>' % (url, url)) elif rfc: url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc) results.append('<a href="%s">%s</a>' % (url, escape(all))) elif pep: url = 'http://www.python.org/dev/peps/pep-%04d/' % int(pep) results.append('<a href="%s">%s</a>' % (url, escape(all))) elif text[end:end+1] == '(': results.append(self.namelink(name, methods, funcs, classes)) elif selfdot: results.append('self.<strong>%s</strong>' % name) else: results.append(self.namelink(name, classes)) here = end results.append(escape(text[here:])) return ''.join(results)
Mark up some plain text, given a context of symbols to look for. Each context dictionary maps object names to anchor names.
markup
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def docroutine(self, object, name, mod=None, funcs={}, classes={}, methods={}, cl=None): """Produce HTML documentation for a function or method object.""" anchor = (cl and cl.__name__ or '') + '-' + name note = '' title = '<a name="%s"><strong>%s</strong></a>' % ( self.escape(anchor), self.escape(name)) if callable(object): argspec = str(signature(object)) else: argspec = '(...)' if isinstance(object, tuple): argspec = object[0] or argspec docstring = object[1] or "" else: docstring = pydoc.getdoc(object) decl = title + argspec + (note and self.grey( '<font face="helvetica, arial">%s</font>' % note)) doc = self.markup( docstring, self.preformat, funcs, classes, methods) doc = doc and '<dd><tt>%s</tt></dd>' % doc return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)
Produce HTML documentation for a function or method object.
docroutine
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def docserver(self, server_name, package_documentation, methods): """Produce HTML documentation for an XML-RPC server.""" fdict = {} for key, value in methods.items(): fdict[key] = '#-' + key fdict[value] = fdict[key] server_name = self.escape(server_name) head = '<big><big><strong>%s</strong></big></big>' % server_name result = self.heading(head, '#ffffff', '#7799ee') doc = self.markup(package_documentation, self.preformat, fdict) doc = doc and '<tt>%s</tt>' % doc result = result + '<p>%s</p>\n' % doc contents = [] method_items = sorted(methods.items()) for key, value in method_items: contents.append(self.docroutine(value, key, funcs=fdict)) result = result + self.bigsection( 'Methods', '#ffffff', '#eeaa77', ''.join(contents)) return result
Produce HTML documentation for an XML-RPC server.
docserver
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def set_server_title(self, server_title): """Set the HTML title of the generated server documentation""" self.server_title = server_title
Set the HTML title of the generated server documentation
set_server_title
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def set_server_name(self, server_name): """Set the name of the generated HTML server documentation""" self.server_name = server_name
Set the name of the generated HTML server documentation
set_server_name
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def set_server_documentation(self, server_documentation): """Set the documentation string for the entire server.""" self.server_documentation = server_documentation
Set the documentation string for the entire server.
set_server_documentation
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def generate_html_documentation(self): """generate_html_documentation() => html documentation for the server Generates HTML documentation for the server using introspection for installed functions and instances that do not implement the _dispatch method. Alternatively, instances can choose to implement the _get_method_argstring(method_name) method to provide the argument string used in the documentation and the _methodHelp(method_name) method to provide the help text used in the documentation.""" methods = {} for method_name in self.system_listMethods(): if method_name in self.funcs: method = self.funcs[method_name] elif self.instance is not None: method_info = [None, None] # argspec, documentation if hasattr(self.instance, '_get_method_argstring'): method_info[0] = self.instance._get_method_argstring(method_name) if hasattr(self.instance, '_methodHelp'): method_info[1] = self.instance._methodHelp(method_name) method_info = tuple(method_info) if method_info != (None, None): method = method_info elif not hasattr(self.instance, '_dispatch'): try: method = resolve_dotted_attribute( self.instance, method_name ) except AttributeError: method = method_info else: method = method_info else: assert 0, "Could not find method in self.functions and no "\ "instance installed" methods[method_name] = method documenter = ServerHTMLDoc() documentation = documenter.docserver( self.server_name, self.server_documentation, methods ) return documenter.page(html.escape(self.server_title), documentation)
generate_html_documentation() => html documentation for the server Generates HTML documentation for the server using introspection for installed functions and instances that do not implement the _dispatch method. Alternatively, instances can choose to implement the _get_method_argstring(method_name) method to provide the argument string used in the documentation and the _methodHelp(method_name) method to provide the help text used in the documentation.
generate_html_documentation
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def do_GET(self): """Handles the HTTP GET request. Interpret all HTTP GET requests as requests for server documentation. """ # Check that the path is legal if not self.is_rpc_path_valid(): self.report_404() return response = self.server.generate_html_documentation().encode('utf-8') self.send_response(200) self.send_header("Content-type", "text/html") self.send_header("Content-length", str(len(response))) self.end_headers() self.wfile.write(response)
Handles the HTTP GET request. Interpret all HTTP GET requests as requests for server documentation.
do_GET
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def handle_get(self): """Handles the HTTP GET request. Interpret all HTTP GET requests as requests for server documentation. """ response = self.generate_html_documentation().encode('utf-8') print('Content-Type: text/html') print('Content-Length: %d' % len(response)) print() sys.stdout.flush() sys.stdout.buffer.write(response) sys.stdout.buffer.flush()
Handles the HTTP GET request. Interpret all HTTP GET requests as requests for server documentation.
handle_get
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/server.py
MIT
def getparser(use_datetime=False, use_builtin_types=False): """getparser() -> parser, unmarshaller Create an instance of the fastest available parser, and attach it to an unmarshalling object. Return both objects. """ if FastParser and FastUnmarshaller: if use_builtin_types: mkdatetime = _datetime_type mkbytes = base64.decodebytes elif use_datetime: mkdatetime = _datetime_type mkbytes = _binary else: mkdatetime = _datetime mkbytes = _binary target = FastUnmarshaller(True, False, mkbytes, mkdatetime, Fault) parser = FastParser(target) else: target = Unmarshaller(use_datetime=use_datetime, use_builtin_types=use_builtin_types) if FastParser: parser = FastParser(target) else: parser = ExpatParser(target) return parser, target
getparser() -> parser, unmarshaller Create an instance of the fastest available parser, and attach it to an unmarshalling object. Return both objects.
getparser
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/client.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/client.py
MIT
def dumps(params, methodname=None, methodresponse=None, encoding=None, allow_none=False): """data [,options] -> marshalled data Convert an argument tuple or a Fault instance to an XML-RPC request (or response, if the methodresponse option is used). In addition to the data object, the following options can be given as keyword arguments: methodname: the method name for a methodCall packet methodresponse: true to create a methodResponse packet. If this option is used with a tuple, the tuple must be a singleton (i.e. it can contain only one element). encoding: the packet encoding (default is UTF-8) All byte strings in the data structure are assumed to use the packet encoding. Unicode strings are automatically converted, where necessary. """ assert isinstance(params, (tuple, Fault)), "argument must be tuple or Fault instance" if isinstance(params, Fault): methodresponse = 1 elif methodresponse and isinstance(params, tuple): assert len(params) == 1, "response tuple must be a singleton" if not encoding: encoding = "utf-8" if FastMarshaller: m = FastMarshaller(encoding) else: m = Marshaller(encoding, allow_none) data = m.dumps(params) if encoding != "utf-8": xmlheader = "<?xml version='1.0' encoding='%s'?>\n" % str(encoding) else: xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default # standard XML-RPC wrappings if methodname: # a method call data = ( xmlheader, "<methodCall>\n" "<methodName>", methodname, "</methodName>\n", data, "</methodCall>\n" ) elif methodresponse: # a method response, or a fault structure data = ( xmlheader, "<methodResponse>\n", data, "</methodResponse>\n" ) else: return data # return as is return "".join(data)
data [,options] -> marshalled data Convert an argument tuple or a Fault instance to an XML-RPC request (or response, if the methodresponse option is used). In addition to the data object, the following options can be given as keyword arguments: methodname: the method name for a methodCall packet methodresponse: true to create a methodResponse packet. If this option is used with a tuple, the tuple must be a singleton (i.e. it can contain only one element). encoding: the packet encoding (default is UTF-8) All byte strings in the data structure are assumed to use the packet encoding. Unicode strings are automatically converted, where necessary.
dumps
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/client.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/client.py
MIT
def loads(data, use_datetime=False, use_builtin_types=False): """data -> unmarshalled data, method name Convert an XML-RPC packet to unmarshalled data plus a method name (None if not present). If the XML-RPC packet represents a fault condition, this function raises a Fault exception. """ p, u = getparser(use_datetime=use_datetime, use_builtin_types=use_builtin_types) p.feed(data) p.close() return u.close(), u.getmethodname()
data -> unmarshalled data, method name Convert an XML-RPC packet to unmarshalled data plus a method name (None if not present). If the XML-RPC packet represents a fault condition, this function raises a Fault exception.
loads
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/client.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/client.py
MIT
def gzip_encode(data): """data -> gzip encoded data Encode data using the gzip content encoding as described in RFC 1952 """ if not gzip: raise NotImplementedError f = BytesIO() with gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1) as gzf: gzf.write(data) return f.getvalue()
data -> gzip encoded data Encode data using the gzip content encoding as described in RFC 1952
gzip_encode
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/client.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/client.py
MIT
def gzip_decode(data, max_decode=20971520): """gzip encoded data -> unencoded data Decode data using the gzip content encoding as described in RFC 1952 """ if not gzip: raise NotImplementedError with gzip.GzipFile(mode="rb", fileobj=BytesIO(data)) as gzf: try: if max_decode < 0: # no limit decoded = gzf.read() else: decoded = gzf.read(max_decode + 1) except OSError: raise ValueError("invalid data") if max_decode >= 0 and len(decoded) > max_decode: raise ValueError("max gzipped payload length exceeded") return decoded
gzip encoded data -> unencoded data Decode data using the gzip content encoding as described in RFC 1952
gzip_decode
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/client.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/client.py
MIT
def __call__(self, attr): """A workaround to get special attributes on the ServerProxy without interfering with the magic __getattr__ """ if attr == "close": return self.__close elif attr == "transport": return self.__transport raise AttributeError("Attribute %r not found" % (attr,))
A workaround to get special attributes on the ServerProxy without interfering with the magic __getattr__
__call__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/client.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xmlrpc/client.py
MIT
def _wrap(new, old): """Simple substitute for functools.update_wrapper.""" for replace in ['__module__', '__name__', '__qualname__', '__doc__']: if hasattr(old, replace): setattr(new, replace, getattr(old, replace)) new.__dict__.update(old.__dict__)
Simple substitute for functools.update_wrapper.
_wrap
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def acquire(self): """ Acquire the module lock. If a potential deadlock is detected, a _DeadlockError is raised. Otherwise, the lock is always acquired and True is returned. """ tid = _thread.get_ident() _blocking_on[tid] = self try: while True: with self.lock: if self.count == 0 or self.owner == tid: self.owner = tid self.count += 1 return True if self.has_deadlock(): raise _DeadlockError('deadlock detected by %r' % self) if self.wakeup.acquire(False): self.waiters += 1 # Wait for a release() call self.wakeup.acquire() self.wakeup.release() finally: del _blocking_on[tid]
Acquire the module lock. If a potential deadlock is detected, a _DeadlockError is raised. Otherwise, the lock is always acquired and True is returned.
acquire
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def _get_module_lock(name): """Get or create the module lock for a given module name. Acquire/release internally the global import lock to protect _module_locks.""" _imp.acquire_lock() try: try: lock = _module_locks[name]() except KeyError: lock = None if lock is None: if _thread is None: lock = _DummyModuleLock(name) else: lock = _ModuleLock(name) def cb(ref, name=name): _imp.acquire_lock() try: # bpo-31070: Check if another thread created a new lock # after the previous lock was destroyed # but before the weakref callback was called. if _module_locks.get(name) is ref: del _module_locks[name] finally: _imp.release_lock() _module_locks[name] = _weakref.ref(lock, cb) finally: _imp.release_lock() return lock
Get or create the module lock for a given module name. Acquire/release internally the global import lock to protect _module_locks.
_get_module_lock
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def _lock_unlock_module(name): """Acquires then releases the module lock for a given module name. This is used to ensure a module is completely initialized, in the event it is being imported by another thread. """ lock = _get_module_lock(name) try: lock.acquire() except _DeadlockError: # Concurrent circular import, we'll accept a partially initialized # module object. pass else: lock.release()
Acquires then releases the module lock for a given module name. This is used to ensure a module is completely initialized, in the event it is being imported by another thread.
_lock_unlock_module
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def _call_with_frames_removed(f, *args, **kwds): """remove_importlib_frames in import.c will always remove sequences of importlib frames that end with a call to this function Use it instead of a normal call in places where including the importlib frames introduces unwanted noise into the traceback (e.g. when executing module code) """ return f(*args, **kwds)
remove_importlib_frames in import.c will always remove sequences of importlib frames that end with a call to this function Use it instead of a normal call in places where including the importlib frames introduces unwanted noise into the traceback (e.g. when executing module code)
_call_with_frames_removed
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def _verbose_message(message, *args, verbosity=1): """Print the message to stderr if -v/PYTHONVERBOSE is turned on.""" if sys.flags.verbose >= verbosity: if not message.startswith(('#', 'import ')): message = '# ' + message print(message.format(*args), file=sys.stderr)
Print the message to stderr if -v/PYTHONVERBOSE is turned on.
_verbose_message
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def _requires_builtin(fxn): """Decorator to verify the named module is built-in.""" def _requires_builtin_wrapper(self, fullname): if fullname not in sys.builtin_module_names: raise ImportError('{!r} is not a built-in module'.format(fullname), name=fullname) return fxn(self, fullname) _wrap(_requires_builtin_wrapper, fxn) return _requires_builtin_wrapper
Decorator to verify the named module is built-in.
_requires_builtin
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def _requires_frozen(fxn): """Decorator to verify the named module is frozen.""" def _requires_frozen_wrapper(self, fullname): if not _imp.is_frozen(fullname): raise ImportError('{!r} is not a frozen module'.format(fullname), name=fullname) return fxn(self, fullname) _wrap(_requires_frozen_wrapper, fxn) return _requires_frozen_wrapper
Decorator to verify the named module is frozen.
_requires_frozen
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def _load_module_shim(self, fullname): """Load the specified module into sys.modules and return it. This method is deprecated. Use loader.exec_module instead. """ spec = spec_from_loader(fullname, self) if fullname in sys.modules: module = sys.modules[fullname] _exec(spec, module) return sys.modules[fullname] else: return _load(spec)
Load the specified module into sys.modules and return it. This method is deprecated. Use loader.exec_module instead.
_load_module_shim
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def parent(self): """The name of the module's parent.""" if self.submodule_search_locations is None: return self.name.rpartition('.')[0] else: return self.name
The name of the module's parent.
parent
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def spec_from_loader(name, loader, *, origin=None, is_package=None): """Return a module spec based on various loader methods.""" if hasattr(loader, 'get_filename'): if _bootstrap_external is None: raise NotImplementedError spec_from_file_location = _bootstrap_external.spec_from_file_location if is_package is None: return spec_from_file_location(name, loader=loader) search = [] if is_package else None return spec_from_file_location(name, loader=loader, submodule_search_locations=search) if is_package is None: if hasattr(loader, 'is_package'): try: is_package = loader.is_package(name) except ImportError: is_package = None # aka, undefined else: # the default is_package = False return ModuleSpec(name, loader, origin=origin, is_package=is_package)
Return a module spec based on various loader methods.
spec_from_loader
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def module_from_spec(spec): """Create a module based on the provided spec.""" # Typically loaders will not implement create_module(). module = None if hasattr(spec.loader, 'create_module'): # If create_module() returns `None` then it means default # module creation should be used. module = spec.loader.create_module(spec) elif hasattr(spec.loader, 'exec_module'): raise ImportError('loaders that define exec_module() ' 'must also define create_module()') if module is None: module = _new_module(spec.name) _init_module_attrs(spec, module) return module
Create a module based on the provided spec.
module_from_spec
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def _module_repr_from_spec(spec): """Return the repr to use for the module.""" # We mostly replicate _module_repr() using the spec attributes. name = '?' if spec.name is None else spec.name if spec.origin is None: if spec.loader is None: return '<module {!r}>'.format(name) else: return '<module {!r} ({!r})>'.format(name, spec.loader) else: if spec.has_location: return '<module {!r} from {!r}>'.format(name, spec.origin) else: return '<module {!r} ({})>'.format(spec.name, spec.origin)
Return the repr to use for the module.
_module_repr_from_spec
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def _exec(spec, module): """Execute the spec's specified module in an existing module's namespace.""" name = spec.name with _ModuleLockManager(name): if sys.modules.get(name) is not module: msg = 'module {!r} not in sys.modules'.format(name) raise ImportError(msg, name=name) if spec.loader is None: if spec.submodule_search_locations is None: raise ImportError('missing loader', name=spec.name) # namespace package _init_module_attrs(spec, module, override=True) return module _init_module_attrs(spec, module, override=True) if not hasattr(spec.loader, 'exec_module'): # (issue19713) Once BuiltinImporter and ExtensionFileLoader # have exec_module() implemented, we can add a deprecation # warning here. spec.loader.load_module(name) else: spec.loader.exec_module(module) return sys.modules[name]
Execute the spec's specified module in an existing module's namespace.
_exec
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def _load(spec): """Return a new module object, loaded by the spec's loader. The module is not added to its parent. If a module is already in sys.modules, that existing module gets clobbered. """ with _ModuleLockManager(spec.name): return _load_unlocked(spec)
Return a new module object, loaded by the spec's loader. The module is not added to its parent. If a module is already in sys.modules, that existing module gets clobbered.
_load
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def module_repr(module): """Return repr for the module. The method is deprecated. The import machinery does the job itself. """ return '<module {!r} (built-in)>'.format(module.__name__)
Return repr for the module. The method is deprecated. The import machinery does the job itself.
module_repr
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def find_module(cls, fullname, path=None): """Find the built-in module. If 'path' is ever specified then the search is considered a failure. This method is deprecated. Use find_spec() instead. """ spec = cls.find_spec(fullname, path) return spec.loader if spec is not None else None
Find the built-in module. If 'path' is ever specified then the search is considered a failure. This method is deprecated. Use find_spec() instead.
find_module
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def create_module(self, spec): """Create a built-in module""" if spec.name not in sys.builtin_module_names: raise ImportError('{!r} is not a built-in module'.format(spec.name), name=spec.name) return _call_with_frames_removed(_imp.create_builtin, spec)
Create a built-in module
create_module
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def exec_module(self, module): """Exec a built-in module""" _call_with_frames_removed(_imp.exec_builtin, module)
Exec a built-in module
exec_module
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def get_code(cls, fullname): """Return None as built-in modules do not have code objects.""" return None
Return None as built-in modules do not have code objects.
get_code
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def get_source(cls, fullname): """Return None as built-in modules do not have source code.""" return None
Return None as built-in modules do not have source code.
get_source
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def is_package(cls, fullname): """Return False as built-in modules are never packages.""" return False
Return False as built-in modules are never packages.
is_package
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def module_repr(m): """Return repr for the module. The method is deprecated. The import machinery does the job itself. """ return '<module {!r} (frozen)>'.format(m.__name__)
Return repr for the module. The method is deprecated. The import machinery does the job itself.
module_repr
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def find_module(cls, fullname, path=None): """Find a frozen module. This method is deprecated. Use find_spec() instead. """ return cls if _imp.is_frozen(fullname) else None
Find a frozen module. This method is deprecated. Use find_spec() instead.
find_module
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def create_module(cls, spec): """Use default semantics for module creation."""
Use default semantics for module creation.
create_module
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def load_module(cls, fullname): """Load a frozen module. This method is deprecated. Use exec_module() instead. """ return _load_module_shim(cls, fullname)
Load a frozen module. This method is deprecated. Use exec_module() instead.
load_module
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def get_code(cls, fullname): """Return the code object for the frozen module.""" return _imp.get_frozen_object(fullname)
Return the code object for the frozen module.
get_code
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def get_source(cls, fullname): """Return None as frozen modules do not have source code.""" return None
Return None as frozen modules do not have source code.
get_source
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def is_package(cls, fullname): """Return True if the frozen module is a package.""" return _imp.is_frozen_package(fullname)
Return True if the frozen module is a package.
is_package
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def __enter__(self): """Acquire the import lock.""" _imp.acquire_lock()
Acquire the import lock.
__enter__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def __exit__(self, exc_type, exc_value, exc_traceback): """Release the import lock regardless of any raised exceptions.""" _imp.release_lock()
Release the import lock regardless of any raised exceptions.
__exit__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def _resolve_name(name, package, level): """Resolve a relative module name to an absolute one.""" bits = package.rsplit('.', level - 1) if len(bits) < level: raise ValueError('attempted relative import beyond top-level package') base = bits[0] return '{}.{}'.format(base, name) if name else base
Resolve a relative module name to an absolute one.
_resolve_name
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def _find_spec(name, path, target=None): """Find a module's spec.""" meta_path = sys.meta_path if meta_path is None: # PyImport_Cleanup() is running or has been called. raise ImportError("sys.meta_path is None, Python is likely " "shutting down") if not meta_path: _warnings.warn('sys.meta_path is empty', ImportWarning) # We check sys.modules here for the reload case. While a passed-in # target will usually indicate a reload there is no guarantee, whereas # sys.modules provides one. is_reload = name in sys.modules for finder in meta_path: with _ImportLockContext(): try: find_spec = finder.find_spec except AttributeError: spec = _find_spec_legacy(finder, name, path) if spec is None: continue else: spec = find_spec(name, path, target) if spec is not None: # The parent import may have already imported this module. if not is_reload and name in sys.modules: module = sys.modules[name] try: __spec__ = module.__spec__ except AttributeError: # We use the found spec since that is the one that # we would have used if the parent module hadn't # beaten us to the punch. return spec else: if __spec__ is None: return spec else: return __spec__ else: return spec else: return None
Find a module's spec.
_find_spec
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def _sanity_check(name, package, level): """Verify arguments are "sane".""" if not isinstance(name, str): raise TypeError('module name must be str, not {}'.format(type(name))) if level < 0: raise ValueError('level must be >= 0') if level > 0: if not isinstance(package, str): raise TypeError('__package__ not set to a string') elif not package: raise ImportError('attempted relative import with no known parent ' 'package') if not name and level == 0: raise ValueError('Empty module name')
Verify arguments are "sane".
_sanity_check
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def _find_and_load(name, import_): """Find and load the module.""" with _ModuleLockManager(name): module = sys.modules.get(name, _NEEDS_LOADING) if module is _NEEDS_LOADING: return _find_and_load_unlocked(name, import_) if module is None: message = ('import of {} halted; ' 'None in sys.modules'.format(name)) raise ModuleNotFoundError(message, name=name) _lock_unlock_module(name) return module
Find and load the module.
_find_and_load
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def _gcd_import(name, package=None, level=0): """Import and return the module based on its name, the package the call is being made from, and the level adjustment. This function represents the greatest common denominator of functionality between import_module and __import__. This includes setting __package__ if the loader did not. """ _sanity_check(name, package, level) if level > 0: name = _resolve_name(name, package, level) return _find_and_load(name, _gcd_import)
Import and return the module based on its name, the package the call is being made from, and the level adjustment. This function represents the greatest common denominator of functionality between import_module and __import__. This includes setting __package__ if the loader did not.
_gcd_import
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def _handle_fromlist(module, fromlist, import_, *, recursive=False): """Figure out what __import__ should return. The import_ parameter is a callable which takes the name of module to import. It is required to decouple the function from assuming importlib's import implementation is desired. """ # The hell that is fromlist ... # If a package was imported, try to import stuff from fromlist. if hasattr(module, '__path__'): for x in fromlist: if not isinstance(x, str): if recursive: where = module.__name__ + '.__all__' else: where = "``from list''" raise TypeError(f"Item in {where} must be str, " f"not {type(x).__name__}") elif x == '*': if not recursive and hasattr(module, '__all__'): _handle_fromlist(module, module.__all__, import_, recursive=True) elif not hasattr(module, x): from_name = '{}.{}'.format(module.__name__, x) try: _call_with_frames_removed(import_, from_name) except ModuleNotFoundError as exc: # Backwards-compatibility dictates we ignore failed # imports triggered by fromlist for modules that don't # exist. if (exc.name == from_name and sys.modules.get(from_name, _NEEDS_LOADING) is not None): continue raise return module
Figure out what __import__ should return. The import_ parameter is a callable which takes the name of module to import. It is required to decouple the function from assuming importlib's import implementation is desired.
_handle_fromlist
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def _calc___package__(globals): """Calculate what __package__ should be. __package__ is not guaranteed to be defined or could be set to None to represent that its proper value is unknown. """ package = globals.get('__package__') spec = globals.get('__spec__') if package is not None: if spec is not None and package != spec.parent: _warnings.warn("__package__ != __spec__.parent " f"({package!r} != {spec.parent!r})", ImportWarning, stacklevel=3) return package elif spec is not None: return spec.parent else: _warnings.warn("can't resolve package from __spec__ or __package__, " "falling back on __name__ and __path__", ImportWarning, stacklevel=3) package = globals['__name__'] if '__path__' not in globals: package = package.rpartition('.')[0] return package
Calculate what __package__ should be. __package__ is not guaranteed to be defined or could be set to None to represent that its proper value is unknown.
_calc___package__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def __import__(name, globals=None, locals=None, fromlist=(), level=0): """Import a module. The 'globals' argument is used to infer where the import is occurring from to handle relative imports. The 'locals' argument is ignored. The 'fromlist' argument specifies what should exist as attributes on the module being imported (e.g. ``from module import <fromlist>``). The 'level' argument represents the package location to import from in a relative import (e.g. ``from ..pkg import mod`` would have a 'level' of 2). """ if level == 0: module = _gcd_import(name) else: globals_ = globals if globals is not None else {} package = _calc___package__(globals_) module = _gcd_import(name, package, level) if not fromlist: # Return up to the first dot in 'name'. This is complicated by the fact # that 'name' may be relative. if level == 0: return _gcd_import(name.partition('.')[0]) elif not name: return module else: # Figure out where to slice the module's name up to the first dot # in 'name'. cut_off = len(name) - len(name.partition('.')[0]) # Slice end needs to be positive to alleviate need to special-case # when ``'.' not in name``. return sys.modules[module.__name__[:len(module.__name__)-cut_off]] else: return _handle_fromlist(module, fromlist, _gcd_import)
Import a module. The 'globals' argument is used to infer where the import is occurring from to handle relative imports. The 'locals' argument is ignored. The 'fromlist' argument specifies what should exist as attributes on the module being imported (e.g. ``from module import <fromlist>``). The 'level' argument represents the package location to import from in a relative import (e.g. ``from ..pkg import mod`` would have a 'level' of 2).
__import__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def _setup(sys_module, _imp_module): """Setup importlib by importing needed built-in modules and injecting them into the global namespace. As sys is needed for sys.modules access and _imp is needed to load built-in modules, those two modules must be explicitly passed in. """ global _imp, sys _imp = _imp_module sys = sys_module # Set up the spec for existing builtin/frozen modules. module_type = type(sys) for name, module in sys.modules.items(): if isinstance(module, module_type): if name in sys.builtin_module_names: loader = BuiltinImporter elif _imp.is_frozen(name): loader = FrozenImporter else: continue spec = _spec_from_module(module, loader) _init_module_attrs(spec, module) # Directly load built-in modules needed during bootstrap. self_module = sys.modules[__name__] for builtin_name in ('_thread', '_warnings', '_weakref'): if builtin_name not in sys.modules: builtin_module = _builtin_from_name(builtin_name) else: builtin_module = sys.modules[builtin_name] setattr(self_module, builtin_name, builtin_module)
Setup importlib by importing needed built-in modules and injecting them into the global namespace. As sys is needed for sys.modules access and _imp is needed to load built-in modules, those two modules must be explicitly passed in.
_setup
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def _install(sys_module, _imp_module): """Install importers for builtin and frozen modules""" _setup(sys_module, _imp_module) sys.meta_path.append(BuiltinImporter) sys.meta_path.append(FrozenImporter)
Install importers for builtin and frozen modules
_install
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def _install_external_importers(): """Install importers that require external filesystem access""" global _bootstrap_external import _frozen_importlib_external _bootstrap_external = _frozen_importlib_external _frozen_importlib_external._install(sys.modules[__name__])
Install importers that require external filesystem access
_install_external_importers
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap.py
MIT
def _relax_case(): """True if filenames must be checked case-insensitively.""" return key in _os.environ
True if filenames must be checked case-insensitively.
_make_relax_case._relax_case
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap_external.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap_external.py
MIT
def _relax_case(): """True if filenames must be checked case-insensitively.""" return False
True if filenames must be checked case-insensitively.
_make_relax_case._relax_case
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap_external.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/importlib/_bootstrap_external.py
MIT