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

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.kuali.rice.core.api.util.ClassLoaderUtils;
import org.kuali.rice.krad.bo.PersistableBusinessObjectExtension;
import org.kuali.rice.krad.datadictionary.exception.AttributeValidationException;
import org.kuali.rice.krad.datadictionary.exception.CompletionException;
import org.kuali.rice.krad.datadictionary.parse.StringListConverter;
import org.kuali.rice.krad.datadictionary.parse.StringMapConverter;
import org.kuali.rice.krad.service.KRADServiceLocator;
import org.kuali.rice.krad.service.PersistenceStructureService;
import org.kuali.rice.krad.uif.UifConstants.ViewType;
import org.kuali.rice.krad.uif.util.ComponentBeanPostProcessor;
import org.kuali.rice.krad.uif.util.UifBeanFactoryPostProcessor;
import org.kuali.rice.krad.uif.view.View;
import org.kuali.rice.krad.util.ObjectUtils;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.support.KualiDefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.expression.StandardBeanExpressionResolver;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;

import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * Collection of named BusinessObjectEntry objects, each of which contains
 * information relating to the display, validation, and general maintenance of a
 * BusinessObject.
 */
public class DataDictionary  {

	protected KualiDefaultListableBeanFactory ddBeans = new KualiDefaultListableBeanFactory();
    protected XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ddBeans);

	// logger
	private static final Log LOG = LogFactory.getLog(DataDictionary.class);

	/**
	 * The encapsulation of DataDictionary indices
	 */
	protected DataDictionaryIndex ddIndex = new DataDictionaryIndex(ddBeans);

	// View indices
	protected UifDictionaryIndex uifIndex = new UifDictionaryIndex(ddBeans);

	/**
	 * The DataDictionaryMapper
	 * The default mapper simply consults the initialized indices
	 * on workflow document type
	 */
	protected DataDictionaryMapper ddMapper = new DataDictionaryIndexMapper();

	protected List<String> configFileLocations = new ArrayList<String>();

	public List<String> getConfigFileLocations() {
        return this.configFileLocations;
    }

    public void setConfigFileLocations(List<String> configFileLocations) {
        this.configFileLocations = configFileLocations;
    }

    public void addConfigFileLocation( String location ) throws IOException {
        indexSource( location );
    }

    /**
     * Sets the DataDictionaryMapper
     * @param mapper the datadictionary mapper
     */
    public void setDataDictionaryMapper(DataDictionaryMapper mapper) {
    	this.ddMapper = mapper;
    }

    private void indexSource(String sourceName) throws IOException {
        if (sourceName == null) {
            throw new DataDictionaryException("Source Name given is null");
        }

        if (!sourceName.endsWith(".xml") ) {
            Resource resource = getFileResource(sourceName);
            if (resource.exists()) {
                indexSource(resource.getFile());
            } else {
                LOG.warn("Could not find " + sourceName);
                throw new DataDictionaryException("DD Resource " + sourceName + " not found");
            }
        } else {
            if ( LOG.isDebugEnabled() ) {
                LOG.debug("adding sourceName " + sourceName + " ");
            }
            Resource resource = getFileResource(sourceName);
            if (! resource.exists()) {
                throw new DataDictionaryException("DD Resource " + sourceName + " not found");
            }

            String indexName = sourceName.substring(sourceName.lastIndexOf("/") + 1, sourceName.indexOf(".xml"));
            configFileLocations.add( sourceName );
        }
    }

    protected Resource getFileResource(String sourceName) {
        DefaultResourceLoader resourceLoader = new DefaultResourceLoader(ClassLoaderUtils.getDefaultClassLoader());
        return resourceLoader.getResource(sourceName);
    }

    private void indexSource(File dir) {
        for (File file : dir.listFiles()) {
            if (file.isDirectory()) {
                indexSource(file);
            } else if (file.getName().endsWith(".xml") ) {
                configFileLocations.add( "file:" + file.getAbsolutePath());
            } else {
                if ( LOG.isDebugEnabled() ) {
                    LOG.debug("Skipping non xml file " + file.getAbsolutePath() + " in DD load");
                }
            }
        }
    }

    public void parseDataDictionaryConfigurationFiles( boolean allowConcurrentValidation ) {
		// configure the bean factory, setup component decorator post processor
		// and allow Spring EL
        try {
            BeanPostProcessor idPostProcessor = ComponentBeanPostProcessor.class.newInstance();
            ddBeans.addBeanPostProcessor(idPostProcessor);
            ddBeans.setBeanExpressionResolver(new StandardBeanExpressionResolver());

            GenericConversionService conversionService = new GenericConversionService();
            conversionService.addConverter(new StringMapConverter());
            conversionService.addConverter(new StringListConverter());
            ddBeans.setConversionService(conversionService);
        } catch (Exception e1) {
            LOG.error("Cannot create component decorator post processor: " + e1.getMessage(), e1);
            throw new RuntimeException("Cannot create component decorator post processor: " + e1.getMessage(), e1);
        }

        // expand configuration locations into files
        LOG.info("Starting DD XML File Load");

        String[] configFileLocationsArray = new String[configFileLocations.size()];
        configFileLocationsArray = configFileLocations.toArray(configFileLocationsArray);
        configFileLocations.clear(); // empty the list out so other items can be added
        try {
            xmlReader.loadBeanDefinitions(configFileLocationsArray);
        } catch (Exception e) {
            LOG.error("Error loading bean definitions", e);
            throw new DataDictionaryException("Error loading bean definitions: " + e.getLocalizedMessage());
        }
        LOG.info("Completed DD XML File Load");

        UifBeanFactoryPostProcessor factoryPostProcessor = new UifBeanFactoryPostProcessor();
        factoryPostProcessor.postProcessBeanFactory(ddBeans);

        // indexing
        if (allowConcurrentValidation) {
            Thread t = new Thread(ddIndex);
            t.start();

            Thread t2 = new Thread(uifIndex);
            t2.start();
        } else {
            ddIndex.run();
            uifIndex.run();
        }
    }

	static boolean validateEBOs = true;

    public void validateDD( boolean validateEbos ) {
    	DataDictionary.validateEBOs = validateEbos;
    	Map<String,DataObjectEntry> doBeans = ddBeans.getBeansOfType(DataObjectEntry.class);
        for ( DataObjectEntry entry : doBeans.values() ) {
            entry.completeValidation();
        }
        Map<String,DocumentEntry> docBeans = ddBeans.getBeansOfType(DocumentEntry.class);
        for ( DocumentEntry entry : docBeans.values() ) {
            entry.completeValidation();
        }
    }

    public void validateDD() {
    	validateDD(true);
    }

	/**
	 * @param className
	 * @return BusinessObjectEntry for the named class, or null if none exists
	 */
    @Deprecated
	public BusinessObjectEntry getBusinessObjectEntry(String className ) {
		return ddMapper.getBusinessObjectEntry(ddIndex, className);
	}

	/**
     * @param className
     * @return BusinessObjectEntry for the named class, or null if none exists
     */
    public DataObjectEntry getDataObjectEntry(String className ) {
        return ddMapper.getDataObjectEntry(ddIndex, className);
    }

	/**
	 * This method gets the business object entry for a concrete class
	 *
	 * @param className
	 * @return
	 */
	public BusinessObjectEntry getBusinessObjectEntryForConcreteClass(String className){
		return ddMapper.getBusinessObjectEntryForConcreteClass(ddIndex, className);
	}

	/**
	 * @return List of businessObject classnames
	 */
	public List<String> getBusinessObjectClassNames() {
		return ddMapper.getBusinessObjectClassNames(ddIndex);
	}

	/**
	 * @return Map of (classname, BusinessObjectEntry) pairs
	 */
	public Map<String, BusinessObjectEntry> getBusinessObjectEntries() {
		return ddMapper.getBusinessObjectEntries(ddIndex);
	}

	/**
	 * @param className
	 * @return DataDictionaryEntryBase for the named class, or null if none
	 *         exists
	 */
	public DataDictionaryEntry getDictionaryObjectEntry(String className) {
		return ddMapper.getDictionaryObjectEntry(ddIndex, className);
	}

	/**
	 * Returns the KNS document entry for the given lookup key.  The documentTypeDDKey is interpreted
	 * successively in the following ways until a mapping is found (or none if found):
	 *

	 *
KEW/workflow document type

	 *
business object class name

	 *
maintainable class name

	 *

	 * This mapping is compiled when DataDictionary files are parsed on startup (or demand).  Currently this
	 * means the mapping is static, and one-to-one (one KNS document maps directly to one and only
	 * one key).
	 *
	 * @param documentTypeDDKey the KEW/workflow document type name
	 * @return the KNS DocumentEntry if it exists
	 */
	public DocumentEntry getDocumentEntry(String documentTypeDDKey ) {
		return ddMapper.getDocumentEntry(ddIndex, documentTypeDDKey);
	}

	/**
	 * Note: only MaintenanceDocuments are indexed by businessObject Class
	 *
	 * This is a special case that is referenced in one location. Do we need
	 * another map for this stuff??
	 *
	 * @param businessObjectClass
	 * @return DocumentEntry associated with the given Class, or null if there
	 *         is none
	 */
	public MaintenanceDocumentEntry getMaintenanceDocumentEntryForBusinessObjectClass(Class<?> businessObjectClass) {
		return ddMapper.getMaintenanceDocumentEntryForBusinessObjectClass(ddIndex, businessObjectClass);
	}

	public Map<String, DocumentEntry> getDocumentEntries() {
		return ddMapper.getDocumentEntries(ddIndex);
	}

	/**
	 * Returns the View entry identified by the given id
	 *
	 * @param viewId - unique id for view
	 * @return View instance associated with the id
	 */
	public View getViewById(String viewId) {
		return ddMapper.getViewById(uifIndex, viewId);
	}

	/**
	 * Returns View instance identified by the view type name and index
	 *
	 * @param viewTypeName
	 *            - type name for the view
	 * @param indexKey
	 *            - Map of index key parameters, these are the parameters the
	 *            indexer used to index the view initially and needs to identify
	 *            an unique view instance
	 * @return View instance that matches the given index
	 */
	public View getViewByTypeIndex(ViewType viewTypeName, Map<String, String> indexKey) {
		return ddMapper.getViewByTypeIndex(uifIndex, viewTypeName, indexKey);
	}

    /**
     * Indicates whether a View exists for the given view type and index information
     *
     * @param viewTypeName - type name for the view
     * @param indexKey - Map of index key parameters, these are the parameters the
     * indexer used to index the view initially and needs to identify
     * an unique view instance
     * @return boolean true if view exists, false if not
     */
    public boolean viewByTypeExist(ViewType viewTypeName, Map<String, String> indexKey) {
        return ddMapper.viewByTypeExist(uifIndex, viewTypeName, indexKey);
    }

	/**
	 * Gets all View prototypes configured for the given view type
	 * name
	 *
	 * @param viewTypeName
	 *            - view type name to retrieve
	 * @return List<View> view prototypes with the given type name, or empty
	 *         list
	 */
	public List<View> getViewsForType(ViewType viewTypeName) {
		return ddMapper.getViewsForType(uifIndex, viewTypeName);
	}

    /**
     * Returns an object from the dictionary by its spring bean name
     *
     * @param beanName - id or name for the bean definition
     * @return Object object instance created or the singleton being maintained
     */
    public Object getDictionaryObject(String beanName) {
        return ddBeans.getBean(beanName);
    }

    /**
     * Indicates whether the data dictionary contains a bean with the given id
     *
     * @param id - id of the bean to check for
     * @return boolean true if dictionary contains bean, false otherwise
     */
    public boolean containsDictionaryObject(String id) {
        return ddBeans.containsBean(id);
    }

    /**
     * Retrieves the configured property values for the view bean definition associated with the given id
     *
     *

     * Since constructing the View object can be expensive, when metadata only is needed this method can be used
     * to retrieve the configured property values. Note this looks at the merged bean definition
     *

     *
     * @param viewId - id for the view to retrieve
     * @return PropertyValues configured on the view bean definition, or null if view is not found
     */
    public PropertyValues getViewPropertiesById(String viewId) {
        return ddMapper.getViewPropertiesById(uifIndex, viewId);
    }

    /**
     * Retrieves the configured property values for the view bean definition associated with the given type and
     * index
     *
     *

     * Since constructing the View object can be expensive, when metadata only is needed this method can be used
     * to retrieve the configured property values. Note this looks at the merged bean definition
     *

     *
     * @param viewTypeName - type name for the view
     * @param indexKey - Map of index key parameters, these are the parameters the indexer used to index
     * the view initially and needs to identify an unique view instance
     * @return PropertyValues configured on the view bean definition, or null if view is not found
     */
    public PropertyValues getViewPropertiesByType(ViewType viewTypeName, Map<String, String> indexKey) {
        return ddMapper.getViewPropertiesByType(uifIndex, viewTypeName, indexKey);
    }

    /**
     * @param targetClass
     * @param propertyName
     * @return true if the given propertyName names a property of the given class
     * @throws CompletionException if there is a problem accessing the named property on the given class
     */
    public static boolean isPropertyOf(Class targetClass, String propertyName) {
        if (targetClass == null) {
            throw new IllegalArgumentException("invalid (null) targetClass");
        }
        if (StringUtils.isBlank(propertyName)) {
            throw new IllegalArgumentException("invalid (blank) propertyName");
        }

        PropertyDescriptor propertyDescriptor = buildReadDescriptor(targetClass, propertyName);

        boolean isPropertyOf = (propertyDescriptor != null);
        return isPropertyOf;
    }

    /**
     * @param targetClass
     * @param propertyName
     * @return true if the given propertyName names a Collection property of the given class
     * @throws CompletionException if there is a problem accessing the named property on the given class
     */
    public static boolean isCollectionPropertyOf(Class targetClass, String propertyName) {
        boolean isCollectionPropertyOf = false;

        PropertyDescriptor propertyDescriptor = buildReadDescriptor(targetClass, propertyName);
        if (propertyDescriptor != null) {
            Class clazz = propertyDescriptor.getPropertyType();

            if ((clazz != null) && Collection.class.isAssignableFrom(clazz)) {
                isCollectionPropertyOf = true;
            }
        }

        return isCollectionPropertyOf;
    }

    public static PersistenceStructureService persistenceStructureService;

    /**
     * @return the persistenceStructureService
     */
    public static PersistenceStructureService getPersistenceStructureService() {
        if ( persistenceStructureService == null ) {
            persistenceStructureService = KRADServiceLocator.getPersistenceStructureService();
        }
        return persistenceStructureService;
    }

    /**
     * This method determines the Class of the attributeName passed in. Null will be returned if the member is not available, or if
     * a reflection exception is thrown.
     *
     * @param boClass - Class that the attributeName property exists in.
     * @param attributeName - Name of the attribute you want a class for.
     * @return The Class of the attributeName, if the attribute exists on the rootClass. Null otherwise.
     */
    public static Class getAttributeClass(Class boClass, String attributeName) {

        // fail loudly if the attributeName isnt a member of rootClass
        if (!isPropertyOf(boClass, attributeName)) {
            throw new AttributeValidationException("unable to find attribute '" + attributeName + "' in rootClass '" + boClass.getName() + "'");
        }

    	//Implementing Externalizable Business Object Services...
        //The boClass can be an interface, hence handling this separately,
        //since the original method was throwing exception if the class could not be instantiated.
        if(boClass.isInterface())
        	return getAttributeClassWhenBOIsInterface(boClass, attributeName);
        else
        	return getAttributeClassWhenBOIsClass(boClass, attributeName);

    }

    /**
     *
     * This method gets the property type of the given attributeName when the bo class is a concrete class
     *
     * @param boClass
     * @param attributeName
     * @return
     */
    private static Class getAttributeClassWhenBOIsClass(Class boClass, String attributeName){
    	Object boInstance;
        try {
            boInstance = boClass.newInstance();
        } catch (Exception e) {
        	throw new RuntimeException("Unable to instantiate Data Object: " + boClass, e);
        }

        // attempt to retrieve the class of the property
        try {
            return ObjectUtils.getPropertyType(boInstance, attributeName, getPersistenceStructureService());
        } catch (Exception e) {
            throw new RuntimeException("Unable to determine property type for: " + boClass.getName() + "." + attributeName, e);
        }
    }

    /**
     *
     * This method gets the property type of the given attributeName when the bo class is an interface
     * This method will also work if the bo class is not an interface,
     * but that case requires special handling, hence a separate method getAttributeClassWhenBOIsClass
     *
     * @param boClass
     * @param attributeName
     * @return
     */
    private static Class getAttributeClassWhenBOIsInterface(Class boClass, String attributeName){
        if (boClass == null) {
            throw new IllegalArgumentException("invalid (null) boClass");
        }
        if (StringUtils.isBlank(attributeName)) {
            throw new IllegalArgumentException("invalid (blank) attributeName");
        }

        PropertyDescriptor propertyDescriptor = null;

        String[] intermediateProperties = attributeName.split("\\.");
        int lastLevel = intermediateProperties.length - 1;
        Class currentClass = boClass;

        for (int i = 0; i <= lastLevel; ++i) {

            String currentPropertyName = intermediateProperties[i];
            propertyDescriptor = buildSimpleReadDescriptor(currentClass, currentPropertyName);

            if (propertyDescriptor != null) {

                Class propertyType = propertyDescriptor.getPropertyType();
                if ( propertyType.equals( PersistableBusinessObjectExtension.class ) ) {
                    propertyType = getPersistenceStructureService().getBusinessObjectAttributeClass( currentClass, currentPropertyName );
                }
                if (Collection.class.isAssignableFrom(propertyType)) {
                	// TODO: determine property type using generics type definition
                	throw new AttributeValidationException("Can't determine the Class of Collection elements because when the business object is an (possibly ExternalizableBusinessObject) interface.");
                }
                else {
                    currentClass = propertyType;
                }
            }
            else {
            	throw new AttributeValidationException("Can't find getter method of " + boClass.getName() + " for property " + attributeName);
            }
        }
        return currentClass;
    }

    /**
     * This method determines the Class of the elements in the collectionName passed in.
     *
     * @param boClass Class that the collectionName collection exists in.
     * @param collectionName the name of the collection you want the element class for
     * @return
     */
    public static Class getCollectionElementClass(Class boClass, String collectionName) {
        if (boClass == null) {
            throw new IllegalArgumentException("invalid (null) boClass");
        }
        if (StringUtils.isBlank(collectionName)) {
            throw new IllegalArgumentException("invalid (blank) collectionName");
        }

        PropertyDescriptor propertyDescriptor = null;

        String[] intermediateProperties = collectionName.split("\\.");
        Class currentClass = boClass;

        for (int i = 0; i <intermediateProperties.length; ++i) {

            String currentPropertyName = intermediateProperties[i];
            propertyDescriptor = buildSimpleReadDescriptor(currentClass, currentPropertyName);

                if (propertyDescriptor != null) {

                    Class type = propertyDescriptor.getPropertyType();
                    if (Collection.class.isAssignableFrom(type)) {

                        if (getPersistenceStructureService().isPersistable(currentClass)) {

                            Map<String, Class> collectionClasses = new HashMap<String, Class>();
                            collectionClasses = getPersistenceStructureService().listCollectionObjectTypes(currentClass);
                            currentClass = collectionClasses.get(currentPropertyName);

                        }
                        else {
                            throw new RuntimeException("Can't determine the Class of Collection elements because persistenceStructureService.isPersistable(" + currentClass.getName() + ") returns false.");
                        }

                    }
                    else {

                        currentClass = propertyDescriptor.getPropertyType();

                    }
                }
            }

        return currentClass;
    }

    static private Map<String, Map<String, PropertyDescriptor>> cache = new TreeMap<String, Map<String, PropertyDescriptor>>();

    /**
     * @param propertyClass
     * @param propertyName
     * @return PropertyDescriptor for the getter for the named property of the given class, if one exists.
     */
    public static PropertyDescriptor buildReadDescriptor(Class propertyClass, String propertyName) {
        if (propertyClass == null) {
            throw new IllegalArgumentException("invalid (null) propertyClass");
        }
        if (StringUtils.isBlank(propertyName)) {
            throw new IllegalArgumentException("invalid (blank) propertyName");
        }

        PropertyDescriptor propertyDescriptor = null;

        String[] intermediateProperties = propertyName.split("\\.");
        int lastLevel = intermediateProperties.length - 1;
        Class currentClass = propertyClass;

        for (int i = 0; i <= lastLevel; ++i) {

            String currentPropertyName = intermediateProperties[i];
            propertyDescriptor = buildSimpleReadDescriptor(currentClass, currentPropertyName);

            if (i < lastLevel) {

                if (propertyDescriptor != null) {

                    Class propertyType = propertyDescriptor.getPropertyType();
                    if ( propertyType.equals( PersistableBusinessObjectExtension.class ) ) {
                        propertyType = getPersistenceStructureService().getBusinessObjectAttributeClass( currentClass, currentPropertyName );
                    }
                    if (Collection.class.isAssignableFrom(propertyType)) {

                        if (getPersistenceStructureService().isPersistable(currentClass)) {

                            Map<String, Class> collectionClasses = new HashMap<String, Class>();
                            collectionClasses = getPersistenceStructureService().listCollectionObjectTypes(currentClass);
                            currentClass = collectionClasses.get(currentPropertyName);

                        }
                        else {

                            throw new RuntimeException("Can't determine the Class of Collection elements because persistenceStructureService.isPersistable(" + currentClass.getName() + ") returns false.");

                        }

                    }
                    else {

                        currentClass = propertyType;

                    }

                }

            }

        }

        return propertyDescriptor;
    }

    /**
     * @param propertyClass
     * @param propertyName
     * @return PropertyDescriptor for the getter for the named property of the given class, if one exists.
     */
    public static PropertyDescriptor buildSimpleReadDescriptor(Class propertyClass, String propertyName) {
        if (propertyClass == null) {
            throw new IllegalArgumentException("invalid (null) propertyClass");
        }
        if (StringUtils.isBlank(propertyName)) {
            throw new IllegalArgumentException("invalid (blank) propertyName");
        }

        PropertyDescriptor p = null;

        // check to see if we've cached this descriptor already. if yes, return true.
        String propertyClassName = propertyClass.getName();
        Map<String, PropertyDescriptor> m = cache.get(propertyClassName);
        if (null != m) {
            p = m.get(propertyName);
            if (null != p) {
                return p;
            }
        }

        // Use PropertyUtils.getPropertyDescriptors instead of manually constructing PropertyDescriptor because of
        // issues with introspection and generic/co-variant return types
        // See https://issues.apache.org/jira/browse/BEANUTILS-340 for more details

        PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(propertyClass);
        if (ArrayUtils.isNotEmpty(descriptors)) {
            for (PropertyDescriptor descriptor : descriptors) {
                if (descriptor.getName().equals(propertyName)) {
                    p = descriptor;
                }
            }
        }

        // cache the property descriptor if we found it.
        if (p != null) {
            if (m == null) {
                m = new TreeMap<String, PropertyDescriptor>();
                cache.put(propertyClassName, m);
            }
            m.put(propertyName, p);
        }

        return p;
    }

    public Set<InactivationBlockingMetadata> getAllInactivationBlockingMetadatas(Class blockedClass) {
    	return ddMapper.getAllInactivationBlockingMetadatas(ddIndex, blockedClass);
    }

    /**
     * This method gathers beans of type BeanOverride and invokes each one's performOverride() method.
     */
    // KULRICE-4513
    public void performBeanOverrides()
    {
    	Collection<BeanOverride> beanOverrides = ddBeans.getBeansOfType(BeanOverride.class).values();

    	if (beanOverrides.isEmpty()){
    		LOG.info("DataDictionary.performOverrides(): No beans to override");
    	}
		for (BeanOverride beanOverride : beanOverrides) {

			Object bean = ddBeans.getBean(beanOverride.getBeanName());
			beanOverride.performOverride(bean);
			LOG.info("DataDictionary.performOverrides(): Performing override on bean: " + bean.toString());
		}
    }

}


