Curses addch() method that fixes a major bug in python 3.4.

        See http://bugs.python.org/issue21088
499673
def addch(window, y, x, ch, attr):
        

        if sys.version_info[:3] == (3, 4, 0):
            y, x = x, y

        window.addch(y, x, ch, attr)
578673
private void getResolvedScriptSetWithout(CharSequence input, int script, ScriptSet result) {
        result.setAll();

        ScriptSet temp = new ScriptSet();
        for (int utf16Offset = 0; utf16Offset < input.length();) {
            int codePoint = Character.codePointAt(input, utf16Offset);
            utf16Offset += Character.charCount(codePoint);

            // Compute the augmented script set for the character
            getAugmentedScriptSet(codePoint, temp);

            // Intersect the augmented script set with the resolved script set, but only if the character doesn't
            // have the script specified in the function call
            if (script == UScript.CODE_LIMIT || !temp.get(script)) {
                result.and(temp);
            }
        }
    }
1141670
def patch_modules():
    
    old_call = subprocess.call

    def dummy_call(*args, **kwargs):
        with tempfile.TemporaryFile("wb+") as f:
            kwargs["stdout"] = f
            kwargs["stderr"] = f
            rv = subprocess.Popen(*args, **kwargs).wait()
            f.seek(0)
            click.echo(f.read().decode("utf-8", "replace").rstrip())
        return rv

    subprocess.call = dummy_call

    try:
        yield
    finally:
        subprocess.call = old_call
311398
def keypress(self, win, char):
        
        if not self._focused:
            return 1
        if self.log is not None:
            self.log('char = {}\n'.format(char))
        if char in (curses.KEY_ENTER, ord('\n'), ord('\r')):
            """ ENTER """
            if self._has_history:
                self._input_history.add_to_history(self._string)
            return 0
        elif char in (curses.KEY_EXIT, 27):
            self._edit_win.nodelay(True)
            char = self._edit_win.getch()
            self._log_file='/home/spiros/edit.log'
            self._log('   *** char = {}\n'.format(char))
            self._edit_win.nodelay(False)
            if char == -1:
                """ ESCAPE """
                self._string = ''
                self._curs_pos = 0
                return -1
            else:
                return 1
        elif char in (curses.KEY_RIGHT, curses.ascii.ACK):
            """ KEY_RIGHT, Alt-F """
            self._curs_pos += 1
            if len(self._string) < self._curs_pos:
                self._curs_pos = len(self._string)
        elif char in (curses.KEY_LEFT, ):
            """ KEY_LEFT """
            self._curs_pos -= 1
            if self._curs_pos < 0:
                self._curs_pos = 0
        elif char in (curses.KEY_HOME, curses.ascii.SOH):
            """ KEY_HOME, ^A """
            self._curs_pos = 0
        elif char in (curses.KEY_END, curses.ascii.ENQ):
            """ KEY_END, ^E """
            self._curs_pos = len(self._string)
        elif char in (curses.KEY_DC, curses.ascii.EOT):
            """ DEL key, ^D """
            if self._curs_pos < len(self._string):
                self._string = self._string[:self._curs_pos] + self._string[self._curs_pos+1:]
        elif char in (curses.KEY_BACKSPACE, curses.ascii.BS,127):
            """ KEY_BACKSPACE """
            if self._curs_pos > 0:
                self._string = self._string[:self._curs_pos-1] + self._string[self._curs_pos:]
                self._curs_pos -= 1
        elif char in (curses.KEY_UP, curses.ascii.DLE):
            """ KEY_UP, ^N """
            if self._key_up_function_handler is not None:
                try:
                    self._key_up_function_handler()
                except:
                    pass
            else:
                if self._ungetch_unbound_keys:
                    curses.ungetch(char)
        elif char in (curses.KEY_DOWN, curses.ascii.SO):
            """ KEY_DOWN, ^P """
            if self._key_down_function_handler is not None:
                try:
                    self._key_down_function_handler()
                except:
                    pass
            else:
                if self._ungetch_unbound_keys:
                    curses.ungetch(char)
        elif char in (curses.KEY_NPAGE, ):
            """ PgDn """
            if self._key_pgdown_function_handler is not None:
                try:
                    self._key_pgdown_function_handler()
                except:
                    pass
            else:
                if self._ungetch_unbound_keys:
                    curses.ungetch(char)
        elif char in (curses.KEY_PPAGE, ):
            """ PgUp """
            if self._key_pgup_function_handler is not None:
                try:
                    self._key_pgup_function_handler()
                except:
                    pass
        elif char in (9, ):
            """ TAB """
            if self._key_tab_function_handler is not None:
                try:
                    self._key_tab_function_handler()
                except:
                    pass
            else:
                if self._ungetch_unbound_keys:
                    curses.ungetch(char)
        elif char in (curses.KEY_BTAB, ):
            """ Shift-TAB """
            if self._key_stab_function_handler is not None:
                try:
                    self._key_stab_function_handler()
                except:
                    pass
            else:
                if self._ungetch_unbound_keys:
                    curses.ungetch(char)
        elif char in (curses.ascii.VT, ):
            """ Ctrl-K - delete to end of line """
            self._string = self._string[:self._curs_pos]
        elif 0<= char <=31:
            pass
        else:
            if len(self._string) + 1 == self._max_width:
                return 1
            if version_info < (3, 0):
                if 32 <= char < 127:
                    # accept only ascii characters
                    if len(self._string) == self._curs_pos:
                        self._string += chr(char)
                        self._curs_pos += 1
                    else:
                        self._string = self._string[:self._curs_pos] + chr(char) + self._string[self._curs_pos:]
            else:
                char = self._get_char(win, char)
                if len(self._string) == self._curs_pos:
                    self._string += char
                    self._curs_pos += 1
                else:
                    self._string = self._string[:self._curs_pos] + char + self._string[self._curs_pos:]

        self.refreshEditWindow()
        return 1
