text:
package util.genome.kmer;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.*;

import util.DNAUtils;

public class UngappedKmer implements Kmer, Externalizable{
	private static final long serialVersionUID = 1L;

	private Map<String, Score> m_Words;
	private List<String> m_WordList;
	private final Collection<Integer> m_WordLens = new HashSet<Integer>();

	UngappedKmer(Map<String, Score> words, List<String> wordList){
		m_Words = words;
		m_WordList = wordList;
		for(String word : m_Words.keySet()){
			m_WordLens.add(word.length());
		}
	}

	@Override
	public int size(){
		return m_WordList.size();
	}

	@Override
	public boolean contains(String word){
		return m_Words.containsKey(word);
	}

	/**
	 * Returns the escore value of the given word
	 * @param word
	 * @return
	 */
	public double escore(String word){
		if(m_Words.containsKey(word)){
			return m_Words.get(word).ESCORE;
		}
		throw new NoSuchWordException("Does not contain word "+word);
	}

	@Override
	public double escore(String seq, int start, int end){
		return this.escore(seq.substring(start, end));
	}

	private int minWordLen(){
		int min = Integer.MAX_VALUE;
		for(int len : m_WordLens){
			if(len < min) min = len;
		}
		return min;
	}

	@Override
	public double[] escoreSequence(String sequence){
		if(sequence.length() < this.minWordLen()){
			throw new RuntimeException("Cannot escore sequence: "+sequence+". Sequence is shorter than minimum kmer word length: "+this.minWordLen()+".");
		}
		double[] scores = new double[sequence.length()];
		//initialize scores to -infinity
		for(int i=0; i<scores.length; i++){
			scores[i] = Double.NEGATIVE_INFINITY;
		}
		//score each word and assign that score to each contained base if it is greater than
		//the score currently assigned to that base
		for(int i=0; i<this.maxIndex(sequence); i++){
			List<String> words = this.wordsAt(sequence, i);
			for(String word : words){
				Double escore = this.escore(word);
				for(int j=i; j<i+word.length(); j++){
					if(scores[j] < escore){
						scores[j] = escore;
					}
				}
			}
		}
		return scores;
	}

	@Override
	public double[] escoreSequence(String sequence, int start, int end){
		int len = end - start;
		if(len < this.minWordLen()){
			throw new RuntimeException("Cannot escore sequence: "+sequence+" between "+start+" and "+end+". "+len+" is shorter than minimum kmer word length: "+this.minWordLen()+".");
		}
		double[] scores = new double[len];
		//initialize scores to -infinity
		for(int i=0; i<scores.length; i++){
			scores[i] = Double.NEGATIVE_INFINITY;
		}
		//score each word and assign that score to each contained base if it is greater than
		//the score currently assigned to that base
		for(int i=0; i<len-this.minWordLen()+1; i++){
			List<String> words = this.wordsAt(sequence, start + i, end);
			for(String word : words){
				Double escore = this.escore(word);
				for(int j=i; j<i+word.length(); j++){
					if(scores[j] < escore){
						scores[j] = escore;
					}
				}
			}
		}
		return scores;
	}

	@Override
	public int[] getWordLengths() {
		int[] lens = new int[m_WordLens.size()];
		int i = 0;
		for(Integer len : m_WordLens){
			lens[i] = len;
			++i;
		}
		return lens;
	}

	protected int maxIndex(String seq){
		return seq.length() - this.minWordLen() + 1;
	}

	protected List<String> wordsAt(String seq, int index, int max){
		List<String> words = new ArrayList<String>();
		for(int len : m_WordLens){
			if(index + len <= max){
				words.add(seq.substring(index, index+len));
			}
		}
		return words;
	}

	protected List<String> wordsAt(String seq, int index){
		List<String> words = new ArrayList<String>();
		for(int len : m_WordLens){
			if(index + len <= seq.length()){
				words.add(seq.substring(index, index+len));
			}
		}
		return words;
	}

	@Override
	public double intensity(String word) {
		if(m_Words.containsKey(word)){
			return m_Words.get(word).INTENSITY;
		}
		throw new NoSuchWordException("Cannot find intensity for word: "+word+". Word is not contained by this kmer.");
	}

	@Override
	public double[] intensitySequence(String sequence) {
		if(sequence.length() < this.minWordLen()){
			throw new RuntimeException("Cannot intensity score sequence: "+sequence+". Sequence is shorter than kmer word length: "+this.minWordLen()+".");
		}
		double[] scores = new double[sequence.length()];
		//initialize scores to -infinity
		for(int i=0; i<scores.length; i++){
			scores[i] = Double.NEGATIVE_INFINITY;
		}
		//score each word and assign that score to each contained base if it is greater than
		//that base's currently assigned score
		for(int i=0; i< this.maxIndex(sequence); i++){
			List<String> words = this.wordsAt(sequence, i);
			for(String word : words){
				double intensity = this.intensity(word);
				for(int j=i; j<i+word.length(); j++){
					if(scores[j] < intensity){
						scores[j] = intensity;
					}
				}
			}
		}
		return scores;
	}

	@Override
	public double zscore(String word) {
		if(m_Words.containsKey(word)){
			return m_Words.get(word).ZSCORE;
		}
		throw new NoSuchWordException("Cannot find zscore for word: "+word+". Word is not contained by this kmer.");
	}

	@Override
	public double[] zscoreSequence(String sequence) {
		if(sequence.length() < this.minWordLen()){
			throw new RuntimeException("Cannot zscore sequence: "+sequence+". Sequence is shorter than kmer word length: "+this.minWordLen()+".");
		}
		double[] scores = new double[sequence.length()];
		//initialize scores to -infinity
		for(int i=0; i<scores.length; i++){
			scores[i] = Double.NEGATIVE_INFINITY;
		}
		//score each word and assign that score to each contained base if it is
		//greater than the current score of that base
		for(int i=0; i<this.maxIndex(sequence); i++){
			List<String> words = this.wordsAt(sequence, i);
			for(String word : words){
				double zscore = this.zscore(word);
				for(int j=i; j<i+word.length(); j++){
					if(scores[j] < zscore){
						scores[j] = zscore;
					}
				}
			}
		}
		return scores;
	}

	@Override
	public Iterator<String> iterator() {
		return m_WordList.iterator();
	}

	@Override
	public Score getScore(String word) {
		return m_Words.get(word);
	}

	@Override
	public String getWord(int index) {
		return m_WordList.get(index);
	}

	/**
	 * Custom deserialization
	 */
	@Override
	public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
		//read number of entries
		int entries = in.readInt();
		m_WordList = new ArrayList<String>(entries);
		m_Words = new HashMap<String, Score>(entries*2);
		//read each entry
		while(--entries >= 0){
			String word = (String) in.readObject();
			m_WordLens.add(word.length());
			double escore = in.readDouble();
			double intensity = in.readDouble();
			double zscore = in.readDouble();
			Score s = new Score(escore, intensity, zscore);
			m_WordList.add(word);
			m_Words.put(word, s);
			m_Words.put(DNAUtils.reverseCompliment(word), s);
		}
	}

	/**
	 * Custom serialization for better space efficiency
	 */
	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		//write number of entries
		out.writeInt(m_WordList.size());
		//write each entry
		for(String word : m_WordList){
			out.writeObject(word);
			Score s = getScore(word);
			out.writeDouble(s.ESCORE);
			out.writeDouble(s.INTENSITY);
			out.writeDouble(s.ZSCORE);
		}
	}

}


text:
package io.druid.query.lookup;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
import com.metamx.emitter.EmittingLogger;
import io.druid.concurrent.Execs;
import io.druid.concurrent.LifecycleLock;
import io.druid.guice.ManageLifecycle;
import io.druid.guice.annotations.Json;
import io.druid.java.util.common.ISE;
import io.druid.java.util.common.lifecycle.LifecycleStart;
import io.druid.java.util.common.lifecycle.LifecycleStop;

import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport;
import java.util.function.Function;

/**
 * This class provide a basic {@link LookupExtractorFactory} references manager.
 * It allows basic operations fetching, listing, adding and deleting of {@link LookupExtractor} objects
 * It is be used by queries to fetch the lookup reference.
 * It is used by Lookup configuration manager to add/remove or list lookups configuration via HTTP or other protocols.
 * It does periodic snap shot of the list of lookup in order to bootstrap nodes after restart.
 */
@ManageLifecycle
public class LookupReferencesManager
{
  private static final EmittingLogger LOG = new EmittingLogger(LookupReferencesManager.class);

  // Lookups state (loaded/to-be-loaded/to-be-dropped etc) is managed by immutable LookupUpdateState instance.
  // Any update to state is done by creating updated LookupUpdateState instance and atomically setting that
  // into the ref here.
  // this allows getAllLookupsState() to provide a consistent view without using locks.
  @VisibleForTesting
  final AtomicReference<LookupUpdateState> stateRef = new AtomicReference<>();

  @VisibleForTesting
  final LookupSnapshotTaker lookupSnapshotTaker;

  @VisibleForTesting
  final LifecycleLock lifecycleLock = new LifecycleLock();

  @VisibleForTesting
  Thread mainThread;

  //for unit testing only
  private final boolean testMode;

  @Inject
  public LookupReferencesManager(LookupConfig lookupConfig, @Json ObjectMapper objectMapper)
  {
    this(lookupConfig, objectMapper, false);
  }

  @VisibleForTesting
  LookupReferencesManager(LookupConfig lookupConfig, ObjectMapper objectMapper, boolean testMode)
  {
    if (Strings.isNullOrEmpty(lookupConfig.getSnapshotWorkingDir())) {
      this.lookupSnapshotTaker = null;
    } else {
      this.lookupSnapshotTaker = new LookupSnapshotTaker(objectMapper, lookupConfig.getSnapshotWorkingDir());
    }

    this.testMode = testMode;
  }