text:
- **Total Indicator Count**

#### Playbooks
##### Rapid Breach Response - Set Incident Info
- Added transformer 'StringToArray' to sourceofindicators Set task.

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=type.int32_t.html">

Redirecting to type.int32_t.html...


text:
layout: post
unique_id: work_work_work
title: Work Work Work
categories: []
locations:
---

YESTERDAY:
* shrimp for lunch
* met up with an old colleague
  * he's amazing
* product review sessions!
* hiring stuffs
* panda for dinner
* bit of civ 6
* laundry

TODAY:
* head to work
  * debugging
* missed lunch :(
* Zeni's for dinner!
* lost a game of eldritch horror
* won the 2nd game though!

LEARNINGS:
* Medallia was full of talented folks


text:
from Tkinter import *
import threading

class Window(threading.Thread):
    def __init__(self, text):
        self.window = Tk() #Instantiate the window
        self.window.geometry('200x50+0+0') #Sets size and position
        self.window.overrideredirect(1) #Removes Window Border
        self.window.attributes('-topmost', True) #Makes sure window is always on top
        self.window.configure(background="purple")
#        self.window.setBackground("gray")
        self.text = StringVar() #Creates a StringVar
        self.text.set(text) #Set text value to passed argument
        #self.text.setTextColor("purple")
        self.label = Label(self.window, textvariable=self.text, height=16) #Creates the label in which to hold the text
        self.label.configure(background="purple")
        self.label.configure(foreground="grey")
        self.label.configure(font=("Coolvetica RG", 16))
        self.label.pack()
        threading.Thread.__init__(self) #Initialize this as a thread (so it can run independently from the other parts of the program)
        self.start() #Start this object up!

    def run(self):
        self.window.mainloop() #Makes the window actually appear

    def setText(self, text):
        self.text.set(text)

    def hideWindow(self):
        self.window.geometry('0x0')

    def showWindow(self):
        self.window.geometry('200x50+0+0')

    def drop(self, amount = 50):
        self.window.geometry('%dx%d+0+0' % (self.window.winfo_width(), self.window.winfo_height() + 50))

    def lift(self, amount = 50):
        self.window.geometry('%dx%d+0+0' % (self.window.winfo_width(), self.window.winfo_height() - 50 if self.window.winfo_height() >= 100 else self.window.winfo_height()))


text:
require_relative 'boot'
require 'rails/all'

Bundler.require(*Rails.groups)

module Backend
  class Application < Rails::Application
    config.api_only = true
  end
end


text:
"""

Django raises DoesNotExist when consulting an empty ForeignKey field
Django Ticket#12708 (http://code.djangoproject.com/ticket/12708)

We create an Order without a Journal:

  >>> o = Order()
  >>> print o.journal
  None
  >>> o.save()

This works only because `Order.journal` has `null=True`.
In fact I want the `save()` method to complain if `journal` is empty,
so I remove `null=True` from the field definition.

  >>> o = Order2()
  >>> print o.journal
  Traceback (most recent call last):
  ...
  DoesNotExist

The above line raises a DoesNotExist exception. Django should raise
an exception only when I try to save the instance, not already when
I want to see the value of `journal`!

"""

from django.db import models

class Journal(models.Model):
    pass

class Order(models.Model):
    journal = dd.ForeignKey(Journal, null=True)

class Order2(models.Model):
    journal = dd.ForeignKey(Journal)


text:
. /etc/profile.d/modules.sh
module add ci
module add bzip2
module  add  readline
module add gcc/${GCC_VERSION}
module add openmpi/${OPENMPI_VERSION}-gcc-${GCC_VERSION}
module add python/2.7.13-gcc-${GCC_VERSION}
module add icu/59_1-gcc-${GCC_VERSION}
REMOTE_VERSION=`echo ${VERSION} | sed "s/\\./\_/g"`

cd ${WORKSPACE}/${NAME}_${REMOTE_VERSION}/

# There is a check missing
./b2 install

mkdir -p modules
(
cat <<MODULE_FILE
#%Module1.0
## $NAME modulefile
##
proc ModulesHelp { } {
  puts stderr "\\tAdds $NAME ($VERSION.) to your environment."
}
module-whatis "Sets the environment for using $NAME ($VERSION.) Built with GCC ${GCC_VERSION} and OpenMPI Version ${OPENMPI_VERSION}"
module add bzip2
module add readline
module add gcc/${GCC_VERSION}
module add openmpi/${OPENMPI_VERSION}-gcc-${GCC_VERSION}
module add python/2.7.13-gcc-${GCC_VERSION}
module  add  icu/59_1-gcc-${GCC_VERSION}
setenv BOOST_VERSION $VERSION
setenv BOOST_DIR /data/ci-build/$::env(SITE)/$::env(OS)/$::env(ARCH)/${NAME}/${VERSION}-gcc-${GCC_VERSION}-mpi-${OPENMPI_VERSION}
setenv BOOST_ROOT $::env(BOOST_DIR)
setenv CFLAGS "$CFLAGS -I$::env(BOOST_DIR)/include -L$::env(BOOST_DIR)/lib"
prepend-path CPATH $::env(BOOST_DIR)/include
prepend-path LD_LIBRARY_PATH $::env(BOOST_DIR)
MODULE_FILE
) > modules/${VERSION}-gcc-${GCC_VERSION}-mpi-${OPENMPI_VERSION}
mkdir -p ${LIBRARIES}/${NAME}
cp modules/${VERSION}-gcc-${GCC_VERSION}-mpi-${OPENMPI_VERSION} ${LIBRARIES}/${NAME}
module avail ${NAME}
module add ${NAME}/${VERSION}-gcc-${GCC_VERSION}-mpi-${OPENMPI_VERSION}
echo "LD_LIBRARY_PATH is : ${LD_LIBRARY_PATH}"
which g++
cd ${WORKSPACE}
echo "BOOST DIR is ${BOOST_DIR} ; SOFT_DIR is ${SOFT_DIR}"
ls -lht ${BOOST_DIR}
c++ -I${BOOST_DIR}/include -L${BOOST_DIR}/lib hello-world.cpp
./a.out


text:
@class Post;

@interface User : NSManagedObject

@property (nonatomic, retain) NSNumber * age;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * surname;
@property (nonatomic, retain) NSSet *posts;
@end

@interface User (CoreDataGeneratedAccessors)

- (void)addPostsObject:(Post *)value;
- (void)removePostsObject:(Post *)value;
- (void)addPosts:(NSSet *)values;
- (void)removePosts:(NSSet *)values;

@end


text:
package com.marshalchen.common.uimodule.standuptimer.utils;

import android.graphics.Color;

public abstract class TimeFormatHelper {

    public static int determineColor(int seconds, int warningTime) {
        if (seconds <= 0) {
            return Color.RED;
        } else if (seconds <= warningTime) {
            return Color.YELLOW;
        } else {
            return Color.GREEN;
        }
    }

    public static String formatTime(int seconds) {
        return Integer.toString(seconds / 60) + ":" + padWithZeros(seconds % 60);
    }

    public static String formatTime(float seconds) {
        return formatTime((int) seconds);
    }

    private static String padWithZeros(int seconds) {
        return seconds < 10 ? "0" + seconds : Integer.toString(seconds);
    }
}


text:
export * from './menu-module';
export * from './menu-bar';
export * from './menu';
export * from './menu-base';
export * from './menu-item';
export * from './menu-item-checkbox';
export * from './menu-item-radio';
export * from './menu-trigger';
export * from './menu-group';
export * from './menu-item-selectable';
export * from './context-menu-trigger';
export * from './menu-trigger-base';
export * from './pointer-focus-tracker';
export * from './menu-stack';
export * from './menu-interface';
export * from './menu-aim';


text:
package org.apache.derbyTesting.functionTests.tests.memory;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.XAConnection;
import javax.sql.XADataSource;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import junit.framework.Test;
import org.apache.derbyTesting.junit.BaseJDBCTestCase;
import org.apache.derbyTesting.junit.BaseTestSuite;
import org.apache.derbyTesting.junit.J2EEDataSource;
import org.apache.derbyTesting.junit.JDBC;
import org.apache.derbyTesting.junit.TestConfiguration;
import org.apache.derbyTesting.junit.XATestUtil;

/**
 * Tests verifying that the memory usage for certain XA operations / access
 * patterns isn't unreasonably high.
 */
public class XAMemTest
        extends BaseJDBCTestCase {

    public XAMemTest(String name) {
        super(name);
    }

    public void setUp()
            throws SQLException {
        // Create the default wombat database if it doesn't exist.
        // Required to run some of the test cases individually.
        getConnection();
    }

    /**
     * DERBY-4137: Execute a bunch of successful XA transactions with a
     * transaction timeout specified.
     *
     * @throws Exception if something goes wrong
     */
    public void testDerby4137_TransactionTimeoutSpecifiedNotExceeded()
            throws Exception {
        XADataSource xads = J2EEDataSource.getXADataSource();
        XAConnection xac = xads.getXAConnection();
        XAResource xar = xac.getXAResource();
        Xid xid = XATestUtil.getXid(8, 9, 10);
        Connection con = xac.getConnection();
        Statement stmt = con.createStatement();

        // Set a long timeout such that the queue won't be able to clean
        // itself as part of normal processing.
        xar.setTransactionTimeout(100000);

        // 60'000 iterations was selected to balance duration versus chance of
        // detecting a "memory leak". The test failed before DERBY-4137 was
        // addressed.
        for (int i=0; i < 60000; i++) {
            xar.start(xid, XAResource.TMNOFLAGS);
            stmt.executeQuery("values 1");
            xar.end(xid, XAResource.TMSUCCESS);
            xar.commit(xid, true);
        }
        xac.close();
    }

    public static Test suite() {
        if (JDBC.vmSupportsJDBC3()) {
            return TestConfiguration.defaultSuite(XAMemTest.class);
        }

        return new BaseTestSuite(
            "XAMemTest skipped - XADataSource not available");
    }
}


text:
/* eslint-disable qunit/no-test-expect-argument */
import { decamelize } from '@ember/string';
import { moduleFor, AbstractTestCase } from 'internal-test-helpers';

function test(assert, given, expected, description) {
  assert.deepEqual(decamelize(given), expected, description);
}

moduleFor(
  'EmberStringUtils.decamelize',
  class extends AbstractTestCase {
    ['@test String decamelize tests'](assert) {
      test(assert, 'my favorite items', 'my favorite items', 'does nothing with normal string');
      test(assert, 'css-class-name', 'css-class-name', 'does nothing with dasherized string');
      test(assert, 'action_name', 'action_name', 'does nothing with underscored string');
      test(
        assert,
        'innerHTML',
        'inner_html',
        'converts a camelized string into all lower case separated by underscores.'
      );
      test(assert, 'size160Url', 'size160_url', 'decamelizes strings with numbers');
      test(
        assert,
        'PrivateDocs/OwnerInvoice',
        'private_docs/owner_invoice',
        'decamelize namespaced classified string'
      );
      test(
        assert,
        'privateDocs/ownerInvoice',
        'private_docs/owner_invoice',
        'decamelize namespaced camelized string'
      );
    }
  }
);


text:
package io.netty.example.memcache.binary;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.memcache.binary.BinaryMemcacheClientCodec;
import io.netty.handler.codec.memcache.binary.BinaryMemcacheObjectAggregator;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Simple memcache client that demonstrates get and set commands against a memcache server.
 */
public class MemcacheClient {

    private final String host;
    private final int port;

    public MemcacheClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new BinaryMemcacheClientCodec());
                            p.addLast(new BinaryMemcacheObjectAggregator(Integer.MAX_VALUE));
                            p.addLast(new MemcacheClientHandler());
                        }
                    });

            // Start the connection attempt.
            Channel ch = b.connect(host, port).sync().channel();

            // Read commands from the stdin.
            System.out.println("Enter commands (quit to end)");
            System.out.println("get <key>");
            System.out.println("set <key> <value>");
            ChannelFuture lastWriteFuture = null;
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            for (;;) {
                String line = in.readLine();
                if (line == null) {
                    break;
                }
                if ("quit".equals(line.toLowerCase())) {
                    ch.close().sync();
                    break;
                }
                // Sends the received line to the server.
                lastWriteFuture = ch.writeAndFlush(line);
            }

            // Wait until all messages are flushed before closing the channel.
            if (lastWriteFuture != null) {
                lastWriteFuture.sync();
            }
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        // Print usage if no argument is specified.
        if (args.length != 2) {
            System.err.println(
                    "Usage: " + MemcacheClient.class.getSimpleName() +
                            " <host> <port>");
            return;
        }

        // Parse options.
        String host = args[0];
        int port = Integer.parseInt(args[1]);

        new MemcacheClient(host, port).run();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="?attr/themedColorCard">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="16dp">
        <LinearLayout
            android:layout_toLeftOf="@+id/trends_ranking_rank_holder"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingRight="12dp"
            android:orientation="vertical">
            <TextView
                android:id="@+id/trends_ranking_nation"
                android:textSize="17sp"
                android:fontFamily="sans-serif"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="?attr/themedColorLinkText"
                tools:text="Greater Tern" />
            <TextView
                android:id="@+id/trends_ranking_score"
                android:textSize="14sp"
                android:fontFamily="sans-serif-light"
                android:textStyle="italic"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="?attr/themedColorSecondaryText"
                tools:text="1,959,005,987,536,900" />
        </LinearLayout>
        <LinearLayout
            android:id="@+id/trends_ranking_rank_holder"
            android:adjustViewBounds="true"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:orientation="horizontal">
            <TextView
                android:textSize="12sp"
                android:paddingRight="4dp"
                android:gravity="center_vertical"
                android:fontFamily="sans-serif-light"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:textColor="?attr/themedColorSecondaryText"
                android:textAlignment="center"
                android:text="@string/census_hash_symbol"/>
            <TextView
                android:id="@+id/trends_ranking_rank"
                android:textSize="20sp"
                android:fontFamily="sans-serif-light"
                android:textAlignment="center"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="?attr/themedColorSecondaryText"
                tools:text="123,456" />
        </LinearLayout>
    </RelativeLayout>
    <include layout="@layout/view_divider" />
