text:
package org.pentaho.di.core.market;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.io.IOUtils;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.logging.LogChannel;
import org.pentaho.di.core.market.entry.MarketEntry;
import org.pentaho.di.core.market.entry.MarketEntryType;
import org.pentaho.di.core.plugins.KettleURLClassLoader;
import org.pentaho.di.core.plugins.PluginInterface;
import org.pentaho.di.core.plugins.PluginRegistry;
import org.pentaho.di.core.plugins.PluginTypeInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.spoon.Spoon;
import org.pentaho.di.ui.spoon.SpoonLifecycleListener;
import org.pentaho.di.ui.spoon.SpoonPerspective;
import org.pentaho.di.ui.spoon.SpoonPlugin;
import org.pentaho.di.ui.spoon.SpoonPluginCategories;
import org.pentaho.di.ui.spoon.SpoonPluginInterface;
import org.pentaho.di.ui.spoon.dialog.MarketplaceController;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.XulException;
import org.pentaho.xul.swt.tab.TabSet;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

@SpoonPlugin( id = "market", image = "" )
@SpoonPluginCategories( { "spoon" } )
public class Market implements SpoonPluginInterface {

  private static Class<?> PKG = Market.class;

  /**
   * Determines the location of the marketplaces file
   *
   * @return the name of the marketplaces file
   */
  public static final String getMarketplacesFile() {
    return Const.getKettleDirectory() + Const.FILE_SEPARATOR + "marketplaces.xml";
  }

  /**
   * Applies the XUL overlay specified in the loadOverlay call.
   */
  @Override
  public void applyToContainer( String category, XulDomContainer container ) throws XulException {
    if ( category.equals( "spoon" ) ) {
      container.registerClassLoader( getClass().getClassLoader() );
      container.loadOverlay( "org/pentaho/di/core/market/spoon_overlays.xul" );
      container.addEventHandler( new MarketplaceController() );
    }
  }

  @Override
  public SpoonLifecycleListener getLifecycleListener() {
    return null;
  }

  @Override
  public SpoonPerspective getPerspective() {
    return null;
  }

  /**
   * Find the plugin object related to a pluginId.
   *
   * @param pluginId
   *          id of plugin
   * @return plugin object
   */
  private static PluginInterface getPluginObject( String pluginId ) {
    for ( Class<? extends PluginTypeInterface> pluginType : PluginRegistry.getInstance().getPluginTypes() ) {
      if ( PluginRegistry.getInstance().findPluginWithId( pluginType, pluginId ) != null ) {
        return PluginRegistry.getInstance().findPluginWithId( pluginType, pluginId );
      }
    }
    return null;
  }

  /**
   * This method determines the installed version of a plugin. If the plugin doesn't define a version correctly, it
   * returns "Unknown". This method makes the assumption that the plugin id also equals the plugin folder name.
   *
   * @param pluginId
   *          the plugin id related to the version.
   */
  public static String discoverInstalledVersion( MarketEntry marketEntry ) {

    String pluginFolder = buildPluginsFolderPath( marketEntry ) + File.separator + marketEntry.getId();
    File pluginFolderFile = new File( pluginFolder );
    if ( pluginFolderFile.exists() ) {
      marketEntry.setInstalled( true );

      String versionPath = pluginFolder + File.separator + "version.xml";
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      FileReader reader = null;
      try {
        File file = new File( versionPath );
        if ( !file.exists() ) {
          return "Unknown";
        }
        DocumentBuilder db = dbf.newDocumentBuilder();
        reader = new FileReader( versionPath );
        Document dom = db.parse( new InputSource( reader ) );
        NodeList versionElements = dom.getElementsByTagName( "version" );
        if ( versionElements.getLength() >= 1 ) {
          Element versionElement = (Element) versionElements.item( 0 );

          marketEntry.setInstalledBuildId( versionElement.getAttribute( "buildId" ) );
          marketEntry.setInstalledBranch( versionElement.getAttribute( "branch" ) );
          marketEntry.setInstalledVersion( versionElement.getTextContent() );

          return versionElement.getTextContent();
        }

      } catch ( Exception e ) {
        e.printStackTrace();
      } finally {
        try {
          if ( reader != null ) {
            reader.close();
          }
        } catch ( Exception e ) {
          e.printStackTrace();
        }
      }

    } else {
      marketEntry.setInstalled( false );
    }
    return "Unknown";
  }

  /**
   * Builds and returns the path to the plugins folder.
   *
   * @param marketEntry
   * @return String the path to the plugins folder.
   */
  public static String buildPluginsFolderPath( final MarketEntry marketEntry ) {
    PluginInterface plugin = getPluginObject( marketEntry.getId() );
    if ( plugin != null && plugin.getPluginDirectory() != null ) {
      return new File( plugin.getPluginDirectory().getFile() ).getParent();
    } else {
      String subfolder = getInstallationSubfolder( marketEntry );

      // Use current directory (should be the Kettle distribution directory) as the root folder to install plugins
      // This is because plugin types are not guaranteed to search the ~/.kettle folder for plugins.
      return "plugins" + ( subfolder == null ? "" : Const.FILE_SEPARATOR + subfolder );
    }
  }

  /**
   * Installs or uninstalls the MarketEntry.
   *
   * @param marketEntry
   *          The market entry to install/uninstall.
   * @param isInstalled
   *          Boolean indicating if the plugin is installed. If so then it is uninstalled. Otherwise it is installed.
   * @throws KettleException
   */
  public static void installUninstall( final MarketEntry marketEntry, boolean isInstalled,
      ProgressMonitorDialog monitorDialog ) throws KettleException {
    if ( isInstalled ) {
      Market.uninstall( marketEntry, monitorDialog, true );
    } else {
      Market.install( marketEntry, monitorDialog );
    }
  }

  /**
   * Installs the passed MarketEntry into the folder built by buildPluginsFolderPath(marketEntry).
   *
   * A warning dialog box is displayed if the plugin folder already exists. If the user chooses to install then the
   * plugin folder is deleted and then recreated.
   *
   * @param marketEntry
   * @throws KettleException
   */
  public static void install( final MarketEntry marketEntry, ProgressMonitorDialog monitorDialog )
    throws KettleException {
    String parentFolderName = buildPluginsFolderPath( marketEntry );

    // Until plugin dependencies are implemented, check that the pentaho-big-data-plugin directory exists
    // before installing anything of type HadoopShim
    if ( marketEntry.getType().equals( MarketEntryType.HadoopShim ) ) {

      File bdPluginFolder = new File( parentFolderName ).getParentFile();
      if ( bdPluginFolder == null || !bdPluginFolder.exists() ) {
        throw new KettleException( BaseMessages.getString( PKG, "Marketplaces.Dialog.PluginNotInstalled.message",
            "Pentaho Big Data Plugin" )
            + ". You must install the Pentaho Big Data plugin before you can install a Hadoop Shim" );
      }
    }

    File pluginFolder = new File( parentFolderName + File.separator + marketEntry.getId() );
    LogChannel.GENERAL.logBasic( "Installing plugin in folder: " + pluginFolder.getAbsolutePath() );
    if ( pluginFolder.exists() ) {
      monitorDialog.close();
      MessageBox mb = new MessageBox( Spoon.getInstance().getShell(), SWT.NO | SWT.YES | SWT.ICON_WARNING );
      mb.setMessage( BaseMessages.getString( PKG, "Marketplace.Dialog.PromptOverwritePlugin.Message", pluginFolder
          .getAbsolutePath() ) );
      mb.setText( BaseMessages.getString( PKG, "Marketplace.Dialog.PromptOverwritePlugin.Title" ) );
      int answer = SWT.NO;
      answer = mb.open();
      if ( answer == SWT.YES ) {
        monitorDialog.open();
        ClassLoader cl = PluginRegistry.getInstance().getClassLoader( getPluginObject( marketEntry.getId() ) );
        if ( cl instanceof KettleURLClassLoader ) {
          ( (KettleURLClassLoader) cl ).closeClassLoader();
        }
        deleteDirectory( pluginFolder );
        unzipMarketEntry( parentFolderName, marketEntry.getPackageUrl() );
        if ( Market.discoverInstalledVersion( marketEntry ).equalsIgnoreCase( "unknown" ) ) {
          createVersionXML( marketEntry );
        }
        refreshSpoon( monitorDialog );
      }
    } else {
      unzipMarketEntry( parentFolderName, marketEntry.getPackageUrl() );
      if ( Market.discoverInstalledVersion( marketEntry ).equalsIgnoreCase( "unknown" ) ) {
        createVersionXML( marketEntry );
      }
      refreshSpoon( monitorDialog );
    }
  }

  private static void createVersionXML( MarketEntry marketEntry ) throws KettleException {
    String pluginFolder = buildPluginsFolderPath( marketEntry ) + File.separator + marketEntry.getId();
    String versionPath = pluginFolder + File.separator + "version.xml";
    File parentFolder = new File( pluginFolder );
    File file = new File( versionPath );
    if ( file != null ) {
      BufferedWriter bufferedWriter = null;
      try {
        if ( !parentFolder.exists() ) {
          parentFolder.mkdirs();
        }

        FileWriter fw = new FileWriter( file.getAbsoluteFile() );
        bufferedWriter = new BufferedWriter( fw );
        bufferedWriter.write( "<version>" + marketEntry.getVersion() + "</version>" );
      } catch ( IOException ioe ) {
        throw new KettleException( ioe );
      } finally {
        if ( bufferedWriter != null ) {
          try {
            bufferedWriter.close();
          } catch ( IOException ioe ) {
            throw new KettleException( ioe );
          }
        }
      }
    }
  }