  @LifecycleStart
  public void start()
  {
    if (!lifecycleLock.canStart()) {
      throw new ISE("can't start.");
    }

    try {
      LOG.info("LookupReferencesManager is starting.");

      loadSnapshotAndInitStateRef();

      if (!testMode) {
        mainThread = Execs.makeThread(
            "LookupReferencesManager-MainThread",
            new Runnable()
            {
              @Override
              public void run()
              {
                try {

                  if (!lifecycleLock.awaitStarted()) {
                    LOG.error("WTF! lifecycle not started, lookup update notices will not be handled.");
                    return;
                  }

                  while (!Thread.interrupted() && lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS)) {
                    try {
                      handlePendingNotices();
                      LockSupport.parkNanos(LookupReferencesManager.this, TimeUnit.MINUTES.toNanos(1));
                    }
                    catch (Throwable t) {
                      LOG.makeAlert(t, "Error occured while lookup notice handling.").emit();
                    }
                  }
                }
                catch (Throwable t) {
                  LOG.error(t, "Error while waiting for lifecycle start. lookup updates notices will not be handled");
                }
                finally {
                  LOG.info("Lookup Management loop exited, Lookup notices are not handled anymore.");
                }
              }
            },
            true
        );

        mainThread.start();
      }

      LOG.info("LookupReferencesManager is started.");
      lifecycleLock.started();
    }
    finally {
      lifecycleLock.exitStart();
    }
  }

  @VisibleForTesting
  void handlePendingNotices()
  {
    if (stateRef.get().pendingNotices.isEmpty()) {
      return;
    }

    @SuppressWarnings("ArgumentParameterSwap")
    LookupUpdateState swappedState = atomicallyUpdateStateRef(
        oldState -> new LookupUpdateState(oldState.lookupMap, ImmutableList.of(), oldState.pendingNotices)
    );

    Map<String, LookupExtractorFactoryContainer> lookupMap = new HashMap<>(swappedState.lookupMap);
    for (Notice notice : swappedState.noticesBeingHandled) {
      try {
        notice.handle(lookupMap);
      } catch (Exception ex) {
        LOG.error(ex, "Exception occured while handling lookup notice [%s].", notice);
        LOG.makeAlert("Exception occured while handling lookup notice, with message [%s].", ex.getMessage()).emit();
      }
    }

    takeSnapshot(lookupMap);

    ImmutableMap<String, LookupExtractorFactoryContainer> immutableLookupMap = ImmutableMap.copyOf(lookupMap);

    atomicallyUpdateStateRef(
        oldState -> new LookupUpdateState(immutableLookupMap, oldState.pendingNotices, ImmutableList.of())
    );
  }

  @LifecycleStop
  public void stop()
  {
    if (!lifecycleLock.canStop()) {
      throw new ISE("can't stop.");
    }

    LOG.info("LookupReferencesManager is stopping.");

    if (!testMode) {
      mainThread.interrupt();

      try {
        mainThread.join();
      }
      catch (InterruptedException ex) {
        throw new ISE("failed to stop, mainThread couldn't finish.");
      }
    }

    for (Map.Entry<String, LookupExtractorFactoryContainer> e : stateRef.get().lookupMap.entrySet()) {
      try {
        LOG.info("Closing lookup [%s]", e.getKey());
        if (!e.getValue().getLookupExtractorFactory().close()) {
          LOG.error("Failed to close lookup [%s].", e.getKey());
        }
      }
      catch (Exception ex) {
        LOG.error(ex, "Failed to close lookup [%s].", e.getKey());
      }
    }

    LOG.info("LookupReferencesManager is stopped.");
  }

  public void add(String lookupName, LookupExtractorFactoryContainer lookupExtractorFactoryContainer)
  {
    Preconditions.checkState(lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS));
    addNotice(new LoadNotice(lookupName, lookupExtractorFactoryContainer));
  }

  public void remove(String lookupName)
  {
    Preconditions.checkState(lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS));
    addNotice(new DropNotice(lookupName));
  }

  private void addNotice(Notice notice)
  {
    atomicallyUpdateStateRef(
        oldState -> {
          if (oldState.pendingNotices.size() > 10000) { //don't let pendingNotices grow indefinitely
            throw new ISE("There are too many [%d] pendingNotices.", oldState.pendingNotices.size());
          }

          ImmutableList.Builder<Notice> builder = ImmutableList.builder();
          builder.addAll(oldState.pendingNotices);
          builder.add(notice);

          return new LookupUpdateState(
              oldState.lookupMap, builder.build(), oldState.noticesBeingHandled

          );
        }
    );
    LockSupport.unpark(mainThread);
  }

  @Nullable
  public LookupExtractorFactoryContainer get(String lookupName)
  {
    Preconditions.checkState(lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS));
    return stateRef.get().lookupMap.get(lookupName);
  }

  // Note that this should ensure that "toLoad" and "toDrop" are disjoint.
  public LookupsState<LookupExtractorFactoryContainer> getAllLookupsState()
  {
    Preconditions.checkState(lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS));

    LookupUpdateState lookupUpdateState = stateRef.get();

    Map<String, LookupExtractorFactoryContainer> lookupsToLoad = new HashMap<>();
    Set<String> lookupsToDrop = new HashSet<>();

    updateToLoadAndDrop(lookupUpdateState.noticesBeingHandled, lookupsToLoad, lookupsToDrop);
    updateToLoadAndDrop(lookupUpdateState.pendingNotices, lookupsToLoad, lookupsToDrop);

    return new LookupsState<>(lookupUpdateState.lookupMap, lookupsToLoad, lookupsToDrop);
  }

  private void updateToLoadAndDrop(List<Notice> notices, Map<String, LookupExtractorFactoryContainer> lookupsToLoad, Set<String> lookupsToDrop)
  {
    for (Notice notice : notices) {
      if (notice instanceof LoadNotice) {
        LoadNotice loadNotice = (LoadNotice) notice;
        lookupsToLoad.put(loadNotice.lookupName, loadNotice.lookupExtractorFactoryContainer);
        lookupsToDrop.remove(loadNotice.lookupName);
      } else if (notice instanceof DropNotice) {
        DropNotice dropNotice = (DropNotice) notice;
        lookupsToDrop.add(dropNotice.lookupName);
        lookupsToLoad.remove(dropNotice.lookupName);
      } else {
        throw new ISE("Unknown Notice type [%s].", notice.getClass().getName());
      }
    }
  }

  private void takeSnapshot(Map<String, LookupExtractorFactoryContainer> lookupMap)
  {
    if (lookupSnapshotTaker != null) {
      List<LookupBean> lookups = new ArrayList<>(lookupMap.size());
      for (Map.Entry<String, LookupExtractorFactoryContainer> e : lookupMap.entrySet()) {
        lookups.add(new LookupBean(e.getKey(), null, e.getValue()));
      }

      lookupSnapshotTaker.takeSnapshot(lookups);
    }
  }

  private void loadSnapshotAndInitStateRef()
  {
    if (lookupSnapshotTaker != null) {
      ImmutableMap.Builder<String, LookupExtractorFactoryContainer> builder = ImmutableMap.builder();

      final List<LookupBean> lookupBeanList = lookupSnapshotTaker.pullExistingSnapshot();
      for (LookupBean lookupBean : lookupBeanList) {
        LookupExtractorFactoryContainer container = lookupBean.getContainer();

        if (container.getLookupExtractorFactory().start()) {
          builder.put(lookupBean.getName(), container);
        } else {
          throw new ISE("Failed to start lookup [%s]:[%s]", lookupBean.getName(), container);
        }
      }

      stateRef.set(new LookupUpdateState(builder.build(), ImmutableList.of(), ImmutableList.of()));
    } else {
      stateRef.set(new LookupUpdateState(ImmutableMap.of(), ImmutableList.of(), ImmutableList.of()));
    }
  }

  private LookupUpdateState atomicallyUpdateStateRef(Function<LookupUpdateState, LookupUpdateState> fn)
  {
    while(true) {
      LookupUpdateState old = stateRef.get();
      LookupUpdateState newState = fn.apply(old);
      if (stateRef.compareAndSet(old, newState)) {
        return newState;
      }
    }
  }

  @VisibleForTesting
  interface Notice
  {
    void handle(Map<String, LookupExtractorFactoryContainer> lookupMap);
  }

  private static class LoadNotice implements Notice
  {
    private final String lookupName;
    private final LookupExtractorFactoryContainer lookupExtractorFactoryContainer;

    public LoadNotice(String lookupName, LookupExtractorFactoryContainer lookupExtractorFactoryContainer)
    {
      this.lookupName = lookupName;
      this.lookupExtractorFactoryContainer = lookupExtractorFactoryContainer;
    }

    @Override
    public void handle(Map<String, LookupExtractorFactoryContainer> lookupMap)
    {
      LookupExtractorFactoryContainer old = lookupMap.get(lookupName);
      if (old != null && !lookupExtractorFactoryContainer.replaces(old)) {
        LOG.warn(
            "got notice to load lookup [%s] that can't replace existing [%s].",
            lookupExtractorFactoryContainer,
            old
        );
        return;
      }

      if (!lookupExtractorFactoryContainer.getLookupExtractorFactory().start()) {
        throw new ISE(
            "start method returned false for lookup [%s]:[%s]",
            lookupName,
            lookupExtractorFactoryContainer
        );
      }

      old = lookupMap.put(lookupName, lookupExtractorFactoryContainer);

      LOG.debug("Loaded lookup [%s] with spec [%s].", lookupName, lookupExtractorFactoryContainer);

      if (old != null) {
        if (!old.getLookupExtractorFactory().close()) {
          throw new ISE("close method returned false for lookup [%s]:[%s]", lookupName, old);
        }
      }
    }

    @Override
    public String toString()
    {
      return "LoadNotice{" +
             "lookupName='" + lookupName + '\'' +
             ", lookupExtractorFactoryContainer=" + lookupExtractorFactoryContainer +
             '}';
    }
  }

  private static class DropNotice implements Notice
  {
    private final String lookupName;

    public DropNotice(String lookupName)
    {
      this.lookupName = lookupName;
    }

    @Override
    public void handle(Map<String, LookupExtractorFactoryContainer> lookupMap)
    {
      final LookupExtractorFactoryContainer lookupExtractorFactoryContainer = lookupMap.remove(lookupName);

      if (lookupExtractorFactoryContainer != null) {
        LOG.debug("Removed lookup [%s] with spec [%s].", lookupName, lookupExtractorFactoryContainer);

        if (!lookupExtractorFactoryContainer.getLookupExtractorFactory().close()) {
          throw new ISE(
              "close method returned false for lookup [%s]:[%s]",
              lookupName,
              lookupExtractorFactoryContainer
          );
        }
      }
    }

    @Override
    public String toString()
    {
      return "DropNotice{" +
             "lookupName='" + lookupName + '\'' +
             '}';
    }
  }

  private static class LookupUpdateState
  {
    private final ImmutableMap<String, LookupExtractorFactoryContainer> lookupMap;
    private final ImmutableList<Notice> pendingNotices;
    private final ImmutableList<Notice> noticesBeingHandled;

    LookupUpdateState(
        ImmutableMap<String, LookupExtractorFactoryContainer> lookupMap,
        ImmutableList<Notice> pendingNotices,
        ImmutableList<Notice> noticesBeingHandled
    )
    {
      this.lookupMap = lookupMap;
      this.pendingNotices = pendingNotices;
      this.noticesBeingHandled = noticesBeingHandled;
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package riak

import (
	"encoding/json"
	"fmt"
	"github.com/tpjg/goriakpbc/pb"
)

// An object to build a MapReduce job similar to how the Ruby client can
// build it by adding different stages.
type MapReduce struct {
	client  *Client
	inputs  [][]string
	index   string
	phases  []string
	request string
}

func (c *Client) MapReduce() *MapReduce {
	return &MapReduce{client: c, inputs: make([][]string, 0), phases: make([]string, 0), request: ""}
}

func (mr *MapReduce) Add(bucket string, key string) (err error) {
	if mr.index != "" {
		return BadMapReduceInputs
	}
	mr.inputs = append(mr.inputs, []string{bucket, key})
	return
}

// Add a whole bucket as input. Note that this ONLY works on buckets that have secondary indexes (2i) enabled since
// listing keys on a bucket without using indexes is dangerous on production clusters.
func (mr *MapReduce) AddBucket(bucket string) (err error) {
	if len(mr.inputs) > 0 || mr.index != "" {
		return BadMapReduceInputs
	}
	mr.index = fmt.Sprintf(`"bucket":"%v","index":"$bucket","key":"%v"`, bucket, bucket)
	return
}

// Add a range of keys from one bucket using secondary indexes.
func (mr *MapReduce) AddBucketRange(bucket string, start string, end string) (err error) {
	if len(mr.inputs) > 0 || mr.index != "" {
		return BadMapReduceInputs
	}
	mr.index = fmt.Sprintf(`"bucket":"%v","index":"$key","start":"%v","end":"%v"`, bucket, start, end)
	return
}

// Add a keys using a secondary index.
func (mr *MapReduce) AddIndex(bucket string, index string, key string) (err error) {
	if len(mr.inputs) > 0 || mr.index != "" {
		return BadMapReduceInputs
	}
	mr.index = fmt.Sprintf(`"bucket":"%v","index":"%v","key":"%v","end":"%v"`, bucket, index, key)
	return
}

// Add a range of keys using a secondary index.
func (mr *MapReduce) AddIndexRange(bucket string, index string, start string, end string) (err error) {
	if len(mr.inputs) > 0 || mr.index != "" {
		return BadMapReduceInputs
	}
	mr.index = fmt.Sprintf(`"bucket":"%v","index":"%v","start":"%v","end":"%v"`, bucket, index, start, end)
	return
}

func (mr *MapReduce) LinkBucket(name string, keep bool) {
	link := `{"link":{"bucket":"` + name + `", "tag":"_","keep":`
	if keep {
		link = link + "true}}"
	} else {
		link = link + "false}}"
	}
	mr.phases = append(mr.phases, link)
}

func (mr *MapReduce) Map(fun string, keep bool) {
	m := `{"map":{"language":"javascript","keep":`
	if keep {
		m = m + "true,"
	} else {
		m = m + "false,"
	}
	m = m + `"source":"` + fun + `"}}`
	mr.phases = append(mr.phases, m)
}

func (mr *MapReduce) Reduce(fun string, keep bool) {
	m := `{"reduce":{"language":"javascript","keep":`
	if keep {
		m = m + "true,"
	} else {
		m = m + "false,"
	}
	m = m + `"source":"` + fun + `"}}`
	mr.phases = append(mr.phases, m)
}

func (mr *MapReduce) MapErlang(module string, fun string, keep bool) {
	m := `{"map":{"language":"erlang","module":"` + module + `","function":"` + fun + `","keep":`
	if keep {
		m = m + `true`
	} else {
		m = m + `false`
	}
	m = m + `}}`
	mr.phases = append(mr.phases, m)
}

func (mr *MapReduce) ReduceErlang(module string, fun string, arg string, keep bool) {
	m := `{"reduce":{"language":"erlang","module":"` + module + `","function":"` + fun + `"`
	if arg != "" {
		m = m + `,"arg":` + arg + `,"keep":`
	} else {
		m = m + `,"keep":`
	}
	if keep {
		m = m + `true`
	} else {
		m = m + `false`
	}
	m = m + `}}`
	mr.phases = append(mr.phases, m)
}

func (mr *MapReduce) MapObjectValue(keep bool) {
	//{"map":{"language":"erlang","module":"riak_kv_mapreduce","function":"map_object_value"}}
	mr.MapErlang("riak_kv_mapreduce", "map_object_value", keep)
}

func (mr *MapReduce) ReduceObjectCount(keep bool) {
	mr.ReduceErlang("riak_kv_mapreduce", "reduce_count_inputs", `{"do_prereduce":true}`, keep)
}

// Generate the Query string
func (mr *MapReduce) Query() (query []byte, err error) {
	// Check because either a whole bucket should be added or only inputs
	if mr.index != "" && len(mr.inputs) > 0 {
		err = BadMapReduceInputs
		return
	}
	q := ``
	if mr.index == "" {
		inputs, err := json.Marshal(mr.inputs)
		if err != nil {
			return nil, err
		}
		q = `{"inputs":` + string(inputs) + `, "query":[`
	} else {
		q = `{"inputs":{` + mr.index + `}, "query":[`
	}
	for i, s := range mr.phases {
		if i > 0 {
			q = q + ","
		}
		q = q + s
	}
	q = q + "]}"
	return []byte(q), nil
}

func (mr *MapReduce) Run() (resp [][]byte, err error) {
	query, err := mr.Query()
	if err != nil {
		return nil, err
	}
	req := &pb.RpbMapRedReq{
		Request:     query,
		ContentType: []byte("application/json"),
	}
	err, conn := mr.client.request(req, rpbMapRedReq)
	if err != nil {
		return nil, err
	}
	resp, err = mr.client.mr_response(conn)
	if err != nil {
		return nil, err
	}
	return
}

// Run a MapReduce query
func (c *Client) RunMapReduce(query string) (resp [][]byte, err error) {
	req := &pb.RpbMapRedReq{
		Request:     []byte(query),
		ContentType: []byte("application/json"),
	}
	err, conn := c.request(req, rpbMapRedReq)
	if err != nil {
		return nil, err
	}
	resp, err = c.mr_response(conn)
	if err != nil {
		return nil, err
	}
	return
}


text:
package akka.actor.dungeon

import scala.annotation.tailrec
import scala.util.control.NonFatal
import scala.collection.immutable
import akka.actor._
import akka.serialization.SerializationExtension
import akka.util.{ Unsafe, Helpers }
import akka.serialization.SerializerWithStringManifest
import java.util.Optional

private[akka] object Children {
  val GetNobody = () ⇒ Nobody
}

private[akka] trait Children { this: ActorCell ⇒

  import ChildrenContainer._

  @volatile
  private var _childrenRefsDoNotCallMeDirectly: ChildrenContainer = EmptyChildrenContainer

  def childrenRefs: ChildrenContainer =
    Unsafe.instance.getObjectVolatile(this, AbstractActorCell.childrenOffset).asInstanceOf[ChildrenContainer]

  final def children: immutable.Iterable[ActorRef] = childrenRefs.children
  final def getChildren(): java.lang.Iterable[ActorRef] =
    scala.collection.JavaConverters.asJavaIterableConverter(children).asJava

  final def child(name: String): Option[ActorRef] = Option(getChild(name))
  final def getChild(name: String): ActorRef = childrenRefs.getByName(name) match {
    case Some(s: ChildRestartStats) ⇒ s.child
    case _ ⇒ null
  }
  def findChild(name: String): Optional[ActorRef] = Optional.ofNullable(getChild(name))

  def actorOf(props: Props): ActorRef =
    makeChild(this, props, randomName(), async = false, systemService = false)
  def actorOf(props: Props, name: String): ActorRef =
    makeChild(this, props, checkName(name), async = false, systemService = false)
  private[akka] def attachChild(props: Props, systemService: Boolean): ActorRef =
    makeChild(this, props, randomName(), async = true, systemService = systemService)
  private[akka] def attachChild(props: Props, name: String, systemService: Boolean): ActorRef =
    makeChild(this, props, checkName(name), async = true, systemService = systemService)

  @volatile private var _functionRefsDoNotCallMeDirectly = Map.empty[String, FunctionRef]
  private def functionRefs: Map[String, FunctionRef] =
    Unsafe.instance.getObjectVolatile(this, AbstractActorCell.functionRefsOffset).asInstanceOf[Map[String, FunctionRef]]

  private[akka] def getFunctionRefOrNobody(name: String, uid: Int = ActorCell.undefinedUid): InternalActorRef =
    functionRefs.getOrElse(name, Children.GetNobody()) match {
      case f: FunctionRef ⇒
        if (uid == ActorCell.undefinedUid || f.path.uid == uid) f else Nobody
      case other ⇒
        other
    }

  private[akka] def addFunctionRef(f: (ActorRef, Any) ⇒ Unit, name: String = ""): FunctionRef = {
    val r = randomName(new java.lang.StringBuilder("$$"))
    val n = if (name != "") s"$r-$name" else r
    val childPath = new ChildActorPath(self.path, n, ActorCell.newUid())
    val ref = new FunctionRef(childPath, provider, system.eventStream, f)

    @tailrec def rec(): Unit = {
      val old = functionRefs
      val added = old.updated(childPath.name, ref)
      if (!Unsafe.instance.compareAndSwapObject(this, AbstractActorCell.functionRefsOffset, old, added)) rec()
    }
    rec()

    ref
  }

  private[akka] def removeFunctionRef(ref: FunctionRef): Boolean = {
    require(ref.path.parent eq self.path, "trying to remove FunctionRef from wrong ActorCell")
    val name = ref.path.name
    @tailrec def rec(): Boolean = {
      val old = functionRefs
      if (!old.contains(name)) false
      else {
        val removed = old - name
        if (!Unsafe.instance.compareAndSwapObject(this, AbstractActorCell.functionRefsOffset, old, removed)) rec()
        else {
          ref.stop()
          true
        }
      }
    }
    rec()
  }

  protected def stopFunctionRefs(): Unit = {
    val refs = Unsafe.instance.getAndSetObject(this, AbstractActorCell.functionRefsOffset, Map.empty).asInstanceOf[Map[String, FunctionRef]]
    refs.valuesIterator.foreach(_.stop())
  }

  @volatile private var _nextNameDoNotCallMeDirectly = 0L
  final protected def randomName(sb: java.lang.StringBuilder): String = {
    val num = Unsafe.instance.getAndAddLong(this, AbstractActorCell.nextNameOffset, 1)
    Helpers.base64(num, sb)
  }
  final protected def randomName(): String = {
    val num = Unsafe.instance.getAndAddLong(this, AbstractActorCell.nextNameOffset, 1)
    Helpers.base64(num)
  }

  final def stop(actor: ActorRef): Unit = {
    if (childrenRefs.getByRef(actor).isDefined) {
      @tailrec def shallDie(ref: ActorRef): Boolean = {
        val c = childrenRefs
        swapChildrenRefs(c, c.shallDie(ref)) || shallDie(ref)
      }

      if (actor match {
        case r: RepointableRef ⇒ r.isStarted
        case _ ⇒ true
      }) shallDie(actor)
    }
    actor.asInstanceOf[InternalActorRef].stop()
  }

  /*
   * low level CAS helpers
   */
  @inline private final def swapChildrenRefs(oldChildren: ChildrenContainer, newChildren: ChildrenContainer): Boolean =
    Unsafe.instance.compareAndSwapObject(this, AbstractActorCell.childrenOffset, oldChildren, newChildren)

  @tailrec final def reserveChild(name: String): Boolean = {
    val c = childrenRefs
    swapChildrenRefs(c, c.reserve(name)) || reserveChild(name)
  }

  @tailrec final protected def unreserveChild(name: String): Boolean = {
    val c = childrenRefs
    swapChildrenRefs(c, c.unreserve(name)) || unreserveChild(name)
  }

  @tailrec final def initChild(ref: ActorRef): Option[ChildRestartStats] = {
    val cc = childrenRefs
    cc.getByName(ref.path.name) match {
      case old @ Some(_: ChildRestartStats) ⇒ old.asInstanceOf[Option[ChildRestartStats]]
      case Some(ChildNameReserved) ⇒
        val crs = ChildRestartStats(ref)
        val name = ref.path.name
        if (swapChildrenRefs(cc, cc.add(name, crs))) Some(crs) else initChild(ref)
      case None ⇒ None
    }
  }

  @tailrec final protected def setChildrenTerminationReason(reason: ChildrenContainer.SuspendReason): Boolean = {
    childrenRefs match {
      case c: ChildrenContainer.TerminatingChildrenContainer ⇒
        swapChildrenRefs(c, c.copy(reason = reason)) || setChildrenTerminationReason(reason)
      case _ ⇒ false
    }
  }

  final protected def setTerminated(): Unit = Unsafe.instance.putObjectVolatile(this, AbstractActorCell.childrenOffset, TerminatedChildrenContainer)

  /*
   * ActorCell-internal API
   */

  protected def isNormal = childrenRefs.isNormal

  protected def isTerminating = childrenRefs.isTerminating

  protected def waitingForChildrenOrNull = childrenRefs match {
    case TerminatingChildrenContainer(_, _, w: WaitingForChildren) ⇒ w
    case _ ⇒ null
  }

  protected def suspendChildren(exceptFor: Set[ActorRef] = Set.empty): Unit =
    childrenRefs.stats foreach {
      case ChildRestartStats(child, _, _) if !(exceptFor contains child) ⇒ child.asInstanceOf[InternalActorRef].suspend()
      case _ ⇒
    }

  protected def resumeChildren(causedByFailure: Throwable, perp: ActorRef): Unit =
    childrenRefs.stats foreach {
      case ChildRestartStats(child: InternalActorRef, _, _) ⇒
        child.resume(if (perp == child) causedByFailure else null)
    }

  def getChildByName(name: String): Option[ChildStats] = childrenRefs.getByName(name)

  protected def getChildByRef(ref: ActorRef): Option[ChildRestartStats] = childrenRefs.getByRef(ref)

  protected def getAllChildStats: immutable.Iterable[ChildRestartStats] = childrenRefs.stats

  override def getSingleChild(name: String): InternalActorRef =
    if (name.indexOf('#') == -1) {
      // optimization for the non-uid case
      getChildByName(name) match {
        case Some(crs: ChildRestartStats) ⇒ crs.child.asInstanceOf[InternalActorRef]
        case _ ⇒ getFunctionRefOrNobody(name)
      }
    } else {
      val (childName, uid) = ActorCell.splitNameAndUid(name)
      getChildByName(childName) match {
        case Some(crs: ChildRestartStats) if uid == ActorCell.undefinedUid || uid == crs.uid ⇒
          crs.child.asInstanceOf[InternalActorRef]
        case _ ⇒ getFunctionRefOrNobody(childName, uid)
      }
    }

  protected def removeChildAndGetStateChange(child: ActorRef): Option[SuspendReason] = {
    @tailrec def removeChild(ref: ActorRef): ChildrenContainer = {
      val c = childrenRefs
      val n = c.remove(ref)
      if (swapChildrenRefs(c, n)) n else removeChild(ref)
    }

    childrenRefs match { // The match must be performed BEFORE the removeChild
      case TerminatingChildrenContainer(_, _, reason) ⇒
        removeChild(child) match {
          case _: TerminatingChildrenContainer ⇒ None
          case _ ⇒ Some(reason)
        }
      case _ ⇒
        removeChild(child)
        None
    }
  }

  /*
   * Private helpers
   */

  private def checkName(name: String): String = {
    name match {
      case null ⇒ throw InvalidActorNameException("actor name must not be null")
      case "" ⇒ throw InvalidActorNameException("actor name must not be empty")
      case _ ⇒
        ActorPath.validatePathElement(name)
        name
    }
  }

  private def makeChild(cell: ActorCell, props: Props, name: String, async: Boolean, systemService: Boolean): ActorRef = {
    if (cell.system.settings.SerializeAllCreators && !systemService && props.deploy.scope != LocalScope)
      try {
        val ser = SerializationExtension(cell.system)
        props.args forall (arg ⇒
          arg == null ||
            arg.isInstanceOf[NoSerializationVerificationNeeded] ||
            {
              val o = arg.asInstanceOf[AnyRef]
              val serializer = ser.findSerializerFor(o)
              val bytes = serializer.toBinary(o)
              serializer match {
                case ser2: SerializerWithStringManifest ⇒
                  val manifest = ser2.manifest(o)
                  ser.deserialize(bytes, serializer.identifier, manifest).get != null
                case _ ⇒
                  ser.deserialize(bytes, arg.getClass).get != null
              }
            })
      } catch {
        case NonFatal(e) ⇒ throw new IllegalArgumentException(s"pre-creation serialization check failed at [${cell.self.path}/$name]", e)
      }
    /*
     * in case we are currently terminating, fail external attachChild requests
     * (internal calls cannot happen anyway because we are suspended)
     */
    if (cell.childrenRefs.isTerminating) throw new IllegalStateException("cannot create children while terminating or terminated")
    else {
      reserveChild(name)
      // this name will either be unreserved or overwritten with a real child below
      val actor =
        try {
          val childPath = new ChildActorPath(cell.self.path, name, ActorCell.newUid())
          cell.provider.actorOf(cell.systemImpl, props, cell.self, childPath,
            systemService = systemService, deploy = None, lookupDeploy = true, async = async)
        } catch {
          case e: InterruptedException ⇒
            unreserveChild(name)
            Thread.interrupted() // clear interrupted flag before throwing according to java convention
            throw e
          case NonFatal(e) ⇒
            unreserveChild(name)
            throw e
        }
      // mailbox==null during RoutedActorCell constructor, where suspends are queued otherwise
      if (mailbox ne null) for (_ ← 1 to mailbox.suspendCount) actor.suspend()
      initChild(actor)
      actor.start()
      actor
    }
  }

}


text:
import * as React from 'react';
import { StandardProps, Omit } from '..';
import { HiddenProps } from '../Hidden/Hidden';
import { Breakpoint } from '../styles/createBreakpoints';

export type GridItemsAlignment = 'flex-start' | 'center' | 'flex-end' | 'stretch' | 'baseline';

export type GridContentAlignment = 'stretch' | 'center' | 'flex-start' | 'flex-end' |'space-between' | 'space-around';

export type GridDirection = 'row' | 'row-reverse' | 'column' | 'column-reverse';

export type GridSpacing = 0 | 8 | 16 | 24 | 40;

export type GridJustification =
  | 'flex-start'
  | 'center'
  | 'flex-end'
  | 'space-between'
  | 'space-around';

export type GridWrap = 'nowrap' | 'wrap' | 'wrap-reverse';

export type GridSize = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12;

export interface GridProps extends StandardProps<
  React.HTMLAttributes<HTMLElement> & Partial<Record<Breakpoint, boolean | GridSize>>,
  GridClassKey,
  'hidden'
> {
  component?: string | React.ComponentType<Omit<GridProps, StrippedProps>>;
  container?: boolean;
  item?: boolean;
  alignItems?: GridItemsAlignment;
  alignContent?: GridContentAlignment;
  direction?: GridDirection;
  spacing?: GridSpacing;
  hidden?: HiddenProps;
  justify?: GridJustification;
  wrap?: GridWrap;
}

export type GridClassKey =
  | 'typeContainer'
  | 'typeItem'
  | 'direction-xs-column'
  | 'direction-xs-column-reverse'
  | 'direction-xs-row-reverse'
  | 'wrap-xs-nowrap'
  | 'wrap-xs-wrap-reverse'
  | 'align-items-xs-center'
  | 'align-items-xs-flex-start'
  | 'align-items-xs-flex-end'
  | 'align-items-xs-baseline'
  | 'align-content-xs-center'
  | 'align-content-xs-flex-start'
  | 'align-content-xs-flex-end'
  | 'align-content-xs-space-between'
  | 'align-content-xs-space-around'
  | 'justify-xs-center'
  | 'justify-xs-flex-end'
  | 'justify-xs-space-between'
  | 'justify-xs-space-around'
  | 'spacing-xs-8'
  | 'spacing-xs-16'
  | 'spacing-xs-24'
  | 'spacing-xs-40'
  | 'grid-xs'
  | 'grid-xs-1'
  | 'grid-xs-2'
  | 'grid-xs-3'
  | 'grid-xs-4'
  | 'grid-xs-5'
  | 'grid-xs-6'
  | 'grid-xs-7'
  | 'grid-xs-8'
  | 'grid-xs-9'
  | 'grid-xs-10'
  | 'grid-xs-11'
  | 'grid-xs-12'
  ;

declare const Grid: React.ComponentType<GridProps>;

export default Grid;

type StrippedProps =
  | 'classes'
  | 'className'
  | 'component'
  | 'container'
  | 'item'
  | 'alignContent'
  | 'alignItems'
  | 'direction'
  | 'spacing'
  | 'hidden'
  | 'justify'
  | 'wrap'
  | 'xs'
  | 'sm'
  | 'md'
  | 'lg'
  | 'xl'
  ;


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background">
        <shape>
            <solid android:color="#7dffffff" />
            <size android:height="2dp" />
            <corners android:radius="2dp" />
        </shape>
    </item>
    <item android:id="@android:id/secondaryProgress">
        <clip>
            <shape>
                <solid android:color="#ffffffff" />
                <size android:height="2dp" />
                <corners android:radius="2dp" />
            </shape>
        </clip>
    </item>
    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <solid android:color="#FF7000" />
                <size android:height="2dp" />
                <corners android:radius="2dp" />
            </shape>
        </clip>
    </item>
</layer-list>


text:
@echo off

python reviewScraper


text:
<?php

namespace Cubiche\Core\Async\Tests\Units\Promise;

/**
 * Deferred Tests class.
 *
 * @author Ivannis Suárez Jerez <ivannis.suarez@gmail.com>
 * @author Karel Osorio Ramírez <osorioramirez@gmail.com>
 */
class DeferredTests extends DeferredInterfaceTestCase
{
}


text:
layout: post
title: The race
categories: comics then-this-happened
---
![the race](/public/images/may-20-2017-comic.png)


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.12.11 at 03:15:38 PM CET
//

package com.unalsoft.elitefle.entity.xml;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

/**
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "element"
})
@XmlRootElement(name = "referent")
public class Referent extends ElementXML {

    @XmlAttribute
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    protected String type;
    @XmlAttribute(name = "sous-type")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    protected String sousType;
    @XmlAttribute(required = true)
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlID
    protected String idn;
    protected List<Element> element;

    public Referent() {
        this.tag = "referent";
        this.referent = true;
    }

    /**
     * Gets the value of the type property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getType() {
        return type;
    }

    /**
     * Sets the value of the type property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setType(String value) {
        this.type = value;
    }

    /**
     * Gets the value of the sousType property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getSousType() {
        return sousType;
    }

    /**
     * Sets the value of the sousType property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setSousType(String value) {
        this.sousType = value;
    }

    /**
     * Gets the value of the idn property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getIdn() {
        return idn;
    }

    /**
     * Sets the value of the idn property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setIdn(String value) {
        this.idn = value;
    }

    /**
     * Gets the value of the elem property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the elem property.

     * For example, to add a new item, do as follows:
     *

     *    getElement().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link Element }
     *
     *
     */
    public List<Element> getElement() {
        if (element == null) {
            element = new ArrayList<Element>();
        }
        return this.element;
    }

}


text:
#ifndef SVGStyledElement_h
#define SVGStyledElement_h

#if ENABLE(SVG)
#include "CSSPropertyNames.h"
#include "SVGAnimatedString.h"
#include "SVGLocatable.h"
#include "SVGStylable.h"
#include <wtf/HashSet.h>

namespace WebCore {

void mapAttributeToCSSProperty(HashMap<AtomicStringImpl*, CSSPropertyID>* propertyNameToIdMap, const QualifiedName& attrName);

class SVGStyledElement : public SVGElement,
                         public SVGStylable {
public:
    virtual ~SVGStyledElement();

    virtual String title() const;

    bool hasRelativeLengths() const { return !m_elementsWithRelativeLengths.isEmpty(); }

    virtual bool supportsMarkers() const { return false; }

    virtual PassRefPtr<CSSValue> getPresentationAttribute(const String& name);

    bool isKnownAttribute(const QualifiedName&);

    bool instanceUpdatesBlocked() const;
    void setInstanceUpdatesBlocked(bool);

    bool hasPendingResources() const;
    void setHasPendingResources();
    void clearHasPendingResourcesIfPossible();

    virtual void animatedPropertyTypeForAttribute(const QualifiedName&, Vector<AnimatedPropertyType>&);
    static bool isAnimatableCSSProperty(const QualifiedName&);

    virtual AffineTransform localCoordinateSpaceTransform(SVGLocatable::CTMScope) const;

    virtual CSSStyleDeclaration* style() { return StyledElement::style(); }
    virtual bool needsPendingResourceHandling() const { return true; }

protected:
    SVGStyledElement(const QualifiedName&, Document*, ConstructionType = CreateSVGElement);
    virtual bool rendererIsNeeded(const NodeRenderingContext&);

    virtual void parseAttribute(const Attribute&) OVERRIDE;
    virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
    virtual void collectStyleForAttribute(const Attribute&, StylePropertySet*) OVERRIDE;
    virtual void svgAttributeChanged(const QualifiedName&);

    virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
    virtual void removedFrom(ContainerNode*) OVERRIDE;
    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);

    static CSSPropertyID cssPropertyIdForSVGAttributeName(const QualifiedName&);
    void updateRelativeLengthsInformation() { updateRelativeLengthsInformation(selfHasRelativeLengths(), this); }
    void updateRelativeLengthsInformation(bool hasRelativeLengths, SVGStyledElement*);

    virtual bool selfHasRelativeLengths() const { return false; }
    virtual void buildPendingResource() { }

private:
    virtual bool isStyled() const { return true; }

    virtual bool isKeyboardFocusable(KeyboardEvent*) const;
    virtual bool isMouseFocusable() const;

    void buildPendingResourcesIfNeeded();

    HashSet<SVGStyledElement*> m_elementsWithRelativeLengths;

    BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGStyledElement)
        DECLARE_ANIMATED_STRING(ClassName, className)
    END_DECLARE_ANIMATED_PROPERTIES
};

