text:
package com.microrisc.simply.iqrf.dpa.v22x.init;

import com.microrisc.simply.DeviceObject;
import com.microrisc.simply.Node;
import com.microrisc.simply.SimpleDeviceObjectFactory;
import com.microrisc.simply.init.InitConfigSettings;
import com.microrisc.simply.iqrf.dpa.DPA_Node;
import com.microrisc.simply.iqrf.dpa.DPA_NodeImpl;
import com.microrisc.simply.iqrf.dpa.v22x.devices.PeripheralInfoGetter;
import com.microrisc.simply.iqrf.dpa.v22x.services.node.load_code.LoadCodeService;
import com.microrisc.simply.services.Service;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.commons.configuration.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Factory for creating nodes.
 *
 * @author Michal Konopa
 */
public final class NodeFactory {
    /** Logger. */
    private static final Logger logger = LoggerFactory.getLogger(NodeFactory.class);

    private static DPA_InitObjects<InitConfigSettings<Configuration, Map<String, Configuration>>>
            _initObjects = null;

    private static SimpleDeviceObjectFactory _devObjectFactory = null;

    /**
     * Creates and returns peripheral information object for specified node.
     */
    private static PeripheralInfoGetter createPerInfoObject(String networkId, String nodeId)
            throws Exception {
        Class baseImplClass = _initObjects.getImplClassMapper().getImplClass(
                PeripheralInfoGetter.class
        );

        if ( _devObjectFactory == null ) {
            _devObjectFactory = new SimpleDeviceObjectFactory();
        }

        return (PeripheralInfoGetter)_devObjectFactory.getDeviceObject(
                networkId, nodeId, _initObjects.getConnectionStack().getConnector(),
                baseImplClass, _initObjects.getConfigSettings().getGeneralSettings()
        );
    }

    private static DPA_InitObjects<InitConfigSettings<Configuration, Map<String, Configuration>>>
    checkInitObjects(
            DPA_InitObjects<InitConfigSettings<Configuration, Map<String, Configuration>>> initObjects
    ) {
        if ( initObjects == null ) {
            throw new IllegalArgumentException("DPA initialization objects cannot be null");
        }
        return initObjects;
    }

    /**
     * Initializes the Node Factory.
     * @param initObjects DPA initialization objects
     */
    public static void init(
            DPA_InitObjects<InitConfigSettings<Configuration, Map<String, Configuration>>> initObjects
    ) {
        _initObjects = checkInitObjects(initObjects);
    }

    /**
     * Creates node services and returns them.
     * @return node services
     */
    private static Map<Class, Service> createServices() {
        Map<Class, Service> services = new HashMap<>();
        return services;
    }

    /**
     * Creates and returns new node with specified peripherals.
     * @param networkId ID of network the node belongs to
     * @param nodeId ID of node to create
     * @param perNumbers peripheral numbers to create node services for
     * @return new node
     * @throws java.lang.Exception if an error has occured during node creation
     */
    public static DPA_Node createNode(String networkId, String nodeId, Set<Integer> perNumbers)
            throws Exception
    {
        logger.debug("createNode - start: networkId={}, nodeId={}, perNumbers={}",
                networkId, nodeId, Arrays.toString(perNumbers.toArray( new Integer[0] ))
        );

        // node devices
        Map<Class, DeviceObject> devices = new HashMap<>();

        // creating Peripheral Information object
        PeripheralInfoGetter perInfoObject = createPerInfoObject(networkId, nodeId);

        // put info object into service's map
        devices.put(PeripheralInfoGetter.class, (DeviceObject)perInfoObject);

        for ( int perId : perNumbers ) {
            Class devIface = _initObjects.getPeripheralToDevIfaceMapper().getDeviceInterface(perId);

            // IMPORTANT: if no device interface for specified peripheral number is found,
            // continue, not throw an exception
            if ( devIface == null ) {
                logger.warn("Interface not found for peripheral: {}", perId);
                continue;
            }

            Class implClass = _initObjects.getImplClassMapper().getImplClass(devIface);
            if ( implClass == null ) {
                throw new RuntimeException("Implementation for " + devIface.getName() + " not found");
            }

            if ( _devObjectFactory == null ) {
                _devObjectFactory = new SimpleDeviceObjectFactory();
            }

            // creating new device object for implementation class
            DeviceObject newDeviceObj = _devObjectFactory.getDeviceObject(
                    networkId, nodeId, _initObjects.getConnectionStack().getConnector(),
                    implClass, _initObjects.getConfigSettings().getGeneralSettings()
            );

            // put object into service's map
            devices.put(devIface, newDeviceObj);
        }

        Map<Class, Service> services = createServices();
        // load code service
        LoadCodeService loadCodeService = NodeServiceFactory.createService(LoadCodeService.class, devices);
        if ( loadCodeService != null ) {
            services.put(LoadCodeService.class, loadCodeService);
        }

        DPA_Node node = new DPA_NodeImpl(networkId, nodeId, devices, services);

        logger.debug("createNode - end: {}", node);
        return node;
    }

    /**
     * Creates and returns new node with services for all peripherals.
     * @param networkId ID of network the node belongs to
     * @param nodeId ID of node to create
     * @return new node
     * @throws java.lang.Exception if an error has occured during node creation
     */
    public static Node createNodeWithAllPeripherals(String networkId, String nodeId)
            throws Exception
    {
        Set<Integer> peripherals = _initObjects.getPeripheralToDevIfaceMapper().getMappedPeripherals();
        return createNode(networkId, nodeId, peripherals);
    }
}


text:
> Generate new package specification files with Chocolatey.

- Create a new package skeleton:

`choco new {{package_name}}`

- Create a new package with a specific version:

`choco new {{package_name}} --version {{version}}`

- Create a new package with a specific maintainer name:

`choco new {{package_name}} --maintainer {{maintainer_name}}`

- Create a new package in a custom output directory:

`choco new {{package_name}} --output-directory {{path/to/directory}}`

- Create a new package with specific 32-bit and 64-bit installer urls:

`choco new {{package_name}} url="{{url}}" url64="{{url}}"`

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;

namespace Stratageme15.Core.Translation.Reactors
{
    public abstract class ReactorBatchBase
    {
        //(reactor,node)
        private readonly List<Tuple<Type, Type>> _reactorTypes;
        private bool _isReactorsListInitialized;

        protected ReactorBatchBase()
        {
            _reactorTypes = new List<Tuple<Type, Type>>();
            _isReactorsListInitialized = false;
        }

        public IEnumerable<Tuple<Type, Type>> ReactorTypes
        {
            get
            {
                if (!_isReactorsListInitialized)
                {
                    Reactors();
                    _isReactorsListInitialized = true;
                }
                return _reactorTypes;
            }
        }

        public abstract object ReactorBatchData { get; }

        protected void RegisterReactor<TReactor, TNode>() where TNode : SyntaxNode where TReactor : IReactor
        {
            _reactorTypes.Add(new Tuple<Type, Type>(typeof (TReactor), typeof (TNode)));
        }

        protected abstract void Reactors();
    }
}


text:
using System.IO;
using System.Text;
using NServiceBus.Persistence.Sql.ScriptBuilder;

class MsSqlServerSagaScriptWriter : ISagaScriptWriter
{
    TextWriter writer;
    SagaDefinition saga;

    public MsSqlServerSagaScriptWriter(TextWriter textWriter, SagaDefinition saga)
    {
        writer = textWriter;
        this.saga = saga;
    }

    public void Initialize()
    {
    }