  /**
   * Unzips the plugin to the file system The passed MarkeyEntry has the URL of the zip file.
   *
   * @param folderName
   * @param marketEntry
   * @throws KettleException
   */
  private static void unzipMarketEntry( String folderName, String packageUrl ) throws KettleException {

    // Copy the file locally first
    //
    File tmpFile = null;
    InputStream inputStream = null;
    ZipInputStream zis = null;

    try {
      tmpFile = File.createTempFile( "plugin", ".zip" );
      org.apache.commons.io.FileUtils.copyURLToFile( new URL( packageUrl ), tmpFile );

      // Read the package, extract in folder
      //
      inputStream = new FileInputStream( tmpFile );
      zis = new ZipInputStream( inputStream );
      ZipEntry zipEntry = null;
      try {
        zipEntry = zis.getNextEntry();
      } catch ( IOException ioe ) {
        throw new KettleException( ioe );
      }
      byte[] buffer = new byte[1024];
      int bytesRead = 0;
      FileOutputStream fos = null;

      while ( zipEntry != null ) {
        try {
          File file = new File( folderName + File.separator + zipEntry.getName() );

          if ( zipEntry.isDirectory() ) {
            file.mkdirs();
          } else {
            file.getParentFile().mkdirs();

            fos = new FileOutputStream( file );
            while ( ( bytesRead = zis.read( buffer ) ) != -1 ) {
              fos.write( buffer, 0, bytesRead );
            }
          }

          zipEntry = zis.getNextEntry();
        } catch ( FileNotFoundException fnfe ) {
          throw new KettleException( fnfe );
        } catch ( IOException ioe ) {
          throw new KettleException( ioe );
        } finally {
          if ( fos != null ) {
            try {
              fos.close();
            } catch ( IOException e ) {
              // Ignore.
            }
          }
        }
      }
    } catch ( IOException e ) {
      throw new KettleException( "Unable to unzip file " + packageUrl, e );
    } finally {
      if ( zis != null ) {
        tmpFile.delete();
        try {
          zis.close();
        } catch ( Exception e ) {
          throw new KettleException( "Unable to close zip file stream (corrupt file?) of file " + tmpFile, e );
        }
      }
    }

  }

  /**
   * Uninstalls the passed MarketEntry.
   *
   * @param marketEntry
   * @throws KettleException
   */
  public static void uninstall( final MarketEntry marketEntry, final ProgressMonitorDialog monitorDialog,
      boolean refresh ) throws KettleException {

    String parentFolderName = buildPluginsFolderPath( marketEntry );
    File pluginFolder = new File( parentFolderName + File.separator + marketEntry.getId() );
    LogChannel.GENERAL.logBasic( "Uninstalling plugin in folder: " + pluginFolder.getAbsolutePath() );

    if ( !pluginFolder.exists() ) {
      throw new KettleException( "No plugin was found in the expected folder : " + pluginFolder.getAbsolutePath() );
    }

    try {
      for ( PluginInterface plugin : PluginRegistry.getInstance().findPluginsByFolder( pluginFolder.toURI().toURL() ) ) {
        // unload plugin
        ClassLoader cl = PluginRegistry.getInstance().getClassLoader( plugin );
        if ( cl instanceof KettleURLClassLoader ) {
          ( (KettleURLClassLoader) cl ).closeClassLoader();
        }

        // remove plugin from registry
        PluginRegistry.getInstance().removePlugin( plugin.getPluginType(), plugin );
      }
    } catch ( MalformedURLException e1 ) {
      LogChannel.GENERAL.logError( e1.getLocalizedMessage(), e1 );
    }

    // delete plugin folder
    deleteDirectory( pluginFolder );

    if ( refresh ) {
      if ( !Display.getDefault().getThread().equals( Thread.currentThread() ) ) {
        Spoon.getInstance().getDisplay().asyncExec( new Runnable() {
          public void run() {
            try {
              refreshSpoon( monitorDialog );
            } catch ( KettleException e ) {
              e.printStackTrace();
            }
          }
        } );
      } else {
        refreshSpoon( monitorDialog );
      }
    }
  }

  public static void uninstallMarketInSeparateClassLoader( final File path, final ProgressMonitorDialog monitorDialog )
    throws Exception {
    try {
      Spoon.getInstance().getMainSpoonContainer().removeOverlay( "org/pentaho/di/core/market/spoon_overlays.xul" );
      uninstall( new MarketEntry( "market", MarketEntryType.Mixed ), monitorDialog, false );
      Spoon.getInstance().getDisplay().asyncExec( new Runnable() {
        public void run() {
          try {
            refreshSpoon( monitorDialog );
          } catch ( Exception e ) {
            e.printStackTrace();
          } finally {
            if ( Market.class.getClassLoader() instanceof KettleURLClassLoader ) {
              ( (KettleURLClassLoader) Market.class.getClassLoader() ).closeClassLoader();
            }
            path.delete();
          }
        }
      } );
    } catch ( Exception e ) {
      e.printStackTrace();
    }
  }

  public static void upgradeMarketInSeparateClassLoader( final File path, final String packageUrl,
      final ProgressMonitorDialog monitorDialog ) throws Exception {
    try {

      PluginInterface plugin = getPluginObject( "market" );
      if ( plugin == null ) {
        throw new KettleException( "No Plugin!" );
      }
      File pluginFolder = new File( plugin.getPluginDirectory().getFile() );
      String parentFolderName = pluginFolder.getParent();

      // unload plugin
      ClassLoader cl = PluginRegistry.getInstance().getClassLoader( plugin );
      if ( cl instanceof KettleURLClassLoader ) {
        ( (KettleURLClassLoader) cl ).closeClassLoader();
      }
      // remove plugin
      deleteDirectory( pluginFolder );

      // install new version
      unzipMarketEntry( parentFolderName, packageUrl );

      Spoon.getInstance().getDisplay().asyncExec( new Runnable() {
        public void run() {
          try {
            // refresh plugins
            refreshSpoon( monitorDialog );

            MessageBox box = new MessageBox( Spoon.getInstance().getShell(), SWT.ICON_WARNING | SWT.OK );
            box.setText( BaseMessages.getString( PKG, "MarketplacesDialog.RestartUpdate.Title" ) );
            box.setMessage( BaseMessages.getString( PKG, "MarketplacesDialog.RestartUpdate.Message" ) );
            box.open();

          } catch ( KettleException e ) {
            e.printStackTrace();
          } finally {
            if ( Market.class.getClassLoader() instanceof KettleURLClassLoader ) {
              ( (KettleURLClassLoader) Market.class.getClassLoader() ).closeClassLoader();
            }
            path.delete();
          }
        }
      } );

    } catch ( Exception e ) {
      e.printStackTrace();

      // clean up if there was an exception
      if ( Market.class.getClassLoader() instanceof KettleURLClassLoader ) {
        ( (KettleURLClassLoader) Market.class.getClassLoader() ).closeClassLoader();
      }
      path.delete();
    }
  }

  public static void upgradeMarket( final MarketEntry entry ) throws KettleException {
    try {
      PluginInterface plugin = getPluginObject( "market" );
      if ( plugin == null ) {
        throw new KettleException( "No Plugin!" );
      }

      String pluginFolderName = plugin.getPluginDirectory().getFile();
      File folder = new File( pluginFolderName );

      // do these two steps from the Dialog
      // prompt user if they are sure they want to uninstall (optional)
      // exit out of marketplace UI (do this from the UI)

      // find marketplace jar
      File[] files = folder.listFiles();
      File jar = null;
      for ( File f : files ) {
        if ( f.getName().endsWith( ".jar" ) ) {
          jar = f;
          break;
        }
      }
      // load a tmp jar

      final File finalJar = jar;

      Thread t = new Thread() {
        public void run() {
          KettleURLClassLoader classloader = null;
          try {
            File tmpJar = File.createTempFile( "kettle_marketplace_tmp", ".jar" );
            FileInputStream fis = new FileInputStream( finalJar );
            FileOutputStream fos = new FileOutputStream( tmpJar );
            IOUtils.copy( fis, fos );
            fis.close();
            fos.close();
            classloader =
                new KettleURLClassLoader( new URL[] { tmpJar.toURI().toURL() }, Spoon.getInstance().getClass()
                    .getClassLoader() );
            Class<?> clazz = classloader.loadClass( "org.pentaho.di.core.market.Market" );
            // remove the plugin, unload when done.
            Method m = clazz.getMethod( "upgradeMarketInSeparateClassLoader", File.class, String.class );
            m.invoke( null, tmpJar, entry.getPackageUrl() );
          } catch ( Throwable t ) {
            t.printStackTrace();
          } finally {
            if ( classloader != null ) {
              classloader.closeClassLoader();
            }
          }
        }
      };
      t.start();

    } catch ( Throwable t ) {
      t.printStackTrace();
      throw new KettleException( t );
    }
  }

  public static void uninstallMarket() throws KettleException {
    try {
      PluginInterface plugin = getPluginObject( "market" );
      if ( plugin == null ) {
        throw new KettleException( "No Plugin!" );
      }

      String pluginFolderName = plugin.getPluginDirectory().getFile();
      File folder = new File( pluginFolderName );

      // do these two steps from the Dialog
      // prompt user if they are sure they want to uninstall (optional)
      // exit out of marketplace UI (do this from the UI)

      // find marketplace jar
      File[] files = folder.listFiles();
      File jar = null;
      for ( File f : files ) {
        if ( f.getName().endsWith( ".jar" ) ) {
          jar = f;
          break;
        }
      }
      // load a tmp jar

      final File finalJar = jar;

      Thread t = new Thread() {
        KettleURLClassLoader classloader = null;

        public void run() {
          try {
            File tmpJar = File.createTempFile( "kettle_marketplace_tmp", ".jar" );
            FileInputStream fis = new FileInputStream( finalJar );
            FileOutputStream fos = new FileOutputStream( tmpJar );
            IOUtils.copy( fis, fos );
            fis.close();
            fos.close();

            // The classloader will be closed by the invoked method
            //
            @SuppressWarnings( "resource" )
            KettleURLClassLoader classloader =
                new KettleURLClassLoader( new URL[] { tmpJar.toURI().toURL() }, Spoon.getInstance().getClass()
                    .getClassLoader() );
            Class<?> clazz = classloader.loadClass( "org.pentaho.di.core.market.Market" );
            // remove the plugin, unload when done.
            Method m =
                clazz.getMethod( "uninstallMarketInSeparateClassLoader", File.class, ProgressMonitorDialog.class );
            m.invoke( null, tmpJar, null );
          } catch ( Throwable t ) {
            t.printStackTrace();
          } finally {
            if ( classloader != null ) {
              classloader.closeClassLoader();
            }
          }
        }
      };
      t.start();

    } catch ( Throwable t ) {
      t.printStackTrace();
      throw new KettleException( t );
    }
  }

