Cleanup history tables.
487774
public function execute() {
        global $CFG, $DB;

        if (!empty($CFG->gradehistorylifetime)) {
            $now = time();
            $histlifetime = $now - ($CFG->gradehistorylifetime * DAYSECS);
            $tables = [
                'grade_outcomes_history',
                'grade_categories_history',
                'grade_items_history',
                'grade_grades_history',
                'scale_history'
            ];
            foreach ($tables as $table) {
                if ($DB->delete_records_select($table, "timemodified < ?", [$histlifetime])) {
                    mtrace("    Deleted old grade history records from '$table'");
                }
            }
        }
    }
141991
def clean_previous_run(self):
        
        # Execute the base class treatment...
        super(Satellite, self).clean_previous_run()

        # Clean my lists
        del self.broks[:]
        del self.events[:]
964298
public function cleanup()
    {
        $this->db->begin();
        $rslt = $this->db->query( 'SELECT * FROM SQLITE_MASTER' );
        $rslt->setFetchMode( PDO::FETCH_NUM );
        $rows = $rslt->fetchAll();
        foreach ( $rows as $row )
        {
            $table = $row[0];
            $this->db->exec( "DROP TABLE `$table`" );
        }
        $this->db->commit();
    }
559936
def cleanup(self):
        
        remove = []
        for handle, assoc in self.assocs.items():
            if assoc.expiresIn == 0:
                remove.append(handle)
        for handle in remove:
            del self.assocs[handle]
        return len(remove), len(self.assocs)
949564
private void cleanup() {
		CacheEntry oldest = null;
		_count = 0;

		// Cleanup obsolete entries and find the oldest
		for (Map.Entry<String, CacheEntry> e : _cache.entrySet()) {
			String key = e.getKey();
			CacheEntry entry = e.getValue();
			// Remove obsolete entry
			if (entry.isExpired()) {
				_cache.remove(key);
			}
			// Count the remaining entry
			else {
				_count++;
				if (oldest == null || oldest.getExpiration() > entry.getExpiration())
					oldest = entry;
			}
		}

		// Remove the oldest if cache size exceeded maximum
		if (_count > _maxSize && oldest != null) {
			_cache.remove(oldest.getKey());
			_count--;
		}
	}
357099
def cleanup_datastore(self):
    """"""
    print_header('CLEANING UP ENTIRE DATASTORE')
    kinds_to_delete = [u'Submission', u'SubmissionType',
                       u'DatasetImage', u'DatasetBatch',
                       u'AdversarialImage', u'AdversarialBatch',
                       u'Work', u'WorkType',
                       u'ClassificationBatch']
    keys_to_delete = [e.key for k in kinds_to_delete
                      for e in self.datastore_client.query_fetch(kind=k)]
    self._cleanup_keys_with_confirmation(keys_to_delete)
663689
def cleanup(self):
        
        remove = []
        for handle, assoc in self.assocs.iteritems():
            if assoc.getExpiresIn() == 0:
                remove.append(handle)
        for handle in remove:
            del self.assocs[handle]
        return len(remove), len(self.assocs)
750796
public function cleanup()
    {
        $baseClasses = [];
        foreach (ClassInfo::subclassesFor(DataObject::class) as $class) {
            if (get_parent_class($class) == DataObject::class) {
                $baseClasses[] = $class;
            }
        }

        $schema = DataObject::getSchema();
        foreach ($baseClasses as $baseClass) {
            // Get data classes
            $baseTable = $schema->baseDataTable($baseClass);
            $subclasses = ClassInfo::subclassesFor($baseClass);
            unset($subclasses[0]);
            foreach ($subclasses as $k => $subclass) {
                if (!DataObject::getSchema()->classHasTable($subclass)) {
                    unset($subclasses[$k]);
                }
            }

            if ($subclasses) {
                $records = DB::query("SELECT * FROM \"$baseTable\"");


                foreach ($subclasses as $subclass) {
                    $subclassTable = $schema->tableName($subclass);
                    $recordExists[$subclass] =
                        DB::query("SELECT \"ID\" FROM \"$subclassTable\"")->keyedColumn();
                }

                foreach ($records as $record) {
                    foreach ($subclasses as $subclass) {
                        $subclassTable = $schema->tableName($subclass);
                        $id = $record['ID'];
                        if (($record['ClassName'] != $subclass)
                            && (!is_subclass_of($record['ClassName'], $subclass))
                            && isset($recordExists[$subclass][$id])
                        ) {
                            $sql = "DELETE FROM \"$subclassTable\" WHERE \"ID\" = ?";
                            echo "<li>$sql [{$id}]</li>";
                            DB::prepared_query($sql, [$id]);
                        }
                    }
                }
            }
        }
    }
174568
private function cleanup(): void
    {

        CharacterBlueprint::where('character_id', $this->getCharacterId())
            ->whereNotIn('item_id', $this->cleanup_ids->flatten()->unique()->all())
            ->delete();
    }
1047403
def RecordHistory(self):
        """"""
        if not self.restoringHistory:
            record = self.activated_node
            if self.historyIndex < -1:
                try:
                    del self.history[self.historyIndex+1:]
                except AttributeError, err:
                    pass
            if (not self.history) or record != self.history[-1]:
                self.history.append(record)
            del self.history[:-200]
            self.historyIndex = -1