</LinearLayout>


text:
<?php
/**
 * Reveal.wp functions and definitions
 *
 * @package Reveal.wp
 */

/**
 * Set the content width based on the theme's design and stylesheet.
 */
if ( ! isset( $content_width ) ) {
	$content_width = 640; /* pixels */
}

if ( ! function_exists( 'reveal_wp_setup' ) ) :
/**
 * Sets up theme defaults and registers support for various WordPress features.
 *
 * Note that this function is hooked into the after_setup_theme hook, which
 * runs before the init hook. The init hook is too late for some features, such
 * as indicating support for post thumbnails.
 */
function reveal_wp_setup() {

	/*
	 * Make theme available for translation.
	 * Translations can be filed in the /languages/ directory.
	 * If you're building a theme based on Reveal.wp, use a find and replace
	 * to change 'reveal-wp' to the name of your theme in all the template files
	 */
	load_theme_textdomain( 'reveal-wp', get_template_directory() . '/languages' );

	// Add default posts and comments RSS feed links to head.
	add_theme_support( 'automatic-feed-links' );

	/*
	 * Enable support for Post Thumbnails on posts and pages.
	 *
	 * @link http://codex.wordpress.org/Function_Reference/add_theme_support#Post_Thumbnails
	 */
	//add_theme_support( 'post-thumbnails' );

	// This theme uses wp_nav_menu() in one location.
	register_nav_menus( array(
		'primary' => __( 'Primary Menu', 'reveal-wp' ),
	) );

	/*
	 * Switch default core markup for search form, comment form, and comments
	 * to output valid HTML5.
	 */
	add_theme_support( 'html5', array(
		'search-form', 'comment-form', 'comment-list', 'gallery', 'caption',
	) );

	/*
	 * Enable support for Post Formats.
	 * See http://codex.wordpress.org/Post_Formats
	 */
	add_theme_support( 'post-formats', array(
		'aside', 'image', 'video', 'quote', 'link',
	) );

	// Setup the WordPress core custom background feature.
	add_theme_support( 'custom-background', apply_filters( 'reveal_wp_custom_background_args', array(
		'default-color' => 'ffffff',
		'default-image' => '',
	) ) );
}
endif; // reveal_wp_setup
add_action( 'after_setup_theme', 'reveal_wp_setup' );