  /**
   * Refreshes Spoons plugin registry, core objects and some UI things.
   *
   * @throws KettleException
   */
  private static void refreshSpoon( ProgressMonitorDialog monitorDialog ) throws KettleException {

    if ( monitorDialog != null ) {
      monitorDialog.close();
    }

    MessageBox box = new MessageBox( Spoon.getInstance().getShell(), SWT.ICON_QUESTION | SWT.OK );
    box.setText( BaseMessages.getString( PKG, "MarketplacesDialog.RestartUpdate.Title" ) );
    box.setMessage( BaseMessages.getString( PKG, "MarketplacesDialog.RestartUpdate.Message" ) );
    box.open();

    DatabaseMeta.clearDatabaseInterfacesMap();
    PluginRegistry.init();
    Spoon spoon = Spoon.getInstance();

    // Close all Execution Results panes to avoid SWT disposal issues during refresh
    int numTabs = spoon.delegates.tabs.getTabs().size();
    TabSet tabSet = spoon.getTabSet();
    int selectedIndex = tabSet.getSelectedIndex();
    for ( int i = numTabs - 1; i >= 0; i-- ) {
      if ( i != selectedIndex ) {
        tabSet.setSelected( i );
        if ( spoon.isExecutionResultsPaneVisible() ) {
          spoon.showExecutionResults();
        }
      }
    }
    tabSet.setSelected( selectedIndex );
    if ( spoon.isExecutionResultsPaneVisible() ) {
      spoon.showExecutionResults();
    }

    // Refresh Spoon objects and UI components
    spoon.refreshCoreObjects();
    spoon.refreshTree();
    spoon.refreshGraph();
    spoon.enableMenus();
    GUIResource.getInstance().reload();
    spoon.selectionFilter.setText( spoon.selectionFilter.getText() );
  }

  /**
   * Returns the folder name for the MarketEntries type.
   *
   * @param marketEntry
   * @return
   */
  public static String getInstallationSubfolder( MarketEntry marketEntry ) {
    String subfolder = null;
    switch ( marketEntry.getType() ) {
      case Step:
        subfolder = "steps";
        break;
      case JobEntry:
        subfolder = "jobentries";
        break;
      case Partitioner:
        subfolder = "steps";
        break;
      case SpoonPlugin:
        subfolder = "spoon";
        break;
      case Database:
        subfolder = "databases";
        break;
      case Repository:
        subfolder = "repositories";
        break;
      case HadoopShim:
        subfolder = "pentaho-big-data-plugin" + File.separator + "hadoop-configurations";
        break;
      case Mixed:
      case General:
        subfolder = "";
        break;

      default:
        subfolder = null;
    }
    return subfolder;
  }

  /**
   * This is a copy of method. That method works fine if the plugin is used in the same version it is built from. When
   * the plugin was dropped into PDI 4.2.1 then an invocation target exception was thrown when invoking
   * JarfileGenerator.deleteDirectory().
   *
   * I placed the method here even though the cause of the exception is not that obvious. The
   * JarfileGenerator.deleteDirectory method has not changed since 4.2.1.
   *
   * @param dir
   */
  private static void deleteDirectory( File dir ) throws KettleException {
    if ( dir != null ) {
      File[] files = dir.listFiles();
      if ( files != null ) {
        for ( int i = 0; i < files.length; i++ ) {
          if ( files[i].isDirectory() ) {
            deleteDirectory( files[i] );
          } else if ( !files[i].delete() ) {
            throw new KettleException( "Failed to delete " + files[i] );
          }
        }
      }
      if ( !dir.delete() ) {
        throw new KettleException( "Failed to delete directory " + dir );
      }
    }
  }
}


text:
simple-indexed-collection
=========================

JavaScript simple in-memory indexed Collection, loosely inspired by mongodb's collections

redpajama_set_name: RedPajamaGithub


text:
module Conpar
  module Directive
    # Class for a commented line
    class Comment < Base
      SIGNATURE = /^\:(.*)?$/

      def initialize(content="", options={})
        super
        @ilk = :comment
        @sub_ilk = "comment"
      end
    end
  end
end


text:
import React from 'react';
import { createStory, createDropzoneStory } from './core';

const { filePickerReact } = window.Kloudless;

export default {
  title: 'E2E Test',
};

const ChooserStory = createStory(filePickerReact.Chooser);
const SaverStory = createStory(filePickerReact.Saver);
const DropzoneStory = createDropzoneStory(filePickerReact.Dropzone);

export const Chooser = () => <ChooserStory></ChooserStory>;
export const Saver = () => <SaverStory></SaverStory>;
export const Dropzone = () => <DropzoneStory></DropzoneStory>;


text:
<?xml version="1.0" encoding="UTF-8"?>
<actions>
        <action>
            <actionName>CUSTOM-skipTests</actionName>
            <displayName>skipTests</displayName>
            <goals>
                <goal>clean</goal>
                <goal>install</goal>
            </goals>
            <properties>
                <skipTests>true</skipTests>
            </properties>
        </action>
    </actions>


text:
package com.weibo.lodil.mmap.wrap;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

import com.weibo.lodil.DictKey;
import com.weibo.lodil.DictValue;
import com.weibo.lodil.LOG;
import com.weibo.lodil.mmap.api.HugeElement;
import com.weibo.lodil.mmap.api.HugeElementType;
import com.weibo.lodil.mmap.model.Enumerated16FieldModel;

public class DictEntryImpl implements DictEntry, HugeElement<DictEntry>, Externalizable {

	DictKey key;
	DictValue value;

	public DictEntryImpl() {
	}

	public DictEntryImpl(final DictKey key, final DictValue value) {
		this.key = key;
		this.value = value;
	}

	public DictEntryImpl(final String key, final String value) {
		this();
		setKey(key);
		setValue(value);
	}

	public String getKey() {
		return key == null ? null : key.getString();
	}

	public DictKey getDictKey() {
		return key;
	}

	public void setKey(final String key) {
		this.key = new DictKey(key);
	}

	public String getValue() {
		return value == null ? null : value.getString();
	}

	public DictValue getDictValue() {
		return value;
	}

	public void setValue(final String value) {
		this.value = new DictValue(value);
	}

	public HugeElementType hugeElementType() {
		return HugeElementType.BeanImpl;
	}

	public void copyOf(final DictEntry t) {
		LOG.debug(t.toString());
		setKey(t.getKey());
		setValue(t.getValue());
	}

	public void index(final long n) {
		LOG.debug(this.toString() + " n:" + n);
		throw new UnsupportedOperationException();
	}

	public long index() {
		return -1;
	}

	@Override
	public int hashCode() {
		return getKeyValueString().hashCode();
	}

	public long longHashCode() {
		return hashCode();
	}

	protected String getKeyValueString() {
		return getKey() + connector + getValue();
	}

	private void initFromString(final String result) {
		final String[] parts = result.split(connector);

		assert parts.length == 2;

		this.key = new DictKey(parts[0]);
		this.value = new DictValue(parts[1]);
	}

	@Override
	public boolean equals(final Object o) {
		if (this == o) {
			return true;
		}
		if ((o == null) || !(o instanceof DictEntry)) {
			return false;
		}

		final DictEntry that = (DictEntry) o;

		return that.getKey().equals(getKey()) && that.getValue().equals(getValue());
	}

	public void writeExternal(final ObjectOutput out) throws IOException {
		Enumerated16FieldModel.write(out, String.class, getKeyValueString());
	}

	public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
		initFromString(Enumerated16FieldModel.read(in, String.class));
	}

	@Override
	public String toString() {
		return this.getClass() + ":" + getKeyValueString();
	}

	public void recycle() {
		key = null;
		value = null;
	}

}


text:
package org.semagrow.sevod.scraper.sparql;

/**
 * Created by antonis on 29/7/2016.
 */
public final class Queries {

    public final static String triples_count;
    public final static String subjects_count;
    public final static String predicates_count;
    public final static String objects_count;
    public final static String classes_count;
    public final static String entities_count;

    public final static String predicates;
    public final static String classes;

    public final static String subject_prefix;
    public final static String object_prefix;
    public final static String entity_prefix;

    public final static String graph_var;
    public final static String predicate_var;
    public final static String class_var;
    public final static String prefix_var;
    public final static String count_var;

    static {

        triples_count    = "select (count(*) as ?c) where { graph ?g { ?s ?p ?o } }";
        subjects_count   = "select (count(distinct ?s) as ?c) where { graph ?g { ?s ?p ?o } }";
        predicates_count = "select (count(distinct ?p) as ?c) where { graph ?g { ?s ?p ?o } }";
        objects_count    = "select (count(distinct ?o) as ?c) where { graph ?g { ?s ?p ?o } }";
        classes_count    = "select (count(distinct ?o) as ?c) where { graph ?g { ?s a ?o } }";
        entities_count   = "select (count(distinct ?s) as ?c) where { graph ?g { ?s a ?o } }";

        predicates = "select distinct ?p where { graph ?g { ?s ?p ?o } }";
        classes    = "select distinct ?o where { graph ?g { ?s a ?o } }";

        subject_prefix = "select * where { graph ?g { ?s ?p ?o . filter(strstarts(str(?s), ?z)) } } LIMIT 1";
        object_prefix  = "select * where { graph ?g { ?s ?p ?o . filter(strstarts(str(?o), ?z)) } } LIMIT 1";
        entity_prefix  = "select * where { graph ?g { ?s a ?o . filter(strstarts(str(?s), ?z)) } } LIMIT 1";

        graph_var = "?g";
        predicate_var = "?p";
        class_var = "?o";
        prefix_var = "?z";
        count_var = "?c";

    }
}


text:
// +build !ignore_autogenerated

// This file was autogenerated by deepcopy-gen. Do not edit it manually!

package v1alpha1

import (
	v1 "k8s.io/client-go/1.4/pkg/api/v1"
	conversion "k8s.io/client-go/1.4/pkg/conversion"
	runtime "k8s.io/client-go/1.4/pkg/runtime"
	reflect "reflect"
)

func init() {
	SchemeBuilder.Register(RegisterDeepCopies)
}

// RegisterDeepCopies adds deep-copy functions to the given scheme. Public
// to allow building arbitrary schemes.
func RegisterDeepCopies(scheme *runtime.Scheme) error {
	return scheme.AddGeneratedDeepCopyFuncs(
		conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_ImageReview, InType: reflect.TypeOf(&ImageReview{})},
		conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_ImageReviewContainerSpec, InType: reflect.TypeOf(&ImageReviewContainerSpec{})},
		conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_ImageReviewSpec, InType: reflect.TypeOf(&ImageReviewSpec{})},
		conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_ImageReviewStatus, InType: reflect.TypeOf(&ImageReviewStatus{})},
	)
}

