text:
package edu.usu.sdl.openstorefront.service;

import edu.usu.sdl.openstorefront.common.exception.OpenStorefrontRuntimeException;
import edu.usu.sdl.openstorefront.common.manager.FileSystemManager;
import edu.usu.sdl.openstorefront.common.util.OpenStorefrontConstant;
import edu.usu.sdl.openstorefront.common.util.ReflectionUtil;
import edu.usu.sdl.openstorefront.common.util.TimeUtil;
import edu.usu.sdl.openstorefront.core.api.AttributeService;
import edu.usu.sdl.openstorefront.core.api.query.GenerateStatementOption;
import edu.usu.sdl.openstorefront.core.api.query.QueryByExample;
import edu.usu.sdl.openstorefront.core.api.query.QueryType;
import edu.usu.sdl.openstorefront.core.api.query.SpecialOperatorModel;
import edu.usu.sdl.openstorefront.core.entity.Article;
import edu.usu.sdl.openstorefront.core.entity.ArticleTracking;
import edu.usu.sdl.openstorefront.core.entity.AttributeCode;
import edu.usu.sdl.openstorefront.core.entity.AttributeCodePk;
import edu.usu.sdl.openstorefront.core.entity.AttributeType;
import edu.usu.sdl.openstorefront.core.entity.AttributeXRefMap;
import edu.usu.sdl.openstorefront.core.entity.AttributeXRefType;
import edu.usu.sdl.openstorefront.core.entity.Component;
import edu.usu.sdl.openstorefront.core.entity.ComponentAttribute;
import edu.usu.sdl.openstorefront.core.entity.ComponentAttributePk;
import edu.usu.sdl.openstorefront.core.entity.LookupEntity;
import edu.usu.sdl.openstorefront.core.model.Architecture;
import edu.usu.sdl.openstorefront.core.model.AttributeXrefModel;
import edu.usu.sdl.openstorefront.core.model.BulkComponentAttributeChange;
import edu.usu.sdl.openstorefront.core.sort.ArchitectureComparator;
import edu.usu.sdl.openstorefront.core.util.EntityUtil;
import edu.usu.sdl.openstorefront.core.view.ArticleTrackingCompleteWrapper;
import edu.usu.sdl.openstorefront.core.view.ArticleTrackingResult;
import edu.usu.sdl.openstorefront.core.view.ArticleView;
import edu.usu.sdl.openstorefront.core.view.AttributeCodeView;
import edu.usu.sdl.openstorefront.core.view.AttributeCodeWrapper;
import edu.usu.sdl.openstorefront.core.view.AttributeTypeWrapper;
import edu.usu.sdl.openstorefront.core.view.AttributeXRefView;
import edu.usu.sdl.openstorefront.core.view.ComponentSearchView;
import edu.usu.sdl.openstorefront.core.view.FilterQueryParams;
import edu.usu.sdl.openstorefront.security.SecurityUtil;
import edu.usu.sdl.openstorefront.service.api.AttributeServicePrivate;
import edu.usu.sdl.openstorefront.service.manager.OSFCacheManager;
import edu.usu.sdl.openstorefront.validation.HTMLSanitizer;
import edu.usu.sdl.openstorefront.validation.ValidationModel;
import edu.usu.sdl.openstorefront.validation.ValidationResult;
import edu.usu.sdl.openstorefront.validation.ValidationUtil;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import net.sf.ehcache.Element;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * Handles Attribute information
 *
 * @author dshurtleff
 */