inline SVGStyledElement* toSVGStyledElement(Node* node)
{
    ASSERT(!node || (node->isStyledElement() && node->isSVGElement()));
    return static_cast<SVGStyledElement*>(node);
}

} // namespace WebCore

#endif // ENABLE(SVG)
#endif // SVGStyledElement


text:
package org.camunda.bpm.engine.delegate;

/**
 *
 * @author Daniel Meyer
 * @author Roman Smirnov
 * @author Sebastian Menski
 *
 */
public interface BaseDelegateExecution extends VariableScope {

  /** Unique id of this path of execution that can be used as a handle to provide external signals back into the engine after wait states. */
  String getId();

  /** The {@link ExecutionListener#EVENTNAME_START event name} in case this execution is passed in for an {@link ExecutionListener}  */
  String getEventName();

  /** The business key for the root execution (e.g. process instance).
   */
  String getBusinessKey();

}


text:
class MainApp : public wxApp
{
public:
    MainApp() {}
    virtual ~MainApp() {}

    virtual bool OnInit() {
        // Add the common image handlers
        wxImage::AddHandler( new wxPNGHandler );
        wxImage::AddHandler( new wxJPEGHandler );

        SetAppName("ColorGrab");

        MainFrame *mainFrame = new MainFrame(NULL);
        SetTopWindow(mainFrame);
        return GetTopWindow()->Show();
    }
};

