text:
package com.box.l10n.mojito.service.tm.importer;

import static com.box.l10n.mojito.entity.TMTextUnitVariant.Status.APPROVED;
import static com.box.l10n.mojito.utils.Predicates.logIfFalse;

import com.box.l10n.mojito.entity.Asset;
import com.box.l10n.mojito.entity.Locale;
import com.box.l10n.mojito.entity.Repository;
import com.box.l10n.mojito.entity.TMTextUnitCurrentVariant;
import com.box.l10n.mojito.entity.TMTextUnitVariant.Status;
import com.box.l10n.mojito.entity.security.user.User;
import com.box.l10n.mojito.quartz.QuartzPollableTaskScheduler;
import com.box.l10n.mojito.security.AuditorAwareImpl;
import com.box.l10n.mojito.service.NormalizationUtils;
import com.box.l10n.mojito.service.asset.AssetRepository;
import com.box.l10n.mojito.service.asset.ImportTextUnitJob;
import com.box.l10n.mojito.service.asset.ImportTextUnitJobInput;
import com.box.l10n.mojito.service.assetintegritychecker.integritychecker.IntegrityCheckException;
import com.box.l10n.mojito.service.assetintegritychecker.integritychecker.IntegrityCheckerFactory;
import com.box.l10n.mojito.service.assetintegritychecker.integritychecker.TextUnitIntegrityChecker;
import com.box.l10n.mojito.service.locale.LocaleService;
import com.box.l10n.mojito.service.pollableTask.PollableFuture;
import com.box.l10n.mojito.service.pollableTask.PollableFutureTaskResult;
import com.box.l10n.mojito.service.repository.RepositoryRepository;
import com.box.l10n.mojito.service.tm.TMService;
import com.box.l10n.mojito.service.tm.TMTextUnitCurrentVariantRepository;
import com.box.l10n.mojito.service.tm.TextUnitBatchMatcher;
import com.box.l10n.mojito.service.tm.TextUnitForBatchMatcher;
import com.box.l10n.mojito.service.tm.search.TextUnitDTO;
import com.box.l10n.mojito.service.tm.search.TextUnitSearcher;
import com.box.l10n.mojito.service.tm.textunitdtocache.TextUnitDTOsCacheService;
import com.box.l10n.mojito.service.tm.textunitdtocache.UpdateType;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import java.util.AbstractMap.SimpleEntry;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.codec.digest.DigestUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/** @author jaurambault */
@Component
public class TextUnitBatchImporterService {

  /** logger */
  static Logger logger = LoggerFactory.getLogger(TextUnitBatchImporterService.class);

  @Autowired TextUnitSearcher textUnitSearcher;

  @Autowired RepositoryRepository repositoryRepository;

  @Autowired TMService tmService;

  @Autowired TMTextUnitCurrentVariantRepository tmTextUnitCurrentVariantRepository;

  @Autowired AssetRepository assetRepository;

  @Autowired LocaleService localeService;

  @Autowired IntegrityCheckerFactory integrityCheckerFactory;

  @Autowired QuartzPollableTaskScheduler quartzPollableTaskScheduler;

  @Autowired TextUnitBatchMatcher textUnitBatchMatcher;

  @Autowired AuditorAwareImpl auditorAwareImpl;

  @Autowired TextUnitDTOsCacheService textUnitDTOsCacheService;

  /**
   * Imports a batch of text units.
   *
   *
Assumes the text units have the following mandatory attributes: repository name, target
   * locale, asset path, name (or tm textUnit id), target
   *
   *
Optional attribute: name (or tm text unit id), comment, status, includedInFile
   *
   *
If mandatory attributes are missing the text unit will be skipped
   *
   *
Integrity checks are applied and will determine the {@link Status}. Any string that passes
   * the integrity check will be imported as approved. If it doesn't pass the test it will be need
   * translation or the previous status when target is the same and the option is
   * integrityCheckKeepStatusIfFailedAndSameTarget is passed
   *
   * @param textUnitDTOs text units to import
   * @return
   */
  public PollableFuture<Void> asyncImportTextUnits(
      List<TextUnitDTO> textUnitDTOs,
      boolean integrityCheckSkipped,
      boolean integrityCheckKeepStatusIfFailedAndSameTarget) {

    ImportTextUnitJobInput importTextUnitJobInput = new ImportTextUnitJobInput();
    importTextUnitJobInput.setTextUnitDTOs(textUnitDTOs);
    importTextUnitJobInput.setIntegrityCheckSkipped(integrityCheckSkipped);
    importTextUnitJobInput.setIntegrityCheckKeepStatusIfFailedAndSameTarget(
        integrityCheckKeepStatusIfFailedAndSameTarget);

    return quartzPollableTaskScheduler.scheduleJob(ImportTextUnitJob.class, importTextUnitJobInput);
  }

  public PollableFuture<Void> importTextUnits(
      List<TextUnitDTO> textUnitDTOs,
      boolean integrityCheckSkipped,
      boolean integrityCheckKeepStatusIfFailedAndSameTarget) {

    logger.debug("Import {} text units", textUnitDTOs.size());
    List<TextUnitForBatchMatcherImport> textUnitForBatchImports =
        skipInvalidAndConvertToTextUnitForBatchImport(textUnitDTOs);

    logger.debug("Batch by locale and asset to optimize the import");
    Map<Locale, Map<Asset, List<TextUnitForBatchMatcherImport>>> groupedByLocaleAndAsset =
        textUnitForBatchImports.stream()
            .collect(
                Collectors.groupingBy(
                    TextUnitForBatchMatcherImport::getLocale,
                    Collectors.groupingBy(TextUnitForBatchMatcherImport::getAsset)));

    groupedByLocaleAndAsset.forEach(
        (locale, assetMap) -> {
          assetMap.forEach(
              (asset, textUnitsForBatchImport) -> {
                mapTextUnitsToImportWithExistingTextUnits(locale, asset, textUnitsForBatchImport);
                if (!integrityCheckSkipped) {
                  applyIntegrityChecks(
                      asset,
                      textUnitsForBatchImport,
                      integrityCheckKeepStatusIfFailedAndSameTarget);
                }
                importTextUnitsOfLocaleAndAsset(locale, asset, textUnitsForBatchImport);
              });
        });

    return new PollableFutureTaskResult<>();
  }

  /**
   * Maps text units to import with existing text units by first looking up by the tm text unit id
   * then the name of used text unit and finally the name of unused text unit (if there is only one
   * of them for a given name)
   *
   * @param locale
   * @param asset
   * @param textUnitsToImport text units to which the current text units must be added
   */
  void mapTextUnitsToImportWithExistingTextUnits(
      Locale locale, Asset asset, List<TextUnitForBatchMatcherImport> textUnitsToImport) {
    logger.debug(
        "Map the text units to import with current text unit for the given locale and asset");
    List<TextUnitDTO> textUnitTDOsForLocaleAndAsset =
        getTextUnitTDOsForLocaleAndAsset(locale, asset);
    Function<TextUnitForBatchMatcher, Optional<TextUnitDTO>> match =
        textUnitBatchMatcher.match(textUnitTDOsForLocaleAndAsset);
    textUnitsToImport.forEach(tu -> match.apply(tu).ifPresent(m -> tu.setCurrentTextUnit(m)));
  }

  @Transactional
  void importTextUnitsOfLocaleAndAsset(
      Locale locale, Asset asset, List<TextUnitForBatchMatcherImport> textUnitsToImport) {
    DateTime importTime = new DateTime();
    logger.debug(
        "Start import text units for asset: {} and locale: {}",
        asset.getPath(),
        locale.getBcp47Tag());

    textUnitsToImport.stream()
        .filter(
            logIfFalse(
                t -> t.getCurrentTextUnit() != null,
                logger,
                "No current text unit, skip: {}",
                TextUnitForBatchMatcherImport::getName))
        .filter(
            logIfFalse(
                t -> t.getContent() != null,
                logger,
                "Content can't be null, skip: {}",
                TextUnitForBatchMatcherImport::getName))
        .filter(
            logIfFalse(
                this::isUpdateNeeded,
                logger,
                "Update not needed, skip: {}",
                TextUnitForBatchMatcherImport::getName))
        .forEach(
            textUnitForBatchImport -> {
              logger.debug(
                  "Add translation: {} --> {}",
                  textUnitForBatchImport.getName(),
                  textUnitForBatchImport.getContent());

              TextUnitDTO currentTextUnit = textUnitForBatchImport.getCurrentTextUnit();

              TMTextUnitCurrentVariant tmTextUnitCurrentVariant = null;
              if (currentTextUnit.getTmTextUnitCurrentVariantId() != null) {
                logger.debug("Looking up current variant");
                tmTextUnitCurrentVariant =
                    tmTextUnitCurrentVariantRepository.findByLocale_IdAndTmTextUnit_Id(
                        currentTextUnit.getLocaleId(), currentTextUnit.getTmTextUnitId());
              }

              User importedBy = auditorAwareImpl.getCurrentAuditor().orElse(null);
              tmService.addTMTextUnitCurrentVariantWithResult(
                  tmTextUnitCurrentVariant,
                  asset.getRepository().getTm().getId(),
                  asset.getId(),
                  currentTextUnit.getTmTextUnitId(),
                  locale.getId(),
                  textUnitForBatchImport.getContent(),
                  textUnitForBatchImport.getComment(),
                  textUnitForBatchImport.getStatus(),
                  textUnitForBatchImport.isIncludedInLocalizedFile(),
                  importTime,
                  importedBy);
            });
  }

  boolean isUpdateNeeded(TextUnitForBatchMatcherImport textUnitForBatchImport) {

    TextUnitDTO currentTextUnit = textUnitForBatchImport.getCurrentTextUnit();

    return currentTextUnit.getTarget() == null
        || tmService.isUpdateNeededForTmTextUnitVariant(
            currentTextUnit.getStatus(),
            DigestUtils.md5Hex(currentTextUnit.getTarget()),
            currentTextUnit.isIncludedInLocalizedFile(),
            currentTextUnit.getComment(),
            textUnitForBatchImport.getStatus(),
            DigestUtils.md5Hex(textUnitForBatchImport.getContent()),
            textUnitForBatchImport.isIncludedInLocalizedFile(),
            textUnitForBatchImport.getComment());
  }

