gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _readFromUrl(cls, url, writable):
    srcBucket, srcKey = cls._extractKeyInfoFromUrl(url)
    srcKey.get_contents_to_file(writable)


# Traceback (boto.exception.S3ResponseError)
2016-04-26 14:13:37,623 ERROR:root: Got exception 'S3ResponseError: 400 Bad Request
<Error><Code>InvalidRequest</Code><Message>The specified copy source is larger than the maximum allowable size for a copy source: 5368709120</Message><RequestId>CCB50A66B881B563</RequestId><HostId>1dAVKee/hXEaLCvisKyxUHlWtLbZwqcedEXOsKVSzAoE5ISrsuykzg9teW9vzidQaIqImJxbNgI=</HostId></Error>' while writing 's3://1000genomes/phase3/data/HG01977/sequence_read/SRR360135_1.filt.fastq.gz'
Traceback (most recent call last):
File "/usr/local/bin/cwltoil", line 9, in <module>
load_entry_point('toil==3.2.0a2', 'console_scripts', 'cwltoil')()
File "/usr/local/lib/python2.7/dist-packages/toil/cwl/cwltoil.py", line 580, in main
adjustFiles(builder.job, functools.partial(writeFile, toil.importFile, {}))
File "/usr/local/lib/python2.7/dist-packages/cwltool/process.py", line 128, in adjustFiles
adjustFiles(rec[d], op)
File "/usr/local/lib/python2.7/dist-packages/cwltool/process.py", line 131, in adjustFiles
adjustFiles(d, op)
File "/usr/local/lib/python2.7/dist-packages/cwltool/process.py", line 131, in adjustFiles
adjustFiles(d, op)
File "/usr/local/lib/python2.7/dist-packages/cwltool/process.py", line 126, in adjustFiles
rec["path"] = op(rec["path"])
File "/usr/local/lib/python2.7/dist-packages/toil/cwl/cwltoil.py", line 162, in writeFile
index[x] = (writeFunc(rp), os.path.basename(x))
File "/usr/local/lib/python2.7/dist-packages/toil/common.py", line 570, in importFile
return self.jobStore.importFile(srcUrl)
File "/usr/local/lib/python2.7/dist-packages/toil/jobStores/abstractJobStore.py", line 260, in importFile
return self._importFile(findJobStoreForUrl(url), url)
File "/usr/local/lib/python2.7/dist-packages/toil/jobStores/aws/jobStore.py", line 279, in _importFile
info.copyFrom(srcKey)
File "/usr/local/lib/python2.7/dist-packages/toil/jobStores/aws/jobStore.py", line 826, in copyFrom
headers=self._s3EncryptionHeaders()).version_id
File "/usr/local/lib/python2.7/dist-packages/toil/jobStores/aws/jobStore.py", line 865, in _copyKey
headers=headers)
File "/usr/local/lib/python2.7/dist-packages/boto/s3/bucket.py", line 888, in copy_key
response.reason, body)
boto.exception.S3ResponseError: S3ResponseError: 400 Bad Request
<Error><Code>InvalidRequest</Code><Message>The specified copy source is larger than the maximum allowable size for a copy source: 5368709120</Message><RequestId>CCB50A66B881B563</RequestId><HostId>1dAVKee/hXEaLCvisKyxUHlWtLbZwqcedEXOsKVSzAoE5ISrsuykzg9teW9vzidQaIqImJxbNgI=</HostId></Error>

# Fixed code
def _readFromUrl(cls, url, writable):
    srcBucket, srcKey = cls._extractKeyInfoFromUrl(url, existing=True)
    srcKey.get_contents_to_file(writable)
# Buggy code
def runTask():
    log.debug("Running task %s", task.task_id.value)
    sendUpdate(mesos_pb2.TASK_RUNNING)
    # This is where task.data is first invoked. Using this position to setup cleanupInfo
    taskData = pickle.loads(task.data)
    if self.workerCleanupInfo is not None:
        assert self.workerCleanupInfo == taskData.workerCleanupInfo
    else:
        self.workerCleanupInfo = taskData.workerCleanupInfo
    popen = runJob(taskData)
    self.runningTasks[task.task_id.value] = popen.pid
    try:
        exitStatus = popen.wait()
        if 0 == exitStatus:
            sendUpdate(mesos_pb2.TASK_FINISHED)
        elif -9 == exitStatus:
            sendUpdate(mesos_pb2.TASK_KILLED)
        else:
            sendUpdate(mesos_pb2.TASK_FAILED, message=str(exitStatus))
    except:
        exc_type, exc_value, exc_trace = sys.exc_info()
        sendUpdate(
            mesos_pb2.TASK_FAILED,
            message=str(traceback.format_exception_only(exc_type, exc_value)),
        )
    finally:
        del self.runningTasks[task.task_id.value]


# Traceback (ValueError)
Failed to call scheduler's statusUpdate
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/toil/batchSystems/mesos/batchSystem.py", line 458, in statusUpdate
exitStatus = int(update.message)
ValueError: invalid literal for int() with base 10: ''

# Fixed code
def runTask():
    log.debug("Running task %s", task.task_id.value)
    sendUpdate(mesos_pb2.TASK_RUNNING)
    # This is where task.data is first invoked. Using this position to setup cleanupInfo
    taskData = pickle.loads(task.data)
    if self.workerCleanupInfo is not None:
        assert self.workerCleanupInfo == taskData.workerCleanupInfo
    else:
        self.workerCleanupInfo = taskData.workerCleanupInfo
    try:
        popen = runJob(taskData)
        self.runningTasks[task.task_id.value] = popen.pid
        try:
            exitStatus = popen.wait()
            if 0 == exitStatus:
                sendUpdate(mesos_pb2.TASK_FINISHED)
            elif -9 == exitStatus:
                sendUpdate(mesos_pb2.TASK_KILLED)
            else:
                sendUpdate(mesos_pb2.TASK_FAILED, message=str(exitStatus))
        finally:
            del self.runningTasks[task.task_id.value]
    except:
        exc_info = sys.exc_info()
        log.error("Exception while running task:", exc_info=exc_info)
        exc_type, exc_value, exc_trace = exc_info
        sendUpdate(
            mesos_pb2.TASK_FAILED,
            message="".join(traceback.format_exception_only(exc_type, exc_value)),
        )
