<commit_before>import logging
import os
import datetime as dt
from pyoperant import utils, components, local, hwio


try: import simplejson as json
except ImportError: import json

class BaseExp(object):
    """Base class for an experiment.

    Keyword arguments:
    name -- name of this experiment
    desc -- long description of this experiment
    debug -- (bool) flag for debugging (default=False)
    light_schedule  -- the light schedule for the experiment. either 'sun' or
        a tuple of (starttime,endtime) tuples in (hhmm,hhmm) form defining
        time intervals for the lights to be on
    experiment_path -- path to the experiment
    stim_path -- path to stimuli (default = <experiment_path>/stims)
    subject -- identifier of the subject
    panel -- instance of local Panel() object

    Methods:
    run() -- runs the experiment

    """
    def __init__(self,
                 name='',
                 description='',
                 debug=False,
                 filetime_fmt='%Y%m%d%H%M%S',
                 light_schedule='sun',
                 idle_poll_interval = 60.0,
                 experiment_path='',
                 stim_path='',
                 subject='',
                 panel=None,
                 *args, **kwargs):
        super(BaseExp,  self).__init__()

        self.name = name
        self.description = description
        self.debug = debug
        self.timestamp = dt.datetime.now().strftime(filetime_fmt)
        self.parameters = kwargs
        self.parameters['filetime_fmt'] = filetime_fmt
        self.parameters['light_schedule'] = light_schedule
        self.parameters['idle_poll_interval'] = idle_poll_interval

        self.parameters['experiment_path'] = experiment_path
        if stim_path == '':
            self.parameters['stim_path'] = os.path.join(experiment_path,'stims')
        else:
            self.parameters['stim_path'] = stim_path
        self.parameters['subject'] = subject

        # configure logging
        self.log_file = os.path.join(self.parameters['experiment_path'], self.parameters['subject'] + '.log')
        self.log_config()

        self.req_panel_attr= ['house_light',
                              'reset',
                              ]
        self.panel = panel
        self.log.debug('panel %s initialized' % self.parameters['panel_name'])

    def save(self):
        self.snapshot_f = os.path.join(self.parameters['experiment_path'], self.timestamp+'.json')
        with open(self.snapshot_f, 'wb') as config_snap:
            json.dump(self.parameters, config_snap, sort_keys=True, indent=4)

    def log_config(self):
        if self.debug:
            self.log_level = logging.DEBUG
        else:
            self.log_level = logging.INFO

        logging.basicConfig(filename=self.log_file,
                            level=self.log_level,
                            format='"%(asctime)s","%(levelname)s","%(message)s"')
        self.log = logging.getLogger()
        #email_handler = logging.handlers.SMTPHandler(mailhost='localhost',
        #                                             fromaddr='<EMAIL>',
        #                                             toaddrs=[options['experimenter']['email'],],
        #                                             subject='error notice',
        #                                             )
        #email_handler.setlevel(logging.ERROR)
        #log.addHandler(email_handler)

    def check_light_schedule(self):
        return utils.check_time(self.parameters['light_schedule'])

    def check_session_schedule(self):
        return False


    def run(self):<commit_msg>send uncaught exceptions to log file<commit_after>import logging
import os, sys
import datetime as dt
from pyoperant import utils, components, local, hwio


try: import simplejson as json
except ImportError: import json

def _log_except_hook(*exc_info):
    text = "".join(traceback.format_exception(*exc_info))
    logging.error("Unhandled exception: %s", text)


class BaseExp(object):
    """Base class for an experiment.

    Keyword arguments:
    name -- name of this experiment
    desc -- long description of this experiment
    debug -- (bool) flag for debugging (default=False)
    light_schedule  -- the light schedule for the experiment. either 'sun' or
        a tuple of (starttime,endtime) tuples in (hhmm,hhmm) form defining
        time intervals for the lights to be on
    experiment_path -- path to the experiment
    stim_path -- path to stimuli (default = <experiment_path>/stims)
    subject -- identifier of the subject
    panel -- instance of local Panel() object

    Methods:
    run() -- runs the experiment

    """
    def __init__(self,
                 name='',
                 description='',
                 debug=False,
                 filetime_fmt='%Y%m%d%H%M%S',
                 light_schedule='sun',
                 idle_poll_interval = 60.0,
                 experiment_path='',
                 stim_path='',
                 subject='',
                 panel=None,
                 *args, **kwargs):
        super(BaseExp,  self).__init__()

        self.name = name
        self.description = description
        self.debug = debug
        self.timestamp = dt.datetime.now().strftime(filetime_fmt)
        self.parameters = kwargs
        self.parameters['filetime_fmt'] = filetime_fmt
        self.parameters['light_schedule'] = light_schedule
        self.parameters['idle_poll_interval'] = idle_poll_interval

        self.parameters['experiment_path'] = experiment_path
        if stim_path == '':
            self.parameters['stim_path'] = os.path.join(experiment_path,'stims')
        else:
            self.parameters['stim_path'] = stim_path
        self.parameters['subject'] = subject

        # configure logging
        self.log_file = os.path.join(self.parameters['experiment_path'], self.parameters['subject'] + '.log')
        self.log_config()

        self.req_panel_attr= ['house_light',
                              'reset',
                              ]
        self.panel = panel
        self.log.debug('panel %s initialized' % self.parameters['panel_name'])

    def save(self):
        self.snapshot_f = os.path.join(self.parameters['experiment_path'], self.timestamp+'.json')
        with open(self.snapshot_f, 'wb') as config_snap:
            json.dump(self.parameters, config_snap, sort_keys=True, indent=4)

    def log_config(self):
        if self.debug:
            self.log_level = logging.DEBUG
        else:
            self.log_level = logging.INFO

        sys.excepthook = _log_except_hook # send uncaught exceptions to log file
        
        logging.basicConfig(filename=self.log_file,
                            level=self.log_level,
                            format='"%(asctime)s","%(levelname)s","%(message)s"')
        self.log = logging.getLogger()
        #email_handler = logging.handlers.SMTPHandler(mailhost='localhost',
        #                                             fromaddr='<EMAIL>',
        #                                             toaddrs=[options['experimenter']['email'],],
        #                                             subject='error notice',
        #                                             )
        #email_handler.setlevel(logging.ERROR)
        #log.addHandler(email_handler)

    def check_light_schedule(self):
        return utils.check_time(self.parameters['light_schedule'])

    def check_session_schedule(self):
        return False


    def run(self):
{'fraction_non_alphanumeric': 0.1052492046659597, 'fraction_numerical': 0.0010604453870625664, 'mean_word_length': 1.9484173505275497, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 16, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1427241', 'n_tokens_mistral': 1980, 'n_tokens_neox': 1948, 'n_words': 441}