585339
def get(cap, *args, **kwargs):
    
    # Hack for readthedocs.org
    if 'READTHEDOCS' in os.environ:
        return ''

    if kwargs != {}:
        raise TypeError("get(): No such argument %r" % kwargs.popitem()[0])

    if _cache == {}:
        # Fix for BPython
        try:
            curses.setupterm()
        except:
            pass
    
    s = _cache.get(cap)
    if not s:
        s = curses.tigetstr(cap)
        if s == None:
            s = curses.tigetnum(cap)
            if s == -2:
                s = curses.tigetflag(cap)
                if s == -1:
                    # default to empty string so tparm doesn't fail
                    s = ''
                else:
                    s = bool(s)
        _cache[cap] = s

    # if 's' is not set 'curses.tparm' will throw an error if given arguments
    if args and s:
        r = curses.tparm(s, *args)
        return r.decode('utf-8')
    else:
        if isinstance(s, bytes):
            return s.decode('utf-8')
        else:
            return s
692068
def cmd_add(self, txt):
        
        self.show_output('Adding ', txt)
        self.raw.add(txt)
        print(self.raw)
        return 'Added ' + txt
620815
def getbug(self, objid,
               include_fields=None, exclude_fields=None, extra_fields=None):
        
        data = self._getbug(objid,
            include_fields=include_fields, exclude_fields=exclude_fields,
            extra_fields=extra_fields)
        return Bug(self, dict=data, autorefresh=self.bug_autorefresh)
840432
def cursesMain(_scr, sheetlist):
    ''

    colors.setup()

    for vs in sheetlist:
        vd().push(vs)  # first push does a reload

    status('Ctrl+H opens help')
    return vd().run(_scr)