# Buggy code
def runTask():
    log.debug("Running task %s", task.task_id.value)
    sendUpdate(mesos_pb2.TASK_RUNNING)
    popen = runJob(pickle.loads(task.data))
    self.runningTasks[task.task_id.value] = popen.pid
    try:
        exitStatus = popen.wait()
        if 0 == exitStatus:
            sendUpdate(mesos_pb2.TASK_FINISHED)
        elif -9 == exitStatus:
            sendUpdate(mesos_pb2.TASK_KILLED)
        else:
            sendUpdate(mesos_pb2.TASK_FAILED, message=str(exitStatus))
    except:
        exc_type, exc_value, exc_trace = sys.exc_info()
        sendUpdate(
            mesos_pb2.TASK_FAILED,
            message=str(traceback.format_exception_only(exc_type, exc_value)),
        )
    finally:
        del self.runningTasks[task.task_id.value]


# Traceback (ValueError)
Failed to call scheduler's statusUpdate
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/toil/batchSystems/mesos/batchSystem.py", line 458, in statusUpdate
exitStatus = int(update.message)
ValueError: invalid literal for int() with base 10: ''

# Fixed code
def runTask():
    log.debug("Running task %s", task.task_id.value)
    sendUpdate(mesos_pb2.TASK_RUNNING)
    try:
        popen = runJob(pickle.loads(task.data))
        self.runningTasks[task.task_id.value] = popen.pid
        try:
            exitStatus = popen.wait()
            if 0 == exitStatus:
                sendUpdate(mesos_pb2.TASK_FINISHED)
            elif -9 == exitStatus:
                sendUpdate(mesos_pb2.TASK_KILLED)
            else:
                sendUpdate(mesos_pb2.TASK_FAILED, message=str(exitStatus))
        finally:
            del self.runningTasks[task.task_id.value]
    except:
        exc_info = sys.exc_info()
        log.error("Exception while running task:", exc_info=exc_info)
        exc_type, exc_value, exc_trace = exc_info
        sendUpdate(
            mesos_pb2.TASK_FAILED,
            message="".join(traceback.format_exception_only(exc_type, exc_value)),
        )
# Buggy code
def __updateState(self, intID, exitStatus):
    self.updatedJobsQueue.put((intID, exitStatus))
    del self.runningJobMap[intID]


# Traceback (ValueError)
Failed to call scheduler's statusUpdate
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/toil/batchSystems/mesos/batchSystem.py", line 458, in statusUpdate
exitStatus = int(update.message)
ValueError: invalid literal for int() with base 10: ''

# Fixed code
def __updateState(self, intID, exitStatus):
    self.updatedJobsQueue.put((intID, exitStatus))
    try:
        del self.runningJobMap[intID]
    except KeyError:
        log.warning(
            "Cannot find %i among running jobs. "
            "Sent update about its exit code of %i anyways.",
            intID,
            exitStatus,
        )
# Buggy code
def _startParasol(self, numCores=None, memory=None):
    if numCores is None:
        numCores = multiprocessing.cpu_count()
    if memory is None:
        memory = self._physicalMemory()
    self.numCores = numCores
    self.memory = memory
    self.leader = self.ParasolLeaderThread()
    self.leader.start()
    self.worker = self.ParasolWorkerThread()
    self.worker.start()
    while self.leader.popen is None or self.worker.popen is None:
        log.info("Waiting for leader and worker processes")
        time.sleep(0.1)


# Traceback (ValueError)
Traceback (most recent call last):
File "wdltoil.py", line 1, in <module>
from toil.job import Job
File "/Users/sfrazer/projects/toil/src/toil/job.py", line 36, in <module>
from toil.common import loadJobStore
File "/Users/sfrazer/projects/toil/src/toil/common.py", line 27, in <module>
from toil.batchSystems.singleMachine import SingleMachineBatchSystem
File "/Users/sfrazer/projects/toil/src/toil/batchSystems/singleMachine.py", line 31, in <module>
class SingleMachineBatchSystem(AbstractBatchSystem):
File "/Users/sfrazer/projects/toil/src/toil/batchSystems/singleMachine.py", line 47, in SingleMachineBatchSystem
physicalMemory = os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES')
ValueError: unrecognized configuration name

# Fixed code
def _startParasol(self, numCores=None, memory=None):
    if numCores is None:
        numCores = multiprocessing.cpu_count()
    if memory is None:
        memory = physicalMemory()
    self.numCores = numCores
    self.memory = memory
    self.leader = self.ParasolLeaderThread()
    self.leader.start()
    self.worker = self.ParasolWorkerThread()
    self.worker.start()
    while self.leader.popen is None or self.worker.popen is None:
        log.info("Waiting for leader and worker processes")
        time.sleep(0.1)
# Buggy code
def logToMaster(self, string, level=logging.INFO):
    """
            Send a logging message to the leader. The message will also be \
            logged by the worker at the same level.
            
            :param string: The string to log.
            :param int level: The logging level.
            """
    logger.log(level=level, msg=("LOG-TO-MASTER: " + string))
    self.loggingMessages.append((str(string), level))


# Traceback (UnicodeDecodeError)
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/toil/worker.py", line 408, in <module>
main()
File "/usr/local/lib/python2.7/dist-packages/toil/worker.py", line 392, in main
jobStore.writeStatsAndLogging(ET.tostring(elementNode))
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 1126, in tostring
ElementTree(element).write(file, encoding, method=method)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 820, in write
serialize(write, self._root, encoding, qnames, namespaces)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 939, in _serialize_xml
_serialize_xml(write, e, encoding, qnames, None)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 939, in _serialize_xml
_serialize_xml(write, e, encoding, qnames, None)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 937, in _serialize_xml
write(_escape_cdata(text, encoding))
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 1073, in _escape_cdata
return text.encode(encoding, "xmlcharrefreplace")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 48: ordinal not in range(128)