func DeepCopy_v1alpha1_ImageReview(in interface{}, out interface{}, c *conversion.Cloner) error {
	{
		in := in.(*ImageReview)
		out := out.(*ImageReview)
		out.TypeMeta = in.TypeMeta
		if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil {
			return err
		}
		if err := DeepCopy_v1alpha1_ImageReviewSpec(&in.Spec, &out.Spec, c); err != nil {
			return err
		}
		out.Status = in.Status
		return nil
	}
}

func DeepCopy_v1alpha1_ImageReviewContainerSpec(in interface{}, out interface{}, c *conversion.Cloner) error {
	{
		in := in.(*ImageReviewContainerSpec)
		out := out.(*ImageReviewContainerSpec)
		out.Image = in.Image
		return nil
	}
}

func DeepCopy_v1alpha1_ImageReviewSpec(in interface{}, out interface{}, c *conversion.Cloner) error {
	{
		in := in.(*ImageReviewSpec)
		out := out.(*ImageReviewSpec)
		if in.Containers != nil {
			in, out := &in.Containers, &out.Containers
			*out = make([]ImageReviewContainerSpec, len(*in))
			for i := range *in {
				(*out)[i] = (*in)[i]
			}
		} else {
			out.Containers = nil
		}
		if in.Annotations != nil {
			in, out := &in.Annotations, &out.Annotations
			*out = make(map[string]string)
			for key, val := range *in {
				(*out)[key] = val
			}
		} else {
			out.Annotations = nil
		}
		out.Namespace = in.Namespace
		return nil
	}
}

func DeepCopy_v1alpha1_ImageReviewStatus(in interface{}, out interface{}, c *conversion.Cloner) error {
	{
		in := in.(*ImageReviewStatus)
		out := out.(*ImageReviewStatus)
		out.Allowed = in.Allowed
		out.Reason = in.Reason
		return nil
	}
}


text:
@interface bigViewCell : UITableViewCell
@property(nonatomic,strong)UIImageView *bigImgView;
@property(nonatomic,strong)UILabel *dataLabel;
@property(nonatomic,strong)UILabel *headLabel;

@end


text:
package com.intellij.json;

import com.intellij.codeInsight.editorActions.smartEnter.SmartEnterProcessor;
import com.intellij.codeInsight.editorActions.smartEnter.SmartEnterProcessors;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Editor;
import org.jetbrains.annotations.NotNull;

import java.util.List;

/**
 * @author Mikhail Golubev
 */
public class JsonSmartEnterTest extends JsonTestCase {
  public void doTest() {
    myFixture.configureByFile("smartEnter/" + getTestName(false) + ".json");
    final List<SmartEnterProcessor> processors = SmartEnterProcessors.INSTANCE.forKey(JsonLanguage.INSTANCE);
    new WriteCommandAction(myFixture.getProject()) {
      @Override
      protected void run(@NotNull Result result) throws Throwable {
        final Editor editor = myFixture.getEditor();
        for (SmartEnterProcessor processor : processors) {
          processor.process(myFixture.getProject(), editor, myFixture.getFile());
        }
      }
    }.execute();
    myFixture.checkResultByFile("smartEnter/" + getTestName(false) + "_after.json", true);
  }

  public void testCommaInsertedAfterArrayElement() {
    doTest();
  }

  public void testCommaInsertedAfterProperty() {
    doTest();
  }

  public void testCommaInsertedAfterPropertyWithMultilineValue() {
    doTest();
  }

  public void testColonInsertedAfterPropertyKey() {
    doTest();
  }
}


text:
ofxGifFile::ofxGifFile(){
    w = h = 0;
    lastDrawn = 0;
    frameIndex = 0;
}

ofxGifFile::~ofxGifFile(){}

void ofxGifFile::setup(int _w, int _h, vector<ofColor> _globalPalette, int _nPages){
    w               = _w;
    h               = _h;
    globalPalette   = _globalPalette;
    nPages          = _nPages;
}

// by now we're copying everything (no pointers)
void ofxGifFile::addFrame(ofPixels _px, int _left, int _top, bool useTexture, GifFrameDisposal disposal, float _duration){
    ofxGifFrame f;

    if(getNumFrames() == 0){
        accumPx = _px; // we assume 1st frame is fully drawn
        if ( !useTexture ){
            f.setUseTexture(false);
        }
        f.setFromPixels(_px , _left, _top, _duration);
		gifDuration = _duration;
    } else {
        // add new pixels to accumPx
        int cropOriginX = _left;
        int cropOriginY = _top;

        // [todo] make this loop only travel through _px, not accumPx
        for (int i = 0; i < accumPx.getWidth() * accumPx.getHeight(); i++) {
            int x = i % accumPx.getWidth();
            int y = i / accumPx.getWidth();

            if (x >= _left  && x < _left + _px.getWidth()  &&
                y >= _top   && y < _top  + _px.getHeight()){
                int cropX = x - cropOriginX;  //   (i - _left) % _px.getWidth();
                int cropY = y - cropOriginY;
                //int cropI = cropX + cropY * _px.getWidth();
                if ( _px.getColor(cropX, cropY).a == 0 ){
                    switch ( disposal ) {
                        case GIF_DISPOSAL_BACKGROUND:
                            _px.setColor(x,y,bgColor);
                            break;

                        case GIF_DISPOSAL_LEAVE:
                        case GIF_DISPOSAL_UNSPECIFIED:
                            _px.setColor(x,y,accumPx.getColor(cropX, cropY));
//                            accumPx.setColor(x,y,_px.getColor(cropX, cropY));
                            break;

                        case GIF_DISPOSAL_PREVIOUS:
                            _px.setColor(x,y,accumPx.getColor(cropX, cropY));
                            break;
                    }
                } else {
                    accumPx.setColor(x, y, _px.getColor(cropX, cropY) );
                }
            } else {
                if ( _px.getColor(x, y) == bgColor ){
                    switch ( disposal ) {
                        case GIF_DISPOSAL_BACKGROUND:
                            accumPx.setColor(x,y,bgColor);
                            break;

                        case GIF_DISPOSAL_UNSPECIFIED:
                        case GIF_DISPOSAL_LEAVE:
                            accumPx.setColor(x,y,_px.getColor(x, y));
                            break;

                        case GIF_DISPOSAL_PREVIOUS:
                            _px.setColor(x,y,accumPx.getColor(x, y));
                            break;
                    }
                } else {
                    accumPx.setColor(x, y, _px.getColor(x, y) );
                }
            }
        }

        if ( !useTexture ){
            f.setUseTexture(false);
        }
        f.setFromPixels(_px,_left, _top, _duration);
    }
    accumPx = _px;

    //
    gifFrames.push_back(f);
}

int ofxGifFile::getWidth(){
    return w;
}

int ofxGifFile::getHeight(){
    return h;
}

float ofxGifFile::getDuration(){
    return gifDuration;
}

void ofxGifFile::draw(float _x, float _y){
    if ( getNumFrames() == 0 ){
        ofLogWarning()<<"ofxGifFile::No frames to draw!";
        return;
    }
    if ( getNumFrames() == 0 ){
        ofLogWarning()<<"ofxGifFile::No frames to draw!";
        return;
    }
    // never drawn, lets kick off
    if ( lastDrawn == -1 ){
        lastDrawn = ofGetElapsedTimef();

    } else if ( ofGetElapsedTimef() - lastDrawn >= gifFrames[frameIndex].getDuration() ){
        frameIndex++;
        frameIndex %= getNumFrames();
    }
    drawFrame( frameIndex, _x, _y );
}

void ofxGifFile::draw(float _x, float _y, float _w, float _h){
    if ( getNumFrames() == 0 ){
        ofLogWarning()<<"ofxGifFile::No frames to draw!";
        return;
    }
    // never drawn, lets kick off
    if ( lastDrawn == -1 ){
        lastDrawn = ofGetElapsedTimef();
    } else if ( ofGetElapsedTimef() - lastDrawn >= gifFrames[frameIndex].getDuration() ){
        lastDrawn = ofGetElapsedTimef();
        frameIndex++;
        frameIndex %= getNumFrames();
    }
    drawFrame( frameIndex, _x, _y, _w, _h);
}

void ofxGifFile::drawFrame(int _frameNum, float _x, float _y){
    if(_frameNum < 0 || _frameNum >= gifFrames.size()){
        ofLog(OF_LOG_WARNING, "ofxGifFile::drawFrame frame out of bounds. not drawing");
        return;
    }
    gifFrames[_frameNum].draw(_x , _y , gifFrames[_frameNum].getWidth(), gifFrames[_frameNum].getHeight());
}

void ofxGifFile::drawFrame(int _frameNum, float _x, float _y, int _w, int _h){
    if(_frameNum < 0 || _frameNum >= gifFrames.size()){
        ofLog(OF_LOG_WARNING, "ofxGifFile::drawFrame frame out of bounds. not drawing");
        return;
    }
    gifFrames[_frameNum].draw(_x , _y , _w, _h);
}

void ofxGifFile::setBackgroundColor(ofColor _c) {
    bgColor = _c;
    cout<<bgColor<<endl;
}

ofColor ofxGifFile::getBackgroundColor() {
    return bgColor;
}

int ofxGifFile::getNumFrames() {
    return gifFrames.size();
}

ofxGifFrame * ofxGifFile::getFrameAt(int _index) {
    if ( _index < getNumFrames() ){
        return &(gifFrames[_index]); //??
    } else {
        ofLogWarning()<<"ofxGifFile:: trying to get frame that doesn't exist, returning NULL!";
        return NULL;
    }
}

vector <ofxGifFrame> & ofxGifFile::getFrames(){
    return gifFrames;
}

vector <ofColor> ofxGifFile::getPalette(){
    return globalPalette;
}

void ofxGifFile::clear() {
    gifFrames.clear();
    globalPalette.clear();
}


text:
using System;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Runtime.Serialization;

namespace MapperExpression.Exceptions
{
    /// <summary>
    /// Exception for real only property
    /// </summary>
    [Serializable]

