text:
package org.apache.rahas.impl.util;

import org.apache.axiom.om.impl.dom.jaxp.DocumentBuilderFactoryImpl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.rahas.TrustException;
import org.apache.ws.security.WSConstants;
import org.apache.ws.security.WSPasswordCallback;
import org.apache.ws.security.WSSecurityEngine;
import org.apache.ws.security.WSSecurityException;
import org.apache.ws.security.components.crypto.Crypto;
import org.apache.ws.security.processor.EncryptedKeyProcessor;
import org.apache.ws.security.util.Base64;
import org.apache.xml.security.exceptions.XMLSecurityException;
import org.apache.xml.security.keys.KeyInfo;
import org.apache.xml.security.keys.content.X509Data;
import org.apache.xml.security.keys.content.x509.XMLX509Certificate;
import org.opensaml.Configuration;
import org.opensaml.DefaultBootstrap;
import org.opensaml.saml2.core.*;
import org.opensaml.xml.ConfigurationException;
import org.opensaml.xml.XMLObject;
import org.opensaml.xml.io.*;
import org.w3c.dom.*;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.SAXException;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.List;

public class SAML2Utils {

    private static final Log log = LogFactory.getLog(SAML2Utils.class);

    public static Element getElementFromAssertion(XMLObject xmlObj) throws TrustException {
        try {

            String jaxpProperty = System.getProperty("javax.xml.parsers.DocumentBuilderFactory");
            System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

            MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
            Marshaller marshaller = marshallerFactory.getMarshaller(xmlObj);
            Element element = marshaller.marshall(xmlObj);

            // Reset the sys. property to its previous value.
            if (jaxpProperty == null) {
                System.getProperties().remove("javax.xml.parsers.DocumentBuilderFactory");
            } else {
                System.setProperty("javax.xml.parsers.DocumentBuilderFactory", jaxpProperty);
            }

            ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();

            DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();

            DOMImplementationLS impl =
                    (DOMImplementationLS) registry.getDOMImplementation("LS");

            LSSerializer writer = impl.createLSSerializer();
            LSOutput output = impl.createLSOutput();
            output.setByteStream(byteArrayOutputStrm);
            writer.write(element, output);
            String elementString = byteArrayOutputStrm.toString();

            DocumentBuilderFactoryImpl.setDOOMRequired(true);

            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = docBuilder.parse(new ByteArrayInputStream(elementString.trim().getBytes()));
            Element assertionElement = document.getDocumentElement();
            DocumentBuilderFactoryImpl.setDOOMRequired(false);

            log.debug("DOM element is created successfully from the OpenSAML2 XMLObject");
            return assertionElement;

        } catch (Exception e) {
            throw new TrustException("Error creating DOM object from the assertion", e);
        }
    }

     /**
     * Extract certificates or the key available in the SAMLAssertion
     *
     * @param elem
     * @return the SAML2 Key Info
     * @throws org.apache.ws.security.WSSecurityException
     *
     */
    public static SAML2KeyInfo getSAML2KeyInfo(Element elem, Crypto crypto,
                                              CallbackHandler cb) throws WSSecurityException {
        Assertion assertion;

        //build the assertion by unmarhalling the DOM element.
        try {
            DefaultBootstrap.bootstrap();

            String keyInfoElementString = elem.toString();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = docBuilder.parse(new ByteArrayInputStream(keyInfoElementString.trim().getBytes()));
            Element element = document.getDocumentElement();
            UnmarshallerFactory unmarshallerFactory = Configuration
                    .getUnmarshallerFactory();
            Unmarshaller unmarshaller = unmarshallerFactory
                    .getUnmarshaller(element);
            assertion = (Assertion) unmarshaller
                    .unmarshall(element);
        }
        catch (ConfigurationException e) {
            throw new WSSecurityException(
                    WSSecurityException.FAILURE, "Failure in bootstrapping", null, e);
        } catch (UnmarshallingException e) {
            throw new WSSecurityException(
                    WSSecurityException.FAILURE, "Failure in unmarshelling the assertion", null, e);
        } catch (IOException e) {
            throw new WSSecurityException(
                    WSSecurityException.FAILURE, "Failure in unmarshelling the assertion", null, e);
        } catch (SAXException e) {
            throw new WSSecurityException(
                    WSSecurityException.FAILURE, "Failure in unmarshelling the assertion", null, e);
        } catch (ParserConfigurationException e) {
            throw new WSSecurityException(
                    WSSecurityException.FAILURE, "Failure in unmarshelling the assertion", null, e);
        }
        return getSAML2KeyInfo(assertion, crypto, cb);

    }

    public static SAML2KeyInfo getSAML2KeyInfo(Assertion assertion, Crypto crypto,
                                               CallbackHandler cb) throws WSSecurityException {

        //First ask the cb whether it can provide the secret
        WSPasswordCallback pwcb = new WSPasswordCallback(assertion.getID(), WSPasswordCallback.CUSTOM_TOKEN);
        if (cb != null) {
            try {
                cb.handle(new Callback[]{pwcb});
            } catch (Exception e1) {
                throw new WSSecurityException(WSSecurityException.FAILURE, "noKey",
                        new Object[]{assertion.getID()}, e1);
            }
        }

        byte[] key = pwcb.getKey();

        if (key != null) {
            return new SAML2KeyInfo(assertion, key);
        } else {
            // if the cb fails to provide the secret.
            try {
                // extract the subject
                Subject samlSubject = assertion.getSubject();
                if (samlSubject == null) {
                    throw new WSSecurityException(WSSecurityException.FAILURE,
                            "invalidSAML2Token", new Object[]{"for Signature (no Subject)"});
                }

                // extract the subject confirmation element from the subject
                SubjectConfirmation subjectConf = (SubjectConfirmation) samlSubject.getSubjectConfirmations().get(0);
                if (subjectConf == null) {
                    throw new WSSecurityException(WSSecurityException.FAILURE,
                            "invalidSAML2Token", new Object[]{"for Signature (no Subject Confirmation)"});
                }

                // Get the subject confirmation data, KeyInfoConfirmationDataType extends SubjectConfirmationData.
                SubjectConfirmationData scData = subjectConf.getSubjectConfirmationData();

                if (scData == null) {
                    throw new WSSecurityException(WSSecurityException.FAILURE,
                            "invalidSAML2Token", new Object[]{"for Signature (no Subject Confirmation Data)"});
                }

                // Get the SAML specific XML representation of the keyInfo object
                XMLObject KIElem = null;
                List<XMLObject> scDataElements = scData.getOrderedChildren();
                Iterator<XMLObject> iterator = scDataElements.iterator();
                while (iterator.hasNext()) {
                    XMLObject xmlObj = iterator.next();
                    if (xmlObj instanceof org.opensaml.xml.signature.KeyInfo) {
                        KIElem = xmlObj;
                        break;
                    }
                }

                Element keyInfoElement;

                // Generate a DOM element from the XMLObject.
                if (KIElem != null) {

                    // Set the "javax.xml.parsers.DocumentBuilderFactory" system property to make sure the endorsed JAXP
                    // implementation is picked over the default jaxp impl shipped with the JDK.
                    String jaxpProperty = System.getProperty("javax.xml.parsers.DocumentBuilderFactory");
                    System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

                    MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
                    Marshaller marshaller = marshallerFactory.getMarshaller(KIElem);
                    keyInfoElement = marshaller.marshall(KIElem);

                    // Reset the sys. property to its previous value.
                    if (jaxpProperty == null) {
                        System.getProperties().remove("javax.xml.parsers.DocumentBuilderFactory");
                    } else {
                        System.setProperty("javax.xml.parsers.DocumentBuilderFactory", jaxpProperty);
                    }

                } else {
                    throw new WSSecurityException(WSSecurityException.FAILURE,
                            "invalidSAML2Token", new Object[]{"for Signature (no key info element)"});
                }

                AttributeStatement attrStmt = assertion.getAttributeStatements().size() != 0 ?
                        (AttributeStatement) assertion.getAttributeStatements().get(0) : null;
                AuthnStatement authnStmt = assertion.getAuthnStatements().size() != 0 ?
                        (AuthnStatement) assertion.getAuthnStatements().get(0) : null;

                // if an attr stmt is present, then it has a symmetric key.
                if (attrStmt != null) {
                    NodeList children = keyInfoElement.getChildNodes();
                    int len = children.getLength();

                    for (int i = 0; i < len; i++) {
                        Node child = children.item(i);
                        if (child.getNodeType() != Node.ELEMENT_NODE) {
                            continue;
                        }
                        QName el = new QName(child.getNamespaceURI(), child.getLocalName());
                        if (el.equals(WSSecurityEngine.ENCRYPTED_KEY)) {

                            EncryptedKeyProcessor proc = new EncryptedKeyProcessor();
                            proc.handleEncryptedKey((Element) child, cb, crypto, null);

                            return new SAML2KeyInfo(assertion, proc.getDecryptedBytes());
                        } else if (el.equals(new QName(WSConstants.WST_NS, "BinarySecret"))) {
                            Text txt = (Text) child.getFirstChild();
                            return new SAML2KeyInfo(assertion, Base64.decode(txt.getData()));
                        } else if (el.equals(new QName(WSConstants.SIG_NS, "X509Data"))) {
                            X509Certificate[] certs = null;
                            try {
                                KeyInfo ki = new KeyInfo(keyInfoElement, null);

                                if (ki.containsX509Data()) {
                                    X509Data data = ki.itemX509Data(0);
                                    XMLX509Certificate certElem = null;
                                    if (data != null && data.containsCertificate()) {
                                        certElem = data.itemCertificate(0);
                                    }
                                    if (certElem != null) {
                                        X509Certificate cert = certElem.getX509Certificate();
                                        certs = new X509Certificate[1];
                                        certs[0] = cert;
                                        return new SAML2KeyInfo(assertion, certs);
                                    }
                                }

                            } catch (XMLSecurityException e3) {
                                throw new WSSecurityException(WSSecurityException.FAILURE,
                                        "invalidSAMLsecurity",
                                        new Object[]{"cannot get certificate (key holder)"}, e3);
                            }

                        }
                    }

                }

                // If an authn stmt is present then it has a public key.
                if (authnStmt != null) {

                    X509Certificate[] certs = null;
                    try {
                        KeyInfo ki = new KeyInfo(keyInfoElement, null);

                        if (ki.containsX509Data()) {
                            X509Data data = ki.itemX509Data(0);
                            XMLX509Certificate certElem = null;
                            if (data != null && data.containsCertificate()) {
                                certElem = data.itemCertificate(0);
                            }
                            if (certElem != null) {
                                X509Certificate cert = certElem.getX509Certificate();
                                certs = new X509Certificate[1];
                                certs[0] = cert;
                                return new SAML2KeyInfo(assertion, certs);
                            }
                        }

                    } catch (XMLSecurityException e3) {
                        throw new WSSecurityException(WSSecurityException.FAILURE,
                                "invalidSAMLsecurity",
                                new Object[]{"cannot get certificate (key holder)"}, e3);
                    }

                }

                throw new WSSecurityException(WSSecurityException.FAILURE,
                        "invalidSAMLsecurity",
                        new Object[]{"cannot get certificate or key "});

            } catch (MarshallingException e) {
                throw new WSSecurityException(WSSecurityException.FAILURE,
                        "Failed marshalling the SAML Assertion", null, e);
            }
        }
    }

}


