text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """ Close the cursor. """
self.result_set = None if self.impl is not None: self.impl._reset() self.impl = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)), ] ) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def focus_right(pymux): " Move focus to the right. " _move_focus(pymux, lambda wp: wp.xpos + wp.width + 1, lambda wp: wp.ypos)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def focus_down(pymux): " Move focus down. " _move_focus(pymux, lambda wp: wp.xpos, lambda wp: wp.ypos + wp.height + 2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def focus_up(pymux): " Move focus up. " _move_focus(pymux, lambda wp: wp.xpos, lambda wp: wp.ypos - 2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _mouse_handler(self, cli, mouse_event): " Click callback. " if mouse_event.event_type == MouseEventType.MOUSE_UP: self.on_click(cli) else: return NotImplemented
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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) ])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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], })
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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, ))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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, ))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def invalidate(self): " Invalidate the UI for all clients. " logger.info('Invalidating %s applications', len(self.apps)) for app in self.apps: app.invalidate()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prefix(self, keys): """ Set a new prefix key. """
assert isinstance(keys, tuple) self._prefix = keys self._load_prefix_binding()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, ))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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:])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def next_layout(pymux, variables): " Select next layout. " pane = pymux.arrangement.get_active_window() if pane: pane.select_next_layout()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def previous_layout(pymux, variables): " Select previous layout. " pane = pymux.arrangement.get_active_window() if pane: pane.select_previous_layout()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _(pymux, variables): " Go to previous active window. " w = pymux.arrangement.get_previous_active_window() if w: pymux.arrangement.set_active_window(w)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, ))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def display_message(pymux, variables): " Display a message. " message = variables['<message>'] client_state = pymux.get_client_state() client_state.message = message
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ''
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ''
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rotate_window(self, count=1): " Rotate the panes in the active window. " w = self.get_active_window() w.rotate(count=count)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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'\"'), )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_default_shell(): """ return the path to the default shell for the current user. """
if is_windows(): return 'cmd.exe' else: import pwd import getpass if 'SHELL' in os.environ: return os.environ['SHELL'] else: username = getpass.getuser() shell = pwd.getpwnam(username).pw_shell return shell
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _confirm_or_prompt_or_command(pymux): " True when we are waiting for a command, prompt or confirmation. " client_state = pymux.get_client_state() if client_state.confirm_text or client_state.prompt_command or client_state.command_mode: return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def mutate(self): ''' Mutate to next state :return: True if mutated, False if not ''' self._get_ready() if self._is_last_index(): return False self._current_index += 1 self._mutate() return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_stats(self): ''' Get kitty stats as a dictionary ''' resp = requests.get('%s/api/stats.json' % self.url) assert(resp.status_code == 200) return resp.json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _handle_options(self, option_line): ''' Handle options from command line, in docopt style. This allows passing arguments to the fuzzer from the command line without the need to re-write it in each runner. :param option_line: string with the command line options to be parsed. ''' if option_line is not None: usage = ''' These are the options to the kitty fuzzer object, not the options to the runner. Usage: fuzzer [options] [-v ...] Options: -d --delay <delay> delay between tests in secodes, float number -f --session <session-file> session file name to use -n --no-env-test don't perform environment test before the fuzzing session -r --retest <session-file> retest failed/error tests from a session file -t --test-list <test-list> a comma delimited test list string of the form "-10,12,15-20,30-" -v --verbose be more verbose in the log Removed options: end, start - use --test-list instead ''' options = docopt.docopt(usage, shlex.split(option_line)) # ranges if options['--retest']: retest_file = options['--retest'] try: test_list_str = self._get_test_list_from_session_file(retest_file) except Exception as ex: raise KittyException('Failed to open session file (%s) for retesting: %s' % (retest_file, ex)) else: test_list_str = options['--test-list'] self._set_test_ranges(None, None, test_list_str) # session file session_file = options['--session'] if session_file is not None: self.set_session_file(session_file) # delay between tests delay = options['--delay'] if delay is not None: self.set_delay_between_tests(float(delay)) # environment test skip_env_test = options['--no-env-test'] if skip_env_test: self.set_skip_env_test(True) # verbosity verbosity = options['--verbose'] self.set_verbosity(verbosity)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def set_model(self, model): ''' Set the model to fuzz :type model: :class:`~kitty.model.high_level.base.BaseModel` or a subclass :param model: Model object to fuzz ''' self.model = model if self.model: self.model.set_notification_handler(self) self.handle_stage_changed(model) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def set_range(self, start_index=0, end_index=None): ''' Set range of tests to run .. deprecated:: use :func:`~kitty.fuzzers.base.BaseFuzzer.set_test_list` :param start_index: index to start at (default=0) :param end_index: index to end at(default=None) ''' if end_index is not None: end_index += 1 self._test_list = StartEndList(start_index, end_index) self.session_info.start_index = start_index self.session_info.current_index = 0 self.session_info.end_index = end_index self.session_info.test_list_str = self._test_list.as_test_list_str() return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def start(self): ''' Start the fuzzing session If fuzzer already running, it will return immediatly ''' if self._started: self.logger.warning('called while fuzzer is running. ignoring.') return self._started = True assert(self.model) assert(self.user_interface) assert(self.target) if self._load_session(): self._check_session_validity() self._set_test_ranges( self.session_info.start_index, self.session_info.end_index, self.session_info.test_list_str ) else: self.session_info.kitty_version = _get_current_version() # TODO: write hash for high level self.session_info.data_model_hash = self.model.hash() # if self.session_info.end_index is None: # self.session_info.end_index = self.model.last_index() if self._test_list is None: self._test_list = StartEndList(0, self.model.num_mutations()) else: self._test_list.set_last(self.model.last_index()) list_count = self._test_list.get_count() self._test_list.skip(list_count - 1) self.session_info.end_index = self._test_list.current() self._test_list.reset() self._store_session() self._test_list.skip(self.session_info.current_index) self.session_info.test_list_str = self._test_list.as_test_list_str() self._set_signal_handler() self.user_interface.set_data_provider(self.dataman) self.user_interface.set_continue_event(self._continue_event) self.user_interface.start() self.session_info.start_time = time.time() try: self._start_message() self.target.setup() start_from = self.session_info.current_index if self._skip_env_test: self.logger.info('Skipping environment test') else: self.logger.info('Performing environment test') self._test_environment() self._in_environment_test = False self._test_list.reset() self._test_list.skip(start_from) self.session_info.current_index = start_from self.model.skip(self._test_list.current()) self._start() return True except Exception as e: self.logger.error('Error occurred while fuzzing: %s', repr(e)) self.logger.error(traceback.format_exc()) return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def handle_stage_changed(self, model): ''' handle a stage change in the data model :param model: the data model that was changed ''' stages = model.get_stages() if self.dataman: self.dataman.set('stages', stages)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def stop(self): ''' stop the fuzzing session ''' assert(self.model) assert(self.user_interface) assert(self.target) self.user_interface.stop() self.target.teardown() self.dataman.submit_task(None) self._un_set_signal_handler()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _keep_running(self): ''' Should we still fuzz?? ''' if self.config.max_failures: if self.session_info.failure_count >= self.config.max_failures: return False return self._test_list.current() is not None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def set_verbosity(cls, verbosity): ''' Set verbosity of logger :param verbosity: verbosity level. currently, we only support 1 (logging.DEBUG) ''' if verbosity > 0: # currently, we only toggle between INFO, DEBUG logger = KittyObject.get_logger() levels = [logging.DEBUG] verbosity = min(verbosity, len(levels)) - 1 logger.setLevel(levels[verbosity])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def not_implemented(self, func_name): ''' log access to unimplemented method and raise error :param func_name: name of unimplemented function. :raise: NotImplementedError detailing the function the is not implemented. ''' msg = '%s is not overridden by %s' % (func_name, type(self).__name__) self.logger.error(msg) raise NotImplementedError(msg)