    public class ReadOnlyPropertyException : MapperExceptionBase
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ReadOnlyPropertyException"/> class.
        /// </summary>
        /// <param name="property">The property.</param>
        public ReadOnlyPropertyException(PropertyInfo property)
            : base(ValidateParameter(property))
        {

        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ReadOnlyPropertyException"/> class.
        /// </summary>
        public ReadOnlyPropertyException()
        {

        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ReadOnlyPropertyException"/> class.
        /// </summary>
        /// <param name="serializer">The serializer.</param>
        /// <param name="context">The context.</param>
        protected ReadOnlyPropertyException(SerializationInfo serializer, StreamingContext context)
            :base(serializer, context)
        {

        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MapperExceptionBase"/> class.
        /// </summary>
        /// <param name="exceptionMessage">The exception message.</param>
        /// <param name="innerException">The inner exception.</param>
        public ReadOnlyPropertyException(string exceptionMessage, Exception innerException)
            : base(exceptionMessage,innerException)
        {

        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ReadOnlyPropertyException"/> class.
        /// </summary>
        /// <param name="exceptionMessage">The exception message.</param>
        public ReadOnlyPropertyException(string exceptionMessage)
            : base(exceptionMessage)
        {

        }
        private static string ValidateParameter(PropertyInfo property)
        {
            Contract.Requires(property != null);

            return "The destination property  '" + property.Name + "' is read-only";
        }
    }
}


text:
package org.apache.sis.util;

/**
 * Throws when a null argument has been given to a method that doesn't accept them.
 * This exception extends {@link NullPointerException} in order to stress out that
 * the error is an illegal argument rather than an unexpected usage of a null pointer
 * inside a method body.
 *
 *
API note:
 * We could argue that this exception should extend {@link IllegalArgumentException}.
 * However {@link NullPointerException} has become a more widely adopted practice and
 * is now the recommended one in the Effective Java book.

 *
 * @author Martin Desruisseaux (Geomatys)
 * @since   0.3
 * @version 0.3
 * @module
 *
 * @see ArgumentChecks#ensureNonNull(String, Object)
 */
public class NullArgumentException extends NullPointerException {
    /**
     * For cross-version compatibility.
     */
    private static final long serialVersionUID = 7924011726325288438L;

    /**
     * Constructs an exception with no detail message.
     */
    public NullArgumentException() {
        super();
    }

    /**
     * Constructs an exception with the specified detail message.
     *
     * @param message The detail message.
     */
    public NullArgumentException(final String message) {
        super(message);
    }
}


text:
using System.Collections.Generic;

namespace CrestSharp.Model
{
    public interface ICrestConstellation : ICrestNameIdObject
    {
        IVector3D Position { get; }

        ICrestRegion Region { get; }

        ICollection<ICrestSolarSystem> Systems { get; }
    }
}


text:
{% load humanize %}
{% load bootstrap3 %}
{% load mptt_tags %}
{% load i18n %}

{% recursetree comments %}

                 {{ node.name }}
                {{ node.submit_date|naturaltime }} | {% trans 'Respond' %}

                {{ node.text }}

            {% if not node.is_leaf_comment %}
                {{ children }}
            {% endif %}

{% endrecursetree %}

<form class="" id="comment-form" method="post">
    {% csrf_token %}
    {% bootstrap_form form %}
    <input type="submit" value="{% trans 'Submit comment' %}" class="btn btn-primary btn-lg btn-block"/>
</form>


text:
layout: portfolio_entry
name: rbbn
title: Rockband Bar Nights
categories:
- portfolio
tags: [Agency, Coding, Content Management, CSS, Drupal, HTML, ISITE Design, jQuery, PHP]
website: www.rockband.com/press/local-rules
project: Rockband Bar Nights Social Website
excerpt: Rock Band Bar Nights was a social site that managed venues that wanted to host a karaoke style Rock Band experience.

thumb-ext: jpg
thumb-alt: Home – rbbn.com
img-ext: jpg
img-alt: Home – rbbn.com

color-dark: 111
---
I worked with a PHP back-end coder to develop a custom website for Rockband. The site's purpose was to be a tool for bars to host Rockband themed events. It was built using Drupal and contained many custom templates, jQuery plugins, and admin customization to achieve the desired look and feel.

  Screen captures


text: from .feedback_view import feedback_view  # noqa


text:
from peyotl.api import PhylesystemAPI
pa = PhylesystemAPI(get_from='external')
print(pa.get('pg_10',
             tree_id='tree3',
             subtree_id='ingroup',
             format='newick'))


text:
package aos.data.structure5;
/**
 * An interface the supports a Map whose values are kept
 * in increasing order.  Values stored within an OrderedMap
 * should implement Comparable; ie. they should have an implemented
 * compareTo method.
 *
 * @see Table
 * @see java.lang.Comparable
 * @see java.lang.Comparable#compareTo
 * @version $Id: OrderedMap.java 35 2007-08-09 20:38:38Z bailey $
 * @author, 2001 duane a. bailey
 */
public interface OrderedMap<K extends Comparable<K>,V> extends Map<K,V>
{
}


text:
typedef enum
{
    transit         =0,
    driving         =1,
    walking         =2
} TransportMode;

@interface MapEntity : NSObject
@property(nonatomic,retain)NSString *sourceApplication;//应用名称。
@property(nonatomic,retain)NSString *backScheme;//第三方调回使用的 scheme,
@property(nonatomic,assign)CLLocationCoordinate2D origin;
@property(nonatomic,assign)CLLocationCoordinate2D destination;
@property(nonatomic,retain)NSString *originName;
@property(nonatomic,retain)NSString *destinationName;
@property(nonatomic,retain)NSString *destinationSubTitle;

+(NSArray *)checkHasOwnApp;
-(NSString *)callBaiduMapForPath:(TransportMode)mode native:(BOOL)callNative; //百度地图uri
-(NSString *)callAMapForPath:(TransportMode)mode native:(BOOL)callNative; //高德地图uri
-(NSString *)callGoogleMapForPath:(TransportMode)mode native:(BOOL)callNative;//google 地图uri
-(NSString *)callAppleMapForPath:(TransportMode)mode native:(BOOL)callNative;//苹果 地图uri

@end


text:
class QAction;
class QWidget;
class Core;
class CloudList;
class LayerList;
class FlatView;
class GLWidget;
class MainWindow;

class RadiusFilter : public IPlugin {
    Q_INTERFACES(IPlugin)
    Q_OBJECT
    Q_PLUGIN_METADATA(IID "za.co.circlingthesun.cloudclean.radiusfilter" FILE "radiusfilter.json")
 public:
    QString getName();
    void initialize(Core * core);
    void cleanup();
    ~RadiusFilter();

 signals:
   void enabling();

 private slots:
    void enable();
    void disable();
    void filter();

 private:
    Core * core_;
    CloudList * cl_;
    LayerList * ll_;
    GLWidget * glwidget_;
    FlatView * flatview_;
    MainWindow * mw_;

    QAction * enable_;
    QWidget * settings_;
    bool is_enabled_;

    float radius_;
};

#endif  // RADIUSFILTER_H


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Coffee_Maker
{
    class Program
    {
        static void Main(string[] args)
        {
            int n1 = int.Parse(Console.ReadLine());
            int n2 = int.Parse(Console.ReadLine());
            int n3 = int.Parse(Console.ReadLine());
            int n4 = int.Parse(Console.ReadLine());
            int n5 = int.Parse(Console.ReadLine());
            double a = double.Parse(Console.ReadLine());
            double p = double.Parse(Console.ReadLine());

            double inMachine = n1 * 0.05 + n2 * 0.10 + n3 * 0.20 + n4 * 0.50 + n5 * 1.00;

            if (a >= p)
            {
                double change = a - p;
                if (change <= inMachine)
                {
                    Console.WriteLine("Yes there is change {0:F2}", inMachine - change);
                }
                else
                {
                    Console.WriteLine("No there is no change {0:F2}",inMachine );
                }
            }

        }
    }
}


text:
package com.ibm.g11n.pipeline.tools.cli;

import java.util.HashSet;
import java.util.Set;

import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.ibm.g11n.pipeline.client.NewDocumentData;
import com.ibm.g11n.pipeline.client.ServiceException;

/**
 * Creates a new document for translation.
 *
 * @author John Emmons
 */
@Parameters(commandDescription = "Creates a new document for translation.")
final class CreateDocumentCmd extends DocumentCmd {
    @Parameter(
            names = {"-l", "--language"},
            description = "Language ID(s) separted by comma. "
                        + "The first element will be used as source language",
            required = true)
    private String languageIds;

    @Override
    protected void _execute() {
        String[] langs = languageIds.split(",");
        NewDocumentData newDocumentData = new NewDocumentData(langs[0].trim());
        if (langs.length > 1) {
            Set<String> targetLangs = new HashSet<String>(langs.length - 1);
            for (int i = 1; i < langs.length; i++) {
                targetLangs.add(langs[i].trim());
            }
            newDocumentData.setTargetLanguages(targetLangs);
        }

        try {
            getClient().createDocument(type, documentId, newDocumentData);
        } catch (ServiceException e) {
            throw new RuntimeException(e);
        }

        System.out.println("A new document '" + documentId + "' was successfully created.");
    }
}


text:
package controllers

import javax.inject.Inject

import com.mohiva.play.silhouette.api.exceptions.{ConfigurationException, ProviderException}
import com.mohiva.play.silhouette.api.services.AuthInfoService
import com.mohiva.play.silhouette.api.util.Credentials
import com.mohiva.play.silhouette.api.{Environment, LoginEvent, Silhouette}
import com.mohiva.play.silhouette.impl
import com.mohiva.play.silhouette.impl.authenticators.JWTAuthenticator
import com.mohiva.play.silhouette.impl.exceptions.IdentityNotFoundException
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import models.User
import models.services.UserService
import play.api.i18n.Messages
import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.mvc.Action

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

/**
 * The credentials auth controller.
 *
 * @param env The Silhouette environment.
 */
class CredentialsAuthController @Inject() (
  implicit val env: Environment[User, JWTAuthenticator],
  val userService: UserService,
  val authInfoService: AuthInfoService)
  extends Silhouette[User, JWTAuthenticator] {

  /**
   * Converts the JSON into a [[impl.providers.OAuth2Info]] object.
   */
  implicit val credentialsReads = (
    (__ \ 'email).read[String] and
    (__ \ 'password).read[String]
  )(Credentials.apply _)

  /**
   * Authenticates a user against the credentials provider.
   *
   * @return The result to display.
   */
  def authenticate = Action.async(parse.json) { implicit request =>
    request.body.validate[Credentials].map { credentials =>
      (env.providers.get(CredentialsProvider.ID) match {
        case Some(p: CredentialsProvider) => p.authenticate(credentials)
        case _ => Future.failed(new ConfigurationException(s"Cannot find credentials provider"))
      }).flatMap { loginInfo =>
        userService.retrieve(loginInfo).flatMap {
          case Some(user) => env.authenticatorService.create(user.loginInfo).flatMap { authenticator =>
            env.eventBus.publish(LoginEvent(user, request, request2lang))
            env.authenticatorService.init(authenticator).flatMap { token =>
              Future.successful(Ok(Json.obj("token" -> token)))
            }
          }
          case None => Future.failed(new IdentityNotFoundException("Couldn't find user"))
        }
      }.recover {
        case e: ProviderException => Unauthorized(Json.obj("message" -> Messages("invalid.credentials")))
      }
    }.recoverTotal {
      case error =>
        Future.successful(Unauthorized(Json.obj("message" -> Messages("invalid.credentials"))))
    }
  }
}


text:
package com.google.logging.v2;

import com.google.common.base.Preconditions;
import com.google.api.pathtemplate.PathTemplate;
import com.google.api.resourcenames.ResourceName;
import com.google.api.resourcenames.ResourceNameType;
import java.io.IOException;
import java.util.Map;

// AUTO-GENERATED DOCUMENTATION AND CLASS
@javax.annotation.Generated("by GAPIC protoc plugin")
public class BillingLogName implements ResourceName {

  private static final PathTemplate PATH_TEMPLATE =
      PathTemplate.createWithoutUrlEncoding("billingAccounts/{billing_account}/logs/{log}");

  private final String billingAccount;
  private final String log;

  public String getBillingAccount() {
    return billingAccount;
  }

  public String getLog() {
    return log;
  }

  public static Builder newBuilder() {
    return new Builder();
  }

  public Builder toBuilder() {
    return new Builder(this);
  }

  private BillingLogName(Builder builder) {
    billingAccount = Preconditions.checkNotNull(builder.getBillingAccount());
    log = Preconditions.checkNotNull(builder.getLog());
  }

  public static BillingLogName create(String billingAccount, String log) {
    return newBuilder()
      .setBillingAccount(billingAccount)
      .setLog(log)
      .build();
  }

  public static BillingLogName parse(String formattedString) {
    Map<String, String> matchMap =
        PATH_TEMPLATE.validatedMatch(formattedString, "BillingLogName.parse: formattedString not in valid format");
    return create(matchMap.get("billing_account"), matchMap.get("log"));
  }

  public static boolean isParsableFrom(String formattedString) {
    return PATH_TEMPLATE.matches(formattedString);
  }

  @Override
  public ResourceNameType getType() {
    return BillingLogNameType.instance();
  }

  @Override
  public String toString() {
    return PATH_TEMPLATE.instantiate("billing_account", billingAccount, "log", log);
  }

  /** Builder for BillingLogName. */
  public static class Builder {

    private String billingAccount;
    private String log;

    public String getBillingAccount() {
      return billingAccount;
    }

    public String getLog() {
      return log;
    }

    public Builder setBillingAccount(String billingAccount) {
      this.billingAccount = billingAccount;
      return this;
    }

    public Builder setLog(String log) {
      this.log = log;
      return this;
    }

    private Builder() {
    }

    private Builder(BillingLogName billingLogName) {
      billingAccount = billingLogName.billingAccount;
      log = billingLogName.log;
    }

    public BillingLogName build() {
      return new BillingLogName(this);
    }
  }

  @Override
  public boolean equals(Object o) {
    if (o == this) {
      return true;
    }
    if (o instanceof BillingLogName) {
      BillingLogName that = (BillingLogName) o;
      return (this.billingAccount.equals(that.billingAccount))
          && (this.log.equals(that.log));
    }
    return false;
  }

  @Override
  public int hashCode() {
    int h = 1;
    h *= 1000003;
    h ^= billingAccount.hashCode();
    h *= 1000003;
    h ^= log.hashCode();
    return h;
  }
}


text:
package jkm.cineclub.raft

import jkm.cineclub.raft.PersistentState._
import com.typesafe.config.{ConfigFactory, Config, ConfigValue}
import scala.collection.JavaConversions._

/**
 * Created with IntelliJ IDEA.
 * User: cineclub
 * Date: 12/26/13
 * Time: 9:04 PM
 * To change this template use File | Settings | File Templates.
 */
class RaftConfig {
  import RaftConfig._
  var id:RaftMemberId=null
  var serviceAddress:TcpAddress=null

  var persistentStateDBInfo:DBInfo=null
  var logEntryDBInfo:DBInfo=null

  var membership:RaftMembership=null
  var addressTable:Map[RaftMemberId,TcpAddress]=null

  var electionTimeout:Int = -1
}
object RaftConfig {
  case class TcpAddress(hostname:String,port:Int)
  case class DBInfo(dbName:String,dbRootPath:String) {
    override def toString=  "("+"dbName="+dbName+","+"dbRootPath="+dbRootPath+")"
  }

  def convertToTcpAddress(a:ConfigValue): TcpAddress= {
    val address=a.unwrapped().asInstanceOf[java.util.ArrayList[Object]].toList
    val hostname=address(0).asInstanceOf[String]
    val port = address(1).asInstanceOf[Int]
    TcpAddress(hostname,port)
  }

  implicit def convertConfigToTcpAddress(a:Config): TcpAddress= {
    val hostname=a.getString("hostname")
    val port = a.getInt("port")
    TcpAddress(hostname,port)
  }

  implicit def convertConfigToDBInfo(a:Config):DBInfo = {
    val dbName=a.getString("dbName")
    var dbRootPath=a.getString("rootPath")
    if (dbRootPath.isEmpty) dbRootPath=null
    DBInfo(dbName,dbRootPath)
  }

  def getRaftMembership(a:Config):RaftMembership={
    RaftMembership(
      RaftMembership.getConfigType(a.getString("configType")),
      a.getStringList("newMembers").toList ,
      a.getStringList("oldMembers").toList )
  }

  def readConfig(configName:String,prefix:String):RaftConfig ={
    val conf=ConfigFactory.load(configName)
    if (conf==null) return null

    val raftConfig=new RaftConfig

    def addPrefix(path:String) =prefix+"."+ path

    raftConfig.id=conf.getString(addPrefix("id"))
    raftConfig.serviceAddress=conf.getConfig(addPrefix("serviceAddress"))
    raftConfig.persistentStateDBInfo=conf.getConfig(addPrefix("persistentStateDB"))
    raftConfig.logEntryDBInfo=conf.getConfig(addPrefix("logEntryDB"))
    raftConfig.membership=getRaftMembership(conf.getConfig(addPrefix("init.membership")))
    raftConfig.addressTable=conf.getConfig(addPrefix("init.addressTable")).entrySet().toList.map( x=> (x.getKey,convertToTcpAddress(x.getValue))).toMap
    raftConfig.electionTimeout=conf.getInt( addPrefix("init.electionTimeout"))
    raftConfig
  }

  def printRaftConfig(raftConfig:RaftConfig) ={
    println("id="+raftConfig.id)
    println("serverAddress="+raftConfig.serviceAddress)
    println("persistentStateDBInfo="+raftConfig.persistentStateDBInfo)
    println("logEntryDBInfo="+raftConfig.logEntryDBInfo)
    println("members="+raftConfig.membership)
    println("addressTable="+raftConfig.addressTable)
    println("electionTimeout="+raftConfig.electionTimeout)
  }

}


text:
/*
*
* InstallPluginPopup
*
*/

import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { Modal, ModalHeader, ModalBody } from 'reactstrap';
import { map } from 'lodash';
import cn from 'classnames';

import Official from '../Official';
// import StarsContainer from 'components/StarsContainer';

import styles from './styles.scss';

class InstallPluginPopup extends React.Component {
  handleClick = () => {
    this.props.history.push({ pathname: this.props.history.location.pathname });

    if (!this.props.isAlreadyInstalled) {
      this.context.downloadPlugin(this.props.plugin.id);
    }
  }

  toggle = () => {
    this.props.history.push({
      pathname: this.props.history.location.pathname,
    });
  }

  navLinks = [
    {
      content: 'app.components.InstallPluginPopup.navLink.description',
      name: 'description',
    },
    {
      content: 'app.components.InstallPluginPopup.navLink.screenshots',
      name: 'screenshots',
    },
    {
      content: 'app.components.InstallPluginPopup.navLink.avis',
      name: 'avis',
    },
    {
      content: 'app.components.InstallPluginPopup.navLink.faq',
      name: 'faq',
    },
    {
      content: 'app.components.InstallPluginPopup.navLink.changelog',
      name: 'changelog',
    },
  ];

  render() {
    const descriptions = {
      short: this.props.plugin.id === 'support-us' ? <FormattedMessage id={this.props.plugin.description.short} /> : this.props.plugin.description.short,
      long: this.props.plugin.id === 'support-us' ? <FormattedMessage id={this.props.plugin.description.long || this.props.plugin.description.short} /> : this.props.plugin.description.long || this.props.plugin.description.short,
    };
    const buttonName = this.props.isAlreadyInstalled ? 'app.components.PluginCard.Button.label.install' : 'app.components.InstallPluginPopup.downloads';

    return (
      <Modal isOpen={this.props.isOpen} toggle={this.toggle} className={styles.modalPosition}>
        <ModalHeader toggle={this.toggle} className={styles.modalHeader} />
        <ModalBody className={styles.modalBody}>

<img src={`${this.props.plugin.logo}`} alt="icon" />

{this.props.plugin.name}

                  {/*}
                  <StarsContainer ratings={this.props.plugin.ratings} />

                    {this.props.plugin.ratings}
                    /5

                  */}
                  <Official style={{ marginTop: '0' }} />

                  {descriptions.short}

                    <i className={`fa fa-${this.props.plugin.isCompatible ? 'check' : 'times'}`} />
                    <FormattedMessage id={`app.components.PluginCard.compatible${this.props.plugin.id === 'support-us' ? 'Community' : ''}`} />

                      {/*}
                      +{this.props.plugin.downloads_nb}k <FormattedMessage id="app.components.InstallPluginPopup.downloads" />
                      */}

                        <FormattedMessage id={buttonName} />

                      {/* Uncomment whebn prices are running}

{this.props.plugin.price} €

                    */}

            {map(this.navLinks, link => {
              const isActive = this.props.history.location.hash.split('::')[1] === link.name;

              return (

 {
                    if (link.name === 'description') {
                      this.props.history.push({ pathname: this.props.history.location.pathname, hash: `${this.props.plugin.id}::${link.name}` });
                    }
                  }}
                  style={isActive ? { paddingTop: '4px'} : { paddingTop: '6px' }}
                >
                  <FormattedMessage id={link.content} />

              );
            })}

            {descriptions.long}

        </ModalBody>
      </Modal>
    );
  }
}

InstallPluginPopup.contextTypes = {
  downloadPlugin: PropTypes.func.isRequired,
};

InstallPluginPopup.defaultProps = {
  description: {
    short: 'app.Components.InstallPluginPopup.noDescription',
  },
};

InstallPluginPopup.propTypes = {
  description: PropTypes.shape({
    long: PropTypes.string,
    short: PropTypes.string,
  }),
  history: PropTypes.object.isRequired,
  isAlreadyInstalled: PropTypes.bool.isRequired,
  isOpen: PropTypes.bool.isRequired,
  plugin: PropTypes.object.isRequired,
};

export default InstallPluginPopup;


text:
#include "stromx/runtime/DataContainer.h"
#include "stromx/runtime/Recycler.h"
#include "stromx/runtime/impl/DataContainerImpl.h"

namespace stromx
{
    namespace runtime
    {
        DataContainer::DataContainer(Data* data)
          : m_impl(new impl::DataContainerImpl(data))
        {
        }

        bool operator==(const runtime::DataContainer& lhs, const runtime::DataContainer& rhs)
        {
            if(! lhs.m_impl.get() && ! rhs.m_impl.get())
                return true;

            if(! lhs.m_impl.get() || ! rhs.m_impl.get())
                return false;

            return lhs.m_impl->data() == rhs.m_impl->data();
        }

        bool operator!=(const runtime::DataContainer& lhs, const runtime::DataContainer& rhs)
        {
            return ! (lhs == rhs);
        }

        std::ostream& operator<<(std::ostream& out, const runtime::DataContainer& container)
        {
            if(! container.m_impl.get())
                out << 0;
            else
                out << container.m_impl->data();

            return out;
        }
    }
}


text:
package org.bremersee.profile.domain.acls.model;

import org.bremersee.common.security.acls.model.ObjectIdentityRetrievalStrategyInterceptor;
import org.bremersee.common.security.acls.model.ObjectIdentityUtils;
import org.bremersee.profile.domain.ldap.entity.RoleLdap;
import org.bremersee.profile.model.RoleDto;
import org.springframework.security.acls.domain.IdentityUnavailableException;
import org.springframework.security.acls.domain.ObjectIdentityImpl;
import org.springframework.security.acls.model.ObjectIdentity;
import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * @author Christian Bremer
 */
@Component("roleAclInterceptor")
public class RoleInterceptor implements ObjectIdentityRetrievalStrategyInterceptor {

    @Override
    public boolean supportsType(final String type) {
        return ObjectIdentityUtils.supportsAclType(type, RoleDto.TYPE_ID, RoleDto.class.getName(),
                RoleDto.class.getSimpleName(),
                RoleLdap.class.getName(), RoleLdap.class.getSimpleName());
    }

    @Override
    public boolean supportsDomainObject(final Object domainObject) {
        return domainObject != null && supportsType(domainObject.getClass().getName());
    }

    @Override
    public ObjectIdentity getObjectIdentity(final Object domainObject) {
        if (domainObject instanceof RoleDto) {
            return new ObjectIdentityImpl(RoleDto.TYPE_ID, ((RoleDto) domainObject).getName());
        }
        throw new IdentityUnavailableException("Domain object [" + domainObject + "] is not a role.");
    }

    @Override
    public ObjectIdentity createObjectIdentity(final Serializable id, final String type) {
        return new ObjectIdentityImpl(type, id.toString());
    }
}


text:
(function() {
    'use strict';

    function listEpisodesCompactDirective() {
        return {
            restrict: 'A',
            templateUrl: '/views/directives/episodes/list-episodes-compact-directive'
        };
    }

    angular.module('app')
        .directive('listEpisodesCompact', [listEpisodesCompactDirective]);
}());


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>concurrent.futures._base — ArcherBashPYDocs 1.0.0. documentation</title>

  <link href='https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic|Roboto+Slab:400,700|Inconsolata:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>

    <link rel="stylesheet" href="../../../_static/css/theme.css" type="text/css" />

    <link rel="top" title="ArcherBashPYDocs 1.0.0. documentation" href="../../../index.html"/>
        <link rel="up" title="Module code" href="../../index.html"/>

           ArcherBashPYDocs

  <form id="rtd-search-form" class="wy-form" action="../../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

        ArcherBashPYDocs

Docs »

Module code »

concurrent.futures._base

Source code for concurrent.futures._base

# Copyright 2009 Brian Quinlan. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

__author__ = 'Brian Quinlan (brian@sweetapp.com)'

import collections
import logging
import threading
import time

FIRST_COMPLETED = 'FIRST_COMPLETED'
FIRST_EXCEPTION = 'FIRST_EXCEPTION'
ALL_COMPLETED = 'ALL_COMPLETED'
_AS_COMPLETED = '_AS_COMPLETED'

# Possible future states (for internal use by the futures package).
PENDING = 'PENDING'
RUNNING = 'RUNNING'
# The future was cancelled by the user...
CANCELLED = 'CANCELLED'
# ...and _Waiter.add_cancelled() was called by a worker.
CANCELLED_AND_NOTIFIED = 'CANCELLED_AND_NOTIFIED'
FINISHED = 'FINISHED'

_FUTURE_STATES = [
    PENDING,
    RUNNING,
    CANCELLED,
    CANCELLED_AND_NOTIFIED,
    FINISHED
]

_STATE_TO_DESCRIPTION_MAP = {
    PENDING: "pending",
    RUNNING: "running",
    CANCELLED: "cancelled",
    CANCELLED_AND_NOTIFIED: "cancelled",
    FINISHED: "finished"
}

# Logger for internal use by the futures package.
LOGGER = logging.getLogger("concurrent.futures")

class Error(Exception):
    """Base class for all future-related exceptions."""
    pass

[docs]class CancelledError(Error):
    """The Future was cancelled."""
    pass

[docs]class TimeoutError(Error):
    """The operation exceeded the given deadline."""
    pass

class _Waiter(object):
    """Provides the event that wait() and as_completed() block on."""
    def __init__(self):
        self.event = threading.Event()
        self.finished_futures = []

    def add_result(self, future):
        self.finished_futures.append(future)

    def add_exception(self, future):
        self.finished_futures.append(future)

    def add_cancelled(self, future):
        self.finished_futures.append(future)

class _AsCompletedWaiter(_Waiter):
    """Used by as_completed()."""

    def __init__(self):
        super(_AsCompletedWaiter, self).__init__()
        self.lock = threading.Lock()

    def add_result(self, future):
        with self.lock:
            super(_AsCompletedWaiter, self).add_result(future)
            self.event.set()

    def add_exception(self, future):
        with self.lock:
            super(_AsCompletedWaiter, self).add_exception(future)
            self.event.set()

    def add_cancelled(self, future):
        with self.lock:
            super(_AsCompletedWaiter, self).add_cancelled(future)
            self.event.set()

class _FirstCompletedWaiter(_Waiter):
    """Used by wait(return_when=FIRST_COMPLETED)."""

    def add_result(self, future):
        super().add_result(future)
        self.event.set()

    def add_exception(self, future):
        super().add_exception(future)
        self.event.set()

    def add_cancelled(self, future):
        super().add_cancelled(future)
        self.event.set()

class _AllCompletedWaiter(_Waiter):
    """Used by wait(return_when=FIRST_EXCEPTION and ALL_COMPLETED)."""

    def __init__(self, num_pending_calls, stop_on_exception):
        self.num_pending_calls = num_pending_calls
        self.stop_on_exception = stop_on_exception
        self.lock = threading.Lock()
        super().__init__()

    def _decrement_pending_calls(self):
        with self.lock:
            self.num_pending_calls -= 1
            if not self.num_pending_calls:
                self.event.set()

    def add_result(self, future):
        super().add_result(future)
        self._decrement_pending_calls()

    def add_exception(self, future):
        super().add_exception(future)
        if self.stop_on_exception:
            self.event.set()
        else:
            self._decrement_pending_calls()

    def add_cancelled(self, future):
        super().add_cancelled(future)
        self._decrement_pending_calls()

class _AcquireFutures(object):
    """A context manager that does an ordered acquire of Future conditions."""

    def __init__(self, futures):
        self.futures = sorted(futures, key=id)

    def __enter__(self):
        for future in self.futures:
            future._condition.acquire()

    def __exit__(self, *args):
        for future in self.futures:
            future._condition.release()

def _create_and_install_waiters(fs, return_when):
    if return_when == _AS_COMPLETED:
        waiter = _AsCompletedWaiter()
    elif return_when == FIRST_COMPLETED:
        waiter = _FirstCompletedWaiter()
    else:
        pending_count = sum(
                f._state not in [CANCELLED_AND_NOTIFIED, FINISHED] for f in fs)

        if return_when == FIRST_EXCEPTION:
            waiter = _AllCompletedWaiter(pending_count, stop_on_exception=True)
        elif return_when == ALL_COMPLETED:
            waiter = _AllCompletedWaiter(pending_count, stop_on_exception=False)
        else:
            raise ValueError("Invalid return condition: %r" % return_when)

    for f in fs:
        f._waiters.append(waiter)

    return waiter

def as_completed(fs, timeout=None):
    """An iterator over the given futures that yields each as it completes.

    Args:
        fs: The sequence of Futures (possibly created by different Executors) to
            iterate over.
        timeout: The maximum number of seconds to wait. If None, then there
            is no limit on the wait time.

    Returns:
        An iterator that yields the given Futures as they complete (finished or
        cancelled). If any given Futures are duplicated, they will be returned
        once.

    Raises:
        TimeoutError: If the entire result iterator could not be generated
            before the given timeout.
    """
    if timeout is not None:
        end_time = timeout + time.time()

    fs = set(fs)
    with _AcquireFutures(fs):
        finished = set(
                f for f in fs
                if f._state in [CANCELLED_AND_NOTIFIED, FINISHED])
        pending = fs - finished
        waiter = _create_and_install_waiters(fs, _AS_COMPLETED)

    try:
        yield from finished

        while pending:
            if timeout is None:
                wait_timeout = None
            else:
                wait_timeout = end_time - time.time()
                if wait_timeout < 0:
                    raise TimeoutError(
                            '%d (of %d) futures unfinished' % (
                            len(pending), len(fs)))

            waiter.event.wait(wait_timeout)

            with waiter.lock:
                finished = waiter.finished_futures
                waiter.finished_futures = []
                waiter.event.clear()

            for future in finished:
                yield future
                pending.remove(future)

    finally:
        for f in fs:
            with f._condition:
                f._waiters.remove(waiter)

DoneAndNotDoneFutures = collections.namedtuple(
        'DoneAndNotDoneFutures', 'done not_done')
def wait(fs, timeout=None, return_when=ALL_COMPLETED):
    """Wait for the futures in the given sequence to complete.

    Args:
        fs: The sequence of Futures (possibly created by different Executors) to
            wait upon.
        timeout: The maximum number of seconds to wait. If None, then there
            is no limit on the wait time.
        return_when: Indicates when this function should return. The options
            are:

            FIRST_COMPLETED - Return when any future finishes or is
                              cancelled.
            FIRST_EXCEPTION - Return when any future finishes by raising an
                              exception. If no future raises an exception
                              then it is equivalent to ALL_COMPLETED.
            ALL_COMPLETED -   Return when all futures finish or are cancelled.

    Returns:
        A named 2-tuple of sets. The first set, named 'done', contains the
        futures that completed (is finished or cancelled) before the wait
        completed. The second set, named 'not_done', contains uncompleted
        futures.
    """
    with _AcquireFutures(fs):
        done = set(f for f in fs
                   if f._state in [CANCELLED_AND_NOTIFIED, FINISHED])
        not_done = set(fs) - done

        if (return_when == FIRST_COMPLETED) and done:
            return DoneAndNotDoneFutures(done, not_done)
        elif (return_when == FIRST_EXCEPTION) and done:
            if any(f for f in done
                   if not f.cancelled() and f.exception() is not None):
                return DoneAndNotDoneFutures(done, not_done)

        if len(done) == len(fs):
            return DoneAndNotDoneFutures(done, not_done)

        waiter = _create_and_install_waiters(fs, return_when)

    waiter.event.wait(timeout)
    for f in fs:
        with f._condition:
            f._waiters.remove(waiter)

    done.update(waiter.finished_futures)
    return DoneAndNotDoneFutures(done, set(fs) - done)

class Future(object):
    """Represents the result of an asynchronous computation."""

    def __init__(self):
        """Initializes the future. Should not be called by clients."""
        self._condition = threading.Condition()
        self._state = PENDING
        self._result = None
        self._exception = None
        self._waiters = []
        self._done_callbacks = []

    def _invoke_callbacks(self):
        for callback in self._done_callbacks:
            try:
                callback(self)
            except Exception:
                LOGGER.exception('exception calling callback for %r', self)

    def __repr__(self):
        with self._condition:
            if self._state == FINISHED:
                if self._exception:
                    return '<Future at %s state=%s raised %s>' % (
                        hex(id(self)),
                        _STATE_TO_DESCRIPTION_MAP[self._state],
                        self._exception.__class__.__name__)
                else:
                    return '<Future at %s state=%s returned %s>' % (
                        hex(id(self)),
                        _STATE_TO_DESCRIPTION_MAP[self._state],
                        self._result.__class__.__name__)
            return '<Future at %s state=%s>' % (
                    hex(id(self)),
                   _STATE_TO_DESCRIPTION_MAP[self._state])

    def cancel(self):
        """Cancel the future if possible.

        Returns True if the future was cancelled, False otherwise. A future
        cannot be cancelled if it is running or has already completed.
        """
        with self._condition:
            if self._state in [RUNNING, FINISHED]:
                return False

            if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
                return True

            self._state = CANCELLED
            self._condition.notify_all()

        self._invoke_callbacks()
        return True

    def cancelled(self):
        """Return True if the future was cancelled."""
        with self._condition:
            return self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]

    def running(self):
        """Return True if the future is currently executing."""
        with self._condition:
            return self._state == RUNNING

    def done(self):
        """Return True of the future was cancelled or finished executing."""
        with self._condition:
            return self._state in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED]

    def __get_result(self):
        if self._exception:
            raise self._exception
        else:
            return self._result

    def add_done_callback(self, fn):
        """Attaches a callable that will be called when the future finishes.

        Args:
            fn: A callable that will be called with this future as its only
                argument when the future completes or is cancelled. The callable
                will always be called by a thread in the same process in which
                it was added. If the future has already completed or been
                cancelled then the callable will be called immediately. These
                callables are called in the order that they were added.
        """
        with self._condition:
            if self._state not in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED]:
                self._done_callbacks.append(fn)
                return
        fn(self)