text:
package org.kuali.kfs.module.ar.batch.vo;

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.converters.SqlDateConverter;
import org.apache.commons.lang.StringUtils;
import org.kuali.kfs.module.ar.batch.report.CustomerLoadBatchErrors;
import org.kuali.kfs.module.ar.businessobject.Customer;
import org.kuali.kfs.module.ar.businessobject.CustomerAddress;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.rice.core.api.datetime.DateTimeService;
import org.kuali.rice.core.api.util.type.KualiDecimal;
import org.kuali.rice.kns.service.MaintenanceDocumentDictionaryService;

/**
 *
 * This class converts a CustomerDigesterVO object to a standard
 * Customer object.
 */
public class CustomerDigesterAdapter {
    private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(CustomerDigesterAdapter.class);

    private static final Class<Customer> BO_CLASS = Customer.class;
    private static final String DD_ENTRY_NAME = BO_CLASS.getName();

    private DateTimeService dateTimeService;
    private MaintenanceDocumentDictionaryService maintDocDDService;

    private Customer customer;
    private String customerName;
    private CustomerLoadBatchErrors errors;
    private CustomerDigesterVO customerDigesterVO;

    public CustomerDigesterAdapter() {
        if (dateTimeService == null) dateTimeService = SpringContext.getBean(DateTimeService.class);
        if (maintDocDDService == null) maintDocDDService = SpringContext.getBean(MaintenanceDocumentDictionaryService.class);
    }

    /**
     *
     * Converts a CustomerDigesterVO to a real Customer BO.  Tries to do intelligent type
     * conversions where the types arent Strings.
     *
     * NOTE that conversion exceptions will be swallowed! and converted to errors in the
     * parameter errorMap.
     *
     * @param customerDigesterVO The VO full of String values to convert from.
     * @param errorMap An empty MessageMap collection to add errors to.  Only new errors will be added.
     * @return A populated Customer object, from the VO.
     */
    public Customer convert(CustomerDigesterVO customerDigesterVO, CustomerLoadBatchErrors errors) {

        if (customerDigesterVO == null) {
            throw new IllegalArgumentException("Parameter customerDigesterVO may not be null.");
        }
        this.customerDigesterVO = customerDigesterVO;

        //  the whole error system is keyed of customerName, so if we dont get one of those, we cant even proceed.
        if (StringUtils.isBlank(customerDigesterVO.getCustomerName())) {
            LOG.error("CustomerName can never be empty-string or null.");
            addError("customerName", String.class, customerDigesterVO.getCustomerName(), "CustomerName can never be empty-string or null.");
            return null;
        }

        customer = new Customer();
        customerName = this.customerDigesterVO.getCustomerName();

        if (errors == null) {
            LOG.error("Passed in CustomerLoadBatchErrors must not be null.");
            throw new IllegalArgumentException("Passed in CustomerLoadBatchErrors must not be null.");
        }
        this.errors = errors;

        convertCustomerStringProperties();
        convertCustomerDateProperties();
        convertCustomerKualiDecimalProperties();
        convertCustomerBooleanProperties();
        convertCustomerAddresses();

        return customer;
    }

    private void convertCustomerStringProperties() {

        //  these are String to String conversions, so they will always work
        customer.setCustomerNumber(applyDefaultValue("customerNumber", customerDigesterVO.getCustomerNumber()));
        customer.setCustomerName(applyDefaultValue("customerName", customerDigesterVO.getCustomerName()));
        customer.setCustomerParentCompanyNumber(applyDefaultValue("customerParentCompanyNumber", customerDigesterVO.getCustomerParentCompanyNumber()));
        customer.setCustomerTypeCode(applyDefaultValue("customerTypeCode", customerDigesterVO.getCustomerTypeCode()));
        customer.setCustomerTaxTypeCode(applyDefaultValue("customerTaxTypeCode", customerDigesterVO.getCustomerTaxTypeCode()));
        customer.setCustomerTaxNbr(applyDefaultValue("customerTaxNbr", customerDigesterVO.getCustomerTaxNbr()));
        customer.setCustomerPhoneNumber(applyDefaultValue("customerPhoneNumber", customerDigesterVO.getCustomerPhoneNumber()));
        customer.setCustomer800PhoneNumber(applyDefaultValue("customer800PhoneNumber", customerDigesterVO.getCustomer800PhoneNumber()));
        customer.setCustomerContactName(applyDefaultValue("customerContactName", customerDigesterVO.getCustomerContactName()));
        customer.setCustomerContactPhoneNumber(applyDefaultValue("customerContactPhoneNumber", customerDigesterVO.getCustomerContactPhoneNumber()));
        customer.setCustomerFaxNumber(applyDefaultValue("customerFaxNumber", customerDigesterVO.getCustomerFaxNumber()));
        customer.setCustomerCreditApprovedByName(applyDefaultValue("customerCreditApprovedByName", customerDigesterVO.getCustomerCreditApprovedByName()));
        customer.setCustomerEmailAddress(applyDefaultValue("customerEmailAddress", customerDigesterVO.getCustomerEmailAddress()));
        return;
    }

    private void convertCustomerDateProperties() {
        java.sql.Date todayDate = dateTimeService.getCurrentSqlDate();

        customer.setCustomerAddressChangeDate(todayDate);
        customer.setCustomerRecordAddDate(todayDate);
        customer.setCustomerLastActivityDate(todayDate);

        customer.setCustomerBirthDate(convertToJavaSqlDate("customerBirthDate", applyDefaultValue("customerBirthDate", customerDigesterVO.getCustomerBirthDate())));
        return;
    }

    private void convertCustomerKualiDecimalProperties() {
        customer.setCustomerCreditLimitAmount(convertToKualiDecimal("customerCreditLimitAmount", applyDefaultValue("customerCreditLimitAmount", customerDigesterVO.getCustomerCreditLimitAmount())));
        return;
    }

    private void convertCustomerBooleanProperties() {

        customer.setActive(convertToLittleBoolean("customerActiveIndicator", applyDefaultValue("customerActiveIndicator", customerDigesterVO.getCustomerActiveIndicator())));
        customer.setCustomerTaxExemptIndicator(convertToLittleBoolean("customerTaxExemptIndicator", applyDefaultValue("customerTaxExemptIndicator", customerDigesterVO.getCustomerTaxExemptIndicator())));
        return;
    }

    private void convertCustomerAddresses() {
        CustomerAddress customerAddress = null;
        for (CustomerAddressDigesterVO addressVO : customerDigesterVO.getCustomerAddresses()) {
            customerAddress = convertCustomerAddress(addressVO, customer.getCustomerNumber());
            customer.getCustomerAddresses().add(customerAddress);
        }
        return;
    }

    private CustomerAddress convertCustomerAddress(CustomerAddressDigesterVO customerAddressDigesterVO, String customerNumber) {
        CustomerAddress customerAddress = new CustomerAddress();

        //  link the customerAddress to the parent customer
        customerAddress.setCustomerNumber(customerNumber);

        customerAddress.setCustomerAddressName(applyDefaultValue("customerAddressName", customerAddressDigesterVO.getCustomerAddressName()));
        customerAddress.setCustomerLine1StreetAddress(applyDefaultValue("customerLine1StreetAddress", customerAddressDigesterVO.getCustomerLine1StreetAddress()));
        customerAddress.setCustomerLine2StreetAddress(applyDefaultValue("customerLine2StreetAddress", customerAddressDigesterVO.getCustomerLine2StreetAddress()));
        customerAddress.setCustomerCityName(applyDefaultValue("customerCityName", customerAddressDigesterVO.getCustomerCityName()));
        customerAddress.setCustomerStateCode(applyDefaultValue("customerStateCode", customerAddressDigesterVO.getCustomerStateCode()));
        customerAddress.setCustomerZipCode(applyDefaultValue("customerZipCode", customerAddressDigesterVO.getCustomerZipCode()));
        customerAddress.setCustomerCountryCode(applyDefaultValue("customerCountryCode", customerAddressDigesterVO.getCustomerCountryCode()));
        customerAddress.setCustomerAddressInternationalProvinceName(applyDefaultValue("customerAddressInternationalProvinceName", customerAddressDigesterVO.getCustomerAddressInternationalProvinceName()));
        customerAddress.setCustomerInternationalMailCode(applyDefaultValue("customerInternationalMailCode", customerAddressDigesterVO.getCustomerInternationalMailCode()));
        customerAddress.setCustomerEmailAddress(applyDefaultValue("customerEmailAddress", customerAddressDigesterVO.getCustomerEmailAddress()));
        customerAddress.setCustomerAddressTypeCode(applyDefaultValue("customerAddressTypeCode", customerAddressDigesterVO.getCustomerAddressTypeCode()));

        customerAddress.setCustomerAddressEndDate(convertToJavaSqlDate("customerAddressEndDate", applyDefaultValue("customerAddressEndDate", customerAddressDigesterVO.getCustomerAddressEndDate())));

        return customerAddress;
    }