public class AttributeServiceImpl
		extends ServiceProxy
		implements AttributeService, AttributeServicePrivate
{

	private static final Logger log = Logger.getLogger(AttributeServiceImpl.class.getName());

	@Override
	public List<AttributeType> getRequiredAttributes()
	{
		AttributeType example = new AttributeType();
		example.setActiveStatus(AttributeType.ACTIVE_STATUS);
		example.setRequiredFlg(Boolean.TRUE);
		List<AttributeType> required = persistenceService.queryByExample(AttributeType.class, new QueryByExample(example));
		return required;
	}

	@Override
	public List<AttributeCode> getAllAttributeCodes(String activeStatus)
	{
		List<AttributeCode> attributeCodes;
		Element element = OSFCacheManager.getAttributeCodeAllCache().get(OSFCacheManager.ALLCODE_KEY);
		if (element != null) {
			attributeCodes = (List<AttributeCode>) element.getObjectValue();
		} else {
			attributeCodes = persistenceService.queryByExample(AttributeCode.class, new AttributeCode());
			element = new Element(OSFCacheManager.ALLCODE_KEY, attributeCodes);
			OSFCacheManager.getAttributeCodeAllCache().put(element);
		}
		if (StringUtils.isNotBlank(activeStatus)) {
			attributeCodes = attributeCodes.stream().filter(code -> code.getActiveStatus().equals(activeStatus)).collect(Collectors.toList());
		}
		return attributeCodes;
	}

	@Override
	public List<AttributeCode> findCodesForType(String type)
	{
		return findCodesForType(type, false);
	}

	@Override
	public List<AttributeCode> findCodesForType(String type, boolean all)
	{
		List<AttributeCode> attributeCodes;
		if (all) {
			AttributeCode attributeCodeExample = new AttributeCode();
			AttributeCodePk attributeCodePk = new AttributeCodePk();
			attributeCodePk.setAttributeType(type);
			attributeCodeExample.setAttributeCodePk(attributeCodePk);
			attributeCodes = persistenceService.queryByExample(AttributeCode.class, new QueryByExample(attributeCodeExample));
		} else {
			Element element;
			element = OSFCacheManager.getAttributeCache().get(type);
			if (element != null) {
				attributeCodes = (List<AttributeCode>) element.getObjectValue();
			} else {

				AttributeCode attributeCodeExample = new AttributeCode();
				AttributeCodePk attributeCodePk = new AttributeCodePk();
				attributeCodePk.setAttributeType(type);
				attributeCodeExample.setAttributeCodePk(attributeCodePk);
				attributeCodeExample.setActiveStatus(AttributeCode.ACTIVE_STATUS);

				attributeCodes = persistenceService.queryByExample(AttributeCode.class, new QueryByExample(attributeCodeExample));
				element = new Element(type, attributeCodes);
				OSFCacheManager.getAttributeCache().put(element);
			}
		}
		return attributeCodes;
	}

	@Override
	public void saveAttributeType(AttributeType attributeType)
	{
		saveAttributeType(attributeType, true);
	}

	@Override
	public void saveAttributeType(AttributeType attributeType, boolean updateIndexes)
	{
		getAttributeServicePrivate().performSaveAttributeType(attributeType);

		if (updateIndexes) {
			ComponentAttributePk componentAttributePk = new ComponentAttributePk();
			componentAttributePk.setAttributeType(attributeType.getAttributeType());
			ComponentAttribute componentAttribute = new ComponentAttribute();
			componentAttribute.setComponentAttributePk(componentAttributePk);
			List<ComponentAttribute> componentAttributes = getPersistenceService().queryByExample(ComponentAttribute.class, componentAttribute);

			List<ArticleView> articles = new ArrayList<>();

			AttributeCode attributeCodeExample = new AttributeCode();
			AttributeCodePk codePk = new AttributeCodePk();
			codePk.setAttributeType(attributeType.getAttributeType());
			attributeCodeExample.setAttributeCodePk(codePk);
			List<AttributeCode> attributeCodes = persistenceService.queryByExample(AttributeCode.class, attributeCodeExample);
			for (AttributeCode attributeCode : attributeCodes) {
				if (attributeCode.getArticle() != null) {
					ArticleView article = getArticle(attributeCode.getAttributeCodePk());
					articles.add(article);
				}
			}

			List<Component> components = new ArrayList<>();
			componentAttributes.stream().forEach((attr) -> {
				components.add(persistenceService.findById(Component.class, attr.getComponentAttributePk().getComponentId()));
			});
			getSearchService().indexArticlesAndComponents(articles, components);
		}
	}

	@Override
	public void performSaveAttributeType(AttributeType attributeType)
	{
		AttributeType existing = persistenceService.findById(AttributeType.class, attributeType.getAttributeType());

		ValidationResult validationResult = attributeType.customValidation();
		if (validationResult.valid() == false) {
			throw new OpenStorefrontRuntimeException(validationResult.toString());
		}

		if (existing != null) {
			//remove to inactivate
			existing.updateFields(attributeType);
			persistenceService.persist(existing);
		} else {
			attributeType.populateBaseCreateFields();
			persistenceService.persist(attributeType);
		}
		cleanCaches(attributeType.getAttributeType());
	}

	private void cleanCaches(String attributeType)
	{
		OSFCacheManager.getAttributeCache().remove(attributeType);
		OSFCacheManager.getAttributeTypeCache().remove(attributeType);
		OSFCacheManager.getAttributeCodeAllCache().removeAll();
	}

	@Override
	public void saveAttributeCode(AttributeCode attributeCode)
	{
		saveAttributeCode(attributeCode, true);
	}

	@Override
	public void saveAttributeCode(AttributeCode attributeCode, boolean updateIndexes)
	{
		getAttributeServicePrivate().performSaveAttributeCode(attributeCode);

		if (updateIndexes) {
			ComponentAttributePk pk = new ComponentAttributePk();
			pk.setAttributeType(attributeCode.getAttributeCodePk().getAttributeType());
			pk.setAttributeCode(attributeCode.getAttributeCodePk().getAttributeCode());
			ComponentAttribute example = new ComponentAttribute();
			example.setComponentAttributePk(pk);

			List<ComponentAttribute> componentAttributes = getPersistenceService().queryByExample(ComponentAttribute.class, new QueryByExample(example));

			List<ArticleView> articles = new ArrayList<>();
			if (attributeCode.getArticle() != null) {
				ArticleView article = getArticle(attributeCode.getAttributeCodePk());
				articles.add(article);
			}

			List<Component> components = new ArrayList<>();
			componentAttributes.stream().forEach((attr) -> {
				components.add(persistenceService.findById(Component.class, attr.getComponentAttributePk().getComponentId()));
			});
			getSearchService().indexArticlesAndComponents(articles, components);
		}
	}

	@Override
	public void performSaveAttributeCode(AttributeCode attributeCode)
	{
		AttributeCode existing = persistenceService.findById(AttributeCode.class, attributeCode.getAttributeCodePk());
		if (existing != null) {
			existing.updateFields(attributeCode);
			persistenceService.persist(existing);
		} else {
			attributeCode.populateBaseCreateFields();
			persistenceService.persist(attributeCode);
		}
		cleanCaches(attributeCode.getAttributeCodePk().getAttributeType());
	}

	@Override
	public ArticleView getArticle(AttributeCodePk attributeCodePk)
	{
		ArticleView article = null;

		Objects.requireNonNull(attributeCodePk, "AttributeCodePk is required.");
		Objects.requireNonNull(attributeCodePk.getAttributeType(), "Type is required.");
		Objects.requireNonNull(attributeCodePk.getAttributeCode(), "Code is required.");

		AttributeCode attributeCode = persistenceService.findById(AttributeCode.class, attributeCodePk);
		if (attributeCode != null) {
			if (attributeCode.getArticle() != null) {
				File articleDir = FileSystemManager.getDir(FileSystemManager.ARTICLE_DIR);
				try {
					byte data[] = Files.readAllBytes(Paths.get(articleDir.getPath() + "/" + attributeCode.getArticle().getArticleFilename()));
					article = ArticleView.toViewHtml(attributeCode, new String(data));
				} catch (IOException e) {
					throw new OpenStorefrontRuntimeException("Unable to find article for type: " + attributeCodePk.getAttributeType() + " code: " + attributeCodePk.getAttributeCode(), "Contact system admin to confirm file exists and is not corrupt.", e);
				}
			}
		}
		return article;
	}

	@Override
	public void saveArticle(AttributeCode attributeCode, String articleContents)
	{
		getAttributeServicePrivate().performSaveArticle(attributeCode, articleContents);
		List<ArticleView> articleViews = new ArrayList<>();
		articleViews.add(ArticleView.toViewHtml(attributeCode, articleContents));
		getSearchService().indexArticles(articleViews);
	}

	@Override
	public void saveArticle(ArticleView article)
	{
		getAttributeServicePrivate().performSaveArticle(article);
		List<ArticleView> articleViews = new ArrayList<>();
		articleViews.add(article);
		getSearchService().indexArticles(articleViews);
	}

	@Override
	public void performSaveArticle(ArticleView article)
	{
		AttributeCodePk pk = new AttributeCodePk();
		AttributeCode code = new AttributeCode();
		Article temp = new Article();

		pk.setAttributeCode(article.getAttributeCode());
		pk.setAttributeType(article.getAttributeType());

		temp.setDescription(article.getDescription());
		temp.setTitle(article.getTitle());

		code.setArticle(temp);
		code.setAttributeCodePk(pk);

		performSaveArticle(code, article.getHtml());
	}

	@Override
	public void performSaveArticle(AttributeCode attributeCode, String articleContents)
	{
		Objects.requireNonNull(attributeCode, "AttributeCode is required.");
		Objects.requireNonNull(attributeCode.getArticle(), "Article is required.");
		AttributeCodePk attributeCodePk = attributeCode.getAttributeCodePk();

		Objects.requireNonNull(attributeCodePk, "AttributeCodePk is required.");
		Objects.requireNonNull(attributeCodePk.getAttributeType(), "Type is required.");
		Objects.requireNonNull(attributeCodePk.getAttributeCode(), "Code is required.");

		AttributeCode attributeCodeExisting = persistenceService.findById(AttributeCode.class, attributeCode.getAttributeCodePk());
		if (attributeCodeExisting != null) {
			HTMLSanitizer sanitizer = new HTMLSanitizer();
			articleContents = sanitizer.santize(articleContents).toString();

			//save the article
			String filename = attributeCodeExisting.getAttributeCodePk().toKey() + ".htm";
			File articleDir = FileSystemManager.getDir(FileSystemManager.ARTICLE_DIR);
			try {
				Files.write(Paths.get(articleDir.getPath() + "/" + filename), articleContents.getBytes());

				//save attribute
				if (attributeCodeExisting.getArticle() != null) {
					attributeCodeExisting.getArticle().setArticleFilename(filename);
					attributeCodeExisting.getArticle().updateFields(attributeCode.getArticle());
					persistenceService.saveNonPkEntity(attributeCodeExisting.getArticle());
				} else {
					attributeCodeExisting.setArticle(attributeCode.getArticle());
					attributeCodeExisting.getArticle().setArticleFilename(filename);
					attributeCodeExisting.getArticle().populateBaseCreateFields();
					persistenceService.persist(attributeCodeExisting);
				}
				cleanCaches(attributeCodeExisting.getAttributeCodePk().getAttributeType());

			} catch (IOException e) {
				throw new OpenStorefrontRuntimeException("Unable to save article.", "Contact system admin.  Check permissions on the directory and make sure device has enough space.");
			}
		} else {
			throw new OpenStorefrontRuntimeException("Unable to find attribute for type: " + attributeCodePk.getAttributeType() + " code: " + attributeCodePk.getAttributeCode(), "Add attribute first before posting article");
		}
	}

	@Override
	public void deleteArticle(AttributeCodePk attributeCodePk)
	{
		getAttributeServicePrivate().performDeleteArticle(attributeCodePk);

		// currently articles don't have an 'id' so we're indexing them with
		// a composite ID made from the type and code like so:
		getSearchService().deleteById(attributeCodePk.toKey());
	}

	@Override
	public void performDeleteArticle(AttributeCodePk attributeCodePk)
	{
		AttributeCode attributeCode = persistenceService.findById(AttributeCode.class, attributeCodePk);
		if (attributeCode != null) {
			attributeCode.setDetailUrl(null);
			if (attributeCode.getArticle() != null) {
				File articleDir = FileSystemManager.getDir(FileSystemManager.ARTICLE_DIR);
				File ariticleFile = new File(articleDir.getPath() + "/" + attributeCode.getArticle().getArticleFilename());
				if (ariticleFile.exists()) {
					if (ariticleFile.delete() == false) {
						log.log(Level.WARNING, "Unable to remove file");
					}
				}
				persistenceService.delete(attributeCode.getArticle());
				attributeCode.setArticle(null);
			}
			attributeCode.setUpdateUser(SecurityUtil.getCurrentUserName());
			saveAttributeCode(attributeCode, false);
		}
	}

	@Override
	public void removeAttributeType(String type)
	{
		Objects.requireNonNull(type, "Type is required.");

		AttributeType attributeType = persistenceService.findById(AttributeType.class, type);
		if (attributeType != null) {
			attributeType.setActiveStatus(AttributeCode.INACTIVE_STATUS);
			attributeType.setUpdateDts(TimeUtil.currentDate());
			attributeType.setUpdateUser(SecurityUtil.getCurrentUserName());
			persistenceService.persist(attributeType);

			BulkComponentAttributeChange bulkComponentAttributeChange = new BulkComponentAttributeChange();
			bulkComponentAttributeChange.setAttributes(getComponentAttributes(type, null));
			bulkComponentAttributeChange.setOpertionType(BulkComponentAttributeChange.OpertionType.INACTIVE);

			//Stay in the same transaction
			(new ComponentServiceImpl(persistenceService)).bulkComponentAttributeChange(bulkComponentAttributeChange);

			cleanCaches(type);
		}
	}

	private List<ComponentAttribute> getComponentAttributes(String type, String code)
	{
		ComponentAttribute componentAttributeExample = new ComponentAttribute();
		ComponentAttributePk componentAttributePk = new ComponentAttributePk();
		componentAttributePk.setAttributeType(type);
		componentAttributePk.setAttributeCode(code);
		componentAttributeExample.setComponentAttributePk(componentAttributePk);
		QueryByExample queryByExample = new QueryByExample(componentAttributeExample);
		queryByExample.setReturnNonProxied(false);
		return persistenceService.queryByExample(ComponentAttribute.class, queryByExample);
	}

	@Override
	public void removeAttributeCode(AttributeCodePk attributeCodePk)
	{
		Objects.requireNonNull(attributeCodePk, "AttributeCodePk is required.");

		AttributeCode attributeCode = persistenceService.findById(AttributeCode.class, attributeCodePk);
		if (attributeCode != null) {
			attributeCode.setActiveStatus(AttributeCode.INACTIVE_STATUS);
			attributeCode.setUpdateDts(TimeUtil.currentDate());
			attributeCode.setUpdateUser(SecurityUtil.getCurrentUserName());
			persistenceService.persist(attributeCode);

			BulkComponentAttributeChange bulkComponentAttributeChange = new BulkComponentAttributeChange();
			bulkComponentAttributeChange.setAttributes(getComponentAttributes(attributeCodePk.getAttributeType(), attributeCodePk.getAttributeCode()));
			bulkComponentAttributeChange.setOpertionType(BulkComponentAttributeChange.OpertionType.INACTIVE);
			(new ComponentServiceImpl(persistenceService)).bulkComponentAttributeChange(bulkComponentAttributeChange);

			cleanCaches(attributeCodePk.getAttributeType());
		}
	}

	@Override
	public void cascadeDeleteAttributeType(String type)
	{
		Objects.requireNonNull(type, "Attribute type is required.");

		AttributeType attributeType = persistenceService.findById(AttributeType.class, type);
		if (attributeType != null) {
			AttributeCode attributeCodeExample = new AttributeCode();
			AttributeCodePk attributeCodePk = new AttributeCodePk();
			attributeCodePk.setAttributeType(type);
			attributeCodeExample.setAttributeCodePk(attributeCodePk);
			persistenceService.deleteByExample(attributeCodeExample);

			ArticleTracking articleTrackingExample = new ArticleTracking();
			articleTrackingExample.setAttributeType(type);
			persistenceService.deleteByExample(articleTrackingExample);

			deleteAttributeXrefType(type);

			persistenceService.delete(attributeType);

			BulkComponentAttributeChange bulkComponentAttributeChange = new BulkComponentAttributeChange();
			bulkComponentAttributeChange.setAttributes(getComponentAttributes(type, null));
			bulkComponentAttributeChange.setOpertionType(BulkComponentAttributeChange.OpertionType.DELETE);
			(new ComponentServiceImpl(persistenceService)).bulkComponentAttributeChange(bulkComponentAttributeChange);

			cleanCaches(type);
		}
	}

	@Override
	public void cascadeDeleteAttributeCode(AttributeCodePk attributeCodePk)
	{
		Objects.requireNonNull(attributeCodePk, "AttributeCodePk is required.");

		AttributeCode attributeCode = persistenceService.findById(AttributeCode.class, attributeCodePk);
		if (attributeCode != null) {

			ArticleTracking articleTrackingExample = new ArticleTracking();
			articleTrackingExample.setAttributeType(attributeCodePk.getAttributeType());
			articleTrackingExample.setAttributeCode(attributeCodePk.getAttributeCode());
			persistenceService.deleteByExample(articleTrackingExample);

			AttributeXRefMap example = new AttributeXRefMap();
			example.setAttributeType(attributeCodePk.getAttributeType());
			example.setLocalCode(attributeCodePk.getAttributeCode());
			persistenceService.deleteByExample(example);

			persistenceService.delete(attributeCode);

			BulkComponentAttributeChange bulkComponentAttributeChange = new BulkComponentAttributeChange();
			bulkComponentAttributeChange.setAttributes(getComponentAttributes(attributeCodePk.getAttributeType(), attributeCodePk.getAttributeCode()));
			bulkComponentAttributeChange.setOpertionType(BulkComponentAttributeChange.OpertionType.DELETE);
			(new ComponentServiceImpl(persistenceService)).bulkComponentAttributeChange(bulkComponentAttributeChange);

			cleanCaches(attributeCodePk.getAttributeType());
		}
	}

	@Override
	public void activateAttributeCode(AttributeCodePk attributeCodePk)
	{
		Objects.requireNonNull(attributeCodePk, "AttributeCodePk is required.");

		AttributeCode attributeCode = persistenceService.findById(AttributeCode.class, attributeCodePk);
		if (attributeCode != null) {
			attributeCode.setActiveStatus(AttributeCode.ACTIVE_STATUS);
			attributeCode.setUpdateDts(TimeUtil.currentDate());
			attributeCode.setUpdateUser(SecurityUtil.getCurrentUserName());
			persistenceService.persist(attributeCode);

			BulkComponentAttributeChange bulkComponentAttributeChange = new BulkComponentAttributeChange();
			bulkComponentAttributeChange.setAttributes(getComponentAttributes(attributeCodePk.getAttributeType(), attributeCodePk.getAttributeCode()));
			bulkComponentAttributeChange.setOpertionType(BulkComponentAttributeChange.OpertionType.ACTIVATE);
			(new ComponentServiceImpl(persistenceService)).bulkComponentAttributeChange(bulkComponentAttributeChange);

			cleanCaches(attributeCodePk.getAttributeType());
		}
	}

	@Override
	public void syncAttribute(Map<AttributeType, List<AttributeCode>> attributeMap)
	{
		AttributeType attributeTypeExample = new AttributeType();
		List<AttributeType> attributeTypes = persistenceService.queryByExample(AttributeType.class, new QueryByExample(attributeTypeExample));
		Map<String, AttributeType> existingAttributeMap = new HashMap<>();
		attributeTypes.stream().forEach((attributeType) -> {
			existingAttributeMap.put(attributeType.getAttributeType(), attributeType);
		});

		attributeMap.keySet().stream().forEach(attributeType -> {

			try {

				ValidationModel validationModel = new ValidationModel(attributeType);
				validationModel.setConsumeFieldsOnly(true);
				ValidationResult validationResult = ValidationUtil.validate(validationModel);
				if (validationResult.valid()) {
					attributeType.setAttributeType(attributeType.getAttributeType().replace(ReflectionUtil.COMPOSITE_KEY_SEPERATOR, ReflectionUtil.COMPOSITE_KEY_REPLACER));

					AttributeType existing = existingAttributeMap.get(attributeType.getAttributeType());
					if (existing != null) {
						existing.setDescription(attributeType.getDescription());
						existing.setAllowMultipleFlg(attributeType.getAllowMultipleFlg());
						existing.setArchitectureFlg(attributeType.getArchitectureFlg());
						existing.setImportantFlg(attributeType.getImportantFlg());
						existing.setRequiredFlg(attributeType.getRequiredFlg());
						existing.setVisibleFlg(attributeType.getVisibleFlg());
						existing.setDetailedDescription(attributeType.getDetailedDescription());
						existing.setHideOnSubmission(attributeType.getHideOnSubmission());
						existing.setDefaultAttributeCode(attributeType.getDefaultAttributeCode());
						existing.setActiveStatus(AttributeType.ACTIVE_STATUS);
						existing.setCreateUser(OpenStorefrontConstant.SYSTEM_ADMIN_USER);
						existing.setUpdateUser(OpenStorefrontConstant.SYSTEM_ADMIN_USER);
						saveAttributeType(existing, false);
					} else {
						attributeType.setActiveStatus(AttributeType.ACTIVE_STATUS);
						attributeType.setCreateUser(OpenStorefrontConstant.SYSTEM_ADMIN_USER);
						attributeType.setUpdateUser(OpenStorefrontConstant.SYSTEM_ADMIN_USER);
						saveAttributeType(attributeType, false);
					}

					List<AttributeCode> existingAttributeCodes = findCodesForType(attributeType.getAttributeType());
					Map<String, AttributeCode> existingCodeMap = new HashMap<>();
					for (AttributeCode attributeCode : existingAttributeCodes) {
						existingCodeMap.put(attributeCode.getAttributeCodePk().toKey(), attributeCode);
					}

					Set<String> newCodeSet = new HashSet<>();
					List<AttributeCode> attributeCodes = attributeMap.get(attributeType);
					for (AttributeCode attributeCode : attributeCodes) {
						try {
							ValidationModel validationModelCode = new ValidationModel(attributeCode);
							validationModelCode.setConsumeFieldsOnly(true);
							ValidationResult validationResultCode = ValidationUtil.validate(validationModelCode);
							if (validationResultCode.valid()) {
								attributeCode.getAttributeCodePk().setAttributeCode(attributeCode.getAttributeCodePk().getAttributeCode().replace(ReflectionUtil.COMPOSITE_KEY_SEPERATOR, ReflectionUtil.COMPOSITE_KEY_REPLACER));

								AttributeCode existingCode = existingCodeMap.get(attributeCode.getAttributeCodePk().toKey());
								if (existingCode != null) {
									if (EntityUtil.isObjectsDifferent(existingCode, attributeCode, true)) {
										existingCode.setDescription(attributeCode.getDescription());
										existingCode.setDetailUrl(attributeCode.getDetailUrl());
										existingCode.setLabel(attributeCode.getLabel());
										existingCode.setArchitectureCode(attributeCode.getArchitectureCode());
										existingCode.setBadgeUrl(attributeCode.getBadgeUrl());
										existingCode.setGroupCode(attributeCode.getGroupCode());
										existingCode.setSortOrder(attributeCode.getSortOrder());
										existingCode.setHighlightStyle(attributeCode.getHighlightStyle());
										existingCode.setActiveStatus(AttributeCode.ACTIVE_STATUS);
										existingCode.setCreateUser(OpenStorefrontConstant.SYSTEM_ADMIN_USER);
										existingCode.setUpdateUser(OpenStorefrontConstant.SYSTEM_ADMIN_USER);
										saveAttributeCode(existingCode, false);
									}
								} else {
									attributeCode.setActiveStatus(AttributeCode.ACTIVE_STATUS);
									attributeCode.setCreateUser(OpenStorefrontConstant.SYSTEM_ADMIN_USER);
									attributeCode.setUpdateUser(OpenStorefrontConstant.SYSTEM_ADMIN_USER);
									saveAttributeCode(attributeCode, false);
								}
								newCodeSet.add(attributeCode.getAttributeCodePk().toKey());
							} else {
								log.log(Level.WARNING, MessageFormat.format("(Data Sync) Unable to Add  Attribute Code:  {0} Validation Issues:\n{1}", new Object[]{attributeCode.getAttributeCodePk().toKey(), validationResult.toString()}));
							}
						} catch (Exception e) {
							log.log(Level.SEVERE, "Unable to save attribute code: " + attributeCode.getAttributeCodePk().toKey(), e);
						}
					}
					//inactive missing codes
					existingAttributeCodes.stream().forEach((attributeCode) -> {
						if (newCodeSet.contains(attributeCode.getAttributeCodePk().toKey()) == false) {
							attributeCode.setActiveStatus(LookupEntity.INACTIVE_STATUS);
							attributeCode.setUpdateUser(OpenStorefrontConstant.SYSTEM_ADMIN_USER);
							removeAttributeCode(attributeCode.getAttributeCodePk());
						}
					});
				} else {
					log.log(Level.WARNING, MessageFormat.format("(Data Sync) Unable to Add Type:  {0} Validation Issues:\n{1}", new Object[]{attributeType.getAttributeType(), validationResult.toString()}));
				}
			} catch (Exception e) {
				log.log(Level.SEVERE, "Unable to save attribute type:" + attributeType.getAttributeType(), e);
			}
		});
		//Clear cache
		OSFCacheManager.getAttributeTypeCache().removeAll();
		OSFCacheManager.getAttributeCache().removeAll();
		OSFCacheManager.getAttributeCodeAllCache().removeAll();

		getSearchService().saveAll();
	}

	@Override
	public AttributeCode findCodeForType(AttributeCodePk pk)
	{
		AttributeCode attributeCode = null;
		List<AttributeCode> attributeCodes = findCodesForType(pk.getAttributeType());
		for (AttributeCode attributeCodeCheck : attributeCodes) {
			if (attributeCodeCheck.getAttributeCodePk().getAttributeCode().equals(pk.getAttributeCode())) {
				attributeCode = attributeCodeCheck;
				break;
			}
		}

		return attributeCode;
	}

	@Override
	public AttributeType findType(String type)
	{
		AttributeType attributeType = null;

		Element element = OSFCacheManager.getAttributeTypeCache().get(type);
		if (element != null) {
			attributeType = (AttributeType) element.getObjectValue();
		} else {
			AttributeType attributeTypeExample = new AttributeType();
			attributeTypeExample.setActiveStatus(AttributeType.ACTIVE_STATUS);
			List<AttributeType> attributeTypes = persistenceService.queryByExample(AttributeType.class, new QueryByExample(attributeTypeExample));
			for (AttributeType attributeTypeCheck : attributeTypes) {
				if (attributeTypeCheck.getAttributeType().equals(type)) {
					attributeType = attributeTypeCheck;
				}
				element = new Element(attributeTypeCheck.getAttributeType(), attributeTypeCheck);
				OSFCacheManager.getAttributeTypeCache().put(element);
			}
		}

		return attributeType;
	}

	@Override
	public List<AttributeCode> findRecentlyAddedArticles(Integer maxResults)
	{
		return findRecentlyAddedArticles(maxResults, AttributeCode.ACTIVE_STATUS);
	}

	@Override
	public List<AttributeCode> findRecentlyAddedArticles(Integer maxResults, String activeStatus)
	{
		String query;

		String activeStatusQuery = "";
		if (StringUtils.isNotBlank(activeStatus)) {
			activeStatusQuery = "activeStatus = :activeStatusParam and ";
		}

		if (maxResults != null) {
			query = "select from AttributeCode where  " + activeStatusQuery
					+ " article is not null "
					+ " order by article.createDts DESC LIMIT " + maxResults;
		} else {
			query = "select from AttributeCode where  " + activeStatusQuery
					+ " article is not null "
					+ " order by article.createDts DESC";
		}

		Map<String, Object> parameters = new HashMap<>();
		if (StringUtils.isNotBlank(activeStatus)) {
			parameters.put("activeStatusParam", activeStatus);
		}

		return persistenceService.query(query, parameters);
	}

	@Override
	public Architecture generateArchitecture(String attributeType)
	{
		Architecture architecture = new Architecture();

		AttributeType attributeTypeFull = persistenceService.findById(AttributeType.class, attributeType);
		if (attributeTypeFull != null) {
			if (attributeTypeFull.getArchitectureFlg()) {
				architecture.setName(attributeTypeFull.getDescription());
				architecture.setAttributeType(attributeType);

				String rootCode = "0";
				List<AttributeCode> attributeCodes = findCodesForType(attributeType);
				for (AttributeCode attributeCode : attributeCodes) {
					if (rootCode.equals(attributeCode.adjustedArchitectureCode())) {
						architecture.setAttributeCode(attributeCode.adjustedArchitectureCode());
						architecture.setDescription(attributeCode.getDescription());
					} else {
						String codeTokens[] = attributeCode.adjustedArchitectureCode().split(Pattern.quote("."));
						Architecture rootArchtecture = architecture;
						StringBuilder codeKey = new StringBuilder();
						for (int i = 0; i < codeTokens.length - 1; i++) {
							codeKey.append(codeTokens[i]);

							//put in stubs as needed
							boolean found = false;
							for (Architecture child : rootArchtecture.getChildren()) {
								if (child.getAttributeCode().equals(codeKey.toString())) {
									found = true;
									rootArchtecture = child;
									break;
								}
							}
							if (!found) {
								Architecture newChild = new Architecture();
								newChild.setAttributeCode(codeKey.toString());
								newChild.setAttributeType(attributeType);
								rootArchtecture.getChildren().add(newChild);
								rootArchtecture = newChild;
							}
							codeKey.append(".");
						}
						//now find the correct postion and add/update
						boolean found = false;
						for (Architecture child : rootArchtecture.getChildren()) {
							if (child.getAttributeCode().equals(attributeCode.adjustedArchitectureCode())) {
								child.setName(attributeCode.getLabel());
								child.setDescription(attributeCode.getDescription());
								found = true;
							}
						}
						if (!found) {
							Architecture newChild = new Architecture();
							newChild.setAttributeCode(attributeCode.adjustedArchitectureCode());
							newChild.setOriginalAttributeCode(attributeCode.getAttributeCodePk().getAttributeCode());
							newChild.setArchitectureCode(attributeCode.getArchitectureCode());
							newChild.setSortOrder(attributeCode.getSortOrder());
							newChild.setAttributeType(attributeType);
							newChild.setName(attributeCode.getLabel());
							newChild.setDescription(attributeCode.getDescription());
							rootArchtecture.getChildren().add(newChild);
						}
					}
				}

			} else {
				throw new OpenStorefrontRuntimeException("Attribute Type is not an architecture: " + attributeType, "Make sure type is an architecture.");
			}
		} else {
			throw new OpenStorefrontRuntimeException("Unable to find attribute type: " + attributeType, "Check type code.");
		}
		sortArchitecture(architecture.getChildren());
		return architecture;
	}

	private void sortArchitecture(List<Architecture> architectures)
	{
		if (architectures.isEmpty()) {
			return;
		}

		for (Architecture architecture : architectures) {
			sortArchitecture(architecture.getChildren());
		}
		architectures.sort(new ArchitectureComparator<>());
	}

	@Override
	public void addArticleTrackEvent(ArticleTracking articleTracking)
	{
		articleTracking.setArticleTrackingId(persistenceService.generateId());
		articleTracking.setActiveStatus(ArticleTracking.ACTIVE_STATUS);
		articleTracking.setCreateDts(TimeUtil.currentDate());
		articleTracking.setCreateUser(SecurityUtil.getCurrentUserName());
		articleTracking.setUpdateDts(TimeUtil.currentDate());
		articleTracking.setUpdateUser(SecurityUtil.getCurrentUserName());
		persistenceService.persist(articleTracking);
	}

	@Override
	public List<ComponentSearchView> getArticlesSearchView()
	{
		List<ComponentSearchView> list = new ArrayList<>();
		List<AttributeCode> codes = findRecentlyAddedArticles(null);
		codes.stream().forEach((code) -> {
			list.add(ComponentSearchView.toView(ArticleView.toView(code)));
		});
		return list;
	}

	@Override
	public List<ArticleView> getArticlesForCodeLike(AttributeCodePk attributeCodePk)
	{
		List<ArticleView> articles = new ArrayList<>();
		Objects.requireNonNull(attributeCodePk, "AttributeCodePk is required.");
		Objects.requireNonNull(attributeCodePk.getAttributeType(), "Type is required.");
		Objects.requireNonNull(attributeCodePk.getAttributeCode(), "Code is required.");

		AttributeCode attributeCode = persistenceService.findById(AttributeCode.class, attributeCodePk);
		if (attributeCode == null) {
			AttributeCode attributeCodeExample = new AttributeCode();
			AttributeCodePk attributeCodePkExample = new AttributeCodePk();
			attributeCodePkExample.setAttributeType(attributeCodePk.getAttributeType());
			attributeCodeExample.setAttributeCodePk(attributeCodePkExample);
			attributeCodeExample.setArchitectureCode(attributeCodePk.getAttributeCode());

			attributeCode = persistenceService.queryOneByExample(AttributeCode.class, attributeCodeExample);
		}

		AttributeCode attributeCodeExample = new AttributeCode();
		AttributeCodePk attributeCodePkExample = new AttributeCodePk();
		attributeCodePkExample.setAttributeType(attributeCodePk.getAttributeType());
		attributeCodeExample.setAttributeCodePk(attributeCodePkExample);

		AttributeCode attributeCodeLikeExample = new AttributeCode();
		if (attributeCode != null && StringUtils.isNotBlank(attributeCode.getArchitectureCode())) {
			attributeCodeLikeExample.setArchitectureCode(attributeCode.getArchitectureCode() + "%");
		} else {
			AttributeCodePk attributeCodePkLikeExample = new AttributeCodePk();

			// get attribute codes by using LIKE sql construct 'value%'
			attributeCodePkLikeExample.setAttributeCode(attributeCodePk.getAttributeCode() + "%");
			attributeCodeLikeExample.setAttributeCodePk(attributeCodePkLikeExample);
		}

		QueryByExample queryByExample = new QueryByExample(attributeCodeExample);
		queryByExample.setLikeExample(attributeCodeLikeExample);
		List<AttributeCode> attributeCodes = persistenceService.queryByExample(AttributeCode.class, queryByExample);

		for (AttributeCode code : attributeCodes) {
			if (code.getArticle() != null) {
				articles.add(ArticleView.toView(code));
			}
		}
		return articles;
	}

	@Override
	public List<ArticleView> getArticles()
	{
		List<ArticleView> list = new ArrayList<>();
		List<AttributeCode> codes = findRecentlyAddedArticles(null);
		codes.stream().forEach((code) -> {
			ArticleView article = getArticle(code.getAttributeCodePk());
			list.add(article);
		});
		return list;
	}

	@Override
	public ArticleView getArticleView(AttributeCodePk attributeCodePk)
	{
		ArticleView article = null;

		Objects.requireNonNull(attributeCodePk, "AttributeCodePk is required.");
		Objects.requireNonNull(attributeCodePk.getAttributeType(), "Type is required.");
		Objects.requireNonNull(attributeCodePk.getAttributeCode(), "Code is required.");

		AttributeCode attributeCode = persistenceService.findById(AttributeCode.class, attributeCodePk);
		if (attributeCode.getArticle() != null) {
			article = getArticle(attributeCodePk);
		}
		return article;
	}

	@Override
	public List<AttributeXRefType> getAttributeXrefTypes(AttributeXrefModel attributeXrefModel)
	{
		AttributeXRefType xrefAttributeTypeExample = new AttributeXRefType();
		xrefAttributeTypeExample.setActiveStatus(AttributeXRefType.ACTIVE_STATUS);
		xrefAttributeTypeExample.setIntegrationType(attributeXrefModel.getIntegrationType());
		xrefAttributeTypeExample.setProjectType(attributeXrefModel.getProjectKey());
		xrefAttributeTypeExample.setIssueType(attributeXrefModel.getIssueType());
		List<AttributeXRefType> xrefAttributeTypes = persistenceService.queryByExample(AttributeXRefType.class, xrefAttributeTypeExample);
		return xrefAttributeTypes;
	}

	@Override
	public Map<String, Map<String, String>> getAttributeXrefMapFieldMap()
	{
		Map<String, Map<String, String>> attributeCodeMap = new HashMap<>();

		AttributeXRefMap xrefAttributeMapExample = new AttributeXRefMap();
		xrefAttributeMapExample.setActiveStatus(AttributeXRefMap.ACTIVE_STATUS);

		List<AttributeXRefMap> xrefAttributeMaps = persistenceService.queryByExample(AttributeXRefMap.class, xrefAttributeMapExample);
		for (AttributeXRefMap xrefAttributeMap : xrefAttributeMaps) {

			if (attributeCodeMap.containsKey(xrefAttributeMap.getAttributeType())) {
				Map<String, String> codeMap = attributeCodeMap.get(xrefAttributeMap.getAttributeType());
				if (codeMap.containsKey(xrefAttributeMap.getExternalCode())) {

					//should only have one external code if there's a dup we'll only use one.
					//(however, which  code  is used depends on the order that came in.  which is not  determinate)
					//First one we hit wins
					log.log(Level.WARNING, MessageFormat.format("Duplicate external code for attribute type: {0} Code: {1}", new Object[]{xrefAttributeMap.getAttributeType(), xrefAttributeMap.getExternalCode()}));
				} else {
					codeMap.put(xrefAttributeMap.getExternalCode(), xrefAttributeMap.getLocalCode());
				}
			} else {
				Map<String, String> codeMap = new HashMap<>();
				codeMap.put(xrefAttributeMap.getExternalCode(), xrefAttributeMap.getLocalCode());
				attributeCodeMap.put(xrefAttributeMap.getAttributeType(), codeMap);
			}
		}

		return attributeCodeMap;
	}

	@Override
	public void saveAttributeXrefMap(AttributeXRefView attributeXRefView)
	{
		AttributeXRefType type = persistenceService.findById(AttributeXRefType.class, attributeXRefView.getType().getAttributeType());
		if (type != null) {
			type.setAttributeType(attributeXRefView.getType().getAttributeType());
			type.setActiveStatus(attributeXRefView.getType().getActiveStatus());
			type.setFieldId(attributeXRefView.getType().getFieldId());
			type.setFieldName(attributeXRefView.getType().getFieldName());
			type.setIntegrationType(attributeXRefView.getType().getIntegrationType());
			type.setIssueType(attributeXRefView.getType().getIssueType());
			type.setProjectType(attributeXRefView.getType().getProjectType());
			persistenceService.persist(type);
			AttributeXRefMap mapTemp = new AttributeXRefMap();
			mapTemp.setAttributeType(type.getAttributeType());
			List<AttributeXRefMap> tempMaps = persistenceService.queryByExample(AttributeXRefMap.class, new QueryByExample(mapTemp));
			for (AttributeXRefMap tempMap : tempMaps) {
				mapTemp = persistenceService.findById(AttributeXRefMap.class, tempMap.getXrefId());
				persistenceService.delete(mapTemp);
			}

			for (AttributeXRefMap map : attributeXRefView.getMap()) {
				AttributeXRefMap temp = persistenceService.queryOneByExample(AttributeXRefMap.class, map);
				if (temp != null) {
					temp.setActiveStatus(map.getActiveStatus());
					temp.setAttributeType(map.getAttributeType());
					temp.setExternalCode(map.getExternalCode());
					temp.setLocalCode(map.getLocalCode());
					persistenceService.persist(temp);
				} else {
					map.setActiveStatus(AttributeXRefMap.ACTIVE_STATUS);
					map.setXrefId(persistenceService.generateId());
					persistenceService.persist(map);
				}
			}
		} else {
			attributeXRefView.getType().setActiveStatus(AttributeXRefType.ACTIVE_STATUS);
			persistenceService.persist(attributeXRefView.getType());
			for (AttributeXRefMap map : attributeXRefView.getMap()) {
				map.setActiveStatus(AttributeXRefMap.ACTIVE_STATUS);
				map.setXrefId(persistenceService.generateId());
				persistenceService.persist(map);
			}
		}

	}

	@Override
	public void deleteAttributeXrefType(String attributeType)
	{
		AttributeXRefMap example = new AttributeXRefMap();
		example.setAttributeType(attributeType);
		persistenceService.deleteByExample(example);

		AttributeXRefType attributeXRefType = persistenceService.findById(AttributeXRefType.class, attributeType);
		if (attributeXRefType != null) {
			persistenceService.delete(attributeXRefType);
		}
	}

	@Override
	public void activateAttributeType(String type)
	{
		AttributeType attributeType = persistenceService.findById(AttributeType.class, type);

		if (attributeType != null) {
			attributeType.setActiveStatus(AttributeType.ACTIVE_STATUS);
			attributeType.setUpdateDts(TimeUtil.currentDate());
			attributeType.setUpdateUser(SecurityUtil.getCurrentUserName());
			persistenceService.persist(attributeType);

			BulkComponentAttributeChange bulkComponentAttributeChange = new BulkComponentAttributeChange();
			bulkComponentAttributeChange.setAttributes(getComponentAttributes(type, null));
			bulkComponentAttributeChange.setOpertionType(BulkComponentAttributeChange.OpertionType.ACTIVATE);
			(new ComponentServiceImpl(persistenceService)).bulkComponentAttributeChange(bulkComponentAttributeChange);

			cleanCaches(type);
		} else {
			throw new OpenStorefrontRuntimeException("Unable to save sort order.  Attribute Type: " + type, "Check data");
		}
	}

	@Override
	public void saveAttributeCodeSortOrder(AttributeCodePk attributeCodePk, Integer sortOrder)
	{
		Objects.requireNonNull(attributeCodePk, "Attribute Code PK is required");
		AttributeCode code = persistenceService.findById(AttributeCode.class, attributeCodePk);
		if (code != null) {
			code.setSortOrder(sortOrder);
			persistenceService.persist(code);

			cleanCaches(attributeCodePk.getAttributeType());
		} else {
			throw new OpenStorefrontRuntimeException("Unable to save sort order.  Attribute code: " + attributeCodePk.toString(), "Check data");
		}
	}

	@Override
	public List<AttributeCode> getArticles(Boolean all)
	{
		List<AttributeCode> attributeCodes;
		if (all) {
			attributeCodes = findRecentlyAddedArticles(null, null);
		} else {
			attributeCodes = findRecentlyAddedArticles(null, AttributeCode.ACTIVE_STATUS);
		}
		return attributeCodes;
	}

	@Override
	public ArticleTrackingResult getAttributeTracking(FilterQueryParams filter, AttributeCodePk attributeCodePk)
	{
		ArticleTrackingResult result = new ArticleTrackingResult();

		ArticleTracking articleTrackingExample = new ArticleTracking();
		articleTrackingExample.setActiveStatus(filter.getStatus());
		if (attributeCodePk != null) {
			articleTrackingExample.setAttributeCode(attributeCodePk.getAttributeCode());
			articleTrackingExample.setAttributeType(attributeCodePk.getAttributeType());
		}

		ArticleTracking articleTrackingStartExample = new ArticleTracking();
		articleTrackingStartExample.setEventDts(filter.getStart());

		ArticleTracking articleTrackingEndExample = new ArticleTracking();
		articleTrackingEndExample.setEventDts(filter.getEnd());

		QueryByExample queryByExample = new QueryByExample(articleTrackingExample);

		SpecialOperatorModel specialOperatorModel = new SpecialOperatorModel();
		specialOperatorModel.setExample(articleTrackingStartExample);
		specialOperatorModel.getGenerateStatementOption().setOperation(GenerateStatementOption.OPERATION_GREATER_THAN);
		queryByExample.getExtraWhereCauses().add(specialOperatorModel);

		specialOperatorModel = new SpecialOperatorModel();
		specialOperatorModel.setExample(articleTrackingEndExample);
		specialOperatorModel.getGenerateStatementOption().setOperation(GenerateStatementOption.OPERATION_LESS_THAN_EQUAL);
		specialOperatorModel.getGenerateStatementOption().setParamaterSuffix(GenerateStatementOption.PARAMETER_SUFFIX_END_RANGE);
		queryByExample.getExtraWhereCauses().add(specialOperatorModel);

		queryByExample.setMaxResults(filter.getMax());
		queryByExample.setFirstResult(filter.getOffset());
		queryByExample.setSortDirection(filter.getSortOrder());

		ArticleTracking articleTrackingTrackingOrderExample = new ArticleTracking();
		Field sortField = ReflectionUtil.getField(articleTrackingTrackingOrderExample, filter.getSortField());
		if (sortField != null) {
			try {
				BeanUtils.setProperty(articleTrackingTrackingOrderExample, sortField.getName(), QueryByExample.getFlagForType(sortField.getType()));
			} catch (IllegalAccessException | InvocationTargetException ex) {
				log.log(Level.WARNING, "Unable to set sort field", ex);
			}
			queryByExample.setOrderBy(articleTrackingTrackingOrderExample);
		}

		List<ArticleTracking> articleTrackings = persistenceService.queryByExample(ArticleTracking.class, queryByExample);

		List<AttributeCode> codes = getArticles(Boolean.TRUE);
		Map<AttributeCodePk, Article> codeMap = new HashMap<>();
		codes.stream().forEach((code) -> {
			codeMap.put(code.getAttributeCodePk(), code.getArticle());
		});
		for (ArticleTracking item : articleTrackings) {
			ArticleTrackingCompleteWrapper wrapper = new ArticleTrackingCompleteWrapper();

			AttributeCodePk newPk = new AttributeCodePk();
			newPk.setAttributeCode(item.getAttributeCode());
			newPk.setAttributeType(item.getAttributeType());

			wrapper.setData(item);
			wrapper.setArticle(codeMap.get(newPk));
			result.getResult().add(wrapper);
		}

		if (filter.getSortField().equals(ArticleTrackingCompleteWrapper.FIELD_TITLE)) {
			if (filter.getSortOrder().equals(OpenStorefrontConstant.SORT_DESCENDING)) {
				result.getResult().sort((ArticleTrackingCompleteWrapper p1, ArticleTrackingCompleteWrapper p2) -> p1.getArticle().getTitle().compareToIgnoreCase(p2.getArticle().getTitle()));
			} else {
				result.getResult().sort((ArticleTrackingCompleteWrapper p1, ArticleTrackingCompleteWrapper p2) -> p2.getArticle().getTitle().compareToIgnoreCase(p1.getArticle().getTitle()));
			}
		}
		queryByExample.setQueryType(QueryType.COUNT);
		result.setCount(persistenceService.countByExample(queryByExample));

		return result;
	}

	@Override
	public void importArticles(List<ArticleView> articles)
	{
		articles.forEach(this::saveArticle);
	}

	@Override
	public AttributeTypeWrapper getFilteredTypes(FilterQueryParams filter)
	{
		AttributeTypeWrapper result = new AttributeTypeWrapper();

		AttributeType attributeExample = new AttributeType();
		if (filter.getAll() == null || filter.getAll() == false) {
			attributeExample.setActiveStatus(filter.getStatus());
		}

		QueryByExample queryByExample = new QueryByExample(attributeExample);

		queryByExample.setMaxResults(filter.getMax());
		queryByExample.setFirstResult(filter.getOffset());
		queryByExample.setSortDirection(filter.getSortOrder());

		AttributeType attributeOrderExample = new AttributeType();
		Field sortField = ReflectionUtil.getField(attributeOrderExample, filter.getSortField());
		if (sortField != null) {
			try {
				BeanUtils.setProperty(attributeOrderExample, sortField.getName(), QueryByExample.getFlagForType(sortField.getType()));
			} catch (IllegalAccessException | InvocationTargetException ex) {
				log.log(Level.WARNING, "Unable to set sort field", ex);
			}
			queryByExample.setOrderBy(attributeOrderExample);
		}

		List<AttributeType> attributes = persistenceService.queryByExample(AttributeType.class, queryByExample);

		result.setData(attributes);

		queryByExample.setQueryType(QueryType.COUNT);
		result.setTotalNumber(persistenceService.countByExample(queryByExample));
		return result;
	}

	@Override
	public AttributeCodeWrapper getFilteredCodes(FilterQueryParams filter, String type)
	{
		AttributeCodeWrapper result = new AttributeCodeWrapper();
		AttributeCodePk pk = new AttributeCodePk();
		pk.setAttributeType(type);
		AttributeCode attributeExample = new AttributeCode();
		attributeExample.setAttributeCodePk(pk);
		attributeExample.setActiveStatus(filter.getStatus());

		QueryByExample queryByExample = new QueryByExample(attributeExample);

		queryByExample.setMaxResults(filter.getMax());
		queryByExample.setFirstResult(filter.getOffset());
		queryByExample.setSortDirection(filter.getSortOrder());

		AttributeCode attributeOrderExample = new AttributeCode();
		if (filter.getSortField().equals("code")) {
			AttributeCodePk newPk = new AttributeCodePk();
			newPk.setAttributeCode(QueryByExample.STRING_FLAG);
			attributeOrderExample.setAttributeCodePk(newPk);
			queryByExample.setOrderBy(attributeOrderExample);
		} else {

			Field sortField = ReflectionUtil.getField(attributeOrderExample, filter.getSortField());
			if (sortField != null) {
				try {
					BeanUtils.setProperty(attributeOrderExample, sortField.getName(), QueryByExample.getFlagForType(sortField.getType()));
				} catch (IllegalAccessException | InvocationTargetException ex) {
					log.log(Level.WARNING, "Unable to set sort field", ex);
				}
				queryByExample.setOrderBy(attributeOrderExample);
			}
		}

		List<AttributeCode> attributes = persistenceService.queryByExample(AttributeCode.class, queryByExample);
		List<AttributeCodeView> views = AttributeCodeView.toViews(attributes);

		result.setData(views);

		queryByExample.setQueryType(QueryType.COUNT);
		result.setTotalNumber(persistenceService.countByExample(queryByExample));
		return result;
	}

	@Override
	public void changeAttributeCode(AttributeCodePk attributeCodePk, String newCode)
	{

		ArticleTracking trackingExample = new ArticleTracking();
		trackingExample.setAttributeType(attributeCodePk.getAttributeType());
		trackingExample.setAttributeCode(attributeCodePk.getAttributeCode());

		ArticleTracking trackingUpdateExample = new ArticleTracking();
		trackingUpdateExample.setAttributeCode(newCode);
		persistenceService.updateByExample(ArticleTracking.class, trackingUpdateExample, trackingExample);

		String query = "Update " + ComponentAttributePk.class.getSimpleName() + " set attributeCode = :attributeCodeParamReplace where attributeCode = :oldCodeParam and attributeType = :attributeTypeParam";
		Map<String, Object> parameters = new HashMap<>();
		parameters.put("attributeCodeParamReplace", newCode);
		parameters.put("oldCodeParam", attributeCodePk.getAttributeCode());
		parameters.put("attributeTypeParam", attributeCodePk.getAttributeType());

		persistenceService.runDbCommand(query, parameters);

		query = "Update " + AttributeCodePk.class.getSimpleName() + " set attributeCode = :attributeCodeParamReplace where attributeCode = :oldCodeParam and attributeType = :attributeTypeParam";
		parameters = new HashMap<>();
		parameters.put("attributeCodeParamReplace", newCode);
		parameters.put("oldCodeParam", attributeCodePk.getAttributeCode());
		parameters.put("attributeTypeParam", attributeCodePk.getAttributeType());

		persistenceService.runDbCommand(query, parameters);

		cleanCaches(attributeCodePk.getAttributeType());
	}

}