  List<TextUnitDTO> getTextUnitTDOsForLocaleAndAsset(Locale locale, Asset asset) {
    return textUnitDTOsCacheService.getTextUnitDTOsForAssetAndLocale(
        asset.getId(), locale.getId(), false, UpdateType.ALWAYS);
  }

  void applyIntegrityChecks(
      Asset asset,
      List<TextUnitForBatchMatcherImport> textUnitsForBatchImport,
      boolean keepStatusIfCheckFailedAndSameTarget) {

    Set<TextUnitIntegrityChecker> textUnitCheckers =
        integrityCheckerFactory.getTextUnitCheckers(asset);

    for (TextUnitForBatchMatcherImport textUnitForBatchImport : textUnitsForBatchImport) {

      TextUnitDTO currentTextUnit = textUnitForBatchImport.getCurrentTextUnit();

      if (currentTextUnit == null) {
        continue;
      }

      textUnitForBatchImport.setIncludedInLocalizedFile(true);
      textUnitForBatchImport.setStatus(APPROVED);

      for (TextUnitIntegrityChecker textUnitChecker : textUnitCheckers) {
        try {
          textUnitChecker.check(currentTextUnit.getSource(), textUnitForBatchImport.getContent());
        } catch (IntegrityCheckException ice) {

          boolean hasSameTarget =
              textUnitForBatchImport.getContent().equals(currentTextUnit.getTarget());

          if (hasSameTarget && keepStatusIfCheckFailedAndSameTarget) {
            textUnitForBatchImport.setIncludedInLocalizedFile(
                currentTextUnit.isIncludedInLocalizedFile());
            textUnitForBatchImport.setStatus(currentTextUnit.getStatus());
          } else {
            logger.info(
                "Integrity check failed for string with source {}, content {}: {}",
                currentTextUnit.getSource(),
                textUnitForBatchImport.getContent(),
                ice);
            textUnitForBatchImport.setIncludedInLocalizedFile(false);
            textUnitForBatchImport.setStatus(Status.TRANSLATION_NEEDED);
          }

          break;
        }
      }
    }
  }

  List<TextUnitForBatchMatcherImport> skipInvalidAndConvertToTextUnitForBatchImport(
      List<TextUnitDTO> textUnitDTOs) {

    logger.debug("Create caches to map convert to TextUnitForBatchMatcherImport list");
    LoadingCache<String, Repository> repositoriesCache =
        CacheBuilder.newBuilder()
            .build(CacheLoader.from((name) -> repositoryRepository.findByName(name)));

    LoadingCache<Map.Entry<String, Long>, Asset> assetsCache =
        CacheBuilder.newBuilder()
            .build(
                CacheLoader.from(
                    (entry) ->
                        assetRepository.findByPathAndRepositoryId(
                            entry.getKey(), entry.getValue())));

    logger.debug("Start converting to TextUnitForBatchMatcherImport");
    return textUnitDTOs.stream()
        .filter(
            logIfFalse(
                t -> t.getRepositoryName() != null,
                logger,
                "Missing mandatory repository name, skip: {}",
                TextUnitDTO::getName))
        .filter(
            logIfFalse(
                t -> t.getAssetPath() != null,
                logger,
                "Missing mandatory asset path, skip: {}",
                TextUnitDTO::getName))
        .filter(
            logIfFalse(
                t -> t.getTargetLocale() != null,
                logger,
                "Missing mandatory target locale, skip: {}",
                TextUnitDTO::getName))
        .filter(
            logIfFalse(
                t -> !(t.getName() == null && t.getTmTextUnitId() == null),
                logger,
                "Missing mandatory name or tmTextUnitId, skip: {}",
                TextUnitDTO::getName))
        .filter(
            logIfFalse(
                t -> t.getTarget() != null,
                logger,
                "Missing mandatory target, skip: {}",
                TextUnitDTO::getName))
        .map(
            t -> {
              TextUnitForBatchMatcherImport textUnitForBatchImport =
                  new TextUnitForBatchMatcherImport();
              textUnitForBatchImport.setTmTextUnitId(t.getTmTextUnitId());

              textUnitForBatchImport.setRepository(
                  repositoriesCache.getUnchecked(t.getRepositoryName()));
              if (textUnitForBatchImport.getRepository() != null) {
                textUnitForBatchImport.setAsset(
                    assetsCache.getUnchecked(
                        new SimpleEntry<>(
                            t.getAssetPath(), textUnitForBatchImport.getRepository().getId())));
              }
              textUnitForBatchImport.setName(t.getName());

              textUnitForBatchImport.setLocale(localeService.findByBcp47Tag(t.getTargetLocale()));
              textUnitForBatchImport.setContent(NormalizationUtils.normalize(t.getTarget()));
              textUnitForBatchImport.setComment(t.getComment());
              textUnitForBatchImport.setIncludedInLocalizedFile(t.isIncludedInLocalizedFile());
              textUnitForBatchImport.setStatus(t.getStatus() == null ? APPROVED : t.getStatus());

              return textUnitForBatchImport;
            })
        .filter(
            logIfFalse(
                t -> t.getRepository() != null,
                logger,
                "No repository found, skip: {}",
                TextUnitForBatchMatcherImport::getName))
        .filter(
            logIfFalse(
                t -> t.getAsset() != null,
                logger,
                "No asset found, skip: {}",
                TextUnitForBatchMatcherImport::getName))
        .filter(
            logIfFalse(
                t -> t.getLocale() != null,
                logger,
                "No locale found, skip: {}",
                TextUnitForBatchMatcherImport::getName))
        .collect(Collectors.toList());
  }
}


text:
package io.cattle.platform.lb.instance.process;

import static io.cattle.platform.core.model.tables.PortTable.PORT;
import io.cattle.platform.archaius.util.ArchaiusUtil;
import io.cattle.platform.configitem.request.ConfigUpdateRequest;
import io.cattle.platform.configitem.request.util.ConfigUpdateRequestUtils;
import io.cattle.platform.configitem.version.ConfigItemStatusManager;
import io.cattle.platform.core.constants.CommonStatesConstants;
import io.cattle.platform.core.constants.InstanceConstants;
import io.cattle.platform.core.constants.PortConstants;
import io.cattle.platform.core.dao.GenericResourceDao;
import io.cattle.platform.core.dao.IpAddressDao;
import io.cattle.platform.core.dao.LoadBalancerDao;
import io.cattle.platform.core.dao.LoadBalancerTargetDao;
import io.cattle.platform.core.dao.NetworkDao;
import io.cattle.platform.core.model.Agent;
import io.cattle.platform.core.model.Instance;
import io.cattle.platform.core.model.IpAddress;
import io.cattle.platform.core.model.LoadBalancer;
import io.cattle.platform.core.model.LoadBalancerListener;
import io.cattle.platform.core.model.Nic;
import io.cattle.platform.core.model.Port;
import io.cattle.platform.engine.handler.HandlerResult;
import io.cattle.platform.engine.handler.ProcessPostListener;
import io.cattle.platform.engine.process.ProcessInstance;
import io.cattle.platform.engine.process.ProcessState;
import io.cattle.platform.json.JsonMapper;
import io.cattle.platform.lb.instance.process.lock.LoadBalancerInstancePortLock;
import io.cattle.platform.lb.instance.service.LoadBalancerInstanceManager;
import io.cattle.platform.lb.instance.service.impl.LoadBalancerLookup;
import io.cattle.platform.lock.LockCallbackNoReturn;
import io.cattle.platform.lock.LockManager;
import io.cattle.platform.object.resource.ResourceMonitor;
import io.cattle.platform.object.resource.ResourcePredicate;
import io.cattle.platform.object.util.DataUtils;
import io.cattle.platform.process.common.handler.AbstractObjectProcessLogic;
import io.cattle.platform.util.type.Priority;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.inject.Inject;
import javax.inject.Named;

import com.netflix.config.DynamicStringListProperty;

@Named
public class LoadBalancerUpdateConfig extends AbstractObjectProcessLogic implements ProcessPostListener, Priority {
    private static final DynamicStringListProperty ITEMS = ArchaiusUtil.getList("lb.config.items");
    private static final DynamicStringListProperty PROCESS_NAMES = ArchaiusUtil.getList("lb.instance.update.config.item.processes");

    @Inject
    LoadBalancerInstanceManager lbInstanceManager;

    @Inject
    LoadBalancerDao lbDao;

    @Inject
    JsonMapper jsonMapper;

    @Inject
    ConfigItemStatusManager statusManager;

    @Inject
    IpAddressDao ipAddressDao;

    @Inject
    NetworkDao networkDao;

    @Inject
    ResourceMonitor resourceMonitor;

    @Inject
    List<LoadBalancerLookup> lbLookups;

    @Inject
    LoadBalancerTargetDao targetDao;

    @Inject
    GenericResourceDao resourceDao;

    @Inject
    LockManager lockManager;

    @Override
    public String[] getProcessNames() {
        List<String> result = PROCESS_NAMES.get();
        return result.toArray(new String[result.size()]);
    }

    @Override
    public HandlerResult handle(ProcessState state, ProcessInstance process) {
        Set<Long> lbIds = new HashSet<>();

        for (LoadBalancerLookup lookup : lbLookups) {
            lbIds = lookup.getLoadBalancerIds(state.getResource());
            if (!lbIds.isEmpty()) {
                break;
            }
        }

        // update config only for active load balancers
        Set<Long> activeLbIds = new HashSet<>();
        for (Long lbId : lbIds) {
            LoadBalancer lb = objectManager.loadResource(LoadBalancer.class, lbId);
            List<String> activeStates = Arrays.asList(CommonStatesConstants.ACTIVATING, CommonStatesConstants.ACTIVE, CommonStatesConstants.UPDATING_ACTIVE);

            if (activeStates.contains(lb.getState())) {
                activeLbIds.add(lbId);
            }
        }

        Map<Long, List<? extends Instance>> lbInstancesMap = createLoadBalancerInstances(state, process, activeLbIds);

        updateLoadBalancerConfigs(state, lbInstancesMap);

        updatePublicPorts(state, lbInstancesMap);

        return null;
    }