1314939
def msg_curse(self, args=None, max_width=None):
        """"""
        # Init the return message
        ret = []

        # Build the string message
        # Header
        ret.append(self.curse_add_line(self.view_data['version'], 'TITLE'))
        ret.append(self.curse_add_line(self.view_data['psutil_version']))
        ret.append(self.curse_new_line())

        # Configuration file path
        if 'configuration_file' in self.view_data:
            ret.append(self.curse_new_line())
            ret.append(self.curse_add_line(self.view_data['configuration_file']))
            ret.append(self.curse_new_line())

        # Keys
        ret.append(self.curse_new_line())
        ret.append(self.curse_add_line(self.view_data['sort_auto']))
        ret.append(self.curse_add_line(self.view_data['sort_network']))
        ret.append(self.curse_new_line())
        ret.append(self.curse_add_line(self.view_data['sort_cpu']))
        ret.append(self.curse_add_line(self.view_data['show_hide_alert']))
        ret.append(self.curse_new_line())

        ret.append(self.curse_add_line(self.view_data['sort_mem']))
        ret.append(self.curse_add_line(self.view_data['delete_warning_alerts']))
        ret.append(self.curse_new_line())
        ret.append(self.curse_add_line(self.view_data['sort_user']))
        ret.append(self.curse_add_line(self.view_data['delete_warning_critical_alerts']))
        ret.append(self.curse_new_line())
        ret.append(self.curse_add_line(self.view_data['sort_proc']))
        ret.append(self.curse_add_line(self.view_data['percpu']))
        ret.append(self.curse_new_line())
        ret.append(self.curse_add_line(self.view_data['sort_io']))
        ret.append(self.curse_add_line(self.view_data['show_hide_ip']))
        ret.append(self.curse_new_line())
        ret.append(self.curse_add_line(self.view_data['sort_cpu_times']))
        ret.append(self.curse_add_line(self.view_data['enable_disable_docker']))
        ret.append(self.curse_new_line())
        ret.append(self.curse_add_line(self.view_data['show_hide_diskio']))
        ret.append(self.curse_add_line(self.view_data['view_network_io_combination']))
        ret.append(self.curse_new_line())
        ret.append(self.curse_add_line(self.view_data['show_hide_filesystem']))
        ret.append(self.curse_add_line(self.view_data['view_cumulative_network']))
        ret.append(self.curse_new_line())
        ret.append(self.curse_add_line(self.view_data['show_hide_network']))
        ret.append(self.curse_add_line(self.view_data['show_hide_filesytem_freespace']))
        ret.append(self.curse_new_line())
        ret.append(self.curse_add_line(self.view_data['show_hide_sensors']))
        ret.append(self.curse_add_line(self.view_data['generate_graphs']))
        ret.append(self.curse_new_line())
        ret.append(self.curse_add_line(self.view_data['show_hide_left_sidebar']))
        ret.append(self.curse_add_line(self.view_data['reset_history']))
        ret.append(self.curse_new_line())
        ret.append(self.curse_add_line(self.view_data['enable_disable_process_stats']))
        ret.append(self.curse_add_line(self.view_data['show_hide_help']))
        ret.append(self.curse_new_line())
        ret.append(self.curse_add_line(self.view_data['enable_disable_quick_look']))
        ret.append(self.curse_add_line(self.view_data['diskio_iops']))
        ret.append(self.curse_new_line())
        ret.append(self.curse_add_line(self.view_data['enable_disable_top_extends_stats']))
        ret.append(self.curse_add_line(self.view_data['show_hide_top_menu']))
        ret.append(self.curse_new_line())
        ret.append(self.curse_add_line(self.view_data['enable_disable_short_processname']))
        ret.append(self.curse_add_line(self.view_data['show_hide_irq']))
        ret.append(self.curse_new_line())
        ret.append(self.curse_add_line(self.view_data['enable_disable_gpu']))
        ret.append(self.curse_add_line(self.view_data['enable_disable_mean_gpu']))
        ret.append(self.curse_new_line())
        ret.append(self.curse_add_line(self.view_data['enable_disable_irix']))
        ret.append(self.curse_add_line(self.view_data['quit']))
        ret.append(self.curse_new_line())

        ret.append(self.curse_new_line())

        ret.append(self.curse_add_line(self.view_data['edit_pattern_filter']))

        # Return the message with decoration
        return ret
1161037
def _add_throughput(self, y, x, width, op, title, available, used):
        
        percent = float(used) / available
        self.win.addstr(y, x, "[")
        # Because we have disabled scrolling, writing the lower right corner
        # character in a terminal can throw an error (this is inside the curses
        # implementation). If that happens (and it will only ever happen here),
        # we should just catch it and continue.
        try:
            self.win.addstr(y, x + width - 1, "]")
        except curses.error:
            pass
        x += 1
        right = "%.1f/%d:%s" % (used, available, op)
        pieces = self._progress_bar(width - 2, percent, title, right)
        for color, text in pieces:
            self.win.addstr(y, x, text, curses.color_pair(color))
            x += len(text)