1246835
private void cleanUpHistory() {
    long oldestAllowedTimestamp = System.currentTimeMillis() - historyLength;
    int trashedNotifications = 0;
    
    if (LOG.isDebugEnabled()) {
      LOG.debug("History cleanup: Checking old notifications to remove from history list ...");
    }
    
    HistoryTreeEntry key = new HistoryTreeEntry(oldestAllowedTimestamp, 0, (byte)0);
    int notificationsCount = 0;
    historyLock.writeLock().lock();
    try {
      notificationsCount = orderedHistoryList.size();
      LOG.warn("History cleanup: size of the history before cleanup: " + notificationsCount);

      if (!historyLimitDisabled && notificationsCount > historyLimit) {
        LOG.warn("History cleanup: Reached physical limit. Number of stored notifications: " + 
            notificationsCount + ". Clearing ...");
      }
      
      int index = Collections.binarySearch(orderedHistoryList, key, comparatorByTS);
      int toDeleteByTS = index >= 0 ? index : - (index + 1);
      int toDeleteByLimit = historyLimitDisabled ? 0 : notificationsCount - (int)historyLimit;
      toDeleteByLimit = toDeleteByLimit > 0 ? toDeleteByLimit : 0;
      
      int toDelete = Math.max(toDeleteByTS, toDeleteByLimit);
      
      // Delete items which are too old
      if (toDelete > 0) {
        LOG.warn("History cleanup: number of the history to cleanup: " + toDelete);
        for (int i = 0; i < toDelete; i++) {
          orderedHistoryList.get(i).removeFromTree();
        }
        
        orderedHistoryList.subList(0, toDelete).clear();
        
        if (toDeleteByLimit > toDeleteByTS) {
          // If we delete a notification because we don't have space left
          trashedNotifications ++;
        }
        notificationsCount = orderedHistoryList.size();
        LOG.warn("History cleanup: size of the history after cleanup: " + notificationsCount);
        
        // clean up history tree, remove the node that has no children and
        // no notifications associated with them.
        cleanUpHistoryTree(historyTree);
      }
      
    } finally {
      historyLock.writeLock().unlock();
    }
    
    core.getMetrics().trashedHistoryNotifications.inc(trashedNotifications);
    core.getMetrics().historySize.set(notificationsCount);
    core.getMetrics().historyQueues.set(historyQueuesCount);
  }
156484
def MultiClearPathHistory(self, path_infos):
    """"""
    for client_id, client_path_infos in iteritems(path_infos):
      self.ClearPathHistory(client_id, client_path_infos)
1195143
public function cleanup_tables()
    {

        logger()->info('Performing table maintenance');

        // Prune the failed jobs table
        FailedJob::where('id', '<', (FailedJob::max('id') - 100))->delete();

        // Prune the server statuses older than a week.
        ServerStatus::where('created_at', '<', carbon('now')->subWeek(1))->delete();

        // Prune ESI statuses older than a week
        EsiStatus::where('created_at', '<', carbon('now')->subWeek(1))->delete();

        // Remove groups with no users
        Group::doesntHave('users')->delete();
    }
39874
def purge(self):
        '''
        
        '''
        for table_name in self._db.list_tables():
            self._db.flush(table_name)

        self._run_init_queries()
1185791
public function cleanup()
  {
    // Has to be done, otherwise sqlite-file is locked on Windows-OS
    $this->PDO = null;
    $this->PreparedInsertStatement = null;

    unlink($this->sqlite_db_file);
  }
1129170
def _cleanup(self):  # pragma: no cover
        
        need_to_delete = []  # can't delete from a dict while iterating
        with self.attr_lock:
            now_time = time()
            for path in self.cache:
                if now_time - self.attr[path][TIMESTAMP_KEY] >= MAX_CACHE_TIME:
                    need_to_delete.append(path)
            for path in need_to_delete:
                del self.attr[path]
                del self.cache[path]
684791
def _fix_history_sequence(self, df, table):
        

        # remove "Unnamed: x" columns
        cols = df.columns[df.columns.str.startswith('Unnamed:')].tolist()
        df.drop(cols, axis=1, inplace=True)

        # remove future dates
        df['datetime'] = pd.to_datetime(df['datetime'], utc=True)
        blacklist = df[df['datetime'] > pd.to_datetime('now', utc=True)]
        df = df.loc[set(df.index) - set(blacklist)]  # .tail()

        # loop through data, symbol by symbol
        dfs = []
        bad_ids = [blacklist['id'].values.tolist()]

        for symbol_id in list(df['symbol_id'].unique()):

            data = df[df['symbol_id'] == symbol_id].copy()

            # sort by id
            data.sort_values('id', axis=0, ascending=True, inplace=False)

            # convert index to column
            data.loc[:, "ix"] = data.index
            data.reset_index(inplace=True)

            # find out of sequence ticks/bars
            malformed = data.shift(1)[(data['id'] > data['id'].shift(1)) & (
                data['datetime'] < data['datetime'].shift(1))]

            # cleanup rows
            if malformed.empty:
                # if all rows are in sequence, just remove last row
                dfs.append(data)
            else:
                # remove out of sequence rows + last row from data
                index = [
                    x for x in data.index.values if x not in malformed['ix'].values]
                dfs.append(data.loc[index])

                # add to bad id list (to remove from db)
                bad_ids.append(list(malformed['id'].values))

        # combine all lists
        data = pd.concat(dfs, sort=True)

        # flatten bad ids
        bad_ids = sum(bad_ids, [])

        # remove bad ids from db
        if bad_ids:
            bad_ids = list(map(str, map(int, bad_ids)))
            self.dbcurr.execute("DELETE FROM greeks WHERE %s IN (%s)" % (
                table.lower()[:-1] + "_id", ",".join(bad_ids)))
            self.dbcurr.execute("DELETE FROM " + table.lower() +
                                " WHERE id IN (%s)" % (",".join(bad_ids)))
            try:
                self.dbconn.commit()
            except Exception as e:
                self.dbconn.rollback()

        # return
        return data.drop(['id', 'ix', 'index'], axis=1)