    def result(self, timeout=None):
        """Return the result of the call that the future represents.

        Args:
            timeout: The number of seconds to wait for the result if the future
                isn't done. If None, then there is no limit on the wait time.

        Returns:
            The result of the call that the future represents.

        Raises:
            CancelledError: If the future was cancelled.
            TimeoutError: If the future didn't finish executing before the given
                timeout.
            Exception: If the call raised then that exception will be raised.
        """
        with self._condition:
            if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
                raise CancelledError()
            elif self._state == FINISHED:
                return self.__get_result()

            self._condition.wait(timeout)

            if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
                raise CancelledError()
            elif self._state == FINISHED:
                return self.__get_result()
            else:
                raise TimeoutError()

    def exception(self, timeout=None):
        """Return the exception raised by the call that the future represents.

        Args:
            timeout: The number of seconds to wait for the exception if the
                future isn't done. If None, then there is no limit on the wait
                time.

        Returns:
            The exception raised by the call that the future represents or None
            if the call completed without raising.

        Raises:
            CancelledError: If the future was cancelled.
            TimeoutError: If the future didn't finish executing before the given
                timeout.
        """

        with self._condition:
            if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
                raise CancelledError()
            elif self._state == FINISHED:
                return self._exception

            self._condition.wait(timeout)