DECLARE_APP(MainApp)
IMPLEMENT_APP(MainApp)


text:
(function() {
    'use strict';

    angular
        .module('myApp')
        .config(configure);

    configure.$inject = ['$stateProvider'];

    function configure($stateProvider) {
        $stateProvider.state('perfil-form', getState());
    }

    function getState() {
        return {
            url: '/perfil/:id',
            templateUrl: 'partial/perfil-usuario/perfil-form.html',
            controller: 'PerfilFormCtrl',
            controllerAs: 'vm',
            parent: 'home',
            params: {
                'id': null
            },
            resolve: {
                getData: getData
            }
        };
    }

    getData.$inject = ['$state', '$stateParams', 'perfilService'];

    function getData($state, $stateParams, perfilService) {
        //console.info('$stateParams', $stateParams);

        if ($stateParams.id) {
            return perfilService.getById($stateParams.id).then(success).catch(error);
        } else {
            return {};
        }

        function success(response) {
            console.info(response);
            if (response.query.length === 0) {
                $state.go('404');
            } else {
                return response.query[0];
            }
        }

        function error(response) {
            return response;
        }
    }
})();


text:
package co.cask.yare;

/**
 * Class description here.
 */
public class RulebookNotFoundException extends Exception {
  public RulebookNotFoundException(String message) {
    super(message);
  }
}