    private void updateLoadBalancerConfigs(ProcessState state, Map<Long, List<? extends Instance>> lbInstancesMap) {
        List<Agent> agents = new ArrayList<>();
        for (Long lbId : lbInstancesMap.keySet()) {
            for (Instance lbInstance : lbInstancesMap.get(lbId)) {
                Agent agent = objectManager.loadResource(Agent.class, lbInstance.getAgentId());
                if (agent.getRemoved() == null) {
                    agents.add(agent);
                }
            }
        }

        for (Agent agent : agents) {
            ConfigUpdateRequest request = ConfigUpdateRequestUtils.getRequest(jsonMapper, state, getContext(agent));
            request = before(request, agent);
            ConfigUpdateRequestUtils.setRequest(request, state, getContext(agent));
        }

        for (Agent agent : agents) {
            ConfigUpdateRequest request = ConfigUpdateRequestUtils.getRequest(jsonMapper, state, getContext(agent));
            after(request);
            ConfigUpdateRequestUtils.setRequest(request, state, getContext(agent));
        }
    }

    @Override
    public int getPriority() {
        return Priority.DEFAULT;
    }

    protected ConfigUpdateRequest before(ConfigUpdateRequest request, Agent agent) {
        if (request == null) {
            request = ConfigUpdateRequest.forResource(Agent.class, agent.getId());
            for (String item : ITEMS.get()) {
                request.addItem(item).withApply(true).withIncrement(true).setCheckInSyncOnly(true);
            }
        }

        statusManager.updateConfig(request);

        return request;
    }

    protected void after(ConfigUpdateRequest request) {
        if (request == null) {
            return;
        }

        statusManager.waitFor(request);
    }

    public String getContext(Agent agent) {
        return String.format("AgentUpdateConfig:%s", agent.getId());
    }

    private Map<Long, List<? extends Instance>> createLoadBalancerInstances(ProcessState state,
            ProcessInstance process, Set<Long> lbIds) {
        Map<Long, List<? extends Instance>> lbInstancesMap = new HashMap<>();
        List<Instance> allLbInstances = new ArrayList<>();
        // create lb instances and open the ports for them
        for (Long lbId : lbIds) {
            List<? extends Instance> lbInstances = new ArrayList<>();
            LoadBalancer lb = loadResource(LoadBalancer.class, lbId);
            lbInstances = lbInstanceManager.createLoadBalancerInstances(lb);
            allLbInstances.addAll(lbInstances);
            lbInstancesMap.put(lbId, lbInstances);
        }
        for (Instance lbInstance : allLbInstances) {
            lbInstance = resourceMonitor.waitFor(lbInstance, new ResourcePredicate<Instance>() {
                @Override
                public boolean evaluate(Instance obj) {
                    return InstanceConstants.STATE_RUNNING.equals(obj.getState());
                }
            });
        }
        return lbInstancesMap;
    }