text:
package version

import "github.com/coreos/go-semver/semver"

var (
	// VersionMajor is for an API incompatible changes.
	VersionMajor int64
	// VersionMinor is for functionality in a backwards-compatible manner.
	VersionMinor int64 = 8
	// VersionPatch is for backwards-compatible bug fixes.
	VersionPatch int64 = 3
	// VersionPre indicates prerelease.
	VersionPre string
	// VersionDev indicates development branch. Releases will be empty string.
	VersionDev string
)

// Version is the specification version that the package types support.
var Version = semver.Version{
	Major:      VersionMajor,
	Minor:      VersionMinor,
	Patch:      VersionPatch,
	PreRelease: semver.PreRelease(VersionPre),
	Metadata:   VersionDev,
}

redpajama_set_name: RedPajamaGithub


text:
"""
Objects used to access Twitter streaming APIs.
"""
from copy import copy
from logging.handlers import TimedRotatingFileHandler
from logging import getLogger, LogRecord
from tweepy.streaming import StreamListener
from tweepy.error import TweepError
from tweepy import Stream, OAuthHandler

import os
import sys

_LOGGER = getLogger(__name__)

class ApiKeys(object):
    """ Helper to get an OAuthHandler for an API key dict. """

    _KEYNAME_API_KEY = 'api_key'
    _KEYNAME_API_SECRET = 'api_secret'
    _KEYNAME_ACCESS_TOKEN = 'access_token'
    _KEYNAME_ACCESS_SECRET = 'access_secret'

    def __init__(self, keys):

        if self._KEYNAME_API_KEY not in keys \
                or self._KEYNAME_API_SECRET not in keys \
                or self._KEYNAME_ACCESS_TOKEN not in keys \
                or self._KEYNAME_ACCESS_SECRET not in keys:
            raise ValueError('Keys dict does not contain api key/secret '
                             'and access token/secret')

        self._api_key = keys[self._KEYNAME_API_KEY]
        self._api_secret = keys[self._KEYNAME_API_SECRET]
        self._access_token = keys[self._KEYNAME_ACCESS_TOKEN]
        self._access_secret = keys[self._KEYNAME_ACCESS_SECRET]
        self._auth = OAuthHandler(self._api_key, self._api_secret)
        self._auth.set_access_token(self._access_token, self._access_secret)

    @property
    def auth(self):
        """ Get OAuthHandler for API. """
        auth = OAuthHandler(self._api_key, self._api_secret)
        auth.set_access_token(self._access_token, self._access_secret)
        return auth

    @property
    def api_key(self):
        """ Get the API key. """
        return copy(self._api_key)

    @property
    def api_secret(self):
        """ Get the API secret. """
        return copy(self._api_secret)

    @property
    def access_token(self):
        """ Get the access token. """
        return copy(self._access_token)

    @property
    def access_secret(self):
        """ Get the access secret. """
        return copy(self._access_secret)