/**
 * Register widget area.
 *
 * @link http://codex.wordpress.org/Function_Reference/register_sidebar
 */
function reveal_wp_widgets_init() {
	register_sidebar( array(
		'name'          => __( 'Sidebar', 'reveal-wp' ),
		'id'            => 'sidebar-1',
		'description'   => '',
		'before_widget' => '',
		'after_widget'  => '',
		'before_title'  => '
',
		'after_title'   => '
',
	) );
}
add_action( 'widgets_init', 'reveal_wp_widgets_init' );

/**
 * Enqueue scripts and styles.
 */
function reveal_wp_scripts() {
	wp_enqueue_style( 'reveal-wp-style', get_stylesheet_uri() );

	wp_enqueue_script( 'reveal-wp-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20120206', true );

	wp_enqueue_script( 'reveal-wp-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20130115', true );

	if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
		wp_enqueue_script( 'comment-reply' );
	}
}
add_action( 'wp_enqueue_scripts', 'reveal_wp_scripts' );

/**
 * Implement the Custom Header feature.
 */
//require get_template_directory() . '/inc/custom-header.php';

/**
 * Custom template tags for this theme.
 */
require get_template_directory() . '/inc/template-tags.php';

/**
 * Custom functions that act independently of the theme templates.
 */
require get_template_directory() . '/inc/extras.php';