    private void updatePublicPorts(ProcessState state, Map<Long, List<? extends Instance>> lbInstancesMap) {
        for (Long lbId : lbInstancesMap.keySet()) {
            final LoadBalancer lb = loadResource(LoadBalancer.class, lbId);
            List<? extends LoadBalancerListener> listeners = lbDao.listActiveListenersForConfig(lb
                    .getLoadBalancerConfigId());
            final Set<Integer> listenerPorts = new HashSet<>();
            for (LoadBalancerListener listener : listeners) {
                listenerPorts.add(listener.getSourcePort());
            }
            List<? extends Instance> lbInstances = lbInstancesMap.get(lbId);
            // surround by lock
            for (final Instance lbInstance : lbInstances) {
                boolean lbHasActiveTargets = (targetDao.getLoadBalancerActiveTargetInstances(lb.getId()).size() + targetDao
                        .getLoadBalancerActiveIpTargets(lb.getId()).size()) > 0;
                List<String> ports = DataUtils.getFieldList(lbInstance.getData(), InstanceConstants.FIELD_PORTS,
                        String.class);
                boolean lbInstanceHasPortsSet = (ports != null && !ports.isEmpty());
                final boolean hasActiveInstances = lbHasActiveTargets || lbInstanceHasPortsSet;

                final Map<Integer, Port> portsToCreate = new HashMap<Integer, Port>();
                final Map<Integer, Port> portsToRemove = new HashMap<Integer, Port>();
                lockManager.lock(new LoadBalancerInstancePortLock(lbInstance), new LockCallbackNoReturn() {
                    @Override
                    public void doWithLockNoResult() {
                        Map<Integer, Port> existingPorts = new HashMap<Integer, Port>();
                        for (Port port : objectManager.children(lbInstance, Port.class)) {
                            if (port.getRemoved() == null && !port.getState().equals(CommonStatesConstants.REMOVED)) {
                                existingPorts.put(port.getPublicPort(), port);
                            }
                        }
                        for (Port port : existingPorts.values()) {
                            if (listenerPorts.contains(port.getPublicPort()) && hasActiveInstances) {
                                portsToCreate.put(port.getPublicPort(), port);
                            } else {
                                portsToRemove.put(port.getPublicPort(), port);
                            }
                        }

                        if (hasActiveInstances) {
                            for (Integer listenerPort : listenerPorts) {
                                if (existingPorts.containsKey(listenerPort)) {
                                    continue;
                                }

                                Nic primaryNic = networkDao.getPrimaryNic(lbInstance.getId());
                                if (primaryNic == null) {
                                    continue;
                                }
                                IpAddress ipAddress = ipAddressDao.getPrimaryIpAddress(primaryNic);
                                if (ipAddress == null) {
                                    continue;
                                }

                                Port portObj = objectManager.create(Port.class, PORT.KIND, PortConstants.KIND_USER,

                                        PORT.ACCOUNT_ID,
                                        lbInstance.getAccountId(),
                                        PORT.INSTANCE_ID, lbInstance.getId(), PORT.PUBLIC_PORT, listenerPort,
                                        PORT.PRIVATE_PORT, listenerPort, PORT.PROTOCOL, "tcp",
                                        PORT.PRIVATE_IP_ADDRESS_ID, ipAddress.getId());
                                portsToCreate.put(portObj.getPublicPort(), portObj);
                            }
                        }
                    }
                });

                if (hasActiveInstances) {
                    for (Port port : portsToCreate.values()) {
                        createThenActivate(port, state.getData());
                    }
                }

                for (Port port : portsToRemove.values()) {
                    deactivateThenRemove(port, state.getData());
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
GetSub = function (name) {
  for(var id in Meteor.connection._subscriptions) {
    var sub = Meteor.connection._subscriptions[id];
    if(name === sub.name) {
      return sub;
    }
  }
};

FlowRouter.route('/');


text:
module Produce
  class Manager
    # Produces app at DeveloperCenter and ItunesConnect
    def self.start_producing
      FastlaneCore::PrintTable.print_values(config: Produce.config, hide_keys: [], title: "Summary for produce #{Produce::VERSION}")

      Produce::DeveloperCenter.new.run unless Produce.config[:skip_devcenter]
      return Produce::ItunesConnect.new.run unless Produce.config[:skip_itc]
    end
  end
end


text:
define(function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var TexHighlightRules = require("./tex_highlight_rules").TexHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;

var Mode = function(suppressHighlighting) {
	if (suppressHighlighting)
    	this.$tokenizer = new Tokenizer(new TextHighlightRules().getRules());
	else
    	this.$tokenizer = new Tokenizer(new TexHighlightRules().getRules());
    this.$outdent = new MatchingBraceOutdent();
};
oop.inherits(Mode, TextMode);

(function() {
   this.getNextLineIndent = function(state, line, tab) {
      return this.$getIndent(line);
   };

   this.allowAutoInsert = function() {
      return false;
   };
}).call(Mode.prototype);

exports.Mode = Mode;
});


text:
    #pragma hdrstop
#endif

#ifndef WX_PRECOMP
    #include "wx/utils.h"
    #include "wx/gdicmn.h"
#endif

#include "wx/settings.h"

#include "wx/msw/private.h"

#ifndef SPI_GETFLATMENU
#define SPI_GETFLATMENU                     0x1022
#endif

#include "wx/module.h"
#include "wx/fontutil.h"

#ifdef __WXWINCE__ // for SM_CXCURSOR and SM_CYCURSOR
#include "wx/msw/wince/missing.h"
#endif // __WXWINCE__

// ----------------------------------------------------------------------------
// private classes
// ----------------------------------------------------------------------------

// the module which is used to clean up wxSystemSettingsNative data (this is a
// singleton class so it can't be done in the dtor)
class wxSystemSettingsModule : public wxModule
{
public:
    virtual bool OnInit();
    virtual void OnExit();

private:
    DECLARE_DYNAMIC_CLASS(wxSystemSettingsModule)
};

// ----------------------------------------------------------------------------
// global data
// ----------------------------------------------------------------------------

// the font returned by GetFont(wxSYS_DEFAULT_GUI_FONT): it is created when
// GetFont() is called for the first time and deleted by wxSystemSettingsModule
static wxFont *gs_fontDefault = NULL;

// ============================================================================
// implementation
// ============================================================================

// TODO: see ::SystemParametersInfo for all sorts of Windows settings.
// Different args are required depending on the id. How does this differ
// from GetSystemMetric, and should it? Perhaps call it GetSystemParameter
// and pass an optional void* arg to get further info.
// Should also have SetSystemParameter.
// Also implement WM_WININICHANGE (NT) / WM_SETTINGCHANGE (Win95)

// ----------------------------------------------------------------------------
// wxSystemSettingsModule
// ----------------------------------------------------------------------------

IMPLEMENT_DYNAMIC_CLASS(wxSystemSettingsModule, wxModule)

bool wxSystemSettingsModule::OnInit()
{
    return true;
}

void wxSystemSettingsModule::OnExit()
{
    delete gs_fontDefault;
    gs_fontDefault = NULL;
}

// ----------------------------------------------------------------------------
// wxSystemSettingsNative
// ----------------------------------------------------------------------------

// ----------------------------------------------------------------------------
// colours
// ----------------------------------------------------------------------------

wxColour wxSystemSettingsNative::GetColour(wxSystemColour index)
{
    // we use 0 as the default value just to avoid compiler warnings, as there
    // is no invalid colour value we use hasCol as the real indicator of
    // whether colSys was initialized or not
    COLORREF colSys = 0;
    bool hasCol = false;

    // the default colours for the entries after BTNHIGHLIGHT
    static const COLORREF s_defaultSysColors[] =
    {
        0x000000,   // 3DDKSHADOW
        0xdfdfdf,   // 3DLIGHT
        0x000000,   // INFOTEXT
        0xe1ffff,   // INFOBK

        0,          // filler - no std colour with this index

        // TODO: please fill in the standard values of those, I don't have them
        0,          // HOTLIGHT
        0,          // GRADIENTACTIVECAPTION
        0,          // GRADIENTINACTIVECAPTION
        0,          // MENU
        0,          // MENUBAR (unused)
    };

    if ( index == wxSYS_COLOUR_LISTBOX )
    {
        // there is no standard colour with this index, map to another one
        index = wxSYS_COLOUR_WINDOW;
    }
    else if ( index > wxSYS_COLOUR_BTNHIGHLIGHT )
    {
        // the indices before BTNHIGHLIGHT are understood by GetSysColor() in
        // all Windows version, for the other ones we have to check
        bool useDefault;

        int verMaj, verMin;
        wxGetOsVersion(&verMaj, &verMin);
        if ( verMaj < 4 )
        {
            // NT 3.5
            useDefault = true;
        }
        else if ( verMaj == 4 )
        {
            // Win95/NT 4.0
            useDefault = index > wxSYS_COLOUR_INFOBK;
        }
        else if ( verMaj == 5 && verMin == 0 )
        {
            // Win98/Win2K
            useDefault = index > wxSYS_COLOUR_GRADIENTINACTIVECAPTION;
        }
        else // >= 5.1
        {
            // 5.1 is Windows XP
            useDefault = false;
            // Determine if we are using flat menus, only then allow wxSYS_COLOUR_MENUBAR
            if ( index == wxSYS_COLOUR_MENUBAR )
            {
                BOOL isFlat ;
                if ( SystemParametersInfo( SPI_GETFLATMENU , 0 ,&isFlat, 0 ) )
                {
                    if ( !isFlat )
                        index = wxSYS_COLOUR_MENU ;
                }
            }
        }

        if ( useDefault )
        {
            // special handling for MENUBAR colour: we use this in wxToolBar
            // and wxStatusBar to have correct bg colour under Windows XP
            // (which uses COLOR_MENUBAR for them) but they should still look
            // correctly under previous Windows versions as well
            if ( index == wxSYS_COLOUR_MENUBAR )
            {
                index = wxSYS_COLOUR_3DFACE;
            }
            else // replace with default colour
            {
                unsigned int n = index - wxSYS_COLOUR_BTNHIGHLIGHT;

                wxASSERT_MSG( n < WXSIZEOF(s_defaultSysColors),
                              _T("forgot tp update the default colours array") );

                colSys = s_defaultSysColors[n];
                hasCol = true;
            }
        }
    }

    if ( !hasCol )
    {
#ifdef __WXWINCE__
        colSys = ::GetSysColor(index|SYS_COLOR_INDEX_FLAG);
#else
        colSys = ::GetSysColor(index);
#endif
    }

    return wxRGBToColour(colSys);
}

// ----------------------------------------------------------------------------
// fonts
// ----------------------------------------------------------------------------

wxFont wxCreateFontFromStockObject(int index)
{
    wxFont font;

    HFONT hFont = (HFONT) ::GetStockObject(index);
    if ( hFont )
    {
        LOGFONT lf;
        if ( ::GetObject(hFont, sizeof(LOGFONT), &lf) != 0 )
        {
            wxNativeFontInfo info;
            info.lf = lf;
#ifndef __WXWINCE__
            // We want Windows 2000 or later to have new fonts even MS Shell Dlg
            // is returned as default GUI font for compatibility
            int verMaj;
            if(index == DEFAULT_GUI_FONT && wxGetOsVersion(&verMaj) == wxWINDOWS_NT && verMaj >= 5)
                wxStrcpy(info.lf.lfFaceName, wxT("MS Shell Dlg 2"));
#endif
            // Under MicroWindows we pass the HFONT as well
            // because it's hard to convert HFONT -> LOGFONT -> HFONT
            // It's OK to delete stock objects, the delete will be ignored.
#ifdef __WXMICROWIN__
            font.Create(info, (WXHFONT) hFont);
#else
            font.Create(info);
#endif
        }
        else
        {
            wxFAIL_MSG( _T("failed to get LOGFONT") );
        }
    }
    else // GetStockObject() failed
    {
        wxFAIL_MSG( _T("stock font not found") );
    }

    return font;
}

wxFont wxSystemSettingsNative::GetFont(wxSystemFont index)
{
#ifdef __WXWINCE__
    // under CE only a single SYSTEM_FONT exists
    index;

    if ( !gs_fontDefault )
    {
        gs_fontDefault = new wxFont(wxCreateFontFromStockObject(SYSTEM_FONT));
    }

    return *gs_fontDefault;
#else // !__WXWINCE__
    // wxWindow ctor calls GetFont(wxSYS_DEFAULT_GUI_FONT) so we're
    // called fairly often -- this is why we cache this particular font
    const bool isDefaultRequested = index == wxSYS_DEFAULT_GUI_FONT;
    if ( isDefaultRequested )
    {
        if ( gs_fontDefault )
            return *gs_fontDefault;
    }

    wxFont font = wxCreateFontFromStockObject(index);

    if ( isDefaultRequested )
    {
        // if we got here it means we hadn't cached it yet - do now
        gs_fontDefault = new wxFont(font);
    }

    return font;
#endif // __WXWINCE__/!__WXWINCE__
}

// ----------------------------------------------------------------------------
// system metrics/features
// ----------------------------------------------------------------------------

// TODO: some of the "metrics" clearly should be features now that we have
//       HasFeature()!

// the conversion table from wxSystemMetric enum to GetSystemMetrics() param
//
// if the constant is not defined, put -1 in the table to indicate that it is
// unknown
static const int gs_metricsMap[] =
{
    -1,  // wxSystemMetric enums start at 1, so give a dummy value for pos 0.
#if defined(__WIN32__) && !defined(__WXWINCE__)
    SM_CMOUSEBUTTONS,
#else
    -1,
#endif

    SM_CXBORDER,
    SM_CYBORDER,
#ifdef SM_CXCURSOR
	SM_CXCURSOR,
    SM_CYCURSOR,
#else
	-1, -1,
#endif
    SM_CXDOUBLECLK,
    SM_CYDOUBLECLK,
#if defined(__WIN32__) && defined(SM_CXDRAG)
    SM_CXDRAG,
    SM_CYDRAG,
    SM_CXEDGE,
    SM_CYEDGE,
#else
    -1, -1, -1, -1,
#endif
    SM_CXHSCROLL,
    SM_CYHSCROLL,
#ifdef SM_CXHTHUMB
    SM_CXHTHUMB,
#else
    -1,
#endif
    SM_CXICON,
    SM_CYICON,
    SM_CXICONSPACING,
    SM_CYICONSPACING,
#ifdef SM_CXHTHUMB
    SM_CXMIN,
    SM_CYMIN,
#else
    -1, -1,
#endif
    SM_CXSCREEN,
    SM_CYSCREEN,

#if defined(__WIN32__) && defined(SM_CXSIZEFRAME)
    SM_CXSIZEFRAME,
    SM_CYSIZEFRAME,
    SM_CXSMICON,
    SM_CYSMICON,
#else
    -1, -1, -1, -1,
#endif
    SM_CYHSCROLL,
    SM_CXVSCROLL,
    SM_CXVSCROLL,
    SM_CYVSCROLL,
#ifdef SM_CYVTHUMB
    SM_CYVTHUMB,
#else
    -1,
#endif
    SM_CYCAPTION,
    SM_CYMENU,
#if defined(__WIN32__) && defined(SM_NETWORK)
    SM_NETWORK,
#else
    -1,
#endif
#ifdef SM_PENWINDOWS
    SM_PENWINDOWS,
#else
    -1,
#endif
#if defined(__WIN32__) && defined(SM_SHOWSOUNDS)
    SM_SHOWSOUNDS,
#else
    -1,
#endif
#ifdef SM_SWAPBUTTON
    SM_SWAPBUTTON,
#else
    -1
#endif
};

// Get a system metric, e.g. scrollbar size
int wxSystemSettingsNative::GetMetric(wxSystemMetric index, wxWindow* WXUNUSED(win))
{
#ifdef __WXMICROWIN__
    // TODO: probably use wxUniv themes functionality
    return 0;
#else // !__WXMICROWIN__
    wxCHECK_MSG( index > 0 && (size_t)index < WXSIZEOF(gs_metricsMap), 0,
                 _T("invalid metric") );

    int indexMSW = gs_metricsMap[index];
    if ( indexMSW == -1 )
    {
        // not supported under current system
        return -1;
    }

    int rc = ::GetSystemMetrics(indexMSW);
    if ( index == wxSYS_NETWORK_PRESENT )
    {
        // only the last bit is significant according to the MSDN
        rc &= 1;
    }

    return rc;
#endif // __WXMICROWIN__/!__WXMICROWIN__
}

bool wxSystemSettingsNative::HasFeature(wxSystemFeature index)
{
    switch ( index )
    {
        case wxSYS_CAN_ICONIZE_FRAME:
        case wxSYS_CAN_DRAW_FRAME_DECORATIONS:
            return true;

        default:
            wxFAIL_MSG( _T("unknown system feature") );

            return false;
    }
}

// ----------------------------------------------------------------------------
// function from wx/msw/wrapcctl.h: there is really no other place for it...
// ----------------------------------------------------------------------------

#if wxUSE_LISTCTRL || wxUSE_TREECTRL

extern wxFont wxGetCCDefaultFont()
{
#ifndef __WXWINCE__
    // under the systems enumerated below (anything released after Win98), the
    // default font used for the common controls seems to be the desktop font
    // which is also used for the icon titles and not the stock default GUI
    // font
    bool useIconFont;
    int verMaj, verMin;
    switch ( wxGetOsVersion(&verMaj, &verMin) )
    {
        case wxWIN95:
            // 4.10 is Win98
            useIconFont = verMaj == 4 && verMin >= 10;
            break;

        case wxWINDOWS_NT:
            // 5.0 is Win2k
            useIconFont = verMaj >= 5;
            break;

        default:
            useIconFont = false;
    }

    if ( useIconFont )
    {
        LOGFONT lf;
        if ( ::SystemParametersInfo
               (
                    SPI_GETICONTITLELOGFONT,
                    sizeof(lf),
                    &lf,
                    0
               ) )
        {
            return wxFont(wxCreateFontFromLogFont(&lf));
        }
        else
        {
            wxLogLastError(_T("SystemParametersInfo(SPI_GETICONTITLELOGFONT"));
        }
    }
#endif // __WXWINCE__

    // fall back to the default font for the normal controls
    return wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
}

#endif // wxUSE_LISTCTRL || wxUSE_TREECTRL


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

require 'stringio'

$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "..", "lib"))
require 'protocol_buffers/runtime/field'

describe ProtocolBuffers, "fields" do

  def mkfield(ftype)
    ProtocolBuffers::Field.const_get(ftype).new(:optional, "test", 1)
  end

  it "checks bounds on varint field types" do
    u32 = mkfield(:Uint32Field)
    proc { u32.check_valid(0xFFFFFFFF) }.should_not raise_error()
    proc { u32.check_valid(0x100000000) }.should raise_error(ArgumentError)
    proc { u32.check_valid(-1) }.should raise_error(ArgumentError)

    u64 = mkfield(:Uint64Field)
    proc { u64.check_valid(0xFFFFFFFF_FFFFFFFF) }.should_not raise_error()
    proc { u64.check_valid(0x100000000_00000000) }.should raise_error(ArgumentError)
    proc { u64.check_valid(-1) }.should raise_error(ArgumentError)
  end

  it "properly encodes and decodes negative varints" do
    val = -2082844800000000
    str = "\200\300\313\274\236\265\246\374\377\001"
    sio = ProtocolBuffers.bin_sio
    ProtocolBuffers::Varint.encode(sio, val)
    sio.string.should == str
    sio.rewind
    val2 = ProtocolBuffers::Varint.decode(sio)
    int64 = mkfield(:Int64Field)
    int64.deserialize(val2).should == val
    proc { int64.check_value(int64.deserialize(val2)) }.should_not raise_error
  end

  context "UTF-8 encoding of length-delimited fields" do
    if RUBY_VERSION < "1.9"
      pending "UTF-8 validation only happens in ruby 1.9+"
    else

      before :each do
        @good_utf   = "\xc2\xa1hola\x21"
        @bad_utf    = "\xc2"
        @good_ascii = "!hola!".force_encoding("us-ascii")

        @good_utf_io   = proc { StringIO.new(@good_utf) }
        @bad_utf_io    = proc { StringIO.new(@bad_utf) }
        @good_ascii_io = proc { StringIO.new(@good_ascii) }

        @s = mkfield(:StringField)
        @b = mkfield(:BytesField)
      end

      context "string fields" do

        it "forces UTF-8 on serializing" do
          @s.serialize(@good_utf).encoding.should == Encoding::UTF_8
          proc { @s.check_valid(@s.serialize(@good_utf)) }.should_not raise_error()

          @s.serialize(@good_ascii).encoding.should == Encoding::UTF_8
          proc { @s.check_valid(@s.serialize(@good_ascii)) }.should_not raise_error()

          proc { @s.serialize(@bad_utf) }.should raise_error(ArgumentError)
        end

        it "forces UTF-8 on deserializing" do
          @s.deserialize(@good_utf_io[]).encoding.should == Encoding::UTF_8
          proc { @s.check_valid(@s.deserialize(@good_utf_io[])) }.should_not raise_error()

          @s.deserialize(@good_ascii_io[]).encoding.should == Encoding::UTF_8
          proc { @s.check_valid(@s.deserialize(@good_ascii_io[])) }.should_not raise_error()

          @s.deserialize(@bad_utf_io[]).encoding.should == Encoding::UTF_8
          proc { @s.check_valid(@s.deserialize(@bad_utf_io[])) }.should raise_error(ArgumentError)
        end
      end

      context "byte fields" do

        it "does not force UTF-8 on deserializing" do
          @b.deserialize(@good_utf_io[]).encoding.should == Encoding::BINARY
          proc { @b.check_valid(@b.deserialize(@good_utf_io[])) }.should_not raise_error()

          @b.deserialize(@good_ascii_io[]).encoding.should == Encoding.find("us-ascii")
          proc { @b.check_valid(@b.deserialize(@good_ascii_io[])) }.should_not raise_error()

          @b.deserialize(@bad_utf_io[]).encoding.should == Encoding::BINARY
          proc { @b.check_valid(@b.deserialize(@bad_utf_io[])) }.should_not raise_error()
        end
      end
    end
  end

  it "provides a reader for proxy_class on message fields" do
    ProtocolBuffers::Field::MessageField.new(nil, :optional, :fake_name, 1).should respond_to(:proxy_class)
    ProtocolBuffers::Field::MessageField.new(Class, :optional, :fake_name, 1).proxy_class.should == Class
  end
end


text:
package org.wildfly.swarm.topology.openshift.runtime;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import com.openshift.restclient.ClientBuilder;
import com.openshift.restclient.IClient;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;

public class ClientService implements Service<IClient> {

    public static final ServiceName SERVICE_NAME = OpenShiftTopologyConnector.SERVICE_NAME.append("client");

    public static int servicePort(String serviceName) {
        String envName = serviceName.replace("-", "_").toUpperCase() + "_SERVICE_PORT";
        String envPort = System.getenv(envName);
        if (envPort == null) {
            return -1;
        }

        return Integer.parseInt(envPort);
    }

    @Override
    public void start(StartContext context) throws StartException {
        try {
            this.client = openshiftClient();
            // Trigger an API call to ensure we fail-fast if we can't talk
            // to the API
            this.client.getServerReadyStatus();
        } catch (IOException ex) {
            throw new StartException(ex);
        }
    }

    @Override
    public void stop(StopContext context) {
        this.client = null;
    }

    @Override
    public IClient getValue() throws IllegalStateException, IllegalArgumentException {
        return this.client;
    }

    private IClient openshiftClient() throws IOException {
        String kubeHost = serviceHost("kubernetes");
        int kubePort = servicePort("kubernetes");

        Path tokenFile = Paths.get("/var/run/secrets/kubernetes.io/serviceaccount/token");
        String scheme = "http";
        String token = null;
        if (Files.exists(tokenFile)) {
            token = new String(Files.readAllBytes(tokenFile));
            scheme = "https";
        }

        return new ClientBuilder(scheme + "://" + kubeHost + ":" + kubePort)
                .usingToken(token)
                .build();
    }

    protected String serviceHost(String serviceName) {
        String envName = serviceName.replace("-", "_").toUpperCase() + "_SERVICE_HOST";
        return System.getenv(envName);
    }

    private IClient client;
}


text:
    height: 175px;
    padding: 10px;
    text-align: center;
    background-color: #3c8dbc;
}

#loginMenu .dropdown-menu .user-header img {
    margin-bottom:10px;
}
#loginMenu .dropdown-menu .user-footer {
    background-color: #f9f9f9;
    padding: 10px;
}