    /**
     *
     * This method converts a string value that may represent a date into a java.sql.Date.
     * If the value is blank (whitespace, empty, null) then a null Date object is returned.  If
     * the value cannot be converted to a java.sql.Date, then a RuntimException or ConversionException
     * will be thrown.
     *
     * @param propertyName Name of the field whose value is being converted.
     * @param dateValue The value being converted.
     * @param errorMap The errorMap to add conversion errors to.
     * @return A valid java.sql.Date with the converted value, if possible.
     */
    private java.sql.Date convertToJavaSqlDate(String propertyName, String dateValue) {

        if (StringUtils.isBlank(dateValue)) {
            return null;
        }

        java.sql.Date date = null;
        SqlDateConverter converter = new SqlDateConverter();
        Object obj = null;
        try {
            obj = converter.convert(java.sql.Date.class, dateValue);
        }
        catch (ConversionException e) {
            LOG.error("Failed to convert the value [" + dateValue + "] from field [" + propertyName + "] to a java.sql.Date.");
            addError(propertyName, java.sql.Date.class, dateValue, "Could not convert value to target type.");
            return null;
        }
        try {
            date = (java.sql.Date) obj;
        }
        catch (Exception e) {
            LOG.error("Failed to cast the converters results to a java.sql.Date.");
            addError(propertyName, java.sql.Date.class, dateValue, "Could not convert value to target type.");
            return null;
        }

        if (!(obj instanceof java.sql.Date)) {
            LOG.error("Failed to convert the value [" + dateValue + "] from field [" + propertyName + "] to a java.sql.Date.");
            addError(propertyName, java.sql.Date.class, dateValue, "Could not convert value to target type.");
            return null;
        }
        return date;
    }

    /**
     *
     * This method converts a string, which may be blank, null or whitespace, into a KualiDecimal, if possible.
     *
     * A null, blank, or whitespace value passed in will result in a Null KualiDecimal value returned.  A value passed in
     * which is not blank, but cannot otherwise be converted to a KualiDecimal, will throw a ValueObjectConverterException.
     * Otherwise, the value will be converted to a KualiDecimal and returned.
     *
     * @param propertyName The name of the property being converted (used for exception handling).
     * @param stringDecimal The value being passed in, which will be converted to a KualiDecimal.
     * @param errorMap The errorMap to add conversion errors to.
     * @return A valid KualiDecimal value.  If the method returns a value, then it will be a legitimate value.
     */
    private KualiDecimal convertToKualiDecimal(String propertyName, String stringDecimal) {
        if (StringUtils.isBlank(stringDecimal)) {
            return null;
        }
        KualiDecimal kualiDecimal = null;
        try {
            kualiDecimal = new KualiDecimal(stringDecimal);
        }
        catch (NumberFormatException e) {
            LOG.error("Failed to convert the value [" + stringDecimal + "] from field [" + propertyName + "] to a KualiDecimal.");
            addError(propertyName, KualiDecimal.class, stringDecimal, "Could not convert value to target type.");
            return null;
        }
        return kualiDecimal;
    }

    /**
     *
     * This method converts a String into a boolean.
     *
     * It will return
     * @param propertyName
     * @param stringBoolean
     * @param errorMap The errorMap to add conversion errors to.
     * @return
     */
    private static final boolean convertToLittleBoolean(String propertyName, String stringBoolean) {
        if (StringUtils.isBlank(stringBoolean)) {
            return false;
        }
        if ("Y".equalsIgnoreCase(stringBoolean)) {
            return true;
        }
        if ("YES".equalsIgnoreCase(stringBoolean)) {
            return true;
        }
        if ("TRUE".equalsIgnoreCase(stringBoolean)) {
            return true;
        }
        if ("T".equalsIgnoreCase(stringBoolean)) {
            return true;
        }
        if ("1".equalsIgnoreCase(stringBoolean)) {
            return true;
        }
        return false;
    }

    /**
     *
     * This method is used to apply any DataDictionary default value rules, if appropriate.
     *
     * If the incoming value isnt blank, empty, or null, then nothing happens, and the method
     * returns the incoming value.
     *
     * If the value is empty/blank/null, then the MaintenanceDocumentDictionaryService is consulted,
     * and if there is a defaultValue applied to this field, then its used in place of the empty/blank/null.
     *
     * @param propertyName The propertyName of the field (must match case exactly to work).
     * @param batchValue The invoming value from the batch file, which at this point is always still a string.
     * @return If the original value is null/blank/empty, then if a default value is configured, that default value
     *         is returned.  If no default value is configured, then the original value (trimmed) is returned.  Otherwise,
     *         if the original incoming value is not empty/null/blank, then the original value is immediately returned.
     */
    private String applyDefaultValue(String propertyName, String batchValue) {

        //  short-circuit if value isnt empty/blank/null, as default wouldnt apply anyway
        if (StringUtils.isNotBlank(batchValue)) {
            return batchValue;
        }

        //  if its a string, we try to normalize it to null if empty/blank
        String incomingValue;
        if (StringUtils.isBlank(batchValue)) {
            incomingValue = null;
        }
        else {
            incomingValue = StringUtils.trimToNull(batchValue);
        }

        //  apply the default value from DD if exists
        String defaultValue = maintDocDDService.getFieldDefaultValue(BO_CLASS, propertyName);
        if (incomingValue == null && StringUtils.isNotBlank(defaultValue)) {
            LOG.info("Applied DD default value of '" + defaultValue + "' to field [" + propertyName + "].");
            return defaultValue;
        }
        else {
            return ((incomingValue == null) ? "" : incomingValue);
        }
    }

    private void addError(String propertyName, Class<?> propertyClass, String origValue, String description) {
        LOG.error("Failed conversion on field [" + propertyName + "] with value: '" + origValue + "': " + description);
        errors.addError(customerName, propertyName, propertyClass, origValue, description);
    }

    public void setDateTimeService(DateTimeService dateTimeService) {
        this.dateTimeService = dateTimeService;
    }

    public void setMaintDocDDService(MaintenanceDocumentDictionaryService maintDocDDService) {
        this.maintDocDDService = maintDocDDService;
    }

}

redpajama_set_name: RedPajamaGithub


text:
from jrpc import SimpleTCPClient

conn = SimpleTCPClient("localhost", 9999)
print conn.ping()
print conn.blah("test")


text:
/**
 * Autogenerated by Thrift
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */

package test.fixtures.inheritance;

import java.util.*;
import org.apache.thrift.protocol.*;
import com.facebook.thrift.util.Readers;