class TimedRotatingStreamListener(StreamListener):
    """
    A Twitter stream listener that writes to compressed, timed rotating file.
    """

    def __init__(self, log_dir, prefix, when_interval=None):
        """
        Init with output path and name prefix.

        Default rollover interval is four hours.

        :param str log_dir: Where to write logged data.
        :param str prefix: Filename prefix for logged data.
        :param tuple when_interval: Listener rollover interval. See
        https://docs.python.org/2.7/library/logging.handlers.html
        #logging.handlers.TimedRotatingFileHandler for more information.
        """

        log_dir = os.path.abspath(log_dir)

        if not os.path.exists(log_dir):
            os.mkdir(log_dir)

        if not isinstance(prefix, str):
            raise ValueError("Prefix string required for output files")

        if when_interval is None:
            when, interval = 'H', 1
        else:
            when, interval = when_interval
            if not (isinstance(when, str) and isinstance(interval, int)):
                raise ValueError("Rollover interval should be like ('h', 1)")

        log_path = os.path.join(log_dir, prefix)

        _LOGGER.info("Saving data to path {}".format(log_path))
        _LOGGER.info("Rollover interval {}"
                     .format("{}{}".format(when, interval)))

        # Create the logger.
        self._logger = TimedRotatingFileHandler(filename=log_path,
                                                encoding='utf-8',
                                                when=when,
                                                interval=interval)

    def on_data(self, data):
        """ Log stream data. """
        # Skip keep-alive newlines.
        data_stripped = data.strip()
        if len(data) > 0:
            record = LogRecord(None, None, None, None, data_stripped, (), None)
            self._logger.emit(record)

    def on_error(self, status):
        """ Print status to stderr and raise exception. """
        sys.stderr.write('{}\n'.format(status))
        raise TweepError(status)