/**
 * Customizer additions.
 */
require get_template_directory() . '/inc/customizer.php';

/**
 * Load Jetpack compatibility file.
 */
require get_template_directory() . '/inc/jetpack.php';


text:
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.tasks.youtrack.model;

import org.jetbrains.annotations.NotNull;

/**
 * @noinspection unused, FieldCanBeLocal
 */
public class YouTrackWorkItem {
  /** @noinspection FieldMayBeStatic*/
  private final boolean usesMarkdown = true;
  private final String text;
  private final Duration duration;

  public YouTrackWorkItem(@NotNull String text, int durationInMinutes) {
    this.text = text;
    duration = new Duration(durationInMinutes);
  }

  @NotNull
  public String getText() {
    return text;
  }

  @NotNull
  public Duration getDuration() {
    return duration;
  }

  private static class Duration {
    private final int minutes;

    private Duration(int minutes) {
      this.minutes = minutes;
    }

    private int getMinutes() {
      return minutes;
    }
  }
}


text:
import os
import random
from scrapy.conf import settings

class RandomUserAgentMiddleware(object):
    def process_request(self, request, spider):
        ua = random.choice(settings.get('USER_AGENT_LIST'))
        if ua:
            request.headers.setdefault('User-Agent', ua)

class ProxyMiddleware(object):
    def process_request(self, request, spider):
        request.meta['proxy'] = settings.get('HTTP_PROXY')


text:
package term

import (
	"errors"
	"testing"
	"time"

	"github.com/Netflix/chaosmonkey"
	"github.com/Netflix/chaosmonkey/clock"
	"github.com/Netflix/chaosmonkey/config"
	"github.com/Netflix/chaosmonkey/config/param"
	"github.com/Netflix/chaosmonkey/deps"
	"github.com/Netflix/chaosmonkey/mock"
)

func mockDeps() deps.Deps {
	monkeyCfg := config.Defaults()
	monkeyCfg.Set(param.Enabled, true)
	monkeyCfg.Set(param.Leashed, false)
	monkeyCfg.Set(param.Accounts, []string{"prod"})
	recorder := mock.Checker{Error: nil}
	confGetter := mock.ConfigGetter{}
	cl := clock.New()
	dep := mock.Deployment()
	ttor := mock.Terminator{}
	ou := mock.Outage{}
	env := mock.Env{IsInTest: false}
	return deps.Deps{MonkeyCfg: monkeyCfg, Checker: recorder, ConfGetter: confGetter, Cl: cl, Dep: dep, T: &ttor, Ou: ou, Env: env}
}

// TestTerminateKills ensure the terminator actually gets invoked
func TestTerminateKills(t *testing.T) {

	deps := mockDeps()
	err := Terminate(deps, "foo", "prod", "us-east-1", "", "foo-prod")

	if err != nil {
		t.Fatal(err)
	}

	ttor := deps.T.(*mock.Terminator)
	ins := ttor.Instance

	if got, want := ttor.Ncalls, 1; got != want {
		t.Fatalf("Expected terminator to be called once, got ttor.Ncalls=%d", ttor.Ncalls)
	}

	if got, want := ins.AppName(), "foo"; got != want {
		t.Errorf("Expected ins.AppName()=%s. want %s", got, want)
	}

	if got, want := ins.AccountName(), "prod"; got != want {
		t.Errorf("Expected ins.AccountName()=%s. want %s", got, want)
	}

	if got, want := ins.RegionName(), "us-east-1"; got != want {
		t.Errorf("Expected ins.RegionName()=%s. want %s", got, want)
	}

	if got, want := ins.ClusterName(), "foo-prod"; got != want {
		t.Errorf("Expected ins.ClusterName()=%s. want %s", got, want)
	}
}

// TestTerminateOnlyKillsInProd ensures we don't kill in non-prod accounts
// This is temporary until we have full support for multiple accounts
func TestTerminateOnlyKillsInProd(t *testing.T) {
	deps := mockDeps()

	err := Terminate(deps, "quux", "test", "us-east-1", "", "quux-test")

	if err != nil {
		t.Fatal(err)
	}

	ttor := deps.T.(*mock.Terminator)
	if got, want := ttor.Ncalls, 0; got != want {
		t.Errorf("Expected terminator to not be called, got ttor.Ncalls=%d", ttor.Ncalls)
	}

}

func TestTerminateDoesntKillIfRecorderFails(t *testing.T) {
	deps := mockDeps()
	deps.Checker = mock.Checker{Error: chaosmonkey.ErrViolatesMinTime{InstanceID: "i-8703ada6", KilledAt: time.Now().Add(-1 * time.Hour)}}

	err := Terminate(deps, "foo", "prod", "us-east-1", "", "foo-prod")
	if err == nil {
		t.Fatal("Expected Terminate to fail, it succeeded")
	}

	ttor := deps.T.(*mock.Terminator)
	if got, want := ttor.Ncalls, 0; got != want {
		t.Errorf("Expected terminator to not be called, got ttor.Ncalls=%d", ttor.Ncalls)
	}
}

// TestTerminateDoesntKillInLeashedMode ensure terminator does not get invoked
// if leashed is enabled
func TestTerminateDoesntKillInLeashedMode(t *testing.T) {

	deps := mockDeps()
	cfg := config.Defaults()
	// Setting leashed explicitly for code clarity, default is leashed so
	// this isn't strictly neededj
	cfg.Set(param.Leashed, true)

	deps.MonkeyCfg = cfg

	err := Terminate(deps, "foo", "prod", "us-east-1", "", "foo-prod")

	if err != nil {
		t.Fatal(err)
	}

	ttor := deps.T.(*mock.Terminator)
	if got, want := ttor.Ncalls, 0; got != want {
		t.Errorf("Expected terminator to not be called, got ttor.Ncalls=%d", ttor.Ncalls)
	}

}

// TestNeverTerminateInTestEnv checks that unleasshed terms are not allowed in
// test
func TestNeverTerminateUnleashedInTestEnv(t *testing.T) {

	deps := mockDeps()
	deps.Env = mock.Env{IsInTest: true}

	err := Terminate(deps, "foo", "prod", "us-east-1", "", "foo-prod")

	if _, ok := err.(UnleashedInTestEnv); !ok {
		t.Fatalf("Expected Terminate to return an error when running unleashed in test mode")
	}

	ttor := deps.T.(*mock.Terminator)
	if got, want := ttor.Ncalls, 0; got != want {
		t.Errorf("Expected terminator to be called once, got ttor.Ncalls=%d", ttor.Ncalls)
	}

}

func TestDoesNotTerminateIfTrackerFails(t *testing.T) {
	deps := mockDeps()

	// We pass two trackers, the first one succeeds, the second returns an error
	deps.Trackers = []chaosmonkey.Tracker{
		mock.Tracker{},
		mock.Tracker{Error: errors.New("something went wrong")}}

	err := Terminate(deps, "foo", "prod", "us-east-1", "", "foo-prod")
	if err == nil {
		t.Fatal("Tracker failed but Terminate did not return an error")
	}

	ttor := deps.T.(*mock.Terminator)
	if got, want := ttor.Ncalls, 0; got != want {
		t.Errorf("Expected terminator to not be called, got ttor.Ncalls=%d", ttor.Ncalls)
	}

}