# Fixed code
def logToMaster(self, text, level=logging.INFO):
    """
            Send a logging message to the leader. The message will also be \
            logged by the worker at the same level.
            
            :param string: The string to log.
            :param int level: The logging level.
            """
    logger.log(level=level, msg=("LOG-TO-MASTER: " + text))
    self.loggingMessages.append(dict(text=text, level=level))
# Buggy code
def readStatsAndLogging(self, statsAndLoggingCallBackFn):
    """
    Reads stats/logging strings accumulated by "writeStatsAndLogging" function.
    For each stats/logging file calls the statsAndLoggingCallBackFn with
    an open, readable file-handle that can be used to parse the stats.
    Returns the number of stat/logging strings processed.
    Stats/logging files are only read once and are removed from the
    file store after being written to the given file handle.
    """
    raise NotImplementedError()


# Traceback (UnicodeDecodeError)
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/toil/worker.py", line 408, in <module>
main()
File "/usr/local/lib/python2.7/dist-packages/toil/worker.py", line 392, in main
jobStore.writeStatsAndLogging(ET.tostring(elementNode))
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 1126, in tostring
ElementTree(element).write(file, encoding, method=method)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 820, in write
serialize(write, self._root, encoding, qnames, namespaces)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 939, in _serialize_xml
_serialize_xml(write, e, encoding, qnames, None)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 939, in _serialize_xml
_serialize_xml(write, e, encoding, qnames, None)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 937, in _serialize_xml
write(_escape_cdata(text, encoding))
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 1073, in _escape_cdata
return text.encode(encoding, "xmlcharrefreplace")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 48: ordinal not in range(128)

# Fixed code
def readStatsAndLogging(self, callback, readAll=False):
    """
    Reads stats/logging strings accumulated by the writeStatsAndLogging() method. For each
    stats/logging string this method calls the given callback function with an open,
    readable file handle from which the stats string can be read. Returns the number of
    stats/logging strings processed. Each stats/logging string is only processed once unless
    the readAll parameter is set, in which case the given callback will be invoked for all
    existing stats/logging strings, including the ones from a previous invocation of this
    method.

    :type callback: callable
    :type readAll: bool
    """
    raise NotImplementedError()
# Buggy code
def readStatsAndLogging(self, statsCallBackFn):
    itemsProcessed = 0
    items = None
    for attempt in retry_sdb():
        with attempt:
            items = list(
                self.filesDomain.select(
                    consistent_read=True,
                    query="select * from `%s` where ownerID='%s'"
                    % (self.filesDomain.name, str(self.statsFileOwnerID)),
                )
            )
    assert items is not None
    for item in items:
        info = self.FileInfo.fromItem(item)
        with info.downloadStream() as readable:
            statsCallBackFn(readable)
        self.deleteFile(item.name)
        itemsProcessed += 1
    return itemsProcessed


# Traceback (UnicodeDecodeError)
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/toil/worker.py", line 408, in <module>
main()
File "/usr/local/lib/python2.7/dist-packages/toil/worker.py", line 392, in main
jobStore.writeStatsAndLogging(ET.tostring(elementNode))
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 1126, in tostring
ElementTree(element).write(file, encoding, method=method)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 820, in write
serialize(write, self._root, encoding, qnames, namespaces)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 939, in _serialize_xml
_serialize_xml(write, e, encoding, qnames, None)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 939, in _serialize_xml
_serialize_xml(write, e, encoding, qnames, None)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 937, in _serialize_xml
write(_escape_cdata(text, encoding))
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 1073, in _escape_cdata
return text.encode(encoding, "xmlcharrefreplace")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 48: ordinal not in range(128)

# Fixed code
def readStatsAndLogging(self, callback, readAll=False):
    itemsProcessed = 0

    for info in self._readStatsAndLogging(callback, self.statsFileOwnerID):
        info._ownerID = self.readStatsFileOwnerID
        info.save()
        itemsProcessed += 1

    if readAll:
        for _ in self._readStatsAndLogging(callback, self.readStatsFileOwnerID):
            itemsProcessed += 1

    return itemsProcessed
# Buggy code
def readStatsAndLogging(self, statsAndLoggingCallbackFn):
    numStatsFiles = 0
    for entity in self.statsFileIDs.query_entities():
        jobStoreFileID = entity.RowKey
        with self._downloadStream(jobStoreFileID, self.statsFiles) as fd:
            statsAndLoggingCallbackFn(fd)
        self.statsFiles.delete_blob(blob_name=jobStoreFileID)
        self.statsFileIDs.delete_entity(row_key=jobStoreFileID)
        numStatsFiles += 1
    return numStatsFiles


# Traceback (UnicodeDecodeError)
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/toil/worker.py", line 408, in <module>
main()
File "/usr/local/lib/python2.7/dist-packages/toil/worker.py", line 392, in main
jobStore.writeStatsAndLogging(ET.tostring(elementNode))
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 1126, in tostring
ElementTree(element).write(file, encoding, method=method)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 820, in write
serialize(write, self._root, encoding, qnames, namespaces)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 939, in _serialize_xml
_serialize_xml(write, e, encoding, qnames, None)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 939, in _serialize_xml
_serialize_xml(write, e, encoding, qnames, None)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 937, in _serialize_xml
write(_escape_cdata(text, encoding))
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 1073, in _escape_cdata
return text.encode(encoding, "xmlcharrefreplace")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 48: ordinal not in range(128)

# Fixed code
def readStatsAndLogging(self, callback, readAll=False):
    suffix = "_old"
    numStatsFiles = 0
    for entity in self.statsFileIDs.query_entities():
        jobStoreFileID = entity.RowKey
        hasBeenRead = len(jobStoreFileID) > self.jobIDLength
        if not hasBeenRead:
            with self._downloadStream(jobStoreFileID, self.statsFiles) as fd:
                callback(fd)
            # Mark this entity as read by appending the suffix
            self.statsFileIDs.insert_entity(entity={"RowKey": jobStoreFileID + suffix})
            self.statsFileIDs.delete_entity(row_key=jobStoreFileID)
            numStatsFiles += 1
        elif readAll:
            # Strip the suffix to get the original ID
            jobStoreFileID = jobStoreFileID[: -len(suffix)]
            with self._downloadStream(jobStoreFileID, self.statsFiles) as fd:
                callback(fd)
            numStatsFiles += 1
    return numStatsFiles