text:
import os
import tempfile
import shutil

from django.core.files.uploadedfile import UploadedFile
from django.test import TransactionTestCase
from django.contrib.auth.models import Group

from hs_core.testing import MockIRODSTestCaseMixin
from hs_core import hydroshare
from hs_core.models import Coverage
from hs_core.hydroshare.utils import resource_post_create_actions
from hs_core.views.utils import move_or_rename_file_or_folder

from hs_file_types.models import GenericLogicalFile, GenericFileMetaData

class GenericFileTypeMetaDataTest(MockIRODSTestCaseMixin, TransactionTestCase):
    def setUp(self):
        super(GenericFileTypeMetaDataTest, self).setUp()
        self.group, _ = Group.objects.get_or_create(name='Resource Author')
        self.user = hydroshare.create_account(
            'user1@nowhere.com',
            username='user1',
            first_name='Creator_FirstName',
            last_name='Creator_LastName',
            superuser=False,
            groups=[self.group]
        )

        self.composite_resource = hydroshare.create_resource(
            resource_type='CompositeResource',
            owner=self.user,
            title='Test Generic File Metadata'
        )

        self.temp_dir = tempfile.mkdtemp()
        self.generic_file_name = 'generic_file.txt'
        self.raster_zip_file_name = 'logan_vrt_small.zip'
        self.generic_file = 'hs_file_types/tests/{}'.format(self.generic_file_name)
        target_temp_generic_file = os.path.join(self.temp_dir, self.generic_file_name)
        shutil.copy(self.generic_file, target_temp_generic_file)
        self.generic_file_obj = open(target_temp_generic_file, 'r')

    def tearDown(self):
        super(GenericFileTypeMetaDataTest, self).tearDown()
        if os.path.exists(self.temp_dir):
            shutil.rmtree(self.temp_dir)

    def test_generic_logical_file(self):
        # test that when any file is uploaded to Composite Resource
        # the file is assigned to GenericLogicalFile type
        # test that generic logical file type can have the following metadata (all optional:
        #   coverage (spatial and temporal)
        #   key/value metadata
        #   title (dataset_name)
        #   keywords
        self.generic_file_obj = open(self.generic_file, 'r')
        self._create_composite_resource()

        # there should be one resource file
        self.assertEqual(self.composite_resource.files.all().count(), 1)
        res_file = self.composite_resource.files.first()
        # check that the resource file is associated with GenericLogicalFile
        self.assertEqual(res_file.has_logical_file, True)
        self.assertEqual(res_file.logical_file_type_name, "GenericLogicalFile")

        logical_file = res_file.logical_file
        # test that the generic logical file has no value for the datataset_name
        self.assertEqual(logical_file.dataset_name, None)
        logical_file.dataset_name = "This is a generic dataset"
        logical_file.save()
        logical_file = res_file.logical_file
        self.assertEqual(logical_file.dataset_name, "This is a generic dataset")

        # check that the logical file has metadata object
        self.assertNotEqual(logical_file.metadata, None)

        # there should be no coverage element at this point
        self.assertEqual(logical_file.metadata.coverages.count(), 0)

        # there should not be any extra_metadata (key/value) at this point
        self.assertEqual(logical_file.metadata.extra_metadata, {})
        # create key/vale metadata
        logical_file.metadata.extra_metadata = {'key1': 'value 1', 'key2': 'value 2'}
        logical_file.metadata.save()
        res_file = self.composite_resource.files.first()
        logical_file = res_file.logical_file
        self.assertEqual(logical_file.metadata.extra_metadata,
                         {'key1': 'value 1', 'key2': 'value 2'})

        # update key/value metadata
        logical_file.metadata.extra_metadata = {'key1': 'value 1', 'key2': 'value 2',
                                                'key 3': 'value3'}
        logical_file.metadata.save()
        res_file = self.composite_resource.files.first()
        logical_file = res_file.logical_file
        self.assertEqual(logical_file.metadata.extra_metadata,
                         {'key1': 'value 1', 'key2': 'value 2', 'key 3': 'value3'})

        # delete key/value metadata
        logical_file.metadata.extra_metadata = {}
        logical_file.metadata.save()
        res_file = self.composite_resource.files.first()
        logical_file = res_file.logical_file
        self.assertEqual(logical_file.metadata.extra_metadata, {})

        # test keywords
        self.assertEqual(logical_file.metadata.keywords, [])
        logical_file.metadata.keywords = ['kw-1', 'kw-2']
        logical_file.metadata.save()
        self.assertIn('kw-1', logical_file.metadata.keywords)
        self.assertIn('kw-2', logical_file.metadata.keywords)

        # test coverage element CRUD
        res_file = [f for f in self.composite_resource.files.all()
                    if f.logical_file_type_name == "GenericLogicalFile"][0]

        gen_logical_file = res_file.logical_file
        value_dict = {'name': 'Name for period coverage', 'start': '1/1/2000', 'end': '12/12/2012'}
        temp_cov = gen_logical_file.metadata.create_element('coverage', type='period',
                                                            value=value_dict)
        self.assertEqual(temp_cov.value['name'], 'Name for period coverage')
        self.assertEqual(temp_cov.value['start'], '1/1/2000')
        self.assertEqual(temp_cov.value['end'], '12/12/2012')
        # update temporal coverage
        value_dict = {'start': '10/1/2010', 'end': '12/1/2016'}
        gen_logical_file.metadata.update_element('coverage', temp_cov.id, type='period',
                                                 value=value_dict)
        temp_cov = gen_logical_file.metadata.temporal_coverage
        self.assertEqual(temp_cov.value['name'], 'Name for period coverage')
        self.assertEqual(temp_cov.value['start'], '10/1/2010')
        self.assertEqual(temp_cov.value['end'], '12/1/2016')

        # add spatial coverage
        value_dict = {'east': '56.45678', 'north': '12.6789', 'units': 'Decimal degree'}
        spatial_cov = gen_logical_file.metadata.create_element('coverage', type='point',
                                                               value=value_dict)
        self.assertEqual(spatial_cov.value['projection'], 'WGS 84 EPSG:4326')
        self.assertEqual(spatial_cov.value['units'], 'Decimal degree')
        self.assertEqual(spatial_cov.value['north'], 12.6789)
        self.assertEqual(spatial_cov.value['east'], 56.45678)
        # update spatial coverage
        value_dict = {'east': '-156.45678', 'north': '45.6789', 'units': 'Decimal degree'}
        gen_logical_file.metadata.update_element('coverage', spatial_cov.id, type='point',
                                                 value=value_dict)
        spatial_cov = logical_file.metadata.spatial_coverage
        self.assertEqual(spatial_cov.value['projection'], 'WGS 84 EPSG:4326')
        self.assertEqual(spatial_cov.value['units'], 'Decimal degree')
        self.assertEqual(spatial_cov.value['north'], 45.6789)
        self.assertEqual(spatial_cov.value['east'], -156.45678)
        self.composite_resource.delete()
        # there should be no GenericLogicalFile object at this point
        self.assertEqual(GenericLogicalFile.objects.count(), 0)
        # there should be no GenericFileMetaData object at this point
        self.assertEqual(GenericFileMetaData.objects.count(), 0)

    def test_file_rename_or_move(self):
        # test that resource file that belongs to GenericLogicalFile object
        # can be moved or renamed

        self.generic_file_obj = open(self.generic_file, 'r')
        self._create_composite_resource()
        res_file = self.composite_resource.files.first()
        self.assertEqual(os.path.basename(res_file.resource_file.name), 'generic_file.txt')
        # test rename of file is allowed
        src_path = 'data/contents/generic_file.txt'
        tgt_path = "data/contents/generic_file_1.txt"
        move_or_rename_file_or_folder(self.user, self.composite_resource.short_id, src_path,
                                      tgt_path)
        res_file = self.composite_resource.files.first()
        self.assertEqual(os.path.basename(res_file.resource_file.name), 'generic_file_1.txt')
        # test moving the file to a new folder is allowed
        src_path = 'data/contents/generic_file_1.txt'
        tgt_path = "data/contents/test_folder/generic_file_1.txt"
        move_or_rename_file_or_folder(self.user, self.composite_resource.short_id, src_path,
                                      tgt_path)
        res_file = self.composite_resource.files.first()
        self.assertTrue(res_file.resource_file.name.endswith(tgt_path))

    def test_file_type_metadata_on_file_delete(self):
        # test that when a file that's part of the GenericLogicalFile object
        # is deleted all metadata associated with the file type also get deleted
        self.generic_file_obj = open(self.generic_file, 'r')
        self._create_composite_resource()
        res_file = self.composite_resource.files.first()
        gen_logical_file = res_file.logical_file
        self.assertEqual(GenericLogicalFile.objects.count(), 1)
        self.assertEqual(GenericFileMetaData.objects.count(), 1)
        # at this point there should not be any coverage elements associated with
        # logical file
        self.assertEqual(gen_logical_file.metadata.coverages.count(), 0)
        # at this point there should not be any key/value metadata associated with
        # logical file
        self.assertEqual(gen_logical_file.metadata.extra_metadata, {})
        # add temporal coverage
        value_dict = {'name': 'Name for period coverage', 'start': '1/1/2000', 'end': '12/12/2012'}
        gen_logical_file.metadata.create_element('coverage', type='period', value=value_dict)
        # add spatial coverage
        value_dict = {'east': '56.45678', 'north': '12.6789', 'units': 'Decimal degree'}
        gen_logical_file.metadata.create_element('coverage', type='point', value=value_dict)
        # at this point there should be 2 coverage elements associated with
        # logical file
        self.assertEqual(gen_logical_file.metadata.coverages.count(), 2)
        # at this point we should have 4 coverage elements (2 resource level
        # and 2 file type level
        self.assertEqual(Coverage.objects.count(), 4)
        # add key/value metadata
        gen_logical_file.metadata.extra_metadata = {'key1': 'value 1', 'key2': 'value 2'}
        gen_logical_file.metadata.save()
        hydroshare.delete_resource_file(self.composite_resource.short_id,
                                        res_file.id,
                                        self.user)
        # test that we don't have logical file of type GenericLogicalFile
        self.assertEqual(GenericLogicalFile.objects.count(), 0)
        self.assertEqual(GenericFileMetaData.objects.count(), 0)
        # test that all metadata deleted
        self.assertEqual(Coverage.objects.count(), 0)

    def _create_composite_resource(self):
        uploaded_file = UploadedFile(file=self.generic_file_obj,
                                     name=os.path.basename(self.generic_file_obj.name))
        self.composite_resource = hydroshare.create_resource(
            resource_type='CompositeResource',
            owner=self.user,
            title='Test Generic File Type Metadata',
            files=(uploaded_file,)
        )

        # set the logical file
        resource_post_create_actions(resource=self.composite_resource, user=self.user,
                                     metadata=self.composite_resource.metadata)


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