text:
module CW
  class Timing

    attr_accessor :delay_time
    attr_accessor :start_time

    def initialize
      @delay_time = 0.0
      @cw_encoding = Encoding.new
    end

    def cw_encoding enc
      @cw_encoding.fetch(enc)
    end

    def dot wpm
      1.2 / wpm.to_f
    end

    def dot_ms
      dot @wpm
    end

    def init_print_words_timeout
      @start_print_time, @delay_print_time = Time.now, 2.0
    end

    def print_words_timeout?
      (Time.now - @start_print_time) > @delay_print_time
    end

    def effective_dot_ms
      dot @effective_wpm
    end

    def init_char_timer
      @start_time, @delay_time = Time.now, 0.0
    end

    def char_delay_timeout?
      (Time.now - @start_time) > @delay_time
    end

    def char_timing(* args)
      timing = 0
      args.flatten.each do |arg|
        case arg
        when :dot  then timing += 2
        when :dash then timing += 4
        else
          puts "Error! invalid morse symbol - was #{arg}"
        end
      end
      timing -= 1
      timing = timing.to_f * dot_ms
      timing + code_space_timing
    end

    def code_space_timing
      @effective_wpm ? 3.0 * effective_dot_ms :
        3.0 * dot_ms
    end

    def space_timing
      space = 4.0
      @effective_wpm ? space * effective_dot_ms :
        space * dot_ms
    end

    def char_delay(char, wpm, ewpm)
      @wpm, @effective_wpm = wpm, ewpm
      if(char != ' ')
        char_timing(cw_encoding(char)) unless(char == ' ')
      else
        space_timing
      end
    end

    def append_char_delay letr, wpm, ewpm
      @delay_time += char_delay(letr, wpm, ewpm)
    end
  end
end


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

/*============================================================
**
  Type:  IntrospectionExtensions
**
==============================================================*/

using global::System;
using global::Internal.Reflection.Augments;

namespace System.Reflection
{
    public static class IntrospectionExtensions
    {
        public static TypeInfo GetTypeInfo(this Type type)
        {
            return ReflectionAugments.ReflectionCoreCallbacks.GetTypeInfo(type);
        }
    }
}


text:
import time

import pytest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

app_url = 'https://pw-dev.djones.co/'

def wait_for_stale(driver, el):
    WebDriverWait(driver, 10).until(EC.staleness_of(el))

@pytest.fixture(scope='module')
def credentials():
    return (f'test-{str(int(time.time()))}', '12345678')

@pytest.fixture(scope='module')
def driver():
    myDriver = webdriver.Remote(
       command_executor='http://127.0.0.1:4444',
       desired_capabilities=DesiredCapabilities.FIREFOX,
    )
    myDriver.fullscreen_window()
    yield myDriver
    myDriver.close()

def test_create_user(driver, credentials):
    driver.get(app_url)
    el = driver.find_element_by_link_text("Sign Up")
    el.click()
    el = driver.find_element_by_name('username')
    el.clear()
    el.send_keys(credentials[0])
    el = driver.find_element_by_name('password')
    el.clear()
    el.send_keys(credentials[1])
    el.submit()
    wait_for_stale(driver, el)
    el = driver.find_element_by_css_selector('.container .alert')
    assert 'has been created' in el.text
    assert credentials[0] in el.text

def test_login(driver, credentials):
    driver.get(app_url)
    el = driver.find_element_by_link_text("Log In")
    el.click()
    el = driver.find_element_by_name('username')
    el.clear()
    el.send_keys(credentials[0])
    el = driver.find_element_by_name('password')
    el.clear()
    el.send_keys(credentials[1])
    el.submit()
    wait_for_stale(driver, el)
    el = driver.find_element_by_css_selector('.container .alert')
    assert 'You are logged in.' in el.text

def test_create_record(driver):
    title = 'test'
    url = 'http://example.com/'
    username = 'test'
    other = 'This is a test.'
    driver.get(app_url)
    driver.find_element_by_name('title').send_keys(title)
    driver.find_element_by_name('url').send_keys(url)
    driver.find_element_by_name('username').send_keys(username)
    el = driver.find_element_by_name('other')
    el.send_keys(other)
    el.submit()
    wait_for_stale(driver, el)
    el = driver.find_elements_by_css_selector('.panel-body .row .col-sm-9')
    assert el[0].text == title
    assert el[1].text == url
    assert el[2].text == username
    assert el[3].text == '••••••••'
    assert len(
        el[3].find_element_by_css_selector('button.cb-copy')
        .get_attribute('data-clipboard-text')
    ) == 16
    assert el[4].text == other

def test_edit_record(driver):
    title = 'test'
    url = 'http://example.com/'
    username = 'test'
    other = 'This is a test.'
    edited = ' edited'
    driver.get(app_url)
    driver.find_element_by_link_text('All Records').click()
    driver.execute_script(
        'return document.querySelector(\'[href^="/edit/"]\')'
    ).click()
    driver.find_element_by_name('title').send_keys(edited)
    driver.find_element_by_name('url').send_keys(Keys.END+edited[1:])
    driver.find_element_by_name('username').send_keys(edited)
    driver.find_element_by_name('password').send_keys(edited)
    el = driver.find_element_by_name('other')
    el.send_keys(edited)
    el.submit()
    wait_for_stale(driver, el)
    el = driver.find_elements_by_css_selector('.panel-body .row .col-sm-9')
    assert el[0].text == title + edited
    assert el[1].text == url + edited[1:]
    assert el[2].text == username + edited
    assert el[3].text == '••••••••'
    assert (
        el[3].find_element_by_css_selector('button.cb-copy')
        .get_attribute('data-clipboard-text')
    )[16:] == edited
    assert el[4].text == other + edited

def test_search(driver):
    driver.get(app_url)
    el = driver.find_element_by_name('q')
    el.send_keys('edited')
    el.submit()
    wait_for_stale(driver, el)
    el = driver.find_element_by_css_selector('.container .alert')
    assert '1' in el.text

def test_save_search(driver):
    driver.get(app_url)
    el = driver.find_element_by_name('q')
    el.send_keys('test')
    el.submit()
    wait_for_stale(driver, el)
    driver.find_element_by_link_text('Saved Searches').click()
    driver.find_element_by_link_text('Save This Search').click()
    el = driver.find_element_by_css_selector('.container .alert')
    assert 'Search term saved.' in el.text
    driver.find_element_by_link_text('Saved Searches').click()
    driver.find_element_by_link_text('test').click()
    el = driver.find_element_by_css_selector('.container .alert')
    assert '1' in el.text

def test_edit_search(driver):
    driver.get(app_url)
    driver.find_element_by_link_text('Saved Searches').click()
    driver.find_element_by_link_text('Edit Searches').click()
    el = driver.find_element_by_name('searches-0-name')
    el.send_keys('mysearch')
    el.submit()
    wait_for_stale(driver, el)
    driver.find_element_by_link_text('Saved Searches').click()
    driver.find_element_by_link_text('mysearch').click()
    el = driver.find_element_by_css_selector('.container .alert')
    assert '1' in el.text

def test_delete_search(driver):
    driver.get(app_url)
    driver.find_element_by_link_text('Saved Searches').click()
    driver.find_element_by_link_text('Edit Searches').click()
    el = driver.find_element_by_name('searches-0-delete')
    el.click()
    el.submit()
    wait_for_stale(driver, el)
    el = driver.find_element_by_link_text('Saved Searches')
    el.click()
    el = el.find_element_by_xpath('..').find_element_by_css_selector('ul')
    assert el.text == ''

def test_change_password(driver, credentials):
    driver.get(app_url)
    el = driver.find_element_by_css_selector('nav .glyphicon-cog')
    el.find_element_by_xpath('..').click()
    driver.find_element_by_link_text('Change Password').click()
    el = driver.find_element_by_name('old_password')
    el.send_keys(credentials[1])
    el = driver.find_element_by_name('new_password')
    el.send_keys(credentials[1])
    el = driver.find_element_by_name('confirm_new_password')
    el.send_keys(credentials[1])
    el.submit()
    wait_for_stale(driver, el)
    el = driver.find_elements_by_css_selector('.container .alert')
    assert 'Your password has been updated' in el[0].text
    assert 'You are not logged in' in el[1].text


text:
using UnityEngine;
using UnityEngine.XR;
using System.Collections.Generic;

namespace VRKeys {

	/// <summary>
	/// Base class for platform-specific inputs and controller access.
	/// </summary>
	public class Controller : MonoBehaviour {
		private Mallet mallet;
		private InputDeviceRole role = InputDeviceRole.Unknown;
		private InputDevice _device = new InputDevice ();

		private void Start () {
			mallet = GetComponent<Mallet> ();

			role = (mallet.hand == Mallet.MalletHand.Left) ? InputDeviceRole.LeftHanded : InputDeviceRole.RightHanded;
		}

		private InputDevice GetDevice () {
			if (_device.isValid) return _device;
			if (role == InputDeviceRole.Unknown) return _device;

			List<InputDevice> devices = new List<InputDevice> ();
			InputDevices.GetDevicesWithRole (role, devices);

			if (devices.Count > 0 && devices[0].isValid) {
				_device = devices[0];
			}

			return _device;
		}

		private bool DeviceIsValid () {
			return GetDevice ().isValid;
		}

		public void TriggerPulse () {
			if (!DeviceIsValid ()) return;

			GetDevice ().SendHapticImpulse (0, 0.3f, 0.05f);
		}

		public bool OnGrip () {
			if (!DeviceIsValid ()) return false;

			bool value;
			GetDevice ().TryGetFeatureValue (CommonUsages.gripButton, out value);
			return value;
		}
	}
}


text:
Comments module for Yii2
========================

This module provide a comments managing system for Yii2 application.

Installation
------------

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

Either run

```
php composer.phar require --prefer-dist yii2mod/yii2-comments "*"
```

or add

```json
"yii2mod/yii2-comments": "*"
```

to the require section of your composer.json.

Usage
======================================

**1. Manage comments in admin panel:**

    1.1 Add the following code to admin module section in main config

  ```php
  'controllerMap' => [
        'comments' => 'yii2mod\comments\controllers\ManageController'
  ]
  ```
    1.2 Run migrations:

  ```php
      php yii migrate --migrationPath=@vendor/yii2mod/yii2-comments/migrations
  ```

**You can then access to management section through the following URL:**
  ```
    http://localhost/path/to/index.php?r=admin/comments/index
  ```

**2. Usage comment widget in view:**

    2.1 Add module to config section:
```php
'modules' => [
    'comment' => [
        'class' => 'yii2mod\comments\Module'
    ]
]
```
```
   2.2 Use in view:
```