public class MyLeafRpcServerHandler  extends test.fixtures.inheritance.MyNodeRpcServerHandler
  implements com.facebook.thrift.server.RpcServerHandler {

  private final java.util.Map<String, com.facebook.thrift.server.RpcServerHandler> _methodMap;

  private final MyLeaf.Reactive _delegate;

  private final java.util.List<com.facebook.thrift.payload.Reader> _doLeafReaders;

  private final java.util.List<com.facebook.swift.service.ThriftEventHandler> _eventHandlers;

  public MyLeafRpcServerHandler(MyLeaf _delegate,
                                    java.util.List<com.facebook.swift.service.ThriftEventHandler> _eventHandlers) {
    this(new MyLeafBlockingReactiveWrapper(_delegate), _eventHandlers);
  }

  public MyLeafRpcServerHandler(MyLeaf.Async _delegate,
                                    java.util.List<com.facebook.swift.service.ThriftEventHandler> _eventHandlers) {
    this(new MyLeafAsyncReactiveWrapper(_delegate), _eventHandlers);
  }

  public MyLeafRpcServerHandler(MyLeaf.Reactive _delegate,
                                    java.util.List<com.facebook.swift.service.ThriftEventHandler> _eventHandlers) {
    super(_delegate, _eventHandlers);
    this._methodMap = new java.util.HashMap<>();
    this._delegate = _delegate;
    this._eventHandlers = _eventHandlers;

    _methodMap.put("doLeaf", this);
    _doLeafReaders = _create_doLeaf_request_readers();

  }

  private static java.util.List<com.facebook.thrift.payload.Reader> _create_doLeaf_request_readers() {
    java.util.List<com.facebook.thrift.payload.Reader> _readerList = new java.util.ArrayList<>();

    return _readerList;
  }

  private static com.facebook.thrift.payload.Writer _create_doLeaf_response_writer(
      final java.lang.Object _r,
      final com.facebook.swift.service.ContextChain _chain,
      final int _seqId) {
      return oprot -> {
      try {
        oprot.writeStructBegin(com.facebook.thrift.util.RpcPayloadUtil.TSTRUCT);

        oprot.writeFieldStop();
        oprot.writeStructEnd();

        _chain.postWrite(_r);
      } catch (Throwable _e) {
        com.facebook.thrift.util.NettyUtil.releaseIfByteBufTProtocol(oprot);
        throw reactor.core.Exceptions.propagate(_e);
      }
    };
  }

  private static reactor.core.publisher.Mono<com.facebook.thrift.payload.ServerResponsePayload>
    _dodoLeaf(
    MyLeaf.Reactive _delegate,
    com.facebook.thrift.payload.ServerRequestPayload _payload,
    java.util.List<com.facebook.thrift.payload.Reader> _readers,
    com.facebook.swift.service.ContextChain _chain) {
          _chain.preRead();
          java.util.List<java.lang.Object>_data = _payload.getData(_readers);
          java.util.Iterator<java.lang.Object> _iterator = _data.iterator();

          _chain.postRead(_data);

          reactor.core.publisher.Mono<Void> _delegateResponse = null;

          if (com.facebook.thrift.util.resources.RpcResources.isForceExecutionOffEventLoop()) {
            _delegateResponse = reactor.core.publisher.Mono.defer(() ->
              _delegate.doLeaf());
            _delegateResponse = _delegateResponse.publishOn(com.facebook.thrift.util.resources.RpcResources.getOffLoopScheduler());
          } else {
            _delegateResponse = _delegate.doLeaf();
          }

          reactor.core.publisher.Mono<com.facebook.thrift.payload.ServerResponsePayload> _internalResponse =
            _delegateResponse.map(_response -> {
              _chain.preWrite(_response);
              com.facebook.thrift.payload.ServerResponsePayload _serverResponsePayload =
                com.facebook.thrift.util.RpcPayloadUtil.createServerResponsePayload(
                  _payload,
                  _create_doLeaf_response_writer(_response, _chain, _payload.getMessageSeqId()));

                return _serverResponsePayload;
            })
            .switchIfEmpty(
              reactor.core.publisher.Mono.fromSupplier(
                () -> {
                  _chain.preWrite(null);
                  return com.facebook.thrift.util.RpcPayloadUtil.createServerResponsePayload(
                    _payload,
                    _create_doLeaf_response_writer(null, _chain, _payload.getMessageSeqId()));
                }
              )
            )
            .<com.facebook.thrift.payload.ServerResponsePayload>onErrorResume(_t -> {
                _chain.preWriteException(_t);
                // exception is not of user declared type
                String _errorMessage = String.format("Internal error processing doLeaf: %s", _t.getMessage() == null ? "<null>" : _t.getMessage());
                org.apache.thrift.TApplicationException _tApplicationException =
                    new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, _errorMessage);
                _tApplicationException.initCause(_t);
                com.facebook.thrift.payload.ServerResponsePayload _serverResponsePayload =
                    com.facebook.thrift.util.RpcPayloadUtil.fromTApplicationException(_tApplicationException, _payload.getRequestRpcMetadata(),  _chain);

                return reactor.core.publisher.Mono.just(_serverResponsePayload);
            });
          if (com.facebook.thrift.util.resources.RpcResources.isForceExecutionOffEventLoop()) {
            _internalResponse = _internalResponse.subscribeOn(com.facebook.thrift.util.resources.RpcResources.getOffLoopScheduler());
          }

          return _internalResponse;
  }

  @java.lang.Override
  public reactor.core.publisher.Flux<com.facebook.thrift.payload.ServerResponsePayload> singleRequestStreamingResponse(com.facebook.thrift.payload.ServerRequestPayload _payload) {
    final String _name = _payload.getRequestRpcMetadata().getName();

    com.facebook.swift.service.ContextChain _chain;
    try {
      _chain = new com.facebook.swift.service.ContextChain(_eventHandlers, _name, _payload.getRequestContext());
    } catch (Throwable _t) {
      org.apache.thrift.TApplicationException _tApplicationException = new org.apache.thrift.TApplicationException(_t.getMessage());
      com.facebook.thrift.payload.ServerResponsePayload _serverResponsePayload = com.facebook.thrift.util.RpcPayloadUtil.fromTApplicationException(_tApplicationException, _payload.getRequestRpcMetadata(), null);
      return reactor.core.publisher.Flux.just(_serverResponsePayload);
    }

    reactor.core.publisher.Flux<com.facebook.thrift.payload.ServerResponsePayload> _result;
    try {
      switch(_name) {
        default: {
          _result =  super.singleRequestStreamingResponse(_payload);
        }
      }
    } catch (org.apache.thrift.TApplicationException _tApplicationException) {
      com.facebook.thrift.payload.ServerResponsePayload _serverResponsePayload = com.facebook.thrift.util.RpcPayloadUtil.fromTApplicationException(_tApplicationException, _payload.getRequestRpcMetadata(), _chain);
      return reactor.core.publisher.Flux.just(_serverResponsePayload);
    } catch (Throwable _t) {
      _result = reactor.core.publisher.Flux.error(_t);
    }
    return _result;
  }

  @java.lang.Override
  public reactor.core.publisher.Mono<com.facebook.thrift.payload.ServerResponsePayload> singleRequestSingleResponse(com.facebook.thrift.payload.ServerRequestPayload _payload) {
    final String _name = _payload.getRequestRpcMetadata().getName();

    com.facebook.swift.service.ContextChain _chain;
    try {
      _chain = new com.facebook.swift.service.ContextChain(_eventHandlers, _name, _payload.getRequestContext());
    } catch (Throwable _t) {
      org.apache.thrift.TApplicationException _tApplicationException = new org.apache.thrift.TApplicationException(_t.getMessage());
      com.facebook.thrift.payload.ServerResponsePayload _serverResponsePayload = com.facebook.thrift.util.RpcPayloadUtil.fromTApplicationException(_tApplicationException, _payload.getRequestRpcMetadata(), null);
      return reactor.core.publisher.Mono.just(_serverResponsePayload);
    }

    reactor.core.publisher.Mono<com.facebook.thrift.payload.ServerResponsePayload> _result;
    try {
      switch (_name) {
        case "doLeaf":
          _result = _dodoLeaf(_delegate, _payload, _doLeafReaders, _chain);
        break;
        default: {
          _result =  super.singleRequestSingleResponse(_payload);
        }
      }
    } catch (org.apache.thrift.TApplicationException _tApplicationException) {
      com.facebook.thrift.payload.ServerResponsePayload _serverResponsePayload = com.facebook.thrift.util.RpcPayloadUtil.fromTApplicationException(_tApplicationException, _payload.getRequestRpcMetadata(), _chain);
      return reactor.core.publisher.Mono.just(_serverResponsePayload);
    } catch (Throwable _t) {
      _result = reactor.core.publisher.Mono.error(_t);
    }

    return _result;
  }

  @java.lang.Override
  public reactor.core.publisher.Mono<Void> singleRequestNoResponse(com.facebook.thrift.payload.ServerRequestPayload _payload) {
    final String _name = _payload.getRequestRpcMetadata().getName();

    com.facebook.swift.service.ContextChain _chain;
    try {
      _chain = new com.facebook.swift.service.ContextChain(_eventHandlers, _name, _payload.getRequestContext());
    } catch (Throwable _t) {
      return reactor.core.publisher.Mono.error(_t);
    }

    reactor.core.publisher.Mono<Void> _result;
    try {
      switch (_name) {
        default: {
          _result =  super.singleRequestNoResponse(_payload);
        }
      }
    } catch (Throwable _t) {
      _result = reactor.core.publisher.Mono.error(_t);
    }

    return _result;
  }

  public java.util.Map<String, com.facebook.thrift.server.RpcServerHandler> getMethodMap() {
      java.util.Map<String, com.facebook.thrift.server.RpcServerHandler> _combined = new java.util.HashMap();
      _combined.putAll(_methodMap);
      _combined.putAll(super.getMethodMap());
      return _combined;
  }

}


text:
Ext.define('CustomApp', {
    extend: 'Rally.app.App',
    componentCls: 'app',
    itemId:"App",

    leafNodes :[],
    orphanNodes :[],
    parentHash:{},
    processedRefs :{},
    tree:undefined,

    launch: function() {

        this.add({
            xtype:"rallyreleasecombobox",
            listeners:{
                change:function(combo) {
                    this._getStoriesInRelease(combo.getValue());
                },
                ready:function(combo) {
                    this._getStoriesInRelease(combo.getValue());
                },
                scope:this
            }

        });
    },

    _reset:function() {
        this.parentHash = {};
        this.orphanNodes = [];
        this.leafNodes = [];
        this._outstandingQueries = 0;
    },

    _getStoriesInRelease:function(release) {
        this._reset();
        this._outstandingQueries++;
        var context = this.getContext().getDataContext();
        context.project = undefined;
        var store = Ext.create("Rally.data.WsapiDataStore", {
            model:"story",
            autoLoad:true,
            limit:Infinity,
            filters: [
                {
                    property: 'Release',
                    value: release
                }
            ],
            listeners:{
                load:function(store, records) {
                    this._processResults(records);
                },
                scope:this
            },
            context:context
        });
    },

    _storeInParentHash:function(parentRef, child) {
        if (this.parentHash[parentRef.getRelativeUri()]) {
            this.parentHash[parentRef.getRelativeUri()].push(child);
        }
        else {
            this.parentHash[parentRef.getRelativeUri()] = [child];
        }
    },

    _outstandingQueries:0,

    _processResults:function(children) {
        this._outstandingQueries--;

        var portfolioItems = [];
        var stories = [];
        Ext.each(children, function(child) {
            this.processedRefs[Rally.util.Ref.getRelativeUri(child)] = true;
            var parent = child.get('Parent') || child.get('PortfolioItem');
            if (parent) {
                var parentRef = new Rally.util.Ref(parent._ref);
                if (parentRef.getType() === "hierarchicalrequirement") {
                    stories.push(parentRef.getRelativeUri());
                }
                else {
                    portfolioItems.push(parentRef.getRelativeUri());
                }
                this._storeInParentHash(parentRef, child);
            }
            else {
                this.leafNodes.push(child);
            }
        }, this);

        if (portfolioItems.length) {
            this._getPortfolioItems(portfolioItems);
        }

        if (stories.length) {
            this._getStories(stories);
        }

        if (!this._outstandingQueries) {
            this._display();
        }
    },

    _hasNotBeenRetrieved:function(ref) {
        return !this.processedRefs[ref];
    },

    _getNotRetrieved:function(refs) {

        var results = [];
        Ext.each(refs, function(ref) {
            if (this._hasNotBeenRetrieved(ref)) {
                results.push(ref);
            }
        }, this);
        return results;
    },

    _getObjectIdsFromRefs:function(refs) {
        var objectIds = [];
        Ext.each(refs, function(ref) {
            objectIds.push(new Rally.util.Ref(ref).getOid());
        });
        return objectIds;
    },

    _getStories:function(stories) {
        var context = this.getContext().getDataContext();
        context.project = undefined;
        stories = this._getNotRetrieved(stories);
        if (!stories.length) {
            return;
        }
        this._outstandingQueries++;
        var objectIds = this._getObjectIdsFromRefs(stories);

        var filter = Ext.create('Rally.data.QueryFilter', {
            property: 'ObjectID',
            value:objectIds.pop()
        });
        while (objectIds.length) {
            filter = filter.or({
                property: 'ObjectID',
                value: objectIds.pop()
            });
        }

        var store = Ext.create("Rally.data.WsapiDataStore", {
            model:"story",
            autoLoad:true,
            limit:Infinity,
            filters: filter,
            context:context,
            listeners:{
                load:function(store, records) {
                    this._processResults(records);
                },
                scope:this
            }
        });
    },

    _getPortfolioItems:function(portfolioItems) {
        var context = this.getContext().getDataContext();
        context.project = undefined;
        portfolioItems = this._getNotRetrieved(portfolioItems);
        if (!portfolioItems.length) {
            return;
        }
        this._outstandingQueries++;
        var objectIds = this._getObjectIdsFromRefs(portfolioItems);

        var filter = Ext.create('Rally.data.QueryFilter', {
            property: 'ObjectID',
            value:objectIds.pop()
        });
        while (objectIds.length) {
            filter = filter.or({
                property: 'ObjectID',
                value: objectIds.pop()
            });
        }

        var store = Ext.create("Rally.data.WsapiDataStore", {
            model:"portfolioitem",
            autoLoad:true,
            limit:Infinity,
            filters: filter,
            context:context,
            listeners:{
                load:function(store, records) {
                    this._processResults(records);
                },
                scope:this
            }
        });
    },

    _display:function() {
        var currentRef;
        var depth = 0;
        var children = [];
        Ext.each(this.leafNodes, function(record) {
            children.push(this._addOneRef(record));
        }, this);

        var store = Ext.create('Ext.data.TreeStore', {
            root: {
                expanded: true,
                children: children
            },
            sorters: [
                {
                    property: "leaf"
                }
            ],
            fields:["name","points","leafCount"]
        });

        if (this.tree) {
            this.tree.destroy();
        }

        this.tree = Ext.create('Ext.tree.Panel', {
            store: store,
            rootVisible: false,
            height:900,
            columns: [
                {
                    xtype: 'treecolumn',
                    text: 'Name',
                    dataIndex: 'name',
                    flex:1,
                    sortable: true
                },
                {
                    text: 'Points Shipped in this Release',
                    dataIndex: 'points',
                    width:35,
                    sortable: true
                },
                {
                    text: 'Leaf Story Count',
                    dataIndex: 'leafCount',
                    width:35,
                    sortable: true
                }
            ]
        });

        this.add(this.tree);

    },

    _addOneRef:function(record) {
        var currentRef = Rally.util.Ref.getRelativeUri(record.get('_ref'));
        var points = record.get("PlanEstimate") || 0;
        var leafCount = 0;
        var childArray = this.parentHash[currentRef];
        var children = [];
        if (childArray) {
            Ext.each(childArray, function(child) {
                var childNode = this._addOneRef(child);
                points += childNode.points;
                leafCount += childNode.leafCount;
                if (childNode.leaf) {
                    leafCount++;
                }
                children.push(childNode);
            }, this);
        }
        return {
            name:record.get("Name") + " Points:" + points + " Leaf Count:" + leafCount,
            children:children,
            leaf:!children.length,
            points:points,
            leafCount:leafCount,
            expanded:true
        };
    }

});