# Buggy code
def readStatsAndLogging(self, statsAndLoggingCallBackFn):
    numberOfFilesProcessed = 0
    for tempDir in self._tempDirectories():
        for tempFile in os.listdir(tempDir):
            if tempFile.startswith("stats"):
                absTempFile = os.path.join(tempDir, tempFile)
                if not tempFile.endswith(".new"):
                    with open(absTempFile, "r") as fH:
                        statsAndLoggingCallBackFn(fH)
                    numberOfFilesProcessed += 1
                    os.remove(absTempFile)
    return numberOfFilesProcessed


# Traceback (UnicodeDecodeError)
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/toil/worker.py", line 408, in <module>
main()
File "/usr/local/lib/python2.7/dist-packages/toil/worker.py", line 392, in main
jobStore.writeStatsAndLogging(ET.tostring(elementNode))
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 1126, in tostring
ElementTree(element).write(file, encoding, method=method)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 820, in write
serialize(write, self._root, encoding, qnames, namespaces)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 939, in _serialize_xml
_serialize_xml(write, e, encoding, qnames, None)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 939, in _serialize_xml
_serialize_xml(write, e, encoding, qnames, None)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 937, in _serialize_xml
write(_escape_cdata(text, encoding))
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 1073, in _escape_cdata
return text.encode(encoding, "xmlcharrefreplace")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 48: ordinal not in range(128)

# Fixed code
def readStatsAndLogging(self, callback, readAll=False):
    numberOfFilesProcessed = 0
    for tempDir in self._tempDirectories():
        for tempFile in os.listdir(tempDir):
            if tempFile.startswith("stats"):
                absTempFile = os.path.join(tempDir, tempFile)
                if readAll or not tempFile.endswith(".new"):
                    with open(absTempFile, "r") as fH:
                        callback(fH)
                    numberOfFilesProcessed += 1
                    newName = tempFile.rsplit(".", 1)[0] + ".new"
                    newAbsTempFile = os.path.join(tempDir, newName)
                    # Mark this item as read
                    os.rename(absTempFile, newAbsTempFile)
    return numberOfFilesProcessed
# Buggy code
def __init__(self):
    # Core options
    self.jobStore = os.path.abspath("./toil")
    self.logLevel = getLogLevelString()
    self.workDir = None
    self.stats = False

    # Because the stats option needs the jobStore to persist past the end of the run,
    # the clean default value depends the specified stats option and is determined in setOptions
    self.clean = None

    # Restarting the workflow options
    self.restart = False

    # Batch system options
    self.batchSystem = "singleMachine"
    self.scale = 1
    self.mesosMasterAddress = "localhost:5050"
    self.parasolCommand = "parasol"
    self.parasolMaxBatches = 10000
    self.environment = {}

    # Resource requirements
    self.defaultMemory = 2147483648
    self.defaultCores = 1
    self.defaultDisk = 2147483648
    self.defaultCache = 2147483648  # Cache is 2GB
    self.maxCores = sys.maxint
    self.maxMemory = sys.maxint
    self.maxDisk = sys.maxint

    # Retrying/rescuing jobs
    self.retryCount = 0
    self.maxJobDuration = sys.maxint
    self.rescueJobsFrequency = 3600

    # Misc
    self.maxLogFileSize = 50120
    self.sseKey = None
    self.cseKey = None

    # Debug options
    self.badWorker = 0.0
    self.badWorkerFailInterval = 0.01


# Traceback (RuntimeError)
Traceback (most recent call last):
File "hello_world.py", line 10, in <module>
result = Job.Runner.startToil( job, options )
File "/usr/local/lib/python2.7/dist-packages/toil/job.py", line 436, in startToil
rootJob = job._serialiseFirstJob(jobStore)
File "/usr/local/lib/python2.7/dist-packages/toil/job.py", line 1246, in _serialiseFirstJob
predecessorNumber=0)
File "/usr/local/lib/python2.7/dist-packages/toil/job.py", line 1104, in _createEmptyJobForJob
" than the disk requirement for the job! (disk: %s)" % (cache, disk))
RuntimeError: Trying to allocate a cache (cache: 2147483648.0) larger than the disk requirement for the job! (disk: 1000000)

# Fixed code
def __init__(self):
    # Core options
    self.jobStore = os.path.abspath("./toil")
    self.logLevel = getLogLevelString()
    self.workDir = None
    self.stats = False

    # Because the stats option needs the jobStore to persist past the end of the run,
    # the clean default value depends the specified stats option and is determined in setOptions
    self.clean = None

    # Restarting the workflow options
    self.restart = False

    # Batch system options
    self.batchSystem = "singleMachine"
    self.scale = 1
    self.mesosMasterAddress = "localhost:5050"
    self.parasolCommand = "parasol"
    self.parasolMaxBatches = 10000
    self.environment = {}

    # Resource requirements
    self.defaultMemory = 2147483648
    self.defaultCores = 1
    self.defaultDisk = 2147483648
    self.defaultCache = self.defaultDisk
    self.maxCores = sys.maxint
    self.maxMemory = sys.maxint
    self.maxDisk = sys.maxint

    # Retrying/rescuing jobs
    self.retryCount = 0
    self.maxJobDuration = sys.maxint
    self.rescueJobsFrequency = 3600

    # Misc
    self.maxLogFileSize = 50120
    self.sseKey = None
    self.cseKey = None

    # Debug options
    self.badWorker = 0.0
    self.badWorkerFailInterval = 0.01
# Buggy code
def setOption(varName, parsingFn=None, checkFn=None):
    # If options object has the option "varName" specified
    # then set the "varName" attrib to this value in the config object
    x = getattr(options, varName, None)
    if x != None:
        if parsingFn != None:
            x = parsingFn(x)
        if checkFn != None:
            try:
                checkFn(x)
            except AssertionError:
                raise RuntimeError(
                    "The %s option has an invalid value: %s" % (varName, x)
                )
        setattr(self, varName, x)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "hello_world.py", line 10, in <module>