#loginMenu .dropdown-menu .row {
    margin-left:0;
    margin-right:0;
}

.jOrgChart .phoneKey {
    background-color: red;
    width: 20px;
    border-radius: 10px;
    height: 20px;
    color: white;
    cursor: default;
    font-weight: bold;
    margin: -10px auto auto;
}

.jOrgChart .addModule {
    background-color: darkgreen;
    width: 20px;
    border-radius: 10px;
    height: 20px;
    color: white;
    cursor: pointer;
    font-weight: bold;
    margin: auto;
}

.jOrgChart .moduleDescription {
    max-height:60px;
    overflow: auto;
}


text:
#ifndef _SWAY_CONTAINER_H
#define _SWAY_CONTAINER_H
#include <wlc/wlc.h>
typedef struct sway_container swayc_t;

#include "layout.h"

/**
 * Different kinds of containers.
 *
 * This enum is in order. A container will never be inside of a container below
 * it on this list.
 */
enum swayc_types {
	C_ROOT,				/**< The root container. Only one of these ever exists. */
	C_OUTPUT,			/**< An output (aka monitor, head, etc). */
	C_WORKSPACE,		/**< A workspace. */
	C_CONTAINER,		/**< A manually created container. */
	C_VIEW,				/**< A view (aka window). */
	// Keep last
	C_TYPES,
};

/**
 * Different ways to arrange a container.
 */
enum swayc_layouts {
	L_NONE, 			/**< Used for containers that have no layout (views, root) */
	L_HORIZ,
	L_VERT,
	L_STACKED,
	L_TABBED,
	L_FLOATING,			/**< A psuedo-container, removed from the tree, to hold floating windows */
	// Keep last
	L_LAYOUTS,
};

/**
 * Stores information about a container.
 *
 * The tree is made of these. Views are containers that cannot have children.
 */
struct sway_container {
	/**
	 * If this container maps to a WLC object, this is set to that object's
	 * handle. Otherwise, NULL.
	 */
	wlc_handle handle;

