Manage contexts and add debugging to psiTurk sessions.
963966
def scoped_session_decorator(func):
    """"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        from wallace.db import session as wallace_session
        with sessions_scope(wallace_session) as session:
            from psiturk.db import db_session as psi_session
            with sessions_scope(psi_session) as session_psiturk:
                # The sessions used in func come from the funcs globals, but
                # they will be proxied thread locals vars from the session
                # registry, and will therefore be identical to those returned
                # by the context managers above.
                logger.debug('Running worker %s in scoped DB sessions',
                             func.__name__)
                return func(*args, **kwargs)
    return wrapper
998331
def setup_app_scope(name, scope):
    """"""

    # load plugins
    plugins = []
    for plugin_name, active in get('settings').get('rw.plugins', {}).items():
        plugin = __import__(plugin_name)
        plugin_path = plugin_name.split('.')[1:] + ['plugin']
        for sub in plugin_path:
            plugin = getattr(plugin, sub)
        plugins.append(scope.activate(plugin))

    yield plugins
    raise rw.gen.Return(scope['settings'])
678022
def bump_context(self, name):
        """"""
        data = self._context(name)
        data["priority"] = self._next_priority
        self._flush_tools()
248849
def main():
    """"""

    # Squelch SSL warnings
    logging.captureWarnings(True)
    if six.PY3:
        # These ones get triggered even when capturing warnings is turned on
        warnings.simplefilter('ignore', ResourceWarning)  # pylint:disable=E0602

    # Set the terminal title
    if os.getenv('DISPLAY'):
        title = 'rtv {0}'.format(__version__)
        sys.stdout.write('\x1b]2;{0}\x07'.format(title))
        sys.stdout.flush()

    args = Config.get_args()
    fargs, bindings = Config.get_file(args.get('config'))

    # Apply the file config first, then overwrite with any command line args
    config = Config()
    config.update(**fargs)
    config.update(**args)

    # If key bindings are supplied in the config file, overwrite the defaults
    if bindings:
        config.keymap.set_bindings(bindings)

    if config['copy_config']:
        return copy_default_config()
    if config['copy_mailcap']:
        return copy_default_mailcap()
    if config['list_themes']:
        return Theme.print_themes()

    # Load the browsing history from previous sessions
    config.load_history()

    # Load any previously saved auth session token
    config.load_refresh_token()
    if config['clear_auth']:
        config.delete_refresh_token()

    if config['log']:
        # Log request headers to the file (print hack only works on python 3.x)
        # from http import client
        # _http_logger = logging.getLogger('http.client')
        # client.HTTPConnection.debuglevel = 2
        # def print_to_file(*args, **_):
        #     if args[0] != "header:":
        #         _http_logger.info(' '.join(args))
        # client.print = print_to_file
        logging.basicConfig(
            level=logging.DEBUG,
            filename=config['log'],
            format='%(asctime)s:%(levelname)s:%(filename)s:%(lineno)d:%(message)s')
    else:
        # Add an empty handler so the logger doesn't complain
        logging.root.addHandler(logging.NullHandler())

    # Make sure the locale is UTF-8 for unicode support
    default_locale = locale.setlocale(locale.LC_ALL, '')
    try:
        encoding = locale.getlocale()[1] or locale.getdefaultlocale()[1]
    except ValueError:
        # http://stackoverflow.com/a/19961403
        # OS X on some terminals will set the LC_CTYPE to "UTF-8"
        # (as opposed to something like "en_US.UTF-8") and python
        # doesn't know how to handle it.
        _logger.warning('Error parsing system locale: `%s`,'
                        ' falling back to utf-8', default_locale)
        encoding = 'UTF-8'

    if not encoding or encoding.lower() != 'utf-8':
        text = ('System encoding was detected as (%s) instead of UTF-8'
                ', falling back to ascii only mode' % encoding)
        warnings.warn(text)
        config['ascii'] = True

    if packages.__praw_bundled__:
        praw_info = 'packaged, commit {}'.format(packages.__praw_hash__[:12])
    else:
        praw_info = 'system installed v{}'.format(praw.__version__)

    # Update the webbrowser module's default behavior
    patch_webbrowser()
    if webbrowser_import_warning:
        _logger.warning('webbrowser module was unexpectedly imported before'
                        '$BROWSER could be overwritten')

    # Construct the reddit user agent
    user_agent = docs.AGENT.format(version=__version__)

    debug_info = [
        'rtv version: rtv {}'.format(__version__),
        'rtv module path: {}'.format(os.path.abspath(__file__)),
        'python version: {}'.format(sys.version.replace('\n', ' ')),
        'python executable: {}'.format(sys.executable),
        'praw version: {}'.format(praw_info),
        'locale, encoding: {}, {}'.format(default_locale, encoding),
        'Environment Variables']
    for name, value in [
        ('BROWSER', BROWSER),
        ('DISPLAY', os.getenv('DISPLAY')),
        ('EDITOR', os.getenv('EDITOR')),
        ('LANG', os.getenv('LANG')),
        ('PAGER', os.getenv('PAGER')),
        ('RTV_BROWSER', RTV_BROWSER),
        ('RTV_EDITOR', os.getenv('RTV_EDITOR')),
        ('RTV_PAGER', os.getenv('RTV_PAGER')),
        ('RTV_URLVIEWER', os.getenv('RTV_URLVIEWER')),
        ('TERM', os.getenv('TERM')),
        ('VISUAL', os.getenv('VISUAL')),
        ('XDG_CONFIG_HOME', os.getenv('XDG_CONFIG_HOME')),
        ('XDG_DATA_HOME', os.getenv('XDG_DATA_HOME')),
    ]:
        debug_info.append('  {:<16}: {}'.format(name, value or ''))
    debug_info.append('')
    debug_text = '\n'.join(debug_info)

    _logger.info(debug_text)
    if config['debug_info']:
        print(debug_text)
        return

    try:
        with curses_session() as stdscr:

            term = Terminal(stdscr, config)

            if config['monochrome'] or config['theme'] == 'monochrome':
                _logger.info('Using monochrome theme')
                theme = Theme(use_color=False)
            elif config['theme'] and config['theme'] != 'default':
                _logger.info('Loading theme: %s', config['theme'])
                theme = Theme.from_name(config['theme'])
            else:
                # Set to None to let the terminal figure out which theme
                # to use depending on if colors are supported or not
                theme = None
            term.set_theme(theme)

            with term.loader('Initializing', catch_exception=False):
                reddit = praw.Reddit(user_agent=user_agent,
                                     decode_html_entities=False,
                                     disable_update_check=True,
                                     timeout=10,  # 10 second request timeout
                                     handler=RequestHeaderRateLimiter())

            # Dial the request cache up from 30 seconds to 5 minutes
            # I'm trying this out to make navigation back and forth
            # between pages quicker, it may still need to be fine tuned.
            reddit.config.api_request_delay = 300

            # Authorize on launch if the refresh token is present
            oauth = OAuthHelper(reddit, term, config)
            if config['autologin'] and config.refresh_token:
                oauth.authorize(autologin=True)

            # Open the supplied submission link before opening the subreddit
            if config['link']:
                # Expand shortened urls like https://redd.it/
                # Praw won't accept the shortened versions, add the reddit
                # headers to avoid a 429 response from reddit.com
                url = requests.head(
                    config['link'],
                    headers=reddit.http.headers,
                    allow_redirects=True
                ).url

                page = None
                with term.loader('Loading submission'):
                    try:
                        page = SubmissionPage(reddit, term, config, oauth, url)
                    except Exception as e:
                        _logger.exception(e)
                        raise SubmissionError('Unable to load {0}'.format(url))
                while page:
                    page = page.loop()

            page = None
            name = config['subreddit']
            with term.loader('Loading subreddit'):
                try:
                    page = SubredditPage(reddit, term, config, oauth, name)
                except Exception as e:
                    # If we can't load the subreddit that was requested, try
                    # to load the "popular" page instead so at least the
                    # application still launches. This used to use the user's
                    # front page, but some users have an empty front page.
                    _logger.exception(e)
                    page = SubredditPage(reddit, term, config, oauth, 'popular')
                    raise SubredditError('Unable to load {0}'.format(name))

            # Launch the subreddit page
            while page:
                page = page.loop()

    except ConfigError as e:
        _logger.exception(e)
        print(e)
    except Exception as e:
        _logger.exception(e)
        import traceback
        exit_message = '\n'.join([
            debug_text,
            traceback.format_exc(),
            'rtv has crashed. Please report this traceback at:',
            'https://github.com/michael-lazar/rtv/issues\n'])
        sys.stderr.write(exit_message)
        return 1  # General error exception code
    except KeyboardInterrupt:
        pass
    finally:
        # Try to save the browsing history
        config.save_history()
        # Ensure sockets are closed to prevent a ResourceWarning
        if 'reddit' in locals():
            reddit.handler.http.close()
67359
def register_plugin(self):
        """"""
        self.breakpoints.edit_goto.connect(self.main.editor.load)
        #self.redirect_stdio.connect(self.main.redirect_internalshell_stdio)
        self.breakpoints.clear_all_breakpoints.connect(
                                        self.main.editor.clear_all_breakpoints)
        self.breakpoints.clear_breakpoint.connect(
            self.main.editor.clear_breakpoint)
        self.main.editor.breakpoints_saved.connect(self.breakpoints.set_data)
        self.breakpoints.set_or_edit_conditional_breakpoint.connect(
                           self.main.editor.set_or_edit_conditional_breakpoint)
        
        self.main.add_dockwidget(self)
        
        list_action = create_action(self, _("List breakpoints"),
                                   triggered=self.show)
        list_action.setEnabled(True)
        pos = self.main.debug_menu_actions.index('list_breakpoints')
        self.main.debug_menu_actions.insert(pos, list_action)
        self.main.editor.pythonfile_dependent_actions += [list_action]
454732
def set_context(context):
    """"""
    try:
        handler = logging.getLogger().handlers[0]
    except IndexError:
        # logging is not initialized
        return
    if not isinstance(handler, StructuredHandler):
        return
    handler.acquire()
    try:
        handler.local.context = context
    finally:
        handler.release()
268015
def before_all(context):
    
    lf = LoggerFactory(config_file='../features/resources/test_config.yaml')
    lf.initialize()
    ll = lf.get_instance('environment')
    ll.info('Logger initialized: {}'.format(lf.config))
    ll.info('Initial test context: {}'.format(context))
1000299
def create_api_context(self, cls):
        """"""
        return self.api_context_schema().load({
            "name": cls.name,
            "cls": cls,
            "inst": [],
            "conf": self.conf.get_api_service(cls.name),
            "calls": self.conf.get_api_calls(),
            "shared": {},  # Used per-API to monitor state
            "log_level": self.conf.get_log_level(),
            "callback": self.receive
            })
313593
def debug(self):  # pragma: no cover
        """"""

        print("Aliases:")
        pprint.pprint(self._aliases)
        print("Override:")
        pprint.pprint(self._override)
        print("Args:")
        pprint.pprint(self._args)
        print("Env:")
        pprint.pprint(self._env)
        print("Config:")
        pprint.pprint(self._config)
        print("Key/Value Store:")
        pprint.pprint(self._kvstore)
        print("Defaults:")
        pprint.pprint(self._defaults)
1070526
def set_context(self, context):
        """"""
        self._set_context(context, emit=False)
        self._modified = (not context.load_path)
        self.dataChanged.emit(self.CONTEXT_CHANGED |
                              self.REQUEST_CHANGED |
                              self.PACKAGES_PATH_CHANGED |
                              self.LOCKS_CHANGED |
                              self.LOADPATH_CHANGED |
                              self.PACKAGE_FILTER_CHANGED |
                              self.CACHING_CHANGED)
310044
def log_context(trace_level, stream):
    '''
    
    '''
    original_trace_level = DebugInfoHolder.DEBUG_TRACE_LEVEL
    original_stream = DebugInfoHolder.DEBUG_STREAM

    DebugInfoHolder.DEBUG_TRACE_LEVEL = trace_level
    DebugInfoHolder.DEBUG_STREAM = stream
    try:
        yield
    finally:
        DebugInfoHolder.DEBUG_TRACE_LEVEL = original_trace_level
        DebugInfoHolder.DEBUG_STREAM = original_stream
1033830
def dispatch(self):
    """"""
    try:
      webapp2.RequestHandler.dispatch(self)
    finally:
      self.session_store.save_sessions(self.response)
173433
def set_debug(self, status):
        """"""
        if status:
            self.logger.setLevel('DEBUG')
        else:
            self.logger.setLevel('INFO')
23217
def init_debug(self):
        """"""
        import signal

        def debug_trace(sig, frame):
            """Interrupt running process, and provide a python prompt for interactive
            debugging."""

            self.log('Trace signal received')
            self.log(''.join(traceback.format_stack(frame)))

        signal.signal(signal.SIGUSR2, debug_trace)
237046
def activate_debug():
    
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    logger.addHandler(ch)
    logger.setLevel(logging.DEBUG)
386917
def add_variables_to_context(generator):
    ''''''
    context = generator.context             # minimize attr lookup
    context['relpath_to_site'] = relpath_to_site
    context['main_siteurl'] = _MAIN_SITEURL
    context['main_lang'] = _MAIN_LANG
    context['lang_siteurls'] = _SITE_DB
    current_lang = generator.settings['DEFAULT_LANG']
    extra_siteurls = _SITE_DB.copy()
    extra_siteurls.pop(current_lang)
    context['extra_siteurls'] = extra_siteurls
220483
def load(self, context):
    
    if not (context.flags.debugger_data_server_grpc_port > 0 or
            context.flags.debugger_port > 0):
      return None
    flags = context.flags
    try:
      # pylint: disable=g-import-not-at-top,unused-import
      import tensorflow
    except ImportError:
      raise ImportError(
          'To use the debugger plugin, you need to have TensorFlow installed:\n'
          '  pip install tensorflow')
    try:
      # pylint: disable=line-too-long,g-import-not-at-top
      from tensorboard.plugins.debugger import debugger_plugin as debugger_plugin_lib
      from tensorboard.plugins.debugger import interactive_debugger_plugin as interactive_debugger_plugin_lib
      # pylint: enable=line-too-long,g-import-not-at-top
    except ImportError as e:
      e_type, e_value, e_traceback = sys.exc_info()
      message = e.msg if hasattr(e, 'msg') else e.message  # Handle py2 vs py3
      if 'grpc' in message:
        e_value = ImportError(
            message +
            '\n\nTo use the debugger plugin, you need to have '
            'gRPC installed:\n  pip install grpcio')
      six.reraise(e_type, e_value, e_traceback)
    if flags.debugger_port > 0:
      interactive_plugin = (
          interactive_debugger_plugin_lib.InteractiveDebuggerPlugin(context))
      logger.info('Starting Interactive Debugger Plugin at gRPC port %d',
                   flags.debugger_data_server_grpc_port)
      interactive_plugin.listen(flags.debugger_port)
      return interactive_plugin
    elif flags.debugger_data_server_grpc_port > 0:
      noninteractive_plugin = debugger_plugin_lib.DebuggerPlugin(context)
      logger.info('Starting Non-interactive Debugger Plugin at gRPC port %d',
                   flags.debugger_data_server_grpc_port)
      noninteractive_plugin.listen(flags.debugger_data_server_grpc_port)
      return noninteractive_plugin
    raise AssertionError()