1316594
def addstr(self, h, w, text, attrs=0):
        
        self.update_window_size()
        if h > self.height or w > self.width:
            return
        try:
            # Python curses addstr doesn't deal with non-ascii characters
            #self.window.addstr(h, w, text.encode("ascii", "ignore"), attrs)
            self.window.addstr(h, w, text, attrs)
        except Exception as e:
            pass
310731
function patch(obj, method, optionsArgIndex) {
    var orig = obj[method];
    if (!orig) return;
    obj[method] = function () {
      var opts = arguments[optionsArgIndex];
      var file = null;
      if (opts) {
        file = typeof opts == 'string' ? opts : opts.filename;
      }
      if (file) callback(file);
      return orig.apply(this, arguments);
    };
  }
631356
def patch(self, patched_value):
        """"""
        try:
            if self.getter:
                setattr(self.getter_class, self.attr_name, patched_value)
            else:
                setattr(self.orig_object, self.attr_name, patched_value)
        except TypeError:
            # Workaround for patching builtin objects:
            proxy_name = 'fudge_proxy_%s_%s_%s' % (
                                self.orig_object.__module__,
                                self.orig_object.__name__,
                                patched_value.__class__.__name__
            )
            self.proxy_object = type(proxy_name, (self.orig_object,),
                                     {self.attr_name: patched_value})
            mod = sys.modules[self.orig_object.__module__]
            setattr(mod, self.orig_object.__name__, self.proxy_object)
910161
def fix_return_value(v, method_name, method=None, checker=None):
    
    # remove common check prefix
    method_name = (method_name or method.__func__.__name__).replace("check_","")
    if v is None or not isinstance(v, Result):
        v = Result(value=v, name=method_name)

    v.name         = v.name or method_name

    v.checker      = checker
    v.check_method = method

    return v
1177667
def _modify_new_lines(code_to_modify, offset, code_to_insert):
    
    # There's a nice overview of co_lnotab in
    # https://github.com/python/cpython/blob/3.6/Objects/lnotab_notes.txt

    new_list = list(code_to_modify.co_lnotab)
    if not new_list:
        # Could happen on a lambda (in this case, a breakpoint in the lambda should fallback to
        # tracing).
        return None

    # As all numbers are relative, what we want is to hide the code we inserted in the previous line
    # (it should be the last thing right before we increment the line so that we have a line event
    # right after the inserted code).
    bytecode_delta = len(code_to_insert)

    byte_increments = code_to_modify.co_lnotab[0::2]
    line_increments = code_to_modify.co_lnotab[1::2]

    if offset == 0:
        new_list[0] += bytecode_delta
    else:
        addr = 0
        it = zip(byte_increments, line_increments)
        for i, (byte_incr, _line_incr) in enumerate(it):
            addr += byte_incr
            if addr == offset:
                new_list[i * 2] += bytecode_delta
                break

    return bytes(new_list)
712750
function attemptFix(problem) {
        const fix = problem.fix;
        const start = fix.range[0];
        const end = fix.range[1];

        // Remain it as a problem if it's overlapped or it's a negative range
        if (lastPos >= start || start > end) {
            remainingMessages.push(problem);
            return false;
        }

        // Remove BOM.
        if ((start < 0 && end >= 0) || (start === 0 && fix.text.startsWith(BOM))) {
            output = "";
        }

        // Make output to this fix.
        output += text.slice(Math.max(0, lastPos), Math.max(0, start));
        output += fix.text;
        lastPos = end;
        return true;
    }
170263
def err(*output, **kwargs):
    
    output = 'Error: ' + ' '.join([str(o) for o in output])
    if kwargs.get('wrap') is not False:
        output = '\n'.join(wrap(output, kwargs.get('indent', '')))
    elif kwargs.get('indent'):
        indent = kwargs['indent']
        output = indent + ('\n' + indent).join(output.splitlines())
    sys.stderr.write(output + '\n')