            if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
                raise CancelledError()
            elif self._state == FINISHED:
                return self._exception
            else:
                raise TimeoutError()

    # The following methods should only be used by Executors and in tests.
    def set_running_or_notify_cancel(self):
        """Mark the future as running or process any cancel notifications.

        Should only be used by Executor implementations and unit tests.

        If the future has been cancelled (cancel() was called and returned
        True) then any threads waiting on the future completing (though calls
        to as_completed() or wait()) are notified and False is returned.

        If the future was not cancelled then it is put in the running state
        (future calls to running() will return True) and True is returned.

        This method should be called by Executor implementations before
        executing the work associated with this future. If this method returns
        False then the work should not be executed.

        Returns:
            False if the Future was cancelled, True otherwise.

        Raises:
            RuntimeError: if this method was already called or if set_result()
                or set_exception() was called.
        """
        with self._condition:
            if self._state == CANCELLED:
                self._state = CANCELLED_AND_NOTIFIED
                for waiter in self._waiters:
                    waiter.add_cancelled(self)
                # self._condition.notify_all() is not necessary because
                # self.cancel() triggers a notification.
                return False
            elif self._state == PENDING:
                self._state = RUNNING
                return True
            else:
                LOGGER.critical('Future %s in unexpected state: %s',
                                id(self),
                                self._state)
                raise RuntimeError('Future in unexpected state')