	enum swayc_types type;
	enum swayc_layouts layout;

	/**
	 * Width and height of this container, without borders or gaps.
	 */
	double width, height;

	/**
	 * Views may request geometry, which is stored in this and ignored until
	 * the views are floated.
	 */
	int desired_width, desired_height;

	/**
	 * The coordinates that this view appear at, relative to the output they
	 * are located on (output containers have absolute coordinates).
	 */
	double x, y;

	/**
	 * False if this view is invisible. It could be in the scratchpad or on a
	 * workspace that is not shown.
	 */
	bool visible;
	bool is_floating;
	bool is_focused;
	bool sticky; // floating view always visible on its output

	// Attributes that mostly views have.
	char *name;
	char *class;
	char *app_id;

	int gaps;

	list_t *children;
	/**
	 * Children of this container that are floated.
	 */
	list_t *floating;

	/**
	 * The parent of this container. NULL for the root container.
	 */
	struct sway_container *parent;
	/**
	 * Which of this container's children has focus.
	 */
	struct sway_container *focused;
};

enum visibility_mask {
	VISIBLE = true
} visible;

/**
 * Allocates a new output container.
 */
swayc_t *new_output(wlc_handle handle);
/**
 * Allocates a new workspace container.
 */
swayc_t *new_workspace(swayc_t *output, const char *name);
/**
 * Allocates a new container and places a child into it.
 *
 * This is used from the split command, which creates a new container with the
 * requested layout and replaces the focused container in the tree with the new
 * one. Then the removed container is added as a child of the new container.
 */
swayc_t *new_container(swayc_t *child, enum swayc_layouts layout);
/**
 * Allocates a new view container.
 *
 * Pass in a sibling view, or a workspace to become this container's parent.
 */
swayc_t *new_view(swayc_t *sibling, wlc_handle handle);
/**
 * Allocates a new floating view in the active workspace.
 */
swayc_t *new_floating_view(wlc_handle handle);

/**
 * Frees an output's container.
 */
swayc_t *destroy_output(swayc_t *output);
/**
 * Destroys a workspace container and returns the parent pointer, or NULL.
 */
swayc_t *destroy_workspace(swayc_t *workspace);
/**
 * Destroys a container and all empty parents. Returns the topmost non-empty
 * parent container, or NULL.
 */
swayc_t *destroy_container(swayc_t *container);
/**
 * Destroys a view container and all empty parents. Returns the topmost
 * non-empty parent container, or NULL.
 */
swayc_t *destroy_view(swayc_t *view);

/**
 * Finds a container based on test criteria. Returns the first container that
 * passes the test.
 */
swayc_t *swayc_by_test(swayc_t *container, bool (*test)(swayc_t *view, void *data), void *data);
/**
 * Finds a parent container with the given swayc_type.
 */
swayc_t *swayc_parent_by_type(swayc_t *container, enum swayc_types);
/**
 * Finds a parent with the given swayc_layout.
 */
swayc_t *swayc_parent_by_layout(swayc_t *container, enum swayc_layouts);
/**
 * Finds the bottom-most focused container of a type.
 */
swayc_t *swayc_focus_by_type(swayc_t *container, enum swayc_types);
/**
 * Finds the bottom-most focused container of a layout.
 */
swayc_t *swayc_focus_by_layout(swayc_t *container, enum swayc_layouts);

/**
 * Gets the swayc_t associated with a wlc_handle.
 */
swayc_t *swayc_by_handle(wlc_handle handle);
/**
 * Gets the named swayc_t.
 */
swayc_t *swayc_by_name(const char *name);
/**
 * Gets the active output's container.
 */
swayc_t *swayc_active_output(void);
/**
 * Gets the active workspace's container.
 */
swayc_t *swayc_active_workspace(void);
/**
 * Gets the workspace for the given view container.
 */
swayc_t *swayc_active_workspace_for(swayc_t *view);
/**
 * Finds the container currently underneath the pointer.
 */
swayc_t *container_under_pointer(void);

/**
 * Returns true if a container is fullscreen.
 */
bool swayc_is_fullscreen(swayc_t *view);
/**
 * Returns true if this view is focused.
 */
bool swayc_is_active(swayc_t *view);
/**
 * Returns true if the parent is an ancestor of the child.
 */
bool swayc_is_parent_of(swayc_t *parent, swayc_t *child);
/**
 * Returns true if the child is a desecendant of the parent.
 */
bool swayc_is_child_of(swayc_t *child, swayc_t *parent);
/**
 * Returns the gap (padding) of the container.
 *
 * This returns the inner gaps for a view, the outer gaps for a workspace, and
 * 0 otherwise.
 */
int swayc_gap(swayc_t *container);

/**
 * Maps a container's children over a function.
 */
void container_map(swayc_t *, void (*f)(swayc_t *, void *), void *);

/**
 * Set a view as visible or invisible.
 *
 * This will perform the required wlc calls as well; it is not sufficient to
 * simply toggle the boolean in swayc_t.
 */
void set_view_visibility(swayc_t *view, void *data);
/**
 * Set the gaps value for a view.
 */
void set_gaps(swayc_t *view, void *amount);
/**
 * Add to the gaps value for a view.
 */
void add_gaps(swayc_t *view, void *amount);

/**
 * Issue wlc calls to make the visibility of a container consistent.
 */
void update_visibility(swayc_t *container);

#endif


text:
<?php

error_reporting(E_STRICT | E_ALL);

// Add the library to the include path. This is not neccessary if you've already
// done so in your php.ini file.
$path = dirname(__FILE__) . '/../../../src';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

require_once 'Google/Api/Ads/AdWords/Lib/AdWordsUser.php';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 */
function AddAudienceExample(AdWordsUser $user) {
  // Get the services, which loads the required classes.
  $userListService = $user->GetService('UserListService', 'v201109_1');
  $conversionTrackerService =
      $user->GetService('ConversionTrackerService', 'v201109_1');

  // Create conversion type (tag).
  $conversionType = new UserListConversionType();
  $conversionType->name = 'Mars cruise customers #' . uniqid();

  // Create remarketing user list.
  $userList = new RemarketingUserList();
  $userList->name = 'Mars cruise customers #' . uniqid();
  $userList->conversionTypes = array($conversionType);

  // Set additional settings (optional).
  $userList->description = 'A list of mars cruise customers in the last year';
  $userList->status = 'OPEN';
  $userList->membershipLifeSpan = 365;

  // Create operation.
  $operation = new UserListOperation();
  $operation->operand = $userList;
  $operation->operator = 'ADD';

  $operations = array($operation);

  // Make the mutate request.
  $result = $userListService->mutate($operations);
  $userList = $result->value[0];

  // Wait a moment before retrieving the conversion snippet.
  sleep(1);

  // Create the selector.
  $selector = new Selector();
  $selector->fields = array('Id');
  $selector->predicates[] =
      new Predicate('Id', 'IN', array($userList->conversionTypes[0]->id));

  // Make the get request.
  $page = $conversionTrackerService->get($selector);
  $conversionTracker = $page->entries[0];

  // Display result.
  printf("Audience with name '%s' and id '%.0f' was added.\n", $userList->name,
      $userList->id);
  printf("Tag code:\n%s\n", $conversionTracker->snippet);
}

// Don't run the example if the file is being included.
if (__FILE__ != realpath($_SERVER['PHP_SELF'])) {
  return;
}

try {
  // Get AdWordsUser from credentials in "../auth.ini"
  // relative to the AdWordsUser.php file's directory.
  $user = new AdWordsUser();

  // Log every SOAP XML request and response.
  $user->LogAll();

  // Run the example.
  AddAudienceExample($user);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}


text:
<?php

namespace Google\AdsApi\Dfp\v201611;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class Stats
{

    /**
     * @var int $impressionsDelivered
     */
    protected $impressionsDelivered = null;

    /**
     * @var int $clicksDelivered
     */
    protected $clicksDelivered = null;

    /**
     * @var int $videoCompletionsDelivered
     */
    protected $videoCompletionsDelivered = null;

    /**
     * @var int $videoStartsDelivered
     */
    protected $videoStartsDelivered = null;

    /**
     * @var int $viewableImpressionsDelivered
     */
    protected $viewableImpressionsDelivered = null;

    /**
     * @param int $impressionsDelivered
     * @param int $clicksDelivered
     * @param int $videoCompletionsDelivered
     * @param int $videoStartsDelivered
     * @param int $viewableImpressionsDelivered
     */
    public function __construct($impressionsDelivered = null, $clicksDelivered = null, $videoCompletionsDelivered = null, $videoStartsDelivered = null, $viewableImpressionsDelivered = null)
    {
      $this->impressionsDelivered = $impressionsDelivered;
      $this->clicksDelivered = $clicksDelivered;
      $this->videoCompletionsDelivered = $videoCompletionsDelivered;
      $this->videoStartsDelivered = $videoStartsDelivered;
      $this->viewableImpressionsDelivered = $viewableImpressionsDelivered;
    }

    /**
     * @return int
     */
    public function getImpressionsDelivered()
    {
      return $this->impressionsDelivered;
    }

    /**
     * @param int $impressionsDelivered
     * @return \Google\AdsApi\Dfp\v201611\Stats
     */
    public function setImpressionsDelivered($impressionsDelivered)
    {
      $this->impressionsDelivered = $impressionsDelivered;
      return $this;
    }

    /**
     * @return int
     */
    public function getClicksDelivered()
    {
      return $this->clicksDelivered;
    }

    /**
     * @param int $clicksDelivered
     * @return \Google\AdsApi\Dfp\v201611\Stats
     */
    public function setClicksDelivered($clicksDelivered)
    {
      $this->clicksDelivered = $clicksDelivered;
      return $this;
    }

    /**
     * @return int
     */
    public function getVideoCompletionsDelivered()
    {
      return $this->videoCompletionsDelivered;
    }

