Utility function that performs the alchemy vision call. the cleanup removes the temp storage, and I am not sure whether it should be called here or after alchemy returns and passed control back to cbdone.
346665
function performAction(params, feature, cbdone, cbcleanup) {
    var alchemy_vision = watson.alchemy_vision( { api_key: apikey } );

    if (feature == 'imageFaces')
    {
      alchemy_vision.recognizeFaces(params, cbdone);
    } else if (feature == 'imageLink') {
      alchemy_vision.getImageLinks(params, cbdone);
    } else if (feature == 'imageKeywords') {
      alchemy_vision.getImageKeywords(params, cbdone);
    } else if (feature == 'imageText') {
      alchemy_vision.getImageSceneText(params, cbdone);
    }

    if (cbcleanup) cbcleanup();
  }
847451
private void disposeDecoder(IoSession session) {
        ProtocolDecoder decoder = (ProtocolDecoder) session
                .removeAttribute(DECODER);
        if (decoder == null) {
            return;
        }

        try {
            decoder.dispose(session);
        } catch (Throwable t) {
            LOGGER.warn(
                    "Failed to dispose: " + decoder.getClass().getName() + " (" + decoder + ')');
        }
    }
998763
function cleanUp() {
			_Helper.removeByPath(that.mPostRequests, sPath, oEntityData);
			aCollection.splice(aCollection.indexOf(oEntityData), 1);
			aCollection.$created -= 1;
			addToCount(that.mChangeListeners, sPath, aCollection, -1);
			delete aCollection.$byPredicate[sTransientPredicate];
			if (!sPath) {
				// Note: sPath is empty only in a CollectionCache, so we may call adjustReadRequests
				that.adjustReadRequests(0, -1);
			}
			fnCancelCallback();
		}
592042
protected function cleanup()
    {
        // if $this->fs is an object, the Filesystem has been used, clean it up.
        if (is_object($this->fs)) {
            if ($this->fs->isDirectory($this->tempPath)) {
                $this->fs->deleteDirectory($this->tempPath, false);
            }
        }
    }
886033
@Override
    public void cleanUpState(VirtualConnection vc) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "cleanUpState");
        }

        // Remove the discriminator state from the state map.
        SSLDiscriminatorState discState = (SSLDiscriminatorState) vc.getStateMap().remove(SSL_DISCRIMINATOR_STATE);
        // PK13349 - close the discrimination engine
        closeEngine(discState.getEngine());
        WsByteBuffer decryptedNetBuffer = discState.getDecryptedNetBuffer();
        // Release the decrypted network buffer back to the pool. This shouldn't
        // ever be null, but check anyhow.
        if (decryptedNetBuffer != null) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                Tr.event(tc, "Releasing decryptedNetworkBuffer");
            }
            decryptedNetBuffer.release();
            decryptedNetBuffer = null;
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "cleanUpState");
        }
    }
932247
private void cleanupViewStates() {
        completeRequestSpan(currentRequest());
        finishedDecoding();
        viewInfoObservable = null;
        viewRowObservable = null;
        viewErrorObservable = null;
        viewParsingState = QUERY_STATE_INITIAL;
    }
34655
def cleanup(self):
        """"""
        if self.image:
            try:
                self.image.close()
            except Exception:
                pass
        if (self.outtmp is not None):
            try:
                os.unlink(self.outtmp)
            except OSError as e:
                self.logger.warning("Failed to cleanup tmp output file %s"
                                    % (self.outtmp))
230331
def close(self):
        """"""
        # make sure the environment hasn't already been closed
        if self._env is None:
            raise ValueError('env has already been closed.')
        # purge the environment from C++ memory
        _LIB.Close(self._env)
        # deallocate the object locally
        self._env = None
        # if there is an image viewer open, delete it
        if self.viewer is not None:
            self.viewer.close()
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)
1237819
def _cleanup_tempdir(tempdir):
    """"""
    try:
        shutil.rmtree(tempdir)
    except OSError as err:
        if err.errno != errno.ENOENT:
            raise
327810
def process_view(self, request, view_func, view_args, view_kwargs):
        

        # Purge data in view method cache
        # Python 3's keys() method returns an iterator, so force evaluation before iterating.
        view_keys = list(VIEW_METHOD_DATA.keys())
        for key in view_keys:
            del VIEW_METHOD_DATA[key]

        self.view_data = {}

        try:
            cbv = view_func.view_class
        except AttributeError:
            cbv = False

        if cbv:

            self.view_data['cbv'] = True
            klass = view_func.view_class
            self.view_data['bases'] = [base.__name__ for base in inspect.getmro(klass)]
            # Inject with drugz

            for member in inspect.getmembers(view_func.view_class):
                # Check that we are interested in capturing data for this method
                # and ensure that a decorated method is not decorated multiple times.
                if member[0] in VIEW_METHOD_WHITEIST and member[0] not in PATCHED_METHODS[klass]:
                    decorate_method(klass, member[0])
                    PATCHED_METHODS[klass].append(member[0])
276068
def cleanup(self):
        ''''''
        if self.state == ClientState.WAITING_FOR_RESULT:
            # There is an ongoing call to execute()
            # Not sure what to do here
            logger.warn('cleanup() called while state is WAITING_FOR_RESULT: ignoring')
        elif self.state == ClientState.TERMINATING:
            # terminate() has been called but we have not recieved SIGCHLD yet
            # Not sure what to do here
            logger.warn('cleanup() called while state is TERMINATING: ignoring')
        elif self.state in ClientState.TerminatedSet:
            # We have already terminated
            # TODO: should we deal with TERMINATED_ASYNC in some special way?
            logger.debug('cleanup() called while state is TERMINATING: nothing needs to be done')
        else:
            logger.debug('cleanup() called while state is %s: attempting to terminate',
                          self.strstate)
            try:
                self.terminate()
            except ProcessTerminationError as ex:
                # Terminate can throw a ProcessTerminationError if the
                # process terminated at some point between the last
                # execute() and the call to terminate()
                # For now we just ignore this.
                pass