text:
package com.yunos.alicontacts.test;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

/**
 * Empty fragment used for testing.
 */
public class EmptyFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Must return a ViewGroup, FrameLayout will do.
        return new FrameLayout(getActivity());
    }
}


text:
<?php

namespace i18nTracker\Controllers;

use i18nTracker\MapperFactory;
use i18nTracker\Models\Resource;
use Neuron\Net\Response;

class Projects
	extends Base {

	/**
	 * @param string $text
	 * @return string
	 */
	private function trim($text)
	{
		return str_replace('\\u0000', '', trim($text));
	}

	public function track ($projectToken) {

		$project = $this->getProject ($projectToken);
		$language = MapperFactory::getLanguageMapper ()->getFromToken ('original');

		$bundle = $this->getBundle ($project, $language);

		// Fetch the resource.
		$resource = new Resource ();
		$resource->setBundle ($bundle);
		$resource->setText ($this->trim($this->request->input ('text')));
		$resource->setToken ($this->trim($resource->getText ()));
		$resource->setN ($this->request->input ('quantified') ? 1 : 0);

		MapperFactory::getResourceMapper ()->touch ($resource);

		return Response::json (array ('test' => 1));

	}

	/*
	public function translate ($projectToken, $language) {

		$project = $this->getProject ($projectToken);

		$language = MapperFactory::getLanguageMapper ()->getFromToken ($language);
		$bundle = MapperFactory::getBundleMapper ()->getFromLanguage ($project, $language);

		$resources = MapperFactory::getResourceMapper ()->getFromBundle ($bundle);
		return Response::json ($resources->getData ());

	}
	*/

}


text:
package com.helger.dao.wal;

import java.time.Duration;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import javax.annotation.Nonnull;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.Immutable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.helger.commons.annotation.UsedViaReflection;
import com.helger.commons.collection.impl.CommonsHashMap;
import com.helger.commons.collection.impl.CommonsHashSet;
import com.helger.commons.collection.impl.ICommonsMap;
import com.helger.commons.collection.impl.ICommonsSet;
import com.helger.commons.concurrent.BasicThreadFactory;
import com.helger.commons.concurrent.ExecutorServiceHelper;
import com.helger.scope.IScope;
import com.helger.scope.singleton.AbstractGlobalSingleton;

/**
 * The global write ahead logging manager that schedules future writings of a
 * DAO.
 *
 * @author Philip Helger
 */
public final class WALListener extends AbstractGlobalSingleton
{
  /**
   * A single scheduled action consisting of the scheduled {@link Future} as
   * well as the original {@link Runnable} for rescheduling upon shutdown.
   *
   * @author Philip Helger
   */
  @Immutable
  private static final class WALItem
  {
    private final ScheduledFuture <?> m_aFuture;
    private final Runnable m_aRunnable;

    public WALItem (@Nonnull final ScheduledFuture <?> aFuture, @Nonnull final Runnable aRunnable)
    {
      m_aFuture = aFuture;
      m_aRunnable = aRunnable;
    }
  }

  private static final Logger LOGGER = LoggerFactory.getLogger (WALListener.class);

  // custom ThreadFactory to give the baby a name
  private final ScheduledExecutorService m_aES = Executors.newSingleThreadScheduledExecutor (BasicThreadFactory.builder ()
                                                                                .namingPattern ("WAL-Listener-%d")
                                                                                .build ());
  @GuardedBy ("m_aRWLock")
  private final ICommonsSet <String> m_aWaitingDAOs = new CommonsHashSet <> ();
  @GuardedBy ("m_aRWLock")
  private final ICommonsMap <String, WALListener.WALItem> m_aScheduledItems = new CommonsHashMap <> ();

  /**
   * Constructor
   *
   * @deprecated Called via reflection - don't call it yourself
   */
  @Deprecated (forRemoval = false)
  @UsedViaReflection
  public WALListener ()
  {}

  @Nonnull
  public static WALListener getInstance ()
  {
    return getGlobalSingleton (WALListener.class);
  }

  @Override
  protected void onDestroy (@Nonnull final IScope aScopeInDestruction)
  {
    m_aRWLock.writeLocked ( () -> {
      // Reschedule all existing scheduled items to run now
      for (final Map.Entry <String, WALListener.WALItem> aEntry : m_aScheduledItems.entrySet ())
      {
        final WALListener.WALItem aItem = aEntry.getValue ();
        if (aItem.m_aFuture.cancel (false))
        {
          // reschedule to perform it now
          m_aES.submit (aItem.m_aRunnable);
          LOGGER.info ("Rescheduled DAO writing for " + aEntry.getKey () + " to happen now");
        }
        else
          LOGGER.info ("Cannot reschedule DAO writing for " + aEntry.getKey () + " because it is already running");
      }
      // ensure all are cleared
      m_aScheduledItems.clear ();
    });

    // Wait until all tasks finished
    ExecutorServiceHelper.shutdownAndWaitUntilAllTasksAreFinished (m_aES);
  }

  /**
   * This is the main method for registration of later writing.
   *
   * @param aDAO
   *        The DAO to be written
   * @param sWALFilename
   *        The filename of the WAL file for later deletion (in case the
   *        filename changes over time).
   * @param aWaitingWime
   *        The time to wait, until the file is physically written. May not be
   *        null.
   */
  public void registerForLaterWriting (@Nonnull final AbstractWALDAO <?> aDAO,
                                       @Nonnull final String sWALFilename,
                                       @Nonnull final Duration aWaitingWime)
  {
    // In case many DAOs of the same class exist, the filename is also added
    final String sKey = aDAO.getClass ().getName () + "::" + sWALFilename;

    // Check if the passed DAO is already scheduled for writing
    final boolean bDoScheduleForWriting = m_aRWLock.writeLockedBoolean ( () -> m_aWaitingDAOs.add (sKey));

    if (bDoScheduleForWriting)
    {
      // We need to schedule it now
      if (LOGGER.isDebugEnabled ())
        LOGGER.debug ("Now scheduling writing for DAO " + sKey);

      // What should be executed upon writing
      final Runnable r = () -> {
        // Use DAO lock!
        aDAO.internalWriteLocked ( () -> {
          // Main DAO writing
          aDAO._writeToFileAndResetPendingChanges ("ScheduledWriter.run");
          // Delete the WAL file
          aDAO._deleteWALFileAfterProcessing (sWALFilename);

          if (LOGGER.isDebugEnabled ())
            LOGGER.debug ("Finished scheduled writing for DAO " + sKey);
        });

        // Remove from the internal set so that another job will be
        // scheduled for the same DAO
        // Do this after the writing to the file
        m_aRWLock.writeLocked ( () -> {
          // Remove from the overall set as well as from the scheduled items
          m_aWaitingDAOs.remove (sKey);
          m_aScheduledItems.remove (sKey);
        });
      };

      // Schedule exactly once in the specified waiting time
      final ScheduledFuture <?> aFuture = m_aES.schedule (r, aWaitingWime.toMillis (), TimeUnit.MILLISECONDS);

      // Remember the scheduled item and the runnable so that the task can
      // be rescheduled upon shutdown.
      m_aRWLock.writeLocked ( () -> m_aScheduledItems.put (sKey, new WALItem (aFuture, r)));
    }
    // else the writing of the passed DAO is already scheduled and no further
    // action is necessary
  }
}


text:
package com.lagg;

import com.lagg.graph.BadInputException;
import com.lagg.graph.TopicGraph;

import java.util.HashSet;

/**
 * Created by serem on 11/03/2017.
 * Parent class for com.lagg.Learn and com.lagg.Test. Every topic has a list of these.
 */
public class Artefact {
    private String name;
    private String link;
    private ArtefactType type;
    private HashSet<Topic> topics;

    public String getName() {
        return name;
    }

    public String getLink() {
        return link;
    }

    public HashSet<Topic> getTopics() {
        return new HashSet<Topic>(topics);
    }

    public boolean isLearn() {
        return(type instanceof Learn);
    }

    public boolean isTest() {
        return(type instanceof Test);
    }

    public Artefact(String base, String topics) throws BadInputException {
            String[] attributes = base.split(",");
            for(int i = 0; i < attributes.length; i++)
                attributes[i] = attributes[i].trim();
            name = attributes[0];
            link = attributes[1];
            if(attributes[2].equals("Learn"))
                type = new Learn(attributes[3], attributes[4]);
            else if (attributes[2].equals("Test"))
                type = new Test(attributes[3]);
            else throw new BadInputException("wrong artefact type");

            this.topics = new HashSet<>();

            String[] topicNames = topics.split(",");
            for(int i = 0; i < topicNames.length; i++) {
                try {
                    topicNames[i] = topicNames[i].trim();
                    this.topics.add(TopicGraph.getTopic(topicNames[i]));
                }
                catch(NullPointerException nullpt) {
                    throw new BadInputException("inexistent topic " + topicNames[i]);
                }
            }
    }
}


text:
Extend the Unity Editor with the power of Community.