result = Job.Runner.startToil( job, options )
File "/usr/local/lib/python2.7/dist-packages/toil/job.py", line 436, in startToil
rootJob = job._serialiseFirstJob(jobStore)
File "/usr/local/lib/python2.7/dist-packages/toil/job.py", line 1246, in _serialiseFirstJob
predecessorNumber=0)
File "/usr/local/lib/python2.7/dist-packages/toil/job.py", line 1104, in _createEmptyJobForJob
" than the disk requirement for the job! (disk: %s)" % (cache, disk))
RuntimeError: Trying to allocate a cache (cache: 2147483648.0) larger than the disk requirement for the job! (disk: 1000000)

# Fixed code
def setOption(varName, parsingFn=None, checkFn=None):
    # If options object has the option "varName" specified
    # then set the "varName" attrib to this value in the config object
    x = getattr(options, varName, None)
    if x is not None:
        if parsingFn is not None:
            x = parsingFn(x)
        if checkFn is not None:
            try:
                checkFn(x)
            except AssertionError:
                raise RuntimeError(
                    "The %s option has an invalid value: %s" % (varName, x)
                )
        setattr(self, varName, x)
# Buggy code
def _createEmptyJobForJob(self, jobStore, command=None, predecessorNumber=0):
    """
    Create an empty job for the job.
    """
    memory = (
        self.memory if self.memory is not None else float(jobStore.config.defaultMemory)
    )
    cores = (
        self.cores if self.cores is not None else float(jobStore.config.defaultCores)
    )
    disk = self.disk if self.disk is not None else float(jobStore.config.defaultDisk)
    cache = (
        self.cache if self.cache is not None else float(jobStore.config.defaultCache)
    )

    if cache > disk:
        raise RuntimeError(
            "Trying to allocate a cache (cache: %s) larger"
            " than the disk requirement for the job! (disk: %s)" % (cache, disk)
        )

    return jobStore.create(
        command=command,
        memory=memory,
        cores=cores,
        disk=disk,
        predecessorNumber=predecessorNumber,
    )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "hello_world.py", line 10, in <module>
result = Job.Runner.startToil( job, options )
File "/usr/local/lib/python2.7/dist-packages/toil/job.py", line 436, in startToil
rootJob = job._serialiseFirstJob(jobStore)
File "/usr/local/lib/python2.7/dist-packages/toil/job.py", line 1246, in _serialiseFirstJob
predecessorNumber=0)
File "/usr/local/lib/python2.7/dist-packages/toil/job.py", line 1104, in _createEmptyJobForJob
" than the disk requirement for the job! (disk: %s)" % (cache, disk))
RuntimeError: Trying to allocate a cache (cache: 2147483648.0) larger than the disk requirement for the job! (disk: 1000000)

# Fixed code
def _createEmptyJobForJob(self, jobStore, command=None, predecessorNumber=0):
    """
    Create an empty job for the job.
    """
    requirements = self.effectiveRequirements(jobStore.config)
    del requirements.cache
    return jobStore.create(
        command=command, predecessorNumber=predecessorNumber, **requirements
    )
# Buggy code
def __init__(self, config, maxCores, maxMemory, maxDisk):
    """This method must be called.
    The config object is setup by the toilSetup script and
    has configuration parameters for the jobtree. You can add stuff
    to that script to get parameters for your batch system.
    """
    self.config = config
    self.maxCores = maxCores
    self.maxMemory = maxMemory
    self.maxDisk = maxDisk


# Traceback (ConfigParser.NoSectionError)
DEBUG:toil.batchSystems.mesos.executor:Starting executor
I0924 22:47:08.587648 43191 exec.cpp:132] Version: 0.22.0
I0924 22:47:08.592193 43192 exec.cpp:206] Executor registered on slave 20150924-214557-83886090-5050-44087-S8
INFO:toil.batchSystems.mesos.executor:Registered with framework
DEBUG:toil.batchSystems.mesos.executor:Running task 0
DEBUG:toil.batchSystems.mesos.executor:Sending status update ...
DEBUG:toil.batchSystems.mesos.executor:Sent status update
DEBUG:toil.batchSystems.mesos.executor:Invoking command: '/usr/bin/python2.7 -E /usr/local/lib/python2.7/dist-packages/toil/worker.py azure:hgvm:tree2 683b1010_55c3_4978_a7e7_853f17ed1803'
DEBUG:toil.batchSystems.mesos.executor:Sent stats message
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/toil/worker.py", line 408, in <module>
main()
File "/usr/local/lib/python2.7/dist-packages/toil/worker.py", line 89, in main
jobStore = loadJobStore(jobStoreString)
File "/usr/local/lib/python2.7/dist-packages/toil/common.py", line 366, in loadJobStore
return AzureJobStore( account, namePrefix, config=config )
File "/usr/local/lib/python2.7/dist-packages/toil/jobStores/azureJobStore.py", line 78, in __init__
account_key = _fetchAzureAccountKey(accountName)
File "/usr/local/lib/python2.7/dist-packages/toil/jobStores/azureJobStore.py", line 63, in _fetchAzureAccountKey
return configParser.get('AzureStorageCredentials', accountName)
File "/usr/lib/python2.7/ConfigParser.py", line 330, in get
raise NoSectionError(section)
ConfigParser.NoSectionError: No section: 'AzureStorageCredentials'
DEBUG:toil.batchSystems.mesos.executor:Sending status update ...
DEBUG:toil.batchSystems.mesos.executor:Sent status update
I0924 22:47:09.738494 43200 exec.cpp:379] Executor asked to shutdown
CRITICAL:toil.batchSystems.mesos.executor:Shutting down executor...
CRITICAL:toil.batchSystems.mesos.executor:Executor shut down

# Fixed code
def __init__(self, config, maxCores, maxMemory, maxDisk):
    """This method must be called.
    The config object is setup by the toilSetup script and
    has configuration parameters for the jobtree. You can add stuff
    to that script to get parameters for your batch system.
    """
    self.config = config
    self.maxCores = maxCores
    self.maxMemory = maxMemory
    self.maxDisk = maxDisk
    self.environment = {}
    """
        :type dict[str,str]
        """
# Buggy code
def runJob(job):
    """
    :type job: toil.batchSystems.mesos.ToilJob

    :rtype: subprocess.Popen
    """
    if job.userScript:
        job.userScript.register()
    log.debug("Invoking command: '%s'", job.command)
    with self.popenLock:
        return subprocess.Popen(job.command, shell=True)