class StreamFilterRunner(object):
    """ Run a stream filter. """

    class _MyStreamFilter(object):
        """ Wrapper used to run and to close a stream. """

        def __init__(self, runner):

            self._listener = TimedRotatingStreamListener(runner.log_dir,
                                                         runner.prefix,
                                                         runner.when_interval)
            self._stream = Stream(runner.auth, self._listener)
            self._track = runner.track
            self._locations = runner.locations

        def run(self):
            """ Run the collector. """
            self._stream.filter(track=self._track, locations=self._locations)

        def close(self):
            """ Close the collector. """
            self._stream.disconnect()
            self._listener.flush()
            self._listener.close()

    def __init__(self, api_keys, track, locations,
                 log_dir, prefix, when_interval=None):
        """
        Run a stream filter.

        :param ApiKeys keys: The keys used for OAuth.
        :param list track: List of phrases to track.
        :param list locations: List of location coordinates to filter.
        :param str log_dir: Directory used to write tweets.
        :param str prefix: File output prefix.
        :param str when: Output file rollover interval.
        """
        self._api_keys = api_keys
        self._track = track
        self._locations = locations
        self._log_dir = log_dir
        self._prefix = prefix
        self._when_interval = when_interval
        self._stream_filter = None

    def __enter__(self):
        if self._stream_filter is None:
            self._stream_filter = self._MyStreamFilter(self)
            self._stream_filter.run()
        else:
            raise ValueError("Cannot start again")

    def __exit__(self, valtype, value, traceback):
        self._stream_filter.close()
        return False  # do not suppress exceptions

    @property
    def auth(self):
        """ Get API auth. """
        return self._api_keys.auth

    @property
    def track(self):
        """ Get filter track. """
        return self._track

    @property
    def locations(self):
        """ Get filter locations. """
        return self._locations

    @property
    def log_dir(self):
        """ Get output directory. """
        return self._log_dir

    @property
    def prefix(self):
        """ Get output prefix. """
        return self._prefix

    @property
    def when_interval(self):
        """ Get output interval. """
        return self._when_interval