namespace Bio.Algorithms.Alignment.MultipleSequenceAlignment
{
    /// <summary>
    /// An ISequenceAlignment is the result of running an alignment algorithm on a set
    /// of two or more sequences. This could be a pairwise alignment, an MSA (multiple
    /// sequence alignment), or an overlap alignment of the sort needed for sequence
    /// assembly.
    /// </summary>
    /// <remarks>
    /// this is just a storage object – it's up to an algorithm object to fill it in.
    /// for efficiency's sake, we are leaving it up to calling code to keep track of the
    /// input sequences, if desired.
    /// </remarks>
    public interface ISequenceAlignment
    {
        /// <summary>
        /// A list of the (usually modified) output sequences, in the same order
        /// that the inputs were passed to the alignment algorithm.
        /// </summary>
        IList<ISequence> Sequences { set; get; }

        /// <summary>
        /// Offset is the starting position of alignment of sequence1
        /// with respect to sequence2.
        /// </summary>
        IList<int> Offsets { set; get; }

        /// <summary>
        /// A consensus sequence representing the alignment.
        /// </summary>
        ISequence Consensus { set; get; }

        /// <summary>
        /// The score for the alignment. Higher scores mean better alignments.
        /// The score is determined by the alignment algorithm used.
        /// </summary>
        int Score { set; get; }

        /// <summary>
        /// The Documentation object is intended for tracking the history, provenance,
        /// and experimental context of a sequence. The user can adopt any desired
        /// convention for use of this object.
        /// </summary>
        object Documentation { set; get; }

        /// <summary>
        /// Clears the alignment
        /// </summary>
        void Clear();
    }
}


text:
package com.avsystem.commons
package jiop

import java.time.Instant

import com.avsystem.commons.jiop.JavaTimeInterop.InstantOps
import com.avsystem.commons.misc.Timestamp

trait JavaTimeInterop {
  implicit def instantOps(instant: Instant): InstantOps = new InstantOps(instant)
}
object JavaTimeInterop {
  class InstantOps(private val instant: Instant) extends AnyVal {
    def truncateToTimestamp: Timestamp = Timestamp(instant.toEpochMilli)
    def truncateToJDate: JDate = new JDate(instant.toEpochMilli)
  }
}


text:
package cz.scholz.amqp.transactionmonkey.tests;

import cz.scholz.amqp.transactionmonkey.configuration.Configuration;
import cz.scholz.amqp.transactionmonkey.configuration.ConfigurationException;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;

/**
 * Created by jakub on 08.03.16.
 */
public class ConfigurationTest {
    public String[] getRequiredOptions()
    {
        List<String> options = new ArrayList<>();
        options.add("--first-broker-host");
        options.add("host1");
        options.add("--first-broker-port");
        options.add("11111");
        options.add("-first-broker-username");
        options.add("user1");
        options.add("--first-broker-password");
        options.add("password1");
        options.add("--first-broker-queue");
        options.add("queue1");
        options.add("--second-broker-host");
        options.add("host2");
        options.add("--second-broker-port");
        options.add("22222");
        options.add("--second-broker-username");
        options.add("user2");
        options.add("--second-broker-password");
        options.add("password2");
        options.add("--second-broker-queue");
        options.add("queue2");

        String[] args = new String[options.size()];
        options.toArray(args);
        return args;
    }

    @Test
    public void testRequiredOptions()
    {
        try {
            Configuration config = new Configuration(getRequiredOptions());
        }
        catch (ConfigurationException e) {
            Assert.fail();
        }
    }

    @Test
    public void testPorts()
    {
        Configuration config = new Configuration();

        try {
            config.setaPort("5672");
            Assert.assertEquals("5672", config.getaPort());
        }
        catch (ConfigurationException e) {
            Assert.fail("Valid port for first broker was not accepted - 5672");
        }

        try {
            config.setbPort("5672");
            Assert.assertEquals("5672", config.getbPort());
        }
        catch (ConfigurationException e) {
            Assert.fail("Valid port for second broker was not accepted - 5672");
        }

        try {
            config.setaPort("xxx");
            Assert.fail("Invalid port for first broker was not detected - string");
        }
        catch (ConfigurationException e) {
            //pass
        }

        try {
            config.setaPort("66666");
            Assert.fail("Invalid port for first broker was not detected - 66666");
        }
        catch (ConfigurationException e) {
            //pass
        }

        try {
            config.setaPort("0");
            Assert.fail("Invalid port for first broker was not detected - 66666");
        }
        catch (ConfigurationException e) {
            //pass
        }
    }

    @Test
    public void testLogLevel() throws ConfigurationException
    {
        Configuration config = new Configuration();
        String DEFAULT_LOG_LEVEL = config.getLogLevel();

        config.setLogLevel(null);
        Assert.assertEquals(DEFAULT_LOG_LEVEL, config.getLogLevel(), "Incorrect Log Level set for null");

        config.setLogLevel("error");
        Assert.assertEquals("error", config.getLogLevel(), "Incorrect Log Level set for error");

        config.setLogLevel("warning");
        Assert.assertEquals("warning", config.getLogLevel(), "Incorrect Log Level set for warning");

        config.setLogLevel("info");
        Assert.assertEquals("info", config.getLogLevel(), "Incorrect Log Level set for info");

        config.setLogLevel("debug");
        Assert.assertEquals("debug", config.getLogLevel(), "Incorrect Log Level set for debug");

        config.setLogLevel("trace");
        Assert.assertEquals("trace", config.getLogLevel(), "Incorrect Log Level set for trace");

        config.setLogLevel("TRACE");
        Assert.assertEquals("trace".toLowerCase(), config.getLogLevel().toLowerCase(), "Incorrect Log Level set for TRACE");

        config.setLogLevel("Trace");
        Assert.assertEquals("trace".toLowerCase(), config.getLogLevel().toLowerCase(), "Incorrect Log Level set for Trace");

        try {
            config.setLogLevel("xxx");
            Assert.fail("Invalid Log Level was accepted");
        }
        catch (ConfigurationException e) {
            //pass
        }
    }

    @Test
    public void testProcessInt() throws ConfigurationException
    {
        String[] defaultCli = getRequiredOptions();
        String[] cli = new String[defaultCli.length+2];
        System.arraycopy(defaultCli, 0, cli, 0, defaultCli.length);

        int key = defaultCli.length;
        int val = defaultCli.length+1;

        // Test ineteger
        cli[key] = "--transaction-count";
        cli[val] = "60000";
        new Configuration(cli);

        // Test string
        try {
            cli[key] = "--transaction-count";
            cli[val] = "xxx";
            new Configuration(cli);
            Assert.fail("xxx was accepted as integer");
        }
        catch (ConfigurationException e)
        {
            // pass
        }

        // Test negative value
        try {
            cli[key] = "--transaction-count";
            cli[val] = "-1";
            new Configuration(cli);
            Assert.fail("-1 was accepted as non-negative value");
        }
        catch (ConfigurationException e)
        {
            // pass
        }
    }

    @Test
    public void testAllOptions() throws ConfigurationException {
        List<String> cli = new ArrayList<>(Arrays.asList(getRequiredOptions()));
        cli.add("--enable-amqp10-routing");
        cli.add("--amqp10-routing-wait-time");
        cli.add("101");
        cli.add("--amqp10-routing-transaction-gap");
        cli.add("102");
        cli.add("--enable-amqp10-rollback");
        cli.add("--amqp10-rollback-wait-time");
        cli.add("103");
        cli.add("--amqp10-rollback-transaction-gap");
        cli.add("104");
        cli.add("--enable-amqp010-routing");
        cli.add("--amqp010-routing-wait-time");
        cli.add("105");
        cli.add("--amqp010-routing-transaction-gap");
        cli.add("106");
        cli.add("--enable-amqp010-rollback");
        cli.add("--amqp010-rollback-wait-time");
        cli.add("107");
        cli.add("--amqp010-rollback-transaction-gap");
        cli.add("108");
        cli.add("--enable-amqp010-xa-routing");
        cli.add("--amqp010-xa-routing-wait-time");
        cli.add("109");
        cli.add("--amqp010-xa-routing-transaction-gap");
        cli.add("110");
        cli.add("--enable-amqp010-xa-rollback");
        cli.add("--amqp010-xa-rollback-wait-time");
        cli.add("111");
        cli.add("--amqp010-xa-rollback-transaction-gap");
        cli.add("112");
        cli.add("--wait-time");
        cli.add("113");
        cli.add("--feed-messages");
        cli.add("--feed-messages-count");
        cli.add("115");
        cli.add("--feed-messages-size");
        cli.add("116");
        cli.add("--log-level");
        cli.add("trace");

        String[] args = new String[cli.size()];
        cli.toArray(args);

        Configuration config = new Configuration(args);

        Assert.assertEquals(config.isAmqp10Router(), true, "AMQP 1.0 router is not enabled");
        Assert.assertEquals(config.getAmqp10RouterWaitTime(), 101, "AMQP 1.0 router wait time does not match");
        Assert.assertEquals(config.getAmqp10RouterTransactionGap(), 102, "AMQP 1.0 router transaction gap does not match");

        Assert.assertEquals(config.isAmqp10Rollback(), true, "AMQP 1.0 rollback is not enabled");
        Assert.assertEquals(config.getAmqp10RollbackWaitTime(), 103, "AMQP 1.0 rollback wait time does not match");
        Assert.assertEquals(config.getAmqp10RollbackTransactionGap(), 104, "AMQP 1.0 rollback transaction gap does not match");

        Assert.assertEquals(config.isAmqp010Router(), true, "AMQP 0-10 router is not enabled");
        Assert.assertEquals(config.getAmqp010RouterWaitTime(), 105, "AMQP 0-10 router wait time does not match");
        Assert.assertEquals(config.getAmqp010RouterTransactionGap(), 106, "AMQP 0-10 router transaction gap does not match");

        Assert.assertEquals(config.isAmqp010Rollback(), true, "AMQP 0-10 rollback is not enabled");
        Assert.assertEquals(config.getAmqp010RollbackWaitTime(), 107, "AMQP 0-10 rollback wait time does not match");
        Assert.assertEquals(config.getAmqp010RollbackTransactionGap(), 108, "AMQP 0-10 rollback transaction gap does not match");

        Assert.assertEquals(config.isXaRouter(), true, "AMQP 0-10 XA router is not enabled");
        Assert.assertEquals(config.getXaRouterWaitTime(), 109, "AMQP 0-10 XA router wait time does not match");
        Assert.assertEquals(config.getXaRouterTransactionGap(), 110, "AMQP 0-10 XA router transaction gap does not match");

        Assert.assertEquals(config.isXaRollback(), true, "AMQP 0-10 XA rollback is not enabled");
        Assert.assertEquals(config.getXaRollbackWaitTime(), 111, "AMQP 0-10 XA rollback wait time does not match");
        Assert.assertEquals(config.getXaRollbackTransactionGap(), 112, "AMQP 0-10 XA rollback transaction gap does not match");

        Assert.assertEquals(config.getWaitTime(), 113, "Wait time does not match");

        Assert.assertEquals(config.isFeedMessages(), true, "Feeding of messages is not enabled");
        Assert.assertEquals(config.getFeedMessagesCount(), 115, "Feeding message count does not match");
        Assert.assertEquals(config.getFeedMessagesSize(), 116, "Feeding message size does not match");

        Assert.assertEquals(config.getLogLevel(), "trace", "Log level does not match");
    }
}