# Traceback (ConfigParser.NoSectionError)
DEBUG:toil.batchSystems.mesos.executor:Starting executor
I0924 22:47:08.587648 43191 exec.cpp:132] Version: 0.22.0
I0924 22:47:08.592193 43192 exec.cpp:206] Executor registered on slave 20150924-214557-83886090-5050-44087-S8
INFO:toil.batchSystems.mesos.executor:Registered with framework
DEBUG:toil.batchSystems.mesos.executor:Running task 0
DEBUG:toil.batchSystems.mesos.executor:Sending status update ...
DEBUG:toil.batchSystems.mesos.executor:Sent status update
DEBUG:toil.batchSystems.mesos.executor:Invoking command: '/usr/bin/python2.7 -E /usr/local/lib/python2.7/dist-packages/toil/worker.py azure:hgvm:tree2 683b1010_55c3_4978_a7e7_853f17ed1803'
DEBUG:toil.batchSystems.mesos.executor:Sent stats message
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/toil/worker.py", line 408, in <module>
main()
File "/usr/local/lib/python2.7/dist-packages/toil/worker.py", line 89, in main
jobStore = loadJobStore(jobStoreString)
File "/usr/local/lib/python2.7/dist-packages/toil/common.py", line 366, in loadJobStore
return AzureJobStore( account, namePrefix, config=config )
File "/usr/local/lib/python2.7/dist-packages/toil/jobStores/azureJobStore.py", line 78, in __init__
account_key = _fetchAzureAccountKey(accountName)
File "/usr/local/lib/python2.7/dist-packages/toil/jobStores/azureJobStore.py", line 63, in _fetchAzureAccountKey
return configParser.get('AzureStorageCredentials', accountName)
File "/usr/lib/python2.7/ConfigParser.py", line 330, in get
raise NoSectionError(section)
ConfigParser.NoSectionError: No section: 'AzureStorageCredentials'
DEBUG:toil.batchSystems.mesos.executor:Sending status update ...
DEBUG:toil.batchSystems.mesos.executor:Sent status update
I0924 22:47:09.738494 43200 exec.cpp:379] Executor asked to shutdown
CRITICAL:toil.batchSystems.mesos.executor:Shutting down executor...
CRITICAL:toil.batchSystems.mesos.executor:Executor shut down

# Fixed code
def runJob(job):
    """
    :type job: toil.batchSystems.mesos.ToilJob

    :rtype: subprocess.Popen
    """
    if job.userScript:
        job.userScript.register()
    log.debug("Invoking command: '%s'", job.command)
    with self.popenLock:
        return subprocess.Popen(
            job.command, shell=True, env=dict(os.environ, **job.environment)
        )
# Buggy code
def getIssuedBatchJobIDs(self):
    """
    A list of jobs (as jobIDs) currently issued (may be running, or maybe just waiting).
    """
    # TODO: Ensure jobList holds jobs that have been "launched" from Mesos
    jobList = []
    for k, queue in self.jobQueueList.iteritems():
        for item in queue:
            jobList.append(item.jobID)
    for k, v in self.runningJobMap.iteritems():
        jobList.append(k)

    return jobList


# Traceback (RuntimeError)
Failed to call scheduler's resourceOffer
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/toil/batchSystems/mesos/batchSystem.py", line 359, in resourceOffers
self._updateStateToRunning(offer, task)
File "/usr/local/lib/python2.7/dist-packages/toil/batchSystems/mesos/batchSystem.py", line 310, in _updateStateToRunning
self._deleteByJobID(int(task.task_id.value))
File "/usr/local/lib/python2.7/dist-packages/toil/batchSystems/mesos/batchSystem.py", line 301, in _deleteByJobID
for key, jobType in self.jobQueueList.iteritems():
RuntimeError: dictionary changed size during iteration
I0929 00:22:16.111704 31507 sched.cpp:1623] Asked to abort the driver
INFO:realtime:Aligned /tmp/tmpvAfao6/localTempDir/output.gam
I0929 00:22:16.117781 31507 sched.cpp:856] Aborting framework '20150928-184937-83886090-5050-35771-0006'

# Fixed code
def getIssuedBatchJobIDs(self):
    """
    A list of jobs (as jobIDs) currently issued (may be running, or maybe just waiting).
    """
    # TODO: Ensure jobList holds jobs that have been "launched" from Mesos
    jobList = set()
    for queue in self.jobQueueList.values():
        for item in queue:
            jobList.add(item.jobID)
    for key in self.runningJobMap.keys():
        jobList.add(key)

    return list(jobList)
# Buggy code
def getRunningBatchJobIDs(self):
    """
    Gets a map of jobs (as jobIDs) currently running (not just waiting) and a how long they have been running for
    (in seconds).
    """
    currentTime = dict()
    for jobID, data in self.runningJobMap.iteritems():
        currentTime[jobID] = time.time() - data.startTime
    return currentTime


# Traceback (RuntimeError)
Failed to call scheduler's resourceOffer
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/toil/batchSystems/mesos/batchSystem.py", line 359, in resourceOffers
self._updateStateToRunning(offer, task)
File "/usr/local/lib/python2.7/dist-packages/toil/batchSystems/mesos/batchSystem.py", line 310, in _updateStateToRunning
self._deleteByJobID(int(task.task_id.value))
File "/usr/local/lib/python2.7/dist-packages/toil/batchSystems/mesos/batchSystem.py", line 301, in _deleteByJobID
for key, jobType in self.jobQueueList.iteritems():
RuntimeError: dictionary changed size during iteration
I0929 00:22:16.111704 31507 sched.cpp:1623] Asked to abort the driver
INFO:realtime:Aligned /tmp/tmpvAfao6/localTempDir/output.gam
I0929 00:22:16.117781 31507 sched.cpp:856] Aborting framework '20150928-184937-83886090-5050-35771-0006'

