_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3 values | text stringlengths 75 19.8k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q36800 | base_argparser | train | def base_argparser(argv=()):
"""Initial parser that can set values for the rest of the parsing process.
"""
global verbose
verbose = _not_verbose
_p = argparse.ArgumentParser(add_help=False)
_p.add_argument('--debug', action='store_true', help="turn on all the show and verbose options (mainly for debugging pydeps itself)")
_p.add_argument('--config', help="specify config file", metavar="FILE")
_p.add_argument('--no-config', help="disable processing of config files", action='store_true')
_p.add_argument('--version', action='store_true', help='print pydeps version')
_p.add_argument('-L', '--log', help=textwrap.dedent('''
set log-level to one of CRITICAL, ERROR, WARNING, INFO, DEBUG, NOTSET.
'''))
_args, argv = _p.parse_known_args(argv)
if _args.log:
loglevels = "CRITICAL DEBUG ERROR FATAL INFO WARN"
if _args.log not in loglevels: # pragma: nocover
error('legal values for the -L parameter are:', loglevels)
loglevel = getattr(logging, _args.log)
else:
loglevel = None
logging.basicConfig(
level=loglevel,
format='%(filename)s:%(lineno)d: %(levelname)s: %(message)s'
)
if _args.version: # pragma: nocover
print("pydeps v" + __version__)
sys.exit(0)
return _p, _args, argv | python | {
"resource": ""
} |
q36801 | dep2req | train | def dep2req(name, imported_by):
"""Convert dependency to requirement.
"""
lst = [item for item in sorted(imported_by) if not item.startswith(name)]
res = '%-15s # from: ' % name
imps = ', '.join(lst)
if len(imps) < WIDTH - 24:
return res + imps
return res + imps[:WIDTH - 24 - 3] + '...' | python | {
"resource": ""
} |
q36802 | pydeps2reqs | train | def pydeps2reqs(deps):
"""Convert a deps instance into requirements.
"""
reqs = defaultdict(set)
for k, v in list(deps.items()):
# not a built-in
p = v['path']
if p and not p.startswith(sys.real_prefix):
if p.startswith(sys.prefix) and 'site-packages' in p:
if not p.endswith('.pyd'):
if '/win32/' in p.replace('\\', '/'):
reqs['win32'] |= set(v['imported_by'])
else:
name = k.split('.', 1)[0]
if name not in skiplist:
reqs[name] |= set(v['imported_by'])
if '_dummy' in reqs:
del reqs['_dummy']
return '\n'.join(dep2req(name, reqs[name]) for name in sorted(reqs)) | python | {
"resource": ""
} |
q36803 | main | train | def main():
"""Cli entrypoint.
"""
if len(sys.argv) == 2:
fname = sys.argv[1]
data = json.load(open(fname, 'rb'))
else:
data = json.loads(sys.stdin.read())
print(pydeps2reqs(data)) | python | {
"resource": ""
} |
q36804 | pydeps | train | def pydeps(**args):
"""Entry point for the ``pydeps`` command.
This function should do all the initial parameter and environment
munging before calling ``_pydeps`` (so that function has a clean
execution path).
"""
_args = args if args else cli.parse_args(sys.argv[1:])
inp = target.Target(_args['fname'])
log.debug("Target: %r", inp)
if _args.get('output'):
_args['output'] = os.path.abspath(_args['output'])
else:
_args['output'] = os.path.join(
inp.calling_dir,
inp.modpath.replace('.', '_') + '.' + _args.get('format', 'svg')
)
with inp.chdir_work():
_args['fname'] = inp.fname
_args['isdir'] = inp.is_dir
if _args.get('externals'):
del _args['fname']
exts = externals(inp, **_args)
print(json.dumps(exts, indent=4))
return exts # so the tests can assert
else:
# this is the call you're looking for :-)
return _pydeps(inp, **_args) | python | {
"resource": ""
} |
q36805 | Target._path_parts | train | def _path_parts(self, pth):
"""Return a list of all directories in the path ``pth``.
"""
res = re.split(r"[\\/]", pth)
if res and os.path.splitdrive(res[0]) == (res[0], ''):
res[0] += os.path.sep
return res | python | {
"resource": ""
} |
q36806 | Connection.cursor | train | def cursor(self):
"""
Create a new ``Cursor`` instance associated with this ``Connection``
:return: A new ``Cursor`` instance
"""
self._assert_valid()
c = Cursor(self.impl.cursor())
self.cursors.add(c)
return c | python | {
"resource": ""
} |
q36807 | Connection.close | train | def close(self):
"""
Close the connection and all associated cursors. This will implicitly
roll back any uncommitted operations.
"""
for c in self.cursors:
c.close()
self.cursors = []
self.impl = None | python | {
"resource": ""
} |
q36808 | make_options | train | def make_options(read_buffer_size=None,
parameter_sets_to_buffer=None,
varchar_max_character_limit=None,
prefer_unicode=None,
use_async_io=None,
autocommit=None,
large_decimals_as_64_bit_types=None,
limit_varchar_results_to_max=None,
force_extra_capacity_for_unicode=None,
fetch_wchar_as_char=None):
"""
Create options that control how turbodbc interacts with a database. These
options affect performance for the most part, but some options may require adjustment
so that all features work correctly with certain databases.
If a parameter is set to `None`, this means the default value is used.
:param read_buffer_size: Affects performance. Controls the size of batches fetched from the
database when reading result sets. Can be either an instance of ``turbodbc.Megabytes`` (recommended)
or ``turbodbc.Rows``.
:param parameter_sets_to_buffer: Affects performance. Number of parameter sets (rows) which shall be
transferred to the server in a single batch when ``executemany()`` is called. Must be an integer.
:param varchar_max_character_limit: Affects behavior/performance. If a result set contains fields
of type ``VARCHAR(max)`` or ``NVARCHAR(max)`` or the equivalent type of your database, buffers
will be allocated to hold the specified number of characters. This may lead to truncation. The
default value is ``65535`` characters. Please note that large values reduce the risk of
truncation, but may affect the number of rows in a batch of result sets (see ``read_buffer_size``).
Please note that this option only relates to retrieving results, not sending parameters to the
database.
:param use_async_io: Affects performance. Set this option to ``True`` if you want to use asynchronous
I/O, i.e., while Python is busy converting database results to Python objects, new result sets are
fetched from the database in the background.
:param prefer_unicode: May affect functionality and performance. Some databases do not support
strings encoded with UTF-8, leading to UTF-8 characters being misinterpreted, misrepresented, or
downright rejected. Set this option to ``True`` if you want to transfer character data using the
UCS-2/UCS-16 encoding that use (multiple) two-byte instead of (multiple) one-byte characters.
:param autocommit: Affects behavior. If set to ``True``, all queries and commands executed
with ``cursor.execute()`` or ``cursor.executemany()`` will be succeeded by an implicit ``COMMIT``
operation, persisting any changes made to the database. If not set or set to ``False``,
users has to take care of calling ``cursor.commit()`` themselves.
:param large_decimals_as_64_bit_types: Affects behavior. If set to ``True``, ``DECIMAL(x, y)``
results with ``x > 18`` will be rendered as 64 bit integers (``y == 0``) or 64 bit floating
point numbers (``y > 0``), respectively. Use this option if your decimal data types are larger
than the data they actually hold. Using this data type can lead to overflow errors and loss
of precision. If not set or set to ``False``, large decimals are rendered as strings.
:param limit_varchar_results_to_max: Affects behavior/performance. If set to ``True``,
any text-like fields such as ``VARCHAR(n)`` and ``NVARCHAR(n)`` will be limited to a maximum
size of ``varchar_max_character_limit`` characters. This may lead to values being truncated,
but reduces the amount of memory required to allocate string buffers, leading to larger, more
efficient batches. If not set or set to ``False``, strings can exceed ``varchar_max_character_limit``
in size if the database reports them this way. For fields such as ``TEXT``, some databases
report a size of 2 billion characters.
Please note that this option only relates to retrieving results, not sending parameters to the
database.
:param force_extra_capacity_for_unicode Affects behavior/performance. Some ODBC drivers report the
length of the ``VARCHAR``/``NVARCHAR`` field rather than the number of code points for which space is required
to be allocated, resulting in string truncations. Set this option to ``True`` to increase the memory
allocated for ``VARCHAR`` and ``NVARCHAR`` fields and prevent string truncations.
Please note that this option only relates to retrieving results, not sending parameters to the
database.
:param fetch_wchar_as_char Affects behavior. Some ODBC drivers retrieve single byte encoded strings
into ``NVARCHAR`` fields of result sets, which are decoded incorrectly by turbodbc default settings,
resulting in corrupt strings. Set this option to ``True`` to have turbodbc treat ``NVARCHAR`` types
as narrow character types when decoding the fields in result sets.
Please note that this option only relates to retrieving results, not sending parameters to the
database.
:return: An option struct that is suitable to pass to the ``turbodbc_options`` parameter of
``turbodbc.connect()``
"""
options = Options()
if not read_buffer_size is None:
options.read_buffer_size = read_buffer_size
if not parameter_sets_to_buffer is None:
options.parameter_sets_to_buffer = parameter_sets_to_buffer
if not varchar_max_character_limit is None:
options.varchar_max_character_limit = varchar_max_character_limit
if not prefer_unicode is None:
options.prefer_unicode = prefer_unicode
if not use_async_io is None:
options.use_async_io = use_async_io
if not autocommit is None:
options.autocommit = autocommit
if not large_decimals_as_64_bit_types is None:
options.large_decimals_as_64_bit_types = large_decimals_as_64_bit_types
if not limit_varchar_results_to_max is None:
options.limit_varchar_results_to_max = limit_varchar_results_to_max
if not force_extra_capacity_for_unicode is None:
options.force_extra_capacity_for_unicode = force_extra_capacity_for_unicode
if not fetch_wchar_as_char is None:
options.fetch_wchar_as_char = fetch_wchar_as_char
return options | python | {
"resource": ""
} |
q36809 | _get_distutils_build_directory | train | def _get_distutils_build_directory():
"""
Returns the directory distutils uses to build its files.
We need this directory since we build extensions which have to link
other ones.
"""
pattern = "lib.{platform}-{major}.{minor}"
return os.path.join('build', pattern.format(platform=sysconfig.get_platform(),
major=sys.version_info[0],
minor=sys.version_info[1])) | python | {
"resource": ""
} |
q36810 | get_extension_modules | train | def get_extension_modules():
extension_modules = []
"""
Extension module which is actually a plain C++ library without Python bindings
"""
turbodbc_sources = _get_source_files('cpp_odbc') + _get_source_files('turbodbc')
turbodbc_library = Extension('libturbodbc',
sources=turbodbc_sources,
include_dirs=include_dirs,
extra_compile_args=extra_compile_args,
extra_link_args=base_library_link_args,
libraries=[odbclib],
library_dirs=library_dirs)
if sys.platform == "win32":
turbodbc_libs = []
else:
turbodbc_libs = [_get_turbodbc_libname()]
extension_modules.append(turbodbc_library)
"""
An extension module which contains the main Python bindings for turbodbc
"""
turbodbc_python_sources = _get_source_files('turbodbc_python')
if sys.platform == "win32":
turbodbc_python_sources = turbodbc_sources + turbodbc_python_sources
turbodbc_python = Extension('turbodbc_intern',
sources=turbodbc_python_sources,
include_dirs=include_dirs,
extra_compile_args=extra_compile_args + hidden_visibility_args,
libraries=[odbclib] + turbodbc_libs,
extra_link_args=python_module_link_args,
library_dirs=library_dirs)
extension_modules.append(turbodbc_python)
"""
An extension module which contains Python bindings which require numpy support
to work. Not included in the standard Python bindings so this can stay optional.
"""
if _has_numpy_headers():
import numpy
turbodbc_numpy_sources = _get_source_files('turbodbc_numpy')
if sys.platform == "win32":
turbodbc_numpy_sources = turbodbc_sources + turbodbc_numpy_sources
turbodbc_numpy = Extension('turbodbc_numpy_support',
sources=turbodbc_numpy_sources,
include_dirs=include_dirs + [numpy.get_include()],
extra_compile_args=extra_compile_args + hidden_visibility_args,
libraries=[odbclib] + turbodbc_libs,
extra_link_args=python_module_link_args,
library_dirs=library_dirs)
extension_modules.append(turbodbc_numpy)
"""
An extension module which contains Python bindings which require Apache Arrow
support to work. Not included in the standard Python bindings so this can
stay optional.
"""
if _has_arrow_headers():
import pyarrow
pyarrow_location = os.path.dirname(pyarrow.__file__)
# For now, assume that we build against bundled pyarrow releases.
pyarrow_include_dir = os.path.join(pyarrow_location, 'include')
turbodbc_arrow_sources = _get_source_files('turbodbc_arrow')
pyarrow_module_link_args = list(python_module_link_args)
if sys.platform == "win32":
turbodbc_arrow_sources = turbodbc_sources + turbodbc_arrow_sources
elif sys.platform == "darwin":
pyarrow_module_link_args.append('-Wl,-rpath,@loader_path/pyarrow')
else:
pyarrow_module_link_args.append("-Wl,-rpath,$ORIGIN/pyarrow")
turbodbc_arrow = Extension('turbodbc_arrow_support',
sources=turbodbc_arrow_sources,
include_dirs=include_dirs + [pyarrow_include_dir],
extra_compile_args=extra_compile_args + hidden_visibility_args,
libraries=[odbclib, 'arrow', 'arrow_python'] + turbodbc_libs,
extra_link_args=pyarrow_module_link_args,
library_dirs=library_dirs + [pyarrow_location])
extension_modules.append(turbodbc_arrow)
return extension_modules | python | {
"resource": ""
} |
q36811 | connect | train | def connect(dsn=None, turbodbc_options=None, connection_string=None, **kwargs):
"""
Create a connection with the database identified by the ``dsn`` or the ``connection_string``.
:param dsn: Data source name as given in the (unix) odbc.ini file
or (Windows) ODBC Data Source Administrator tool.
:param turbodbc_options: Options that control how turbodbc interacts with the database.
Create such a struct with `turbodbc.make_options()` or leave this blank to take the defaults.
:param connection_string: Preformatted ODBC connection string.
Specifying this and dsn or kwargs at the same time raises ParameterError.
:param \**kwargs: You may specify additional options as you please. These options will go into
the connection string that identifies the database. Valid options depend on the specific database you
would like to connect with (e.g. `user` and `password`, or `uid` and `pwd`)
:return: A connection to your database
"""
if turbodbc_options is None:
turbodbc_options = make_options()
if connection_string is not None and (dsn is not None or len(kwargs) > 0):
raise ParameterError("Both connection_string and dsn or kwargs specified")
if connection_string is None:
connection_string = _make_connection_string(dsn, **kwargs)
connection = Connection(intern_connect(connection_string,
turbodbc_options))
return connection | python | {
"resource": ""
} |
q36812 | Cursor.description | train | def description(self):
"""
Retrieve a description of the columns in the current result set
:return: A tuple of seven elements. Only some elements are meaningful:\n
* Element #0 is the name of the column
* Element #1 is the type code of the column
* Element #6 is true if the column may contain ``NULL`` values
"""
if self.result_set:
info = self.result_set.get_column_info()
return [(c.name, c.type_code(), None, None, None, None, c.supports_null_values) for c in info]
else:
return None | python | {
"resource": ""
} |
q36813 | Cursor.execute | train | def execute(self, sql, parameters=None):
"""
Execute an SQL command or query
:param sql: A (unicode) string that contains the SQL command or query. If you would like to
use parameters, please use a question mark ``?`` at the location where the
parameter shall be inserted.
:param parameters: An iterable of parameter values. The number of values must match
the number of parameters in the SQL string.
:return: The ``Cursor`` object to allow chaining of operations.
"""
self.rowcount = -1
self._assert_valid()
self.impl.prepare(sql)
if parameters:
buffer = make_parameter_set(self.impl)
buffer.add_set(parameters)
buffer.flush()
return self._execute() | python | {
"resource": ""
} |
q36814 | Cursor.close | train | def close(self):
"""
Close the cursor.
"""
self.result_set = None
if self.impl is not None:
self.impl._reset()
self.impl = None | python | {
"resource": ""
} |
q36815 | connect_to_pipe | train | def connect_to_pipe(pipe_name):
"""
Connect to a new pipe in message mode.
"""
pipe_handle = windll.kernel32.CreateFileW(
pipe_name,
DWORD(GENERIC_READ | GENERIC_WRITE | FILE_WRITE_ATTRIBUTES),
DWORD(0), # No sharing.
None, # Default security attributes.
DWORD(OPEN_EXISTING), # dwCreationDisposition.
FILE_FLAG_OVERLAPPED, # dwFlagsAndAttributes.
None # hTemplateFile,
)
if pipe_handle == INVALID_HANDLE_VALUE:
raise Exception('Invalid handle. Connecting to pipe %r failed.' % pipe_name)
# Turn pipe into message mode.
dwMode = DWORD(PIPE_READMODE_MESSAGE)
windll.kernel32.SetNamedPipeHandleState(
pipe_handle,
byref(dwMode),
None,
None)
return pipe_handle | python | {
"resource": ""
} |
q36816 | create_event | train | def create_event():
"""
Create Win32 event.
"""
event = windll.kernel32.CreateEventA(
None, # Default security attributes.
BOOL(True), # Manual reset event.
BOOL(True), # Initial state = signaled.
None # Unnamed event object.
)
if not event:
raise Exception('event creation failed.')
return event | python | {
"resource": ""
} |
q36817 | wait_for_event | train | def wait_for_event(event):
"""
Wraps a win32 event into a `Future` and wait for it.
"""
f = Future()
def ready():
get_event_loop().remove_win32_handle(event)
f.set_result(None)
get_event_loop().add_win32_handle(event, ready)
return f | python | {
"resource": ""
} |
q36818 | WindowsClient._start_reader | train | def _start_reader(self):
"""
Read messages from the Win32 pipe server and handle them.
"""
while True:
message = yield From(self.pipe.read_message())
self._process(message) | python | {
"resource": ""
} |
q36819 | _draw_number | train | def _draw_number(screen, x_offset, y_offset, number, style='class:clock',
transparent=False):
" Write number at position. "
fg = Char(' ', 'class:clock')
bg = Char(' ', '')
for y, row in enumerate(_numbers[number]):
screen_row = screen.data_buffer[y + y_offset]
for x, n in enumerate(row):
if n == '#':
screen_row[x + x_offset] = fg
elif not transparent:
screen_row[x + x_offset] = bg | python | {
"resource": ""
} |
q36820 | _create_split | train | def _create_split(pymux, window, split):
"""
Create a prompt_toolkit `Container` instance for the given pymux split.
"""
assert isinstance(split, (arrangement.HSplit, arrangement.VSplit))
is_vsplit = isinstance(split, arrangement.VSplit)
def get_average_weight():
""" Calculate average weight of the children. Return 1 if none of
the children has a weight specified yet. """
weights = 0
count = 0
for i in split:
if i in split.weights:
weights += split.weights[i]
count += 1
if weights:
return max(1, weights // count)
else:
return 1
def report_write_position_callback(item, write_position):
"""
When the layout is rendered, store the actial dimensions as
weights in the arrangement.VSplit/HSplit classes.
This is required because when a pane is resized with an increase of +1,
we want to be sure that this corresponds exactly with one row or
column. So, that updating weights corresponds exactly 1/1 to updating
the size of the panes.
"""
if is_vsplit:
split.weights[item] = write_position.width
else:
split.weights[item] = write_position.height
def get_size(item):
return D(weight=split.weights.get(item) or average_weight)
content = []
average_weight = get_average_weight()
for i, item in enumerate(split):
# Create function for calculating dimensions for child.
width = height = None
if is_vsplit:
width = partial(get_size, item)
else:
height = partial(get_size, item)
# Create child.
if isinstance(item, (arrangement.VSplit, arrangement.HSplit)):
child = _create_split(pymux, window, item)
elif isinstance(item, arrangement.Pane):
child = _create_container_for_process(pymux, window, item)
else:
raise TypeError('Got %r' % (item,))
# Wrap child in `SizedBox` to enforce dimensions and sync back.
content.append(SizedBox(
child, width=width, height=height,
report_write_position_callback=partial(report_write_position_callback, item)))
# Create prompt_toolkit Container.
if is_vsplit:
return_cls = VSplit
padding_char = _border_vertical
else:
return_cls = HSplit
padding_char = _border_horizontal
return return_cls(content,
padding=1,
padding_char=padding_char) | python | {
"resource": ""
} |
q36821 | _create_container_for_process | train | def _create_container_for_process(pymux, window, arrangement_pane, zoom=False):
"""
Create a `Container` with a titlebar for a process.
"""
@Condition
def clock_is_visible():
return arrangement_pane.clock_mode
@Condition
def pane_numbers_are_visible():
return pymux.display_pane_numbers
terminal_is_focused = has_focus(arrangement_pane.terminal)
def get_terminal_style():
if terminal_is_focused():
result = 'class:terminal.focused'
else:
result = 'class:terminal'
return result
def get_titlebar_text_fragments():
result = []
if zoom:
result.append(('class:titlebar-zoom', ' Z '))
if arrangement_pane.process.is_terminated:
result.append(('class:terminated', ' Terminated '))
# Scroll buffer info.
if arrangement_pane.display_scroll_buffer:
result.append(('class:copymode', ' %s ' % arrangement_pane.scroll_buffer_title))
# Cursor position.
document = arrangement_pane.scroll_buffer.document
result.append(('class:copymode.position', ' %i,%i ' % (
document.cursor_position_row, document.cursor_position_col)))
if arrangement_pane.name:
result.append(('class:name', ' %s ' % arrangement_pane.name))
result.append(('', ' '))
return result + [
('', format_pymux_string(pymux, ' #T ', pane=arrangement_pane)) # XXX: Make configurable.
]
def get_pane_index():
try:
w = pymux.arrangement.get_active_window()
index = w.get_pane_index(arrangement_pane)
except ValueError:
index = '/'
return '%3s ' % index
def on_click():
" Click handler for the clock. When clicked, select this pane. "
arrangement_pane.clock_mode = False
pymux.arrangement.get_active_window().active_pane = arrangement_pane
pymux.invalidate()
return HighlightBordersIfActive(
window,
arrangement_pane,
get_terminal_style,
FloatContainer(
HSplit([
# The terminal.
TracePaneWritePosition(
pymux, arrangement_pane,
content=arrangement_pane.terminal),
]),
#
floats=[
# The title bar.
Float(content=
ConditionalContainer(
content=VSplit([
Window(
height=1,
content=FormattedTextControl(
get_titlebar_text_fragments)),
Window(
height=1,
width=4,
content=FormattedTextControl(get_pane_index),
style='class:paneindex')
], style='class:titlebar'),
filter=Condition(lambda: pymux.enable_pane_status)),
left=0, right=0, top=-1, height=1, z_index=Z_INDEX.WINDOW_TITLE_BAR),
# The clock.
Float(
content=ConditionalContainer(BigClock(on_click),
filter=clock_is_visible)),
# Pane number.
Float(content=ConditionalContainer(
content=PaneNumber(pymux, arrangement_pane),
filter=pane_numbers_are_visible)),
]
)
) | python | {
"resource": ""
} |
q36822 | focus_left | train | def focus_left(pymux):
" Move focus to the left. "
_move_focus(pymux,
lambda wp: wp.xpos - 2, # 2 in order to skip over the border.
lambda wp: wp.ypos) | python | {
"resource": ""
} |
q36823 | focus_right | train | def focus_right(pymux):
" Move focus to the right. "
_move_focus(pymux,
lambda wp: wp.xpos + wp.width + 1,
lambda wp: wp.ypos) | python | {
"resource": ""
} |
q36824 | focus_down | train | def focus_down(pymux):
" Move focus down. "
_move_focus(pymux,
lambda wp: wp.xpos,
lambda wp: wp.ypos + wp.height + 2) | python | {
"resource": ""
} |
q36825 | focus_up | train | def focus_up(pymux):
" Move focus up. "
_move_focus(pymux,
lambda wp: wp.xpos,
lambda wp: wp.ypos - 2) | python | {
"resource": ""
} |
q36826 | _move_focus | train | def _move_focus(pymux, get_x, get_y):
" Move focus of the active window. "
window = pymux.arrangement.get_active_window()
try:
write_pos = pymux.get_client_state().layout_manager.pane_write_positions[window.active_pane]
except KeyError:
pass
else:
x = get_x(write_pos)
y = get_y(write_pos)
# Look for the pane at this position.
for pane, wp in pymux.get_client_state().layout_manager.pane_write_positions.items():
if (wp.xpos <= x < wp.xpos + wp.width and
wp.ypos <= y < wp.ypos + wp.height):
window.active_pane = pane
return | python | {
"resource": ""
} |
q36827 | Background.write_to_screen | train | def write_to_screen(self, screen, mouse_handlers, write_position,
parent_style, erase_bg, z_index):
" Fill the whole area of write_position with dots. "
default_char = Char(' ', 'class:background')
dot = Char('.', 'class:background')
ypos = write_position.ypos
xpos = write_position.xpos
for y in range(ypos, ypos + write_position.height):
row = screen.data_buffer[y]
for x in range(xpos, xpos + write_position.width):
row[x] = dot if (x + y) % 3 == 0 else default_char | python | {
"resource": ""
} |
q36828 | BigClock._mouse_handler | train | def _mouse_handler(self, cli, mouse_event):
" Click callback. "
if mouse_event.event_type == MouseEventType.MOUSE_UP:
self.on_click(cli)
else:
return NotImplemented | python | {
"resource": ""
} |
q36829 | LayoutManager.display_popup | train | def display_popup(self, title, content):
"""
Display a pop-up dialog.
"""
assert isinstance(title, six.text_type)
assert isinstance(content, six.text_type)
self.popup_dialog.title = title
self._popup_textarea.text = content
self.client_state.display_popup = True
get_app().layout.focus(self._popup_textarea) | python | {
"resource": ""
} |
q36830 | LayoutManager._create_select_window_handler | train | def _create_select_window_handler(self, window):
" Return a mouse handler that selects the given window when clicking. "
def handler(mouse_event):
if mouse_event.event_type == MouseEventType.MOUSE_DOWN:
self.pymux.arrangement.set_active_window(window)
self.pymux.invalidate()
else:
return NotImplemented # Event not handled here.
return handler | python | {
"resource": ""
} |
q36831 | LayoutManager._get_status_tokens | train | def _get_status_tokens(self):
" The tokens for the status bar. "
result = []
# Display panes.
for i, w in enumerate(self.pymux.arrangement.windows):
if i > 0:
result.append(('', ' '))
if w == self.pymux.arrangement.get_active_window():
style = 'class:window.current'
format_str = self.pymux.window_status_current_format
else:
style = 'class:window'
format_str = self.pymux.window_status_format
result.append((
style,
format_pymux_string(self.pymux, format_str, window=w),
self._create_select_window_handler(w)))
return result | python | {
"resource": ""
} |
q36832 | DynamicBody._get_body | train | def _get_body(self):
" Return the Container object for the current CLI. "
new_hash = self.pymux.arrangement.invalidation_hash()
# Return existing layout if nothing has changed to the arrangement.
app = get_app()
if app in self._bodies_for_app:
existing_hash, container = self._bodies_for_app[app]
if existing_hash == new_hash:
return container
# The layout changed. Build a new layout when the arrangement changed.
new_layout = self._build_layout()
self._bodies_for_app[app] = (new_hash, new_layout)
return new_layout | python | {
"resource": ""
} |
q36833 | DynamicBody._build_layout | train | def _build_layout(self):
" Rebuild a new Container object and return that. "
logger.info('Rebuilding layout.')
if not self.pymux.arrangement.windows:
# No Pymux windows in the arrangement.
return Window()
active_window = self.pymux.arrangement.get_active_window()
# When zoomed, only show the current pane, otherwise show all of them.
if active_window.zoom:
return to_container(_create_container_for_process(
self.pymux, active_window, active_window.active_pane, zoom=True))
else:
window = self.pymux.arrangement.get_active_window()
return HSplit([
# Some spacing for the top status bar.
ConditionalContainer(
content=Window(height=1),
filter=Condition(lambda: self.pymux.enable_pane_status)),
# The actual content.
_create_split(self.pymux, window, window.root)
]) | python | {
"resource": ""
} |
q36834 | bind_and_listen_on_socket | train | def bind_and_listen_on_socket(socket_name, accept_callback):
"""
Return socket name.
:param accept_callback: Callback is called with a `PipeConnection` as
argument.
"""
if is_windows():
from .win32_server import bind_and_listen_on_win32_socket
return bind_and_listen_on_win32_socket(socket_name, accept_callback)
else:
from .posix import bind_and_listen_on_posix_socket
return bind_and_listen_on_posix_socket(socket_name, accept_callback) | python | {
"resource": ""
} |
q36835 | list_clients | train | def list_clients():
"""
List all the servers that are running.
"""
p = '%s/pymux.sock.%s.*' % (tempfile.gettempdir(), getpass.getuser())
for path in glob.glob(p):
try:
yield PosixClient(path)
except socket.error:
pass | python | {
"resource": ""
} |
q36836 | PosixClient.attach | train | def attach(self, detach_other_clients=False, color_depth=ColorDepth.DEPTH_8_BIT):
"""
Attach client user interface.
"""
assert isinstance(detach_other_clients, bool)
self._send_size()
self._send_packet({
'cmd': 'start-gui',
'detach-others': detach_other_clients,
'color-depth': color_depth,
'term': os.environ.get('TERM', ''),
'data': ''
})
with raw_mode(sys.stdin.fileno()):
data_buffer = b''
stdin_fd = sys.stdin.fileno()
socket_fd = self.socket.fileno()
current_timeout = INPUT_TIMEOUT # Timeout, used to flush escape sequences.
try:
def winch_handler(signum, frame):
self._send_size()
signal.signal(signal.SIGWINCH, winch_handler)
while True:
r = select_fds([stdin_fd, socket_fd], current_timeout)
if socket_fd in r:
# Received packet from server.
data = self.socket.recv(1024)
if data == b'':
# End of file. Connection closed.
# Reset terminal
o = Vt100_Output.from_pty(sys.stdout)
o.quit_alternate_screen()
o.disable_mouse_support()
o.disable_bracketed_paste()
o.reset_attributes()
o.flush()
return
else:
data_buffer += data
while b'\0' in data_buffer:
pos = data_buffer.index(b'\0')
self._process(data_buffer[:pos])
data_buffer = data_buffer[pos + 1:]
elif stdin_fd in r:
# Got user input.
self._process_stdin()
current_timeout = INPUT_TIMEOUT
else:
# Timeout. (Tell the server to flush the vt100 Escape.)
self._send_packet({'cmd': 'flush-input'})
current_timeout = None
finally:
signal.signal(signal.SIGWINCH, signal.SIG_IGN) | python | {
"resource": ""
} |
q36837 | PosixClient._process_stdin | train | def _process_stdin(self):
"""
Received data on stdin. Read and send to server.
"""
with nonblocking(sys.stdin.fileno()):
data = self._stdin_reader.read()
# Send input in chunks of 4k.
step = 4056
for i in range(0, len(data), step):
self._send_packet({
'cmd': 'in',
'data': data[i:i + step],
}) | python | {
"resource": ""
} |
q36838 | ClientState._handle_command | train | def _handle_command(self, buffer):
" When text is accepted in the command line. "
text = buffer.text
# First leave command mode. We want to make sure that the working
# pane is focused again before executing the command handers.
self.pymux.leave_command_mode(append_to_history=True)
# Execute command.
self.pymux.handle_command(text) | python | {
"resource": ""
} |
q36839 | ClientState._handle_prompt_command | train | def _handle_prompt_command(self, buffer):
" When a command-prompt command is accepted. "
text = buffer.text
prompt_command = self.prompt_command
# Leave command mode and handle command.
self.pymux.leave_command_mode(append_to_history=True)
self.pymux.handle_command(prompt_command.replace('%%', text)) | python | {
"resource": ""
} |
q36840 | ClientState._create_app | train | def _create_app(self):
"""
Create `Application` instance for this .
"""
pymux = self.pymux
def on_focus_changed():
""" When the focus changes to a read/write buffer, make sure to go
to insert mode. This happens when the ViState was set to NAVIGATION
in the copy buffer. """
vi_state = app.vi_state
if app.current_buffer.read_only():
vi_state.input_mode = InputMode.NAVIGATION
else:
vi_state.input_mode = InputMode.INSERT
app = Application(
output=self.output,
input=self.input,
color_depth=self.color_depth,
layout=Layout(container=self.layout_manager.layout),
key_bindings=pymux.key_bindings_manager.key_bindings,
mouse_support=Condition(lambda: pymux.enable_mouse_support),
full_screen=True,
style=self.pymux.style,
style_transformation=ConditionalStyleTransformation(
SwapLightAndDarkStyleTransformation(),
Condition(lambda: self.pymux.swap_dark_and_light),
),
on_invalidate=(lambda _: pymux.invalidate()))
# Synchronize the Vi state with the CLI object.
# (This is stored in the current class, but expected to be in the
# CommandLineInterface.)
def sync_vi_state(_):
VI = EditingMode.VI
EMACS = EditingMode.EMACS
if self.confirm_text or self.prompt_command or self.command_mode:
app.editing_mode = VI if pymux.status_keys_vi_mode else EMACS
else:
app.editing_mode = VI if pymux.mode_keys_vi_mode else EMACS
app.key_processor.before_key_press += sync_vi_state
app.key_processor.after_key_press += sync_vi_state
app.key_processor.after_key_press += self.sync_focus
# Set render postpone time. (.1 instead of 0).
# This small change ensures that if for a split second a process
# outputs a lot of information, we don't give the highest priority to
# rendering output. (Nobody reads that fast in real-time.)
app.max_render_postpone_time = .1 # Second.
# Hide message when a key has been pressed.
def key_pressed(_):
self.message = None
app.key_processor.before_key_press += key_pressed
# The following code needs to run with the application active.
# Especially, `create_window` needs to know what the current
# application is, in order to focus the new pane.
with set_app(app):
# Redraw all CLIs. (Adding a new client could mean that the others
# change size, so everything has to be redrawn.)
pymux.invalidate()
pymux.startup()
return app | python | {
"resource": ""
} |
q36841 | ClientState.sync_focus | train | def sync_focus(self, *_):
"""
Focus the focused window from the pymux arrangement.
"""
# Pop-up displayed?
if self.display_popup:
self.app.layout.focus(self.layout_manager.popup_dialog)
return
# Confirm.
if self.confirm_text:
return
# Custom prompt.
if self.prompt_command:
return # Focus prompt
# Command mode.
if self.command_mode:
return # Focus command
# No windows left, return. We will quit soon.
if not self.pymux.arrangement.windows:
return
pane = self.pymux.arrangement.get_active_pane()
self.app.layout.focus(pane.terminal) | python | {
"resource": ""
} |
q36842 | Pymux._start_auto_refresh_thread | train | def _start_auto_refresh_thread(self):
"""
Start the background thread that auto refreshes all clients according to
`self.status_interval`.
"""
def run():
while True:
time.sleep(self.status_interval)
self.invalidate()
t = threading.Thread(target=run)
t.daemon = True
t.start() | python | {
"resource": ""
} |
q36843 | Pymux.get_client_state | train | def get_client_state(self):
" Return the active ClientState instance. "
app = get_app()
for client_state in self._client_states.values():
if client_state.app == app:
return client_state
raise ValueError('Client state for app %r not found' % (app, )) | python | {
"resource": ""
} |
q36844 | Pymux.get_connection | train | def get_connection(self):
" Return the active Connection instance. "
app = get_app()
for connection, client_state in self._client_states.items():
if client_state.app == app:
return connection
raise ValueError('Connection for app %r not found' % (app, )) | python | {
"resource": ""
} |
q36845 | Pymux.get_title | train | def get_title(self):
"""
The title to be displayed in the titlebar of the terminal.
"""
w = self.arrangement.get_active_window()
if w and w.active_process:
title = w.active_process.screen.title
else:
title = ''
if title:
return '%s - Pymux' % (title, )
else:
return 'Pymux' | python | {
"resource": ""
} |
q36846 | Pymux.get_window_size | train | def get_window_size(self):
"""
Get the size to be used for the DynamicBody.
This will be the smallest size of all clients.
"""
def active_window_for_app(app):
with set_app(app):
return self.arrangement.get_active_window()
active_window = self.arrangement.get_active_window()
# Get sizes for connections watching the same window.
apps = [client_state.app for client_state in self._client_states.values()
if active_window_for_app(client_state.app) == active_window]
sizes = [app.output.get_size() for app in apps]
rows = [s.rows for s in sizes]
columns = [s.columns for s in sizes]
if rows and columns:
return Size(rows=min(rows) - (1 if self.enable_status else 0),
columns=min(columns))
else:
return Size(rows=20, columns=80) | python | {
"resource": ""
} |
q36847 | Pymux.invalidate | train | def invalidate(self):
" Invalidate the UI for all clients. "
logger.info('Invalidating %s applications', len(self.apps))
for app in self.apps:
app.invalidate() | python | {
"resource": ""
} |
q36848 | Pymux.kill_pane | train | def kill_pane(self, pane):
"""
Kill the given pane, and remove it from the arrangement.
"""
assert isinstance(pane, Pane)
# Send kill signal.
if not pane.process.is_terminated:
pane.process.kill()
# Remove from layout.
self.arrangement.remove_pane(pane) | python | {
"resource": ""
} |
q36849 | Pymux.detach_client | train | def detach_client(self, app):
"""
Detach the client that belongs to this CLI.
"""
connection = self.get_connection()
if connection:
connection.detach_and_close()
# Redraw all clients -> Maybe their size has to change.
self.invalidate() | python | {
"resource": ""
} |
q36850 | Pymux.listen_on_socket | train | def listen_on_socket(self, socket_name=None):
"""
Listen for clients on a Unix socket.
Returns the socket name.
"""
def connection_cb(pipe_connection):
# We have to create a new `context`, because this will be the scope for
# a new prompt_toolkit.Application to become active.
with context():
connection = ServerConnection(self, pipe_connection)
self.connections.append(connection)
self.socket_name = bind_and_listen_on_socket(socket_name, connection_cb)
# Set session_name according to socket name.
# if '.' in self.socket_name:
# self.session_name = self.socket_name.rpartition('.')[-1]
logger.info('Listening on %r.' % self.socket_name)
return self.socket_name | python | {
"resource": ""
} |
q36851 | _bind_posix_socket | train | def _bind_posix_socket(socket_name=None):
"""
Find a socket to listen on and return it.
Returns (socket_name, sock_obj)
"""
assert socket_name is None or isinstance(socket_name, six.text_type)
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
if socket_name:
s.bind(socket_name)
return socket_name, s
else:
i = 0
while True:
try:
socket_name = '%s/pymux.sock.%s.%i' % (
tempfile.gettempdir(), getpass.getuser(), i)
s.bind(socket_name)
return socket_name, s
except (OSError, socket.error):
i += 1
# When 100 times failed, cancel server
if i == 100:
logger.warning('100 times failed to listen on posix socket. '
'Please clean up old sockets.')
raise | python | {
"resource": ""
} |
q36852 | PosixSocketConnection.write | train | def write(self, message):
"""
Coroutine that writes the next packet.
"""
try:
self.socket.send(message.encode('utf-8') + b'\0')
except socket.error:
if not self._closed:
raise BrokenPipeError
return Future.succeed(None) | python | {
"resource": ""
} |
q36853 | PymuxKeyBindings._load_prefix_binding | train | def _load_prefix_binding(self):
"""
Load the prefix key binding.
"""
pymux = self.pymux
# Remove previous binding.
if self._prefix_binding:
self.custom_key_bindings.remove_binding(self._prefix_binding)
# Create new Python binding.
@self.custom_key_bindings.add(*self._prefix, filter=
~(HasPrefix(pymux) | has_focus(COMMAND) | has_focus(PROMPT) |
WaitsForConfirmation(pymux)))
def enter_prefix_handler(event):
" Enter prefix mode. "
pymux.get_client_state().has_prefix = True
self._prefix_binding = enter_prefix_handler | python | {
"resource": ""
} |
q36854 | PymuxKeyBindings.prefix | train | def prefix(self, keys):
"""
Set a new prefix key.
"""
assert isinstance(keys, tuple)
self._prefix = keys
self._load_prefix_binding() | python | {
"resource": ""
} |
q36855 | PymuxKeyBindings.remove_custom_binding | train | def remove_custom_binding(self, key_name, needs_prefix=False):
"""
Remove custom key binding for a key.
:param key_name: Pymux key name, for instance "C-A".
"""
k = (needs_prefix, key_name)
if k in self.custom_bindings:
self.custom_key_bindings.remove(self.custom_bindings[k].handler)
del self.custom_bindings[k] | python | {
"resource": ""
} |
q36856 | PipeInstance._handle_client | train | def _handle_client(self):
"""
Coroutine that connects to a single client and handles that.
"""
while True:
try:
# Wait for connection.
logger.info('Waiting for connection in pipe instance.')
yield From(self._connect_client())
logger.info('Connected in pipe instance')
conn = Win32PipeConnection(self)
self.pipe_connection_cb(conn)
yield From(conn.done_f)
logger.info('Pipe instance done.')
finally:
# Disconnect and reconnect.
logger.info('Disconnecting pipe instance.')
windll.kernel32.DisconnectNamedPipe(self.pipe_handle) | python | {
"resource": ""
} |
q36857 | PipeInstance._connect_client | train | def _connect_client(self):
"""
Wait for a client to connect to this pipe.
"""
overlapped = OVERLAPPED()
overlapped.hEvent = create_event()
while True:
success = windll.kernel32.ConnectNamedPipe(
self.pipe_handle,
byref(overlapped))
if success:
return
last_error = windll.kernel32.GetLastError()
if last_error == ERROR_IO_PENDING:
yield From(wait_for_event(overlapped.hEvent))
# XXX: Call GetOverlappedResult.
return # Connection succeeded.
else:
raise Exception('connect failed with error code' + str(last_error)) | python | {
"resource": ""
} |
q36858 | pymux_key_to_prompt_toolkit_key_sequence | train | def pymux_key_to_prompt_toolkit_key_sequence(key):
"""
Turn a pymux description of a key. E.g. "C-a" or "M-x" into a
prompt-toolkit key sequence.
Raises `ValueError` if the key is not known.
"""
# Make the c- and m- prefixes case insensitive.
if key.lower().startswith('m-c-'):
key = 'M-C-' + key[4:]
elif key.lower().startswith('c-'):
key = 'C-' + key[2:]
elif key.lower().startswith('m-'):
key = 'M-' + key[2:]
# Lookup key.
try:
return PYMUX_TO_PROMPT_TOOLKIT_KEYS[key]
except KeyError:
if len(key) == 1:
return (key, )
else:
raise ValueError('Unknown key: %r' % (key, )) | python | {
"resource": ""
} |
q36859 | PositiveIntOption.set_value | train | def set_value(self, pymux, value):
"""
Take a string, and return an integer. Raise SetOptionError when the
given text does not parse to a positive integer.
"""
try:
value = int(value)
if value < 0:
raise ValueError
except ValueError:
raise SetOptionError('Expecting an integer.')
else:
setattr(pymux, self.attribute_name, value) | python | {
"resource": ""
} |
q36860 | handle_command | train | def handle_command(pymux, input_string):
"""
Handle command.
"""
assert isinstance(input_string, six.text_type)
input_string = input_string.strip()
logger.info('handle command: %s %s.', input_string, type(input_string))
if input_string and not input_string.startswith('#'): # Ignore comments.
try:
if six.PY2:
# In Python2.6, shlex doesn't work with unicode input at all.
# In Python2.7, shlex tries to encode using ASCII.
parts = shlex.split(input_string.encode('utf-8'))
parts = [p.decode('utf-8') for p in parts]
else:
parts = shlex.split(input_string)
except ValueError as e:
# E.g. missing closing quote.
pymux.show_message('Invalid command %s: %s' % (input_string, e))
else:
call_command_handler(parts[0], pymux, parts[1:]) | python | {
"resource": ""
} |
q36861 | cmd | train | def cmd(name, options=''):
"""
Decorator for all commands.
Commands will receive (pymux, variables) as input.
Commands can raise CommandException.
"""
# Validate options.
if options:
try:
docopt.docopt('Usage:\n %s %s' % (name, options, ), [])
except SystemExit:
pass
def decorator(func):
def command_wrapper(pymux, arguments):
# Hack to make the 'bind-key' option work.
# (bind-key expects a variable number of arguments.)
if name == 'bind-key' and '--' not in arguments:
# Insert a double dash after the first non-option.
for i, p in enumerate(arguments):
if not p.startswith('-'):
arguments.insert(i + 1, '--')
break
# Parse options.
try:
# Python 2 workaround: pass bytes to docopt.
# From the following, only the bytes version returns the right
# output in Python 2:
# docopt.docopt('Usage:\n app <params>...', [b'a', b'b'])
# docopt.docopt('Usage:\n app <params>...', [u'a', u'b'])
# https://github.com/docopt/docopt/issues/30
# (Not sure how reliable this is...)
if six.PY2:
arguments = [a.encode('utf-8') for a in arguments]
received_options = docopt.docopt(
'Usage:\n %s %s' % (name, options),
arguments,
help=False) # Don't interpret the '-h' option as help.
# Make sure that all the received options from docopt are
# unicode objects. (Docopt returns 'str' for Python2.)
for k, v in received_options.items():
if isinstance(v, six.binary_type):
received_options[k] = v.decode('utf-8')
except SystemExit:
raise CommandException('Usage: %s %s' % (name, options))
# Call handler.
func(pymux, received_options)
# Invalidate all clients, not just the current CLI.
pymux.invalidate()
COMMANDS_TO_HANDLERS[name] = command_wrapper
COMMANDS_TO_HELP[name] = options
# Get list of option flags.
flags = re.findall(r'-[a-zA-Z0-9]\b', options)
COMMANDS_TO_OPTION_FLAGS[name] = flags
return func
return decorator | python | {
"resource": ""
} |
q36862 | kill_window | train | def kill_window(pymux, variables):
" Kill all panes in the current window. "
for pane in pymux.arrangement.get_active_window().panes:
pymux.kill_pane(pane) | python | {
"resource": ""
} |
q36863 | next_layout | train | def next_layout(pymux, variables):
" Select next layout. "
pane = pymux.arrangement.get_active_window()
if pane:
pane.select_next_layout() | python | {
"resource": ""
} |
q36864 | previous_layout | train | def previous_layout(pymux, variables):
" Select previous layout. "
pane = pymux.arrangement.get_active_window()
if pane:
pane.select_previous_layout() | python | {
"resource": ""
} |
q36865 | _ | train | def _(pymux, variables):
" Go to previous active window. "
w = pymux.arrangement.get_previous_active_window()
if w:
pymux.arrangement.set_active_window(w) | python | {
"resource": ""
} |
q36866 | split_window | train | def split_window(pymux, variables):
"""
Split horizontally or vertically.
"""
executable = variables['<executable>']
start_directory = variables['<start-directory>']
# The tmux definition of horizontal is the opposite of prompt_toolkit.
pymux.add_process(executable, vsplit=variables['-h'],
start_directory=start_directory) | python | {
"resource": ""
} |
q36867 | command_prompt | train | def command_prompt(pymux, variables):
"""
Enter command prompt.
"""
client_state = pymux.get_client_state()
if variables['<command>']:
# When a 'command' has been given.
client_state.prompt_text = variables['<message>'] or '(%s)' % variables['<command>'].split()[0]
client_state.prompt_command = variables['<command>']
client_state.prompt_mode = True
client_state.prompt_buffer.reset(Document(
format_pymux_string(pymux, variables['<default>'] or '')))
get_app().layout.focus(client_state.prompt_buffer)
else:
# Show the ':' prompt.
client_state.prompt_text = ''
client_state.prompt_command = ''
get_app().layout.focus(client_state.command_buffer)
# Go to insert mode.
get_app().vi_state.input_mode = InputMode.INSERT | python | {
"resource": ""
} |
q36868 | send_prefix | train | def send_prefix(pymux, variables):
"""
Send prefix to active pane.
"""
process = pymux.arrangement.get_active_pane().process
for k in pymux.key_bindings_manager.prefix:
vt100_data = prompt_toolkit_key_to_vt100_key(k)
process.write_input(vt100_data) | python | {
"resource": ""
} |
q36869 | unbind_key | train | def unbind_key(pymux, variables):
"""
Remove key binding.
"""
key = variables['<key>']
needs_prefix = not variables['-n']
pymux.key_bindings_manager.remove_custom_binding(
key, needs_prefix=needs_prefix) | python | {
"resource": ""
} |
q36870 | send_keys | train | def send_keys(pymux, variables):
"""
Send key strokes to the active process.
"""
pane = pymux.arrangement.get_active_pane()
if pane.display_scroll_buffer:
raise CommandException('Cannot send keys. Pane is in copy mode.')
for key in variables['<keys>']:
# Translate key from pymux key to prompt_toolkit key.
try:
keys_sequence = pymux_key_to_prompt_toolkit_key_sequence(key)
except ValueError:
raise CommandException('Invalid key: %r' % (key, ))
# Translate prompt_toolkit key to VT100 key.
for k in keys_sequence:
pane.process.write_key(k) | python | {
"resource": ""
} |
q36871 | copy_mode | train | def copy_mode(pymux, variables):
"""
Enter copy mode.
"""
go_up = variables['-u'] # Go in copy mode and page-up directly.
# TODO: handle '-u'
pane = pymux.arrangement.get_active_pane()
pane.enter_copy_mode() | python | {
"resource": ""
} |
q36872 | paste_buffer | train | def paste_buffer(pymux, variables):
"""
Paste clipboard content into buffer.
"""
pane = pymux.arrangement.get_active_pane()
pane.process.write_input(get_app().clipboard.get_data().text, paste=True) | python | {
"resource": ""
} |
q36873 | source_file | train | def source_file(pymux, variables):
"""
Source configuration file.
"""
filename = os.path.expanduser(variables['<filename>'])
try:
with open(filename, 'rb') as f:
for line in f:
line = line.decode('utf-8')
handle_command(pymux, line)
except IOError as e:
raise CommandException('IOError: %s' % (e, )) | python | {
"resource": ""
} |
q36874 | display_message | train | def display_message(pymux, variables):
" Display a message. "
message = variables['<message>']
client_state = pymux.get_client_state()
client_state.message = message | python | {
"resource": ""
} |
q36875 | clear_history | train | def clear_history(pymux, variables):
" Clear scrollback buffer. "
pane = pymux.arrangement.get_active_pane()
if pane.display_scroll_buffer:
raise CommandException('Not available in copy mode')
else:
pane.process.screen.clear_history() | python | {
"resource": ""
} |
q36876 | list_keys | train | def list_keys(pymux, variables):
"""
Display all configured key bindings.
"""
# Create help string.
result = []
for k, custom_binding in pymux.key_bindings_manager.custom_bindings.items():
needs_prefix, key = k
result.append('bind-key %3s %-10s %s %s' % (
('-n' if needs_prefix else ''), key, custom_binding.command,
' '.join(map(wrap_argument, custom_binding.arguments))))
# Display help in pane.
result = '\n'.join(sorted(result))
pymux.get_client_state().layout_manager.display_popup('list-keys', result) | python | {
"resource": ""
} |
q36877 | list_panes | train | def list_panes(pymux, variables):
"""
Display a list of all the panes.
"""
w = pymux.arrangement.get_active_window()
active_pane = w.active_pane
result = []
for i, p in enumerate(w.panes):
process = p.process
result.append('%i: [%sx%s] [history %s/%s] %s' % (
i, process.sx, process.sy,
min(pymux.history_limit, process.screen.line_offset + process.sy),
pymux.history_limit,
('(active)' if p == active_pane else '')))
# Display help in pane.
result = '\n'.join(sorted(result))
pymux.get_client_state().layout_manager.display_popup('list-keys', result) | python | {
"resource": ""
} |
q36878 | show_buffer | train | def show_buffer(pymux, variables):
"""
Display the clipboard content.
"""
text = get_app().clipboard.get_data().text
pymux.get_client_state().layout_manager.display_popup('show-buffer', text) | python | {
"resource": ""
} |
q36879 | Pane.name | train | def name(self):
"""
The name for the window as displayed in the title bar and status bar.
"""
# Name, explicitely set for the pane.
if self.chosen_name:
return self.chosen_name
else:
# Name from the process running inside the pane.
name = self.process.get_name()
if name:
return os.path.basename(name)
return '' | python | {
"resource": ""
} |
q36880 | Window.name | train | def name(self):
"""
The name for this window as it should be displayed in the status bar.
"""
# Name, explicitely set for the window.
if self.chosen_name:
return self.chosen_name
else:
pane = self.active_pane
if pane:
return pane.name
return '' | python | {
"resource": ""
} |
q36881 | Window.add_pane | train | def add_pane(self, pane, vsplit=False):
"""
Add another pane to this Window.
"""
assert isinstance(pane, Pane)
assert isinstance(vsplit, bool)
split_cls = VSplit if vsplit else HSplit
if self.active_pane is None:
self.root.append(pane)
else:
parent = self._get_parent(self.active_pane)
same_direction = isinstance(parent, split_cls)
index = parent.index(self.active_pane)
if same_direction:
parent.insert(index + 1, pane)
else:
new_split = split_cls([self.active_pane, pane])
parent[index] = new_split
# Give the newly created split the same weight as the original
# pane that was at this position.
parent.weights[new_split] = parent.weights[self.active_pane]
self.active_pane = pane
self.zoom = False | python | {
"resource": ""
} |
q36882 | Window.remove_pane | train | def remove_pane(self, pane):
"""
Remove pane from this Window.
"""
assert isinstance(pane, Pane)
if pane in self.panes:
# When this pane was focused, switch to previous active or next in order.
if pane == self.active_pane:
if self.previous_active_pane:
self.active_pane = self.previous_active_pane
else:
self.focus_next()
# Remove from the parent. When the parent becomes empty, remove the
# parent itself recursively.
p = self._get_parent(pane)
p.remove(pane)
while len(p) == 0 and p != self.root:
p2 = self._get_parent(p)
p2.remove(p)
p = p2
# When the parent has only one item left, collapse into its parent.
while len(p) == 1 and p != self.root:
p2 = self._get_parent(p)
p2.weights[p[0]] = p2.weights[p] # Keep dimensions.
i = p2.index(p)
p2[i] = p[0]
p = p2 | python | {
"resource": ""
} |
q36883 | Window.panes | train | def panes(self):
" List with all panes from this Window. "
result = []
for s in self.splits:
for item in s:
if isinstance(item, Pane):
result.append(item)
return result | python | {
"resource": ""
} |
q36884 | Window.focus_next | train | def focus_next(self, count=1):
" Focus the next pane. "
panes = self.panes
if panes:
self.active_pane = panes[(panes.index(self.active_pane) + count) % len(panes)]
else:
self.active_pane = None | python | {
"resource": ""
} |
q36885 | Window.select_layout | train | def select_layout(self, layout_type):
"""
Select one of the predefined layouts.
"""
assert layout_type in LayoutTypes._ALL
# When there is only one pane, always choose EVEN_HORIZONTAL,
# Otherwise, we create VSplit/HSplit instances with an empty list of
# children.
if len(self.panes) == 1:
layout_type = LayoutTypes.EVEN_HORIZONTAL
# even-horizontal.
if layout_type == LayoutTypes.EVEN_HORIZONTAL:
self.root = HSplit(self.panes)
# even-vertical.
elif layout_type == LayoutTypes.EVEN_VERTICAL:
self.root = VSplit(self.panes)
# main-horizontal.
elif layout_type == LayoutTypes.MAIN_HORIZONTAL:
self.root = HSplit([
self.active_pane,
VSplit([p for p in self.panes if p != self.active_pane])
])
# main-vertical.
elif layout_type == LayoutTypes.MAIN_VERTICAL:
self.root = VSplit([
self.active_pane,
HSplit([p for p in self.panes if p != self.active_pane])
])
# tiled.
elif layout_type == LayoutTypes.TILED:
panes = self.panes
column_count = math.ceil(len(panes) ** .5)
rows = HSplit()
current_row = VSplit()
for p in panes:
current_row.append(p)
if len(current_row) >= column_count:
rows.append(current_row)
current_row = VSplit()
if current_row:
rows.append(current_row)
self.root = rows
self.previous_selected_layout = layout_type | python | {
"resource": ""
} |
q36886 | Window.change_size_for_active_pane | train | def change_size_for_active_pane(self, up=0, right=0, down=0, left=0):
"""
Increase the size of the current pane in any of the four directions.
"""
child = self.active_pane
self.change_size_for_pane(child, up=up, right=right, down=down, left=left) | python | {
"resource": ""
} |
q36887 | Window.change_size_for_pane | train | def change_size_for_pane(self, pane, up=0, right=0, down=0, left=0):
"""
Increase the size of the current pane in any of the four directions.
Positive values indicate an increase, negative values a decrease.
"""
assert isinstance(pane, Pane)
def find_split_and_child(split_cls, is_before):
" Find the split for which we will have to update the weights. "
child = pane
split = self._get_parent(child)
def found():
return isinstance(split, split_cls) and (
not is_before or split.index(child) > 0) and (
is_before or split.index(child) < len(split) - 1)
while split and not found():
child = split
split = self._get_parent(child)
return split, child # split can be None!
def handle_side(split_cls, is_before, amount, trying_other_side=False):
" Increase weights on one side. (top/left/right/bottom). "
if amount:
split, child = find_split_and_child(split_cls, is_before)
if split:
# Find neighbour.
neighbour_index = split.index(child) + (-1 if is_before else 1)
neighbour_child = split[neighbour_index]
# Increase/decrease weights.
split.weights[child] += amount
split.weights[neighbour_child] -= amount
# Ensure that all weights are at least one.
for k, value in split.weights.items():
if value < 1:
split.weights[k] = 1
else:
# When no split has been found where we can move in this
# direction, try to move the other side instead using a
# negative amount. This happens when we run "resize-pane -R 4"
# inside the pane that is completely on the right. In that
# case it's logical to move the left border to the right
# instead.
if not trying_other_side:
handle_side(split_cls, not is_before, -amount,
trying_other_side=True)
handle_side(VSplit, True, left)
handle_side(VSplit, False, right)
handle_side(HSplit, True, up)
handle_side(HSplit, False, down) | python | {
"resource": ""
} |
q36888 | Window.get_pane_index | train | def get_pane_index(self, pane):
" Return the index of the given pane. ValueError if not found. "
assert isinstance(pane, Pane)
return self.panes.index(pane) | python | {
"resource": ""
} |
q36889 | Arrangement.set_active_window_from_pane_id | train | def set_active_window_from_pane_id(self, pane_id):
"""
Make the window with this pane ID the active Window.
"""
assert isinstance(pane_id, int)
for w in self.windows:
for p in w.panes:
if p.pane_id == pane_id:
self.set_active_window(w) | python | {
"resource": ""
} |
q36890 | Arrangement.get_window_by_index | train | def get_window_by_index(self, index):
" Return the Window with this index or None if not found. "
for w in self.windows:
if w.index == index:
return w | python | {
"resource": ""
} |
q36891 | Arrangement.create_window | train | def create_window(self, pane, name=None, set_active=True):
"""
Create a new window that contains just this pane.
:param pane: The :class:`.Pane` instance to put in the new window.
:param name: If given, name for the new window.
:param set_active: When True, focus the new window.
"""
assert isinstance(pane, Pane)
assert name is None or isinstance(name, six.text_type)
# Take the first available index.
taken_indexes = [w.index for w in self.windows]
index = self.base_index
while index in taken_indexes:
index += 1
# Create new window and add it.
w = Window(index)
w.add_pane(pane)
self.windows.append(w)
# Sort windows by index.
self.windows = sorted(self.windows, key=lambda w: w.index)
app = get_app(return_none=True)
if app is not None and set_active:
self.set_active_window(w)
if name is not None:
w.chosen_name = name
assert w.active_pane == pane
assert w._get_parent(pane) | python | {
"resource": ""
} |
q36892 | Arrangement.break_pane | train | def break_pane(self, set_active=True):
"""
When the current window has multiple panes, remove the pane from this
window and put it in a new window.
:param set_active: When True, focus the new window.
"""
w = self.get_active_window()
if len(w.panes) > 1:
pane = w.active_pane
self.get_active_window().remove_pane(pane)
self.create_window(pane, set_active=set_active) | python | {
"resource": ""
} |
q36893 | Arrangement.rotate_window | train | def rotate_window(self, count=1):
" Rotate the panes in the active window. "
w = self.get_active_window()
w.rotate(count=count) | python | {
"resource": ""
} |
q36894 | ServerConnection._process | train | def _process(self, data):
"""
Process packet received from client.
"""
try:
packet = json.loads(data)
except ValueError:
# So far, this never happened. But it would be good to have some
# protection.
logger.warning('Received invalid JSON from client. Ignoring.')
return
# Handle commands.
if packet['cmd'] == 'run-command':
self._run_command(packet)
# Handle stdin.
elif packet['cmd'] == 'in':
self._pipeinput.send_text(packet['data'])
# elif packet['cmd'] == 'flush-input':
# self._inputstream.flush() # Flush escape key. # XXX: I think we no longer need this.
# Set size. (The client reports the size.)
elif packet['cmd'] == 'size':
data = packet['data']
self.size = Size(rows=data[0], columns=data[1])
self.pymux.invalidate()
# Start GUI. (Create CommandLineInterface front-end for pymux.)
elif packet['cmd'] == 'start-gui':
detach_other_clients = bool(packet['detach-others'])
color_depth = packet['color-depth']
term = packet['term']
if detach_other_clients:
for c in self.pymux.connections:
c.detach_and_close()
print('Create app...')
self._create_app(color_depth=color_depth, term=term) | python | {
"resource": ""
} |
q36895 | ServerConnection._send_packet | train | def _send_packet(self, data):
"""
Send packet to client.
"""
if self._closed:
return
data = json.dumps(data)
def send():
try:
yield From(self.pipe_connection.write(data))
except BrokenPipeError:
self.detach_and_close()
ensure_future(send()) | python | {
"resource": ""
} |
q36896 | ServerConnection._run_command | train | def _run_command(self, packet):
"""
Execute a run command from the client.
"""
create_temp_cli = self.client_states is None
if create_temp_cli:
# If this client doesn't have a CLI. Create a Fake CLI where the
# window containing this pane, is the active one. (The CLI instance
# will be removed before the render function is called, so it doesn't
# hurt too much and makes the code easier.)
pane_id = int(packet['pane_id'])
self._create_app()
with set_app(self.client_state.app):
self.pymux.arrangement.set_active_window_from_pane_id(pane_id)
with set_app(self.client_state.app):
try:
self.pymux.handle_command(packet['data'])
finally:
self._close_connection() | python | {
"resource": ""
} |
q36897 | ServerConnection._create_app | train | def _create_app(self, color_depth, term='xterm'):
"""
Create CommandLineInterface for this client.
Called when the client wants to attach the UI to the server.
"""
output = Vt100_Output(_SocketStdout(self._send_packet),
lambda: self.size,
term=term,
write_binary=False)
self.client_state = self.pymux.add_client(
input=self._pipeinput, output=output, connection=self, color_depth=color_depth)
print('Start running app...')
future = self.client_state.app.run_async()
print('Start running app got future...', future)
@future.add_done_callback
def done(_):
print('APP DONE.........')
print(future.result())
self._close_connection() | python | {
"resource": ""
} |
q36898 | _ClientInput._create_context_manager | train | def _create_context_manager(self, mode):
" Create a context manager that sends 'mode' commands to the client. "
class mode_context_manager(object):
def __enter__(*a):
self.send_packet({'cmd': 'mode', 'data': mode})
def __exit__(*a):
self.send_packet({'cmd': 'mode', 'data': 'restore'})
return mode_context_manager() | python | {
"resource": ""
} |
q36899 | wrap_argument | train | def wrap_argument(text):
"""
Wrap command argument in quotes and escape when this contains special characters.
"""
if not any(x in text for x in [' ', '"', "'", '\\']):
return text
else:
return '"%s"' % (text.replace('\\', r'\\').replace('"', r'\"'), ) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.