text:
/* global describe, it, afterEach, beforeEach */
import {expect} from 'chai'
import {mapStateToProps, mapPropsOnChange, hasObjectTypeError, setPropTypes, setStateTypes, composeProps} from '../src/composeProps.js'
import {PropTypes} from 'react'

describe('compose-props', () => {
  describe('mapStateToProps()', () => {
    const initState = {set: [{ id: 1 }, { id: 2 }]}
    const initProps = {a: 1, b: {c: 2}}

    it('should call propMapper function with state and props', () => {
      const newPropsFunction = function (passedState, passedProps) {
        expect(passedState).to.deep.equal(initState)
        expect(passedProps).to.deep.equal(initProps)
        return {}
      }
      const statePropsFunc = mapStateToProps(newPropsFunction)
      statePropsFunc(initState, initProps)
    })
    it('should return new object with initial props spread first then returned propMapper object spread', () => {
      const newPropsFunction = function (passedState, passedProps) {
        return {b: 3}
      }
      const statePropsFunc = mapStateToProps(newPropsFunction)
      const newObject = statePropsFunc(initState, initProps)
      expect(newObject).to.deep.equal({a: 1, b: 3})
    })
  })

  describe('mapPropsOnChange()', () => {
    const initState = {set: [{ id: 1 }, { id: 2 }]}
    const initProps = {a: 1, b: {c: 2}}

    it('should call propMapper function with state and props', () => {
      const newPropsFunction = function (passedState, passedProps) {
        expect(passedState).to.deep.equal(initState)
        expect(passedProps).to.deep.equal(initProps)
        return {}
      }
      const statePropsFunc = mapPropsOnChange(['b'], newPropsFunction)
      statePropsFunc(initState, initProps)
    })
    it('should return new object with initial props(omiting watched keys) spread first then returned propMapper object spread', () => {
      const newPropsFunction = function (passedState, passedProps) {
        return {a: 3}
      }
      const statePropsFunc = mapPropsOnChange(['b'], newPropsFunction)
      const newObject = statePropsFunc(initState, initProps)
      expect(newObject).to.deep.equal({a: 3})
    })
    it('should only call propMapper once if watched props are unchanged', () => {
      let propMapperCalled = 0
      const newPropsFunction = function (passedState, passedProps) {
        propMapperCalled += 1
        return {}
      }
      const statePropsFunc = mapPropsOnChange(['b'], newPropsFunction)
      statePropsFunc(initState, initProps)
      statePropsFunc(initState, initProps)
      expect(propMapperCalled).to.equal(1)
    })
    it('should call propMapper again when watched props are changed', () => {
      let propMapperCalled = 0
      const newPropsFunction = function (passedState, passedProps) {
        propMapperCalled += 1
        return {}
      }
      const statePropsFunc = mapPropsOnChange(['b'], newPropsFunction)
      statePropsFunc(initState, initProps)
      statePropsFunc(initState, {a: 1, b: {c: 3}})
      expect(propMapperCalled).to.equal(2)
    })
  })

  describe('hasObjectTypeError() - used by setStateTypes and setPropTypes', () => {
    let oldConsoleWarn
    let testError = 'no errors'
    beforeEach(() => {
      // mocking console.warn for test purposes... gross...
      oldConsoleWarn = console.warn
      console.warn = (err) => {
        testError = err
      }
    })
    afterEach(() => {
      console.warn = oldConsoleWarn
      testError = 'no errors'
    })

    const dataObject = {a: 1, b: {c: 2}}
    const testObjectTypes = {
      a: PropTypes.number.isRequired,
      b: PropTypes.shape({c: PropTypes.number.isRequired}).isRequired
    }

    it('should return false when there are no error', () => {
      const hasErrors = hasObjectTypeError({}, dataObject)
      expect(hasErrors).to.deep.equal(false)
    })
    it('should return false and not console.warn any errors with passing propTypes', () => {
      const hasErrors = hasObjectTypeError(testObjectTypes, dataObject)
      expect(hasErrors).to.deep.equal(false)
      expect(testError).to.equal('no errors')
    })
    it('should return true and console.warn errors when there are errors in propTypes', () => {
      const hasErrors = hasObjectTypeError(testObjectTypes, {})
      expect(hasErrors).to.deep.equal(true)
      expect(testError).to.not.equal('no errors')
    })

    describe('hasObjectTypeError tests which NODE_ENV environment', () => {
      let oldEnv
      beforeEach(() => {
        oldEnv = process.env.NODE_ENV
      })
      afterEach(() => {
        process.env.NODE_ENV = oldEnv
      })
      it('should return false when NODE_ENV is \'production\'', () => {
        process.env.NODE_ENV = 'production'
        const hasErrors = hasObjectTypeError(testObjectTypes, {})
        expect(hasErrors).to.deep.equal(false)
      })
    })
    describe('hasObjectTypeError tests if running in React Native environment', () => {
      let oldEnv
      beforeEach(() => {
        oldEnv = process.env.NODE_ENV
        GLOBAL.navigator = {}
        Object.defineProperty(GLOBAL.navigator, 'product', {value: 'ReactNative'})
      })
      afterEach(() => {
        process.env.NODE_ENV = oldEnv
        delete GLOBAL.navigator
      })
      it('should run when in React Native, even when NODE_ENV is \'production\'', () => {
        process.env.NODE_ENV = 'production'
        const hasErrors = hasObjectTypeError(testObjectTypes, {})
        expect(hasErrors).to.deep.equal(true)
      })
    })
  })

  describe('setPropTypes()', () => {
    let oldConsoleWarn
    beforeEach(() => {
      // mocking console.warn for test purposes... gross...
      oldConsoleWarn = console.warn
      console.warn = () => {}
    })
    afterEach(() => {
      console.warn = oldConsoleWarn
    })
    it('should return props when there are no errors', () => {
      const initProps = {a: 1}
      const statePropsFunc = setPropTypes({})
      const outputProps = statePropsFunc({}, initProps)
      expect(outputProps).to.deep.equal(initProps)
    })
    it('should return null when there are errors', () => {
      const initProps = {a: '1'}
      const testObjectTypes = { a: PropTypes.number.isRequired }
      const statePropsFunc = setPropTypes(testObjectTypes)
      const outputProps = statePropsFunc({}, initProps)
      expect(outputProps).to.equal(null)
    })
  })

  describe('setStateTypes()', () => {
    let oldConsoleWarn
    beforeEach(() => {
      // mocking console.warn for test purposes... gross...
      oldConsoleWarn = console.warn
      console.warn = () => {}
    })
    afterEach(() => {
      console.warn = oldConsoleWarn
    })
    it('should return props when there are no errors', () => {
      const initProps = {a: 1}
      const statePropsFunc = setStateTypes({})
      const outputProps = statePropsFunc({}, initProps)
      expect(outputProps).to.deep.equal(initProps)
    })
    it('should return null when there are errors', () => {
      const initState = {a: '1'}
      const testObjectTypes = { a: PropTypes.number.isRequired }
      const statePropsFunc = setPropTypes(testObjectTypes)
      const outputProps = statePropsFunc(initState, {})
      expect(outputProps).to.equal(null)
    })
  })

  describe('composeProps()', () => {
    const initState = {set: [{ id: 1 }, { id: 2 }]}
    const initProps = {a: 1, b: {c: 2}}

    it('should default props to empty object and pass in state', () => {
      const statePropsFunc = composeProps(
        (passedState, passedProps) => {
          expect(passedProps).to.deep.equal({})
          expect(passedState).to.deep.equal(initState)
        }
      )
      statePropsFunc(initState)
    })

    it('should work with any function that takes in (state, props), and return last functions returned object', () => {
      let calledFuncCount = 0
      const statePropsFunc = composeProps(
        (state, props) => {
          calledFuncCount += 1
          expect(props).to.deep.equal(initProps)
          return {a: 1}
        },
        (state, props) => {
          calledFuncCount += 1
          expect(props).to.deep.equal({a: 1})
          return {c: 1}
        }
      )
      expect(calledFuncCount).to.equal(0)
      const finalProps = statePropsFunc(initState, initProps)
      expect(calledFuncCount).to.equal(2)
      expect(finalProps).to.deep.equal({c: 1})
    })

    describe('works with other compose-props methods', () => {
      let oldConsoleWarn
      let testError = 'no errors'
      beforeEach(() => {
        // mocking console.warn for test purposes... gross...
        oldConsoleWarn = console.warn
        console.warn = (err) => {
          testError = err
        }
      })
      afterEach(() => {
        console.warn = oldConsoleWarn
        testError = 'no errors'
      })

      it('should \'short circuit\' when a composed function returns null, and return an empty object({})', () => {
        const testStateProps = { set: PropTypes.arrayOf(PropTypes.number.isRequired).isRequired }
        let count = 0
        const initState = {set: ['a', 'b']}

        const statePropsFunc = composeProps(
          (s, p) => {
            count += 1
            return p
          },
          setStateTypes(testStateProps, 'compose setStateTypes'),
          (s, p) => {
            count += 1
            return p
          }
        )

        expect(count).to.equal(0)
        const firstRunProps = statePropsFunc(initState, initProps)
        expect(testError).to.not.equal('no errors')
        expect(count).to.equal(1)
        expect(firstRunProps).to.deep.equal({})
      })

      it('should work with mapStateToProps, setPropTypes, setStateTypes, and mapPropsOnChange', () => {
        const testStateProps = {
          set: PropTypes.arrayOf(PropTypes.shape({id: PropTypes.number.isRequired})).isRequired
        }
        const testPropTypes = {
          a: PropTypes.number.isRequired,
          b: PropTypes.shape({c: PropTypes.number.isRequired}).isRequired
        }
        let calledComposeCount = 0
        let calledOnChangeCount = 0
        const initState = {set: [{ id: 1 }, { id: 2 }]}
        const initProps = {a: 1, b: {c: 2}}

        const statePropsFunc = composeProps(
          (s, p) => {
            calledComposeCount += 1
            return p
          },
          setStateTypes(testStateProps, 'compose setStateTypes'),
          setPropTypes(testPropTypes, 'compose setPropTypes'),
          mapStateToProps((passedState, passedProps) => {
            expect(passedState).to.deep.equal(initState)
            expect(passedProps).to.deep.equal(initProps)
            return {d: 4}
          }),
          mapPropsOnChange(['b'], (passedState, passedProps) => {
            expect(passedState).to.deep.equal(initState)
            expect(passedProps).to.deep.equal({...initProps, d: 4})
            calledOnChangeCount += 1
            return {e: 5}
          })
        )

        expect(calledComposeCount).to.equal(0)
        expect(calledOnChangeCount).to.equal(0)

        const expectOutProps = {a: 1, d: 4, e: 5}
        const firstRunProps = statePropsFunc(initState, initProps)
        expect(testError).to.equal('no errors')
        expect(calledComposeCount).to.equal(1)
        expect(calledOnChangeCount).to.equal(1)
        expect(firstRunProps).to.deep.equal(expectOutProps)

        const secondRunProps = statePropsFunc(initState, initProps)
        expect(calledComposeCount).to.equal(2)
        expect(calledOnChangeCount).to.equal(1)
        expect(secondRunProps).to.deep.equal(expectOutProps)
      })
    })
    it('should \'compose\' other composeProps\'s output', () => {
      const state = {b: 1}
      const statePropsFunc = composeProps(
        (passedState, passedProps) => {
          expect(passedProps).to.deep.equal({})
          expect(passedState).to.deep.equal(state)
          return {a: 1}
        },
        composeProps(
          (passedState, passedProps) => {
            expect(passedProps).to.deep.equal({a: 1})
            expect(passedState).to.deep.equal(state)
            return {c: 1}
          }
        )
      )
      const finalProps = statePropsFunc(state)
      expect(finalProps).to.deep.equal({c: 1})
    })
  })
})


