text:
#if HAVE_CONFIG_H
#  include <config.h>
#endif				/* HAVE_CONFIG_H */

#include <complib/cl_types.h>
#include <complib/cl_debug.h>
#include <complib/cl_spinlock.h>

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

/*
 *  Prototypes
 */

extern
 cl_status_t __cl_timer_prov_create(void);

extern
void __cl_timer_prov_destroy(void);

cl_spinlock_t cl_atomic_spinlock;

void complib_init(void)
{
	cl_status_t status = CL_SUCCESS;

	status = cl_spinlock_init(&cl_atomic_spinlock);
	if (status != CL_SUCCESS)
		goto _error;

	status = __cl_timer_prov_create();
	if (status != CL_SUCCESS)
		goto _error;
	return;

_error:
	cl_msg_out("__init: failed to create complib (%s)\n",
		   CL_STATUS_MSG(status));
	exit(1);
}

void complib_exit(void)
{
	__cl_timer_prov_destroy();
	cl_spinlock_destroy(&cl_atomic_spinlock);
}

boolean_t cl_is_debug(void)
{
#if defined( _DEBUG_ )
	return TRUE;
#else
	return FALSE;
#endif				/* defined( _DEBUG_ ) */
}


text:
Contribution are always **welcome and recommended**! Here is how:

- Fork the repository ([here is the guide](https://help.github.com/articles/fork-a-repo/)).
- Clone to your machine ```git clone https://github.com/YOUR_USERNAME/novel.git```
- Make your changes
- Create a pull request

redpajama_set_name: RedPajamaGithub


text:
package org.glyptodon.guacamole.net.basic.rest.auth;

import com.google.inject.Inject;
import java.io.UnsupportedEncodingException;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.xml.bind.DatatypeConverter;
import org.glyptodon.guacamole.GuacamoleException;
import org.glyptodon.guacamole.environment.Environment;
import org.glyptodon.guacamole.net.auth.AuthenticationProvider;
import org.glyptodon.guacamole.net.auth.Credentials;
import org.glyptodon.guacamole.net.auth.UserContext;
import org.glyptodon.guacamole.net.auth.credentials.CredentialsInfo;
import org.glyptodon.guacamole.net.auth.credentials.GuacamoleInvalidCredentialsException;
import org.glyptodon.guacamole.net.basic.GuacamoleSession;
import org.glyptodon.guacamole.net.basic.rest.APIError;
import org.glyptodon.guacamole.net.basic.rest.APIRequest;
import org.glyptodon.guacamole.net.basic.rest.AuthProviderRESTExposure;
import org.glyptodon.guacamole.net.basic.rest.APIException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A service for managing auth tokens via the Guacamole REST API.
 *
 * @author James Muehlner
 */
@Path("/tokens")
@Produces(MediaType.APPLICATION_JSON)
public class TokenRESTService {

    /**
     * The Guacamole server environment.
     */
    @Inject
    private Environment environment;

    /**
     * The authentication provider used to authenticate this user.
     */
    @Inject
    private AuthenticationProvider authProvider;

    /**
     * The map of auth tokens to sessions for the REST endpoints.
     */
    @Inject
    private TokenSessionMap tokenSessionMap;

    /**
     * A generator for creating new auth tokens.
     */
    @Inject
    private AuthTokenGenerator authTokenGenerator;

    /**
     * Logger for this class.
     */
    private static final Logger logger = LoggerFactory.getLogger(TokenRESTService.class);

    /**
     * Regular expression which matches any IPv4 address.
     */
    private static final String IPV4_ADDRESS_REGEX = "([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})";

    /**
     * Regular expression which matches any IPv6 address.
     */
    private static final String IPV6_ADDRESS_REGEX = "([0-9a-fA-F]*(:[0-9a-fA-F]*){0,7})";

    /**
     * Regular expression which matches any IP address, regardless of version.
     */
    private static final String IP_ADDRESS_REGEX = "(" + IPV4_ADDRESS_REGEX + "|" + IPV6_ADDRESS_REGEX + ")";

    /**
     * Pattern which matches valid values of the de-facto standard
     * "X-Forwarded-For" header.
     */
    private static final Pattern X_FORWARDED_FOR = Pattern.compile("^" + IP_ADDRESS_REGEX + "(, " + IP_ADDRESS_REGEX + ")*$");

    /**
     * Returns a formatted string containing an IP address, or list of IP
     * addresses, which represent the HTTP client and any involved proxies. As
     * the headers used to determine proxies can easily be forged, this data is
     * superficially validated to ensure that it at least looks like a list of
     * IPs.
     *
     * @param request
     *     The HTTP request to format.
     *
     * @return
     *     A formatted string containing one or more IP addresses.
     */
    private String getLoggableAddress(HttpServletRequest request) {

        // Log X-Forwarded-For, if present and valid
        String header = request.getHeader("X-Forwarded-For");
        if (header != null && X_FORWARDED_FOR.matcher(header).matches())
            return "[" + header + ", " + request.getRemoteAddr() + "]";

        // If header absent or invalid, just use source IP
        return request.getRemoteAddr();

    }

    /**
     * Authenticates a user, generates an auth token, associates that auth token
     * with the user's UserContext for use by further requests. If an existing
     * token is provided, the authentication procedure will attempt to update
     * or reuse the provided token.
     *
     * @param username
     *     The username of the user who is to be authenticated.
     *
     * @param password
     *     The password of the user who is to be authenticated.
     *
     * @param token
     *     An optional existing auth token for the user who is to be
     *     authenticated.
     *
     * @param consumedRequest
     *     The HttpServletRequest associated with the login attempt. The
     *     parameters of this request may not be accessible, as the request may
     *     have been fully consumed by JAX-RS.
     *
     * @param parameters
     *     A MultivaluedMap containing all parameters from the given HTTP
     *     request. All request parameters must be made available through this
     *     map, even if those parameters are no longer accessible within the
     *     now-fully-consumed HTTP request.
     *
     * @return The auth token for the newly logged-in user.
     * @throws GuacamoleException If an error prevents successful login.
     */
    @POST
    @AuthProviderRESTExposure
    public APIAuthToken createToken(@FormParam("username") String username,
            @FormParam("password") String password,
            @FormParam("token") String token,
            @Context HttpServletRequest consumedRequest,
            MultivaluedMap<String, String> parameters)
            throws GuacamoleException {

        // Reconstitute the HTTP request with the map of parameters
        HttpServletRequest request = new APIRequest(consumedRequest, parameters);

        // Pull existing session if token provided
        GuacamoleSession existingSession;
        if (token != null)
            existingSession = tokenSessionMap.get(token);
        else
            existingSession = null;

        // If no username/password given, try Authorization header
        if (username == null && password == null) {

            String authorization = request.getHeader("Authorization");
            if (authorization != null && authorization.startsWith("Basic ")) {

                try {

                    // Decode base64 authorization
                    String basicBase64 = authorization.substring(6);
                    String basicCredentials = new String(DatatypeConverter.parseBase64Binary(basicBase64), "UTF-8");

                    // Pull username/password from auth data
                    int colon = basicCredentials.indexOf(':');
                    if (colon != -1) {
                        username = basicCredentials.substring(0, colon);
                        password = basicCredentials.substring(colon + 1);
                    }
                    else
                        logger.debug("Invalid HTTP Basic \"Authorization\" header received.");

                }

                // UTF-8 support is required by the Java specification
                catch (UnsupportedEncodingException e) {
                    throw new UnsupportedOperationException("Unexpected lack of UTF-8 support.", e);
                }

            }

        } // end Authorization header fallback

        // Build credentials
        Credentials credentials = new Credentials();
        credentials.setUsername(username);
        credentials.setPassword(password);
        credentials.setRequest(request);
        credentials.setSession(request.getSession(true));

        UserContext userContext;
        try {

            // Update existing user context if session already exists
            if (existingSession != null)
                userContext = authProvider.updateUserContext(existingSession.getUserContext(), credentials);

            /// Otherwise, generate a new user context
            else {

                userContext = authProvider.getUserContext(credentials);

                // Log successful authentication
                if (userContext != null && logger.isInfoEnabled())
                    logger.info("User \"{}\" successfully authenticated from {}.",
                            userContext.self().getIdentifier(), getLoggableAddress(request));

            }

            // Request standard username/password if no user context was produced
            if (userContext == null)
                throw new GuacamoleInvalidCredentialsException("Permission Denied.",
                        CredentialsInfo.USERNAME_PASSWORD);

        }
        catch (GuacamoleException e) {

            // Log authentication failures with associated usernames
            if (username != null) {
                if (logger.isWarnEnabled())
                    logger.warn("Authentication attempt from {} for user \"{}\" failed.",
                            getLoggableAddress(request), username);
            }

            // Log anonymous authentication failures
            else if (logger.isDebugEnabled())
                logger.debug("Anonymous authentication attempt from {} failed.",
                        getLoggableAddress(request), username);

            throw e;
        }

        // Update existing session, if it exists
        String authToken;
        if (existingSession != null) {
            authToken = token;
            existingSession.setCredentials(credentials);
            existingSession.setUserContext(userContext);
        }

        // If no existing session, generate a new token/session pair
        else {
            authToken = authTokenGenerator.getToken();
            tokenSessionMap.put(authToken, new GuacamoleSession(environment, credentials, userContext));
        }

        logger.debug("Login was successful for user \"{}\".", userContext.self().getIdentifier());
        return new APIAuthToken(authToken, userContext.self().getIdentifier());

    }

    /**
     * Invalidates a specific auth token, effectively logging out the associated
     * user.
     *
     * @param authToken The token being invalidated.
     */
    @DELETE
    @Path("/{token}")
    @AuthProviderRESTExposure
    public void invalidateToken(@PathParam("token") String authToken) {

        GuacamoleSession session = tokenSessionMap.remove(authToken);
        if (session == null)
            throw new APIException(APIError.Type.NOT_FOUND, "No such token.");

        session.invalidate();

    }

}


text:
package org.kuali.rice.krad.lookup;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.kuali.rice.core.api.CoreApiServiceLocator;
import org.kuali.rice.core.api.encryption.EncryptionService;
import org.kuali.rice.core.api.search.SearchOperator;
import org.kuali.rice.coreservice.framework.CoreFrameworkServiceLocator;
import org.kuali.rice.krad.bo.ExternalizableBusinessObject;
import org.kuali.rice.krad.data.KradDataServiceLocator;
import org.kuali.rice.krad.datadictionary.RelationshipDefinition;
import org.kuali.rice.krad.datadictionary.exception.UnknownBusinessClassAttributeException;
import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
import org.kuali.rice.krad.service.ModuleService;
import org.kuali.rice.krad.uif.UifConstants;
import org.kuali.rice.krad.uif.UifPropertyPaths;
import org.kuali.rice.krad.uif.lifecycle.ComponentPostMetadata;
import org.kuali.rice.krad.uif.lifecycle.ViewPostMetadata;
import org.kuali.rice.krad.uif.util.ObjectPropertyUtils;
import org.kuali.rice.krad.util.ExternalizableBusinessObjectUtils;
import org.kuali.rice.krad.util.KRADConstants;
import org.kuali.rice.krad.util.KRADPropertyConstants;
import org.kuali.rice.krad.util.KRADUtils;
import org.kuali.rice.krad.web.form.UifFormBase;
import org.springframework.beans.PropertyAccessorUtils;

import javax.servlet.http.HttpServletRequest;

import java.sql.Date;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Provides static utility methods for use within the lookup framework.
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class LookupUtils {
    private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(LookupUtils.class);
    private static final String[] searchList = new String[SearchOperator.QUERY_CHARACTERS.size()];

    static {
        int index = 0;
        for (SearchOperator operator : SearchOperator.QUERY_CHARACTERS) {
            searchList[index++] = operator.op();
        }
    }

    private static final String[] replacementList = Collections.nCopies(searchList.length, "").toArray(new String[0]);

    private LookupUtils() {}

    /**
     * Retrieves the value for the given parameter name to send as a lookup parameter.
     *
     * @param form form instance to retrieve values from
     * @param request request object to retrieve parameters from
     * @param lookupObjectClass data object class associated with the lookup, used to check whether the
     * value needs to be encyrpted
     * @param propertyName name of the property associated with the parameter, used to check whether the
     * value needs to be encrypted
     * @param parameterName name of the parameter to retrieve the value for
     * @return String parameter value or empty string if no value was found
     */
    public static String retrieveLookupParameterValue(UifFormBase form, HttpServletRequest request,
            Class<?> lookupObjectClass, String propertyName, String parameterName) {
        // return a null value if it is secure
        if (KRADUtils.isSecure(propertyName, lookupObjectClass)) {
            LOG.warn("field name " + propertyName + " is a secure value and not returned in parameter result value");
            return null;
        }

        String parameterValue = "";

        // get literal parameter values first
        if (StringUtils.startsWith(parameterName, "'") && StringUtils.endsWith(parameterName, "'")) {
            parameterValue = StringUtils.substringBetween(parameterName, "'");
        } else if (parameterValue.startsWith(KRADConstants.LOOKUP_PARAMETER_LITERAL_PREFIX
                + KRADConstants.LOOKUP_PARAMETER_LITERAL_DELIMITER)) {
            parameterValue = StringUtils.removeStart(parameterValue, KRADConstants.LOOKUP_PARAMETER_LITERAL_PREFIX
                    + KRADConstants.LOOKUP_PARAMETER_LITERAL_DELIMITER);
        }
        // check if parameter is in request
        else if (request.getParameterMap().containsKey(parameterName)) {
            parameterValue = request.getParameter(parameterName);
        }
        // get parameter value from form object
        else {
            parameterValue = ObjectPropertyUtils.getPropertyValueAsText(form, parameterName);
        }

        return parameterValue;
    }

    /**
     * Retrieves the default KRAD base lookup URL, used to build lookup URLs in code
     *
     * @return String base lookup URL (everything except query string)
     */
    public static String getBaseLookupUrl() {
        return CoreApiServiceLocator.getKualiConfigurationService().getPropertyValueAsString(
                KRADConstants.KRAD_LOOKUP_URL_KEY);
    }

    /**
     * Uses the DataDictionary to determine whether to force uppercase the value, and if it should, then it does the
     * uppercase, and returns the upper-cased value.
     *
     * @param dataObjectClass parent DO class that the fieldName is a member of
     * @param fieldName name of the field to be forced to uppercase
     * @param fieldValue value of the field that may be uppercased
     * @return the correctly uppercased fieldValue if it should be uppercased, otherwise fieldValue is returned
     *         unchanged
     */
    public static String forceUppercase(Class<?> dataObjectClass, String fieldName, String fieldValue) {
        // short-circuit to exit if there isnt enough information to do the forceUppercase
        if (StringUtils.isBlank(fieldValue)) {
            return fieldValue;
        }

        // parameter validation
        if (dataObjectClass == null) {
            throw new IllegalArgumentException("Parameter dataObjectClass passed in with null value.");
        }

        if (StringUtils.isBlank(fieldName)) {
            throw new IllegalArgumentException("Parameter fieldName passed in with empty value.");
        }

        if (!KRADServiceLocatorWeb.getDataDictionaryService().isAttributeDefined(dataObjectClass, fieldName)
                .booleanValue()) {
            return fieldValue;
        }

        boolean forceUpperCase = false;
        try {
            forceUpperCase = KRADServiceLocatorWeb.getDataDictionaryService()
                    .getAttributeForceUppercase(dataObjectClass, fieldName).booleanValue();
        } catch (UnknownBusinessClassAttributeException ubae) {
            // do nothing, don't alter the fieldValue
        }

        if (forceUpperCase && !fieldValue.endsWith(EncryptionService.ENCRYPTION_POST_PREFIX)) {
            return fieldValue.toUpperCase();
        }

        return fieldValue;
    }

    /**
     * Uses the DataDictionary to determine whether to force uppercase the values, and if it should, then it does the
     * uppercase, and returns the upper-cased Map of fieldname/fieldValue pairs.
     *
     * @param dataObjectClass parent DO class that the fieldName is a member of
     * @param fieldValues a Map<String,String> where the key is the fieldName and the value is the fieldValue
     * @return the same Map is returned, with the appropriate values uppercased (if any)
     */
    public static Map<String, String> forceUppercase(Class<?> dataObjectClass, Map<String, String> fieldValues) {
        if (dataObjectClass == null) {
            throw new IllegalArgumentException("Parameter boClass passed in with null value.");
        }

        if (fieldValues == null) {
            throw new IllegalArgumentException("Parameter fieldValues passed in with null value.");
        }

        for (String fieldName : fieldValues.keySet()) {
            fieldValues.put(fieldName, forceUppercase(dataObjectClass, fieldName, fieldValues.get(fieldName)));
        }

        return fieldValues;
    }

    /**
     * Parses and returns the lookup result set limit, checking first for the limit for the specific view,
     * then the class being looked up, and then the global application limit if there isn't a limit specific
     * to this data object class.
     *
     * @param dataObjectClass class to get limit for
     * @param lookupForm lookupForm to use.  May be null if the form is unknown. If lookupForm is null, only the
     * dataObjectClass will be used to find the search results set limit
     * @return result set limit
     */
    public static Integer getSearchResultsLimit(Class dataObjectClass, LookupForm lookupForm) {
        Integer limit = KRADServiceLocatorWeb.getViewDictionaryService().getResultSetLimitForLookup(dataObjectClass,
                lookupForm);
        if (limit == null) {
            limit = getApplicationSearchResultsLimit();
        }

        return limit;
    }

    /**
     * Retrieves the default application search limit configured through a system parameter.
     *
     * @return default result set limit of the application
     */
    public static Integer getApplicationSearchResultsLimit() {
        String limitString = CoreFrameworkServiceLocator.getParameterService()
                .getParameterValueAsString(KRADConstants.KRAD_NAMESPACE,
                        KRADConstants.DetailTypes.LOOKUP_PARM_DETAIL_TYPE,
                        KRADConstants.SystemGroupParameterNames.LOOKUP_RESULTS_LIMIT);
        if (limitString != null) {
            return Integer.valueOf(limitString);
        }

        return null;
    }

    /**
     * Retrieves the default application multiple value search limit configured through a system parameter.
     *
     * @return default multiple value result set limit of the application
     */
    public static Integer getApplicationMultipleValueSearchResultsLimit() {
        String limitString = CoreFrameworkServiceLocator.getParameterService()
                .getParameterValueAsString(KRADConstants.KRAD_NAMESPACE,
                        KRADConstants.DetailTypes.LOOKUP_PARM_DETAIL_TYPE,
                        KRADConstants.SystemGroupParameterNames.MULTIPLE_VALUE_LOOKUP_RESULTS_LIMIT);
        if (limitString != null) {
            return Integer.valueOf(limitString);
        }

        return null;
    }

    /**
     * Determines what Timestamp should be used for active queries on effective dated records. Determination made as
     * follows:
     *
     *

     *
Use activeAsOfDate value from search values Map if value is not empty

     *
If search value given, try to convert to sql date, if conversion fails, try to convert to Timestamp

     *
If search value empty, use current Date

     *
If Timestamp value not given, create Timestamp from given Date setting the time as 1 second before midnight
     *

     *
     * @param searchValues map containing search key/value pairs
     * @return timestamp to be used for active criteria
     */
    public static Timestamp getActiveDateTimestampForCriteria(Map searchValues) {
        Date activeDate = CoreApiServiceLocator.getDateTimeService().getCurrentSqlDate();

        Timestamp activeTimestamp = null;
        if (searchValues.containsKey(KRADPropertyConstants.ACTIVE_AS_OF_DATE)) {
            String activeAsOfDate = (String) searchValues.get(KRADPropertyConstants.ACTIVE_AS_OF_DATE);
            if (StringUtils.isNotBlank(activeAsOfDate)) {
                try {
                    activeDate = CoreApiServiceLocator.getDateTimeService()
                            .convertToSqlDate(KRADUtils.clean(activeAsOfDate));
                } catch (ParseException e) {
                    // try to parse as timestamp
                    try {
                        activeTimestamp = CoreApiServiceLocator.getDateTimeService()
                                .convertToSqlTimestamp(KRADUtils.clean(activeAsOfDate));
                    } catch (ParseException e1) {
                        throw new RuntimeException("Unable to convert date: " + KRADUtils.clean(activeAsOfDate));
                    }
                }
            }
        }

        // if timestamp not given set to 1 second before midnight on the given date
        if (activeTimestamp == null) {
            Calendar cal = Calendar.getInstance();

            cal.setTime(activeDate);
            cal.set(Calendar.HOUR, cal.getMaximum(Calendar.HOUR));
            cal.set(Calendar.MINUTE, cal.getMaximum(Calendar.MINUTE));
            cal.set(Calendar.SECOND, cal.getMaximum(Calendar.SECOND));

            activeTimestamp = new Timestamp(cal.getTime().getTime());
        }

        return activeTimestamp;
    }

    /**
     * Changes from/to dates into the range operators the lookupable dao expects ("..",">" etc) this method modifies
     * the passed in map and returns an updated search criteria map.
     *
     * @param searchCriteria map of criteria currently set for which the date criteria will be adjusted
     * @return map updated search criteria
     */
    public static Map<String, String> preprocessDateFields(Map<String, String> searchCriteria) {
        Map<String, String> fieldsToUpdate = new HashMap<String, String>();
        Map<String, String> searchCriteriaUpdated = new HashMap<String, String>(searchCriteria);

        Set<String> fieldsForLookup = searchCriteria.keySet();
        for (String propName : fieldsForLookup) {
            if (propName.startsWith(KRADConstants.LOOKUP_RANGE_LOWER_BOUND_PROPERTY_PREFIX)) {
                String from_DateValue = searchCriteria.get(propName);
                String dateFieldName =
                        StringUtils.remove(propName, KRADConstants.LOOKUP_RANGE_LOWER_BOUND_PROPERTY_PREFIX);
                String to_DateValue = searchCriteria.get(dateFieldName);
                String newPropValue = to_DateValue;

                if (StringUtils.isNotEmpty(from_DateValue) && StringUtils.isNotEmpty(to_DateValue)) {
                    newPropValue = from_DateValue + SearchOperator.BETWEEN + to_DateValue;
                } else if (StringUtils.isNotEmpty(from_DateValue) && StringUtils.isEmpty(to_DateValue)) {
                    newPropValue = SearchOperator.GREATER_THAN_EQUAL.op() + from_DateValue;
                } else if (StringUtils.isNotEmpty(to_DateValue) && StringUtils.isEmpty(from_DateValue)) {
                    newPropValue = SearchOperator.LESS_THAN_EQUAL.op() + to_DateValue;
                } // could optionally continue on else here

                fieldsToUpdate.put(dateFieldName, newPropValue);
            }
        }

        // update lookup values from found date values to update
        Set<String> keysToUpdate = fieldsToUpdate.keySet();
        for (String updateKey : keysToUpdate) {
            searchCriteriaUpdated.put(updateKey, fieldsToUpdate.get(updateKey));
        }

        return searchCriteriaUpdated;
    }

    /**
     * Checks whether any of the fieldValues being passed refer to a property within an ExternalizableBusinessObject.
     *
     * @param boClass business object class of the lookup
     * @param fieldValues map of the lookup criteria values
     * @return true if externalizable business object are contained, false otherwise
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public static boolean hasExternalBusinessObjectProperty(Class<?> boClass,
            Map<String, String> fieldValues) throws IllegalAccessException, InstantiationException {
        Object sampleBo = boClass.newInstance();
        for (String key : fieldValues.keySet()) {
            if (isExternalBusinessObjectProperty(sampleBo, key)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check whether the given property represents a property within an EBO starting with the sampleBo object given.
     * This is used to determine if a criteria needs to be applied to the EBO first,
     * before sending to the normal lookup DAO.
     *
     * @param sampleBo business object of the property to be tested
     * @param propertyName property name to be tested
     * @return true if the property is within an externalizable business object.
     */
    public static boolean isExternalBusinessObjectProperty(Object sampleBo, String propertyName) {
        if (propertyName.indexOf(".") > 0 && !StringUtils.contains(propertyName, "add.")) {
            Class<?> propertyClass =
                    ObjectPropertyUtils.getPropertyType(sampleBo, StringUtils.substringBeforeLast(propertyName, "."));
            if (propertyClass != null) {
                return ExternalizableBusinessObjectUtils.isExternalizableBusinessObjectInterface(propertyClass);
            }
        }

        return false;
    }

    /**
     * Returns a map stripped of any properties which refer to ExternalizableBusinessObjects. These values may not be
     * passed into the lookup service, since the objects they refer to are not in the
     * local database.
     *
     * @param boClass business object class of the lookup
     * @param fieldValues map of lookup criteria from which to remove the externalizable business objects
     * @return map of lookup criteria without externalizable business objects
     */
    public static Map<String, String> removeExternalizableBusinessObjectFieldValues(Class<?> boClass,
            Map<String, String> fieldValues) throws IllegalAccessException, InstantiationException {
        Map<String, String> eboFieldValues = new HashMap<String, String>();
        Object sampleBo = boClass.newInstance();
        for (String key : fieldValues.keySet()) {
            if (!isExternalBusinessObjectProperty(sampleBo, key)) {
                eboFieldValues.put(key, fieldValues.get(key));
            }
        }

        return eboFieldValues;
    }

    /**
     * Return the EBO fieldValue entries explicitly for the given eboPropertyName. (I.e., any properties with the given
     * property name as a prefix.
     *
     * @param eboPropertyName the externalizable business object property name to retrieve
     * @param fieldValues map of lookup criteria
     * return map of lookup criteria for the given eboPropertyName
     */
    public static Map<String, String> getExternalizableBusinessObjectFieldValues(String eboPropertyName,
            Map<String, String> fieldValues) {
        Map<String, String> eboFieldValues = new HashMap<String, String>();
        for (String key : fieldValues.keySet()) {
            if (key.startsWith(eboPropertyName + ".")) {
                eboFieldValues.put(StringUtils.substringAfterLast(key, "."), fieldValues.get(key));
            }
        }

        return eboFieldValues;
    }

    /**
     * Get the complete list of all properties referenced in the fieldValues that are ExternalizableBusinessObjects.
     *
     *

     * This is a list of the EBO object references themselves, not of the properties within them.
     *

     *
     * @param boClass business object class of the lookup
     * @param fieldValues map of lookup criteria from which to return the externalizable business objects
     * @return map of lookup criteria that are externalizable business objects
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public static List<String> getExternalizableBusinessObjectProperties(Class<?> boClass,
            Map<String, String> fieldValues) throws IllegalAccessException, InstantiationException {
        Set<String> eboPropertyNames = new HashSet<String>();

        Object sampleBo = boClass.newInstance();
        for (String key : fieldValues.keySet()) {
            if (isExternalBusinessObjectProperty(sampleBo, key)) {
                eboPropertyNames.add(StringUtils.substringBeforeLast(key, "."));
            }
        }

        return new ArrayList<String>(eboPropertyNames);
    }

    /**
     * Given an property on the main BO class, return the defined type of the ExternalizableBusinessObject. This will
     * be used by other code to determine the correct module service to call for the lookup.
     *
     * @param boClass business object class of the lookup
     * @param propertyName property of which the externalizable business object type is to be determined
     * @return externalizable business object type
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public static Class<? extends ExternalizableBusinessObject> getExternalizableBusinessObjectClass(Class<?> boClass,
            String propertyName) throws IllegalAccessException, InstantiationException {
        return (Class<? extends ExternalizableBusinessObject>) ObjectPropertyUtils
                .getPropertyType(boClass.newInstance(), StringUtils.substringBeforeLast(propertyName, "."));
    }

    /**
     * Looks for criteria against nested EBOs and performs a search against that EBO and updates the criteria.
     *
     * @param searchCriteria map of criteria currently set
     * @param unbounded indicates whether the complete result should be returned.  When set to false the result is
     * limited (if necessary) to the max search result limit configured.
     * @return Map of adjusted criteria for nested EBOs
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static Map<String, String> adjustCriteriaForNestedEBOs(Class<?> dataObjectClass,
            Map<String, String> searchCriteria,
            boolean unbounded) throws InstantiationException, IllegalAccessException {
        // remove the EBO criteria
        Map<String, String> nonEboFieldValues = removeExternalizableBusinessObjectFieldValues(
                dataObjectClass, searchCriteria);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Non EBO properties removed: " + nonEboFieldValues);
        }

        // get the list of EBO properties attached to this object
        List<String> eboPropertyNames = getExternalizableBusinessObjectProperties(dataObjectClass, searchCriteria);
        if (LOG.isDebugEnabled()) {
            LOG.debug("EBO properties: " + eboPropertyNames);
        }

        // loop over those properties
        for (String eboPropertyName : eboPropertyNames) {
            // extract the properties as known to the EBO
            Map<String, String> eboFieldValues = LookupUtils.getExternalizableBusinessObjectFieldValues(eboPropertyName,
                    searchCriteria);
            if (LOG.isDebugEnabled()) {
                LOG.debug("EBO properties for master EBO property: " + eboPropertyName);
                LOG.debug("properties: " + eboFieldValues);
            }

            // run search against attached EBO's module service
            ModuleService eboModuleService = KRADServiceLocatorWeb.getKualiModuleService().getResponsibleModuleService(
                    getExternalizableBusinessObjectClass(dataObjectClass, eboPropertyName));

            // KULRICE-4401 made eboResults an empty list and only filled if service is found.
            List<?> eboResults = Collections.emptyList();
            if (eboModuleService != null) {
                eboResults = eboModuleService.getExternalizableBusinessObjectsListForLookup(
                        getExternalizableBusinessObjectClass(dataObjectClass, eboPropertyName),
                        (Map) eboFieldValues, unbounded);
            } else {
                LOG.debug("EBO ModuleService is null: " + eboPropertyName);
            }

            // get the parent property type
            Class<?> eboParentClass;
            String eboParentPropertyName;
            if (PropertyAccessorUtils.isNestedOrIndexedProperty(eboPropertyName)) {
                eboParentPropertyName = StringUtils.substringBeforeLast(eboPropertyName, ".");
                try {
                    eboParentClass = KradDataServiceLocator.getDataObjectService().wrap(dataObjectClass.newInstance()).getPropertyType(
                            eboParentPropertyName);
                } catch (Exception ex) {
                    throw new RuntimeException(
                            "Unable to create an instance of the business object class: " + dataObjectClass
                                    .getName(), ex);
                }
            } else {
                eboParentClass = dataObjectClass;
                eboParentPropertyName = null;
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug("determined EBO parent class/property name: " + eboParentClass + "/" + eboParentPropertyName);
            }

            // look that up in the DD (BOMDS) find the appropriate relationship
            // CHECK THIS: what if eboPropertyName is a nested attribute - need to strip off the
            // eboParentPropertyName if not null
            RelationshipDefinition rd = KRADServiceLocatorWeb.getLegacyDataAdapter().getDictionaryRelationship(
                    eboParentClass, eboPropertyName);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Obtained RelationshipDefinition for " + eboPropertyName);
                LOG.debug(rd);
            }

            // copy the needed properties (primary only) to the field values KULRICE-4446 do
            // so only if the relationship definition exists
            // NOTE: this will work only for single-field PK unless the ORM
            // layer is directly involved
            // (can't make (field1,field2) in ( (v1,v2),(v3,v4) ) style
            // queries in the lookup framework
            if (KRADUtils.isNotNull(rd)) {
                if (rd.getPrimitiveAttributes().size() > 1) {
                    throw new RuntimeException(
                            "EBO Links don't work for relationships with multiple-field primary keys.");
                }
                String boProperty = rd.getPrimitiveAttributes().get(0).getSourceName();
                String eboProperty = rd.getPrimitiveAttributes().get(0).getTargetName();
                StringBuffer boPropertyValue = new StringBuffer();

                // loop over the results, making a string that the lookup DAO will convert into an
                // SQL "IN" clause
                for (Object ebo : eboResults) {
                    if (boPropertyValue.length() != 0) {
                        boPropertyValue.append(SearchOperator.OR.op());
                    }
                    try {
                        boPropertyValue.append(PropertyUtils.getProperty(ebo, eboProperty).toString());
                    } catch (Exception ex) {
                        LOG.warn("Unable to get value for " + eboProperty + " on " + ebo);
                    }
                }

                if (eboParentPropertyName == null) {
                    // non-nested property containing the EBO
                    nonEboFieldValues.put(boProperty, boPropertyValue.toString());
                } else {
                    // property nested within the main searched-for BO that contains the EBO
                    nonEboFieldValues.put(eboParentPropertyName + "." + boProperty, boPropertyValue.toString());
                }
            }
        }

        return nonEboFieldValues;
    }

    /**
     * Removes query characters (such as wildcards) from the given string value.
     *
     * @param criteriaValue string to clean
     * @return string with query characters removed
     */
    public static String scrubQueryCharacters(String criteriaValue) {
        return StringUtils.replaceEach(criteriaValue, searchList, replacementList);
    }

    /**
     * Generates a key string in case of multivalue return. The values are extracted
     * from the list of properties on the lineDataObject.
     *
     * If fieldConversionKeys is empty return the identifier string for the lineDataObject
     *
     * @param lineDataObject   Object from which to extract values
     * @param fieldConversionKeys List of keys whose values have to be concatenated
     * @return string representing the multivalue key
     */
    public static String generateMultiValueKey(Object lineDataObject, List<String> fieldConversionKeys) {
        String lineIdentifier = "";

        if(fieldConversionKeys == null || fieldConversionKeys.isEmpty()) {
            lineIdentifier =
                    KRADServiceLocatorWeb.getLegacyDataAdapter().getDataObjectIdentifierString(lineDataObject);
        } else {
            Collections.sort(fieldConversionKeys);
            for (String fromFieldName : fieldConversionKeys) {
                Object fromFieldValue = ObjectPropertyUtils.getPropertyValue(lineDataObject, fromFieldName);

                if (fromFieldValue != null) {
                    lineIdentifier += fromFieldValue;
                }

                lineIdentifier += ":";
            }
            lineIdentifier = StringUtils.removeEnd(lineIdentifier, ":");
        }

        return lineIdentifier;
    }

    /**
     * Merges the lookup result selections that are part of the request with the selectedLookupResultsCache maintained in
     * the session.
     *
     * @param form lookup form instance containing the selected results and lookup configuration
     */
    public static void refreshLookupResultSelections(LookupForm form) {
        int displayStart = 0;
        int displayLength = 0;

        // avoid blowing the stack if the session expired
        ViewPostMetadata viewPostMetadata = form.getViewPostMetadata();
        if (viewPostMetadata != null) {

            // only one concurrent request per view please
            synchronized (viewPostMetadata) {
                ComponentPostMetadata oldCollectionGroup = viewPostMetadata.getComponentPostMetadata("uLookupResults");
                displayStart = (Integer) oldCollectionGroup.getData(UifConstants.PostMetadata.COLL_DISPLAY_START);
                displayLength = (Integer) oldCollectionGroup.getData(UifConstants.PostMetadata.COLL_DISPLAY_LENGTH);
            }
        }

        List<? extends Object> lookupResults = (List<? extends Object>) form.getLookupResults();
        List<String> fromFieldNames = form.getMultiValueReturnFields();

        Set<String> selectedLines = form.getSelectedCollectionLines().get(UifPropertyPaths.LOOKUP_RESULTS);
        Set<String> selectedLookupResultsCache = form.getSelectedLookupResultsCache();

        selectedLines = (selectedLines == null) ? new HashSet<String>() : selectedLines;

        for(int i = displayStart; i < displayStart + displayLength; i++ ) {
            if(i >= form.getLookupResults().size()) break;

            Object lineItem = lookupResults.get(i);
            String lineIdentifier = LookupUtils.generateMultiValueKey(lineItem, fromFieldNames);

            if(!selectedLines.contains(lineIdentifier)) {
                 selectedLookupResultsCache.remove(lineIdentifier);
            } else {
                selectedLookupResultsCache.add(lineIdentifier);
            }
        }

        selectedLines.addAll( selectedLookupResultsCache );

        form.getSelectedCollectionLines().put(UifPropertyPaths.LOOKUP_RESULTS, selectedLines);
    }

}


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<title><%= htmlWebpackPlugin.options.title %></title>

Contact page


text:
require 'spec_helper'

describe Artwork::ProductsController do

end


text:
itk_fetch_module(LesionSizingToolkit
  "Framework for determining the sizes of lesions in medical images."
  MODULE_COMPLIANCE_LEVEL 2
  GIT_REPOSITORY ${git_protocol}://github.com/InsightSoftwareConsortium/LesionSizingToolkit.git
  GIT_TAG c4f607bcfb1a8e44d7643411e43ae5480739bd99
  )


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.operator;

import com.facebook.presto.memory.context.LocalMemoryContext;
import com.facebook.presto.metadata.Split;
import com.facebook.presto.spi.ColumnHandle;
import com.facebook.presto.spi.ConnectorPageSource;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.UpdatablePageSource;
import com.facebook.presto.split.EmptySplit;
import com.facebook.presto.split.EmptySplitPageSource;
import com.facebook.presto.split.PageSourceProvider;
import com.facebook.presto.sql.planner.plan.PlanNodeId;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;

import java.io.Closeable;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;

import static com.google.common.base.Preconditions.checkState;
import static io.airlift.concurrent.MoreFutures.toListenableFuture;
import static java.util.Objects.requireNonNull;

public class TableScanOperator
        implements SourceOperator, Closeable
{
    public static class TableScanOperatorFactory
            implements SourceOperatorFactory
    {
        private final int operatorId;
        private final PlanNodeId sourceId;
        private final PageSourceProvider pageSourceProvider;
        private final List<ColumnHandle> columns;
        private boolean closed;

        public TableScanOperatorFactory(
                int operatorId,
                PlanNodeId sourceId,
                PageSourceProvider pageSourceProvider,
                Iterable<ColumnHandle> columns)
        {
            this.operatorId = operatorId;
            this.sourceId = requireNonNull(sourceId, "sourceId is null");
            this.pageSourceProvider = requireNonNull(pageSourceProvider, "pageSourceProvider is null");
            this.columns = ImmutableList.copyOf(requireNonNull(columns, "columns is null"));
        }

        @Override
        public PlanNodeId getSourceId()
        {
            return sourceId;
        }

        @Override
        public SourceOperator createOperator(DriverContext driverContext)
        {
            checkState(!closed, "Factory is already closed");
            OperatorContext operatorContext = driverContext.addOperatorContext(operatorId, sourceId, TableScanOperator.class.getSimpleName());
            return new TableScanOperator(
                    operatorContext,
                    sourceId,
                    pageSourceProvider,
                    columns);
        }

        @Override
        public void noMoreOperators()
        {
            closed = true;
        }
    }

    private final OperatorContext operatorContext;
    private final PlanNodeId planNodeId;
    private final PageSourceProvider pageSourceProvider;
    private final List<ColumnHandle> columns;
    private final LocalMemoryContext systemMemoryContext;
    private final SettableFuture<?> blocked = SettableFuture.create();

    private Split split;
    private ConnectorPageSource source;

    private boolean finished;

    private long completedBytes;
    private long readTimeNanos;

    public TableScanOperator(
            OperatorContext operatorContext,
            PlanNodeId planNodeId,
            PageSourceProvider pageSourceProvider,
            Iterable<ColumnHandle> columns)
    {
        this.operatorContext = requireNonNull(operatorContext, "operatorContext is null");
        this.planNodeId = requireNonNull(planNodeId, "planNodeId is null");
        this.pageSourceProvider = requireNonNull(pageSourceProvider, "pageSourceProvider is null");
        this.columns = ImmutableList.copyOf(requireNonNull(columns, "columns is null"));
        this.systemMemoryContext = operatorContext.newLocalSystemMemoryContext(TableScanOperator.class.getSimpleName());
    }

    @Override
    public OperatorContext getOperatorContext()
    {
        return operatorContext;
    }

    @Override
    public PlanNodeId getSourceId()
    {
        return planNodeId;
    }

    @Override
    public Supplier<Optional<UpdatablePageSource>> addSplit(Split split)
    {
        requireNonNull(split, "split is null");
        checkState(this.split == null, "Table scan split already set");

        if (finished) {
            return Optional::empty;
        }

        this.split = split;

        Object splitInfo = split.getInfo();
        if (splitInfo != null) {
            operatorContext.setInfoSupplier(() -> new SplitOperatorInfo(splitInfo));
        }

        blocked.set(null);

        if (split.getConnectorSplit() instanceof EmptySplit) {
            source = new EmptySplitPageSource();
        }

        return () -> {
            if (source instanceof UpdatablePageSource) {
                return Optional.of((UpdatablePageSource) source);
            }
            return Optional.empty();
        };
    }

    @Override
    public void noMoreSplits()
    {
        if (split == null) {
            finished = true;
        }
        blocked.set(null);
    }

    @Override
    public void close()
    {
        finish();
    }

    @Override
    public void finish()
    {
        finished = true;
        blocked.set(null);

        if (source != null) {
            try {
                source.close();
            }
            catch (IOException e) {
                throw new UncheckedIOException(e);
            }
            systemMemoryContext.setBytes(source.getSystemMemoryUsage());
        }
    }

    @Override
    public boolean isFinished()
    {
        if (!finished) {
            finished = (source != null) && source.isFinished();
            if (source != null) {
                systemMemoryContext.setBytes(source.getSystemMemoryUsage());
            }
        }

        return finished;
    }

    @Override
    public ListenableFuture<?> isBlocked()
    {
        if (!blocked.isDone()) {
            return blocked;
        }
        if (source != null) {
            CompletableFuture<?> pageSourceBlocked = source.isBlocked();
            return pageSourceBlocked.isDone() ? NOT_BLOCKED : toListenableFuture(pageSourceBlocked);
        }
        return NOT_BLOCKED;
    }

    @Override
    public boolean needsInput()
    {
        return false;
    }

    @Override
    public void addInput(Page page)
    {
        throw new UnsupportedOperationException(getClass().getName() + " can not take input");
    }

    @Override
    public Page getOutput()
    {
        if (split == null) {
            return null;
        }
        if (source == null) {
            source = pageSourceProvider.createPageSource(operatorContext.getSession(), split, columns);
        }

        Page page = source.getNextPage();
        if (page != null) {
            // assure the page is in memory before handing to another operator
            page = page.getLoadedPage();

            // update operator stats
            long endCompletedBytes = source.getCompletedBytes();
            long endReadTimeNanos = source.getReadTimeNanos();
            operatorContext.recordRawInputWithTiming(endCompletedBytes - completedBytes, endReadTimeNanos - readTimeNanos);
            operatorContext.recordProcessedInput(page.getSizeInBytes(), page.getPositionCount());
            completedBytes = endCompletedBytes;
            readTimeNanos = endReadTimeNanos;
        }

        // updating system memory usage should happen after page is loaded.
        systemMemoryContext.setBytes(source.getSystemMemoryUsage());

        return page;
    }
}


text:
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">

<link rel="stylesheet"
	href="<?php echo base_url();?>resources/bootstrap-3.3.7-dist/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css"
	href="<?php echo base_url();?>resources/styles/estilo.css">

Nombre Snombre Apellido Sapellido

GENERATE FORM

{{title}}

				{{title}}

				<form id="form_{{id}}"  class="form-horizontal formComponent"  >

Generar Json

				</form>

		<button class = "createElementBtn col-xs-2 btn btn-default" >{{text}}</button>

			<button class="addComponentBtn col-xs-3 btn btn-default">{{text}}</button>

			    ▼

				Lugar:

			    ▼

				Fecha:

			<input type="text" class="form-control" id="text_{{id}}" name="text_{{id}}" placeholder="{{placeholder}}">

			    ▼

				Documento:

			    ▼

				Bautizo:

			    ▼

				Defunción:

						País

							<input type="text" class="form-control exampleUpdater _pais" id="{{id}}_pais" name="{{id}}_pais" placeholder="Chile">

						Ciudad

							<input type="text" class="form-control exampleUpdater _ciudad" id="{{id}}_ciudad" name="{{id}}_ciudad" placeholder="Santiago">

						Tipo de Lugar

							<select type="text" class="form-control exampleUpdater _tipo" id="{{id}}_tipo" name="{{id}}_tipo" placeholder="">

								<option value="">Seleccionar...</option>
								<option value="Comuna">Comuna</option>
								<option value="Hacienda">Hacienda</option>
								<option value="Dirección">Dirección</option>
							</select>

						Lugar

							<input type="text" class="form-control exampleUpdater _valor" id="{{id}}_valor" name="{{id}}_valor" placeholder="">

						<button type="button" class="btn btn-success" data-dismiss="modal">Aceptar</button>
						<button type="button" class="btn btn-danger" data-dismiss="modal">Limpiar</button>

						Tipo de Fecha

							<select type="text" class="form-control _tipo_id" id="{{id}}_tipo_id" name="{{id}}_tipo_id" placeholder="">

								<option value="normal">Normal: 05/06/1992</option>
								<option value="ano">Año: 1992</option>
								<option value="cercana">Cerca de 1992</option>
								<option value="siglo">Siglo 20</option>
								<option value="rangoNormal">Rango de Fecha: 01/07/1990 - 05/06/1992</option>
								<option value="rangoAno">Rango de Año: 1990 - 1992</option>
							</select>

						Fecha

							<input type="text" class="form-control _dia-inicial" id="{{id}}_dia-inicial" name="{{id}}_dia-inicial" placeholder="">/

							<input type="text" class="form-control _mes-inicial" id="{{id}}_mes-inicial" name="{{id}}_mes-inicial" placeholder="">/

							<input type="text" class="form-control _ano-inicial" id="{{id}}_ano-inicial" name="{{id}}_ano-inicial" placeholder="">

						<input id="{{id}}_no-estoy-seguro" type="checkbox" name="{{id}}_no-estoy-seguro" class="_no-estoy-seguro">No Estoy Seguro

						Fecha

							<input type="text" class="form-control _dia-final" id="{{id}}_dia-final" name="{{id}}_dia-final" placeholder="">/

							<input type="text" class="form-control _mes-final" id="{{id}}_mes-final" name="{{id}}_mes-final" placeholder="">/

							<input type="text" class="form-control _ano-final" id="{{id}}_ano-final" name="{{id}}_ano-final" placeholder="">

						<input type="text" class="form-control exampleUpdater _output" id="{{id}}_output" name="{{id}}_output" placeholder="" value="">

						<button type="button" class="btn btn-success" data-dismiss="modal">Aceptar</button>
						<button type="button" class="btn btn-danger" data-dismiss="modal">Limpiar</button>

						File

							<input type="file" class="form-control file_" id="file_{{id}}" name="file_{{id}}" placeholder="">/

							<button type="button" class="btn btn-success" data-dismiss="modal">Aceptar</button>
							<button type="button" class="btn btn-danger" data-dismiss="modal">Limpiar</button>

						Padrino(s)

							<input type="text" class="form-control exampleUpdater" id="bautizoPadrino_{{id}}" name="bautizoPadrino_{{id}}">

						Madrina(s)

							<input type="text" class="form-control exampleUpdater" id="bautizoMadrina_{{id}}" name="bautizoMadrina_{{id}}">

						Registro Bautizo

							<input type="text" class="form-control exampleUpdater" id="bautizoRegistro_{{id}}" name="bautizoRegistro_{{id}}">

						Comentario

							<textarea class="form-control exampleUpdater" id="bautizoComentario_{{id}}" name="bautizoComentario_{{id}}" rows="3"></textarea>

						<button type="button" class="btn btn-success" data-dismiss="modal">Aceptar</button>
						<button type="button" class="btn btn-danger" data-dismiss="modal">Limpiar</button>

						Testigo(s)

							<input type="text" class="form-control exampleUpdater" id="defuncionTestigo_{{id}}" name="defuncionTestigo_{{id}}">

						NumReg(s)

							<input type="text" class="form-control exampleUpdater" id="defuncionNumReg_{{id}}" name="defuncionNumReg_{{id}}">

						Comentario

							<textarea class="form-control exampleUpdater" id="defuncionComentario_{{id}}" name="defuncionComentario_{{id}}" rows="3"></textarea>

						<button type="button" class="btn btn-success" data-dismiss="modal">Aceptar</button>
						<button type="button" class="btn btn-danger" data-dismiss="modal">Limpiar</button>


text:
cd harness
cordova platform remove android
cordova plugin remove cordova-plugin-xapp
cordova plugin add --link ../
cordova platform add android


text:
/**
 * Sponge Knowledge Base
 * Using rules - synchronous and asynchronous
 */

var correlationEventsLog;

function onInit() {
    // Variables for assertions only
    correlationEventsLog = new org.openksavi.sponge.examples.util.CorrelationEventsLog();
    sponge.setVariable("correlationEventsLog", correlationEventsLog);
}

var RuleFFF = Java.extend(Rule, {
    onConfigure: function(self) {
        self.withEvents(["e1", "e2", "e3 :first"]).withSynchronous(true);
    },
    onRun: function(self, event) {
        self.logger.debug("Running rule for event: {}", event.name);
        correlationEventsLog.addEvents("RuleFFF", self);
    }
});

var RuleFFL = Java.extend(Rule, {
    onConfigure: function(self) {
        self.withEvents(["e1", "e2", "e3 :last"]).withDuration(Duration.ofSeconds(2)).withSynchronous(false);
    },
    onRun: function(self, event) {
        self.logger.debug("Running rule for event: {}", event.name);
        correlationEventsLog.addEvents("RuleFFL", self);
    }
});

function onStartup() {
    sponge.event("e1").set("label", "1").send();
    sponge.event("e2").set("label", "2").send();
    sponge.event("e2").set("label", "3").send();
    sponge.event("e2").set("label", "4").send();
    sponge.event("e3").set("label", "5").send();
    sponge.event("e3").set("label", "6").send();
    sponge.event("e3").set("label", "7").send();
}


text:
package com.smartdevicelink.protocol.enums;

import java.util.Vector;

import com.smartdevicelink.util.ByteEnumer;

public class SessionType extends ByteEnumer {

	private static Vector<SessionType> theList = new Vector<SessionType>();
	public static Vector<SessionType> getList() { return theList; }

	byte i = 0x00;

	protected SessionType(byte value, String name) {super(value, name);}
	public final static SessionType CONTROL = new SessionType((byte) 0, "CONTROL");
	public final static SessionType RPC = new SessionType((byte)0x07, "RPC");
	public final static SessionType PCM = new SessionType((byte)0x0A, "PCM");
	public final static SessionType NAV = new SessionType((byte)0x0B, "NAV");
	public final static SessionType BULK_DATA = new SessionType((byte)0xF, "BULK_DATA");

	static {
		theList.addElement(RPC);
		theList.addElement(PCM);
		theList.addElement(NAV);
		theList.addElement(BULK_DATA);
		theList.addElement(CONTROL);
	}

	public static SessionType valueOf(byte passedButton) {
		return (SessionType) get(theList, passedButton);
	}

	public static SessionType[] values() {
		return theList.toArray(new SessionType[theList.size()]);
	}
}


text:
package promql

import (
	"math"
	"sort"

	"github.com/prometheus/prometheus/model/histogram"
	"github.com/prometheus/prometheus/model/labels"
)

// Helpers to calculate quantiles.

// excludedLabels are the labels to exclude from signature calculation for
// quantiles.
var excludedLabels = []string{
	labels.MetricName,
	labels.BucketLabel,
}

type bucket struct {
	upperBound float64
	count      float64
}

// buckets implements sort.Interface.
type buckets []bucket

func (b buckets) Len() int           { return len(b) }
func (b buckets) Swap(i, j int)      { b[i], b[j] = b[j], b[i] }
func (b buckets) Less(i, j int) bool { return b[i].upperBound < b[j].upperBound }

type metricWithBuckets struct {
	metric  labels.Labels
	buckets buckets
}

// bucketQuantile calculates the quantile 'q' based on the given buckets. The
// buckets will be sorted by upperBound by this function (i.e. no sorting
// needed before calling this function). The quantile value is interpolated
// assuming a linear distribution within a bucket. However, if the quantile
// falls into the highest bucket, the upper bound of the 2nd highest bucket is
// returned. A natural lower bound of 0 is assumed if the upper bound of the
// lowest bucket is greater 0. In that case, interpolation in the lowest bucket
// happens linearly between 0 and the upper bound of the lowest bucket.
// However, if the lowest bucket has an upper bound less or equal 0, this upper
// bound is returned if the quantile falls into the lowest bucket.
//
// There are a number of special cases (once we have a way to report errors
// happening during evaluations of AST functions, we should report those
// explicitly):
//
// If 'buckets' has 0 observations, NaN is returned.
//
// If 'buckets' has fewer than 2 elements, NaN is returned.
//
// If the highest bucket is not +Inf, NaN is returned.
//
// If q==NaN, NaN is returned.
//
// If q<0, -Inf is returned.
//
// If q>1, +Inf is returned.
func bucketQuantile(q float64, buckets buckets) float64 {
	if math.IsNaN(q) {
		return math.NaN()
	}
	if q < 0 {
		return math.Inf(-1)
	}
	if q > 1 {
		return math.Inf(+1)
	}
	sort.Sort(buckets)
	if !math.IsInf(buckets[len(buckets)-1].upperBound, +1) {
		return math.NaN()
	}

	buckets = coalesceBuckets(buckets)
	ensureMonotonic(buckets)

	if len(buckets) < 2 {
		return math.NaN()
	}
	observations := buckets[len(buckets)-1].count
	if observations == 0 {
		return math.NaN()
	}
	rank := q * observations
	b := sort.Search(len(buckets)-1, func(i int) bool { return buckets[i].count >= rank })

	if b == len(buckets)-1 {
		return buckets[len(buckets)-2].upperBound
	}
	if b == 0 && buckets[0].upperBound <= 0 {
		return buckets[0].upperBound
	}
	var (
		bucketStart float64
		bucketEnd   = buckets[b].upperBound
		count       = buckets[b].count
	)
	if b > 0 {
		bucketStart = buckets[b-1].upperBound
		count -= buckets[b-1].count
		rank -= buckets[b-1].count
	}
	return bucketStart + (bucketEnd-bucketStart)*(rank/count)
}

// histogramQuantile calculates the quantile 'q' based on the given histogram.
//
// The quantile value is interpolated assuming a linear distribution within a
// bucket.
// TODO(beorn7): Find an interpolation method that is a better fit for
// exponential buckets (and think about configurable interpolation).
//
// A natural lower bound of 0 is assumed if the histogram has only positive
// buckets. Likewise, a natural upper bound of 0 is assumed if the histogram has
// only negative buckets.
// TODO(beorn7): Come to terms if we want that.
//
// There are a number of special cases (once we have a way to report errors
// happening during evaluations of AST functions, we should report those
// explicitly):
//
// If the histogram has 0 observations, NaN is returned.
//
// If q<0, -Inf is returned.
//
// If q>1, +Inf is returned.
//
// If q is NaN, NaN is returned.
func histogramQuantile(q float64, h *histogram.FloatHistogram) float64 {
	if q < 0 {
		return math.Inf(-1)
	}
	if q > 1 {
		return math.Inf(+1)
	}

	if h.Count == 0 || math.IsNaN(q) {
		return math.NaN()
	}

	var (
		bucket histogram.Bucket[float64]
		count  float64
		it     = h.AllBucketIterator()
		rank   = q * h.Count
	)
	for it.Next() {
		bucket = it.At()
		count += bucket.Count
		if count >= rank {
			break
		}
	}
	if bucket.Lower < 0 && bucket.Upper > 0 {
		if len(h.NegativeBuckets) == 0 && len(h.PositiveBuckets) > 0 {
			// The result is in the zero bucket and the histogram has only
			// positive buckets. So we consider 0 to be the lower bound.
			bucket.Lower = 0
		} else if len(h.PositiveBuckets) == 0 && len(h.NegativeBuckets) > 0 {
			// The result is in the zero bucket and the histogram has only
			// negative buckets. So we consider 0 to be the upper bound.
			bucket.Upper = 0
		}
	}
	// Due to numerical inaccuracies, we could end up with a higher count
	// than h.Count. Thus, make sure count is never higher than h.Count.
	if count > h.Count {
		count = h.Count
	}
	// We could have hit the highest bucket without even reaching the rank
	// (this should only happen if the histogram contains observations of
	// the value NaN), in which case we simply return the upper limit of the
	// highest explicit bucket.
	if count < rank {
		return bucket.Upper
	}

	rank -= count - bucket.Count
	// TODO(codesome): Use a better estimation than linear.
	return bucket.Lower + (bucket.Upper-bucket.Lower)*(rank/bucket.Count)
}

// histogramFraction calculates the fraction of observations between the
// provided lower and upper bounds, based on the provided histogram.
//
// histogramFraction is in a certain way the inverse of histogramQuantile.  If
// histogramQuantile(0.9, h) returns 123.4, then histogramFraction(-Inf, 123.4, h)
// returns 0.9.
//
// The same notes (and TODOs) with regard to interpolation and assumptions about
// the zero bucket boundaries apply as for histogramQuantile.
//
// Whether either boundary is inclusive or exclusive doesn't actually matter as
// long as interpolation has to be performed anyway. In the case of a boundary
// coinciding with a bucket boundary, the inclusive or exclusive nature of the
// boundary determines the exact behavior of the threshold. With the current
// implementation, that means that lower is exclusive for positive values and
// inclusive for negative values, while upper is inclusive for positive values
// and exclusive for negative values.
//
// Special cases:
//
// If the histogram has 0 observations, NaN is returned.
//
// Use a lower bound of -Inf to get the fraction of all observations below the
// upper bound.
//
// Use an upper bound of +Inf to get the fraction of all observations above the
// lower bound.
//
// If lower or upper is NaN, NaN is returned.
//
// If lower >= upper and the histogram has at least 1 observation, zero is returned.
func histogramFraction(lower, upper float64, h *histogram.FloatHistogram) float64 {
	if h.Count == 0 || math.IsNaN(lower) || math.IsNaN(upper) {
		return math.NaN()
	}
	if lower >= upper {
		return 0
	}

	var (
		rank, lowerRank, upperRank float64
		lowerSet, upperSet         bool
		it                         = h.AllBucketIterator()
	)
	for it.Next() {
		b := it.At()
		if b.Lower < 0 && b.Upper > 0 {
			if len(h.NegativeBuckets) == 0 && len(h.PositiveBuckets) > 0 {
				// This is the zero bucket and the histogram has only
				// positive buckets. So we consider 0 to be the lower
				// bound.
				b.Lower = 0
			} else if len(h.PositiveBuckets) == 0 && len(h.NegativeBuckets) > 0 {
				// This is in the zero bucket and the histogram has only
				// negative buckets. So we consider 0 to be the upper
				// bound.
				b.Upper = 0
			}
		}
		if !lowerSet && b.Lower >= lower {
			lowerRank = rank
			lowerSet = true
		}
		if !upperSet && b.Lower >= upper {
			upperRank = rank
			upperSet = true
		}
		if lowerSet && upperSet {
			break
		}
		if !lowerSet && b.Lower < lower && b.Upper > lower {
			lowerRank = rank + b.Count*(lower-b.Lower)/(b.Upper-b.Lower)
			lowerSet = true
		}
		if !upperSet && b.Lower < upper && b.Upper > upper {
			upperRank = rank + b.Count*(upper-b.Lower)/(b.Upper-b.Lower)
			upperSet = true
		}
		if lowerSet && upperSet {
			break
		}
		rank += b.Count
	}
	if !lowerSet || lowerRank > h.Count {
		lowerRank = h.Count
	}
	if !upperSet || upperRank > h.Count {
		upperRank = h.Count
	}

	return (upperRank - lowerRank) / h.Count
}

// coalesceBuckets merges buckets with the same upper bound.
//
// The input buckets must be sorted.
func coalesceBuckets(buckets buckets) buckets {
	last := buckets[0]
	i := 0
	for _, b := range buckets[1:] {
		if b.upperBound == last.upperBound {
			last.count += b.count
		} else {
			buckets[i] = last
			last = b
			i++
		}
	}
	buckets[i] = last
	return buckets[:i+1]
}

// The assumption that bucket counts increase monotonically with increasing
// upperBound may be violated during:
//
//   * Recording rule evaluation of histogram_quantile, especially when rate()
//      has been applied to the underlying bucket timeseries.
//   * Evaluation of histogram_quantile computed over federated bucket
//      timeseries, especially when rate() has been applied.
//
// This is because scraped data is not made available to rule evaluation or
// federation atomically, so some buckets are computed with data from the
// most recent scrapes, but the other buckets are missing data from the most
// recent scrape.
//
// Monotonicity is usually guaranteed because if a bucket with upper bound
// u1 has count c1, then any bucket with a higher upper bound u > u1 must
// have counted all c1 observations and perhaps more, so that c  >= c1.
//
// Randomly interspersed partial sampling breaks that guarantee, and rate()
// exacerbates it. Specifically, suppose bucket le=1000 has a count of 10 from
// 4 samples but the bucket with le=2000 has a count of 7 from 3 samples. The
// monotonicity is broken. It is exacerbated by rate() because under normal
// operation, cumulative counting of buckets will cause the bucket counts to
// diverge such that small differences from missing samples are not a problem.
// rate() removes this divergence.)
//
// bucketQuantile depends on that monotonicity to do a binary search for the
// bucket with the φ-quantile count, so breaking the monotonicity
// guarantee causes bucketQuantile() to return undefined (nonsense) results.
//
// As a somewhat hacky solution until ingestion is atomic per scrape, we
// calculate the "envelope" of the histogram buckets, essentially removing
// any decreases in the count between successive buckets.

func ensureMonotonic(buckets buckets) {
	max := buckets[0].count
	for i := 1; i < len(buckets); i++ {
		switch {
		case buckets[i].count > max:
			max = buckets[i].count
		case buckets[i].count < max:
			buckets[i].count = max
		}
	}
}

// quantile calculates the given quantile of a vector of samples.
//
// The Vector will be sorted.
// If 'values' has zero elements, NaN is returned.
// If q==NaN, NaN is returned.
// If q<0, -Inf is returned.
// If q>1, +Inf is returned.
func quantile(q float64, values vectorByValueHeap) float64 {
	if len(values) == 0 || math.IsNaN(q) {
		return math.NaN()
	}
	if q < 0 {
		return math.Inf(-1)
	}
	if q > 1 {
		return math.Inf(+1)
	}
	sort.Sort(values)

	n := float64(len(values))
	// When the quantile lies between two samples,
	// we use a weighted average of the two samples.
	rank := q * (n - 1)

	lowerIndex := math.Max(0, math.Floor(rank))
	upperIndex := math.Min(n-1, lowerIndex+1)

	weight := rank - math.Floor(rank)
	return values[int(lowerIndex)].V*(1-weight) + values[int(upperIndex)].V*weight
}


text:
package buildpacks

import (
	"fmt"
	"os"
	"reflect"
	"strings"

	"github.com/dokku/dokku/plugins/common"
)

// ReportSingleApp is an internal function that displays the app report for one or more apps
func ReportSingleApp(appName, infoFlag string) {
	if err := common.VerifyAppName(appName); err != nil {
		common.LogFail(err.Error())
	}

	buildpacks, err := common.PropertyListGet("buildpacks", appName, "buildpacks")
	if err != nil {
		common.LogFail(err.Error())
	}

	infoFlags := map[string]string{
		"--buildpacks-list": strings.Join(buildpacks, ","),
	}

	if len(infoFlag) == 0 {
		common.LogInfo2Quiet(fmt.Sprintf("%s buildpacks information", appName))
		for k, v := range infoFlags {
			key := common.UcFirst(strings.Replace(strings.TrimPrefix(k, "--"), "-", " ", -1))
			common.LogVerbose(fmt.Sprintf("%s%s", Right(fmt.Sprintf("%s:", key), 31, " "), v))
		}
		return
	}

	for k, v := range infoFlags {
		if infoFlag == k {
			fmt.Fprintln(os.Stdout, v)
			return
		}
	}

	keys := reflect.ValueOf(infoFlags).MapKeys()
	strkeys := make([]string, len(keys))
	for i := 0; i < len(keys); i++ {
		strkeys[i] = keys[i].String()
	}
	common.LogFail(fmt.Sprintf("Invalid flag passed, valid flags: %s", strings.Join(strkeys, ", ")))
}

func times(str string, n int) (out string) {
	for i := 0; i < n; i++ {
		out += str
	}
	return
}

// Right right-pads the string with pad up to len runes
func Right(str string, length int, pad string) string {
	return str + times(pad, length-len(str))
}


text:
package be.fnord.demo;

import jade.core.Agent;

/**
 * Hello world!
 *
 */
public class App extends Agent
{
	public static void main(String [] args){
		String str = "1main teat2";
		str = str.replaceAll("(\\b)(\\d)", "$2 ");
		str = str.replaceAll("(\\d)(\\b)", " $1");

		str = str.replaceAll("1", "one");
		str = str.replaceAll("2", "two");
		str = str.replaceAll("3", "three");
		str = str.replaceAll("4", "four");
		str = str.replaceAll("5", "five");
		str = str.replaceAll("6", "six");
		str = str.replaceAll("7", "seven");
		str = str.replaceAll("8", "eight");
		str = str.replaceAll("9", "nine");
		str = str.replaceAll("0", "zero");
		str = str.trim();
		a.e.print(str);

	}
	 protected void setup() {
		  	System.out.println("Hello World! My name is "+getLocalName());

		  	// Make this agent terminate
		  	doDelete();
		  }

}


text:
package easy;

public class VerityRotatePalindrome {
	//lastly create a test case
	public static void main(String[] args)
	{
		String input = "1234321";
		System.out.println(input+"\t A rotated palindrome? "+IfRotatePalindrom(input));

		String input2 = "3432112";
		System.out.println(input2+"\t A rotated palindrome? "+IfRotatePalindrom(input2));

		String input3 = "234321";
		System.out.println(input3+"\t A rotated palindrome? "+IfRotatePalindrom(input3));
	}

	//First, define a palindrome method
	public static boolean IfPalindrome(String in)
	{
		//the idea to verify if a string is a palindrom is to check each pair of chars at position (i, length-1-i)
		//if a mismatch is found return false, otherwise, return true
		char[] ins = in.toCharArray();
		//notice the following loop can be optimized a little by stop at half position! Reason is because (1,3) and (3,1) is the same thing!

		for(int i=0; i<=ins.length/2;i++)
		{
			//verify each position pair of (i, length-1-i)
			if(ins[i]!=ins[ins.length-1-i])
				return false;//any mismatch will cause an immediate false signal return
		}
		//if we come here that means the string passed all check for pairs, so it is a palindrome
		return true;
	}

	//now we start implement our rotate palindrome algorithm
	public static boolean IfRotatePalindrom(String in)
	{
		//as we discussed in the slides, we split each char string into left+right and check the combination
		//of right+left to see if it is a palindrom
		for(int i=0; i<in.length();i++)
		{
			String left = in.substring(0, i);//the first substring method accepts 2 values, 1st is index, 2nd is length
			String right = in.substring(i);//the overloaded substring method accepts the starting index as the only argument
			//now use our palindrom method to check right+left
			if(IfPalindrome(right+left))
				return true;//immediate return as a true rotated palindrome when we find one
		}
		return false;//do not forget to return a default false value if no true signal is returned
	}
}


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.components.devtools_bridge.gcd;

/**
 * Information needed for registration in GCD.
 * Instance secret will be bound to oAuthClientId.
 * gcmChannelId will be used for delivering commands.
 * displayName is a human readable name on the client side.
 */
public final class InstanceDescription {
    public final String oAuthClientId;
    public final String gcmChannelId;
    public final String displayName;

    private InstanceDescription(String oAuthClientId, String gcmChannelId, String displayName) {
        assert oAuthClientId != null;
        assert gcmChannelId != null;
        assert displayName != null;

        this.oAuthClientId = oAuthClientId;
        this.gcmChannelId = gcmChannelId;
        this.displayName = displayName;
    }

    /**
     * Builder for InstanceDescription.
     */
    public static final class Builder {
        private String mOAuthClientId;
        private String mGCMChannelId;
        private String mDisplayName;

        public Builder setOAuthClientId(String value) {
            mOAuthClientId = value;
            return this;
        }

        public Builder setGCMChannelId(String value) {
            mGCMChannelId = value;
            return this;
        }

        public Builder setDisplayName(String value) {
            mDisplayName = value;
            return this;
        }

        public InstanceDescription build() {
            return new InstanceDescription(mOAuthClientId, mGCMChannelId, mDisplayName);
        }
    }
}


text:
package java.lang

import java.lang.Double.{
  doubleToLongBits,
  doubleToRawLongBits,
  longBitsToDouble
}

object DoubleSuite extends tests.Suite {
  test("equals") {
    val pzero = +0.0
    val nzero = -0.0
    assert(pzero equals pzero)
    assert(nzero equals nzero)
    assertNot(pzero equals nzero)
    val szero = 1.0 - 1.0
    assert(pzero equals szero)

    val bpzero: java.lang.Double = pzero
    val bnzero: java.lang.Double = nzero
    assertNot(bpzero equals bnzero)
    val bszero: java.lang.Double = szero
    assert(bpzero equals bszero)

    val num1 = 123.45
    val num2 = 123.45
    assert(num1 equals num2)

    val bnum1: java.lang.Double = num1
    val bnum2: java.lang.Double = num2
    assert(bnum1 == bnum2)
    val pmax1 = scala.Double.MaxValue
    val pmax2 = scala.Double.MaxValue
    assert(pmax1 equals pmax2)
    val pmax3 = scala.Double.MaxValue + 1
    assert(pmax1 equals pmax3)

    val bpmax1: java.lang.Double = scala.Double.MaxValue
    val bpmax2: java.lang.Double = scala.Double.MaxValue
    assert(bpmax1 equals bpmax2)
    val bpmax3: java.lang.Double = scala.Double.MaxValue + 1
    assert(bpmax1 equals bpmax3)

    val pmin1 = scala.Double.MinValue
    val pmin2 = scala.Double.MinValue
    assert(pmin1 equals pmin2)
    val pmin3 = scala.Double.MinValue + 1
    assert(pmin1 equals pmin3)

    val bpmin1: java.lang.Double = scala.Double.MinValue
    val bpmin2: java.lang.Double = scala.Double.MinValue
    assert(bpmin1 equals bpmin2)
    val bpmin3: java.lang.Double = scala.Double.MinValue + 1
    assert(bpmin1 equals bpmin3)

    val pinf1 = scala.Double.PositiveInfinity
    val pinf2 = scala.Double.MaxValue + scala.Double.MaxValue
    assert(pinf1 equals pinf2)

    val bpinf1: java.lang.Double = pinf1
    val bpinf2: java.lang.Double = pinf2
    assert(bpinf1 equals bpinf2)

    val ninf1 = scala.Double.NegativeInfinity
    val ninf2 = scala.Double.MinValue + scala.Double.MinValue
    assert(ninf1 equals ninf2)

    val bninf1: java.lang.Double = ninf1
    val bninf2: java.lang.Double = ninf2
    assert(bninf1 equals bninf2)

    assert(Double.NaN equals Double.NaN)

    val x = Double.NaN
    val y = longBitsToDouble(doubleToRawLongBits(x) | 1)
    assert(x equals y)

    val z = longBitsToDouble(doubleToLongBits(x) | 1)
    assert(x equals z)
  }

  test("==") {
    val pzero = +0.0
    val nzero = -0.0
    assert(pzero == pzero)
    assert(nzero == nzero)
    assert(pzero == nzero)
    val szero = 1.0 - 1.0
    assert(pzero == szero)

    val bpzero: java.lang.Double = pzero
    val bnzero: java.lang.Double = nzero
    assertNot(bpzero == bnzero)
    val bszero: java.lang.Double = szero
    assert(bpzero == bszero)

    val num1 = 123.45
    val num2 = 123.45
    assert(num1 == num2)

    val bnum1: java.lang.Double = num1
    val bnum2: java.lang.Double = num2
    assert(bnum1 == bnum2)

    val pmax1 = scala.Double.MaxValue
    val pmax2 = scala.Double.MaxValue
    assert(pmax1 == pmax2)
    val pmax3 = scala.Double.MaxValue + 1
    assert(pmax1 == pmax3)

    val bpmax1: java.lang.Double = scala.Double.MaxValue
    val bpmax2: java.lang.Double = scala.Double.MaxValue
    assert(bpmax1 == bpmax2)
    val bpmax3: java.lang.Double = scala.Double.MaxValue + 1
    assert(bpmax1 == bpmax3)

    val pmin1 = scala.Double.MinValue
    val pmin2 = scala.Double.MinValue
    assert(pmin1 == pmin2)
    val pmin3 = scala.Double.MinValue + 1
    assert(pmin1 == pmin3)

    val bpmin1: java.lang.Double = scala.Double.MinValue
    val bpmin2: java.lang.Double = scala.Double.MinValue
    assert(bpmin1 == bpmin2)
    val bpmin3: java.lang.Double = scala.Double.MinValue + 1
    assert(bpmin1 == bpmin3)

    val pinf1 = scala.Double.PositiveInfinity
    val pinf2 = scala.Double.MaxValue + scala.Double.MaxValue
    assert(pinf1 == pinf2)

    val bpinf1: java.lang.Double = pinf1
    val bpinf2: java.lang.Double = pinf2
    assert(bpinf1 == bpinf2)

    val ninf1 = scala.Double.NegativeInfinity
    val ninf2 = scala.Double.MinValue + scala.Double.MinValue
    assert(ninf1 == ninf2)

    val bninf1: java.lang.Double = ninf1
    val bninf2: java.lang.Double = ninf2
    assert(bninf1 == bninf2)

    assertNot(Double.NaN == Double.NaN)

    val x = Double.NaN
    val y = longBitsToDouble(doubleToRawLongBits(x) | 1)
    // assertNot(x == y) // FIXME this works on the JVM, but fails on native.

    val z = longBitsToDouble(doubleToLongBits(x) | 1)
    // assertNot(x == z) // FIXME this works on the JVM, but fails on native.
  }

  test("eq") {
    val bpzero: java.lang.Double = +0.0
    val bnzero: java.lang.Double = -0.0
    assert(bpzero eq bpzero)
    assert(bnzero eq bnzero)
    assertNot(bpzero eq bnzero)
    val bszero: java.lang.Double = 1.0 - 1.0
    assertNot(bpzero eq bszero)

    val bnum1: java.lang.Double = 123.45
    val bnum2: java.lang.Double = 123.45
    assertNot(bnum1 eq bnum2)

    val bpmax1: java.lang.Double = scala.Double.MaxValue
    val bpmax2: java.lang.Double = scala.Double.MaxValue
    assertNot(bpmax1 eq bpmax2)
    val bpmax3: java.lang.Double = scala.Double.MaxValue + 1
    assertNot(bpmax1 eq bpmax3)

    val bpmin1: java.lang.Double = scala.Double.MinValue
    val bpmin2: java.lang.Double = scala.Double.MinValue
    assertNot(bpmin1 eq bpmin2)
    val bpmin3: java.lang.Double = scala.Double.MinValue + 1
    assertNot(bpmin1 eq bpmin3)

    val bpinf1: java.lang.Double = scala.Double.PositiveInfinity
    val bpinf2: java.lang.Double = scala.Double.MaxValue + scala.Double.MaxValue
    assertNot(bpinf1 eq bpinf2)

    val bninf1: java.lang.Double = scala.Double.NegativeInfinity
    val bninf2: java.lang.Double = scala.Double.MinValue + scala.Double.MinValue
    assertNot(bninf1 eq bninf2)
  }

  test("parseDouble") {
    assert(Double.parseDouble("1.0") == 1.0)
    assert(Double.parseDouble("-1.0") == -1.0)
    assert(Double.parseDouble("0.0") == 0.0)
    assert(Double.parseDouble("-0.0") == -0.0)
    assert(Double.parseDouble("Infinity") == Double.POSITIVE_INFINITY)
    assert(Double.parseDouble("-Infinity") == Double.NEGATIVE_INFINITY)
    assert(Double.isNaN(Double.parseDouble("NaN")))
  }

  // Not fully JVM compliant yet
  test("toString") {
    assert(Double.toString(1.0).equals("1.000000"))
    assert(Double.toString(-1.0).equals("-1.000000"))
    assert(Double.toString(0.0).equals("0.000000"))
    assert(Double.toString(-0.0).equals("-0.000000"))
    assert(Double.toString(Double.POSITIVE_INFINITY).equals("Infinity"))
    assert(Double.toString(Double.NEGATIVE_INFINITY).equals("-Infinity"))
    assert(Double.toString(Double.NaN).equals("NaN"))
  }
}


text:
class PlaceArea < HashModel

  attr_accessor :place

  def event
    place.event
  end

  def time_slots
    @time_slots ||= begin
      a = []
      @raw_data.time_slots.each do |t|
        slot = TimeSlot.new t
        slot.place_area = self
        a << slot
      end
      a
    end
  end

  def time_slots_at day
    self.time_slots.find_all{|ts| ts.start_at.same_day? day}
  end

  def title
    english? ? title_en : @raw_data.title
  end

end


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>jQuery Mobile Framework - Converter Demo Application</title>
	<link rel="stylesheet"  href="../../jquery.mobile-1.0.min.css" />
	<link rel="stylesheet"  href="converter.css" />

		Edit

Currency converter

			<form method="get" action="" data-role="autoform" id="curr-form">
				Search:
				<input type="search" name="term" id="term" placeholder="Type a value..." value="25" data-theme="a" />
			</form>

Edit conversions

		Done

		Add new...
		Restore defaults

Add new

		Cancel

Select currencies to convert:

			From
			<select name="currency-options" id="currency-options-from" data-theme="c">
				<option value="EUR">EUR to Euro</option>
				<option value="USD">USD to US Dollar</option>
				<option value="GBP">GBP to Great Britain Pound</option>
			</select>

			To
			<select name="currency-options" id="currency-options-to" data-theme="c">
				<option value="EUR">EUR to Euro</option>
				<option value="USD">USD to US Dollar</option>
				<option value="GBP">GBP to Great Britain Pound</option>
			</select>

		Cancel
		Add conversion


text:
const fs = require('graceful-fs');
const mkdirp = require('mkdirp');
const destroy = require('destroy');
const rmdir = require('rmdir');
const tmp = require('tmp');
const request = require('request');
const path = require('path');
const cp = require('cp');
const cpr = require('cpr');

const Promise = require('./promise');

// Write a stream to a file
function writeStream(filename, st) {
    const d = Promise.defer();

    const wstream = fs.createWriteStream(filename);
    const cleanup = function() {
        destroy(wstream);
        wstream.removeAllListeners();
    };

    wstream.on('finish', function() {
        cleanup();
        d.resolve();
    });
    wstream.on('error', function(err) {
        cleanup();
        d.reject(err);
    });

    st.on('error', function(err) {
        cleanup();
        d.reject(err);
    });

    st.pipe(wstream);

    return d.promise;
}

// Return a promise resolved with a boolean
function fileExists(filename) {
    const d = Promise.defer();

    fs.exists(filename, function(exists) {
        d.resolve(exists);
    });

    return d.promise;
}

// Generate temporary file
function genTmpFile(opts) {
    return Promise.nfcall(tmp.file, opts)
        .get(0);
}

// Generate temporary dir
function genTmpDir(opts) {
    return Promise.nfcall(tmp.dir, opts)
        .get(0);
}

// Download an image
function download(uri, dest) {
    return writeStream(dest, request(uri));
}

// Find a filename available in a folder
function uniqueFilename(base, filename) {
    const ext = path.extname(filename);
    filename = path.resolve(base, filename);
    filename = path.join(path.dirname(filename), path.basename(filename, ext));

    let _filename = filename + ext;

    let i = 0;
    while (fs.existsSync(filename)) {
        _filename = filename + '_' + i + ext;
        i = i + 1;
    }

    return Promise(path.relative(base, _filename));
}

// Create all required folder to create a file
function ensureFile(filename) {
    const base = path.dirname(filename);
    return Promise.nfcall(mkdirp, base);
}

// Remove a folder
function rmDir(base) {
    return Promise.nfcall(rmdir, base, {
        fs
    });
}

/**
    Assert a file, if it doesn't exist, call "generator"

    @param {String} filePath
    @param {Function} generator
    @return {Promise}
*/
function assertFile(filePath, generator) {
    return fileExists(filePath)
    .then(function(exists) {
        if (exists) return;

        return generator();
    });
}

/**
    Pick a file, returns the absolute path if exists, undefined otherwise

    @param {String} rootFolder
    @param {String} fileName
    @return {String}
*/
function pickFile(rootFolder, fileName) {
    const result = path.join(rootFolder, fileName);
    if (fs.existsSync(result)) {
        return result;
    }

    return undefined;
}

/**
    Ensure that a directory exists and is empty

    @param {String} folder
    @return {Promise}
*/
function ensureFolder(rootFolder) {
    return rmDir(rootFolder)
    .fail(function() {
        return Promise();
    })
    .then(function() {
        return Promise.nfcall(mkdirp, rootFolder);
    });
}

module.exports = {
    exists: fileExists,
    existsSync: fs.existsSync,
    mkdirp: Promise.nfbind(mkdirp),
    readFile: Promise.nfbind(fs.readFile),
    writeFile: Promise.nfbind(fs.writeFile),
    assertFile,
    pickFile,
    stat: Promise.nfbind(fs.stat),
    statSync: fs.statSync,
    readdir: Promise.nfbind(fs.readdir),
    writeStream,
    readStream: fs.createReadStream,
    copy: Promise.nfbind(cp),
    copyDir: Promise.nfbind(cpr),
    tmpFile: genTmpFile,
    tmpDir: genTmpDir,
    download,
    uniqueFilename,
    ensureFile,
    ensureFolder,
    rmDir
};


text:
use std::result::{Ok, Err};
use std::option::{Some};
use std::collections::HashMap;

use sdl2::surface::{Surface};
use sdl2::render::{Renderer, Texture};
use sdl2::rect::{Rect};
use sdl2::video::Window;
use sdl2_image::LoadSurface;

use p2d::sprite::SpriteTile;

pub struct TextureSheet {
    name: String,
    surface: Box<Surface>,
    texture: Box<Texture>
}

pub type TextureSheets = HashMap<String, TextureSheet>;

impl TextureSheet {
    pub fn new(renderer: &Renderer, path_str: &String, name: String) -> TextureSheet {
        let path = Path::new(path_str.as_slice());
        let surface = match LoadSurface::from_file(&path) {
            Ok(s) => s,
            Err(msg) => panic!(format!("new_sprite_from: Couldn't create texture from path '{}', msg: {}", path_str, msg))
        };
        let surface = box surface;
        let texture = match renderer.create_texture_from_surface(&*surface) {
            Ok(t) => t,
            Err(msg) => panic!(format!("new_sprite_from: Couldn't create texture from path '{}', msg: {}", path_str, msg))
        };
        TextureSheet { name: name,
                     surface: surface, texture: box texture }
    }

    pub fn draw_tile(&self, renderer: &Renderer, st: &SpriteTile,
                     dst_coords: (int, int), dst_size: (uint, uint)) -> bool {
        //let (x, y) = dst;
        let (tile_x, tile_y) = st.coords;
        let (size_x, size_y) = st.size;
        let src = Some(Rect::new(tile_x as i32, tile_y as i32, size_x as i32, size_y as i32));
        let (dst_x, dst_y) = dst_coords;
        let (dst_size_x, dst_size_y) = dst_size;
        let dst = Some(Rect::new(dst_x as i32, dst_y as i32, dst_size_x as i32, dst_size_y as i32));
        // FIXME this is lame
        renderer.copy(&*self.texture, src, dst).is_ok()
    }
}


text:
<!--

    Licensed to Apereo under one or more contributor license
    agreements. See the NOTICE file distributed with this work
    for additional information regarding copyright ownership.
    Apereo licenses this file to you under the Apache License,
    Version 2.0 (the "License"); you may not use this file
    except in compliance with the License.  You may obtain a
    copy of the License at the following location:

      http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <parent>
    <groupId>org.jasig.parent</groupId>
    <artifactId>jasig-parent</artifactId>
    <version>41</version>
  </parent>

  <modelVersion>4.0.0</modelVersion>
  <groupId>org.jasig.portlet</groupId>
  <artifactId>cas-proxy-test-portlet</artifactId>
  <packaging>war</packaging>

  <name>Cas Proxy Test Portlet</name>
  <description>A CASified test portlet.</description>
  <version>1.0.3-SNAPSHOT</version>
  <url>http://www.jasig.org</url>

  <scm>
    <connection>scm:git:git://github.com/Jasig/cas-proxy-test-portlet.git</connection>
    <developerConnection>scm:git:git@github.com:Jasig/cas-proxy-test-portlet.git</developerConnection>
    <url>http://github.com/Jasig/cas-proxy-test-portlet</url>

    <tag>HEAD</tag>
  </scm>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <cas.version>3.1.10</cas.version>
    <spring.version>4.2.5.RELEASE</spring.version>
    <uportal-libs.version>5.1.0</uportal-libs.version>
  </properties>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
      </dependency>
      <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.1.2</version>
      </dependency>
      <dependency>
        <groupId>javax.portlet</groupId>
        <artifactId>portlet-api</artifactId>
        <version>2.0</version>
      </dependency>
      <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
      </dependency>
      <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.2-b02</version>
      </dependency>
      <dependency>
        <groupId>org.jasig.cas</groupId>
        <artifactId>cas-client-core</artifactId>
        <version>${cas.version}</version>
      </dependency>
      <dependency>
        <groupId>org.jasig.portal</groupId>
        <artifactId>uPortal-spring</artifactId>
        <version>${uportal-libs.version}</version>
        <exclusions>
          <exclusion>
            <groupId>org.jasig.portal</groupId>
            <artifactId>uPortal-api-internal</artifactId>
          </exclusion>
          <exclusion>
            <groupId>org.jasig.portal</groupId>
            <artifactId>uPortal-security-core</artifactId>
          </exclusion>
          <exclusion>
            <groupId>org.jasig.portal</groupId>
            <artifactId>uPortal-security-mvc</artifactId>
          </exclusion>
          <exclusion>
            <groupId>org.jasig.portal</groupId>
            <artifactId>uPortal-tools</artifactId>
          </exclusion>
          <exclusion>
            <groupId>net.oauth.core</groupId>
            <artifactId>oauth</artifactId>
          </exclusion>
          <exclusion>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
          </exclusion>
        </exclusions>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc-portlet</artifactId>
        <version>${spring.version}</version>
      </dependency>
      <dependency>
        <groupId>taglibs</groupId>
        <artifactId>standard</artifactId>
        <version>1.1.2</version>
      </dependency>
      <dependency>
        <groupId>xerces</groupId>
        <artifactId>xercesImpl</artifactId>
        <version>2.11.0</version>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.portlet</groupId>
      <artifactId>portlet-api</artifactId>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
    </dependency>

    <dependency>
      <groupId>org.jasig.cas</groupId>
      <artifactId>cas-client-core</artifactId>
    </dependency>

    <dependency>
      <groupId>org.jasig.portal</groupId>
      <artifactId>uPortal-spring</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc-portlet</artifactId>
    </dependency>

    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <scope>runtime</scope>
    </dependency>

    <dependency>
      <groupId>xerces</groupId>
      <artifactId>xercesImpl</artifactId>
      <scope>runtime</scope>
    </dependency>

    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <scope>runtime</scope>
    </dependency>

  </dependencies>
  <build>
    <finalName>cas-proxy-test-portlet</finalName>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
/**
 * @fileoverview
 * @suppress {uselessCode}
 */

class NoCtor {
  field1: number;
}


text:
/* eslint-disable no-unused-expressions */
import { expect } from 'chai';

import * as cornerstone from '../src/index';

describe('A test that pulls in all modules', function () {
  it('pulls in all modules', function () {
    expect(cornerstone).to.exist;
  });
});


text:
This document describes the Python code in the KBase narrative repo.

# Package biokbase

The subdirectory, biokbase/, is a Python package.

## Description

This Python package contains all the KBase Python libraries to support the Python narrative UI, which is built on the IPython notebook.

## Dependencies

See ``requirements.txt``.

IPython Notebook (KBNB) dependencies are here: http://ipython.org/ipython-doc/dev/install/install.html

## Install

Installation uses setup.py and pip. If you don't have 'pip' installed, do that first. See http://www.pip-installer.org/en/latest/installing.html

Then run the install script:

    ./install.sh

## Running

A script to run the notebook, `run_notebook.sh`, is placed in your path from install.sh in the parent directory so you can run it like this:

    run_notebook.sh notebook

# Other packages

MG-RAST_Retina
  Retina/STM are packages to support a widget framework that Folker's group has developed

MG-RAST_ipy-mkmq
  So far this module seems to have an external dependency on R and the MatR R library.
  The instructions indicate that it can be downloaded and installed using the following
  R code snippet:
     > install.packages("matR", repo="http://dunkirk.mcs.anl.gov/~braithwaite/R", type="source")
     > library(matR)
     > dependencies()

  Please see: https://github.com/MG-RAST/matR