# Fixed code
def getRunningBatchJobIDs(self):
    """
    Gets a map of jobs (as jobIDs) currently running (not just waiting) and a how long they have been running for
    (in seconds).
    """
    currentTime = dict()
    for jobID, data in self.runningJobMap.items():
        currentTime[jobID] = time.time() - data.startTime
    return currentTime
# Buggy code
def _sortJobsByResourceReq(self):
    job_types = list(self.jobQueueList.keys())
    # sorts from largest to smallest core usage
    # TODO: add a size() method to ResourceSummary and use it as the key. Ask me why.
    job_types.sort(key=lambda resourceRequirement: ResourceRequirement.cores)
    job_types.reverse()
    return job_types


# Traceback (RuntimeError)
Failed to call scheduler's resourceOffer
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/toil/batchSystems/mesos/batchSystem.py", line 359, in resourceOffers
self._updateStateToRunning(offer, task)
File "/usr/local/lib/python2.7/dist-packages/toil/batchSystems/mesos/batchSystem.py", line 310, in _updateStateToRunning
self._deleteByJobID(int(task.task_id.value))
File "/usr/local/lib/python2.7/dist-packages/toil/batchSystems/mesos/batchSystem.py", line 301, in _deleteByJobID
for key, jobType in self.jobQueueList.iteritems():
RuntimeError: dictionary changed size during iteration
I0929 00:22:16.111704 31507 sched.cpp:1623] Asked to abort the driver
INFO:realtime:Aligned /tmp/tmpvAfao6/localTempDir/output.gam
I0929 00:22:16.117781 31507 sched.cpp:856] Aborting framework '20150928-184937-83886090-5050-35771-0006'

# Fixed code
def _sortJobsByResourceReq(self):
    job_types = self.jobQueueList.keys()
    # sorts from largest to smallest core usage
    # TODO: add a size() method to ResourceSummary and use it as the key. Ask me why.
    job_types.sort(key=lambda resourceRequirement: ResourceRequirement.cores)
    job_types.reverse()
    return job_types
# Buggy code
def _deleteByJobID(
    self,
    jobID,
):
    # FIXME: not efficient, I'm sure.
    for key, jobType in self.jobQueueList.iteritems():
        for job in jobType:
            if jobID == job.jobID:
                jobType.remove(job)


# Traceback (RuntimeError)
Failed to call scheduler's resourceOffer
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/toil/batchSystems/mesos/batchSystem.py", line 359, in resourceOffers
self._updateStateToRunning(offer, task)
File "/usr/local/lib/python2.7/dist-packages/toil/batchSystems/mesos/batchSystem.py", line 310, in _updateStateToRunning
self._deleteByJobID(int(task.task_id.value))
File "/usr/local/lib/python2.7/dist-packages/toil/batchSystems/mesos/batchSystem.py", line 301, in _deleteByJobID
for key, jobType in self.jobQueueList.iteritems():
RuntimeError: dictionary changed size during iteration
I0929 00:22:16.111704 31507 sched.cpp:1623] Asked to abort the driver
INFO:realtime:Aligned /tmp/tmpvAfao6/localTempDir/output.gam
I0929 00:22:16.117781 31507 sched.cpp:856] Aborting framework '20150928-184937-83886090-5050-35771-0006'

# Fixed code
def _deleteByJobID(
    self,
    jobID,
):
    # FIXME: not efficient, I'm sure.
    for jobType in self.jobQueueList.values():
        for job in jobType:
            if jobID == job.jobID:
                jobType.remove(job)
# Buggy code
def __reconcile(self, driver):
    """
    Queries the master about a list of running tasks. If the master has no knowledge of them, their state will be
    updated to LOST.
    """
    # FIXME: we need additional reconciliation. What about the tasks the master knows about but haven't updated?
    now = time.time()
    if now > self.lastReconciliation + self.reconciliationPeriod:
        self.lastReconciliation = now
        driver.reconcileTasks(list(self.runningJobMap.keys()))


# Traceback (RuntimeError)
Failed to call scheduler's resourceOffer
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/toil/batchSystems/mesos/batchSystem.py", line 359, in resourceOffers
self._updateStateToRunning(offer, task)
File "/usr/local/lib/python2.7/dist-packages/toil/batchSystems/mesos/batchSystem.py", line 310, in _updateStateToRunning
self._deleteByJobID(int(task.task_id.value))
File "/usr/local/lib/python2.7/dist-packages/toil/batchSystems/mesos/batchSystem.py", line 301, in _deleteByJobID
for key, jobType in self.jobQueueList.iteritems():
RuntimeError: dictionary changed size during iteration
I0929 00:22:16.111704 31507 sched.cpp:1623] Asked to abort the driver
INFO:realtime:Aligned /tmp/tmpvAfao6/localTempDir/output.gam
I0929 00:22:16.117781 31507 sched.cpp:856] Aborting framework '20150928-184937-83886090-5050-35771-0006'

# Fixed code
def __reconcile(self, driver):
    """
    Queries the master about a list of running tasks. If the master has no knowledge of them, their state will be
    updated to LOST.
    """
    # FIXME: we need additional reconciliation. What about the tasks the master knows about but haven't updated?
    now = time.time()
    if now > self.lastReconciliation + self.reconciliationPeriod:
        self.lastReconciliation = now
        driver.reconcileTasks(self.runningJobMap.keys())
# Buggy code
def _check_load_mat(fname, uint16_codec):
    """Check if the mat struct contains 'EEG'."""
    from ...externals.pymatreader import read_mat

    eeg = read_mat(fname, uint16_codec=uint16_codec)
    if "ALLEEG" in eeg:
        raise NotImplementedError(
            "Loading an ALLEEG array is not supported. Please contact"
            "mne-python developers for more information."
        )
    if "EEG" not in eeg:
        raise ValueError("Could not find EEG array in the .set file.")
    else:
        eeg = eeg["EEG"]
    eeg = eeg.get("EEG", eeg)  # handle nested EEG structure
    eeg = Bunch(**eeg)
    eeg.trials = int(eeg.trials)
    eeg.nbchan = int(eeg.nbchan)
    eeg.pnts = int(eeg.pnts)
    return eeg


# Traceback (ValueError)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-17-1519c0d84577> in <module>
----> 1 raw = mne.io.read_epochs_eeglab(input_fname = data_path + '/'+ subject_name + '_play_merged.set')