text:
COMPILE_FLAGS= -std=c99 -Wall -g
LINK_FLAGS=
LIBS= -lcurl
.PHONY: all clean dir

all: dir build/linux64/libtwc.a

build/linux64/libtwc.a: dir build/twitter.o
	ar rcs $@ build/twitter.o

build/twitter.o: dir twc_codegen code/twitter.c code/twitter.h api.json
	./twc_codegen code/twitter.c api.json
	cc $(COMPILE_FLAGS) -c code/twitter.c -o $@

twc_codegen: build/codegen.o build/json.o
	cc $(LINK_FLAGS) $^ $(LIBS) -o $@

build/codegen.o: dir code/codegen.c code/tokenizer.c code/twitter.h code/json.h
	cc $(COMPILE_FLAGS) -c code/codegen.c -o $@
build/json.o: dir code/json.c code/json.h
	cc $(COMPILE_FLAGS) -c code/json.c -o $@

dir:
	mkdir -p build/linux64

clean:
	rm -r build
	rm -f code/twitter_api.c
	rm -f code/twitter_api.h


text:
layout: post
date: '2016-05-08'
title: "Weddington Way Lela Rose LR178 Quick Delivery Sleeveless Short/Mini Sheath/Column"
category: Weddington Way
tags: [Weddington Way,Sheath/Column,V-neck,Short/Mini,Sleeveless]
---
### Weddington Way Lela Rose LR178 Quick Delivery
Just **$139.99**
###   Sleeveless Short/Mini Sheath/Column

BRANDS	Weddington Way

Silhouette	Sheath/Column

Neckline	V-neck