    def set_result(self, result):
        """Sets the return value of work associated with the future.

        Should only be used by Executor implementations and unit tests.
        """
        with self._condition:
            self._result = result
            self._state = FINISHED
            for waiter in self._waiters:
                waiter.add_result(self)
            self._condition.notify_all()
        self._invoke_callbacks()

    def set_exception(self, exception):
        """Sets the result of the future as being the given exception.

        Should only be used by Executor implementations and unit tests.
        """
        with self._condition:
            self._exception = exception
            self._state = FINISHED
            for waiter in self._waiters:
                waiter.add_exception(self)
            self._condition.notify_all()
        self._invoke_callbacks()

class Executor(object):
    """This is an abstract base class for concrete asynchronous executors."""

    def submit(self, fn, *args, **kwargs):
        """Submits a callable to be executed with the given arguments.

        Schedules the callable to be executed as fn(*args, **kwargs) and returns
        a Future instance representing the execution of the callable.

        Returns:
            A Future representing the given call.
        """
        raise NotImplementedError()

    def map(self, fn, *iterables, timeout=None):
        """Returns a iterator equivalent to map(fn, iter).

        Args:
            fn: A callable that will take as many arguments as there are
                passed iterables.
            timeout: The maximum number of seconds to wait. If None, then there
                is no limit on the wait time.

        Returns:
            An iterator equivalent to: map(func, *iterables) but the calls may
            be evaluated out-of-order.

        Raises:
            TimeoutError: If the entire result iterator could not be generated
                before the given timeout.
            Exception: If fn(*args) raises for any values.
        """
        if timeout is not None:
            end_time = timeout + time.time()

        fs = [self.submit(fn, *args) for args in zip(*iterables)]

        # Yield must be hidden in closure so that the futures are submitted
        # before the first iterator value is required.
        def result_iterator():
            try:
                for future in fs:
                    if timeout is None:
                        yield future.result()
                    else:
                        yield future.result(end_time - time.time())
            finally:
                for future in fs:
                    future.cancel()
        return result_iterator()

    def shutdown(self, wait=True):
        """Clean-up the resources associated with the Executor.

        It is safe to call this method several times. Otherwise, no other
        methods can be called after this one.

        Args:
            wait: If True then shutdown will not return until all running
                futures have finished executing and the resources used by the
                executor have been reclaimed.
        """
        pass

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.shutdown(wait=True)
        return False

        © Copyright 2015, Weldon Henson.

  Built with Sphinx using a theme provided by Read the Docs.


text:
package br.com.cast.treinamento.dao.util;

public enum SortDir {
    ASC, DESC
}