    /**
     * @param int $videoCompletionsDelivered
     * @return \Google\AdsApi\Dfp\v201611\Stats
     */
    public function setVideoCompletionsDelivered($videoCompletionsDelivered)
    {
      $this->videoCompletionsDelivered = $videoCompletionsDelivered;
      return $this;
    }

    /**
     * @return int
     */
    public function getVideoStartsDelivered()
    {
      return $this->videoStartsDelivered;
    }

    /**
     * @param int $videoStartsDelivered
     * @return \Google\AdsApi\Dfp\v201611\Stats
     */
    public function setVideoStartsDelivered($videoStartsDelivered)
    {
      $this->videoStartsDelivered = $videoStartsDelivered;
      return $this;
    }

    /**
     * @return int
     */
    public function getViewableImpressionsDelivered()
    {
      return $this->viewableImpressionsDelivered;
    }

    /**
     * @param int $viewableImpressionsDelivered
     * @return \Google\AdsApi\Dfp\v201611\Stats
     */
    public function setViewableImpressionsDelivered($viewableImpressionsDelivered)
    {
      $this->viewableImpressionsDelivered = $viewableImpressionsDelivered;
      return $this;
    }

}


text:
package org.typemeta.funcj.json.model;

import org.typemeta.funcj.functions.Functions;

import java.io.StringWriter;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Stream;

/**
 * Models a JSON array.
 */
public final class JsArray
        implements Iterable<JsValue>, JsValue {

    private final List<JsValue> values;

    protected JsArray(List<JsValue> values) {
        this.values = Objects.requireNonNull(values);
    }

    public boolean isEmpty() {
        return values.isEmpty();
    }

    public int size() {
        return values.size();
    }

    public JsValue get(int index) {
        return values.get(index);
    }

    @Override
    public Iterator<JsValue> iterator() {
        final Iterator<JsValue> iter = values.iterator();

        return new Iterator<JsValue>() {

            @Override
            public boolean hasNext() {
                return iter.hasNext();
            }

            @Override
            public JsValue next() {
                return iter.next();
            }
        };
    }

    public Stream<JsValue> stream() {
        return values.stream();
    }

    public void forEach(Consumer<? super JsValue> action) {
        values.forEach(action);
    }

    @Override
    public String toString() {
        return write(new StringWriter()).toString();
    }

    @Override
    public boolean equals(Object rhs) {
        if (this == rhs) {
            return true;
        } else if (rhs == null || getClass() != rhs.getClass()) {
            return false;
        } else {
            final JsArray rhsT = (JsArray) rhs;
            return values.equals(rhsT.values);
        }
    }

    @Override
    public int hashCode() {
        return values.hashCode();
    }

    @Override
    public Type type() {
        return Type.ARRAY;
    }

    @Override
    public <T> T match(
            Functions.F<JsNull, T> fNull,
            Functions.F<JsBool, T> fBool,
            Functions.F<JsNumber, T> fNum,
            Functions.F<JsString, T> fStr,
            Functions.F<JsArray, T> fArr,
            Functions.F<JsObject, T> fObj) {
        return fArr.apply(this);
    }

    @Override
    public boolean isArray() {
        return true;
    }

    @Override
    public JsArray asArray() {
        return this;
    }
}


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**success** | **Boolean** | If the response is successful or not | [optional]
**data** | [**[ListProductFollowersResponseAllOfData]**](ListProductFollowersResponseAllOfData.md) | The list of followers | [optional]
**additionalData** | [**AdditionalData**](AdditionalData.md) |  | [optional]


text:
require 'sinatra/base'

class FileServer < Sinatra::Base
  get '/*' do
    # show file or list directory entries
  end

  put '/*' do
    # write files
  end

  delete '/*' do
    # delete files
  end
end


text:
package com.capitalone.dashboard.collector;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import com.capitalone.dashboard.datafactory.rally.RallyDataFactory;
import com.capitalone.dashboard.model.Feature;
import com.capitalone.dashboard.repository.FeatureCollectorRepository;
import com.capitalone.dashboard.repository.FeatureRepository;

public class StoryDataClient {
	private final RallyDataFactory rallyData;
	private final FeatureRepository featureRepository;
	private final FeatureCollectorRepository featureCollectorRepository;
	@Autowired
public StoryDataClient(RallyDataFactory rallyData,FeatureCollectorRepository featureCollectorRepository,FeatureRepository featureRepository){
	this.rallyData=rallyData;
	this.featureRepository=featureRepository;
	this.featureCollectorRepository=featureCollectorRepository;
}
	public void updateMongoinfo() throws IOException,URISyntaxException,DuplicateKeyException{
		List<Feature> stories = new ArrayList<>();

		stories.addAll(rallyData.getStories("scrum","story"));
		stories.addAll(rallyData.getStories("scrum","defect"));
		//stories.addAll(rallyData.getStories("kanban","story"));
		cleanExistingStories();
	HashMap<String,Feature> storyMap = new HashMap<String,Feature>();

		for(Feature story:stories){
			story.setCollectorId(featureCollectorRepository.findByName("Rally").getId());
			storyMap.put(story.getsNumber(),story);
		}
		for(Feature story:storyMap.values()){
			featureRepository.save(story);
		}
	}
	public void cleanExistingStories(){
		featureRepository.deleteAll();
	}

}


text:
namespace SAML2SP.SAML {

    /// <summary>
    /// AssertionConsumerService class.
    /// </summary>
    /// <remarks>
    /// Auto-generated class.
    /// </remarks>
    public partial class AssertionConsumerService {
    }
}


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SamSeifert.ComputerVision
{
    public static partial class MultipleImages
    {
        /// <summary>
        /// All non squishy inputs should be same size.  Bad return if they aren't.
        /// </summary>
        /// <param name="inpt"></param>
        /// <param name="outp"></param>
        /// <returns></returns>
        private static ToolboxReturn MatchSectTypes(Sect[] inpt, ref Sect outp)
        {
            if (inpt == null)
            {
                outp = null;
                return ToolboxReturn.NullInput;
            }
            if (inpt.Length == 0)
            {
                outp = null;
                return ToolboxReturn.NullInput;
            }
            else
            {
                Size sz_out = Size.Empty;
                Boolean first_size = true;

                foreach (var inp in inpt)
                {
                    // Make Sure Inputs All Same Size
                    Size tsz = inp.getPrefferedSize();
                    if (!inp.isSquishy())
                    {
                        if (first_size)
                        {
                            first_size = false;
                            sz_out = inp.getPrefferedSize();
                        }
                        else if (sz_out != tsz)
                        {
                            outp = null;
                            return ToolboxReturn.ImageSizeMismatch;
                        }
                    }
                    else if (first_size)
                    {
                        sz_out.Height = Math.Max(sz_out.Height, tsz.Height);
                        sz_out.Width = Math.Max(sz_out.Width, tsz.Width);
                    }
                }

                return MatchSectTypes(inpt, ref outp, sz_out);
            }
        }

        /// <summary>
        /// Used directly in Convolute.  Used indirectly in Add and Multiply.
        /// </summary>
        /// <param name="inpt"></param>
        /// <param name="outp"></param>
        /// <param name="sz_out"></param>
        /// <returns></returns>
        private static ToolboxReturn MatchSectTypes(Sect[] inpt, ref Sect outp, Size sz_out)
        {
            if (inpt == null)
            {
                outp = null;
                return ToolboxReturn.NullInput;
            }
            if (inpt.Length == 0)
            {
                outp = null;
                return ToolboxReturn.NullInput;
            }
            else
            {
                var holders = new List<SectHolder>();
                var nonholders = new List<Sect>();

                Boolean first_single = true;
                SectType single_type = SectType.NaN;

                foreach (var inp in inpt)
                {
                    if (inp._Type == SectType.Holder) holders.Add(inp as SectHolder);
                    else
                    {
                        if (first_single)
                        {
                            single_type = inp._Type;
                            first_single = false;
                        }
                        else if (inp._Type != single_type) single_type = SectType.NaN;
                        nonholders.Add(inp);
                    }
                }

                SectHolder first_sh = null;

                foreach (var sh in holders)
                {
                    if (first_sh == null) first_sh = sh as SectHolder;
                    else
                    {
                        var k1 = first_sh.Sects.Keys;
                        var k2 = sh.Sects.Keys;
                        if ((k1.Count != k2.Count) || (k1.Except(k2).Any()))
                        {
                            outp = null;
                            return ToolboxReturn.SpecialError;
                        }
                    }
                }

                if (holders.Count == 0) // Just Non Holders
                {
                    if (single_type == SectType.NaN) single_type = SectType.Gray;
                    Boolean remake = outp == null;
                    if (!remake) remake = !(outp is SectArray);
                    if (!remake) remake = (single_type != outp._Type) || (sz_out != outp.getPrefferedSize());
                    if (remake) outp = new SectArray(single_type, sz_out.Width, sz_out.Height);
                }
                else
                {
                    Boolean remake = outp == null;
                    if (!remake) remake = (SectType.Holder != outp._Type) || (sz_out != outp.getPrefferedSize());
                    if (!remake)
                    {
                        var k1 = first_sh.Sects.Keys;
                        var k2 = (outp as SectHolder).Sects.Keys;
                        remake = ((k1.Count != k2.Count) || (k1.Except(k2).Any()));
                    }

                    if (remake) outp = new SectHolder(sz_out, first_sh.getSectTypes());
                }

                return ToolboxReturn.Good;
            }
        }
    }
}


text:
/**
 *
 *      Classes providing rank transformations.
 *
 */
package org.apache.commons.math4.legacy.stat.ranking;


text:
package com.erpdevelopment.vbvm.model;

import android.support.annotation.Nullable;

import com.erpdevelopment.vbvm.database.AppDatabase;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.raizlabs.android.dbflow.annotation.Column;
import com.raizlabs.android.dbflow.annotation.ManyToMany;
import com.raizlabs.android.dbflow.annotation.PrimaryKey;
import com.raizlabs.android.dbflow.annotation.Table;
import com.raizlabs.android.dbflow.structure.BaseModel;

import org.parceler.Parcel;
import com.erpdevelopment.vbvm.api.Mergable;