```php
<?php echo \yii2mod\comments\widgets\Comment::widget(['model' => $model]); ?>
```

#### Example comments
-----
![Alt text](http://res.cloudinary.com/zfort/image/upload/v1438350103/comments_fooguz.png "Example comments")


text:
package org.apache.maven.model.profile.activation;

import org.apache.maven.model.Activation;
import org.apache.maven.model.ActivationProperty;
import org.apache.maven.model.Profile;
import org.apache.maven.model.building.ModelProblemCollector;
import org.apache.maven.model.building.ModelProblem.Severity;
import org.apache.maven.model.building.ModelProblem.Version;
import org.apache.maven.model.building.ModelProblemCollectorRequest;
import org.apache.maven.model.profile.ProfileActivationContext;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.util.StringUtils;

/**
 * Determines profile activation based on the existence or value of some execution property.
 *
 * @author Benjamin Bentmann
 * @see ActivationProperty
 */
@Component( role = ProfileActivator.class, hint = "property" )
public class PropertyProfileActivator
    implements ProfileActivator
{

    public boolean isActive( Profile profile, ProfileActivationContext context, ModelProblemCollector problems )
    {
        Activation activation = profile.getActivation();

        if ( activation == null )
        {
            return false;
        }

        ActivationProperty property = activation.getProperty();

        if ( property == null )
        {
            return false;
        }

        String name = property.getName();
        boolean reverseName = false;

        if ( name != null && name.startsWith( "!" ) )
        {
            reverseName = true;
            name = name.substring( 1 );
        }

        if ( name == null || name.length() <= 0 )
        {
            problems.add( new ModelProblemCollectorRequest( Severity.ERROR, Version.BASE )
                    .setMessage( "The property name is required to activate the profile " + profile.getId() )
                    .setLocation( property.getLocation( "" ) ) );
            return false;
        }

        String sysValue = context.getUserProperties().get( name );
        if ( sysValue == null )
        {
            sysValue = context.getSystemProperties().get( name );
        }

        String propValue = property.getValue();
        if ( StringUtils.isNotEmpty( propValue ) )
        {
            boolean reverseValue = false;
            if ( propValue.startsWith( "!" ) )
            {
                reverseValue = true;
                propValue = propValue.substring( 1 );
            }

            // we have a value, so it has to match the system value...
            boolean result = propValue.equals( sysValue );

            return reverseValue ? !result : result;
        }
        else
        {
            boolean result = StringUtils.isNotEmpty( sysValue );

            return reverseName ? !result : result;
        }
    }

    @Override
    public boolean presentInConfig( Profile profile, ProfileActivationContext context, ModelProblemCollector problems )
    {
        Activation activation = profile.getActivation();

        if ( activation == null )
        {
            return false;
        }

        ActivationProperty property = activation.getProperty();

        if ( property == null )
        {
            return false;
        }
        return true;
    }

}


text:
@class NSString;

@interface CLSStackFrame : NSObject
{
    NSString *_symbol;
    NSString *_fileName;
    unsigned int _lineNumber;
    unsigned long long _offset;
    unsigned long long _address;
    unsigned int _importance;
}

+ (id)stackFrame;
+ (id)stackFrameWithAddress:(unsigned int)arg1;
@property(nonatomic) unsigned long long address; // @synthesize address=_address;
- (void)dealloc;
- (id)description;
@property(copy, nonatomic) NSString *fileName; // @synthesize fileName=_fileName;
@property(nonatomic) unsigned int importance; // @synthesize importance=_importance;
- (id)init;
@property(nonatomic) unsigned int lineNumber; // @synthesize lineNumber=_lineNumber;
@property(nonatomic) unsigned long long offset; // @synthesize offset=_offset;
@property(copy, nonatomic) NSString *symbol; // @synthesize symbol=_symbol;

@end


text:
package org.finra.datagenerator.common.NodeData

import org.finra.datagenerator.common.Graph.Node
import org.finra.datagenerator.common.GraphEngine.{DefaultNodeGenerator, DataNodeGenerator}
import scala.annotation.unchecked.{uncheckedVariance => uV}
import scala.collection.mutable.ListBuffer

/**
 * Type & metadata for data stored in node of a graph
 */
object NodeDataType {
  /**
   * Each object extending this trait can be thought of as a value in an enumeration of all node data types.
   * @tparam T_NodeData Data that uses this type.
   * @tparam T_NodeDataStub Stub type for the data
   * @tparam T_NodeDataTypes Data types type for this data
   * @tparam T_ThisType This type
   */
  abstract class NodeDataType[+T_NodeData <: NodeData,
                     +T_NodeDataStub <: NodeDataStub[T_ThisType, T_NodeData, T_NodeDataTypes, T_NodeDataStub],
                     +T_NodeDataTypes <: NodeDataTypes[T_NodeData @uV, T_NodeDataStub @uV, T_ThisType @uV, T_NodeDataTypes @uV],
                     +T_ThisType <: NodeDataType[T_NodeData, T_NodeDataStub, T_NodeDataTypes, T_ThisType]] extends DisplayableData {
    /**
     * Specifies what generator to use when trying to create a new child or parent from a specified data node
     */
    lazy val dataNodeGenerator: DataNodeGenerator[T_NodeData, T_NodeData, T_NodeDataStub, T_ThisType, T_NodeDataTypes] =
      new DefaultNodeGenerator[T_NodeData, T_NodeData, T_NodeDataStub, T_ThisType, T_NodeDataTypes]()

    /**
     * Specifies what generator to use when trying to create a new child or parent from a specified stub node
     */
    lazy val dataStubNodeGenerator: DataNodeGenerator[T_NodeDataStub, T_NodeData, T_NodeDataStub, T_ThisType, T_NodeDataTypes] =
      new DefaultNodeGenerator[T_NodeDataStub, T_NodeData, T_NodeDataStub, T_ThisType, T_NodeDataTypes]()

    /**
     * Wrapper that specifies all possible node data types in this domain, and possible metadata/groupings thereof.
     */
    def nodeDataTypes: T_NodeDataTypes

    /**
     * Specifies an object of a class implementing DataTransitions, which define, from each type, how to create a
     * child or parent of each allowable child/parent type.
     */
    lazy val dataTransitions = nodeDataTypes.dataTransitions//.asInstanceOf[DataTransitions[T_NodeData, T_ThisType, T_NodeDataStub]]

    /**
     * Creates a stub wrapper around this type
     * @return Stub wrapper around this type
     */
    def asStub: T_NodeDataStub

    /**
     * Name that uniquely identifies this type
     */
    val name: String = getClass.getSimpleName.replaceAllLiterally("$", "")

    /**
     * Lowercased name
     * @return Lowercased name
     */
    def nameLowercase: String = name.toLowerCase()

    /**
     * Name that uniquely identifies this type, to be used for display
     * @return Default displayable data ID (defaults to name)
     */
    override def defaultDisplayableDataId: String = name

    /**
     * Types are considered the same based on their unique names
     * @param that Value to compare to
     * @return True if equals
     */
    override def equals(that: Any): Boolean = {
      that match {
        case that: this.type => true
        case _ => false
      }
    }
    /**
     * Hash code is simply the name
     * @return Hashcode (name)
     */
    override def hashCode: Int = name.hashCode

    /**
     * Gets a sequence of all the node data types that may be created as a child from the current node
     * @param nodeOfThisType Node from which to get allowable child types
     * @return Sequence of NodeDataType
     */
    def getAllowableChildTypes(nodeOfThisType: Node[T_NodeDataStub @uV]): Seq[T_ThisType]

    /**
     * Gets a sequence of all the node data types that may be created as a parent from the current node
     * @param nodeOfThisType Node from which to get allowable parent types
     * @return Sequence of NodeDataType
     */
    def getAllowableParentTypes(nodeOfThisType: Node[T_NodeDataStub @uV]): Seq[T_ThisType]

    /**
     * Gets a sequence of predicates used by the child-generator methods. These predicate functions determine, for each allowable child type,
     * whether or not, when deciding to add a child, if the generator will choose to add a child of that type.
     * @param node Node from which we may wish to add a child
     * @param maxToGenerate Maximum number of nodes in graph
     * @param probabilityMultiplier Example usage: Predicate function might determine true/false based on a random function.
     *                              Multiplier will make that function more probable to return true.
     * @tparam T_DisplayableData Type of data. In this case it will be either a Data or a Stub.
     * @return Mutable list of each possible child data type mapped to a predicate function used to determine whether or not to add a child of that type
     */
    def childStateTransitionPredicates[T_DisplayableData <: DisplayableData](node: Node[T_DisplayableData @uV]
          , maxToGenerate:Int, probabilityMultiplier: Int): ListBuffer[(T_ThisType @uV, (Node[T_DisplayableData @uV] => Boolean))]

    /**
     * Gets a sequence of predicates used by the parent-generator methods. These predicate functions determine, for each allowable parent type,
     * whether or not, when deciding to add a parent, if the generator will choose to add a parent of that type.
     * @param node Node from which we may wish to add a parent
     * @param maxToGenerate Maximum number of nodes in graph
     * @param probabilityMultiplier Example usage: Predicate function might determine true/false based on a random function.
     *                              Multiplier will make that function more probable to return true.
     * @tparam T_DisplayableData Type of data. In this case it will be either a Data or a Stub.
     * @return Mutable list of each possible parent data type mapped to a predicate function used to determine whether or not to add a parent of that type
     */
    def parentStateTransitionPredicates[T_DisplayableData <: DisplayableData](node: Node[T_DisplayableData @uV], maxToGenerate:Int
          , probabilityMultiplier: Int): ListBuffer[(T_ThisType @uV, (Node[T_DisplayableData @uV] => Boolean))]

    /**
     * Probabilistically link this node to another existing node such that the other node should be a parent of this node.
     * Does nothing by default, but may be overridden. Also not yet called from anywhere, but eventually we may have some generation engine that uses this.
     * @param dataNode Node to be linked as a child of another node that already exists in the same graph
     */
    def probabilisticallyLinkToExistingParentDataNode(dataNode: Node[T_NodeData @uV]): Unit

    /**
     * Probabilistically link this node to another existing node such that the other node should be a parent of this node.
     * Does nothing by default, but may be overridden. Also not yet called from anywhere, but eventually we may have some generation engine that uses this.
     * @param stubNode Node to be linked as a child of another node that already exists in the same graph
     */
    def probabilisticallyLinkToExistingParentStubNode(stubNode: Node[T_NodeDataStub @uV]): Unit

    /**
     * Given a stub node, creates new child stub nodes based on the allowable child types
     * and defined predicates specifying whether or not to add a child of a certain type
     * @param stubNode Node of a data stub
     * @param maxToGenerate Maximum number of nodes in graph
     * @param probabilityMultiplier Example usage: Predicate function might determine true/false based on a random function.
     *                              Multiplier will make that function more probable to return true.
     * @return Vector of all added child nodes
     */
    def generateAndAddChildStubs(stubNode: Node[T_NodeDataStub @uV], maxToGenerate: Int, probabilityMultiplier: Int): Vector[Node[T_NodeDataStub @uV]] = {
      dataStubNodeGenerator.generateLinkedNodes(stubNode, maxToGenerate, childStateTransitionPredicates[T_NodeDataStub @uV](stubNode, maxToGenerate
        , probabilityMultiplier), (nextEventType: T_ThisType) => stubNode.addChild(nextEventType.asStub)
      )
    }

    /**
     * Given a stub node, creates new parent stub nodes based on the allowable child types
     * and defined predicates specifying whether or not to add a parent of a certain type
     * @param stubNode Node of a data stub
     * @param maxToGenerate Maximum number of nodes in graph
     * @param probabilityMultiplier Example usage: Predicate function might determine true/false based on a random function.
     *                              Multiplier will make that function more probable to return true.
     * @return Vector of all added parent nodes
     */
    def generateAndAddParentStubs(stubNode: Node[T_NodeDataStub @uV], maxToGenerate: Int, probabilityMultiplier: Int): Vector[Node[T_NodeDataStub @uV]] = {
      dataStubNodeGenerator.generateLinkedNodes(stubNode, maxToGenerate, parentStateTransitionPredicates[T_NodeDataStub @uV](stubNode, maxToGenerate
        , probabilityMultiplier), (nextEventType: T_ThisType) => stubNode.addParent(nextEventType.asStub)
      )
    }

  /**
   * Given a data node, creates new child data nodes based on the allowable child types and defined predicates
   * specifying whether or not to add a child of a certain type
   * @param dataNode Node of a data stub
   * @param maxToGenerate Maximum number of nodes in graph
   * @param probabilityMultiplier Example usage: Predicate function might determine true/false based on a random function.
   *                              Multiplier will make that function more probable to return true.
   * @return Vector of all added child nodes
   */
    def generateAndAddChildNodes(dataNode: Node[T_NodeData @uV], maxToGenerate: Int, probabilityMultiplier: Int): Vector[Node[T_NodeData @uV]] = {
      dataNodeGenerator.generateLinkedNodes(dataNode, maxToGenerate, childStateTransitionPredicates[T_NodeData @uV](dataNode, maxToGenerate
        , probabilityMultiplier), (nextEventType: T_ThisType) => dataTransitions.addRandomlyGeneratedChildData(dataNode, nextEventType))
    }

    /**
     * Given a data node, creates new parent data nodes based on the allowable child types and defined predicates specifying
     * whether or not to add a parent of a certain type
     * @param dataNode Node of a data stub
     * @param maxToGenerate Maximum number of nodes in graph
     * @param probabilityMultiplier Example usage: Predicate function might determine true/false based on a random function.
     *                              Multiplier will make that function more probable to return true.
     * @return Vector of all added parent nodes
     */
    def generateAndAddParentNodes(dataNode: Node[T_NodeData @uV], maxToGenerate: Int, probabilityMultiplier: Int): Vector[Node[T_NodeData @uV]] = {
      dataNodeGenerator.generateLinkedNodes(dataNode, maxToGenerate, parentStateTransitionPredicates[T_NodeData @uV](dataNode, maxToGenerate
        , probabilityMultiplier), (nextEventType: T_ThisType) => dataTransitions.addRandomlyGeneratedParentData(dataNode, nextEventType))
    }
  }
}


text:
#include <math.matrix.dslib/DynamicMatrix.h>
#include <math.matrix.dslib/specialization/DynamicMatrixSpecialization.h>
#include <math.matrix.dslib/DynamicMatrixOperators.h>

#include <math.matrix.dslib/StaticMatrix.h>
#include <math.matrix.dslib/specialization/StaticMatrixNxNSpecialization.h>
#include <math.matrix.dslib/specialization/StaticMatrix3x3Specialization.h>
#include <math.matrix.dslib/specialization/StaticMatrix3x1Specialization.h>
#include <math.matrix.dslib/StaticMatrixOperators.h>

#include <math.matrix.dslib/Quaternion.h>
#include <math.matrix.dslib/specialization/QuaternionSpecialization.h>
#include <math.matrix.dslib/QuaternionOperators.h>
namespace nspace{
  namespace math{
    namespace dslib{
      typedef matrix2::StaticMatrix<Real,2,1> Vector2D;
      typedef matrix2::StaticMatrix<Real,3,1> Vector3D;
      typedef matrix2::StaticMatrix<Real, 3,3> Matrix3x3;
      typedef matrix2::StaticMatrix<Real, 2,2> Matrix2x2;
      typedef matrix2::StaticMatrix<Real, 4,4> Matrix4x4;
      typedef matrix2::StaticMatrix<Real, 4,3> Matrix4x3;
      typedef matrix2::StaticMatrix<Real, 3,4> Matrix3x4;
      typedef matrix2::Quaternion<Real> Quaternion;
      typedef matrix2::DynamicMatrix<Real> VectorND;
      typedef matrix2::DynamicMatrix<Real> MatrixNxM;
    }
  }
}


text:
import panic from './panic';

const non_exhaustive_pattern='non-exhaustive patterns: `_` not covered';

let select_arm=function(value,pattern){
	return (value in pattern)
			? pattern[value]
		: ('_' in pattern)
			? pattern._
			: panic(non_exhaustive_pattern) ;
};

let match=function(value,patterns){
	let rusted=value.__rusted&&'__data' in value,
		name=rusted?value.__name:value,
		data=rusted?value.__data:value;

	if((!rusted)&&!('_' in patterns)){
		panic(non_exhaustive_pattern);
	}

	let buf=select_arm(name,patterns);

	return typeof buf==='function'
		? buf(data)
		: buf;
};

export default match;


text:
using System;
using System.Threading.Tasks;

using MailKit.Net.Smtp;

using MimeKit;

namespace Cql.Core.Messaging
{
    public class MailKitSmtpClient
    {
        private readonly SmtpConfig _smtpConfig;

        public MailKitSmtpClient(SmtpConfig smtpConfig)
        {
            _smtpConfig = smtpConfig;
        }

        public async Task<string> SendMessage(IMessage message)
        {
            var emailMessage = CreateEmailMessage(message);

            using (var client = new SmtpClient())
            {
                if (_smtpConfig.IgnoreCertificateErrors)
                {
                    client.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
                }

                try
                {
                    await client.ConnectAsync(_smtpConfig.Host, _smtpConfig.Port, _smtpConfig.EnableSsl.GetValueOrDefault()).ConfigureAwait(false);

                    if (!string.IsNullOrEmpty(_smtpConfig.Credentials?.Password))
                    {
                        await client.AuthenticateAsync(_smtpConfig.Credentials).ConfigureAwait(false);
                    }

                    await client.SendAsync(emailMessage).ConfigureAwait(false);
                }
                finally
                {
                    await client.DisconnectAsync(true).ConfigureAwait(false);
                }

                return emailMessage.MessageId;
            }
        }

        private static MimeMessage CreateEmailMessage(IMessage message)
        {
            var emailMessage = new MimeMessage();

            emailMessage.From.Add(message.From.AsMailboxAddress());

            foreach (var messageAddress in message.To)
            {
                emailMessage.To.Add(messageAddress.AsMailboxAddress());
            }

            foreach (var messageAddress in message.Cc)
            {
                emailMessage.Cc.Add(messageAddress.AsMailboxAddress());
            }

            foreach (var messageAddress in message.Bcc)
            {
                emailMessage.Bcc.Add(messageAddress.AsMailboxAddress());
            }

            foreach (var messageAddress in message.ReplyTo)
            {
                emailMessage.ReplyTo.Add(messageAddress.AsMailboxAddress());
            }

            emailMessage.Subject = message.Subject;

            var bodyBuilder = new BodyBuilder();

            if (message.IsBodyHtml.GetValueOrDefault())
            {
                bodyBuilder.HtmlBody = message.Body;
            }
            else
            {
                bodyBuilder.TextBody = message.Body;
            }

            if (message.HasAttachments)
            {

                foreach (var attachment in message.Attachments)
                {
                    var contentType = string.IsNullOrEmpty(attachment.ContentType) ? default(ContentType) : ContentType.Parse(attachment.ContentType);

                    switch (attachment.Type)
                    {
                        case AttachmentType.None:
                            break;

                        case AttachmentType.FilePath:
                            bodyBuilder.Attachments.Add(attachment.AttachmentPath, contentType);
                            break;

                        case AttachmentType.Stream:
                            bodyBuilder.Attachments.Add(attachment.AttachmentName, attachment.ContentStream, contentType);
                            break;

                        default:
                            throw new ArgumentOutOfRangeException();
                    }
                }
            }

            emailMessage.Body = bodyBuilder.ToMessageBody();

            return emailMessage;
        }
    }

    public static class ExtensionsForMailKit
    {
        public static MailboxAddress AsMailboxAddress(this IMessageAddress address)
        {
            return new MailboxAddress(address.DisplayName, address.Address);
        }
    }
}
#endif