Hemline/Train	Short/Mini

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/weddington-way/16719-weddington-way-lela-rose-lr178-quick-delivery.html](https://www.readybrides.com/en/weddington-way/16719-weddington-way-lela-rose-lr178-quick-delivery.html)


text:
[![GitHub license](https://img.shields.io/github/license/beto-rodriguez/Live-Charts.svg?style=flat-square)](https://github.com/beto-rodriguez/Live-Charts/blob/master/LICENSE.TXT)
[![AppVeyor](https://ci.appveyor.com/api/projects/status/707m8sye0ggbfrcq)](https://ci.appveyor.com/project/beto-rodriguez/live-charts)
[![GitHub issues](https://img.shields.io/github/issues/beto-rodriguez/Live-Charts.svg?style=flat-square)](https://github.com/beto-rodriguez/Live-Charts/issues)
[![Gitter](https://img.shields.io/gitter/room/beto-rodriguez/Live-Charts.svg?style=flat-square)](https://gitter.im/beto-rodriguez/Live-Charts?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

* **[Get Started Here](http://lvcharts.net/App/examples/wpf/start)**, this repository has many examples also.
* **[Chat](https://gitter.im/beto-rodriguez/Live-Charts)**
* **Questions and support?**, we are always happy to help you at our chat, if you require so you can also try [Stack Overflow](http://stackoverflow.com/questions/tagged/livecharts).

### LiveCharts is
# Flexible, Customizable

*images in this section are built with LiveCharts, but designed by [Kingyo](https://dribbble.com/Kingyo)*

### it is also
# Simple, Interactive

As easy as manipulating any generic list in .Net, LiveCharts updates and animates as your data changes in real time, charts are also sensitive to size changes.

  /

### and of course it also is
# Powerful

LiveCharts is not just beauty charts, this example contains 100,000 points, and the chart is being refreshed constantly, we support zooming, panning, multiple axes, sections, merged UIelemnts and much more!

But that is not all, we try to support as many charts as possible, bars, lines, heat maps, gauges, maps:

### Road Map

- [x] ~~Build at least all the features any other charting library does, in WPF and WinForms~~
- [ ] **[In progress]** Build High performance algorithms
- [ ] **[In progress]** Expand the library to:
 - [x] ~~WPF~~
 - [x] ~~WinForms~~
 - [ ] UWP **[In progress]**
 - [ ] Xamarin
- [ ] Release 1.0 in WPF and WinForms, the other platforms will be beta, in case something went wrong.

###Support

WPF and Winforms, currenlty the library is in the process to become a cross net library...

###Net Version

.Net 4.0 or greater

### Installation

* [Wpf](http://lvcharts.net/App/examples/wpf/Install)
* [WinForms](http://lvcharts.net/App/examples/wf/Install)

### Migrating from older versions?

Please see [https://github.com/beto-rodriguez/Live-Charts/releases](https://github.com/beto-rodriguez/Live-Charts/releases)

### How to Contribute

* **Star** this repo
* Try it
* Report Issues and Improvements
* Pull request are well received

You can also buy me a beer

<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="J86WDLSS9PWGL">
<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_donate_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">

</form>
[![paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=J86WDLSS9PWGL)

### Examples?

The [web site](http://lvcharts.net/App/examples/wpf/start) has a nice set, they are also built in the examples folder up here ^^^^

### Special thanks to

* [JetBrains](https://www.jetbrains.com/), for the resharper license.
* [Contributors](https://github.com/beto-rodriguez/Live-Charts/graphs/contributors) and any one brave enough to report any new issue


text:
{% extends "dbkeeper/base.html" %}

{% block title  %}Master Server Maintenance{% endblock %}
{% block header %}Master Server Maintenance{% endblock %}

{% block main %}
From here you can perform the following operations:

<button>Add Organization</button>

<button>Add User</button>

<button>Add Team</button>

<button>Add Launch Parameters</button>	Enter parameters for the Launch challenge

<button>Add Dock Parameters</button>	Enter parameters for the Dock challenge

<button>Add Secure Parameters</button>	Enter parameters for the Secure challenge

<button>Add Return Parameters</button>	Enter parameters for the Return challenge

<button>Save Settings to CSV</button>	Save the content of the Setting table to a CSV file

<button>Load Settings from CSV</button>	Load the content of the Setting table from a CSV file

<button>Check In Team</button>

<button>Monitor Station Status</button>

<button>dbkeeper Admin Interface</button>

<button style="margin-left:3em">Organization Table Admin Interface</button>

<button style="margin-left:3em">Team Table Admin Interface</button>

<button style="margin-left:3em">Setting Table Admin Interface</button>

<button style="margin-left:3em">User Table Admin Interface</button>

<button>piservice Admin Interface</button>

<button style="margin-left:3em">PiEvent Table Admin Interface</button>

<button style="margin-left:3em">PiStation Table Admin Interface</button>

<button>Start the Competition</button>

<button>End the Competition</button>

<button>Insert a Log Message</button>

{% endblock %}


text:
<?php

use GuzzleHttp\Exception\RequestException;
use Zarinpal\Clients\GuzzleClient;
use Zarinpal\Zarinpal;

trait _Test
{
    private Zarinpal $zarinpal;

    function setZarinpal(): void
    {
        $sandbox = ZarinpalConfig::SANDBOX;
        $merchantID = ZarinpalConfig::MERCHANT_ID;
        $language = ZarinpalConfig::LANGUAGE;
        $zarinGate = ZarinpalConfig::ZARIN_GATE;

        $this->printLn('$sandbox: ' . ($sandbox ? 'true' : 'false'));
        $this->printLn('$merchantID: ' . $merchantID);
        $this->printLn('$merchantID length: ' . strlen($merchantID));
        $this->printLn('$language: ' . $language);
        $this->printLn('$zarinGate: ' . ($zarinGate ? 'true' : 'false'));

        $this->printLn('Creating $client: Zarinpal\Clients\GuzzleClient ...');

        $client = new GuzzleClient($sandbox);

        $this->printLn('$client created');
        $this->printLn('Creating $zarinpal: Zarinpal\Zarinpal ...');

        $zarinpal = new Zarinpal($merchantID, $client, $language, $sandbox, $zarinGate);

        $this->printLn('$zarinpal created');

        $this->zarinpal = $zarinpal;
    }

    function printObject(array $object): void
    {
        $this->printLn(json_encode($object, JSON_PRETTY_PRINT));
    }

    function printResponse(array $response): void
    {
        $code = $response['data']['code'];
        $message = $this->zarinpal->getCodeMessage($code);
        $this->printLn('========= Success =========');
        $this->printLn('$response:');
        $this->printObject($response);
        $this->printLn('$message: ' . $message);
    }

    function printRequestException(RequestException $exception): void
    {
        $this->printLn('========= Error =========');
        $this->printLn('Code: ' . $exception->getCode());
        $this->printLn('Message: ' . $exception->getMessage());
        if ($exception->hasResponse()) {
            $response = $exception->getResponse()->getBody()->getContents();
            $this->printLn('$response:');
            $this->printLn($response);
        }
        $this->printLn('File: ' . $exception->getFile());
        $this->printLn('Line: ' . $exception->getLine());
        $this->printLn('Trace:');
        $this->printLn($exception->getTraceAsString());
    }
}


text:
import { circular_bar, increment, counter } from "ModuleCircularBar.js"
export function circular_foo() {
    if (counter == 0) {
        return circular_bar();
    } else {
        increment();
        return counter;
    }
}
export { circular_bar as rexportbar, reset } from "ModuleCircularBar.js"


text:
from conans.model import Generator
from conans.paths import BUILD_INFO

class DepsCppTXT(object):
    def __init__(self, deps_cpp_info):
        self.include_paths = "\n".join(p.replace("\\", "/")
                                       for p in deps_cpp_info.include_paths)
        self.lib_paths = "\n".join(p.replace("\\", "/")
                                   for p in deps_cpp_info.lib_paths)
        self.res_paths = "\n".join(p.replace("\\", "/")
                                   for p in deps_cpp_info.res_paths)
        self.build_paths = "\n".join(p.replace("\\", "/")
                                     for p in deps_cpp_info.build_paths)
        self.libs = "\n".join(deps_cpp_info.libs)
        self.defines = "\n".join(deps_cpp_info.defines)
        self.cppflags = "\n".join(deps_cpp_info.cppflags)
        self.cflags = "\n".join(deps_cpp_info.cflags)
        self.sharedlinkflags = "\n".join(deps_cpp_info.sharedlinkflags)
        self.exelinkflags = "\n".join(deps_cpp_info.exelinkflags)
        self.bin_paths = "\n".join(p.replace("\\", "/")
                                   for p in deps_cpp_info.bin_paths)
        self.rootpath = "%s" % deps_cpp_info.rootpath.replace("\\", "/")

class TXTGenerator(Generator):
    @property
    def filename(self):
        return BUILD_INFO

    @property
    def content(self):
        template = ('[includedirs{dep}{config}]\n{deps.include_paths}\n\n'
                    '[libdirs{dep}{config}]\n{deps.lib_paths}\n\n'
                    '[bindirs{dep}{config}]\n{deps.bin_paths}\n\n'
                    '[resdirs{dep}{config}]\n{deps.res_paths}\n\n'
                    '[builddirs{dep}{config}]\n{deps.build_paths}\n\n'
                    '[libs{dep}{config}]\n{deps.libs}\n\n'
                    '[defines{dep}{config}]\n{deps.defines}\n\n'
                    '[cppflags{dep}{config}]\n{deps.cppflags}\n\n'
                    '[cflags{dep}{config}]\n{deps.cflags}\n\n'
                    '[sharedlinkflags{dep}{config}]\n{deps.sharedlinkflags}\n\n'
                    '[exelinkflags{dep}{config}]\n{deps.exelinkflags}\n\n')

        sections = []
        deps = DepsCppTXT(self.deps_build_info)
        all_flags = template.format(dep="", deps=deps, config="")
        sections.append(all_flags)

        for config, cpp_info in self.deps_build_info.configs.items():
            deps = DepsCppTXT(cpp_info)
            all_flags = template.format(dep="", deps=deps, config=":" + config)
            sections.append(all_flags)

        template_deps = template + '[rootpath{dep}]\n{deps.rootpath}\n\n'

        for dep_name, dep_cpp_info in self.deps_build_info.dependencies:
            dep = "_" + dep_name
            deps = DepsCppTXT(dep_cpp_info)
            dep_flags = template_deps.format(dep=dep, deps=deps, config="")
            sections.append(dep_flags)

            for config, cpp_info in dep_cpp_info.configs.items():
                deps = DepsCppTXT(cpp_info)
                all_flags = template.format(dep=dep, deps=deps, config=":" + config)
                sections.append(all_flags)

        return "\n".join(sections)


text:
> It's just a chord

A Simple module to get the name of a chord from the intervals names:

```js
var achord = require('achord');
achord(['P1', 'm3', 'd5', 'm7']); // => m7b5
achord(['P1', 'M3', 'P5', 'M7']); // => Maj7
```

This is the reverse module of [d'accord](https://github.com/saebekassebil/daccord)

## License

MIT License


text:
/*
Gamification-server include script, version 0.1, 3 Oct 2014
Source: https://github.com/ngageoint/gamification-server/

Usage: Within a page that includes this file, use JQuery to initialize a call to the gamificaiton server and
 show results within a DIV object on the page. Other options can be set, but the 4 below are required.  Feel
 free to tweak and update this file, it is mostly to be used as a placeholder.

 */

var gamification = {};
gamification.server_url = ""; //This should contain the name of the gamification server
gamification.project_names = ""; //Replace this with the name of the "Project" that is on the gamificaiton server, or a comma-seperated list of projects
gamification.user_name = ""; //This should contain the user that you are requesting information about
gamification.proxy_url = "/proxy/"; //Replace this with your local proxy that the JSON will be requested through

gamification.no_badges_message = "No badges yet";
gamification.badges_to_show_max = 8;
gamification.tag_size_max = 18;
gamification.tag_size_min = 8;
gamification.tag_max_shown = 20;
gamification.$badge_container = null;

gamification.init = function(options){
    gamification.server_url = options.server_url;
    if (options.project_names) gamification.project_names = options.project_names;
    gamification.user_name = options.user_name;
    gamification.$badge_container = options.$badge_container;
    if (typeof gamification.$badge_container == "string") {
        if (gamification.$badge_container.substr(0,1) != "#") {
            gamification.$badge_container = "#"+gamification.$badge_container;
        }
        gamification.$badge_container = $(gamification.$badge_container);
    }

    if (options.proxy_url) gamification.proxy_url = options.proxy_url;

    gamification.loadBadges();
};
gamification.proxify = function(url){
    url = gamification.proxy_url + encodeURI(url);
    return url.replace(/%253D/g,'%3D');
};
gamification.loadBadges = function(){

    if ( gamification.$badge_container && gamification.user_name && gamification.server_url && gamification.project_names) {
        var badgeUrl = gamification.server_url + '/users/' + gamification.user_name + '/projects/' + gamification.project_names + '/badges?format=json';

        var url = gamification.proxify(badgeUrl);
        $.ajax({
            type: 'GET',
            url: url,
            dataType: 'json',
            timeout: 3000,
            success: gamification.badgeDataReturned,
            error: gamification.badgeDataError
        });
    } else {
        gamification.badgeDataError();
    }
};
gamification.badgeDataError = function() {
    if (gamification.$badge_container) {
        gamification.$badge_container.hide();
    }
};
gamification.badgeDataReturned = function (badge_info) {
    if (badge_info && badge_info.profile && badge_info.profile.length ) {

        var points = badge_info.points || 0;
        var badge_text = 'Badges: ';
        if (points) badge_text = 'Points: '+points+', '+badge_text;

        var $tagText = gamification.createTagCloud(badge_info.tags);

        var $title = $('')
            .addClass('muted')
            .css({verticalAlign: 'super'})
            .html(badge_text)
            .appendTo(gamification.$badge_container);
        if ($tagText) {
            $title.popover({
                title: 'Tags',
                html : true,
                content:$tagText,
                trigger:'hover',
                placement:'bottom'
            });
        }

        var allBadges = badge_info.profile;
        allBadges = _.sortBy(allBadges,function(b){return -b.count}); //Reverse count order

        var badgesToShow = _.first(allBadges,gamification.badges_to_show_max); //Only grab the first few badges
        _.each(badgesToShow,function(badge){
            var name = badge.projectbadge__name || "Badge";
            var count = badge.count || 1;
            var description = badge.projectbadge__description || "";
            var icon_url = badge.projectbadge__badge__icon || "";
            var project = badge.projectbadge__project__name || "";
            if (project) {
                description = ""+_.str.titleize(project)+": " + description;
            } else {
                project = gamification.project_names;
            }

            var image_url = encodeURI(icon_url);
            image_url = gamification.proxify(image_url);

            if (image_url) {
                description = " "+description;
            }
            var $span = $('')
                .attr({id:'badge_header_'+ _.str.dasherize(name), title:name})
                .addClass('badge_holder')
                .popover({
                    html:true,
                    title:name + " ("+count+")",
                    content:description,
                    trigger:'hover',
                    placement:'bottom'
                })
                .appendTo(gamification.$badge_container);

            var page_url = gamification.server_url+'/projects/'+project+'/';
            $('')
                .attr({src:image_url})
                .click(function(){
                    window.open(page_url,'_blank');
                })
                .css({cursor:'pointer'})
                .appendTo($span);

            $('')
                .text(count)
                .click(function(){
                    window.open(page_url,'_blank');
                })
                .css({cursor:'pointer'})
                .appendTo($span);
        });

        gamification.$badge_container.show();
    } else {
        gamification.$badge_container.append(gamification.no_badges_message);
    }
};
gamification.createTagCloud=function(tag_array){
    if (tag_array && _.isArray(tag_array)) {
        var tag_smallest = 100000;
        var tag_largest = 0;

        var $holder = $('
')
            .css({width:'200px'});
        $('')
            .text('Tags:')
            .css({fontSize:'14px',fontWeight:'bold'})
            .appendTo($holder);

        //Build the list of tags
        var tags = [];
        for (var field in tag_array) {
            tags.push({name:field, num:tag_array[field]});
        }
        tags = _.sortBy(tags,"num");
        tags = tags.reverse();
        tags = _.first(tags,gamification.tag_max_shown);

        //Find the small/large count of the top n tags
        _.each(tags,function(tag){
            if (tag.num > tag_largest) tag_largest = tag.num;
            if (tag.num < tag_smallest) tag_smallest = tag.num;
        });

        //Add each tag as a sized span
        _.each(tags,function(tag){
            var percent = (tag.num-tag_smallest) / (tag_largest-tag_smallest);
            var size = tag_smallest + ((gamification.tag_size_max-gamification.tag_size_min) * percent);
            size = parseInt(size);

            $('')
                .html(tag.name)
                .css({fontSize:size+'px', border:'1px solid blue', padding:'4px', borderRadius:'4px'})
                .appendTo($holder);
        });
    }
    return $holder;
};


text:
Ansible Role para instalar o servidor [clogd](https://github.com/zanardo/clog).

# Variáveis

- `clogd_version`: versão do clogd a ser instalado.

- `clogd_bind_host`: endereço de escuta do servidor (ex: `0.0.0.0`).

- `clogd_bind_port`: porta de escuta do servidor (ex: `7890`).

- `clogd_pg_host`: endereço do servidor PostgreSQL.

- `clogd_pg_port`: porta do servidor PostgreSQL.

- `clogd_pg_db`: nome do banco de dados no servidor PostgreSQL.

- `clogd_pg_user`: role de login do banco de dados no servidor PostgreSQL.

- `clogd_pg_pass`: senha de login do banco de dados no servidor PostgreSQL.

# Ações

As seguintes mudanças são feitas no sistema:

- São instaladores pacotes para compilação e execução do `clogd` e seus módulos
  necessários (ex: cliente para acesso ao PostgreSQL).

- O clogd é instalado em `/opt/clogd`.

- É criado o usuário `clogd`.

- São criados os diretórios `/etc/opt/clogd` e `/var/opt/log/clogd`.

- É instalado o unit `clogd` do Supervisor.

- As configurações são instaladas em `/etc/opt/clogd/clogd.yml`.

- Os logs são salvos em `/var/opt/log/clogd`.


text:
Graph theory is "the study of nodes (vertices) connected in pairs by edges."<sup>[[1]](https://en.wikipedia.org/wiki/Glossary_of_graph_theory)</sup> Though simple enough to describe, graphs can be a devil to implement. Honey Mushroom builds and traverses these abstract data structures in Ruby.

None of the data structures in this gem are best expressed in Ruby. C programming language, for example, is much better suited to model a queue, using pointers to create a linked list. In fact, using Ruby's array class to model these data-types unnecessarily limits Ruby's array functionality. Furthermore, using Ruby objects to model nodes and edges makes these graphs needlessly space inefficient. These downsides are balanced by Ruby's exceedingly accessible syntax, making the implementation of these graphs easy to understand.

##Data Types Included
* Graph superclass
* Directed Graph (edges have a direction and can only be traversed in said direction)
* Undirected Graph (edges have no direction and be traversed freely)
* Binary Search Tree (a tree is just a special kind of graph)
* Linked List (single and double)
* Queue
* Stack
* Stackqueue

##Algorithms
* Depth-first Search (DFS) [wikipedia](https://en.wikipedia.org/wiki/Depth-first_search)
* Breadth-first Search (BFS) [wikipedia](https://en.wikipedia.org/wiki/Breadth-first_search)

##Examples
See [EXAMPLES.md](/examples.md/) for examples including all of the data types and algorithms listed above. Each data structure and algorithm listed above.

##Coming Soon
* Iterative Deepening Depth First Search
* Dijkstra's Algorithm

##Contributing
I made this project to teach myself abstract data types and I use it to become better at solving real-world problems using graphs. If you wish to contribute to this project:

1. I <3 you.
2. Fork it, clone it, change it and make a pull request with a clear, detailed description of the change or feature.
3. I'll review and merge it.

Bug reports: https://github.com/sp33drac3r/honey_mushroom/issues

##Armillaria Solidipes
This gem gets it's name from the 'Humongous Fungus,' the largest living organism on earth. A single specimen in the Malheur National Forest in Oregon has been growing for over 2,400 years and covers 3.4 square miles. A massive network of long rhizomorphs traverse between sapwood hosts and, in Autumn, bloom honey mushrooms.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.github.commonsrdf.api (Commons RDF: API 0.0.2 API)</title>
<meta name="date" content="2014-08-04">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package com.github.commonsrdf.api

Interface Summary

Interface
Description

BlankNode

An RDF-1.1
 Blank Node, as defined by RDF-1.1 Concepts
 and Abstract Syntax, a W3C Recommendation published on 25 February 2014.

 Note that: Blank nodes are disjoint from IRIs and literals.

BlankNodeOrIRI

This interface represents the RDFTerms that may be used in the
 subject position of an RDF-1.1 Triple, including BlankNode
 and IRI.

Graph

An  RDF 1.1
 Graph, a set of RDF triples, as defined by RDF-1.1 Concepts and Abstract
 Syntax, a W3C Recommendation published on 25 February 2014.

IRI

An RDF-1.1 IRI, as defined by RDF-1.1 Concepts
 and Abstract Syntax, a W3C Recommendation published on 25 February 2014.

Literal

An RDF-1.1 Literal, as defined by RDF-1.1
 Concepts and Abstract Syntax, a W3C Recommendation published on 25
 February 2014

RDFTerm

An RDF-1.1
 Term, as defined by RDF-1.1 Concepts and Abstract Syntax, a W3C Recommendation published on
 25 February 2014.

Triple

An RDF-1.1
 Triple, as defined by RDF-1.1 Concepts and Abstract Syntax, a W3C Recommendation published on
 25 February 2014.

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright © 2014. All rights reserved.


text:
module ImportFile
  extend ActiveSupport::Concern

  # 失敗したインポート処理を一括削除します。
  def self.expire
    self.stucked.find_each do |file|
      file.destroy
    end
  end

  def import_start
    case edit_mode
    when 'create'
      import
    when 'update'
      modify
    when 'destroy'
      remove
    else
      import
    end
  end

  # インポートするファイルの文字コードをUTF-8に変換します。
  # @param [String] line 変換する文字列
  def convert_encoding(line)
    if defined?(CharlockHolmes::EncodingDetector)
      begin
        case user_encoding
        when 'auto_detect'
          encoding = CharlockHolmes::EncodingDetector.detect(line)[:encoding]
        when nil
          encoding = CharlockHolmes::EncodingDetector.detect(line)[:encoding]
        else
          encoding = user_encoding
        end
        line.encode('UTF-8', encoding, universal_newline: true)
      rescue StandardError
        nkf_encode(line)
      end
    else
      nkf_encode(line)
    end
  end

  # インポート完了時のメッセージを送信します。
  def send_message(mailer)
    sender = User.find(1)
    message = Message.create!(
      recipient: user.username,
      sender: sender,
      body: mailer.body.raw_source,
      subject: mailer.subject
    )
  end

  private

  def nkf_encode(line)
    case user_encoding
    when 'auto_detect'
      output_encoding = '-w'
    when 'UTF-8'
      output_encoding = ''
    when 'Shift_JIS'
      output_encoding = '-Sw'
    when 'EUC-JP'
      output_encoding = '-Ew'
    else
      output_encoding = '-w'
    end
    NKF.nkf("#{output_encoding} -Lu", line)
  end

  def create_import_temp_file(attachment)
    tempfile = Tempfile.new(self.class.name.underscore)
    tempfile.write convert_encoding(attachment.download)
    tempfile.close
    tempfile
  end
end


text:
module ngX {

    "use strict";

    /**
     * @name ApiEndpointProvider
     */
    export class ApiEndpointProvider {
        config: any = {
            getBaseUrl: (name?: string) => {
                var baseUrl = "";

                if (name) {
                    this.config.baseUrls.forEach((endpointDefinition: any) => {
                        if (name === endpointDefinition.name) {
                            baseUrl = endpointDefinition.url;
                        }
                    });
                }

                if (!name || baseUrl === "") {
                    this.config.baseUrls.forEach((endpointDefinition: any) => {
                        if (!endpointDefinition.name && baseUrl === "") {
                            baseUrl = endpointDefinition.url;
                        }
                    });
                }
                return baseUrl;
            },
            baseUrls: [],
            configure: function (baseUrl: string, name?: string) {
                var self = this;
                self.baseUrls.push({ url: baseUrl, name: name });
            }
        };

        configure(baseUrl: string, name?: string): void {
            this.config.baseUrls.push({ url: baseUrl, name: name });
        }

        $get(): any {
            return this.config;
        }
    }

    angular.module("ngX").provider("apiEndpoint", ApiEndpointProvider);
}


text:
{-# LANGUAGE DataKinds, ExistentialQuantification, GADTs, PolyKinds, TypeOperators #-}
{-# LANGUAGE TypeInType, TypeFamilies #-}
module T15552 where

import Data.Kind

data Elem :: k -> [k] -> Type

data EntryOfVal (v :: Type) (kvs :: [Type]) where
  EntryOfVal :: forall (v :: Type) (kvs :: [Type]) (k :: Type).
                Elem (k, v) kvs -> EntryOfVal v kvs

type family EntryOfValKey (eov :: EntryOfVal v kvs) :: Type

type family GetEntryOfVal (eov :: EntryOfVal v kvs) :: Elem (EntryOfValKey eov, v) kvs

type family FirstEntryOfVal (v :: Type) (kvs :: [Type]) :: EntryOfVal v kvs where


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="description" content="gf-info simple">
    <meta name="viewport" content="width=device-width, maximum-scale=1, minimum-scale=1, initial-scale=1, user-scalable=no">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="x5-orientation" content="portrait">
    <meta name="full-screen" content="yes">
    <meta name="x5-fullscreen" content="true">
    <title>react-router</title>


text:
DELIMITER /
INSERT INTO CUSTOM_ATTRIBUTE_DOCUMENT (DOCUMENT_TYPE_CODE,CUSTOM_ATTRIBUTE_ID,IS_REQUIRED,ACTIVE_FLAG,UPDATE_USER,UPDATE_TIMESTAMP,OBJ_ID,VER_NBR)
    VALUES ('PERS',(SELECT ID FROM CUSTOM_ATTRIBUTE WHERE NAME = 'billingElement'),'Y','Y','admin',NOW(),UUID(),1)
/
INSERT INTO CUSTOM_ATTRIBUTE_DOCUMENT (DOCUMENT_TYPE_CODE,CUSTOM_ATTRIBUTE_ID,IS_REQUIRED,ACTIVE_FLAG,UPDATE_USER,UPDATE_TIMESTAMP,OBJ_ID,VER_NBR)
    VALUES ('PERS',(SELECT ID FROM CUSTOM_ATTRIBUTE WHERE NAME = 'costSharingBudget'),'N','Y','admin',NOW(),UUID(),1)
/
INSERT INTO CUSTOM_ATTRIBUTE_DOCUMENT (DOCUMENT_TYPE_CODE,CUSTOM_ATTRIBUTE_ID,IS_REQUIRED,ACTIVE_FLAG,UPDATE_USER,UPDATE_TIMESTAMP,OBJ_ID,VER_NBR)
    VALUES ('PERS',(SELECT ID FROM CUSTOM_ATTRIBUTE WHERE NAME = 'numberOfTrainees'),'N','Y','admin',NOW(),UUID(),1)
/
INSERT INTO CUSTOM_ATTRIBUTE_DOCUMENT (DOCUMENT_TYPE_CODE,CUSTOM_ATTRIBUTE_ID,IS_REQUIRED,ACTIVE_FLAG,UPDATE_USER,UPDATE_TIMESTAMP,OBJ_ID,VER_NBR)
    VALUES ('PERS',(SELECT ID FROM CUSTOM_ATTRIBUTE WHERE NAME = 'graduateStudentCount'),'Y','Y','admin',NOW(),UUID(),1)
/
INSERT INTO CUSTOM_ATTRIBUTE_DOCUMENT (DOCUMENT_TYPE_CODE,CUSTOM_ATTRIBUTE_ID,IS_REQUIRED,ACTIVE_FLAG,UPDATE_USER,UPDATE_TIMESTAMP,OBJ_ID,VER_NBR)
    VALUES ('PERS',(SELECT ID FROM CUSTOM_ATTRIBUTE WHERE NAME = 'tenured'),'N','Y','admin',NOW(),UUID(),1)
/
INSERT INTO CUSTOM_ATTRIBUTE_DOCUMENT (DOCUMENT_TYPE_CODE,CUSTOM_ATTRIBUTE_ID,IS_REQUIRED,ACTIVE_FLAG,UPDATE_USER,UPDATE_TIMESTAMP,OBJ_ID,VER_NBR)
    VALUES ('PERS',(SELECT ID FROM CUSTOM_ATTRIBUTE WHERE NAME = 'exportControls'),'N','Y','admin',NOW(),UUID(),1)
/
INSERT INTO CUSTOM_ATTRIBUTE_DOCUMENT (DOCUMENT_TYPE_CODE,CUSTOM_ATTRIBUTE_ID,IS_REQUIRED,ACTIVE_FLAG,UPDATE_USER,UPDATE_TIMESTAMP,OBJ_ID,VER_NBR)
    VALUES ('PERS',(SELECT ID FROM CUSTOM_ATTRIBUTE WHERE NAME = 'inventions'),'N','Y','admin',NOW(),UUID(),1)
/
INSERT INTO CUSTOM_ATTRIBUTE_DOCUMENT (DOCUMENT_TYPE_CODE,CUSTOM_ATTRIBUTE_ID,IS_REQUIRED,ACTIVE_FLAG,UPDATE_USER,UPDATE_TIMESTAMP,OBJ_ID,VER_NBR)
    VALUES ('PERS',(SELECT ID FROM CUSTOM_ATTRIBUTE WHERE NAME = 'localReviewDate'),'N','Y','admin',NOW(),UUID(),1)
/
DELIMITER ;


text:
import {val1, val2} from "./temp/index.js";
import expected from "./src with spaces/module";

it("file url request should be supported", () => {
	expect(val1).toBe(expected);
	expect(val2).toBe(expected);
});