text:
package com.eagle.programmar.BNF.Symbols;

import com.eagle.programmar.BNF.Terminals.BNF_Identifier;
import com.eagle.tokens.ReferenceInterface;

public class BNF_Rule_Reference extends BNF_Identifier implements ReferenceInterface
{
}


text:
namespace mio {

template<class K, class V> class MIOHashMapStub;
template<class T> class MIOArrayStub;

class Statement;
class TypeFactory;
class Scope;
class SimpleFileSystem;
class FunctionEntry;
class MemorySegment;
class ObjectFactory;
class ObjectExtraFactory;
class FunctionRegister;
class CodeRef;
class CodeCache;
class TraceTree;

class MIOHashMap;
class MIOFunction;
class MIOGeneratedFunction;
class MIOString;
class MIOReflectionType;

// [unitName, [statement]]
typedef ZoneHashMap<RawStringRef, ZoneVector<Statement *> *> ParsedUnitMap;

// [moduleName [unitName, statements]]
typedef ZoneHashMap<RawStringRef, ParsedUnitMap *> ParsedModuleMap;

struct ParsingError {
    int column;
    int line;
    int position;
    std::string file_name;
    std::string message;

    ParsingError();

    static ParsingError NoError();

    std::string ToString() const;
}; // struct ParsingError

struct CompiledInfo {
    int global_primitive_segment_bytes;
    int global_object_segment_bytes;
    int next_function_id;
};

class FunctionEntry {
public:
    enum Kind {
        NORMAL,
        NATIVE,
    };
    FunctionEntry() : offset_(0), kind_(NORMAL) {}

    DEF_PROP_RW(int, offset)
    DEF_PROP_RW(Kind, kind)

    DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionEntry)
private:
    int  offset_;
    Kind kind_;
}; // class FunctionEntry

class Compiler {
public:
    static ParsedUnitMap *ParseProject(const char *project_dir,
                                       SimpleFileSystem *sfs,
                                       TypeFactory *types,
                                       Scope *global,
                                       Zone *zone,
                                       ParsingError *error);

    static ParsedUnitMap *ParseProject(const char *project_dir,
                                       const char *entry_module,
                                       const std::vector<std::string> &builtin_modules,
                                       const std::vector<std::string> &search_paths,
                                       SimpleFileSystem *sfs,
                                       TypeFactory *types,
                                       Scope *global,
                                       Zone *zone,
                                       ParsingError *error);

    static ParsedModuleMap *Check(ParsedUnitMap *all_units,
                                  TypeFactory *types,
                                  Scope *global,
                                  Zone *zone,
                                  ParsingError *error);

    static void AstEmitToBitCode(ParsedModuleMap *all_modules,
                                 MemorySegment *p_global,
                                 MemorySegment *o_global,
                                 TypeFactory *types,
                                 ObjectFactory *object_factory,
                                 ObjectExtraFactory *extra_factory,
                                 FunctionRegister *function_register,
                                 MIOHashMapStub<Handle<MIOString>, mio_i32_t> *all_var,
                                 MIOArrayStub<Handle<MIOReflectionType>> *all_type,
                                 std::unordered_map<int64_t, int> *type_id2index,
                                 CompiledInfo *info,
                                 int next_function_id);

    static void BitCodeToNativeCodeFragment(MIOFunction *fn,
                                            int pc,
                                            int id,
                                            TraceTree *tree,
                                            CodeCache *cc,
                                            CodeRef *cr);

    static void BitCodeToNativeCode(MIOFunction *fn,
                                    int pc,
                                    int id,
                                    TraceTree *tree,
                                    CodeCache *cc,
                                    CodeRef *cr);

    Compiler() = delete;
    ~Compiler() = delete;
    DISALLOW_IMPLICIT_CONSTRUCTORS(Compiler)
};

} // namespace mio

#endif // MIO_COMPILER_H


text:
import { browser, element, by, $ } from 'protractor';
import { NavBarPage } from './../page-objects/jhi-page-objects';
const path = require('path');

describe('IrcBot e2e test', () => {

    let navBarPage: NavBarPage;
    let ircBotDialogPage: IrcBotDialogPage;
    let ircBotComponentsPage: IrcBotComponentsPage;
    const fileToUpload = '../../../../main/webapp/content/images/logo-jhipster.png';
    const absolutePath = path.resolve(__dirname, fileToUpload);

    beforeAll(() => {
        browser.get('/');
        browser.waitForAngular();
        navBarPage = new NavBarPage();
        navBarPage.getSignInPage().autoSignInUsing('admin', 'admin');
        browser.waitForAngular();
    });

    it('should load IrcBots', () => {
        navBarPage.goToEntity('irc-bot');
        ircBotComponentsPage = new IrcBotComponentsPage();
        expect(ircBotComponentsPage.getTitle()).toMatch(/gamecraftgatewayApp.ircBot.home.title/);

    });

    it('should load create IrcBot dialog', () => {
        ircBotComponentsPage.clickOnCreateButton();
        ircBotDialogPage = new IrcBotDialogPage();
        expect(ircBotDialogPage.getModalTitle()).toMatch(/gamecraftgatewayApp.ircBot.home.createOrEditLabel/);
        ircBotDialogPage.close();
    });

    it('should create and save IrcBots', () => {
        ircBotComponentsPage.clickOnCreateButton();
        ircBotDialogPage.setIrcBotNameInput('ircBotName');
        expect(ircBotDialogPage.getIrcBotNameInput()).toMatch('ircBotName');
        ircBotDialogPage.setIrcBotDescriptionInput('ircBotDescription');
        expect(ircBotDialogPage.getIrcBotDescriptionInput()).toMatch('ircBotDescription');
        ircBotDialogPage.getIrcBotEnabledInput().isSelected().then(function (selected) {
            if (selected) {
                ircBotDialogPage.getIrcBotEnabledInput().click();
                expect(ircBotDialogPage.getIrcBotEnabledInput().isSelected()).toBeFalsy();
            } else {
                ircBotDialogPage.getIrcBotEnabledInput().click();
                expect(ircBotDialogPage.getIrcBotEnabledInput().isSelected()).toBeTruthy();
            }
        });
        ircBotDialogPage.setIrcServerAddressInput('ircServerAddress');
        expect(ircBotDialogPage.getIrcServerAddressInput()).toMatch('ircServerAddress');
        ircBotDialogPage.setIrcServerPortInput('5');
        expect(ircBotDialogPage.getIrcServerPortInput()).toMatch('5');
        ircBotDialogPage.setIrcBotNicknameInput('ircBotNickname');
        expect(ircBotDialogPage.getIrcBotNicknameInput()).toMatch('ircBotNickname');
        ircBotDialogPage.getIrcServerSecuredProtocolEnabledInput().isSelected().then(function (selected) {
            if (selected) {
                ircBotDialogPage.getIrcServerSecuredProtocolEnabledInput().click();
                expect(ircBotDialogPage.getIrcServerSecuredProtocolEnabledInput().isSelected()).toBeFalsy();
            } else {
                ircBotDialogPage.getIrcServerSecuredProtocolEnabledInput().click();
                expect(ircBotDialogPage.getIrcServerSecuredProtocolEnabledInput().isSelected()).toBeTruthy();
            }
        });
        ircBotDialogPage.save();
        expect(ircBotDialogPage.getSaveButton().isPresent()).toBeFalsy();
    });

    afterAll(() => {
        navBarPage.autoSignOut();
    });
});

export class IrcBotComponentsPage {
    createButton = element(by.css('.jh-create-entity'));
    title = element.all(by.css('jhi-irc-bot div h2 span')).first();

    clickOnCreateButton() {
        return this.createButton.click();
    }

    getTitle() {
        return this.title.getAttribute('jhiTranslate');
    }
}

export class IrcBotDialogPage {
    modalTitle = element(by.css('h4#myIrcBotLabel'));
    saveButton = element(by.css('.modal-footer .btn.btn-primary'));
    closeButton = element(by.css('button.close'));
    ircBotNameInput = element(by.css('input#field_ircBotName'));
    ircBotDescriptionInput = element(by.css('input#field_ircBotDescription'));
    ircBotEnabledInput = element(by.css('input#field_ircBotEnabled'));
    ircServerAddressInput = element(by.css('input#field_ircServerAddress'));
    ircServerPortInput = element(by.css('input#field_ircServerPort'));
    ircBotNicknameInput = element(by.css('input#field_ircBotNickname'));
    ircServerSecuredProtocolEnabledInput = element(by.css('input#field_ircServerSecuredProtocolEnabled'));

    getModalTitle() {
        return this.modalTitle.getAttribute('jhiTranslate');
    }

    setIrcBotNameInput = function (ircBotName) {
        this.ircBotNameInput.sendKeys(ircBotName);
    }

    getIrcBotNameInput = function () {
        return this.ircBotNameInput.getAttribute('value');
    }

    setIrcBotDescriptionInput = function (ircBotDescription) {
        this.ircBotDescriptionInput.sendKeys(ircBotDescription);
    }

    getIrcBotDescriptionInput = function () {
        return this.ircBotDescriptionInput.getAttribute('value');
    }

    getIrcBotEnabledInput = function () {
        return this.ircBotEnabledInput;
    }
    setIrcServerAddressInput = function (ircServerAddress) {
        this.ircServerAddressInput.sendKeys(ircServerAddress);
    }

    getIrcServerAddressInput = function () {
        return this.ircServerAddressInput.getAttribute('value');
    }

    setIrcServerPortInput = function (ircServerPort) {
        this.ircServerPortInput.sendKeys(ircServerPort);
    }

    getIrcServerPortInput = function () {
        return this.ircServerPortInput.getAttribute('value');
    }

    setIrcBotNicknameInput = function (ircBotNickname) {
        this.ircBotNicknameInput.sendKeys(ircBotNickname);
    }

    getIrcBotNicknameInput = function () {
        return this.ircBotNicknameInput.getAttribute('value');
    }

    getIrcServerSecuredProtocolEnabledInput = function () {
        return this.ircServerSecuredProtocolEnabledInput;
    }
    save() {
        this.saveButton.click();
    }

    close() {
        this.closeButton.click();
    }

    getSaveButton() {
        return this.saveButton;
    }
}


text:
namespace Perfectial.Domain.Model
{
    public class UserRole : UserRoleBase<string>
    {
    }
}