~/.pyenv/versions/anaconda3-5.3.1/lib/python3.7/site-packages/mne/io/eeglab/eeglab.py in read_epochs_eeglab(input_fname, events, event_id, eog, verbose, uint16_codec)
277     epochs = EpochsEEGLAB(input_fname=input_fname, events=events, eog=eog,
278                           event_id=event_id, verbose=verbose,
--> 279                           uint16_codec=uint16_codec)
280     return epochs
281

<decorator-gen-198> in __init__(self, input_fname, events, event_id, tmin, baseline, reject, flat, reject_tmin, reject_tmax, montage, eog, verbose, uint16_codec)

~/.pyenv/versions/anaconda3-5.3.1/lib/python3.7/site-packages/mne/io/eeglab/eeglab.py in __init__(self, input_fname, events, event_id, tmin, baseline, reject, flat, reject_tmin, reject_tmax, montage, eog, verbose, uint16_codec)
449                  uint16_codec=None):  # noqa: D102
450         eeg = _check_load_mat(input_fname, uint16_codec)
--> 451
452         if not ((events is None and event_id is None) or
453                 (events is not None and event_id is not None)):

~/.pyenv/versions/anaconda3-5.3.1/lib/python3.7/site-packages/mne/io/eeglab/eeglab.py in _check_load_mat(fname, uint16_codec)
63             'mne-python developers for more information.')
64     if 'EEG' not in eeg:
---> 65         raise ValueError('Could not find EEG array in the .set file.')
66     else:
67         eeg = eeg['EEG']

ValueError: Could not find EEG array in the .set file.

# Fixed code
def _check_load_mat(fname, uint16_codec):
    """Check if the mat struct contains 'EEG'."""
    from ...externals.pymatreader import read_mat

    eeg = read_mat(fname, uint16_codec=uint16_codec)
    if "ALLEEG" in eeg:
        raise NotImplementedError(
            "Loading an ALLEEG array is not supported. Please contact"
            "mne-python developers for more information."
        )
    if "EEG" in eeg:  # fields are contained in EEG structure
        eeg = eeg["EEG"]
    eeg = eeg.get("EEG", eeg)  # handle nested EEG structure
    eeg = Bunch(**eeg)
    eeg.trials = int(eeg.trials)
    eeg.nbchan = int(eeg.nbchan)
    eeg.pnts = int(eeg.pnts)
    return eeg
# Buggy code
def _plot_update_evoked_topomap(params, bools):
    """Update topomaps."""
    projs = [
        proj for ii, proj in enumerate(params["projs"]) if ii in np.where(bools)[0]
    ]

    params["proj_bools"] = bools
    new_evoked = params["evoked"].copy()
    new_evoked.info["projs"] = []
    new_evoked.add_proj(projs)
    new_evoked.apply_proj()

    data = (
        new_evoked.data[np.ix_(params["picks"], params["time_idx"])] * params["scale"]
    )
    if params["merge_grads"]:
        from ..channels.layout import _merge_grad_data

        data = _merge_grad_data(data)
    image_mask = params["image_mask"]

    pos_x, pos_y = np.asarray(params["pos"])[:, :2].T

    xi = np.linspace(pos_x.min(), pos_x.max(), params["res"])
    yi = np.linspace(pos_y.min(), pos_y.max(), params["res"])
    Xi, Yi = np.meshgrid(xi, yi)
    for ii, im in enumerate(params["images"]):
        Zi = _griddata(pos_x, pos_y, data[:, ii], Xi, Yi)
        Zi[~image_mask] = np.nan
        im.set_data(Zi)
    for cont in params["contours"]:
        cont.set_array(np.c_[Xi, Yi, Zi])

    params["fig"].canvas.draw()


# Traceback (IndexError)
Traceback (most recent call last):
File "/home/mainak/anaconda2/lib/python2.7/site-packages/matplotlib/backends/t
guiEvent=event)
File "/home/mainak/anaconda2/lib/python2.7/site-packages/matplotlib/backend_bt
self.callbacks.process(s, mouseevent)
File "/home/mainak/anaconda2/lib/python2.7/site-packages/matplotlib/cbook.py"s
proxy(*args, **kwargs)
File "/home/mainak/anaconda2/lib/python2.7/site-packages/matplotlib/cbook.py"_
return mtd(*args, **kwargs)
File "/home/mainak/anaconda2/lib/python2.7/site-packages/matplotlib/widgets.pd
self.set_active(i)
File "/home/mainak/anaconda2/lib/python2.7/site-packages/matplotlib/widgets.pe
func(self.labels[index].get_text())
File "mne/viz/utils.py", line 257, in _toggle_proj
params['plot_update_proj_callback'](params, bools)
File "mne/viz/topomap.py", line 103, in _plot_update_evoked_topomap
params['time_idx'])] * params['scale']
IndexError: index 104 is out of bounds for axis 0 with size 102

# Fixed code
def _plot_update_evoked_topomap(params, bools):
    """Update topomaps."""
    projs = [
        proj for ii, proj in enumerate(params["projs"]) if ii in np.where(bools)[0]
    ]

    params["proj_bools"] = bools
    new_evoked = params["evoked"].copy()
    new_evoked.info["projs"] = []
    new_evoked.add_proj(projs)
    new_evoked.apply_proj()

    data = new_evoked.data[:, params["time_idx"]] * params["scale"]
    if params["merge_grads"]:
        from ..channels.layout import _merge_grad_data

        data = _merge_grad_data(data)
    image_mask = params["image_mask"]

    pos_x, pos_y = np.asarray(params["pos"])[:, :2].T

    xi = np.linspace(pos_x.min(), pos_x.max(), params["res"])
    yi = np.linspace(pos_y.min(), pos_y.max(), params["res"])
    Xi, Yi = np.meshgrid(xi, yi)
    for ii, im in enumerate(params["images"]):
        Zi = _griddata(pos_x, pos_y, data[:, ii], Xi, Yi)
        Zi[~image_mask] = np.nan
        im.set_data(Zi)
    for cont in params["contours"]:
        cont.set_array(np.c_[Xi, Yi, Zi])

    params["fig"].canvas.draw()