    public void WriteTableNameVariable()
    {
        writer.WriteLine($@"
declare @tableName nvarchar(max) = '[' + @schema + '].[' + @tablePrefix + N'{saga.TableSuffix}]';
declare @tableNameWithoutSchema nvarchar(max) = @tablePrefix + N'{saga.TableSuffix}';
");
    }

    public void CreateComplete()
    {
    }

    public void AddProperty(CorrelationProperty correlationProperty)
    {
        var columnType = MsSqlServerCorrelationPropertyTypeConverter.GetColumnType(correlationProperty.Type);
        var name = correlationProperty.Name;
        writer.Write($@"
if not exists
(
  select * from sys.columns
  where
    name = N'Correlation_{name}' and
    object_id = object_id(@tableName)
)
begin
  declare @createColumn_{name} nvarchar(max);
  set @createColumn_{name} = '
  alter table ' + @tableName + N'
    add Correlation_{name} {columnType};';
  exec(@createColumn_{name});
end
");
    }

    public void VerifyColumnType(CorrelationProperty correlationProperty)
    {
        string columnType;
        if (correlationProperty.Type == CorrelationPropertyType.String)
        {
            columnType = "nvarchar";
        }
        else
        {
            columnType = MsSqlServerCorrelationPropertyTypeConverter.GetColumnType(correlationProperty.Type);
        }
        var name = correlationProperty.Name;
        writer.Write($@"
declare @dataType_{name} nvarchar(max);
set @dataType_{name} = (
  select data_type
  from INFORMATION_SCHEMA.COLUMNS
  where
    table_name = @tableNameWithoutSchema and
    table_schema = @schema and
    column_name = 'Correlation_{name}'
);
if (@dataType_{name} <> '{columnType}')
  begin
    declare @error_{name} nvarchar(max) = N'Incorrect data type for Correlation_{name}. Expected {columnType} got ' + @dataType_{name} + '.';
    throw 50000, @error_{name}, 0
  end
");
    }

    public void WriteCreateIndex(CorrelationProperty correlationProperty)
    {
        var name = correlationProperty.Name;
        writer.Write($@"
if not exists
(
    select *
    from sys.indexes
    where
        name = N'Index_Correlation_{name}' and
        object_id = object_id(@tableName)
)
begin
  declare @createIndex_{name} nvarchar(max);
  set @createIndex_{name} = N'
  create unique index Index_Correlation_{name}
  on ' + @tableName + N'(Correlation_{name})
  where Correlation_{name} is not null;';
  exec(@createIndex_{name});
end
");
    }

    public void WritePurgeObsoleteProperties()
    {
        var builder = new StringBuilder();

        if (saga.CorrelationProperty != null)
        {
            builder.Append($" and\r\n        column_name <> N'Correlation_{saga.CorrelationProperty.Name}'");
        }
        if (saga.TransitionalCorrelationProperty != null)
        {
            builder.Append($" and\r\n        column_name <> N'Correlation_{saga.TransitionalCorrelationProperty.Name}'");
        }

        writer.Write($@"
declare @dropPropertiesQuery nvarchar(max);
select @dropPropertiesQuery =
(
    select 'alter table ' + @tableName + ' drop column ' + column_name + ';'
    from INFORMATION_SCHEMA.COLUMNS
    where
        table_name = @tableNameWithoutSchema and
        table_schema = @schema and
        column_name like 'Correlation_%'{builder}
);
exec sp_executesql @dropPropertiesQuery
");
    }

    public void WritePurgeObsoleteIndex()
    {
        var builder = new StringBuilder();

        if (saga.CorrelationProperty != null)
        {
            builder.Append($" and\r\n        Name <> N'Index_Correlation_{saga.CorrelationProperty.Name}'");
        }
        if (saga.TransitionalCorrelationProperty != null)
        {
            builder.Append($" and\r\n        Name <> N'Index_Correlation_{saga.TransitionalCorrelationProperty.Name}'");
        }

        writer.Write($@"
declare @dropIndexQuery nvarchar(max);
select @dropIndexQuery =
(
    select 'drop index ' + name + ' on ' + @tableName + ';'
    from sysindexes
    where
        Id = object_id(@tableName) and
        Name is not null and
        Name like 'Index_Correlation_%'{builder}
);
exec sp_executesql @dropIndexQuery
");
    }

    public void WriteCreateTable()
    {
        writer.Write(@"
if not exists
(
    select *
    from sys.objects
    where
        object_id = object_id(@tableName) and
        type in ('U')
)
begin
declare @createTable nvarchar(max);
set @createTable = '
    create table ' + @tableName + '(
        Id uniqueidentifier not null primary key,
        Metadata nvarchar(max) not null,
        Data nvarchar(max) not null,
        PersistenceVersion varchar(23) not null,
        SagaTypeVersion varchar(23) not null,
        Concurrency int not null
    )
';
exec(@createTable);
end
");
    }

    public void WriteDropTable()
    {
        writer.Write(@"
if exists
(
    select *
    from sys.objects
    where
        object_id = object_id(@tableName)
        and type in ('U')
)
begin
    declare @dropTable nvarchar(max);
    set @dropTable = 'drop table ' + @tableName;
    exec(@dropTable);
end
");
    }
}


text:
<!doctype html>

    <meta charset="utf-8">
    <title ng-bind="title">Movie Database Teacher Version</title>

    <link rel="stylesheet" href="/css/bootstrap.css">
    <link rel="stylesheet" href="/css/app.css">

                Movie Databasetest

                        Home

                        Movies

                        Actors

                    <input type="text"
                        class="search-query span2"
                        placeholder="Search">


text:
package com.example.chhavi.swiftintern.Utility;

/**
 * Created by chhavi on 1/7/15.
 */
public class Constants {

    public static String NO_NETWORK_FOUND  = "No internet connection was found. Please connect and try again";
    public static String VOLLEY_ERROR  = "Some error occured, please try again";
    public static String SAVE_PAPER  = "The experience paper has been saved for you, you can view it any time";
    public static String APP_PACKAGE_NAME  = "com.chhavi.swiftintern";

}


text:
package org.zaproxy.zap.extension.api;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.common.AbstractParam;
import org.parosproxy.paros.network.HttpInputStream;
import org.parosproxy.paros.network.HttpMessage;
import org.parosproxy.paros.network.HttpOutputStream;
import org.zaproxy.zap.extension.api.API.RequestType;

public abstract class ApiImplementor {

    private static final String GET_OPTION_PREFIX = "option";
    private static final String SET_OPTION_PREFIX = "setOption";
    private static final String ADD_OPTION_PREFIX = "addOption";
    private static final String REMOVE_OPTION_PREFIX = "removeOption";

    private static final Comparator<Method> METHOD_NAME_COMPARATOR;

    static {
        METHOD_NAME_COMPARATOR =
                new Comparator<Method>() {

                    @Override
                    public int compare(Method method, Method otherMethod) {
                        if (method == null) {
                            if (otherMethod == null) {
                                return 0;
                            }
                            return -1;
                        } else if (otherMethod == null) {
                            return 1;
                        }

                        return method.getName().compareTo(otherMethod.getName());
                    }
                };
    }

    private List<ApiAction> apiActions = new ArrayList<>();
    private List<ApiView> apiViews = new ArrayList<>();
    private List<ApiOther> apiOthers = new ArrayList<>();
    private List<String> apiShortcuts = new ArrayList<>();
    private List<ApiPersistentConnection> apiPersistentConnections = new ArrayList<>();
    private AbstractParam param = null;

    public List<ApiView> getApiViews() {
        return this.apiViews;
    }

    public List<ApiAction> getApiActions() {
        return this.apiActions;
    }

    public List<ApiOther> getApiOthers() {
        return this.apiOthers;
    }

    public void addApiView(ApiView view) {
        addApiElement(apiViews, view, RequestType.view);
    }

    private <T extends ApiElement> void addApiElement(
            List<T> elements, T element, RequestType type) {
        validateApiElement(elements, element);
        String descKey = element.getDescriptionTag();
        if (StringUtils.isEmpty(descKey)) {
            descKey = getI18nPrefix() + ".api." + type.name() + "." + element.getName();
            element.setDescriptionTag(descKey);
        }

        String descParamKeyPrefix = descKey + ".param.";
        for (ApiParameter parameter : element.getParameters()) {
            if (parameter.getDescriptionKey().isEmpty()) {
                parameter.setDescriptionKey(descParamKeyPrefix + parameter.getName());
            }
        }

        elements.add(element);
    }

    /**
     * Validates that the name of the given {@code ApiElement} does not already exist in the given
     * list of {@code ApiElement}.
     *
     *
The names should be unique as they are used to select the {@code ApiElement}s.
     *
     * @param apiElements the existing API elements.
     * @param apiElement the API element to validate.
     * @throws IllegalArgumentException if the name already exists.
     */
    private static void validateApiElement(
            List<? extends ApiElement> apiElements, ApiElement apiElement) {
        String name = apiElement.getName();
        apiElements.stream()
                .filter(e -> name.equals(e.getName()))
                .findFirst()
                .ifPresent(
                        e -> {
                            throw new IllegalArgumentException(
                                    "An ApiElement with the given name already exists: " + name);
                        });
    }

    public void addApiOthers(ApiOther other) {
        addApiElement(apiOthers, other, RequestType.other);
    }

    public void addApiAction(ApiAction action) {
        addApiElement(apiActions, action, RequestType.action);
    }

    public void addApiShortcut(String shortcut) {
        this.apiShortcuts.add(shortcut);
    }

    public void addApiPersistentConnection(ApiPersistentConnection pconn) {
        addApiElement(apiPersistentConnections, pconn, RequestType.pconn);
    }

    /**
     * Adds the given options to the API implementor.
     *
     * @param param the options for the API
     * @see ZapApiIgnore
     */
    public void addApiOptions(AbstractParam param) {
        // Add option parameter getters and setters via reflection
        this.param = param;
        Method[] methods = param.getClass().getDeclaredMethods();
        Arrays.sort(methods, METHOD_NAME_COMPARATOR);
        List<String> addedActions = new ArrayList<>();
        // Check for string setters (which take precedence)
        for (Method method : methods) {
            if (isIgnored(method)) {
                continue;
            }

            boolean deprecated = method.getAnnotation(Deprecated.class) != null;

            if (method.getName().startsWith("get") && method.getParameterTypes().length == 0) {
                ApiView view = new ApiView(GET_OPTION_PREFIX + method.getName().substring(3));
                setApiOptionDeprecated(view, deprecated);
                addApiView(view);
            }
            if (method.getName().startsWith("is") && method.getParameterTypes().length == 0) {
                ApiView view = new ApiView(GET_OPTION_PREFIX + method.getName().substring(2));
                setApiOptionDeprecated(view, deprecated);
                addApiView(view);
            }
            if (method.getName().startsWith("set")
                    && method.getParameterTypes().length == 1
                    && method.getParameterTypes()[0].equals(String.class)) {
                ApiAction action =
                        new ApiAction(
                                SET_OPTION_PREFIX + method.getName().substring(3),
                                new String[] {"String"});
                setApiOptionDeprecated(action, deprecated);
                this.addApiAction(action);
                addedActions.add(method.getName());
            }
            if (method.getName().startsWith("add")
                    && method.getParameterTypes().length == 1
                    && method.getParameterTypes()[0].equals(String.class)) {
                ApiAction action =
                        new ApiAction(
                                ADD_OPTION_PREFIX + method.getName().substring(3),
                                new String[] {"String"});
                setApiOptionDeprecated(action, deprecated);
                this.addApiAction(action);
                addedActions.add(method.getName());
            }
            if (method.getName().startsWith("remove")
                    && method.getParameterTypes().length == 1
                    && method.getParameterTypes()[0].equals(String.class)) {
                ApiAction action =
                        new ApiAction(
                                REMOVE_OPTION_PREFIX + method.getName().substring(6),
                                new String[] {"String"});
                setApiOptionDeprecated(action, deprecated);
                this.addApiAction(action);
                addedActions.add(method.getName());
            }
        }
        // Now check for non string setters
        for (Method method : methods) {
            if (isIgnored(method)) {
                continue;
            }

            boolean deprecated = method.getAnnotation(Deprecated.class) != null;

            if (method.getName().startsWith("set")
                    && method.getParameterTypes().length == 1
                    && !addedActions.contains(method.getName())) {
                // Non String setter
                if (method.getParameterTypes()[0].equals(Integer.class)
                        || method.getParameterTypes()[0].equals(int.class)) {
                    ApiAction action =
                            new ApiAction(
                                    SET_OPTION_PREFIX + method.getName().substring(3),
                                    new String[] {"Integer"});
                    setApiOptionDeprecated(action, deprecated);
                    this.addApiAction(action);
                    addedActions.add(method.getName()); // Just in case there are more overloads
                } else if (method.getParameterTypes()[0].equals(Boolean.class)
                        || method.getParameterTypes()[0].equals(boolean.class)) {
                    ApiAction action =
                            new ApiAction(
                                    SET_OPTION_PREFIX + method.getName().substring(3),
                                    new String[] {"Boolean"});
                    setApiOptionDeprecated(action, deprecated);
                    this.addApiAction(action);
                    addedActions.add(method.getName()); // Just in case there are more overloads
                }
            }
        }
    }

    /**
     * Tells whether or not the given {@code method} should be ignored, thus not included in the ZAP
     * API.
     *
     *
Checks if the given {@code method} has been annotated with {@code ZapApiIgnore} or if it's
     * not public, if any of the conditions is {@code true} the {@code method} is ignored.
     *
     * @param method the method that will be checked
     * @return {@code true} if the method should be ignored, {@code false} otherwise.
     * @see ZapApiIgnore
     */
    private static boolean isIgnored(Method method) {
        return method.getAnnotation(ZapApiIgnore.class) != null
                || !Modifier.isPublic(method.getModifiers());
    }

    private void setApiOptionDeprecated(ApiElement apiOption, boolean deprecated) {
        if (deprecated) {
            apiOption.setDeprecated(deprecated);
            if (Constant.messages != null) {
                // Add a custom message when running from ZAP.
                apiOption.setDeprecatedDescription(
                        Constant.messages.getString("api.deprecated.option.endpoint"));
            }
        }
    }

    public ApiResponse handleApiOptionView(String name, JSONObject params) throws ApiException {
        if (this.param == null) {
            return null;
        }
        if (name.startsWith(GET_OPTION_PREFIX)) {
            name = name.substring(GET_OPTION_PREFIX.length());
            Method[] methods = param.getClass().getDeclaredMethods();
            for (Method method : methods) {
                if (isIgnored(method)) {
                    continue;
                }

                if ((method.getName().equals("get" + name) || method.getName().equals("is" + name))
                        && method.getParameterTypes().length == 0) {
                    try {
                        return new ApiResponseElement(name, method.invoke(this.param).toString());
                    } catch (Exception e) {
                        throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
                    }
                }
            }
        }
        return null;
    }

    public ApiResponse handleApiOptionAction(String name, JSONObject params) throws ApiException {
        if (this.param == null) {
            return null;
        }
        boolean isApiOption = false;

        if (name.startsWith(SET_OPTION_PREFIX)) {
            name = "set" + name.substring(SET_OPTION_PREFIX.length());
            isApiOption = true;
        } else if (name.startsWith(ADD_OPTION_PREFIX)) {
            name = "add" + name.substring(ADD_OPTION_PREFIX.length());
            isApiOption = true;
        } else if (name.startsWith(REMOVE_OPTION_PREFIX)) {
            name = "remove" + name.substring(REMOVE_OPTION_PREFIX.length());
            isApiOption = true;
        }

        if (isApiOption) {
            try {
                Method[] methods = param.getClass().getDeclaredMethods();
                for (Method method : methods) {
                    if (isIgnored(method)) {
                        continue;
                    }

                    if (method.getName().equals(name) && method.getParameterTypes().length == 1) {
                        Object val = null;
                        if (method.getParameterTypes()[0].equals(String.class)) {
                            val = params.getString("String");
                        } else if (method.getParameterTypes()[0].equals(Integer.class)
                                || method.getParameterTypes()[0].equals(int.class)) {
                            try {
                                val = params.getInt("Integer");
                            } catch (JSONException e) {
                                throw new ApiException(
                                        ApiException.Type.ILLEGAL_PARAMETER, "Integer");
                            }
                        } else if (method.getParameterTypes()[0].equals(Boolean.class)
                                || method.getParameterTypes()[0].equals(boolean.class)) {
                            try {
                                val = params.getBoolean("Boolean");
                            } catch (JSONException e) {
                                throw new ApiException(
                                        ApiException.Type.ILLEGAL_PARAMETER, "Boolean");
                            }
                        }
                        if (val == null) {
                            // Value supplied doesn't match the type - try the next one
                            continue;
                        }
                        method.invoke(this.param, val);
                        return ApiResponseElement.OK;
                    }
                }
            } catch (ApiException e) {
                throw e;
            } catch (Exception e) {
                throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
            }
        }
        return null;
    }

    /**
     * Override if implementing one or more views
     *
     * @param name the name of the requested view
     * @param params the API request parameters
     * @return the API response
     * @throws ApiException if an error occurred while handling the API view endpoint
     */
    public ApiResponse handleApiView(String name, JSONObject params) throws ApiException {
        throw new ApiException(ApiException.Type.BAD_VIEW, name);
    }

    /**
     * Override if implementing one or more actions
     *
     * @param name the name of the requested action
     * @param params the API request parameters
     * @return the API response
     * @throws ApiException if an error occurred while handling the API action endpoint
     */
    public ApiResponse handleApiAction(String name, JSONObject params) throws ApiException {
        throw new ApiException(ApiException.Type.BAD_ACTION, name);
    }

    /**
     * Override if implementing one or more 'other' operations - these are operations that _dont_
     * return structured data
     *
     * @param msg the HTTP message containing the API request
     * @param name the name of the requested other endpoint
     * @param params the API request parameters
     * @return the HTTP message with the API response
     * @throws ApiException if an error occurred while handling the API other endpoint
     */
    public HttpMessage handleApiOther(HttpMessage msg, String name, JSONObject params)
            throws ApiException {
        throw new ApiException(ApiException.Type.BAD_OTHER, name);
    }

    /**
     * Override if implementing one or more 'persistent connection' operations. These are operations
     * that maintain long running connections, potentially staying alive as long as the client holds
     * them open.
     *
     * @param msg the HTTP message containing the API request
     * @param httpIn the input stream
     * @param httpOut the output stream
     * @param name the name of the requested pconn endpoint
     * @param params the API request parameters
     * @throws ApiException if an error occurred while handling the API pconn endpoint
     */
    public void handleApiPersistentConnection(
            HttpMessage msg,
            HttpInputStream httpIn,
            HttpOutputStream httpOut,
            String name,
            JSONObject params)
            throws ApiException {
        throw new ApiException(ApiException.Type.BAD_PCONN, name);
    }

    /**
     * Override if handling callbacks
     *
     * @param msg the HTTP message containing the API request and response
     * @return the API response (set in the HTTP response body)
     * @throws ApiException if an error occurred while handling the API callback
     */
    public String handleCallBack(HttpMessage msg) throws ApiException {
        throw new ApiException(
                ApiException.Type.URL_NOT_FOUND, msg.getRequestHeader().getURI().toString());
    }

    public HttpMessage handleShortcut(HttpMessage msg) throws ApiException {
        throw new ApiException(
                ApiException.Type.URL_NOT_FOUND, msg.getRequestHeader().getURI().toString());
    }

    public abstract String getPrefix();

    /**
     * Gets the prefix for default resource keys for the description of the API implementor and its
     * elements.
     *
     *
Defaults to {@code getPrefix()}.
     *
     * @return the prefix for i18n keys.
     * @since 2.10.0
     */
    protected String getI18nPrefix() {
        return getPrefix();
    }

    /**
     * Gets the resource key of the description.
     *
     *
Defaults to {@code getI18nPrefix() + ".api.desc"}.
     *
     * @return the key of the description.
     * @since 2.9.0
     * @see org.zaproxy.zap.utils.I18N#getString(String)
     */
    public String getDescriptionKey() {
        return getI18nPrefix() + ".api.desc";
    }

    public ApiAction getApiAction(String name) {
        for (ApiAction action : this.apiActions) {
            if (action.getName().equals(name)) {
                return action;
            }
        }
        return null;
    }

    public ApiView getApiView(String name) {
        for (ApiView view : this.apiViews) {
            if (view.getName().equals(name)) {
                return view;
            }
        }
        return null;
    }

    public ApiOther getApiOther(String name) {
        for (ApiOther other : this.apiOthers) {
            if (other.getName().equals(name)) {
                return other;
            }
        }
        return null;
    }

    protected List<String> getApiShortcuts() {
        return this.apiShortcuts;
    }

    public ApiPersistentConnection getApiPersistentConnection(String name) {
        for (ApiPersistentConnection pconn : this.apiPersistentConnections) {
            if (pconn.getName().equals(name)) {
                return pconn;
            }
        }
        return null;
    }

    public List<ApiPersistentConnection> getApiPersistentConnections() {
        return this.apiPersistentConnections;
    }

    protected int getParam(JSONObject params, String name, int defaultValue) {
        try {
            return params.getInt(name);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    protected long getParam(JSONObject params, String name, long defaultValue) {
        try {
            return params.getLong(name);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    protected String getParam(JSONObject params, String name, String defaultValue) {
        try {
            return params.getString(name);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    protected boolean getParam(JSONObject params, String name, boolean defaultValue) {
        try {
            return params.getBoolean(name);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    /**
     * Validates that a parameter with the given {@code name} exists (and it has a value) in the
     * given {@code parameters}.
     *
     * @param parameters the parameters
     * @param name the name of the parameter that must exist
     * @throws ApiException if the parameter with the given name does not exist or it has no value.
     * @since 2.6.0
     */
    protected void validateParamExists(JSONObject parameters, String name) throws ApiException {
        if (!parameters.has(name) || parameters.getString(name).length() == 0) {
            throw new ApiException(ApiException.Type.MISSING_PARAMETER, name);
        }
    }

    /**
     * Override to add custom headers for specific API operations
     *
     * @param name the name of the operation
     * @param type the type of the operation
     * @param msg the HTTP response message to the API request
     */
    public void addCustomHeaders(String name, RequestType type, HttpMessage msg) {
        // Do nothing in the default implementation
    }

    boolean hasApiOptions() {
        return param != null;
    }
}


text:
package gw.internal.schema.gw.xsd.w3c.soap12_envelope.types.complex;

/***************************************************************************/
/* THIS IS AUTOGENERATED CODE - DO NOT MODIFY OR YOUR CHANGES WILL BE LOST */
/* THIS CODE CAN BE REGENERATED USING 'xsd-codegen'                        */
/***************************************************************************/
public class SupportedEnvType extends gw.internal.schema.gw.xsd.w3c.xmlschema.types.complex.AnyType implements gw.internal.xml.IXmlGeneratedClass {

  public static final javax.xml.namespace.QName $ATTRIBUTE_QNAME_Qname = new javax.xml.namespace.QName( "", "qname", "" );
  public static final javax.xml.namespace.QName $QNAME = new javax.xml.namespace.QName( "http://www.w3.org/2003/05/soap-envelope", "SupportedEnvType", "soap12" );
  public static final gw.util.concurrent.LockingLazyVar<gw.lang.reflect.IType> TYPE = new gw.util.concurrent.LockingLazyVar<gw.lang.reflect.IType>( gw.lang.reflect.TypeSystem.getGlobalLock() ) {
          @Override
          protected gw.lang.reflect.IType init() {
            return gw.lang.reflect.TypeSystem.getByFullName( "gw.xsd.w3c.soap12_envelope.types.complex.SupportedEnvType" );
          }
        };
  private static final gw.util.concurrent.LockingLazyVar<java.lang.Object> SCHEMAINFO = new gw.util.concurrent.LockingLazyVar<java.lang.Object>( gw.lang.reflect.TypeSystem.getGlobalLock() ) {
          @Override
          protected java.lang.Object init() {
            gw.lang.reflect.IType type = TYPE.get();
            return getSchemaInfoByType( type );
          }
        };

  public SupportedEnvType() {
    super( TYPE.get(), SCHEMAINFO.get() );
  }

  protected SupportedEnvType( gw.lang.reflect.IType type, java.lang.Object schemaInfo ) {
    super( type, schemaInfo );
  }

  public javax.xml.namespace.QName Qname() {
    return (javax.xml.namespace.QName) TYPE.get().getTypeInfo().getProperty( "Qname" ).getAccessor().getValue( this );
  }

  public void setQname$( javax.xml.namespace.QName param ) {
    TYPE.get().getTypeInfo().getProperty( "Qname" ).getAccessor().setValue( this, param );
  }

  @SuppressWarnings( {"UnusedDeclaration"} )
  private static final long FINGERPRINT = -6014282781002754770L;

}


text:
'use strict';

var remix = require('./lib/remix');

exports.generate = function(content, options, callback) {
  var contentArr = content.split(/\s/);
  var finalContent = [];

  if (!callback) {
    callback = options;
    options = {};
  }

  contentArr.forEach(function(content, idx) {
    process.nextTick(function() {
      remix.process(content, options, function(err, resp) {
        if (err) {
          callback(err);

        } else {
          finalContent.push({ id: idx, message: resp });
        }

        if (finalContent.length === contentArr.length) {
          var messageArr = [];

          finalContent = finalContent.sort(function(a, b) {
            return parseInt(a.id, 10) - parseInt(b.id, 10);
          });

          finalContent.forEach(function(m) {
            messageArr.push(m.message);
          });

          callback(null, messageArr.join(' '));
        }
      });
    });
  });
};


text:
<?php
use PHPUnit\Framework\TestCase;

// Place this test in a fresh install of Kirby to test it.
// Go to `site/plugins/queue-for-kirby/tests` in the terminal
// Then run `phpunit test --colors` (yaay, colors!)
// Make sure you installed PHPUnit

if(!defined('DS'))  define('DS', DIRECTORY_SEPARATOR);
require(dirname(__DIR__).DS.'..'.DS.'..'.DS.'..'.DS.'kirby'.DS.'bootstrap.php');

// Sorry, need to load some Kirby stuff
$kirby = kirby(); $site = site();
$kirby->extensions(); $kirby->models(); $kirby->plugins();

/**
 * @covers Queue
 */
final class QueueTest extends TestCase
{
    public static function setUpBeforeClass()
    {
        if(count(dir::read(queue::path())))
            die('There are jobs in the queue! Make sure to start fresh.');
    }

    public function tearDown()
    {
        queue::flush();
    }

    /** @test */
    public function Queue_add__adds_jobs()
    {
        $jobcount = count(dir::read(queue::path()));

        queue::add('test_job', [
            'param' => 'some data'
        ]);

        $this->assertEquals(
            count(dir::read(queue::path())),
            $jobcount + 1
        );
    }

    /** @test */
    public function Queue_jobs__returns_jobs()
    {
        queue::add('test_job', [
            'param' => 'some data'
        ]);

        queue::add('another_job');

        $jobs = queue::jobs();

        $this->assertCount(2, $jobs);

        // Test first job of queue
        $job = $jobs->nth(0);
        $this->assertEquals('test_job', $job->name());
        $this->assertEquals([
            'param' => 'some data'
        ], $job->data());
        $this->assertEquals('some data', $job->get('param'));

        // Test second job of queue
        $job = $jobs->nth(1);
        $this->assertEquals('another_job', $job->name());
        $this->assertEquals(null, $job->data());
        $this->assertEquals(null, $job->get('param'));

        // Note that the code above does not remove the jobs
        // or change the queue at all!
        // Use queue::work() for that
    }

    /** @test */
    public function Queue_retry__adds_to_queue()
    {
        queue::define('job_to_fail', function() {
            return false;
        });

        queue::add('job_to_fail');
        queue::work();

        // We now have 0 jobs and 1 failed job
        $this->assertCount(0, queue::jobs());
        $this->assertCount(1, queue::failedJobs());

        // Take the Job and retry
        $failedJob = queue::failedJobs()->first();
        queue::retry($failedJob);

        // The job has been added to the queue again
        $this->assertCount(1, queue::jobs());
        $this->assertCount(0, queue::failedJobs());

        // Job will still fail
        queue::work();

        // The job has failed
        $this->assertCount(0, queue::jobs());
        $this->assertCount(1, queue::failedJobs());

        // Take the Job and retry by ID
        $failedJob = queue::failedJobs()->first();
        $id = $failedJob->id();

        // The ID is a string
        $this->assertInternalType('string', $id);

        queue::retry($id);

        // And the job is back in the queue again
        $this->assertCount(1, queue::jobs());
        $this->assertCount(0, queue::failedJobs());
    }

    /**
     * @test
     * @expectedException Error
     * @expectedExceptionMessage Job not found
     */
    public function Queue_retry__throws_error_on_wrong_id()
    {
        queue::add('job_to_fail');
        queue::work();

        // Take the first ID and add rubbish
        $id = queue::failedJobs()->first()->id();
        $id = $id . 'asdasd';

        queue::retry($id);
    }

    /**
     * @test
     * @expectedException Error
     * @expectedExceptionMessage queue::retry() expects a Job object
     */
    public function Queue_retry__throws_error_on_non_job()
    {
        queue::add('job_to_fail');
        queue::work();

        queue::retry(new HTML());
    }

    /** @test */
    public function Queue_remove__removes_failed_jobs()
    {
        queue::add('job_to_fail');
        queue::add('another_job_that_fails');
        queue::work();
        queue::work();

        // We now have 0 jobs and 2 failed job
        $this->assertCount(0, queue::jobs());
        $this->assertCount(2, queue::failedJobs());

        // Take the Job, check if it's the one, and remove it
        $failedJob = queue::failedJobs()->first();
        $this->assertEquals('job_to_fail', $failedJob->name());
        queue::remove($failedJob);

        // We have only one failed job now
        $this->assertCount(0, queue::jobs());
        $this->assertCount(1, queue::failedJobs());

        // The remaining job is the other job
        $failedJob = queue::failedJobs()->first();
        $this->assertEquals('another_job_that_fails', $failedJob->name());

        // Remove by ID
        queue::remove($failedJob->id());

        // All the jobs are gone
        $this->assertCount(0, queue::jobs());
        $this->assertCount(0, queue::failedJobs());
    }

    /**
     * @test
     * @expectedException Error
     * @expectedExceptionMessage Job not found
     */
    public function Queue_remove__throws_error_on_wrong_id()
    {
        queue::add('job_to_fail');
        queue::work();

        // Take the first ID and add rubbish
        $id = queue::failedJobs()->first()->id();
        $id = $id . 'asdasd';

        queue::remove($id);
    }

    /**
     * @test
     * @expectedException Error
     * @expectedExceptionMessage queue::remove() expects a Job object
     */
    public function Queue_remove__throws_error_on_non_job()
    {
        queue::add('job_to_fail');
        queue::work();

        queue::remove(new Silo());
    }

    /** @test */
    public function Queue_flush__removes_all_jobs()
    {
        $this->assertCount(0, queue::jobs());
        $this->assertFalse(queue::hasJobs());

        queue::add('test_job');
        queue::add('test_job');
        queue::add('test_job');

        $this->assertCount(3, queue::jobs());
        $this->assertTrue(queue::hasJobs());

        queue::flush();

        $this->assertCount(0, queue::jobs());
        $this->assertFalse(queue::hasJobs());
    }

    /** @test */
    public function job_succeeds()
    {
        queue::define('test_job', function() {
            dir::make(queue::path() . DS . '.test');
        });

        $params = [
            'param1' => 'some data',
            'param2' => 'more data'
        ];

        queue::add('test_job', $params);

        // Now we have 1 job
        $this->assertCount(1, queue::jobs());

        // Get the first job ourselfs
        $job = yaml::read(queue::path() . DS .
            a::first(dir::read(queue::path())));

        // Check some things about the job
        $this->assertEquals(
            new Job($job),
            queue::jobs()->first()
        );
        $this->assertEquals($job['name'], 'test_job');
        $this->assertEquals($job['data'], $params);

        queue::work();

        // Now we have 0 jobs
        $this->assertCount(0, queue::jobs());

        // And the job has been done
        $this->assertFileExists(queue::path() . DS . '.test');
    }

    /** @test */
    public function job_fails_on_false()
    {
        queue::define('test_job', function() {
            return false;
        });

        queue::add('test_job');

        // Now we have 1 job
        $this->assertCount(1, queue::jobs());

        queue::work();

        // Now we have 0 jobs and 1 failed job
        $this->assertCount(0, queue::jobs());
        $this->assertCount(1, queue::failedJobs());

        // Get the first job ourselfs
        $job = yaml::read(queue::failedPath() . DS .
            a::first(dir::read(queue::failedPath())));

        // Check some things about the job
        $this->assertEquals(
            new Job($job),
            queue::failedJobs()->first()
        );
        $this->assertEquals($job['name'], 'test_job');
        $this->assertEquals($job['error'], 'Job returned false');
    }

    /** @test */
    public function job_fails_on_exception()
    {
        queue::define('test_job', function() {
            throw new Exception('Exception message');
        });

        queue::add('test_job');

        // Now we have 1 job
        $this->assertCount(1, queue::jobs());

        queue::work();

        // Now we have 0 jobs and 1 failed job
        $this->assertCount(0, queue::jobs());
        $this->assertCount(1, queue::failedJobs());

        // Get the first job ourselfs
        $job = yaml::read(queue::failedPath() . DS .
            a::first(dir::read(queue::failedPath())));

        // Check some things about the job
        $this->assertEquals(
            new Job($job),
            queue::failedJobs()->first()
        );
        $this->assertEquals($job['name'], 'test_job');
        $this->assertEquals($job['error'], 'Exception message');
    }

    /** @test */
    public function job_fails_on_error()
    {
        queue::define('test_job', function() {
            throw new Error('Error message');
        });

        queue::add('test_job');

        // Now we have 1 job
        $this->assertCount(1, queue::jobs());

        queue::work();

        // Now we have 0 jobs and 1 failed job
        $this->assertCount(0, queue::jobs());
        $this->assertCount(1, queue::failedJobs());

        // Get the first job ourselfs
        $job = yaml::read(queue::failedPath() . DS .
            a::first(dir::read(queue::failedPath())));

        // Check some things about the job
        $this->assertEquals(
            new Job($job),
            queue::failedJobs()->first()
        );
        $this->assertEquals($job['name'], 'test_job');
        $this->assertEquals($job['error'], 'Error message');
    }

    /** @test */
    public function job_fails_on_non_existent_action()
    {
        queue::add('job_without_action');

        // Now we have 1 job
        $this->assertCount(1, queue::jobs());

        queue::work();

        // Now we have 0 jobs and 1 failed job
        $this->assertCount(0, queue::jobs());
        $this->assertCount(1, queue::failedJobs());

        // Get the first job ourselfs
        $job = yaml::read(queue::failedPath() . DS .
            a::first(dir::read(queue::failedPath())));

        // Check some things about the job
        $this->assertEquals(
            new Job($job),
            queue::failedJobs()->first()
        );
        $this->assertEquals($job['name'], 'job_without_action');
        $this->assertEquals($job['error'], 'Action \'job_without_action\' not defined');
    }

    /** @test */
    public function job_fails_on_teminating_process()
    {
        // # This one is impossible to test via PHPUnit, because we
        // # exit the PHP-unit process as well. To test this function,
        // # uncomment it, run the test it, and see the contents of
        // # the `site/queue/.failed` folder yourself.
        //
        // # Assert for yourself that:
        // #   $job['name'] == 'teminating_job'
        // #   $job['error'] == 'Job action terminated execution'
        //
        // # After that, remove the file from the queue.
        //
        // queue::define('teminating_job', function() {
        //     die();
        // });
        // queue::add('teminating_job');
        // queue::work();
    }

}


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
* @name: S15.10.2.8_A1_T3;
* @section: 15.10.2.8;
* @assertion: The form (?= Disjunction ) specifies a zero-width positive lookahead.
* In order for it to succeed, the pattern inside Disjunction must match at the current position, but the current position is not advanced before matching the sequel.
* If Disjunction can match at the current position in several ways, only the first one is tried;
* @description: Execute /[Jj]ava([Ss]cript)?(?=\:)/.exec("just Javascript: the way af jedi") and check results;
*/

__executed = /[Jj]ava([Ss]cript)?(?=\:)/.exec("just Javascript: the way af jedi");

__expected = ["Javascript", "script"];
__expected.index = 5;
__expected.input = "just Javascript: the way af jedi";

//CHECK#1
if (__executed.length !== __expected.length) {
	$ERROR('#1: __executed = /[Jj]ava([Ss]cript)?(?=\\:)/.exec("just Javascript: the way af jedi"); __executed.length === ' + __expected.length + '. Actual: ' + __executed.length);
}

//CHECK#2
if (__executed.index !== __expected.index) {
	$ERROR('#2: __executed = /[Jj]ava([Ss]cript)?(?=\\:)/.exec("just Javascript: the way af jedi"); __executed.index === ' + __expected.index + '. Actual: ' + __executed.index);
}

//CHECK#3
if (__executed.input !== __expected.input) {
	$ERROR('#3: __executed = /[Jj]ava([Ss]cript)?(?=\\:)/.exec("just Javascript: the way af jedi"); __executed.input === ' + __expected.input + '. Actual: ' + __executed.input);
}

//CHECK#4
for(var index=0; index<__expected.length; index++) {
	if (__executed[index] !== __expected[index]) {
		$ERROR('#4: __executed = /[Jj]ava([Ss]cript)?(?=\\:)/.exec("just Javascript: the way af jedi"); __executed[' + index + '] === ' + __expected[index] + '. Actual: ' + __executed[index]);
	}
}


text:
package com.fishercoder.solutions;

import com.fishercoder.common.classes.TreeNode;

public class _100 {
    public static class Solution1 {
        public boolean isSameTree(TreeNode p, TreeNode q) {
            if (p == null || q == null) {
                return p == q;
            }
            return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
        }
    }
}


text:
package org.apache.storm.scheduler;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.apache.storm.utils.ServerUtils;
import org.apache.storm.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Sets;

public class EvenScheduler implements IScheduler {
    private static final Logger LOG = LoggerFactory.getLogger(EvenScheduler.class);

    public static List<WorkerSlot> sortSlots(List<WorkerSlot> availableSlots) {
        //For example, we have a three nodes(supervisor1, supervisor2, supervisor3) cluster:
        //slots before sort:
        //supervisor1:6700, supervisor1:6701,
        //supervisor2:6700, supervisor2:6701, supervisor2:6702,
        //supervisor3:6700, supervisor3:6703, supervisor3:6702, supervisor3:6701
        //slots after sort:
        //supervisor3:6700, supervisor2:6700, supervisor1:6700,
        //supervisor3:6701, supervisor2:6701, supervisor1:6701,
        //supervisor3:6702, supervisor2:6702,
        //supervisor3:6703

        if (availableSlots != null && availableSlots.size() > 0) {
            // group by node
            Map<String, List<WorkerSlot>> slotGroups = new TreeMap<String, List<WorkerSlot>>();
            for (WorkerSlot slot : availableSlots) {
                String node = slot.getNodeId();
                List<WorkerSlot> slots = null;
                if(slotGroups.containsKey(node)){
                   slots = slotGroups.get(node);
                }else{
                   slots = new ArrayList<WorkerSlot>();
                   slotGroups.put(node, slots);
                }
                slots.add(slot);
            }

            // sort by port: from small to large
            for (List<WorkerSlot> slots : slotGroups.values()) {
                Collections.sort(slots, new Comparator<WorkerSlot>() {
                    @Override
                    public int compare(WorkerSlot o1, WorkerSlot o2) {
                        return o1.getPort() - o2.getPort();
                    }
                });
            }

            // sort by available slots size: from large to small
            List<List<WorkerSlot>> list = new ArrayList<List<WorkerSlot>>(slotGroups.values());
            Collections.sort(list, new Comparator<List<WorkerSlot>>() {
                @Override
                public int compare(List<WorkerSlot> o1, List<WorkerSlot> o2) {
                    return o2.size() - o1.size();
                }
            });

            return ServerUtils.interleaveAll(list);
        }

        return null;
    }

    public static Map<WorkerSlot, List<ExecutorDetails>> getAliveAssignedWorkerSlotExecutors(Cluster cluster, String topologyId) {
        SchedulerAssignment existingAssignment = cluster.getAssignmentById(topologyId);
        Map<ExecutorDetails, WorkerSlot> executorToSlot = null;
        if (existingAssignment != null) {
            executorToSlot = existingAssignment.getExecutorToSlot();
        }

        return Utils.reverseMap(executorToSlot);
    }

    private static Map<ExecutorDetails, WorkerSlot> scheduleTopology(TopologyDetails topology, Cluster cluster) {
        List<WorkerSlot> availableSlots = cluster.getAvailableSlots();
        Set<ExecutorDetails> allExecutors = topology.getExecutors();
        Map<WorkerSlot, List<ExecutorDetails>> aliveAssigned = getAliveAssignedWorkerSlotExecutors(cluster, topology.getId());
        int totalSlotsToUse = Math.min(topology.getNumWorkers(), availableSlots.size() + aliveAssigned.size());

        List<WorkerSlot> sortedList = sortSlots(availableSlots);
        if (sortedList == null) {
            LOG.error("No available slots for topology: {}", topology.getName());
            return new HashMap<ExecutorDetails, WorkerSlot>();
        }

        //allow requesting slots number bigger than available slots
        int toIndex = (totalSlotsToUse - aliveAssigned.size()) > sortedList.size() ? sortedList.size() : (totalSlotsToUse - aliveAssigned.size());
        List<WorkerSlot> reassignSlots = sortedList.subList(0, toIndex);

        Set<ExecutorDetails> aliveExecutors = new HashSet<ExecutorDetails>();
        for (List<ExecutorDetails> list : aliveAssigned.values()) {
            aliveExecutors.addAll(list);
        }
        Set<ExecutorDetails> reassignExecutors = Sets.difference(allExecutors, aliveExecutors);

        Map<ExecutorDetails, WorkerSlot> reassignment = new HashMap<ExecutorDetails, WorkerSlot>();
        if (reassignSlots.size() == 0) {
            return reassignment;
        }

        List<ExecutorDetails> executors = new ArrayList<ExecutorDetails>(reassignExecutors);
        Collections.sort(executors, new Comparator<ExecutorDetails>() {
            @Override
            public int compare(ExecutorDetails o1, ExecutorDetails o2) {
                return o1.getStartTask() - o2.getStartTask();
            }
        });

        for (int i = 0; i < executors.size(); i++) {
            reassignment.put(executors.get(i), reassignSlots.get(i % reassignSlots.size()));
        }

        if (reassignment.size() != 0) {
            LOG.info("Available slots: {}", availableSlots.toString());
        }
        return reassignment;
    }

    public static void scheduleTopologiesEvenly(Topologies topologies, Cluster cluster) {
        List<TopologyDetails> needsSchedulingTopologies = cluster.needsSchedulingTopologies(topologies);
        for (TopologyDetails topology : needsSchedulingTopologies) {
            String topologyId = topology.getId();
            Map<ExecutorDetails, WorkerSlot> newAssignment = scheduleTopology(topology, cluster);
            Map<WorkerSlot, List<ExecutorDetails>> nodePortToExecutors = Utils.reverseMap(newAssignment);

            for (Map.Entry<WorkerSlot, List<ExecutorDetails>> entry : nodePortToExecutors.entrySet()) {
                WorkerSlot nodePort = entry.getKey();
                List<ExecutorDetails> executors = entry.getValue();
                cluster.assign(nodePort, topologyId, executors);
            }
        }
    }

    @Override
    public void prepare(Map<String, Object> conf) {
        //noop
    }

    @Override
    public void schedule(Topologies topologies, Cluster cluster) {
        scheduleTopologiesEvenly(topologies, cluster);
    }

    @Override
    public Map<String, Object> config() {
        return new HashMap<>();
    }

}


text:
namespace ash {

using LoginErrorBubbleTest = LoginTestBase;

TEST_F(LoginErrorBubbleTest, PersistentEventHandling) {
  auto* container = new views::View;
  container->SetLayoutManager(std::make_unique<views::BoxLayout>(
      views::BoxLayout::Orientation::kVertical));
  SetWidget(CreateWidgetWithContent(container));

  auto* anchor_view = new views::View;
  container->AddChildView(anchor_view);

  auto* bubble = new LoginErrorBubble(anchor_view);
  bubble->set_persistent(true);
  container->AddChildView(bubble);

  EXPECT_FALSE(bubble->GetVisible());

  bubble->Show();
  EXPECT_TRUE(bubble->GetVisible());

  ui::test::EventGenerator* generator = GetEventGenerator();

  generator->MoveMouseTo(anchor_view->GetBoundsInScreen().CenterPoint());
  generator->ClickLeftButton();
  EXPECT_TRUE(bubble->GetVisible());

  generator->MoveMouseTo(bubble->GetBoundsInScreen().CenterPoint());
  generator->ClickLeftButton();
  EXPECT_TRUE(bubble->GetVisible());

  generator->GestureTapAt(anchor_view->GetBoundsInScreen().CenterPoint());
  EXPECT_TRUE(bubble->GetVisible());

  generator->GestureTapAt(bubble->GetBoundsInScreen().CenterPoint());
  EXPECT_TRUE(bubble->GetVisible());

  generator->PressKey(ui::KeyboardCode::VKEY_A, ui::EF_NONE);
  EXPECT_TRUE(bubble->GetVisible());
}

}  // namespace ash


text:
package com.myhoard.app.fragments;

import android.content.AsyncQueryHandler;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;

import com.myhoard.app.R;
import com.myhoard.app.dialogs.TypeConfirmDialog;
import com.myhoard.app.dialogs.TypeDialog;
import com.myhoard.app.provider.DataStorage;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Rafał Soudani on 20.02.2014
 */
public class CollectionFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>,
        View.OnFocusChangeListener, View.OnClickListener {

    private static final int LOAD_DATA_FOR_EDIT = 20;
    private static final int LOAD_NAMES = 30;
    private static final int MIN_NUMBER_OF_CHARACTERS = 2;
    private static final int TYPE_REQUEST_CODE = 100;
    private static final int CONFIRM_REQUEST_CODE = 110;

    private Context context;
    private Long mEditId;
    private String mName, mDescription;
    private final ArrayList<String> mNamesList = new ArrayList<>();
    private String mTags = "";
    private EditText etCollectionName, etCollectionDescription, etCollectionTags, etCollectionType;
    private final HashMap<Integer, String> typesMap = new HashMap<>();
    private int typeOfCollectionBeforeChange;
    Toast toast;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        context = getActivity();
        final View view = inflater.inflate(R.layout.fragment_new_collection, container, false);
        getLoaderManager().initLoader(LOAD_NAMES, null, this);
        setHasOptionsMenu(true);

        setTypesMap();
        setEditId();

        if (view != null) {

            findViewsByIds(view);
            setListeners();

            if (this.getTag().equals("EditCollection")) {
                if (savedInstanceState != null) {
                    mEditId = savedInstanceState.getLong("editId");
                    mTags = savedInstanceState.getString("tags");
                    etCollectionTags.setText(mTags);
                } else {
                    getLoaderManager().restartLoader(LOAD_DATA_FOR_EDIT, null, this);
                }
            } else {
                getActivity().setTitle(context.getString(R.string.new_collection));
            }
        }

        return view;
    }

    private void setTypesMap() {
        typesMap.put(DataStorage.TypeOfCollection.OFFLINE.getType(), getString(R.string.offline));
        typesMap.put(DataStorage.TypeOfCollection.PUBLIC.getType(), getString(R.string.publics));
        typesMap.put(DataStorage.TypeOfCollection.PRIVATE.getType(), getString(R.string.privates));
    }

    private void setEditId() {
        Bundle args = getArguments();
        if (args != null) {
            mEditId = args.getLong("id");
        }
    }

    private void findViewsByIds(View view) {
        etCollectionName = (EditText) view.findViewById(R.id.etCollectionName);
        etCollectionDescription = (EditText) view.findViewById(R.id.etCollectionDescription);
        etCollectionTags = (EditText) view.findViewById(R.id.etCollectionTags);
        etCollectionType = (EditText) view.findViewById(R.id.etCollectionType);
    }

    private void setListeners() {
        etCollectionName.setOnFocusChangeListener(this);
        etCollectionDescription.setOnFocusChangeListener(this);
        etCollectionTags.setOnFocusChangeListener(this);
        etCollectionType.setOnClickListener(this);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();
        inflater.inflate(R.menu.new_collection, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_accept:
                if (etCollectionName.getText() != null) {

                    if (validateCollectionName()) {
                        if (etCollectionName.getText() != null) {
                            mName = etCollectionName.getText().toString();
                        }
                        if (etCollectionDescription.getText() != null) {
                            mDescription = etCollectionDescription.getText().toString();
                        }
                        if (etCollectionTags.getText() != null) {
                            if (validateTags()) {
                                mTags = etCollectionTags.getText().toString();
                            } else {
                                return false;
                            }
                        }
                        if (this.getTag().equals("EditCollection") && typeOfCollectionBeforeChange != DataStorage.TypeOfCollection.OFFLINE.getType()
                                && getTypeOfCollection(String.valueOf(etCollectionType.getText())) == DataStorage.TypeOfCollection.OFFLINE.getType()) {
                            showConfirmTypeDialog();
                        } else {
                            saveDataInDataBase();
                            getActivity().getSupportFragmentManager().popBackStack();
                        }
                    }
                }
                break;
            default:
                return super.onOptionsItemSelected(item);
        }
        return true;
    }

    private void showConfirmTypeDialog() {
        TypeConfirmDialog confirmDialog = new TypeConfirmDialog();
        confirmDialog.setTargetFragment(this, CONFIRM_REQUEST_CODE);
        confirmDialog.show(getFragmentManager(), "");
    }

    private boolean validateTags() {
        String sentence = String.valueOf(etCollectionTags.getText());
        String[] tags = sentence.split(" ");
        List<String> result = new ArrayList<>();
        List<String> temp = new ArrayList<>();

        for (String tag : tags) {
            if (temp.contains(tag.toUpperCase())) {
                String toastText = String.format(getString(R.string.tag_exist), tag);
                showAToast(toastText, Toast.LENGTH_SHORT);
                return false;
            } else {
                temp.add(tag.toUpperCase());
                result.add(tag);
            }
        }
        return true;
    }

    private boolean validateCollectionName() {
        String strCollectionName = "";
        if (etCollectionName.getText() != null) {
            strCollectionName = etCollectionName.getText().toString();
        }
        if (TextUtils.isEmpty(etCollectionName.getText())) {
            showAToast(getString(R.string.required_name_collection), Toast.LENGTH_SHORT);
        } else if (isWhiteSpaces(strCollectionName)) {
            showAToast(getString(R.string.required_name_collection), Toast.LENGTH_SHORT);
        } else if (strCollectionName.length() < MIN_NUMBER_OF_CHARACTERS) {
            showAToast(getString(R.string.name_too_short), Toast.LENGTH_SHORT);
        } else if (mNamesList.contains(strCollectionName)) {
            showAToast(getString(R.string.name_already_exist), Toast.LENGTH_SHORT);
        } else if (strCollectionName.charAt(strCollectionName.length() - 1) == ' ') {
            showAToast(getString(R.string.name_with_space_at_end), Toast.LENGTH_SHORT);
        } else if (strCollectionName.charAt(0) == ' ') {
            showAToast(getString(R.string.name_with_space_at_start), Toast.LENGTH_SHORT);
        } else {
            return true;
        }
        return false;

    }

    public void showAToast(String toastText, int toastDuration) {
        try {
            toast.getView().isShown();     // true if visible
            toast.setText(toastText);
        } catch (Exception e) {         // invisible if exception
            toast = Toast.makeText(getActivity(), toastText, toastDuration);
        }
        toast.show();  //finally display it
    }

    private void saveDataInDataBase() {
        ContentValues values = new ContentValues();
        values.put(DataStorage.Collections.NAME, mName);
        values.put(DataStorage.Collections.NAME_UPPER, mName.toUpperCase());
        values.put(DataStorage.Collections.DESCRIPTION, mDescription);
        values.put(DataStorage.Collections.TAGS, mTags);
        values.put(DataStorage.Collections.MODIFIED_DATE, Calendar.getInstance()
                .getTime().getTime());
        values.put(DataStorage.Collections.TYPE, getTypeOfCollection(String.valueOf(etCollectionType.getText())));
        if (this.getTag().equals("EditCollection")) {
            values.put(DataStorage.Collections.SYNCHRONIZED, false);
            Toast.makeText(getActivity(), context.getString(R.string
                    .collection_edited), Toast.LENGTH_LONG).show();

            AsyncQueryHandler handler =
                    new AsyncQueryHandler(getActivity().getContentResolver()) {
                    };
            handler.startUpdate(-1, null, DataStorage.Collections.CONTENT_URI, values,
                    DataStorage.Collections._ID + " = " + mEditId, null);
        } else {
            showAToast(getString(R.string.collection_added), Toast.LENGTH_SHORT);
            values.put(DataStorage.Collections.CREATED_DATE, Calendar.getInstance()
                    .getTime().getTime());

            AsyncQueryHandler handler =
                    new AsyncQueryHandler(getActivity().getContentResolver()) {
                    };
            handler.startInsert(-1, null, DataStorage
                    .Collections.CONTENT_URI, values);

        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mEditId != null) outState.putLong("editId", mEditId);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {

        switch (id) {
            case LOAD_DATA_FOR_EDIT:
                Uri uri2 = DataStorage.Collections.CONTENT_URI;
                String[] projection2 = DataStorage.Collections.TABLE_COLUMNS;
                return new CursorLoader(context, uri2, projection2, String.format("%s = %s", DataStorage.Collections._ID, mEditId), null, null);
            case LOAD_NAMES:
                Uri uri3 = DataStorage.Collections.CONTENT_URI;
                String[] projection3 = {DataStorage.Collections._ID, DataStorage.Collections.NAME};
                String selection3 = String.format("NOT %s ", DataStorage.Collections.DELETED);
                return new CursorLoader(context, uri3, projection3, selection3, null, null);
            default:
                throw new IllegalArgumentException("there is no action for id: " + id);
        }
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {

        cursor.moveToFirst();
        switch (loader.getId()) {
            case LOAD_DATA_FOR_EDIT:
                mName = cursor.getString(cursor.getColumnIndex(DataStorage.Collections.NAME));
                getActivity().setTitle(mName); //ActionBar title
                etCollectionName.setText(mName);
                mDescription = cursor.getString(cursor.getColumnIndex(DataStorage.Collections.DESCRIPTION));
                etCollectionDescription.setText(mDescription);
                mTags = cursor.getString(cursor.getColumnIndex(DataStorage.Collections.TAGS));
                etCollectionTags.setText(mTags);
                int type = cursor.getInt(cursor.getColumnIndex(DataStorage.Collections.TYPE));
                etCollectionType.setText(getNameOfCollectionType(type));
                typeOfCollectionBeforeChange = type;
            case LOAD_NAMES:
                while (!cursor.isAfterLast()) {
                    if (mEditId != null) {
                        if (cursor.getLong(cursor.getColumnIndex(
                                DataStorage.Collections._ID)) == mEditId) {
                            cursor.moveToNext();
                            continue; //can edit if name not changed
                        }
                    }
                    mNamesList.add(cursor.getString(cursor.getColumnIndex(DataStorage.Collections.NAME)));
                    cursor.moveToNext();
                }

        }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {

    }

    boolean isWhiteSpaces(String s) {
        return s != null && s.matches("\\s+");
    }

    private int getTypeOfCollection(String name) {

        for (Integer i : typesMap.keySet()) {
            if (typesMap.get(i).equals(name)) return i;
        }
        return DataStorage.TypeOfCollection.ERROR.getType();
    }

    private String getNameOfCollectionType(int type) {
        if (typesMap.containsKey(type)) return typesMap.get(type);
        return typesMap.get(DataStorage.TypeOfCollection.OFFLINE.getType());
    }

    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        EditText et = (EditText) view;
        if (hasFocus) {
            et.setTextColor(getResources().getColor(R.color.white));
        } else
            et.setTextColor(getResources().getColor(R.color.yellow_main));
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TYPE_REQUEST_CODE:
                etCollectionType.setText(data.getStringExtra("type"));
                break;
            case CONFIRM_REQUEST_CODE:
                saveDataInDataBase();
                getActivity().getSupportFragmentManager().popBackStack();
                break;

        }
    }

    @Override
    public void onClick(View view) {
        Bundle args = new Bundle();
        args.putString("type", String.valueOf(etCollectionType.getText()));
        TypeDialog typeDialog = new TypeDialog();
        typeDialog.setArguments(args);
        typeDialog.setTargetFragment(this, TYPE_REQUEST_CODE);
        typeDialog.show(getFragmentManager(), "");
    }
}


text: <!-- Left Side Of Navbar -->


text:
svnhooks
========

svn pre-commit hooks with reviewboard


text:
package widoco.gui;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.Iterator;
import widoco.Configuration;

/**
 *
 * @author dgarijo
 */
public class SelectLanguage extends javax.swing.JFrame {
private final Configuration c;
private final GuiStep2 g;
private final String previousLang;//an auxiliar param to knw if the text field is being edited
    /**
     * Creates new form SelectLanguage
     * @param g
     * @param c
     */
    public SelectLanguage(GuiStep2 g, Configuration c) {
        initComponents();
        this.setIconImage(c.getWidocoLogoMini());
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        // Determine the new location of the window
        int w = this.getSize().width;
        int h = this.getSize().height;
        int x = (dim.width-w)/2;
        int y = (dim.height-h)/2;

        // Move the window
        this.setLocation(x, y);

        this.g = g;
        this.c = c;

        Iterator<String> itLanguages = c.getLanguagesToGenerateDoc().iterator();
        String lang = "";
        while(itLanguages.hasNext()){
            String nextL = itLanguages.next();
            if (nextL.contains("en")){
                en.setSelected(true);
            }
            else if(nextL.contains("es")){
                es.setSelected(true);
            }
            else if(nextL.contains("pt")){
                pt.setSelected(true);
            }
            else if(nextL.contains("fr")){
                fr.setSelected(true);
            }
            else if(nextL.contains("cs")){
                cs.setSelected(true);
            }
            else if(nextL.contains("nl")){
                nl.setSelected(true);
            }
            else if(nextL.contains("it")){
                it.setSelected(true);
            }
            else if(nextL.contains("de")){
                de.setSelected(true);
            }
            else{
                otherText.setText(nextL);
                lang = nextL;
            }
        }
        this.previousLang = lang;
        //load the languages here
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        doneButton = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        otherText = new javax.swing.JTextField();
        it = new javax.swing.JCheckBox();
        de = new javax.swing.JCheckBox();
        en = new javax.swing.JCheckBox();
        fr = new javax.swing.JCheckBox();
        es = new javax.swing.JCheckBox();
        pt = new javax.swing.JCheckBox();
        cs = new javax.swing.JCheckBox();
        nl = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Languages...");
        setAlwaysOnTop(true);
        setResizable(true);

        jLabel1.setText("Select languages from the following list:");

        doneButton.setText("Done");
        doneButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                doneButtonActionPerformed(evt);
            }
        });

        jLabel2.setText("Other (will select labels in that lang):");

        it.setText("it");
        de.setText("de");
        en.setText("en (default)");
        fr.setText("fr");
        es.setText("es");
        pt.setText("pt");
        cs.setText("cs");
        nl.setText("nl");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(doneButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(otherText)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(nl)
                            .addComponent(cs)
                            .addComponent(pt)
                            .addComponent(en)
                            .addComponent(fr)
                            .addComponent(es)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(de)
                            .addComponent(it))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(9, 9, 9)
                .addComponent(en)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(es)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pt)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(fr)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cs)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(nl)
                .addGap(6, 6, 6)
                .addComponent(it)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(de)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 5, Short.MAX_VALUE)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(otherText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(doneButton))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void doneButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_doneButtonActionPerformed
        //set the languages
       if(en.isSelected()){
           this.c.addLanguageToGenerate("en");
       }else{
           this.c.removeLanguageToGenerate("en");
       }
       if(es.isSelected()){
           this.c.addLanguageToGenerate("es");
       }else{
           this.c.removeLanguageToGenerate("es");
       }
       if(pt.isSelected()){
           this.c.addLanguageToGenerate("pt");
       }else{
           this.c.removeLanguageToGenerate("pt");
       }
       if(fr.isSelected()){
           this.c.addLanguageToGenerate("fr");
       }else{
           this.c.removeLanguageToGenerate("fr");
       }
       if(cs.isSelected()){
           this.c.addLanguageToGenerate("cs");
       }else{
           this.c.removeLanguageToGenerate("cs");
       }
        if(nl.isSelected()){
            this.c.addLanguageToGenerate("nl");
        }else{
            this.c.removeLanguageToGenerate("nl");
        }
        if(it.isSelected()){
            this.c.addLanguageToGenerate("it");
        }else{
            this.c.removeLanguageToGenerate("it");
        }
        if(de.isSelected()){
            this.c.addLanguageToGenerate("de");
        }else{
            this.c.removeLanguageToGenerate("de");
        }
       String otherL = otherText.getText();
       if(!"".equals(otherL)){
           this.c.addLanguageToGenerate(otherL);
       }else{//empty text
           if(!"".equals(previousLang)){
               c.removeLanguageToGenerate(previousLang);
           }
       }
       if(c.getLanguagesToGenerateDoc().isEmpty()){
           c.addLanguageToGenerate("en");
       }
       g.refreshLanguages();
       this.dispose();
    }//GEN-LAST:event_doneButtonActionPerformed

    /**
     * @param args the command line arguments
     */

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JCheckBox nl;
    private javax.swing.JCheckBox cs;
    private javax.swing.JCheckBox de;
    private javax.swing.JButton doneButton;
    private javax.swing.JCheckBox en;
    private javax.swing.JCheckBox es;
    private javax.swing.JCheckBox fr;
    private javax.swing.JCheckBox it;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField otherText;
    private javax.swing.JCheckBox pt;
    // End of variables declaration//GEN-END:variables
}