Experiencing errors and problems, no worry, [File them, and let us fix them](https://github.com/UnityCommunity/UnityLibrary/issues)

## License
[MIT](https://github.com/UnityCommunity/UnityLibrary/blob/master/LICENSE.md) @ [Unity Community](https://github.com/UnityCommunity/)

Made with :heart: by [Unity Community](https://github.com/UnityCommunity/)


text:
from __future__ import unicode_literals

from django.db import migrations
import multiselectfield

class Migration(migrations.Migration):

    dependencies = [
        ('projects', '0010_merge'),
    ]

    operations = [
        migrations.AlterField(
            model_name='project',
            name='currencies',
            field=multiselectfield.MultiSelectField(choices=[(b'EUR', b'Euro')], max_length=100, null=True),
        ),
    ]


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Schema = mongoose.Schema;

var validateSaveTime = function(property) {
	return property > Date.now();
};

/**
 * Prediction Schema
 */
var PredictionSchema = new Schema({
	goalsHomeTeam: {
		type: Number,
		required: 'Home team goals required'
	},
	goalsAwayTeam: {
		type: Number,
		required: 'Away team goals required'
	},
	result: {
		type: String,
		required: true,
		enun: ['w','d','l']
	},
	user: {
		type: Schema.ObjectId,
		ref: 'User',
		required: 'User required'
	},
	fixture: {
		type: Number,
		ref: 'Fixture',
		required: 'Fixture required'
	},
	timestamp :{
		type: Date,
		default: Date.now()
	}
});

mongoose.model('Prediction', PredictionSchema);


text:
import { Action } from "readium-desktop/common/models/redux";

export const ID = "STREAMER_START_SUCCESS";

export interface Payload {
    streamerUrl: string;
}
export function build(streamerUrl: string):
    Action<typeof ID, Payload> {

    return {
        type: ID,
        payload: {
            streamerUrl,
        },
    };
}
build.toString = () => ID; // Redux StringableActionCreator
export type TAction = ReturnType<typeof build>;


text:
'use strict';

/**
 * Given a base64 encoded string it returns a decoded string
 * @param authorization (encoded base64)
 * @returns {string} decoded string
 */
function atob(authorization) {
    return new Buffer(authorization, 'base64').toString('binary');
}

/**
 * Extracts the raw authorization string and returns an
 * object containing username and password fields.
 * @param authorizationString
 * @returns {{username: *, password: *}}
 */
var extractCredentialsFromHeader = function(authorizationString) {
    var authorization = authorizationString.split(' ');
    var username = null;
    var password = null;
    if (authorization.length > 0) {
        authorization = authorizationString.split(' ')[1];
        authorization = atob(authorization);
        username = authorization.split(':')[0];
        password = authorization.split(':')[1];
    } else {
        throw new Error("Bad authentication format");
    }
    return { code: 200, 'description': 'successfully authenticated', username: username, password: password };
};

/**
 *
 * @param authorizationString
 * @returns {boolean}
 */
var checkAuthorizationString = function(authorizationString) {
    return (/[Basic ][A-Za-z_=]{4,256}/).test(authorizationString);
};

var checkCredentials = function(credentials, fn) {
    return fn(credentials);
};

/**
 *
 * @param user
 * @param resource
 * @param acl
 * @param fn
 * @returns {*}
 */
var checkAuthorization = function(user, resource, acl, fn) {
    return fn(user, resource, acl);
};

/**
 * @param req
 * @param res
 * @param next
 * @returns {*}
 */
var authentication = function(req, res, next) {
    var authorizationString = req.header('authorization');
    req.authentication = req.authentication || {};

    if (authorizationString && checkAuthorizationString(authorizationString)) {
        try {
            var credentials = extractCredentialsFromHeader(authorizationString);
            var isAuthenticated = checkCredentials(credentials, req.authentication.checkCredentials);

            if (isAuthenticated) {
                req.authentication = credentials;
                next();
            } else {
                req.authentication = { 'code': 401, 'description': 'The username or password are wrong' };
                next();
            }
        } catch (ex) {
            req.authentication = { 'code': 500, 'description': ex };
            next();
        }
    } else {
        req.authentication = { 'code': 400, 'description': 'wrong authorization header is provided: ' + authorizationString };
        next();
    }
};

/**
 * Extract the resource's name
 * if the resource's URI ends with the resource name
 * or with the identifies
 * (http|https)://domain/resource/(:id)
 * @private
 */
var extractResourceNameFromURL = function(url) {
    var pathBreakdown = url.split('/');
    var resourceName = pathBreakdown[pathBreakdown.length - 1];
    return resourceName;
};

/**
 * Module exports.
 * @public
 */
module.exports = authentication;


text:
// @ts-check

/**
 * Unix/Windows path match.
 *
 * @return {RegExp}
 */
module.exports = function createAbsolutePathRegExp (path) {
  return new RegExp('^([a-zA-Z]:)?' + path.replace(/\//g, '[/\\\\]'))
}


text:
/**
 * CriteriaPolicy
 * @depends PermissionPolicy
 *
 * Verify that the User fulfills permission 'where' conditions and attribute blacklist restrictions
 */
var wlFilter = require('waterline-criteria');
import _ from 'lodash'

module.exports = function(req, res, next) {
  var permissions = req.permissions;

  if (_.isEmpty(permissions)) {
    return next();
  }

  var action = PermissionService.getMethod(req.method);

  var body = req.body || req.query;

  // if we are creating, we don't need to query the db, just check the where clause vs the passed in data
  if (action === 'create') {
    if (!PermissionService.hasPassingCriteria(body, permissions, body)) {
      return res.send(403, {
        error: 'Can\'t create this object, because of failing where clause'
      });
    }
    return next();
  }

  // set up response filters if we are not mutating an existing object
  if (!_.contains(['update', 'delete'], action)) {

    // get all of the where clauses and blacklists into one flat array
    // if a permission has no criteria then it is always true
    var criteria = _.compact(_.flatten(
      _.map(
        _.pluck(permissions, 'criteria'),
        function(c) {
          if (c.length == 0) {
            return [{where: {}}];
          }
          return c;
        }
      )
    ));

    if (criteria.length) {
      bindResponsePolicy(req, res, criteria);
    }
    return next();
  }

  PermissionService.findTargetObjects(req)
    .then(function(objects) {

      // attributes are not important for a delete request
      if (action === 'delete') {
        body = undefined;
      }

      if (!PermissionService.hasPassingCriteria(objects, permissions, body, req.user.id)) {
        return res.send(403, {
          error: 'Can\'t ' + action + ', because of failing where clause or attribute permissions'
        });
      }

      next();
    })
    .catch(next);
};

function bindResponsePolicy(req, res, criteria) {
  res._ok = res.ok;

  res.ok = _.bind(responsePolicy, {
    req: req,
    res: res
  }, criteria);
}

function responsePolicy(criteria, _data, options) {
  var req = this.req;
  var res = this.res;
  var user = req.owner;
  var method = PermissionService.getMethod(req);
  var isResponseArray = _.isArray(_data);

  var data = isResponseArray ? _data : [_data];

  // remove undefined, since that is invalid input for waterline-criteria
  data = data.filter(item => { return item !== undefined })

  var permitted = data.reduce(function(memo, item) {
    criteria.some(function(crit) {
      var filtered = wlFilter([item], {
        where: {
          or: [crit.where || {}]
        }
      }).results;

      if (filtered.length) {

        if (crit.blacklist && crit.blacklist.length) {
          crit.blacklist.forEach(function (term) {
            delete item[term];
          });
        }
        memo.push(item);
        return true;
      }
    });
    return memo;
  }, []);

  if (isResponseArray) {
    return res._ok(permitted, options);
  } else if (permitted.length === 0) {
    sails.log.silly('permitted.length === 0');
    return res.send(404);
  } else {
    res._ok(permitted[0], options);
  }
}


text:
package com.ctrip.framework.apollo.portal.util;

import org.apache.commons.lang.time.FastDateFormat;

import java.util.Calendar;
import java.util.Date;

public class RelativeDateFormat {
  private static final FastDateFormat TIMESTAMP_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd");
  private static final long ONE_MINUTE = 60000L;
  private static final long ONE_HOUR = 3600000L;
  private static final long ONE_DAY = 86400000L;

  private static final String ONE_SECOND_AGO = "秒前";
  private static final String ONE_MINUTE_AGO = "分钟前";
  private static final String ONE_HOUR_AGO = "小时前";
  private static final String ONE_DAY_AGO = "天前";
  private static final String ONE_MONTH_AGO = "月前";

  public static String format(Date date) {
    if (date.after(new Date())) {
      return "now";
    }

    long delta = new Date().getTime() - date.getTime();
    if (delta < ONE_MINUTE) {
      long seconds = toSeconds(delta);
      return (seconds <= 0 ? 1 : seconds) + ONE_SECOND_AGO;
    }
    if (delta < 45L * ONE_MINUTE) {
      long minutes = toMinutes(delta);
      return (minutes <= 0 ? 1 : minutes) + ONE_MINUTE_AGO;
    }
    if (delta < 24L * ONE_HOUR) {
      long hours = toHours(delta);
      return (hours <= 0 ? 1 : hours) + ONE_HOUR_AGO;
    }

    Date lastDayBeginTime = getDateOffset(-1);
    if (date.after(lastDayBeginTime)) {
      return "昨天";
    }
    Date lastTwoDaysBeginTime = getDateOffset(-2);
    if (date.after(lastTwoDaysBeginTime)) {
      return "前天";
    }
    if (delta < 30L * ONE_DAY) {
      long days = toDays(delta);
      return (days <= 0 ? 1 : days) + ONE_DAY_AGO;
    }

    long months = toMonths(delta);
    if (months <= 3) {
      return (months <= 0 ? 1 : months) + ONE_MONTH_AGO;
    } else {
      return TIMESTAMP_FORMAT.format(date);
    }
  }

  private static long toSeconds(long date) {
    return date / 1000L;
  }

  private static long toMinutes(long date) {
    return toSeconds(date) / 60L;
  }

  private static long toHours(long date) {
    return toMinutes(date) / 60L;
  }

  private static long toDays(long date) {
    return toHours(date) / 24L;
  }

  private static long toMonths(long date) {
    return toDays(date) / 30L;
  }

  public static Date getDateOffset(int offset) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    calendar.add(calendar.DATE, offset);

    return getDayBeginTime(calendar.getTime());
  }

  private static Date getDayBeginTime(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(Calendar.HOUR, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return new Date(calendar.getTime().getTime());
  }

}


text:
			    <li data-thumb="<?php echo base_url().'uploads/product/'.$product['pro_image'] ?>">

 <img src="<?php echo base_url().'uploads/product/'.$product['pro_image'] ?>" data-imagezoom="true" class="img-responsive">

			    <li data-thumb="<?php echo base_url().'uploads/product/'.$product['pro_image'] ?>">

 <img src="<?php echo base_url().'uploads/product/'.$product['pro_image'] ?>" data-imagezoom="true" class="img-responsive">

							<input type="hidden" id="pro_id" value="<?php echo $product['id'];?>">

<?php echo $product['pro_name'];?>

<?php echo $product['pro_detail']; ?>

									 13 reviews /
									  Write a review

							<img class="img-responsive " src="<?php echo base_url()?>uploads/brand/<?php echo $brand_nm['brand_img']; ?>">

								<label  id="price_<?php echo $product['id'];?>" class="add-to item_price">
								<?php echo currency($product['pro_price']); ?>

Available Options :

Size:<select>
									<option>Large</option>
									<option>Medium</option>
									<option>small</option>
									<option>Large</option>
									<option>small</option>
								</select>

 Add To Cart
								Buy Now

<?php $user_session=$this->session->user; ?>

Similer Product

			<?php foreach($similar_product as $r):?>

						<a href="<?php echo base_url()."users/product/product_add/$r->id"; ?>">
							<img class="img-responsive" src="<?php echo base_url().'uploads/product/'.$r->pro_image; ?>" alt="" />

<a href="<?php echo base_url()."users/product/product_add/$r->id"; ?>"><?php echo $r->pro_name ?>

<?php echo $r->pro_detail ?>

<?php echo currency($r->pro_price); ?>

								<a href="<?php echo base_url()."users/product/product_add/$r->id"; ?>">Quick View

				<?php endforeach; ?>

Categories

Men

Cute Kittens

Strange Stuff

Automatic Fails

Women

Cute Kittens

Strange Stuff

Automatic Fails

Kids

Cute Kittens

Strange Stuff

Automatic Fails

Accesories

Cute Kittens

Strange Stuff

Automatic Fails

Shoes

Cute Kittens

Strange Stuff

Automatic Fails

Best Sellers

						<?php foreach($populer as $r):?>

							<a href="<?php echo base_url()."users/product/product_add/$r->id"; ?>"><img class="img-responsive " src="<?php echo base_url().'uploads/product/'.$r->pro_image; ?>" alt="">

<a href="<?php echo base_url()."users/product/product_add/$r->id"; ?>" ><?php echo $r->pro_name; ?>

<a href="<?php echo base_url()."users/product/product_add/$r->id"; ?>" ><?php echo $r->brand_nm; ?>

							<?php echo currency($r->pro_price); ?>

					<?php endforeach;?>

Tags

design

fashion

lorem

dress

fashion

dress

design

dress

design

fashion

lorem

dress

<link href="<?php echo base_url(); ?>css/memenu.css" rel="stylesheet" type="text/css" media="all" />

<link rel="stylesheet" href="<?php echo base_url(); ?>css/flexslider.css" type="text/css" media="screen" />

					<link href="<?php echo base_url(); ?>css/popuo-box.css" rel="stylesheet" type="text/css" media="all"/>


text:
using System;
namespace fivenine.UnifiedMaps
{
    /// <summary>
    /// An <see cref="EventArgs"/> providing a generic playload.
    /// </summary>
    public class MapEventArgs<T> : EventArgs
    {
        /// <summary>
        /// Gets the value of the <see cref="T:MapEventArgs`1"/>.
        /// </summary>
        public T Value { get; private set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="T:MapEventArgs`1"/> class.
        /// </summary>
        /// <param name="value">Value.</param>
        public MapEventArgs(T value)
        {
            Value = value;
        }
    }
}


text:
"""
Set of functions related to jobs errors parsing and extracting descriptions

Created by Tatiana Korchuganova on 05.03.2020
"""
import json
import logging
import numpy as np

from django.core.cache import cache

from core.pandajob.models import Jobsarchived4, Jobsarchived

from core.libs.exlib import get_tmp_table_name, insert_to_temp_table

from core.ErrorCodes import ErrorCodes
import core.constants as const

_logger = logging.getLogger('bigpandamon')

def get_job_error_desc():
    """
    Get ErrorCodes and put into cache
    :return:
    """

    try:
        error_desc_dict = cache.get('errorCodes', None)
    except Exception as e:
        _logger.warning('Can not get error codes from cache: \n{} \nLoading directly instead...'.format(e))
        error_desc_dict = None

    if not error_desc_dict:
        codes = ErrorCodes()
        _, error_desc_dict, _ = codes.getErrorCodes()
        cache.set('errorCodes', error_desc_dict, 60*60*24)
    return error_desc_dict

def getErrorDescription(job, mode='html', provideProcessedCodes = False, **kwargs):
    txt = ''
    codesDescribed = []

    if 'errorCodes' in kwargs:
        errorCodes = kwargs['errorCodes']
    else:
        errorCodes = get_job_error_desc()

    if 'metastruct' in job:
        if type(job['metastruct']) is np.unicode:
            try:
                meta = json.loads(job['metastruct'])
            except:
                print ('Meta type: '+str(type(job['metastruct'])))
                meta = job['metastruct']
            if 'exitCode' in meta and meta['exitCode'] != 0:
                txt += "%s: %s" % (meta['exitAcronym'], meta['exitMsg'])
                if provideProcessedCodes:
                    return txt, codesDescribed
                else:
                    return txt
            else:
                if provideProcessedCodes:
                    return '-', codesDescribed
                else:
                    return '-'
        else:
            meta = job['metastruct']
            if 'exitCode' in meta and meta['exitCode'] != 0:
                txt += "%s: %s" % (meta['exitAcronym'], meta['exitMsg'])
                if provideProcessedCodes:
                    return txt, codesDescribed
                else:
                    return txt

    for errcode in errorCodes:
        errval = 0
        if errcode in job:
            errval = job[errcode]
            if errval != 0 and errval != '0' and errval != None and errval != '':
                try:
                    errval = int(errval)
                except:
                    pass  # errval = -1
                codesDescribed.append(errval)
                errdiag = errcode.replace('errorcode', 'errordiag')
                if errcode.find('errorcode') > 0:
                    if job[errdiag] is not None:
                        diagtxt = str(job[errdiag])
                    else:
                        diagtxt = ''
                else:
                    diagtxt = ''
                if len(diagtxt) > 0:
                    desc = diagtxt
                elif errval in errorCodes[errcode]:
                    desc = errorCodes[errcode][errval]
                else:
                    desc = "Unknown %s error code %s" % (errcode, errval)
                errname = errcode.replace('errorcode', '')
                errname = errname.replace('exitcode', '')
                if mode == 'html':
                    txt += " %s, %d: %s" % (errname, errval, desc)
                else:
                    txt = "%s, %d: %s" % (errname, errval, desc)
    if provideProcessedCodes:
        return txt, codesDescribed
    else:
        return txt

def errorInfo(job, nchars=300, mode='html', **kwargs):
    errtxt = ''
    err1 = ''
    if 'errorCodes' in kwargs:
        errorCodes = kwargs['errorCodes']
    else:
        errorCodes = get_job_error_desc()

    desc, codesDescribed = getErrorDescription(job, provideProcessedCodes=True, errorCodes=errorCodes)

    for error_cat in const.JOB_ERROR_CATEGORIES:
        if error_cat['error'] in job and job[error_cat['error']] != '' and not job[error_cat['error']] is None and int(job[error_cat['error']]) != 0 and int(job[error_cat['error']]) not in codesDescribed:
            if error_cat['diag'] is not None:
                errtxt += '{} {}: {}
'.format(error_cat['title'], job[error_cat['error']], job[error_cat['diag']])
                if err1 == '':
                    err1 = "{}: {}".format(error_cat['name'], job[error_cat['diag']])
            else:
                errtxt += '{} {}
'.format(error_cat['title'], job[error_cat['error']])
                if err1 == '':
                    err1 = "{}: {}".format(error_cat['name'], job[error_cat['error']])

    if len(desc) > 0:
        errtxt += '%s
' % desc
        if err1 == '':
            err1 = getErrorDescription(job, mode='string', errorCodes=errorCodes)

    if err1.find('lost heartbeat') >= 0:
        err1 = 'lost heartbeat'
    if err1.lower().find('unknown transexitcode') >= 0:
        err1 = 'unknown transexit'
    if err1.find(' at ') >= 0:
        err1 = err1[:err1.find(' at ') - 1]
    if errtxt.find('lost heartbeat') >= 0:
        err1 = 'lost heartbeat'
    err1 = err1.replace('\n', ' ')

    if mode == 'html':
        return errtxt
    else:
        return err1[:nchars]

def get_job_errors(pandaids):
    """
    Get error info for a list of PanDA jobs
    :param pandaids: list of pandaids
    :return: errors_dict: dict
    """
    MAX_ENTRIES__IN = 100

    errors_dict = {}

    jobs = []
    jquery = {}
    extra_str = ' (1=1) '
    values = (
        'pandaid',
        'transexitcode',
        'brokerageerrorcode', 'brokerageerrordiag',
        'ddmerrorcode', 'ddmerrordiag',
        'exeerrorcode', 'exeerrordiag',
        'jobdispatchererrorcode', 'jobdispatchererrordiag',
        'piloterrorcode', 'piloterrordiag',
        # 'superrorcode', 'superrordiag',
        'taskbuffererrorcode', 'taskbuffererrordiag'
        )

    if len(pandaids) > 0 and len(pandaids) <= MAX_ENTRIES__IN:
        jquery['pandaid__in'] = pandaids
    elif len(pandaids) > 0 and len(pandaids) > MAX_ENTRIES__IN:
        # insert pandaids to temp DB table
        tmp_table_name = get_tmp_table_name()
        tk_pandaids = insert_to_temp_table(pandaids)
        extra_str += " AND pandaid in (select ID from {} where TRANSACTIONKEY={})".format(tmp_table_name, tk_pandaids)
    else:
        return errors_dict

    jobs.extend(Jobsarchived4.objects.filter(**jquery).extra(where=[extra_str]).values(*values))
    jobs.extend(Jobsarchived.objects.filter(**jquery).extra(where=[extra_str]).values(*values))

    for job in jobs:
        errors_dict[job['pandaid']] = errorInfo(job)

    return errors_dict


text:
 * Documentation overhaul with more examples.

 * Add Data.Csv.Builder, a low-level bytestring builder API.

 * Add a high-level builder API to Data.Csv.Incremental.

 * Generalize the default FromNamedRecord/ToNamedRecord instances.

 * Improved support for deriving instances using GHC.Generics.

 * Added some control over quoting.

## Version 0.4.2.4

 * Support attoparsec 0.13.

## Version 0.4.2.3

 * Support GHC 7.10.

## Version 0.4.2.2

 * Support blaze-builder 0.4.

 * Make sure inlining doesn't prevent rules from firing.

 * Fix incorrect INLINE pragmas.

## Version 0.4.2.1

 * Support deepseq-1.4.

## Version 0.4.2.0

 * Minor performance improvements.

 * Add 8 and 9 tuple instances for From/ToRecord.

 * Support text-1.2.

## Version 0.4.1.0

 * Ignore whitespace when converting numeric fields.

 * Accept \r as a line terminator.

 * Support attoparsec-0.12.


text:
angular.module('merchello.directives').directive('comparisonOperatorRadioButtons', function() {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            operator: '='
        },
        templateUrl: '/App_Plugins/Merchello/Backoffice/Merchello/directives/comparisonOperatorRadioButtons.tpl.html',
        controller: function($scope) {

            function init() {
                if($scope.operator === undefined) {
                    $scope.operator = 'gt';
                }
            }

            init();
        }
    };
});


text:
<?php

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Form\addUser;
use Application\Form\addUserValidator;
use Application\Entity\User;

class ClientController extends \Application\Controller\BaseController
{

    public function redirectTo($action = 'list')
    {
        return $this->redirect()->toRoute('client', array(
            'action' => $action
        ));
    }

    public function indexAction()
    {

    }

    public function addAction()
    {
        $form = new addUser();
        //add developer
        $client_id = 0;
        $developers = $this->getEntityManager()->getRepository('Application\Entity\User')->getDevelopersList($client_id);
        $form->get('developers')->setValueOptions($developers);
        $request = $this->getRequest();

        if ($request->isPost()) {

            $formValidator = new addUserValidator();
            $form->setInputFilter($formValidator->getInputFilter());
            $form->setData($request->getPost());
            $form->setValidationGroup('name', 'username', 'password', 'password_verify');
            $criteria = array(
                'username' => $request->getPost('username'),
                'userType' => 2,
                'status' => 1
            );
            $userExist = $this->getEntityManager()->getRepository('Application\Entity\User')->findOneBy($criteria);
            $error = 0;
            if (count($userExist) > 0) {

                $form->setMessages(array(
                    'username' => array(
                        'exist' => 'Client already exist with this username,try another one please')
                ));
                $error = 1;
            }
            if ($form->isValid() and !$error) {
                $client = new User();
                $client->setUserType(2);
                $client->setAccessType(1);
                $client->setName($request->getPost('name'));
                $client->setEmail($request->getPost('email'));
                $client->setUsername($request->getPost('username'));
                $client->setPassword($request->getPost('password'));
                $client->setStatus($request->getPost('status'));
                $developers = $request->getPost('developers');
                if (count($developers) > 0) {
                    foreach ($developers as $devId) {
                        $dev = $this->getEntityManager()->getRepository('Application\Entity\User')->find($devId);
                        if ($dev instanceof \Application\Entity\User)
                            $client->addDeveloper($dev);
                    }
                }
                $this->getEntityManager()->persist($client);
                $this->getEntityManager()->flush();
                $this->flashMessenger()->addMessage('Client has been saved successfully');
                return $this->redirectTo();
            }
        }
        return array(
            'form' => $form,
            'flashMessages' => $this->flashMessenger()->getMessages()
        );
    }

    public function editAction()
    {
        $id = (int)$this->params()->fromRoute('id', 0);
        if (!$id) {
            $this->redirectTo();
        }
        $request = $this->getRequest();
        $form = new addUser();
        //add developer
        $client_id = 0;
        $developers = $this->getEntityManager()->getRepository('Application\Entity\User')->getDevelopersList($client_id);
        $form->get('developers')->setValueOptions($developers);

        $form->get('submit')->setAttribute('value', 'Edit');
        $form->get('password')->setAttribute('required', '');
        $form->get('password_verify')->setAttribute('required', '');
        $form->get('username')->setAttribute('readonly', 'readonly');
        $client = $this->getEntityManager()->getRepository('Application\Entity\User')->find($id);
        $values = array();
        foreach ($client->getDevelopers() as $dev)
            $values[] = $dev->getId();

        $form->bind($client);
        $form->get('developers')->setValue($values);

        if ($request->isPost()) {

            $formValidator = new addUserValidator();
            $form->setInputFilter($formValidator->getInputFilter());
            $form->setData($request->getPost());
            $form->setValidationGroup('name', 'email', 'password', 'password_verify');

            if ($form->isValid()) {
                $client->setName($request->getPost('name'));
                $client->setEmail($request->getPost('email'));
                $client->setStatus($request->getPost('status'));
                if ($request->getPost('password'))
                    $client->setPassword($request->getPost('password'));
                $client->getDevelopers()->clear();
                $developers = $request->getPost('developers');
                if (count($developers) > 0) {
                    foreach ($developers as $devId) {
                        $dev = $this->getEntityManager()->getRepository('Application\Entity\User')->find($devId);
                        if ($dev instanceof \Application\Entity\User)
                            $client->addDeveloper($dev);
                    }
                }
                $this->getEntityManager()->flush();
                $this->flashMessenger()->addMessage('Client has been updated successfully');
                return $this->redirectTo();
            }
        }
        return array(
            'form' => $form,
            'flashMessages' => $this->flashMessenger()->getMessages()
        );
    }

    public function deleteAction()
    {
        $id = (int)$this->params()->fromRoute('id', 0);
        if (!$id) {
            $this->redirectTo();
        }
        $em = $this->getEntityManager();
        $model = $em->find('Application\Entity\User', $id);
        if ($model) {
            $em->remove($model);
            $em->flush();
            $this->flashMessenger()->addMessage('User has been deleted successfully');
        } else
            $this->flashMessenger()->addMessage('Problem has been occured.can not deleted,error');

        $this->redirectTo();
    }

    public function listAction()
    {
        //add datatable resource
        $renderer = $this->serviceLocator->get('Zend\View\Renderer\RendererInterface');
        $renderer->headScript()->appendFile($renderer->basePath('/DataTables/media/js/jquery.dataTables.min.js'));
        $renderer->headLink()->prependStylesheet($renderer->basePath('/DataTables/media/css/jquery.dataTables.css'));

        $request = $this->getRequest();
        if ($request->isPost()) {

        }
        return new ViewModel(array(
            'client' => $this->getCurrentUserId(),
            'flashMessages' => $this->flashMessenger()->getMessages()
        ));
    }

}


text:
$(function () {
    // Example 1 from http://www.virtuosoft.eu/code/bootstrap-touchspin/
    $("input[name='demo1']").TouchSpin({
        min: 0,
        max: 100,
        step: 0.1,
        decimals: 2,
        boostat: 5,
        maxboostedstep: 10,
        postfix: '%'
    });

    // Example 2 from http://www.virtuosoft.eu/code/bootstrap-touchspin/
    $("input[name='demo2']").TouchSpin({
        min: -1000000000,
        max: 1000000000,
        stepinterval: 50,
        maxboostedstep: 10000000,
        prefix: '$'
    });

    // Example 3 from http://www.virtuosoft.eu/code/bootstrap-touchspin/
    $("input[name='demo_vertical']").TouchSpin({
        verticalbuttons: true
    });

    // Example 4 from http://www.virtuosoft.eu/code/bootstrap-touchspin/
    $("input[name='demo_vertical2']").TouchSpin({
        verticalbuttons: true,
        verticalupclass: 'glyphicon glyphicon-plus',
        verticaldownclass: 'glyphicon glyphicon-minus'
    });

    // Example 5 from http://www.virtuosoft.eu/code/bootstrap-touchspin/
    $("input[name='demo3']").TouchSpin();

    // Example 6 from http://www.virtuosoft.eu/code/bootstrap-touchspin/
    $("input[name='demo3_21']").TouchSpin({
        initval: 40
    });

    // Example 7 from http://www.virtuosoft.eu/code/bootstrap-touchspin/
    $("input[name='demo4']").TouchSpin({
        postfix: "a button",
        postfix_extraclass: "btn btn-default"
    });

    // Example 8 from http://www.virtuosoft.eu/code/bootstrap-touchspin/
    $("input[name='demo4_2']").TouchSpin({
        postfix: "a button",
        postfix_extraclass: "btn btn-default"
    });

    // Example 9 from http://www.virtuosoft.eu/code/bootstrap-touchspin/
    $("input[name='demo5']").TouchSpin({
        prefix: "pre",
        postfix: "post"
    });

    // Example 10 from http://www.virtuosoft.eu/code/bootstrap-touchspin/
    $("input[name='demo6']").TouchSpin({
        buttondown_class: "btn btn-link",
        buttonup_class: "btn btn-link"
    });
});


text:
@interface AuthenticationWVCFlickr()

@property (nonatomic) NSString *authToken;
@property (nonatomic) NSString *authRequestPerm;
@property (nonatomic) NSString *authGrantedPerm;
@property (nonatomic) NSString *callbackBase;

@end

@implementation AuthenticationWVCFlickr

- (void)viewDidLoad {
    self.targetURL = [NSString stringWithFormat:@"https://www.flickr.com/services/oauth/authorize?oauth_token=%@&perms=%@", _authToken, _authRequestPerm];

    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Public Methods
- (void) setAuthToken:(NSString *)authToken permission:(NSString *)permission andCallbackBase:(NSString *)callbackBase {
    _authToken = authToken;
    _authRequestPerm = permission;
    _callbackBase = callbackBase;
}

#define mark - WebView Delegate Override
-(void) authenticationSuccess:(NSDictionary *)response {
    NSLog(@"Authentication Success");
}

-(void) authenticationFailure:(NSError *)error {
    NSLog(@"AUthentication Failure");
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [self.webView stopLoading];

    if([error code] == -1009)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Cannot open the page because it is not connected to the Internet." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [self.delegate authenticationFailure:error];
    }
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *responseURL = [request.URL absoluteString];

    if([responseURL hasPrefix:_callbackBase])
    {
        NSString* pattern = [NSString stringWithFormat:@"%@?", _callbackBase];
        NSString* urlString = [[request URL] absoluteString];
        NSArray * UrlParts = [urlString componentsSeparatedByString:pattern];
        urlString = [UrlParts objectAtIndex:1];

        NSDictionary *response = [FlickrUtil parseURLResponse:urlString];

        if (!self.delegate || ![self.delegate respondsToSelector:@selector(authenticationSuccess:)]) {
            @throw [NSException exceptionWithName:NSInternalInconsistencyException
                                           reason:@"delegate authenticationSuccess not implemented"
                                         userInfo:nil];
            return NO;
        }

        [self.delegate authenticationSuccess:response];
        return NO;
    }
    return YES;
}
@end