332738
def _clean_ctx(self):
        
        try:
            if self.ctx is not None:
                self.__ctxcleanup(self.ctx)
                libcrypto.EVP_CIPHER_CTX_free(self.ctx)
                del self.ctx
        except AttributeError:
            pass
        self.cipher_finalized = True
242903
public function discard()
    {
        if ($this->isNew()) {
            $app = Facade::getFacadeApplication();
            $db = $app->make('database')->connection();
            // check for related version edits. This only gets applied when we edit global areas.
            $r = $db->executeQuery('select cRelationID, cvRelationID from CollectionVersionRelatedEdits where cID = ? and cvID = ?', array(
                $this->cID,
                $this->cvID,
            ));
            while ($row = $r->fetch()) {
                $cn = Page::getByID($row['cRelationID'], $row['cvRelationID']);
                $cnp = new Permissions($cn);
                if ($cnp->canApprovePageVersions()) {
                    $v = $cn->getVersionObject();
                    $v->delete();
                    $db->executeQuery('delete from CollectionVersionRelatedEdits where cID = ? and cvID = ? and cRelationID = ? and cvRelationID = ?', array(
                        $this->cID,
                        $this->cvID,
                        $row['cRelationID'],
                        $row['cvRelationID'],
                    ));
                }
            }
            $this->delete();
        }
        $this->refreshCache();
    }
859055
@Override
    public void removeStorageEngine(StorageEngine<ByteArray, byte[], byte[]> engine) {
        String storeName = engine.getName();
        BdbStorageEngine bdbEngine = (BdbStorageEngine) engine;

        synchronized(lock) {

            // Only cleanup the environment if it is per store. We cannot
            // cleanup a shared 'Environment' object
            if(useOneEnvPerStore) {

                Environment environment = this.environments.get(storeName);
                if(environment == null) {
                    // Nothing to clean up.
                    return;
                }

                // Remove from the set of unreserved stores if needed.
                if(this.unreservedStores.remove(environment)) {
                    logger.info("Removed environment for store name: " + storeName
                                + " from unreserved stores");
                } else {
                    logger.info("No environment found in unreserved stores for store name: "
                                + storeName);
                }

                // Try to delete the BDB directory associated
                File bdbDir = environment.getHome();
                if(bdbDir.exists() && bdbDir.isDirectory()) {
                    String bdbDirPath = bdbDir.getPath();
                    try {
                        FileUtils.deleteDirectory(bdbDir);
                        logger.info("Successfully deleted BDB directory : " + bdbDirPath
                                    + " for store name: " + storeName);
                    } catch(IOException e) {
                        logger.error("Unable to delete BDB directory: " + bdbDirPath
                                     + " for store name: " + storeName);
                    }
                }

                // Remove the reference to BdbEnvironmentStats, which holds a
                // reference to the Environment
                BdbEnvironmentStats bdbEnvStats = bdbEngine.getBdbEnvironmentStats();
                this.aggBdbStats.unTrackEnvironment(bdbEnvStats);

                // Unregister the JMX bean for Environment
                if(voldemortConfig.isJmxEnabled()) {
                    ObjectName name = JmxUtils.createObjectName(JmxUtils.getPackageName(bdbEnvStats.getClass()),
                                                                storeName);
                    // Un-register the environment stats mbean
                    JmxUtils.unregisterMbean(name);
                }

                // Cleanup the environment
                environment.close();
                this.environments.remove(storeName);
                logger.info("Successfully closed the environment for store name : " + storeName);

            }
        }
    }
983694
public void clean()
	{

		ChronoFullRevision cfr = firstCFR;
		totalSize = size;
		while (cfr != null) {
			totalSize += cfr.size();
			cfr = cfr.getNext();
		}

		if (totalSize < MAX_STORAGE_SIZE) {
			return;
		}

		cfr = firstCFR;
		while (cfr != null) {
			totalSize += cfr.clean(revisionIndex, 0);
			cfr = cfr.getNext();
		}

		ChronoStorageBlock block;
		while (last != null && totalSize >= MAX_STORAGE_SIZE) {

			// System.out.println("CLEAN " + last.getRevisionIndex());

			// Retrieve previous block
			block = last.getIndexPrev();

			// Subtract size
			if (storage.remove(last.getRevisionIndex()) == null) {
				throw new RuntimeException("VALUE WAS NOT REMOVED FROM STORAGE");
			}
			totalSize -= last.length();
			size += last.length();

			// Delete references
			if (block != null) {
				block.setIndexNext(null);
			}
			last.setIndexPrev(null);

			cfr = last.getChronoFullRevision();
			totalSize += cfr.size()
					- cfr.clean(revisionIndex, last.getRevisionIndex());

			if (last == first) {
				first = null;
			}

			// Set the new last
			last = block;
		}

		
	}
1099292
function cleanUpView(viewOrContainer) {
    if (viewOrContainer[TVIEW]) {
        var view = viewOrContainer;
        removeListeners(view);
        executeOnDestroys(view);
        executePipeOnDestroys(view);
        // For component views only, the local renderer is destroyed as clean up time.
        if (view[TVIEW].id === -1 && isProceduralRenderer(view[RENDERER])) {
            ngDevMode && ngDevMode.rendererDestroy++;
            view[RENDERER].destroy();
        }
    }
}