import java.util.List;

/**
 * Created by thomascarey on 8/06/17.
 */

@Table(database = AppDatabase.class)
@ManyToMany(referencedTable = Topic.class)
@Parcel(analyze = {Study.class})
public class Study extends BaseModel implements Mergable<Study> {

    @SerializedName("topics")
    @Expose
    public List<Topic> topics = null;

    @Column
    @SerializedName("bibleIndex")
    @Expose
    public Integer bibleIndex;

    @Column
    @SerializedName("thumbnailSource")
    @Expose
    public String thumbnailSource;

    @Column
    @SerializedName("title")
    @Expose
    public String title;

    @Column
    @SerializedName("podcastLink")
    @Expose
    public String podcastLink;

    @Column
    @SerializedName("lessonCount")
    @Expose
    public Integer lessonCount;

    @Column
    @SerializedName("description")
    @Expose
    public String description;

    @Column
    @SerializedName("category")
    @Expose
    public Integer category;

    @PrimaryKey
    @SerializedName("ID")
    @Expose
    public String id;

    @Column
    @SerializedName("url")
    @Expose
    public String url;

    @Column
    @SerializedName("image160")
    @Expose
    public String image160;

    @Column
    @SerializedName("image300")
    @Expose
    public String image300;

    @Column
    @SerializedName("image600")
    @Expose
    public String image600;

    @Column
    @SerializedName("image900")
    @Expose
    public String image900;

    @Column
    @SerializedName("image1100")
    @Expose
    public String image1100;

    @Column
    @SerializedName("image1400")
    @Expose
    public String image1400;

    @Override
    public String identifier() {
        return id;
    }

    @Nullable
    public String imageForWidth(int width) {
        if (width > 1100) {
            return image1400;
        } else if (width > 900) {
            return image1100;
        } else if (width > 600) {
            return image900;
        } else if (width > 300) {
            return image600;
        } else if (width > 160) {
            return image300;
        } else {
            return image160;
        }
    }

    @Override
    public void mergeAPIAttributes(Study apiVersion) {
        if (!this.id.equals(apiVersion.id))
            throw new IllegalArgumentException("The apiVersion.id must match the current id");

        // Only merge data that is exposed to GSON
        this.bibleIndex = apiVersion.bibleIndex;
        this.thumbnailSource = apiVersion.thumbnailSource;
        this.title = apiVersion.title;
        this.podcastLink = apiVersion.podcastLink;
        this.lessonCount = apiVersion.lessonCount;
        this.description = apiVersion.description;
        this.category = apiVersion.category;
        this.url = apiVersion.url;
        this.topics = apiVersion.topics;
        this.image160 = apiVersion.image160;
        this.image300 = apiVersion.image300;
        this.image600 = apiVersion.image600;
        this.image900 = apiVersion.image900;
        this.image1100 = apiVersion.image1100;
        this.image1400 = apiVersion.image1400;
    }

    public static String updated() {
        return "UPDATED-Study";
    }
}


text:
const POST = 0
const COMMUNITY = 1
const NETWORK = 2
const TOPIC = 3
const COMMENT = 4
const COMMUNITY_AND_TOPIC = 5

const GroupDataType = {
  POST,
  COMMUNITY,
  NETWORK,
  TOPIC,
  COMMENT,
  COMMUNITY_AND_TOPIC
}

export default GroupDataType

export function getModelForDataType (dataType) {
  switch (dataType) {
    case POST: return Post
    case COMMUNITY: return Group
    case NETWORK: return Group
    case TOPIC: return Tag
    case COMMENT: return Comment
  }
}

export function getDataTypeForInstance (instance) {
  if (instance instanceof Post) return POST
  if (instance instanceof Community) return COMMUNITY
  if (instance instanceof Network) return NETWORK
  if (instance instanceof Tag) return TOPIC
  if (instance instanceof Comment) return COMMENT
}

export function getDataTypeForModel (model) {
  return getDataTypeForInstance(model.forge())
}


text:
package org.apache.aries.async.promise.test;

import org.osgi.util.promise.Deferred;
import org.osgi.util.promise.Promise;
import org.junit.Test;

import java.lang.reflect.InvocationTargetException;

import static org.junit.Assert.*;

public class DeferredTest {

    @Test
    public void testResolve() throws Exception {
        Deferred<String> def = new Deferred<String>();
        Promise<String> promise = def.getPromise();
        assertFalse("Initial Promise not resolved", promise.isDone());

        def.resolve("Hello");
        assertTrue("Promise resolved", promise.isDone());
        assertEquals("Value matches", "Hello", promise.getValue());
        assertNull("Failure is null", promise.getFailure());

        try {
            def.resolve("Again");
            fail("Already resolved didn't throw IllegalStateException");
        } catch (IllegalStateException e) {
            // suppress empty catch block warning
        }
    }

    @Test
    public void testResolveWithSuccess() throws Exception {
        Deferred<String> def = new Deferred<String>();
        Promise<String> promise = def.getPromise();

        Deferred<String> with = new Deferred<String>();
        Promise<Void> resolvedWith = def.resolveWith(with.getPromise());

        // If the specified Promise is successfully resolved,
        // the associated Promise is resolved with the value of the specified Promise.
        with.resolve("resolveWith");
        assertTrue("Promise resolved", promise.isDone());
        assertEquals("Value matches", "resolveWith", promise.getValue());

        // The returned Promise will be successfully resolved, with the value null,
        // if the associated Promise was resolved by the specified Promise.
        assertNull("resolveWith null", resolvedWith.getValue());
    }

    @Test
    public void testResolveWithAlreadyResolved() throws Exception {
        Deferred<String> def = new Deferred<String>();
        Deferred<String> with = new Deferred<String>();
        Promise<Void> resolvedWith = def.resolveWith(with.getPromise());

        // The returned Promise will be resolved with a failure of IllegalStateException
        // if the associated Promise was already resolved when the specified Promise was resolved.
        def.resolve("Already resolved");
        with.resolve("resolveWith");
        @SuppressWarnings({"not thrown", "all"})
        Throwable failure = resolvedWith.getFailure();
        assertTrue("resolveWith IllegalStateException", failure instanceof IllegalStateException);
    }

    @Test
    public void testResolveWithAlreadyFailed() throws Exception {
        Deferred<String> def = new Deferred<String>();
        Deferred<String> with = new Deferred<String>();
        Promise<Void> resolvedWith = def.resolveWith(with.getPromise());

        // The returned Promise will be resolved with a failure of IllegalStateException
        // if the associated Promise was already resolved when the specified Promise was resolved.
        def.resolve("Already resolved");
        with.fail(new Throwable("failed"));
        @SuppressWarnings({"not thrown", "all"})
        Throwable failure = resolvedWith.getFailure();
        assertTrue("resolveWith IllegalStateException", failure instanceof IllegalStateException);
    }

    @Test
    public void testResolveWithFailure() throws Exception {
        Deferred<String> def = new Deferred<String>();
        Promise<String> promise = def.getPromise();

        Deferred<String> def2 = new Deferred<String>();
        Promise<String> promise2 = def2.getPromise();
        Promise<Void> with = def.resolveWith(promise2);

        // If the specified Promise is resolved with a failure,
        // the associated Promise is resolved with the failure of the specified Promise.
        Exception failure = new Exception("resolveWithFailure");
        def2.fail(failure);
        assertTrue("Promise resolved", promise.isDone());
        assertEquals("Failure matches", failure, promise.getFailure());

        // The returned Promise will be successfully resolved, with the value null,
        // if the associated Promise was resolved by the specified Promise.
        assertNull("resolveWith null", with.getValue());
    }

    @Test
    public void testFail() throws Exception {
        Deferred<String> def = new Deferred<String>();
        Promise<String> promise = def.getPromise();
        Exception failure = new Exception("Oops");

        def.fail(failure);
        assertTrue("Promise resolved", promise.isDone());
        assertEquals("Failure matches", failure, promise.getFailure());

        try {
            promise.getValue();
            fail("getValue didn't throw InvocationTargetException");
        } catch (InvocationTargetException e) {
            assertEquals("Failure matches", failure, e.getCause());
        }

        try {
            def.fail(failure);
            fail("Already failed didn't throw IllegalStateException");
        } catch (IllegalStateException e) {
            assertNotNull(e);
        }
    }

}


text:
import * as React from 'react';
import { findDOMNode } from 'react-dom';
import { Box, Image, WithAnimation, Anchor } from 'ui';
import Overlay from './overlay';
import Relative from './relative';

export interface State {
  isVisible: boolean;
}

export interface Props extends React.HTMLProps<typeof CaseStudy> {
  image: string;
  title: string;
}

export default class CaseStudy extends React.Component<Props, State> {
  constructor() {
    super();
    this.handleScroll = this.handleScroll.bind(this);
    this.state = {
      isVisible: false,
    };
  }
  public componentDidMount() {
    if (typeof window !== 'undefined') {
      this.handleScroll();
      window.addEventListener('scroll', this.handleScroll);
    }
  }
  public componentWillUnmount() {
    if (typeof window !== 'undefined') {
      window.removeEventListener('scroll', this.handleScroll);
    }
  }
  public divRef: Element;
  public handleScroll() {
    const windowHeight = window ? window.innerHeight : 1000;
    const node = findDOMNode(this.divRef);
    if (node) {
      const isVisible = node.getBoundingClientRect().top < windowHeight - (windowHeight / 4);
      this.setState({
        isVisible,
      });
    }
  }
  public render() {
    const { image, title, id } = this.props;
    return (
      <Anchor path={`/case-study/${id}`} plain>

 { this.divRef = ref; }}>
          <WithAnimation duration={1000} {...this.state}>
            <Box pad="large">
              <Relative>
                <Overlay>

{title}

                </Overlay>
                <Image style={{ maxWidth: 700 }} imageSize="large" src={image} alt={title} />
              </Relative>
            </Box>
          </WithAnimation>

      </Anchor>
    );
  }
}


text:
git-shame
=========

This is unbaked. Check out the code for more info or try again later.